row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,746
|
how can i improve this block of code const dedicated = senders.filter((sender) => {
return sender.type === "dedicated";
});
const shared = senders.filter((sender) => {
return sender.type === "shared";
});
const dedicatedNumbers = dedicated.map((sender) => sender.value);
const sharedNumbers = shared.map((sender) => sender.value);
const dedicatedConfigured = configuredSenders!.filter((sender) => {
// @ts-ignore
return sender.isDedicated === true && sender.type === "WHATSAPP";
});
const sharedConfigured = configuredSenders!.filter((sender) => {
// @ts-ignore
return sender.isDedicated === false && sender.type === "WHATSAPP";
});
// @ts-ignore
const aa = dedicatedConfigured.map((sender) => sender.phone);
// @ts-ignore
const bb = sharedConfigured.map((sender) => sender.phone);
|
9a44aec27a37eeb4c19a976d8fcb0e11
|
{
"intermediate": 0.40716665983200073,
"beginner": 0.3654870390892029,
"expert": 0.2273463010787964
}
|
10,747
|
i need to use a stylesheet in wwwroot inside my index.cshtml viewpage, i tried this : "<link rel="stylesheet" href="../wwwroot/css/main.css">"
|
d0c2ff3113c0a3842af01cddb74c3877
|
{
"intermediate": 0.35731154680252075,
"beginner": 0.27402475476264954,
"expert": 0.36866360902786255
}
|
10,748
|
import requests
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
def get_newly_created_contracts(start_block, end_block):
url = f'https://api.bscscan.com/api?module=account&action=txlistinternal&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}'
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f'Error in API request: {e}')
return []
data = response.json()
if data['status'] == '0':
print(f"Error: {data['result']}")
return []
return [tx for tx in data['result'] if tx['isError'] == '0' and tx['contractAddress'] != '']
def display_new_contracts(start_block, end_block):
contracts = get_newly_created_contracts(start_block, end_block)
if not contracts:
print('No new contracts found.')
else:
print(f'Newly created smart contracts between blocks {start_block} and {end_block}: ')
for contract in contracts:
print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}")
start_block = 28496140 # Replace with your desired start block
end_block = 28496140 # Replace with your desired end block
display_new_contracts(start_block, end_block)
Change the above code to only return addresses whose From column value is 0x863b49ae97c3d2a87fd43186dfd921f42783c853
|
1ad2af7dabae9a8d1614e4659eb3fa04
|
{
"intermediate": 0.4726332128047943,
"beginner": 0.3036368191242218,
"expert": 0.22372999787330627
}
|
10,749
|
return value instanceof this.expected ? Result.ok(value) : Result.err(new ExpectedValidationError("s.instance(V)", "Expected", value, this.expected));
|
49e82a1dda3e1b4364b3009c0b505bdc
|
{
"intermediate": 0.4413822293281555,
"beginner": 0.3542170822620392,
"expert": 0.2044006735086441
}
|
10,750
|
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_internal_transactions(start_block, end_block, session):
async with semaphore:
url = f'https://api.bscscan.com/api?module=account&action=txlistinternal&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
return data.get('result', [])
async def get_contracts_in_block(block_number, target_from_address):
async with aiohttp.ClientSession() as session:
transactions = await get_internal_transactions(block_number, block_number, session)
filtered_contracts = []
for tx in transactions:
if tx['isError'] == '0' and tx['contractAddress'] != '' and tx['from'].lower() == target_from_address.lower():
filtered_contracts.append(tx)
return filtered_contracts
async def display_new_contracts(start_block, end_block, target_from_address):
for block_number in range(start_block, end_block + 1):
print(f'Transactions in block {block_number}:')
contracts = await get_contracts_in_block(block_number, target_from_address)
if not contracts:
print('No new contracts found.')
else:
for contract in contracts:
print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}")
async def main():
start_block = 28760800 # Replace with your desired start block
end_block = 28760899 # Replace with your desired end block
target_from_address = '0x863b49ae97c3d2a87fd43186dfd921f42783c853'
await display_new_contracts(start_block, end_block, target_from_address)
asyncio.run(main())
Optimize the code above so that it sends a request and receives responses much faster.
Functionality should remain the same
|
99e343563dd6bee826ea2587ed66c681
|
{
"intermediate": 0.3598223924636841,
"beginner": 0.3858520984649658,
"expert": 0.2543255686759949
}
|
10,751
|
fivem scripting
i'm working on a script and this is my config how would I make it so
drugMenu = {
['heroin'] = {
[5] = {label = '5x Heroin Bricks [$3,000,000]', price = 3000000, reward = 'drugbrick12', amount = 5},
[10] = {label = '10x Heroin Bricks [$5,750,000]', price = 5750000, reward = 'drugbrick12', amount = 10},
[25] = {label = '25x Heroin Bricks [$13,500,000]', price = 13500000, reward = 'drugbrick12', amount = 25}
},
['lsd'] = {
[5] = {label = '5x LSD Sheets [$1,500,000]', price = 1500000, reward = 'drugbrick6', amount = 5},
[10] = {label = '10x LSD Sheets [$2,875,000]', price = 2875000, reward = 'drugbrick6', amount = 10},
[25] = {label = '25x LSD Sheets [$6,750,000]', price = 6750000, reward = 'drugbrick6', amount = 25}
}
}
I have a client menu that selects an option and then triggers an event what would be the best way to detect which option was selected and then do something
|
0925ac8ddd157b035ed8064bff947c6a
|
{
"intermediate": 0.42062950134277344,
"beginner": 0.34576085209846497,
"expert": 0.2336096465587616
}
|
10,752
|
how to keyboard type with delay in puppeteer
|
a10cad24fa9184b973b500a15e2f9a07
|
{
"intermediate": 0.30017417669296265,
"beginner": 0.26846843957901,
"expert": 0.43135738372802734
}
|
10,753
|
hi, i have X as a list of list of string and Y as a list of int. I would train a Graph Neural Network which creare a graph from every list in list X to classify the binary label Y. for example X[0] is a list of strings like this "D0 S3 C95 C97 D0 D0 C22 C27 C43 D0 D0 C24 C30 C52 D0 D0 C21 C7 C5 D0 D0 C42 S15 C6 D0 D0 C59 S11 C35 C11 D0 D0 C40 C37 S12 C72 D0 D0 C1 C19 S5 C99 D0 D0 C90 C92 C84 C81 D0 D0 C41 C44 C78 D0 D0 C98 C83 C2 D0 D0 S12 C34 C39 D0 D0 C68 C61 C66 D0 D0 C58 C47 D0 D0 C36 C79 C17 D0 D0 S3 C96 C88 D0 D0 C12 C16 S7 D0 D0 S20 C71 C55 D0 D0 C14 C70 D0". So i can have 3 types of node: D, C, S. I would train the GNN to classify if X[i], associated to Y[i] is good or not.
|
f72cf3b317d0c1bb0c9ecaa0b8a7374f
|
{
"intermediate": 0.0721803531050682,
"beginner": 0.048889100551605225,
"expert": 0.8789305090904236
}
|
10,754
|
Write a python code to create an ontology of public policy problems.
|
8afb15169a2817564fe8054bd83a32e7
|
{
"intermediate": 0.4248972535133362,
"beginner": 0.31505918502807617,
"expert": 0.26004353165626526
}
|
10,755
|
File "D:\ArjunShaChatGPTChatbotOwnData\app.py", line 1, in <module>
from gpt_index import SimpleDirectoryReader, GPTListIndex, GPTSimpleVectorIndex, LLMPredictor, PromptHelper
ModuleNotFoundError: No module named 'gpt_index'
|
8488052fa8909270fcca8c53ef07ad2b
|
{
"intermediate": 0.5546335577964783,
"beginner": 0.23136624693870544,
"expert": 0.2140001803636551
}
|
10,756
|
fivem scripting
i'm working on a script and this is my config how would I make it so
drugMenu = {
['heroin'] = {
[5] = {label = '5x Heroin Bricks [$3,000,000]', price = 3000000, reward = 'drugbrick12', amount = 5},
[10] = {label = '10x Heroin Bricks [$5,750,000]', price = 5750000, reward = 'drugbrick12', amount = 10},
[25] = {label = '25x Heroin Bricks [$13,500,000]', price = 13500000, reward = 'drugbrick12', amount = 25}
},
['lsd'] = {
[5] = {label = '5x LSD Sheets [$1,500,000]', price = 1500000, reward = 'drugbrick6', amount = 5},
[10] = {label = '10x LSD Sheets [$2,875,000]', price = 2875000, reward = 'drugbrick6', amount = 10},
[25] = {label = '25x LSD Sheets [$6,750,000]', price = 6750000, reward = 'drugbrick6', amount = 25}
}
}
I have a client menu that selects an option and then triggers an event what would be the best way to detect which option was selected and then do something
|
f513f542107f9450b8f7372056744400
|
{
"intermediate": 0.42062950134277344,
"beginner": 0.34576085209846497,
"expert": 0.2336096465587616
}
|
10,757
|
This is my code:
# Read in the pivot table as a pandas dataframe
df = pd.read_csv(f'pivot_{client_name}.csv', index_col=[0, 1], header=[0, 1])
# Pre-define the table cell properties
cell_text = df.values.astype(str)
cell_text = np.core.defchararray.add(cell_text, ' ')
# Create a figure and axis
fig, ax = plt.subplots()
# Remove the default axis labels and ticks
ax.axis('off')
# Get the column and row labels
col_labels = df.columns.levels[1].tolist()
row_labels = [(x[0] + '\n' + x[1]) for x in df.index.tolist()]
# Create the table using the pandas dataframe
table = ax.table(
cellText=cell_text,
cellLoc='left',
colLabels=col_labels,
rowLabels=row_labels,
loc='center'
)
# Set the table font size
table.set_fontsize(14)
# Adjust the table properties for better readability
table.auto_set_font_size(False)
table.auto_set_column_width(col=list(range(len(col_labels))))
for k, cell in table.cells.items():
cell.set_edgecolor("black")
if k[1] == -1: # row label cell
cell.set_text_props(va='center', ha='right', rotation='horizontal', fontsize=10)
elif k[0] == -1: # column label cell
cell.set_text_props(va='center', ha='center', rotation='horizontal', fontsize=10)
# Save the table as an image file
plt.savefig(f'pivot{client_name}.png', bbox_inches='tight')
and I got this error:
No error handlers are registered, logging exception.
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/telegram/ext/dispatcher.py", line 555, in process_update
handler.handle_update(update, self, check, context)
File "/usr/local/lib/python3.10/dist-packages/telegram/ext/handler.py", line 198, in handle_update
return self.callback(update, context)
File "/home/bot/sandbox.py", line 256, in client_name_received
table = ax.table(
File "/home/bot/.local/lib/python3.10/site-packages/matplotlib/table.py", line 816, in table
text=colLabels[col], facecolor=colColours[col],
IndexError: list index out of range
|
bb5a010cdc2fd9a5120f674404c574ea
|
{
"intermediate": 0.5062198638916016,
"beginner": 0.3704708516597748,
"expert": 0.12330923229455948
}
|
10,758
|
how can i down resolution of video then save it to storage in react native expo
|
b496d3254157734a07eb7a62b4b2b433
|
{
"intermediate": 0.5531255006790161,
"beginner": 0.10867872089147568,
"expert": 0.3381957709789276
}
|
10,759
|
LOG [TypeError: undefined is not a function]
cant load pics from firebase and i dont undestand why
import { Text, View, Image, Pressable } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import React, {useState, useEffect} from ‘react’;
import { useNavigation } from ‘@react-navigation/native’;
import {firebase} from ‘…/Firebase/firebase’;
import moment from ‘moment’;
import {getStorage, ref, getDownloadURL} from ‘firebase/compat/storage’;
export default function FutureMK() {
const navigation = useNavigation();
const [futureMKData, setFutureMKData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const futureMKRef = firebase.firestore().collection(‘FutureMK’);
const snapshot = await futureMKRef.get();
const data = snapshot.docs.map((doc) => doc.data());
setFutureMKData(data);
const storageRef = getStorage().ref();
const updateData = await Promise.all(data.map(async(mkData)=>{
const imageUrl = mkData.imageUrl;
const imageRef = ref(storageRef, imageUrl);
const url = await getDownloadURL(imageRef);
return {…mkData, imageUrl:url};
}))
} catch (error) {
console.log(error);
}
};
fetchData();
}, []);
return (
<View style={gStyle.main}>
{futureMKData.map((mkData, index)=>(
<View key={index} style={gStyle.mainFMK}>
<Text style={gStyle.dateFutureMK}>{moment(mkData.time.toDate()).format(‘Do MMM YYYY’)}</Text>
<View style={gStyle.FutureMKimg}>
<Image source={{uri:mkData.imageUrl}} style={gStyle.FutureMKbannerImg}/>
<Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
</View>
<Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text>
<Text style={gStyle.FutureMKdescription}>
{mkData.description}
</Text>
<Pressable style={gStyle.FutureMKmoreDetails}
onPress={()=>{navigation.navigate(‘SignUpForMK’,{mkData});}}
>
<Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.FutureMKline}></Text>
</View>
))}
</View>
);
}
my code
|
9fcd0aa9bc625e62a4baa26a42e6ed0f
|
{
"intermediate": 0.5419135689735413,
"beginner": 0.34941112995147705,
"expert": 0.1086752787232399
}
|
10,760
|
how do I get the call stack when catching an exception in c++ program
|
401694bedacdb79ab5c730ac2662846e
|
{
"intermediate": 0.5812093615531921,
"beginner": 0.2258702963590622,
"expert": 0.19292037189006805
}
|
10,761
|
In python TASK ONE – Build a function that gets the required information from the user and stores it in your data structure of choice. This includes their: · First name · Middle name · Surname · Gender · Birth day · Birth month · Birth year TASK TWO – Introduce data validation to your TASK ONE function; the user should not be allowed to enter erroneous input, such as blank input or a number instead of a first name. TASK THREE – Build a function that generates characters 1-5 and characters 12-13. TASK FOUR – Build a function that generates characters 6, 7-8, 9-10 and 11. TASK FIVE – Build a function that generates characters 14 and 15-16. TASK SIX – Build a function that assembles the final driver’s license and outputs it for the user. based offf.. Figure 1 Character(s) Requirement 1-5 First five characters of the driver’s surname. If the surname is shorter than 5 characters long, any leftover characters are filled up with 9s (e.g, LEE99). 6 The decade digit from the driver’s birth year (e.g, 7 in 1973). 7-8 The driver’s birth month, 01-12. For female drivers only, the seventh character is incremented by 5, 51-62. 9-10 The driver’s birth day, 01-31. If the birth month is February, this range is 01-28, and if the birth year is a leap year, it is 01-29. 11 The year digit from the driver’s birth year (e.g, 3 in 1973). 12-13 The first character from the driver’s first name and the first character from the driver’s middle name. If the driver has no middle name, the character is replaced with a 9. 14 A random digit, typically 9. This is to avoid having drivers with duplicate details. If a new driver with the same details applies, this digit is reduced by 1 and 9 becomes 8, 8 becomes 7 and so on. You can assume there will be no duplicate drivers. 15-16 Two random letters A-Z.
|
98ff7987bf84036ef818d6c517f39cad
|
{
"intermediate": 0.47966718673706055,
"beginner": 0.24372737109661102,
"expert": 0.27660539746284485
}
|
10,762
|
РЕАЛИЗУЙ СОХРАНЕНИЕ УЗЛО ПРИ НАЖАТИИ НА СООТВЕТСТВУЮЩУЮ КНОПКУ package com.example.myapp_2.UI.view.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
import com.example.myapp_2.R;
public class AddNoteActivity extends AppCompatActivity {
public static final String EXTRA_TITLE =
"com.codinginflow.architectureexample.EXTRA_TITLE";
public static final String EXTRA_DESCRIPTION =
"com.codinginflow.architectureexample.EXTRA_DESCRIPTION";
public static final String EXTRA_PRIORITY =
"com.codinginflow.architectureexample.EXTRA_PRIORITY";
private EditText editTextTitle;
private EditText editTextDescription;
private NumberPicker numberPickerPriority;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
editTextTitle = findViewById(R.id.edit_text_title);
editTextDescription = findViewById(R.id.edit_text_description);
numberPickerPriority = findViewById(R.id.number_picker_priority);
numberPickerPriority.setMinValue(1);
numberPickerPriority.setMaxValue(10);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
setTitle("Add Note");
}
private void saveNote() {
String title = editTextTitle.getText().toString();
String description = editTextDescription.getText().toString();
int priority = numberPickerPriority.getValue();
if (title.trim().isEmpty() || description.trim().isEmpty()) {
Toast.makeText(this, "Please insert a title and description", Toast.LENGTH_SHORT).show();
return;
}
Intent data = new Intent();
data.putExtra(EXTRA_TITLE, title);
data.putExtra(EXTRA_DESCRIPTION, description);
data.putExtra(EXTRA_PRIORITY, priority);
setResult(RESULT_OK, data);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return true;
}
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.save_note:
// saveNote();
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
}<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/save_note"
android:icon="@drawable/ic_save"
android:title="Save"
app:showAsAction="ifRoom" />
</menu>
|
558dcc7007f6deefec896d2639fb84da
|
{
"intermediate": 0.29571282863616943,
"beginner": 0.4215353727340698,
"expert": 0.28275182843208313
}
|
10,763
|
проблема в том, что при выборе роли, значение (роль) сбрасывается, кнопка сбрасывается и поиск при выбранной роли не происходит, но зато все еще можно искать по имени и жанру
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query, role) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (role === '' || musician.role.toLowerCase() === role);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method="get">
<label for="query">Search by name or genre:</label>
<input type="text" id="query" name="query">
<br><br>
<label for="role">Search by role:</label>
<select id="role" name="role">
<option value="">All</option>
<option value="Band">Band</option>
<option value="Artist">Artist</option>
</select>
<br><br>
<button type="submit">Search</button>
</form>
<% if (query && musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>">
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href="<%= musician.soundcloud %>">SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query) { %>
<p>No musicians found.</p>
<% } %>
<script>
document.querySelector('#role').addEventListener('change', function() {
const form = document.querySelector('form');
const query = document.querySelector('#query').value;
const role = this.value;
const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role);
form.action = url;
form.submit();
});
</script>
</body>
</html>
|
0e4778255e2cebedaedbbd84517b2fa8
|
{
"intermediate": 0.32226479053497314,
"beginner": 0.5709809064865112,
"expert": 0.10675433278083801
}
|
10,764
|
In python TASK ONE – Build a function that gets the required information from the user and stores it in your data structure of choice. This includes their: · First name · Middle name · Surname · Gender · Birth day · Birth month · Birth year TASK TWO – Introduce data validation to your TASK ONE function; the user should not be allowed to enter erroneous input, such as blank input or a number instead of a first name. TASK THREE – Build a function that generates characters 1-5 and characters 12-13. TASK FOUR – Build a function that generates characters 6, 7-8, 9-10 and 11. TASK FIVE – Build a function that generates characters 14 and 15-16. TASK SIX – Build a function that assembles the final driver’s license and outputs it for the user. based offf.. Figure 1 Character(s) Requirement 1-5 First five characters of the driver’s surname. If the surname is shorter than 5 characters long, any leftover characters are filled up with 9s (e.g, LEE99). 6 The decade digit from the driver’s birth year (e.g, 7 in 1973). 7-8 The driver’s birth month, 01-12. For female drivers only, the seventh character is incremented by 5, 51-62. 9-10 The driver’s birth day, 01-31. If the birth month is February, this range is 01-28, and if the birth year is a leap year, it is 01-29. 11 The year digit from the driver’s birth year (e.g, 3 in 1973). 12-13 The first character from the driver’s first name and the first character from the driver’s middle name. If the driver has no middle name, the character is replaced with a 9. 14 A random digit, typically 9. This is to avoid having drivers with duplicate details. If a new driver with the same details applies, this digit is reduced by 1 and 9 becomes 8, 8 becomes 7 and so on. You can assume there will be no duplicate drivers. 15-16 Two random letters A-Z.
|
5ba1ab1d4ee3f649b514798224808697
|
{
"intermediate": 0.47966718673706055,
"beginner": 0.24372737109661102,
"expert": 0.27660539746284485
}
|
10,765
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
try:
markets = binance_futures.fetch_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
leverage = '100x'
symbol = 'BTC/USDT'
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"symbol":symbol,
"type": "MARKET" if signal == "buy" else "MARKET",
"side": "BUY" if signal == "buy" else "SELL",
"amount": quantity,
"price": price,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.create_order(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: The signal time is: 2023-06-07 09:54:01 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 257, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 243, in order_execution
response = binance_futures.create_order(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: binance.create_order() got an unexpected keyword argument 'leverage'
|
dd207d99c65791d3745a463e83599a8d
|
{
"intermediate": 0.3322139382362366,
"beginner": 0.45794159173965454,
"expert": 0.20984448492527008
}
|
10,766
|
Hi, i need a CMD Script which Outputs the Name If the Default Network printer
|
6b4a33028a9107073f1d87bcb4ceffc3
|
{
"intermediate": 0.2437112033367157,
"beginner": 0.23546364903450012,
"expert": 0.5208250880241394
}
|
10,767
|
Смотри, у меня есть триггеры.
Мне нужно чтобы В МОМЕНТ когда один из этих триггеров срабатывал, у меня отправлялась полная информация об изменениях в этой базе в мой телеграм чат. Покажи полный код для этой реализации. В чат должно отправлять изменение каждого столбца, тоесть old и new чтобы я понимал что на какое значение поменялось.
Если что мой телеграм бот написан на nodejs-bot-telegram-api
// Создание таблицы "profileslog", если она не существует
db.run(
CREATE TABLE IF NOT EXISTS profileslog (
id INTEGER PRIMARY KEY AUTOINCREMENT,
profileid INTEGER,
action TEXT,
columnname TEXT,
oldvalue TEXT,
newvalue TEXT,
timestamp DATETIME DEFAULT CURRENTTIMESTAMP,
FOREIGN KEY (profileid) REFERENCES profiles (id)
);
);
// Создание триггера для INSERT
db.run(
CREATE TRIGGER IF NOT EXISTS profilesinserttrigger
AFTER INSERT ON profiles
BEGIN
INSERT INTO profileslog (profileid, action, columnname, oldvalue, newvalue)
VALUES (NEW.id, 'Insert', 'userid', NULL, NEW.userid),
(NEW.id, 'Insert', 'username', NULL, NEW.username),
(NEW.id, 'Insert', 'novokeki', NULL, NEW.novokeki),
(NEW.id, 'Insert', 'osnova', NULL, NEW.osnova),
(NEW.id, 'Insert', 'accepted', NULL, NEW.accepted),
(NEW.id, 'Insert', 'dailycash', NULL, NEW.dailycash),
(NEW.id, 'Insert', 'totalcash', NULL, NEW.totalcash),
(NEW.id, 'Insert', 'dailytables', NULL, NEW.dailytables),
(NEW.id, 'Insert', 'totaltables', NULL, NEW.total_tables);
END;
);
// Создание триггера для UPDATE
db.run(
CREATE TRIGGER IF NOT EXISTS profilesupdatetrigger
AFTER UPDATE ON profiles
BEGIN
INSERT INTO profileslog (profileid, action, columnname, oldvalue, newvalue)
VALUES (NEW.id, 'Update', 'userid', OLD.userid, NEW.userid),
(NEW.id, 'Update', 'username', OLD.username, NEW.username),
(NEW.id, 'Update', 'novokeki', OLD.novokeki, NEW.novokeki),
(NEW.id, 'Update', 'osnova', OLD.osnova, NEW.osnova),
(NEW.id, 'Update', 'accepted', OLD.accepted, NEW.accepted),
(NEW.id, 'Update', 'dailycash', OLD.dailycash, NEW.dailycash),
(NEW.id, 'Update', 'totalcash', OLD.totalcash, NEW.totalcash),
(NEW.id, 'Update', 'dailytables', OLD.dailytables, NEW.dailytables),
(NEW.id, 'Update', 'totaltables', OLD.totaltables, NEW.totaltables);
END;
);
// Создание триггера для DELETE
db.run(
CREATE TRIGGER IF NOT EXISTS profilesdeletetrigger
AFTER DELETE ON profiles
BEGIN
INSERT INTO profileslog (profileid, action, columnname, oldvalue, newvalue)
VALUES (OLD.id, 'Delete', 'userid', OLD.userid, NULL),
(OLD.id, 'Delete', 'username', OLD.username, NULL),
(OLD.id, 'Delete', 'novokeki', OLD.novokeki, NULL),
(OLD.id, 'Delete', 'osnova', OLD.osnova, NULL),
(OLD.id, 'Delete', 'accepted', OLD.accepted, NULL),
(OLD.id, 'Delete', 'dailycash', OLD.dailycash, NULL),
(OLD.id, 'Delete', 'totalcash', OLD.totalcash, NULL),
(OLD.id, 'Delete', 'dailytables', OLD.dailytables, NULL),
(OLD.id, 'Delete', 'totaltables', OLD.total_tables, NULL);
END;
);
|
dbf6491a2f78eb651f3aefc47a4d1bc7
|
{
"intermediate": 0.3330117166042328,
"beginner": 0.46490585803985596,
"expert": 0.20208245515823364
}
|
10,768
|
How do I only include the last full month in my SQL query?
|
cd2c42a5a6c9a4719828457f060e20f0
|
{
"intermediate": 0.3392474055290222,
"beginner": 0.3350083529949188,
"expert": 0.3257442116737366
}
|
10,769
|
it gives me error in reading this values: const logFormat = printf(({level,message,timestamp}) => {
return "${timestamp} ${level}: ${message}";
})
|
fb76253b970bbdd6e089d7aaccd326ca
|
{
"intermediate": 0.2926819622516632,
"beginner": 0.5481100082397461,
"expert": 0.15920807421207428
}
|
10,770
|
Can you add StandardScaler to it and somehow connect it to the model, so models works on raw data and scales it? Something like pipeline, but adjusted to it.
import xgboost as xgb
import optuna
from sklearn.model_selection import cross_validate
from sklearn.metrics import roc_auc_score
def objective(trial):
max_depth = trial.suggest_int('max_depth', 1, 20)
learning_rate = trial.suggest_float('learning_rate', 0, 0.5)
subsample = trial.suggest_float('subsample', 0, 1)
gamma = trial.suggest_float("gamma", 1e-4, 1e2)
reg_alpha = trial.suggest_float('reg_alpha', 0, 1)
reg_lambda = trial.suggest_float('reg_lambda', 0, 1)
min_split_loss = trial.suggest_float('min_split_loss', 0, 8)
nround=trial.suggest_int('nround',10,300)
params = {
'max_depth': max_depth,
'learning_rate': learning_rate,
'subsample': subsample,
'gamma': gamma,
'reg_alpha': reg_alpha,
'reg_lambda': reg_lambda,
'eval_metric': 'auc',
'min_split_loss':min_split_loss,
'objective': 'binary:logitraw',
}
dtrain = xgb.DMatrix(X, Y, enable_categorical=True, missing=True)
dtest = xgb.DMatrix(X_test, Y_test, enable_categorical=True, missing=True)
model = xgb.train(params, dtrain, num_boost_round=nround, evals=[(dtest, 'eval'), (dtrain, 'train')], verbose_eval=False)
score, is_overfitted = validate(model, X, Y, X_test, Y_test)
if is_overfitted:
return 0
else:
return score
def validate(model, X, Y, X_test, Y_test):
dtrain = xgb.DMatrix(X, Y, enable_categorical=True, missing=True)
dtest = xgb.DMatrix(X_test, Y_test, enable_categorical=True, missing=True)
train_preds = model.predict(dtrain)
test_preds = model.predict(dtest)
train_score = roc_auc_score(Y, train_preds)
test_score = roc_auc_score(Y_test, test_preds)
is_overfitted = train_score - test_score > 0.05
return test_score, is_overfitted
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=1500)
?
|
9beb522b31d589696b4f263e0d59c460
|
{
"intermediate": 0.3350031077861786,
"beginner": 0.3752596378326416,
"expert": 0.28973719477653503
}
|
10,771
|
how can i resize video file on storage from 512*1024 to 256*512 then save it to file with react native expo
|
0b2c7897fc6a0803cb282f54a3bc7552
|
{
"intermediate": 0.4428654909133911,
"beginner": 0.17520414292812347,
"expert": 0.3819303512573242
}
|
10,772
|
При загрузке страницы поиска мне выдает сразу нескольких артистов, а при попытке выбора артиста или группы ничего не происходит, поиск выполнить невозможно, как будто бы сбрасывается, url при этом выглядит вот так: http://localhost:3000/search?query=&role=&role=Artist
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (hiddenRole === '' || musician.role === hiddenRole);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method="get">
<label for="query">Search by name or genre:</label>
<input type="text" id="query" name="query" value="<%= query %>">
<br><br>
<label for="role">Search by role:</label>
<select id="role" name="role">
<option value="">All</option>
<option value="Band" <% if (role === 'Band') { %>selected<% } %>>Band</option>
<option value="Artist" <% if (role === 'Artist') { %>selected<% } %>>Artist</option>
</select>
<!-- Исправлен атрибут name -->
<input type="hidden" id="hidden-role" name="role" value="<%= role %>">
<br><br>
<button type="submit">Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>">
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href="<%= musician.soundcloud %>">SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
const roleSelect = document.querySelector('#role');
const hiddenRole = document.querySelector('#hidden-role');
const searchForm = document.querySelector('form');
const queryInput = document.querySelector('#query');
roleSelect.addEventListener('change', function() {
hiddenRole.value = this.value;
searchForm.submit();
});
searchForm.addEventListener('submit', function(event) {
// Если выбрана роль, устанавливаем значение скрытого поля
if (roleSelect.value !== '') {
hiddenRole.value = roleSelect.value;
}
// Если параметры "query" и "role" присутствуют в URL, устанавливаем их значения в соответствующие элементы формы
const urlParams = new URLSearchParams(window.location.search);
const queryFromUrl = urlParams.get('query');
const roleFromUrl = urlParams.get('role');
if (queryFromUrl) {
queryInput.value = queryFromUrl;
}
if (roleFromUrl) {
hiddenRole.value = roleFromUrl;
}
});
</script>
</body>
</html>
|
60ec843beb2726ea4199cd539231fbb0
|
{
"intermediate": 0.32597899436950684,
"beginner": 0.5364773273468018,
"expert": 0.1375436633825302
}
|
10,773
|
При загрузке страницы поиска мне выдает сразу нескольких артистов, а при попытке выбора артиста или группы ничего не происходит, поиск выполнить невозможно, как будто бы сбрасывается, url при этом выглядит вот так: http://localhost:3000/search?query=&role=&role=Artist
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (hiddenRole === '' || musician.role === hiddenRole);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method="get">
<label for="query">Search by name or genre:</label>
<input type="text" id="query" name="query" value="<%= query %>">
<br><br>
<label for="role">Search by role:</label>
<select id="role" name="role">
<option value="">All</option>
<option value="Band" <% if (role === 'Band') { %>selected<% } %>>Band</option>
<option value="Artist" <% if (role === 'Artist') { %>selected<% } %>>Artist</option>
</select>
<!-- Исправлен атрибут name -->
<input type="hidden" id="hidden-role" name="role" value="<%= role %>">
<br><br>
<button type="submit">Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>">
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href="<%= musician.soundcloud %>">SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
const roleSelect = document.querySelector('#role');
const hiddenRole = document.querySelector('#hidden-role');
const searchForm = document.querySelector('form');
const queryInput = document.querySelector('#query');
roleSelect.addEventListener('change', function() {
hiddenRole.value = this.value;
searchForm.submit();
});
searchForm.addEventListener('submit', function(event) {
// Если выбрана роль, устанавливаем значение скрытого поля
if (roleSelect.value !== '') {
hiddenRole.value = roleSelect.value;
}
// Если параметры "query" и "role" присутствуют в URL, устанавливаем их значения в соответствующие элементы формы
const urlParams = new URLSearchParams(window.location.search);
const queryFromUrl = urlParams.get('query');
const roleFromUrl = urlParams.get('role');
if (queryFromUrl) {
queryInput.value = queryFromUrl;
}
if (roleFromUrl) {
hiddenRole.value = roleFromUrl;
}
});
</script>
</body>
</html>
|
4ff4dffd056321fbc9ef2d1573822d4c
|
{
"intermediate": 0.32597899436950684,
"beginner": 0.5364773273468018,
"expert": 0.1375436633825302
}
|
10,774
|
In this script, the line if (!isRefError(eValue)) { creates an error. Can you please suggest an alternative that will parse correctly?
function processHyperlinks() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var listSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List");
var columnsToCheck = ["C", "H", "M", "R"];
columnsToCheck.forEach(function (column) {
var numRows = activeSheet.getLastRow();
var range = activeSheet.getRange(column + "1:" + column + numRows);
var values = range.getRichTextValues();
for (var i = 0; i < values.length; i++) {
var richText = values[i][0];
if (richText.getLinkUrl()) {
var url = richText.getLinkUrl();
var listRange = listSheet.getRange("C1:C" + listSheet.getLastRow());
var listValues = listRange.getValues();
var isFound = false;
for (var j = 0; j < listValues.length; j++) {
if (listValues[j][0] == url) {
isFound = true;
break;
}
}
if (!isFound) {
var newRow = listSheet.getLastRow() + 1;
listSheet.getRange("C" + newRow).setValue(url);
// Add IMPORTRANGE function to E column
var importRangeFormula = '=IMPORTRANGE(C' + newRow + ',"<<Binder>>!D1")';
listSheet.getRange("E" + newRow).setFormula(importRangeFormula);
// Add regexextract function to B column
var regexExtractFormula = '=IFERROR(REGEXEXTRACT(E' + newRow + ',"[\\w]* [\\w]*"),"")';
listSheet.getRange("B" + newRow).setFormula(regexExtractFormula);
SpreadsheetApp.flush();
var eValue = listSheet.getRange("E" + newRow).getValue();
if (!isRefError(eValue)) {
listSheet.getRange("B" + newRow).clearContent();
listSheet.getRange("C" + newRow).clearContent();
listSheet.getRange("E" + newRow).clearContent();
}
}
}
}
});
}
|
118da53ea7b49f95cfaa50d4e6b2d429
|
{
"intermediate": 0.2916638255119324,
"beginner": 0.4769294261932373,
"expert": 0.2314068228006363
}
|
10,775
|
this is my code : df.shape(), but shows this error: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[13], line 1
----> 1 df.shape()
TypeError: 'tuple' object is not callable
|
f13e263e086ccd1e1860c2de1b8ab9be
|
{
"intermediate": 0.46308234333992004,
"beginner": 0.2375173419713974,
"expert": 0.2994002401828766
}
|
10,776
|
how to get Issues with full changelog using Jira REST API
|
89dfd7b5a747fcd6cfcf20150900a3ce
|
{
"intermediate": 0.6849185228347778,
"beginner": 0.15040594339370728,
"expert": 0.16467560827732086
}
|
10,777
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
//VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Initialize2(Renderer& renderer);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
VkDeviceMemory mvpBufferMemory;
VkBuffer mvpBuffer;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Initialize2(Renderer& renderer)
{
auto [mvpBuffer2, mvpBufferMemory2] = renderer.RequestMvpBuffer();
mvpBuffer = mvpBuffer2;
mvpBufferMemory = mvpBufferMemory2;
material->CreateDescriptorSet(mvpBuffer, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
vkDeviceWaitIdle(device);
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(mvpBuffer, device, sizeof(MVP));
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->descriptorPool = descriptorPool;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
if (descriptorPool != VK_NULL_HANDLE) {
vkDestroyDescriptorPool(device, descriptorPool, nullptr);
descriptorPool = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
Shader.h:
#pragma once
#include <vulkan/vulkan.h>
#include <string>
class Shader
{
public:
Shader();
~Shader();
void LoadFromFile(const std::string& filename, VkDevice device, VkShaderStageFlagBits stage);
VkPipelineShaderStageCreateInfo GetPipelineShaderStageCreateInfo() const;
static void Cleanup(Shader* shader);
private:
VkDevice device;
VkShaderModule shaderModule;
VkShaderStageFlagBits stage;
};
Shader.cpp:
#include "Shader.h"
#include <fstream>
#include <vector>
#include <iostream>
Shader::Shader()
: device(VK_NULL_HANDLE), shaderModule(VK_NULL_HANDLE), stage(VK_SHADER_STAGE_VERTEX_BIT)
{
}
Shader::~Shader()
{
}
void Shader::LoadFromFile(const std::string& filename, VkDevice device, VkShaderStageFlagBits stage)
{
this->device = device;
this->stage = stage;
// Read shader file into a buffer
std::ifstream file(filename, std::ios::ate | std::ios::binary);
if (file.is_open())
{
size_t fileSize = static_cast<size_t>(file.tellg());
std::vector<char> buffer(fileSize);
file.seekg(0);
file.read(buffer.data(), fileSize);
file.close();
// Create shader module from the buffer
VkShaderModuleCreateInfo shaderModuleCreateInfo{};
shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shaderModuleCreateInfo.codeSize = buffer.size();
shaderModuleCreateInfo.pCode = reinterpret_cast<const uint32_t*>(buffer.data());
if (vkCreateShaderModule(device, &shaderModuleCreateInfo, nullptr, &shaderModule) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create shader module.");
}
}
else
{
throw std::runtime_error("Failed to open shader file.");
}
}
void Shader::Cleanup(Shader* shader)
{
// Check if the shader module is not null
if (shader->shaderModule != VK_NULL_HANDLE) {
// Destroy the shader module
vkDestroyShaderModule(shader->device, shader->shaderModule, nullptr);
shader->shaderModule = VK_NULL_HANDLE;
}
}
VkPipelineShaderStageCreateInfo Shader::GetPipelineShaderStageCreateInfo() const
{
VkPipelineShaderStageCreateInfo shaderStageCreateInfo{};
shaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStageCreateInfo.stage = stage;
shaderStageCreateInfo.module = shaderModule;
shaderStageCreateInfo.pName = "main";
return shaderStageCreateInfo;
}
Current Vertex Shader:
#version 450
layout(binding = 0) uniform UniformBufferObject {
mat4 model;
mat4 view;
mat4 proj;
} ubo;
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inColor;
layout(location = 0) out vec3 fragColor;
void main() {
gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0);
fragColor = inColor;
}
Current Fragment Shader:
#version 450
layout(binding = 1) uniform sampler2D texSampler;
layout(location = 0) in vec3 fragColor;
layout(location = 0) out vec4 outColor;
void main() {
outColor = vec4(1,0,1,1);
}
I want to modify the code so the squareTile object makes use of the following shaders:
New Vertex Shader:
#version 450
layout(binding = 0) uniform UniformBufferObject {
mat4 model;
mat4 view;
mat4 proj;
} ubo;
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inColor;
layout(location = 2) in vec2 inTexCoord;
layout(location = 0) out vec3 fragColor;
layout(location = 1) out vec2 fragTexCoord;
void main() {
gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0);
fragColor = inColor;
fragTexCoord = inTexCoord;
}
New Fragment Shader:
#version 450
layout(binding = 1) uniform sampler2D texSampler;
layout(location = 0) in vec3 fragColor;
layout(location = 1) in vec2 fragTexCoord;
layout(location = 0) out vec4 outColor;
void main() {
outColor = texture(texSampler, fragTexCoord);
}
Can you show me how to modify the code to do this? Feel free to make changes to the way the squareTile vertices are defined if necessary.
|
8e93eacfec5e338894807716d9ebd51c
|
{
"intermediate": 0.4590522348880768,
"beginner": 0.37653568387031555,
"expert": 0.16441206634044647
}
|
10,778
|
1) При переходе к странице поиска выдает сразу всех артистов
2) При попытке выбрать артиста или группа (критерии поиска) выбор сбрасывается, а url начинает множить: http://localhost:3000/search?query=&role=Artist&role=Artist%2C
3) При нажатии кнопки поиска при пустом поле url также начинает множить: http://localhost:3000/search?query=&role=&role=%2C%2C%2C%2C%2C%2C%2C%2C%2CArtist%2CArtist%2C
4) При поиске по имени или жанру возникает ошибка: ReferenceError: role is not defined
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (role === '' || musician.role === role);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method="get">
<label for="query">Search by name or genre:</label>
<input type="text" id="query" name="query" value="<%= query %>">
<br><br>
<label for="role">Search by role:</label>
<select id="role" name="role">
<option value="">All</option>
<option value="Band" <% if (role === 'Band') { %>selected<% } %>>Band</option>
<option value="Artist" <% if (role === 'Artist') { %>selected<% } %>>Artist</option>
</select>
<!-- Исправлен атрибут name -->
<input type="hidden" id="role" name="role" value="<%= role %>">
<br><br>
<button type="submit">Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>">
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href="<%= musician.soundcloud %>">SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
document.querySelector('#role').addEventListener('change', function() {
const form = document.querySelector('form');
const query = document.querySelector('#query').value;
const role = this.value;
const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role);
form.action = url;
form.submit();
});
</script>
</body>
</html>
|
3e98faa51ce0d17f61917d9f29aac3c9
|
{
"intermediate": 0.3901045620441437,
"beginner": 0.47526970505714417,
"expert": 0.13462573289871216
}
|
10,779
|
При переходе к странице поиска выдает сразу всех имеющихся артистов, вообще всех
При попытке выбрать артиста или группа (критерии поиска) выбор сбрасывается
При поиске по имени или жанру возникает ошибка: ReferenceError: role is not defined
Логика должна быть такова: ты заходишь на страницу поиска, НЕ ВВОДЯ В ПОЛЕ ни имени, ни жанра, можешь выбрать роль артист или группа, клацнуть на search и тебе выдаст артистов по выбранной роли
Либо же ты можешь выбрать роль артиста и в поле поиска (жанр, имя) ввести, например, имя и тебе будет выдавать артистов с таким именем и подходящей ролью
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (role === '' || musician.role === role);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method="get" action="/search">
<label for="query">Search by name or genre:</label>
<input type="text" id="query" name="query" value="<%= query %>">
<br><br>
<label for="role">Search by role:</label>
<select id="role" name="role">
<option value="">All</option>
<option value="Band" <% if (role === 'Band') { %>selected<% } %>>Band</option>
<option value="Artist" <% if (role === 'Artist') { %>selected<% } %>>Artist</option>
</select>
<br><br>
<button type="submit">Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>">
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href="<%= musician.soundcloud %>">SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
document.querySelector('form').addEventListener('submit', function (event) {
event.preventDefault();
const query = document.querySelector('#query').value;
const role = document.querySelector('#role').value;
const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role);
window.location.href = url;
});"
</script>
</body>
</html>
и пожалуйста, когда будешь давать ответ, не используй curly кавычки, используй нормальные
|
02e3b6bbb52ec88a94fcb182e7cbd230
|
{
"intermediate": 0.33111295104026794,
"beginner": 0.44798123836517334,
"expert": 0.2209058254957199
}
|
10,780
|
modifier onlyOwner1 {
require(owner == msg.sender, "You're not the owner!");
_;
}
modifier onlyOwner2() {
isOwner;
_;
}
function isOwner() internal view virtual {
require(owner() = msg.sender, "You're not the owner!")
}
Which among the following modifiers 'onlyOwner1()' and 'onlyOwner2()' is more gas efficient
way of writing modifiers? Why?
|
5cab8a80dc9b0b4cf9734727248d1466
|
{
"intermediate": 0.43532323837280273,
"beginner": 0.3421022891998291,
"expert": 0.22257450222969055
}
|
10,781
|
При переходе к странице поиска выдает сразу всех имеющихся артистов, вообще всех
При попытке выбрать артиста или группа (критерии поиска) выбор сбрасывается
При поиске по имени или жанру возникает ошибка: ReferenceError: role is not defined
Логика должна быть такова: ты заходишь на страницу поиска, НЕ ВВОДЯ В ПОЛЕ ни имени, ни жанра, можешь выбрать роль артист или группа, клацнуть на search и тебе выдаст артистов по выбранной роли
Либо же ты можешь выбрать роль артиста и в поле поиска (жанр, имя) ввести, например, имя и тебе будет выдавать артистов с таким именем и подходящей ролью
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (role === '' || musician.role === role);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method="get" action="/search">
<label for="query">Search by name or genre:</label>
<input type="text" id="query" name="query" value="<%= query %>">
<br><br>
<label for="role">Search by role:</label>
<select id="role" name="role">
<option value="">All</option>
<option value="Band" <% if (role === 'Band') { %>selected<% } %>>Band</option>
<option value="Artist" <% if (role === 'Artist') { %>selected<% } %>>Artist</option>
</select>
<br><br>
<button type="submit">Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>">
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href="<%= musician.soundcloud %>">SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
document.querySelector('form').addEventListener('submit', function (event) {
event.preventDefault();
const query = document.querySelector('#query').value;
const role = document.querySelector('#role').value;
const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role);
window.location.href = url;
});"
</script>
</body>
</html>
|
432c5f3760de405dd6886a55d4f29997
|
{
"intermediate": 0.33111295104026794,
"beginner": 0.44798123836517334,
"expert": 0.2209058254957199
}
|
10,782
|
UIS.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
if input.KeyCode == Enum.KeyCode.E then
local currentTime = os.clock()
if currentTime - lastAnimationTime1 >= 25 / 60 then
AnimationEvent1:FireServer()
lastAnimationTime1 = currentTime
end
elseif input.KeyCode == Enum.KeyCode.Q then
local currentTime = os.clock()
if currentTime - lastAnimationTime2 >= 30 / 60 then – use a different cooldown time for the second animation
AnimationEvent2:FireServer()
lastAnimationTime2 = currentTime
end
end
end
end)
|
13c0d7a7ca16c7427fef3b1f1ac79c62
|
{
"intermediate": 0.39490950107574463,
"beginner": 0.3228829801082611,
"expert": 0.28220754861831665
}
|
10,783
|
write python code to calculator factorial of a number
|
0732c439b3dfb2e6020592e00446b65d
|
{
"intermediate": 0.39296627044677734,
"beginner": 0.30275753140449524,
"expert": 0.3042761981487274
}
|
10,784
|
contract Owner {
address public owner;
uint public contractBalance;
function becomeOwner() public payable {
require(msg.value > contractBalance, "Pay more than balance to become the owner!");
(bool sent, ) = owner.call{value: contractBalance}("");
require(sent, "Transaction failed");
contractBalance = msg.value;
owner = msg.sender;
}
}
The following smart contract allows anyone to become its owner by sending more ether than
the current balance of the contract.You wish to become the owner of this contract forever,
how could you do it by denying others to become the owner?
|
9c767755590b122d2408a341421c6e82
|
{
"intermediate": 0.34871384501457214,
"beginner": 0.4009050130844116,
"expert": 0.25038114190101624
}
|
10,785
|
1.有push.cpp和push.h
push.cpp:
#include “Pusher.h”
#include <iostream>
#include “Common/config.h”
#include “appPublic.h”
#include “FifoMsg.h”
using namespace std;
using namespace mediakit;
using namespace toolkit;
enum AVCodeConst {
AV_CODER_NONE = 0,
AV_VIDEO_CODER_H264 = 1,
AV_VIDEO_CODER_HEVC = 2,
AV_AUDIO_CODER_AAC = 3
};
enum EnumFrameType {
FRAME_TYPE_VIDEO = 0,
FRAME_TYPE_AUDIO = 1,
};
#define PUSH_FIELD “push.”
const string kEnableAAC2G711A = PUSH_FIELD"EnableAAC2G711A";
#define MAX_WRITE_FAILED_TIME (10)
Pusher::Pusher(const SdpInfo &p_SdpInfo)
:m_bIsInitOK(false)
,m_SdpInfo(p_SdpInfo)
,m_audioIdx(0)
,m_videoIdx(0)
,m_ofmt_ctx(NULL)
,aac_swr_ctx(NULL)
,pAcodecContext(NULL)
,alaw_codecContext(NULL)
,m_writeFailedTime(0){
int nInitFlag = init();
if (nInitFlag == 0){
m_bIsInitOK = true;
InfoL<<“create pusher success,dev:”<<m_SdpInfo.szPlayUrl;
}
else{
nInitFlag = false;
InfoL<<“create pusher failed,dev:”<<m_SdpInfo.szPlayUrl;
release();
return;
}
}
Pusher::~Pusher(){
release();
InfoL<<m_SdpInfo.szPlayUrl<<" pusher is released";
}
void Pusher::release(){
if(m_ofmt_ctx == NULL)
return;
av_write_trailer(m_ofmt_ctx);
if (!(m_ofmt_ctx->flags & AVFMT_NOFILE)) {
avio_close(m_ofmt_ctx->pb);
}
avformat_free_context(m_ofmt_ctx);
m_ofmt_ctx = NULL;
if(pAcodecContext){
avcodec_free_context(&pAcodecContext);
pAcodecContext = NULL;
}
if (alaw_codecContext){
avcodec_free_context(&alaw_codecContext);
alaw_codecContext = NULL;
}
}
void Pusher::ffLogCallback(void *ptr, int level, const char *fmt, va_list vl)
{
if (level > av_log_get_level())
return;
char temp[1024];
vsprintf(temp, fmt, vl);
size_t len = strlen(temp);
if (len > 0 && len < 1024&&temp[len - 1] == ‘\n’)
{
temp[len - 1] = ‘\0’;
}
DebugL << (char )temp;
}
/ select layout with the highest channel count */
uint64_t Pusher::select_channel_layout(const AVCodec *codec)
{
if (!codec)
return AV_CH_LAYOUT_STEREO;
const uint64_t *p;
uint64_t best_ch_layout = 0;
int best_nb_channels = 0;
if (!codec->channel_layouts)
return AV_CH_LAYOUT_STEREO;
p = codec->channel_layouts;
while (*p) {
int nb_channels = av_get_channel_layout_nb_channels(*p);
if (nb_channels > best_nb_channels) {
best_ch_layout = *p;
best_nb_channels = nb_channels;
}
p++;
}
return best_ch_layout;
}
int Pusher::select_sample_rate(const AVCodec *codec)
{
if (!codec)
return 44100;
const int *p;
int best_samplerate = 0;
if (!codec->supported_samplerates)
return 44100;
p = codec->supported_samplerates;
while (*p) {
if (!best_samplerate || abs(44100 - *p) < abs(44100 - best_samplerate))
best_samplerate = *p;
p++;
}
return best_samplerate;
}
bool Pusher::init(){
if (strlen(m_SdpInfo.szPlayUrl) <= 0){
ErrorL<<“输出URL不能为空”;
return false;
}
av_register_all();
avformat_network_init();
av_log_set_level(AV_LOG_INFO);
av_log_set_callback(ffLogCallback);
AVDictionary *pDict = NULL;
int ret = avformat_alloc_output_context2(&m_ofmt_ctx, NULL, m_SdpInfo.szFmt, m_SdpInfo.szPlayUrl);
if (ret < 0){
ErrorL<<“avformat_alloc_output_context2 failed, output:”<<m_SdpInfo.szFmt;
return -1;
}
AVCodec *pEnCodeV = NULL;
if (m_SdpInfo.nVideoCodec == AV_VIDEO_CODER_H264)
pEnCodeV = avcodec_find_encoder(AV_CODEC_ID_H264);
else
pEnCodeV = avcodec_find_encoder(AV_CODEC_ID_H265);
if(pEnCodeV)
InfoL<<“The video codec is:”<<pEnCodeV->name;
//设置视频输出格式
AVStream *pStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeV);
pStreamO->id = m_ofmt_ctx->nb_streams - 1;
pStreamO->codec->codec_tag = 0;
pStreamO->codec->width = 1280;
pStreamO->codec->height = 1080;
pStreamO->codec->pix_fmt = AV_PIX_FMT_YUV420P;
AVRational tb{ 1, 90000 };
pStreamO->time_base = tb;
AVRational fr{ 25, 1 };
pStreamO->r_frame_rate = fr; //(tbr)
pStreamO->avg_frame_rate = fr; //(fps)
AVRational sar{ 1, 1 };
pStreamO->sample_aspect_ratio = sar;
AVRational ctb{ 1, 25 };
pStreamO->codec->time_base = ctb;
pStreamO->codec->sample_aspect_ratio = sar;
pStreamO->codec->gop_size = 12;
if (m_ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {
pStreamO->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
if (avcodec_open2(pStreamO->codec, pEnCodeV, NULL) != 0) {
ErrorL << “avcodec_open2 video error”;
}
AVStream *pAStreamO = NULL;
bool bEnableAAC2G711AFlag = mINI::Instance()[kEnableAAC2G711A];
if (bEnableAAC2G711AFlag){
//设置音频输出格式
AVCodec *pEnCodeA = avcodec_find_encoder(::AV_CODEC_ID_PCM_ALAW);
pAStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeA);
pAStreamO->id = m_ofmt_ctx->nb_streams - 1;
pAStreamO->codec->codec_tag = 0;
pAStreamO->codec->sample_fmt = ::AV_SAMPLE_FMT_S16;
pAStreamO->codec->channel_layout = AV_CH_LAYOUT_MONO;
pAStreamO->codec->sample_rate = 8000;
pAStreamO->codec->channels = 1;
pAStreamO->codec->frame_size = 160/2;
if (avcodec_open2(pAStreamO->codec, pEnCodeA, NULL) != 0) {
ErrorL<<“avcodec_open2 audio error” ;
}
}else{
AVCodec *pEnCodeA = avcodec_find_encoder(::AV_CODEC_ID_AAC);
AVStream *pAStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeA);
pAStreamO->id = m_ofmt_ctx->nb_streams - 1;
pAStreamO->codec->codec_tag = 0;
pAStreamO->codec->sample_fmt = ::AV_SAMPLE_FMT_FLTP;
pAStreamO->codec->channel_layout = select_channel_layout(pAStreamO->codec->codec);
pAStreamO->codec->sample_rate = select_sample_rate(pAStreamO->codec->codec);
pAStreamO->codec->channels = ::av_get_channel_layout_nb_channels(pAStreamO->codec->channel_layout);
if (avcodec_open2(pAStreamO->codec, pEnCodeA, NULL) != 0) {
ErrorL<<“avcodec_open2 audio error” ;
}
}
if (!(m_ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
ret = avio_open(&m_ofmt_ctx->pb, m_SdpInfo.szPlayUrl, AVIO_FLAG_WRITE);
}
if (0 == strcasecmp(m_SdpInfo.szFmt, “rtsp”)){
av_dict_set(&pDict, “rtsp_transport”, “tcp”, 0);
av_dict_set(&pDict, “muxdelay”, “0.1”, 0);
}
ret = avformat_write_header(m_ofmt_ctx, &pDict);
av_dump_format(m_ofmt_ctx, 0, m_SdpInfo.szPlayUrl, 1);
if (!bEnableAAC2G711AFlag){
InfoL<<“新建国标流推流器,设备:”<<m_SdpInfo.szPlayUrl;
return ret;
}
InfoL<<“使能AAC转G711A,初始化AAC解码器和G711A编码器”;
//以下为aac->alaw相关
//aac音频格式
int64_t in_channel_layout = AV_CH_LAYOUT_STEREO;
enum AVSampleFormat in_sample_fmt = AV_SAMPLE_FMT_FLTP;
int in_sample_rate = 44100;
int in_channels = 2;
AVRational in_timeBase = {1,44100};
//alaw音频格式
uint64_t out_channel_layout = AV_CH_LAYOUT_MONO;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_sample_rate = 8000;
int out_nb_samples = 160;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
//aac->alaw重采样器
aac_swr_ctx = swr_alloc();
aac_swr_ctx = swr_alloc_set_opts(aac_swr_ctx, out_channel_layout, out_sample_fmt, out_sample_rate,in_channel_layout, in_sample_fmt, in_sample_rate, 0, NULL);
swr_init(aac_swr_ctx);
//初始化AAC解码器
AVCodec pAcodec = avcodec_find_decoder(AV_CODEC_ID_AAC);
pAcodecContext = avcodec_alloc_context3(pAcodec);
pAcodecContext->sample_rate = in_sample_rate;
pAcodecContext->channels = in_channels;
pAcodecContext->sample_fmt = in_sample_fmt;
pAcodecContext->time_base = in_timeBase;
avcodec_open2(pAcodecContext, pAcodec, NULL);
//初始化alaw编码器
AVCodec alaw_codec = avcodec_find_encoder(AV_CODEC_ID_PCM_ALAW);
alaw_codecContext = avcodec_alloc_context3(alaw_codec);
alaw_codecContext->codec_type = AVMEDIA_TYPE_AUDIO;
alaw_codecContext->sample_rate = 8000;
alaw_codecContext->channels = 1;
alaw_codecContext->sample_fmt = out_sample_fmt; // ALAW编码需要16位采样,U8在目前ff版本不支持
alaw_codecContext->channel_layout = AV_CH_LAYOUT_MONO;
alaw_codecContext->height = pStreamO->codec->height;
alaw_codecContext->width = pStreamO->codec->width;
alaw_codecContext->codec_id = AV_CODEC_ID_PCM_ALAW;
alaw_codecContext->bit_rate = 64000;
//alaw_codecContext->frame_size = 160/2;
ret = avcodec_open2(alaw_codecContext, alaw_codec, NULL);
if (ret < 0)
ErrorL<<“avcodec_open2 alaw_codecContext failed”;
else
InfoL<<“avcodec_open2 alaw_codecContext ok”;
av_init_packet(&m_pkt);
return ret;
}
int Pusher::WriteFrame(const int p_nFrameType,const uint8_t p_frame_data, const int p_frame_len){
if (!m_bIsInitOK)
return -1;
int64_t currentTimeStamp = 0;
if (p_nFrameType == FRAME_TYPE_VIDEO) {
currentTimeStamp = m_videoIdx * 3600;
if(strlen(m_SdpInfo.szFileName) > 0 && (m_videoIdx % 25 == 0)){
int ndownloadProgress = (int)(m_videoIdx * 100 / m_SdpInfo.nHistoryTotalFrameNum);
if(ndownloadProgress >= 100){
ndownloadProgress = 100;
}
InfoL<<“download file:”<<m_SdpInfo.szFileName<<" download progress:"<<ndownloadProgress;
m_SdpInfo.nDownloadProgress = ndownloadProgress;
m_SdpInfo.nEventType = DevProcessType_upload_download_progress;
sendFifoMsg(m_SdpInfo);
}
m_videoIdx++;
}
if (p_nFrameType == FRAME_TYPE_AUDIO) {
currentTimeStamp= m_audioIdx * 1024;
m_audioIdx++;
}
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = (uint8_t)p_frame_data;
pkt.size = p_frame_len;
pkt.pts = currentTimeStamp;
pkt.dts = currentTimeStamp;
pkt.duration = 3600;
pkt.pos = -1;
pkt.stream_index = p_nFrameType;
int ret = -1;
if (p_nFrameType == FRAME_TYPE_VIDEO) {
//std::cout<<“=====lgo 1===”<<std::endl;
if (m_ofmt_ctx){
ret = av_write_frame(m_ofmt_ctx, &pkt);
//std::cout<<“=====lgo 2===ret:”<<ret<<std::endl;
if(ret < 0){
m_writeFailedTime++;
if (MAX_WRITE_FAILED_TIME < m_writeFailedTime || ret == -32){
m_SdpInfo.nEventType = DevProcessType_stop_stream;
sendFifoMsg(m_SdpInfo);
return -1;
}
}
m_writeFailedTime = 0;
}
av_packet_unref(&pkt);
return ret;
}
bool bEnableAAC2G711AFlag = mINI::Instance()[kEnableAAC2G711A];
if (!bEnableAAC2G711AFlag){
if (m_ofmt_ctx){
ret = av_write_frame(m_ofmt_ctx, &pkt);
}
av_packet_unref(&pkt);
return ret;
}
if (p_nFrameType == FRAME_TYPE_AUDIO) {
int got_frame;
AVFrame *pAACFrame=av_frame_alloc();
ret = avcodec_decode_audio4(pAcodecContext, pAACFrame, &got_frame, &pkt);
if(ret < 0){
ErrorL<<“avcodec_decode_audio4 failed”;
return -1;
}else if (got_frame){
//解码aac成功后,重采样得到alaw数据
uint64_t out_channel_layout = AV_CH_LAYOUT_MONO;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_nb_samples = 160;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
int alaw_buffer_size = av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, out_sample_fmt, 1);
//44.1KHZ,16bit,2声道的pcm转换成pcma 8khz,16bit,1声道
uint8_t *alaw_buffer = (uint8_t *)av_malloc(pAACFrame->nb_samples);
swr_convert(aac_swr_ctx, &alaw_buffer, alaw_buffer_size, (const uint8_t *)pAACFrame->data, pAACFrame->nb_samples);
//构造alawFrame
AVFrame * alawFrame = av_frame_alloc();
//设置AVFrame的基本信息
alawFrame->sample_rate = 8000;
alawFrame->channels = 1;
alawFrame->format = AV_SAMPLE_FMT_S16;
alawFrame->channel_layout = AV_CH_LAYOUT_MONO;
alawFrame->nb_samples = alaw_buffer_size/2;
av_frame_get_buffer(alawFrame, 0);
memcpy(alawFrame->data[0], alaw_buffer, alaw_buffer_size);
int got_packet = 0;
AVPacket packet = av_packet_alloc();
av_init_packet(packet);
packet->data = alaw_buffer;
packet->size = alaw_buffer_size;
packet->stream_index = 1;
ret = avcodec_encode_audio2(alaw_codecContext, packet, alawFrame, &got_packet);
av_frame_free(&alawFrame);
if (ret < 0){
ErrorL<<“avcodec_encode_audio2 failed”;
}else if (got_packet){
//成功编码出音频包后,写输出流
int nbSamplesPerPacket = 160;
int sampleRate = 8000;
packet->pts = (m_audioIdx-1) *160;
packet->dts = packet->pts;
packet->duration = 160;
packet->stream_index = 1;
packet->pos = 1;
ret = ::av_write_frame(m_ofmt_ctx, packet);
}
av_packet_free(&packet);
av_free(alaw_buffer);
}
av_frame_free(&pAACFrame);
}
av_packet_unref(&pkt);
return 0;
}
void Pusher::sendFifoMsg(const SdpInfo &p_objSdpInfo){
if (p_objSdpInfo.nSrcPort <= 0 || strlen(p_objSdpInfo.szDevid) <= 0)
return;
char szFifoName[128] = {0};
snprintf(szFifoName, sizeof(szFifoName), FORMAT_PORT_DISPATCH_THREAD_MSG_FIFO,p_objSdpInfo.nSrcPort);
std::string strJson;
SdpParse::makeFifoMsgJson(p_objSdpInfo, strJson);
DebugL<<“send msg, fifo:”<<szFifoName<<“, msg:”<<strJson;
FifoMsg::fifo_send_msg(szFifoName, strJson);
}
push.h
#ifndef PUSHER_H
#define PUSHER_H
#include <string>
#include <string.h>
#include “SdpParse.h”
extern “C” {
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavutil/avutil.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/time.h>
#include <libswresample/swresample.h>
}
class Pusher {
public:
Pusher(const SdpInfo &p_SdpInfo);
~Pusher();
int WriteFrame(const int p_nFrameType,const uint8_t *p_frame_data, const int p_frame_len);
private:
bool init();
static void ffLogCallback(void *ptr, int level, const char *fmt, va_list vl);
uint64_t select_channel_layout(const AVCodec *codec);
int select_sample_rate(const AVCodec *codec);
void release();
void sendFifoMsg(const SdpInfo &p_objSdpInfo);
private:
AVFormatContext *m_ofmt_ctx;
struct SwrContext *aac_swr_ctx;
AVCodecContext pAcodecContext;
AVCodecContext alaw_codecContext;
int m_audioIdx;
int m_videoIdx;
AVPacket m_pkt;
int m_writeFailedTime;
private:
bool m_bIsInitOK;
SdpInfo m_SdpInfo;
};
#endif
1.请描述上面代码实现的功能
1.请用c11重写以上代码,要求不能有内存泄漏,要求成员变量名称统一m_xxx来命名,做到通俗易懂
|
0a48dccf18053ca97f553dcbb820ff70
|
{
"intermediate": 0.4296950101852417,
"beginner": 0.4117417335510254,
"expert": 0.15856324136257172
}
|
10,786
|
При переходе к странице поиска выдает сразу всех имеющихся артистов, вообще всех
При попытке выбрать артиста или группа (критерии поиска) выбор сбрасывается
При поиске по имени или жанру возникает ошибка: ReferenceError: role is not defined
Логика должна быть такова: ты заходишь на страницу поиска, НЕ ВВОДЯ В ПОЛЕ ни имени, ни жанра, можешь выбрать роль артист или группа, клацнуть на search и тебе выдаст артистов по выбранной роли
Либо же ты можешь выбрать роль артиста и в поле поиска (жанр, имя) ввести, например, имя и тебе будет выдавать артистов с таким именем и подходящей ролью
P.S: все данные (в том числе роль) хранятся в musicians.json:
{“musicians”:[{“id”:1,“name”:“sukaAAAAAAA”,“genre”:“BluesZ”,“instrument”:“Guitar”,“soundcloud”:“http://soundcloud.com/dasdasdasd",“password”:“password123”,“location”:"New York”,“login”:“suka”,“bio”:“”},{“id”:2,“name”:“Aerosmith111114446”,“genre”:“Blues”,“password”:“1111”,“location”:“EnglandDdDDDDDDD”,“thumbnail”:“musician_2_jX7hQvfoT2g (2).jpg”,“instrument”:“”,“bio”:“”,“soundcloud”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing",“soundcloud1”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing”},{“id”:3,“name”:“Britpop”,“genre”:“Pop”,“instrument”:“bass”,“soundcloud”:“http://google.com”,“password”:“1111”,“location”:“Sahara”,“login”:“SS1VCSS@gmail.com”,“thumbnail”:“musician_3_photo_2023-02-27_01-16-44.jpg”},{“id”:4,“name”:“Bobq”,“genre”:"Hip hop”,“instrument”:“keys”,“soundcloud”:“http://cloudnine.ru",“password”:“1111”,“location”:“Dallas”,“login”:"SSSS1VYTFFSDDD@gmail.com”,“thumbnail”:“musician_4_1mxwr7Ravu4.jpg”},{“id”:5,“name”:“LOL”,“genre”:“Rock”,“instrument”:“Bass”,“soundcloud”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing",“password”:“1111”,“location”:“Manchester”,“role”:“Artist”,“login”:“<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>”,“thumbnail”:"musician_5_photo_2023-02-27_01-16-43 (2).jpg”}]}
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (role === ‘’ || musician.role === role);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const role = req.query.role || ‘’;
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method=“get” action=”/search">
<label for=“query”>Search by name or genre:</label>
<input type=“text” id=“query” name=“query” value=“<%= query %>”>
<br><br>
<label for=“role”>Search by role:</label>
<select id=“role” name=“role”>
<option value=“”>All</option>
<option value=“Band” <% if (role === ‘Band’) { %>selected<% } %>>Band</option>
<option value=“Artist” <% if (role === ‘Artist’) { %>selected<% } %>>Artist</option>
</select>
<br><br>
<button type=“submit”>Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”>
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”>
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href=“<%= musician.soundcloud %>”>SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
document.querySelector(‘form’).addEventListener(‘submit’, function (event) {
event.preventDefault();
const query = document.querySelector(‘#query’).value;
const role = document.querySelector(‘#role’).value;
const url = ‘/search?query=’ + encodeURIComponent(query) + ‘&role=’ + encodeURIComponent(role);
window.location.href = url;
});"
</script>
</body>
</html>
и прошу, не используй curly кавычки, когда будешь давать ответ мне, используй обычные
|
d667fbf09c1015254127501bd8e1df87
|
{
"intermediate": 0.30043816566467285,
"beginner": 0.43342530727386475,
"expert": 0.26613649725914
}
|
10,787
|
Hello. In python using machine learning, I want you to create a predictor for a kahoot, the quiz mode, where the player has to chose between 4 answers. There is only one answer, and I want you to make an input statement for eachtime a prediction has been made. The user inputs the right answer is numbers; like the first answer box is named 1, second is named 2, third is named 3 and fourth is named 4. Each time the user has sat the new input in, the app makes a predictior for the next best odds on one of the four boxes that's correct. When the prediction has been made, then the programs asks for what was the right answer, and saves it, as it's gonna be stored as data for the app to then predict the next. It will loop until the words "exit" has been wrote and it then exit. Short: Make a predictor in python, that goes in a loop to a 4 box game with one correct answer. The app is gonna predict, and then ask for an user input, and predict again until the user types exit.
|
465dd8b1d93827869d8b17adc248a619
|
{
"intermediate": 0.2405521273612976,
"beginner": 0.16342781484127045,
"expert": 0.5960200428962708
}
|
10,788
|
При переходе к странице поиска выдает сразу всех имеющихся артистов, вообще всех
При попытке выбрать артиста или группа (критерии поиска) выбор сбрасывается
При поиске по имени или жанру возникает ошибка: ReferenceError: role is not defined
Логика должна быть такова: ты заходишь на страницу поиска, НЕ ВВОДЯ В ПОЛЕ ни имени, ни жанра, можешь выбрать роль артист или группа, клацнуть на search и тебе выдаст артистов по выбранной роли
Либо же ты можешь выбрать роль артиста и в поле поиска (жанр, имя) ввести, например, имя и тебе будет выдавать артистов с таким именем и подходящей ролью
P.S: все данные (в том числе роль) хранятся в musicians.json:
{“musicians”:[{“id”:1,“name”:“sukaAAAAAAA”,“genre”:“BluesZ”,“instrument”:“Guitar”,“soundcloud”:“http://soundcloud.com/dasdasdasd",“password”:“password123”,“location”:"New York”,“login”:“suka”,“bio”:“”},{“id”:2,“name”:“Aerosmith111114446”,“genre”:“Blues”,“password”:“1111”,“location”:“EnglandDdDDDDDDD”,“thumbnail”:“musician_2_jX7hQvfoT2g (2).jpg”,“instrument”:“”,“bio”:“”,“soundcloud”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing",“soundcloud1”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing”},{“id”:3,“name”:“Britpop”,“genre”:“Pop”,“instrument”:“bass”,“soundcloud”:“http://google.com”,“password”:“1111”,“location”:“Sahara”,“login”:“SS1VCSS@gmail.com”,“thumbnail”:“musician_3_photo_2023-02-27_01-16-44.jpg”},{“id”:4,“name”:“Bobq”,“genre”:"Hip hop”,“instrument”:“keys”,“soundcloud”:“http://cloudnine.ru",“password”:“1111”,“location”:“Dallas”,“login”:"SSSS1VYTFFSDDD@gmail.com”,“thumbnail”:“musician_4_1mxwr7Ravu4.jpg”},{“id”:5,“name”:“LOL”,“genre”:“Rock”,“instrument”:“Bass”,“soundcloud”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing",“password”:“1111”,“location”:“Manchester”,“role”:“Artist”,“login”:“<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>”,“thumbnail”:"musician_5_photo_2023-02-27_01-16-43 (2).jpg”}]}
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (role === ‘’ || musician.role === role);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const role = req.query.role || ‘’;
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method=“get” action=”/search">
<label for=“query”>Search by name or genre:</label>
<input type=“text” id=“query” name=“query” value=“<%= query %>”>
<br><br>
<label for=“role”>Search by role:</label>
<select id=“role” name=“role”>
<option value=“”>All</option>
<option value=“Band” <% if (role === ‘Band’) { %>selected<% } %>>Band</option>
<option value=“Artist” <% if (role === ‘Artist’) { %>selected<% } %>>Artist</option>
</select>
<br><br>
<button type=“submit”>Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”>
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”>
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href=“<%= musician.soundcloud %>”>SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
document.querySelector(‘form’).addEventListener(‘submit’, function (event) {
event.preventDefault();
const query = document.querySelector(‘#query’).value;
const role = document.querySelector(‘#role’).value;
const url = ‘/search?query=’ + encodeURIComponent(query) + ‘&role=’ + encodeURIComponent(role);
window.location.href = url;
});"
</script>
</body>
</html>
ВАЖНО! И прошу, не используй curly кавычки, когда будешь давать ответ мне, используй обычные
|
a3f7efc51451a6f73d45ab66e3d448ea
|
{
"intermediate": 0.30043816566467285,
"beginner": 0.43342530727386475,
"expert": 0.26613649725914
}
|
10,789
|
Create a script for a Kahoot game that predicts the next round's answer. The game has 4 boxes, each represented by a number: 1, 2, 3, and 4. I want the script to predict the color of the next round based on the previous round's data. The colors are Red (1), Blue (2), Yellow (3), and Green (4). The script should ask for the previous round's correct box number and predict the next round's color. Use machine learning to make the predictions. Every time it has made a prediction, it has to ask for the right answer, to then predict again using that data, so it keeps getting more and more data for better predictions
|
f104fc4955f24becf5d94b9d5e313852
|
{
"intermediate": 0.2231801301240921,
"beginner": 0.08163375407457352,
"expert": 0.6951861381530762
}
|
10,790
|
При переходе к странице поиска выдает сразу всех имеющихся артистов, вообще всех
При попытке выбрать артиста или группа (критерии поиска) выбор сбрасывается
При поиске по имени или жанру возникает ошибка: ReferenceError: role is not defined
Логика должна быть такова: ты заходишь на страницу поиска, НЕ ВВОДЯ В ПОЛЕ ни имени, ни жанра, можешь выбрать роль артист или группа, клацнуть на search и тебе выдаст артистов по выбранной роли
Либо же ты можешь выбрать роль артиста и в поле поиска (жанр, имя) ввести, например, имя и тебе будет выдавать артистов с таким именем и подходящей ролью
P.S: все данные (в том числе роль) хранятся в musicians.json:
{“musicians”:[{“id”:1,“name”:“sukaAAAAAAA”,“genre”:“BluesZ”,“instrument”:“Guitar”,“soundcloud”:“http://soundcloud.com/dasdasdasd",“password”:“password123”,“location”:"New York”,“login”:“suka”,“bio”:“”},{“id”:2,“name”:“Aerosmith111114446”,“genre”:“Blues”,“password”:“1111”,“location”:“EnglandDdDDDDDDD”,“thumbnail”:“musician_2_jX7hQvfoT2g (2).jpg”,“instrument”:“”,“bio”:“”,“soundcloud”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing",“soundcloud1”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing”},{“id”:3,“name”:“Britpop”,“genre”:“Pop”,“instrument”:“bass”,“soundcloud”:“http://google.com”,“password”:“1111”,“location”:“Sahara”,“login”:“SS1VCSS@gmail.com”,“thumbnail”:“musician_3_photo_2023-02-27_01-16-44.jpg”},{“id”:4,“name”:“Bobq”,“genre”:"Hip hop”,“instrument”:“keys”,“soundcloud”:“http://cloudnine.ru",“password”:“1111”,“location”:“Dallas”,“login”:"SSSS1VYTFFSDDD@gmail.com”,“thumbnail”:“musician_4_1mxwr7Ravu4.jpg”},{“id”:5,“name”:“LOL”,“genre”:“Rock”,“instrument”:“Bass”,“soundcloud”:“https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing",“password”:“1111”,“location”:“Manchester”,“role”:“Artist”,“login”:“<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>”,“thumbnail”:"musician_5_photo_2023-02-27_01-16-43 (2).jpg”}]}
прошу, не используй curly кавычки, когда будешь давать ответ мне, используй обычные
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query, hiddenRole) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0 && (role === ‘’ || musician.role === role);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const role = req.query.role || ‘’;
const musicians = search(query, role);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form method=“get” action=”/search">
<label for=“query”>Search by name or genre:</label>
<input type=“text” id=“query” name=“query” value=“<%= query %>”>
<br><br>
<label for=“role”>Search by role:</label>
<select id=“role” name=“role”>
<option value=“”>All</option>
<option value=“Band” <% if (role === ‘Band’) { %>selected<% } %>>Band</option>
<option value=“Artist” <% if (role === ‘Artist’) { %>selected<% } %>>Artist</option>
</select>
<br><br>
<button type=“submit”>Search</button>
</form>
<% if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<% musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”>
<%= musician.name %>
<% if (musician.thumbnail) { %>
<img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”>
<% } %>
</a>
- <%= musician.genre %>
<% if (musician.soundcloud) { %>
<a href=“<%= musician.soundcloud %>”>SoundCloud</a>
<% } %>
</li>
<% }); %>
</ul>
<% } else if (query || role) { %>
<p>No musicians found.</p>
<% } %>
<script>
document.querySelector(‘form’).addEventListener(‘submit’, function (event) {
event.preventDefault();
const query = document.querySelector(‘#query’).value;
const role = document.querySelector(‘#role’).value;
const url = ‘/search?query=’ + encodeURIComponent(query) + ‘&role=’ + encodeURIComponent(role);
window.location.href = url;
});"
</script>
</body>
</html>
прошу, не используй curly кавычки, когда будешь давать ответ мне, используй обычные
|
f9ba97d0759705fe4ca647d71e1d227b
|
{
"intermediate": 0.30043816566467285,
"beginner": 0.43342530727386475,
"expert": 0.26613649725914
}
|
10,791
|
Generate a modern CSS, with header, footer, and a few extra HTML things, for the wiki-based HTML's.
|
4862e50e3e563f8190ec6d2c694e9e00
|
{
"intermediate": 0.3365236222743988,
"beginner": 0.27383846044540405,
"expert": 0.3896379768848419
}
|
10,792
|
write python app using pyPDF2 which modifies existing pdf file by adding a new page at the end of the document and inserts a picture
|
a26e453732a8094598150bd2ad46e7d1
|
{
"intermediate": 0.4892977476119995,
"beginner": 0.2053067535161972,
"expert": 0.30539554357528687
}
|
10,793
|
Here is a function that works, but I want to add further functionality to it. I want to add to the if (!isFound) { branch the following extra steps: If the newly created value in the E column sheet "List" has four or fewer characters, the script continue as it is now. However, if the newly created value in the E column sheet "List" has five or more characters, I want the script to clear all the values that it had just placed (in column B, C and E on the new row of sheet "List") and then continue. Here is the original script:
function processHyperlinks() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var listSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List");
var columnsToCheck = ["C", "H", "M", "R"];
columnsToCheck.forEach(function (column) {
var numRows = activeSheet.getLastRow();
var range = activeSheet.getRange(column + "1:" + column + numRows);
var values = range.getRichTextValues();
for (var i = 0; i < values.length; i++) {
var richText = values[i][0];
if (richText.getLinkUrl()) {
var url = richText.getLinkUrl();
var listRange = listSheet.getRange("C1:C" + listSheet.getLastRow());
var listValues = listRange.getValues();
var isFound = false;
for (var j = 0; j < listValues.length; j++) {
if (listValues[j][0] == url) {
isFound = true;
break;
}
}
if (!isFound) {
var newRow = listSheet.getLastRow() + 1;
listSheet.getRange("C" + newRow).setValue(url);
// Add IMPORTRANGE function to E column
var importRangeFormula = '=IMPORTRANGE(C' + newRow + ',"<<Binder>>!D1")';
listSheet.getRange("E" + newRow).setFormula(importRangeFormula);
// Add regexextract function to B column
var regexExtractFormula = '=IFERROR(REGEXEXTRACT(E' + newRow + ',"[\\w]* [\\w]*"),"")';
listSheet.getRange("B" + newRow).setFormula(regexExtractFormula);
}
}
}
});
}
|
d8a65cc60acb98cd1955ef3190408cdd
|
{
"intermediate": 0.35961997509002686,
"beginner": 0.3405335545539856,
"expert": 0.2998465299606323
}
|
10,794
|
write this code in C
|
64a05eb4ca20446a8542191131aeec48
|
{
"intermediate": 0.18730394542217255,
"beginner": 0.5402274131774902,
"expert": 0.27246859669685364
}
|
10,795
|
Correct the below code for prediting the stock market price using super tend as indicator:
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['H-L'] = data['High'] - data['Low']
data['H-PC'] = abs(data['High'] - data['Close'].shift(1))
data['L-PC'] = abs(data['Low'] - data['Close'].shift(1))
data['TR'] = data[['H-L', 'H-PC', 'L-PC']].max(axis=1)
data['ATR'] = data['TR'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['High'] + data['Low']) / 2 + multiplier * data['ATR']
data['Lower Basic'] = (data['High'] + data['Low']) / 2 - multiplier * data['ATR']
data['Upper Band'] = data.apply(lambda x: x['Upper Basic'] if x['Close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data.apply(lambda x: x['Lower Basic'] if x['Close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.where(data['Close'] > data['Upper Band'], data['Lower Band'], data['Upper Band'])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
stock_data.columns = [col.lower() for col in stock_data.columns]
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['Open', 'High', 'Low', 'Close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label='Actual')
plt.plot(y_pred_inverse, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('Stock Price Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Define the parameters
ticker = '^NSEI' # Ticker symbol for Nifty
start_date = '2010-01-01'
end_date = '2023-06-01'
window_size = 60 # Number of previous days' data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
# Load and preprocess the data
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
# Evaluate the model
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1)) # Fit scaler on training labels
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}")
print(f"Mean Squared Error: {mse}")
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
# Predict the closing price for the upcoming 5 days and plot them
upcoming_days = 5
predictions = []
for i in range(upcoming_days):
next_day_input = np.array([X_test[-1, 1:, :]]) # Use the last window data from X_test and exclude the first element
next_day_pred = model.predict(next_day_input)
predictions.append(next_day_pred[0, 0])
new_row = np.column_stack((next_day_input[0, 1:, :], next_day_pred)) # Create a new row with the predicted value
X_test = np.append(X_test, [new_row], axis=0) # Append the new row to X_test
predictions = np.array(predictions).reshape(-1, 1)
predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1] # Inverse transform for Close prices
# Plot the upcoming 5 days predictions
plt.figure(figsize=(14, 6))
plt.plot(predictions_inverse, marker="o", label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('NIFTY Stock Price Prediction for Upcoming 5 Days')
plt.legend()
plt.show()
|
a052162c04f4032847dd26f8c04f8eab
|
{
"intermediate": 0.4241010546684265,
"beginner": 0.35778939723968506,
"expert": 0.21810954809188843
}
|
10,796
|
Hi, I want to create a chatbot using GPT-4, how to do it?
|
25f46b9538391155ce16740a8ae08dfe
|
{
"intermediate": 0.3155950605869293,
"beginner": 0.10059186816215515,
"expert": 0.5838130712509155
}
|
10,797
|
Overcome this error in the code:
Error:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3801 try:
-> 3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
7 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'High'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
-> 3804 raise KeyError(key) from err
3805 except TypeError:
3806 # If we have a listlike key, _check_indexing_error will raise
KeyError: 'High'
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['H-L'] = data['High'] - data['Low']
data['H-PC'] = abs(data['High'] - data['Close'].shift(1))
data['L-PC'] = abs(data['Low'] - data['Close'].shift(1))
data['TR'] = data[['H-L', 'H-PC', 'L-PC']].max(axis=1)
data['ATR'] = data['TR'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['High'] + data['Low']) / 2 + multiplier * data['ATR']
data['Lower Basic'] = (data['High'] + data['Low']) / 2 - multiplier * data['ATR']
data['Upper Band'] = data.apply(lambda x: x['Upper Basic'] if x['Close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data.apply(lambda x: x['Lower Basic'] if x['Close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.where(data['Close'] > data['Upper Band'], data['Lower Band'], data['Upper Band'])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
stock_data.columns = [col.lower() for col in stock_data.columns]
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['Open', 'High', 'Low', 'Close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label='Actual')
plt.plot(y_pred_inverse, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('Stock Price Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Define the parameters
ticker = '^NSEI' # Ticker symbol for Nifty
start_date = '2010-01-01'
end_date = '2023-06-01'
window_size = 60 # Number of previous days' data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
# Load and preprocess the data
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
# Evaluate the model
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1)) # Fit scaler on training labels
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}“)
print(f"Mean Squared Error: {mse}”)
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
# Predict the closing price for the upcoming 5 days and plot them
upcoming_days = 5
predictions = []
for i in range(upcoming_days):
next_day_input = np.array([X_test[-1, 1:, :]]) # Use the last window data from X_test and exclude the first element
next_day_pred = model.predict(next_day_input)
predictions.append(next_day_pred[0, 0])
new_row = np.column_stack((next_day_input[0, 1:, :], next_day_pred)) # Create a new row with the predicted value
X_test = np.append(X_test, [new_row], axis=0) # Append the new row to X_test
predictions = np.array(predictions).reshape(-1, 1)
predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1] # Inverse transform for Close prices
# Plot the upcoming 5 days predictions
plt.figure(figsize=(14, 6))
plt.plot(predictions_inverse, marker="o", label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('NIFTY Stock Price Prediction for Upcoming 5 Days')
plt.legend()
plt.show()
|
2223bf29ea2313c8730489b6c1ed4cca
|
{
"intermediate": 0.42706891894340515,
"beginner": 0.36994051933288574,
"expert": 0.20299050211906433
}
|
10,798
|
#include <stdio.h>
#include <omp.h>
int main()
{
int i;
double step;
double x, pi, sum = 0.0;
int num_steps = 100000000;
step = 1.0 / (double) num_steps;
#pragma omp parallel for reduction(+:sum)
for (i = 0; i < num_steps; i++)
{
x = (i + 0.5) * step;
sum = sum + 4.0 / (1.0 + x*x);
}
pi = step * sum;
printf("pi is approximately: %.16lf\n",pi);
return 0;
}这个程序可以只使用reduction吗
|
b2d7d197f3204f14bfa5a98c49da0280
|
{
"intermediate": 0.3394981026649475,
"beginner": 0.4058062434196472,
"expert": 0.2546956241130829
}
|
10,799
|
write opencv python app that alows the user to draw an area of interest on the current feed. when the area is defined the user clicks start and the program takes the current color in the area of interest as base for comparing.it should notify when there is a color change in the defined area
|
c5c8eedac7abbf7923418bd3dddf3657
|
{
"intermediate": 0.35708585381507874,
"beginner": 0.1285201758146286,
"expert": 0.5143939256668091
}
|
10,800
|
Here is a function that works, but I want to add further functionality to it. I want to add to the if (!isFound) { branch the following extra steps: If the newly created value in the E column sheet "List" is an error, the script continue as it is now. However, if the newly created value in the E column sheet "List" is not an error, I want the script to clear all the values that it had just placed (in column B, C and E on the new row of sheet "List") and then continue. Here is the original script:
function processHyperlinks() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var listSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List");
var columnsToCheck = ["C", "H", "M", "R"];
columnsToCheck.forEach(function (column) {
var numRows = activeSheet.getLastRow();
var range = activeSheet.getRange(column + "1:" + column + numRows);
var values = range.getRichTextValues();
for (var i = 0; i < values.length; i++) {
var richText = values[i][0];
if (richText.getLinkUrl()) {
var url = richText.getLinkUrl();
var listRange = listSheet.getRange("C1:C" + listSheet.getLastRow());
var listValues = listRange.getValues();
var isFound = false;
for (var j = 0; j < listValues.length; j++) {
if (listValues[j][0] == url) {
isFound = true;
break;
}
}
if (!isFound) {
var newRow = listSheet.getLastRow() + 1;
listSheet.getRange("C" + newRow).setValue(url);
// Add IMPORTRANGE function to E column
var importRangeFormula = '=IMPORTRANGE(C' + newRow + ',"<<Binder>>!D1")';
listSheet.getRange("E" + newRow).setFormula(importRangeFormula);
// Add regexextract function to B column
var regexExtractFormula = '=IFERROR(REGEXEXTRACT(E' + newRow + ',"[\\w]* [\\w]*"),"")';
listSheet.getRange("B" + newRow).setFormula(regexExtractFormula);
}
}
}
});
}
|
88016c8ba23607667530f8e17fe16b28
|
{
"intermediate": 0.4200436472892761,
"beginner": 0.316161185503006,
"expert": 0.2637951672077179
}
|
10,801
|
aws serverless lambda project with python that made it so that you could sync the data between two different trello cards on two different boards.
|
94bae2ab5294ca7d1d1ae2dde80ffd71
|
{
"intermediate": 0.5953771471977234,
"beginner": 0.16021962463855743,
"expert": 0.2444031834602356
}
|
10,802
|
local animations = {
{cooldown = 25/60, event = AnimationEvent1},
{cooldown = 30/60, event = AnimationEvent2},
{cooldown = 20/60, event = AnimationEvent3},
– add more animations here as needed
}
local lastAnimationTimes = {}
UIS.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
for i, animation in ipairs(animations) do
if input.KeyCode == Enum.KeyCode[i] then
local currentTime = os.clock()
if not lastAnimationTimes[i] or currentTime - lastAnimationTimes[i] >= animation.cooldown then
animation.event:FireServer()
lastAnimationTimes[i] = currentTime
end
end
end
end
end)
|
1bb1ba4ffbe5827b7d5595783fef024a
|
{
"intermediate": 0.3647843301296234,
"beginner": 0.2636299133300781,
"expert": 0.37158575654029846
}
|
10,803
|
Почему после ввода id человека в Find user by id крашится программа.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <stdexcept>
#include <set>
using namespace std;
// структура для хранения информации о пользователях
struct User {
int id;
string name;
string masked_ip;
int port;
};
// генерация случайного id пользователя
int generate_id(set<int>& used_ids) {
int id;
do {
id = rand() % 1000000000;
} while (used_ids.find(id) != used_ids.end());
used_ids.insert(id);
return id;
}
// генерация маскированного ip-адреса пользователя
string generate_masked_ip(set<string>& used_ips) {
int number;
stringstream ss;
for (int i = 0; i < 9; i++) {
number = rand() % 10;
ss << number;
}
string masked_ip = ss.str();
while (used_ips.find(masked_ip) != used_ips.end()) {
masked_ip = generate_masked_ip(used_ips);
}
used_ips.insert(masked_ip);
return masked_ip;
}
// функция для сохранения информации о пользователе в файл
void save_user_info(const vector<User>& users) {
ofstream file("C: / users.txt");
if (!file.is_open()) {
throw runtime_error("Cannot open file for writing");
}
for (const User& user : users) {
file << user.id << ", " << user.name << ", " << user.masked_ip << ", " << user.port << endl;
}
file.close();
}
// функция для загрузки информации о пользователях из файла
void load_user_info(vector<User>& users, set<int>& used_ids, set<string>& used_ips) {
ifstream file("C: / users.txt");
if (!file.is_open()) {
ofstream new_file("C: / users.txt");
new_file.close();
}
else {
string line;
while (getline(file, line)) {
User user;
int pos;
pos = line.find(", ");
user.id = stoi(line.substr(0, pos));
if (used_ids.find(user.id) != used_ids.end()) {
throw runtime_error("Duplicated user id : " + to_string(user.id));
}
used_ids.insert(user.id);
line.erase(0, pos + 1);
pos = line.find(", ");
user.name = line.substr(1, pos - 2);
line.erase(0, pos + 1);
pos = line.find(", ");
user.masked_ip = line.substr(1, pos - 2);
if (used_ips.find(user.masked_ip) != used_ips.end()) {
throw runtime_error("Duplicated user ip: " + user.masked_ip);
}
used_ips.insert(user.masked_ip);
line.erase(0, pos + 1);
user.port = stoi(line);
users.push_back(user);
}
file.close();
}
}
// функция для поиска пользователя по id
User find_user_by_id(const vector<User>& users, int id) {
for (const User& user : users) {
if (user.id == id) {
return user;
}
}
User user;
user.id = -1;
return user;
}
// функция для поиска пользователя по имени
User find_user_by_name(const vector<User>& users, const string& name) {
for (const User& user : users) {
if (user.name == name) {
return user;
}
}
User user;
user.id = -1;
return user;
}
// функция для проверки корректности порта
bool is_port_correct(int port) {
if (port < 1024 || port > 65535) {
return false;
}
return true;
}
User find_user_by_masked_ip(const vector<User>& users, const string& masked_ip);
// функция для отправки сообщения от пользователя sender пользователю recipient
void send_message(const vector<User>& users, int sender_id, const string& recipient_ip, const string& message) {
User sender = find_user_by_id(users, sender_id);
if (sender.id == -1) {
throw runtime_error("User with this id was not found");
}
User recipient = find_user_by_masked_ip(users, recipient_ip);
if (recipient.id == -1) {
throw runtime_error("User with this ip was not found");
}
cout << "Message from " << sender.name << " to " << recipient.name << ": " << message << endl;
}
// функция для добавления нового пользователя
void add_new_user(vector<User>& users, set<int>& used_ids, set<string>& used_ips, int my_id) {
User user;
user.id = generate_id(used_ids);
cout << "ID user: " << user.id << endl;
cout << "Enter username: ";
cin >> user.name;
user.masked_ip = generate_masked_ip(used_ips);
while (true) {
cout << "Enter user port: ";
cin >> user.port;
if (is_port_correct(user.port)) {
break;
}
else {
cout << "Incorrect port.Please try again." << endl;
}
}
if (user.id == my_id) {
cout << "Do you want to add this user ? " << endl;
cout << "1.Yes" << endl;
cout << "2.No" << endl;
int choice;
cin >> choice;
if (choice == 1) {
users.push_back(user);
save_user_info(users);
cout << "User added successfully" << endl;
}
else {
cout << "User not added." << endl;
}
}
else {
users.push_back(user);
save_user_info(users);
cout << "User added successfully" << endl;
}
}
// главный метод программы
int main() {
vector<User> users;
set<int> used_ids;
set<string> used_ips;
int my_id = generate_id(used_ids);
cout << "Your id and port: " << my_id << " (" << find_user_by_id(users, my_id).port << ")" << endl;
load_user_info(users, used_ids, used_ips);
int choice;
cout << "1.Find user by id" << endl;
cout << "2.Add new user" << endl;
cout << "3.Send message" << endl;
cout << "Your choice: ";
cin >> choice;
try {
if (choice == 1) {
int id;
cout << "Enter user id: ";
cin >> id;
User found_user = find_user_by_id(users, id);
if (found_user.id == -1) {
cout << "User with this id was not found" << endl;
}
else {
cout << "User found: " << endl;
cout << "ID: " << found_user.id << endl;
cout << "Name: " << found_user.name << endl;
cout << "IP: " << found_user.masked_ip << endl;
cout << "Port: " << found_user.port << endl;
}
}
else if (choice == 2) {
add_new_user(users, used_ids, used_ips, my_id);
}
else if (choice == 3) {
string message, recipient_name;
cout << "Enter message: ";
cin.ignore();
getline(cin, message);
vector<string> friends;
for (const User& user : users) {
if (user.id != my_id) {
friends.push_back(user.name);
}
}
if (friends.empty()) {
cout << "You don’t have friends to send message to." << endl;
}
else {
cout << "Select a friend to send message to: " << endl;
for (size_t i = 0; i < friends.size(); i++) {
cout << i + 1 << ". " << friends[i] << endl;
}
int friend_choice;
cin >> friend_choice;
if (friend_choice > 0 && friend_choice <= friends.size()) {
User recipient = find_user_by_name(users, friends[friend_choice - 1]);
send_message(users, my_id, recipient.masked_ip, message);
}
else {
throw invalid_argument("Invalid friend choice: " + to_string(friend_choice));
}
}
}
else {
throw invalid_argument("Invalid choice: " + to_string(choice));
}
}
catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
exit(1);
}
return 0;
}
User find_user_by_masked_ip(const vector<User>& users, const string& masked_ip);
User find_user_by_masked_ip(const vector<User>& users, const string& masked_ip)
{
for (const User& user : users) {
if (user.masked_ip == masked_ip) {
return user;
}
}
User user;
user.id = -1;
return user;
}
|
4cef0a0871888e377aa9859d7d91e338
|
{
"intermediate": 0.3293613791465759,
"beginner": 0.5028054118156433,
"expert": 0.16783320903778076
}
|
10,804
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
try:
markets = binance_futures.fetch_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
leverage = '100x'
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"type": "MARKET" if signal == "buy" else "MARKET",
"side": "BUY" if signal == "buy" else "SELL",
"amount": quantity,
"price": price,
"params": {
"leverage": leverage
}
}
try:
order_params['symbol'] = symbol
response = binance_futures.create_order(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: The signal time is: 2023-06-07 18:18:02 :sell
Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 560, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/order
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 257, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 243, in order_execution
response = binance_futures.create_order(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 4215, in create_order
response = getattr(self, method)(self.extend(request, requestParams))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7409, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2819, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 576, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7386, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3169, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.InvalidOrder: binance {"code":-2027,"msg":"Exceeded the maximum allowable position at current leverage."} , please if it possible give me right code
|
473cb8953b22bd5f53c058b0311fd5f1
|
{
"intermediate": 0.3322139382362366,
"beginner": 0.45794159173965454,
"expert": 0.20984448492527008
}
|
10,805
|
The script listens for user input from the keyboard and loops through each animation in the animations table. If the key code matches the current animation index i, the script checks if the cooldown time has elapsed since the last time that animation was played. If so, it fires the corresponding server event and updates the last animation time in lastAnimationTimes.
This implementation is more scalable since you can add or remove animations simply by modifying the animations table, without needing to modify the script logic for each animation individually.
This script listens for user input from the keyboard
– and fires server events for different animations
– with specified cooldown times.
– Define the animations and their cooldown times and server events
local animations = {
{cooldown = 25/60, event = AnimationEvent1},
{cooldown = 30/60, event = AnimationEvent2},
{cooldown = 20/60, event = AnimationEvent3},
– add more animations here as needed
}
– Create a table to store the last time each animation was played
local lastAnimationTimes = {}
– Listen for user input and fire the corresponding animation server events
UIS.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.Keyboard then
– Loop through each animation defined in the animations table
for i, animation in ipairs(animations) do
– Check if the input keycode matches the current animation index i
if input.KeyCode == Enum.KeyCode[i] then
– Get the current time
local currentTime = os.clock()
– Check if the cooldown has elapsed since the last time the animation was played
if not lastAnimationTimes[i] or currentTime - lastAnimationTimes[i] >= animation.cooldown then
– Fire the corresponding server event for the animation
animation.event:FireServer()
– Update the last animation time in the lastAnimationTimes table
lastAnimationTimes[i] = currentTime
end
end
end
end
end)
|
879d362a553048aaa9838a83b6f2ae21
|
{
"intermediate": 0.4071163535118103,
"beginner": 0.2840273976325989,
"expert": 0.3088562488555908
}
|
10,806
|
Correct this code for prediction of upcoming 5 days (Give exact predicted value with plot):
Error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-94-936b4947ed80> in <cell line: 5>()
8 predictions.append(next_day_pred[0, 0])
9
---> 10 new_row = np.column_stack((next_day_input[0, 1:, :], next_day_pred)) # Create a new row with the predicted value
11 X_test = np.append(X_test, [new_row], axis=0) # Append the new row to X_test
12
2 frames
/usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 38 and the array at index 1 has size 1
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data[‘h-l’] = data[‘high’] - data[‘low’]
data[‘h-pc’] = abs(data[‘high’] - data[‘close’].shift(1))
data[‘l-pc’] = abs(data[‘low’] - data[‘close’].shift(1))
data[‘tr’] = data[[‘h-l’, ‘h-pc’, ‘l-pc’]].max(axis=1)
data[‘atr’] = data[‘tr’].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data[‘Upper Basic’] = (data[‘high’] + data[‘low’]) / 2 + multiplier * data[‘atr’]
data[‘Lower Basic’] = (data[‘high’] + data[‘low’]) / 2 - multiplier * data[‘atr’]
data[‘Upper Band’] = data.apply(lambda x: x[‘Upper Basic’] if x[‘close’] > x[‘Upper Basic’] else x[‘Lower Basic’], axis=1)
data[‘Lower Band’] = data.apply(lambda x: x[‘Lower Basic’] if x[‘close’] < x[‘Lower Basic’] else x[‘Upper Basic’], axis=1)
data[‘Super Trend’] = np.where(data[‘close’] > data[‘Upper Band’], data[‘Lower Band’], data[‘Upper Band’])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
print(“Original columns:”, stock_data.columns) # <-- Add this line
stock_data.columns = [col.lower() for col in stock_data.columns]
print(“Lowercase columns:”, stock_data.columns) # <-- Add this line
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[[‘open’, ‘high’, ‘low’, ‘close’, ‘Super Trend’]].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50, return_sequences=True))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer=‘adam’, loss=‘mean_squared_error’)
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label=‘Actual’)
plt.plot(y_pred_inverse, label=‘Predicted’)
plt.xlabel(‘Days’)
plt.ylabel(‘Close Price’)
plt.title(‘Stock Price Prediction (Actual vs Predicted)’)
plt.legend()
plt.show()
# Define the parameters
ticker = ‘^NSEI’ # Ticker symbol for Nifty
start_date = ‘2010-01-01’
end_date = ‘2023-06-01’
window_size = 60 # Number of previous days’ data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
# Load and preprocess the data
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
# Evaluate the model
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1)) # Fit scaler on training labels
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}“)
print(f"Mean Squared Error: {mse}”)
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
# Predict the closing price for the upcoming 5 days and plot them
upcoming_days = 5
predictions = []
for i in range(upcoming_days):
next_day_input = np.array([X_test[-1, 1:, :]]) # Use the last window data from X_test and exclude the first element
next_day_pred = model.predict(next_day_input)
predictions.append(next_day_pred[0, 0])
new_row = np.column_stack((next_day_input[0, 1:, :], next_day_pred)) # Create a new row with the predicted value
X_test = np.append(X_test, [new_row], axis=0) # Append the new row to X_test
predictions = np.array(predictions).reshape(-1, 1)
predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1] # Inverse transform for Close prices
# Plot the upcoming 5 days predictions
plt.figure(figsize=(14, 6))
plt.plot(predictions_inverse, marker=“o”, label=‘Predicted’)
plt.xlabel(‘Days’)
plt.ylabel(‘Close Price’)
plt.title(‘NIFTY Stock Price Prediction for Upcoming 5 Days’)
plt.legend()
plt.show()
|
d1bf6887590c87a6fdd83871b26d670f
|
{
"intermediate": 0.43535086512565613,
"beginner": 0.28919950127601624,
"expert": 0.27544963359832764
}
|
10,807
|
Correct this code for prediction of upcoming 5 days (Give exact predicted value with plot):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data[‘h-l’] = data[‘high’] - data[‘low’]
data[‘h-pc’] = abs(data[‘high’] - data[‘close’].shift(1))
data[‘l-pc’] = abs(data[‘low’] - data[‘close’].shift(1))
data[‘tr’] = data[[‘h-l’, ‘h-pc’, ‘l-pc’]].max(axis=1)
data[‘atr’] = data[‘tr’].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data[‘Upper Basic’] = (data[‘high’] + data[‘low’]) / 2 + multiplier * data[‘atr’]
data[‘Lower Basic’] = (data[‘high’] + data[‘low’]) / 2 - multiplier * data[‘atr’]
data[‘Upper Band’] = data.apply(lambda x: x[‘Upper Basic’] if x[‘close’] > x[‘Upper Basic’] else x[‘Lower Basic’], axis=1)
data[‘Lower Band’] = data.apply(lambda x: x[‘Lower Basic’] if x[‘close’] < x[‘Lower Basic’] else x[‘Upper Basic’], axis=1)
data[‘Super Trend’] = np.where(data[‘close’] > data[‘Upper Band’], data[‘Lower Band’], data[‘Upper Band’])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
print(“Original columns:”, stock_data.columns) # <-- Add this line
stock_data.columns = [col.lower() for col in stock_data.columns]
print(“Lowercase columns:”, stock_data.columns) # <-- Add this line
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[[‘open’, ‘high’, ‘low’, ‘close’, ‘Super Trend’]].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50, return_sequences=True))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer=‘adam’, loss=‘mean_squared_error’)
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label=‘Actual’)
plt.plot(y_pred_inverse, label=‘Predicted’)
plt.xlabel(‘Days’)
plt.ylabel(‘Close Price’)
plt.title(‘Stock Price Prediction (Actual vs Predicted)’)
plt.legend()
plt.show()
# Define the parameters
ticker = ‘^NSEI’ # Ticker symbol for Nifty
start_date = ‘2010-01-01’
end_date = ‘2023-06-01’
window_size = 60 # Number of previous days’ data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
# Load and preprocess the data
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
# Evaluate the model
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1)) # Fit scaler on training labels
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}“)
print(f"Mean Squared Error: {mse}”)
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
# Predict the closing price for the upcoming 5 days and plot them
upcoming_days = 5
predictions = []
for i in range(upcoming_days):
next_day_input = np.array([X_test[-1, 1:, :]]) # Use the last window data from X_test and exclude the first element
next_day_pred = model.predict(next_day_input)
predictions.append(next_day_pred[0, 0])
new_row = np.column_stack((next_day_input[0, 1:, :], next_day_pred)) # Create a new row with the predicted value
X_test = np.append(X_test, [new_row], axis=0) # Append the new row to X_test
predictions = np.array(predictions).reshape(-1, 1)
predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1] # Inverse transform for Close prices
# Plot the upcoming 5 days predictions
plt.figure(figsize=(14, 6))
plt.plot(predictions_inverse, marker=“o”, label=‘Predicted’)
plt.xlabel(‘Days’)
plt.ylabel(‘Close Price’)
plt.title(‘NIFTY Stock Price Prediction for Upcoming 5 Days’)
plt.legend()
plt.show()
|
a5aa13b3f99abb482e480cba2b0eb10a
|
{
"intermediate": 0.38792890310287476,
"beginner": 0.3884757459163666,
"expert": 0.22359538078308105
}
|
10,808
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
try:
markets = binance_futures.fetch_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
leverage = '100x'
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"symbol":"symbol",
"type": "MARKET",
"side": "BUY" if signal == "buy" else "SELL",
"amount": "quantity"
}
try:
order_params['symbol'] = symbol
response = binance_futures.create_order(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: BTC/USDT not found in the market
The signal time is: 2023-06-07 19:49:40 :buy
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 254, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 240, in order_execution
response = binance_futures.create_order(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 4192, in create_order
request['quantity'] = self.amount_to_precision(symbol, amount)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3364, in amount_to_precision
result = self.decimal_to_precision(amount, TRUNCATE, market['precision']['amount'], self.precisionMode, self.paddingMode) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\decimal_to_precision.py", line 58, in decimal_to_precision
dec = decimal.Decimal(str(n))
^^^^^^^^^^^^^^^^^^^^^^^
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
|
b64e1a52fc97bdd4f5266c6d57e60060
|
{
"intermediate": 0.3322139382362366,
"beginner": 0.45794159173965454,
"expert": 0.20984448492527008
}
|
10,809
|
I have this code and I want to be able run this with multiple users at the same time, so they files should’ve mixed in the server.
def referral(update, context):
if not is_allowed_user(update.message.from_user.id):
return
update.message.reply_text('Please enter the referral ID:')
return GET_REFID
def get_refid(update, context):
if update.message.text.lower() == "/cancel":
return cancel(update, context)
refid = update.message.text
# Load referral IDs from the JSON file
with open("referrals.json", "r") as f:
referrals = json.load(f)
if refid in referrals:
context.user_data['refid'] = refid
update.message.reply_text('referral ID saved. Now, please enter the company name (without space):')
return GET_CONAME
else:
update.message.reply_text('Invalid referral ID. Please enter a valid referral ID:')
return GET_REFID
def get_coname(update, context):
refid = context.user_data['refid']
if update.message.text.lower() == "/cancel":
return cancel(update, context)
coname = update.message.text
context.user_data['coname'] = coname
update.message.reply_text("Please wait, I'm processing…")
for zip_file, tar_ext in zip(ZIP_FILES, TAR_EXTENSIONS):
# Extract ZIP file
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
zip_ref.extractall()
# Rename binary
os.rename('braiins-toolbox', f'braiins_toolbox_{refid}')
# Add executable permission
os.chmod(f'braiins_toolbox_{refid}', os.stat(f'braiins_toolbox_{refid}').st_mode | stat.S_IEXEC)
# Compress with TAR
output_file = f'braiins_toolbox_{tar_ext}_{coname}.tar.gz'
with tarfile.open(output_file, 'w:gz') as tar:
tar.add(f'braiins_toolbox_{refid}', arcname=f'braiins_toolbox_{refid}', filter=lambda tarinfo: tarinfo)
# Cleanup - only remove the file if it exists
if os.path.isfile(f'braiins_toolbox_{refid}'):
os.remove(f'braiins_toolbox_{refid}')
# Send the file to the user
message_text = f'\n"{coname}" \n"{refid}"'
with open(output_file, 'rb') as f:
context.bot.send_document(
chat_id=update.effective_chat.id,
document=InputFile(f),
filename=output_file,
caption=message_text,
)
os.remove(output_file)
final_message = f'''
==============
Company Name: **{coname}**
referral ID: `{refid}`
Remote Installation on [Beaglebone/Amlogic]:
Download the proper braiins-toolbox from the files above and run the command below.
(please note the suffix of toolbox name should be your referral ID):
`./braiins_toolbox_{refid} firmware install --ip-file list.txt`
If you want to use old toolbox you can download it with your referral ID here:
○ [Windows Version](https://feeds.braiins-os.com/toolbox/latest/bos-toolbox_{refid}.zip)
○ [Linux Version](https://feeds.braiins-os.com/toolbox/latest/bos-toolbox_{refid})
`./bos-toolbox_{refid} update list.csv bos-referral`
**SD Images:**
○ [Antminer X19 (Beaglebone) SD](https://referral.braiins-os.com/{refid}/sd-images/braiins-os_am3-bbb_latest.img)
○ [Antminer X19 (Zynq) SD](https://referral.braiins-os.com/{refid}/sd-images/braiins-os_am2-s17_sd_latest.img)
==============
'''
update.message.reply_text(final_message, parse_mode='Markdown')
update.message.reply_text('⚠️ Hide sender’s name! when you want to forward the messages')
return ConversationHandler.END
add user chat id in the path to manage this
|
3a9615ac70ff294520e35f201c8a43d6
|
{
"intermediate": 0.38087403774261475,
"beginner": 0.44228395819664,
"expert": 0.17684195935726166
}
|
10,810
|
To adjust the “AnimationEvent” script to work with the multiple animations and input script that we have created, you would need to modify it to accept a parameter that determines which animation to play.
Here’s an example of how you can modify the “AnimationEvent” script to work with the input script we created earlier:
local AnimationEvent = game.ReplicatedStorage.AnimationEvent
local Animations = {
[1] = {“rbxassetid://ANIMATION1_ID”, “Animation1”},
[2] = {“rbxassetid://ANIMATION2_ID”, “Animation2”},
– add more animations as needed
}
AnimationEvent.OnServerEvent:Connect(function(plr, animationIndex)
game.Workspace:WaitForChild(plr.Name)
local Character = game.Workspace:FindFirstChild(plr.Name)
local Humanoid = Character.Humanoid
local Animation = Instance.new(“Animation”)
Animation.AnimationId = Animations[animationIndex][1]
local AnimationTrack = Humanoid:LoadAnimation(Animation)
AnimationTrack:Play()
– You can print a message to the console to verify that the correct animation was played
print("Played " … Animations[animationIndex
|
709fb296eded6881124ac2f73e6b682b
|
{
"intermediate": 0.42298001050949097,
"beginner": 0.3184637427330017,
"expert": 0.25855621695518494
}
|
10,811
|
this is my code:df = df.to_excel('data/Ludovico Einaudi.xlsx', encoding='UTF-8', sheet_name='track', index_label='id')
df and its error: C:\Users\user\anaconda3\lib\site-packages\pandas\util\_decorators.py:211: FutureWarning: the 'encoding' keyword is deprecated and will be removed in a future version. Please take steps to stop the use of 'encoding'
return func(*args, **kwargs)
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
Cell In[12], line 1
----> 1 df = df.to_excel('data/Ludovico Einaudi.xlsx', encoding='UTF-8', sheet_name='track', index_label='id')
2 df
File ~\anaconda3\lib\site-packages\pandas\util\_decorators.py:211, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper(*args, **kwargs)
209 else:
210 kwargs[new_arg_name] = new_arg_value
--> 211 return func(*args, **kwargs)
File ~\anaconda3\lib\site-packages\pandas\util\_decorators.py:183, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper(*args, **kwargs)
181 warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
182 kwargs[old_arg_name] = old_arg_value
--> 183 return func(*args, **kwargs)
185 elif mapping is not None:
186 if callable(mapping):
File ~\anaconda3\lib\site-packages\pandas\core\generic.py:2374, in NDFrame.to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep, verbose, freeze_panes, storage_options)
2361 from pandas.io.formats.excel import ExcelFormatter
2363 formatter = ExcelFormatter(
2364 df,
2365 na_rep=na_rep,
(...)
2372 inf_rep=inf_rep,
2373 )
-> 2374 formatter.write(
2375 excel_writer,
2376 sheet_name=sheet_name,
2377 startrow=startrow,
2378 startcol=startcol,
2379 freeze_panes=freeze_panes,
2380 engine=engine,
2381 storage_options=storage_options,
2382 )
File ~\anaconda3\lib\site-packages\pandas\io\formats\excel.py:944, in ExcelFormatter.write(self, writer, sheet_name, startrow, startcol, freeze_panes, engine, storage_options)
940 need_save = False
941 else:
942 # error: Cannot instantiate abstract class 'ExcelWriter' with abstract
943 # attributes 'engine', 'save', 'supported_extensions' and 'write_cells'
--> 944 writer = ExcelWriter( # type: ignore[abstract]
945 writer, engine=engine, storage_options=storage_options
946 )
947 need_save = True
949 try:
File ~\anaconda3\lib\site-packages\pandas\io\excel\_openpyxl.py:60, in OpenpyxlWriter.__init__(self, path, engine, date_format, datetime_format, mode, storage_options, if_sheet_exists, engine_kwargs, **kwargs)
56 from openpyxl.workbook import Workbook
58 engine_kwargs = combine_kwargs(engine_kwargs, kwargs)
---> 60 super().__init__(
61 path,
62 mode=mode,
63 storage_options=storage_options,
64 if_sheet_exists=if_sheet_exists,
65 engine_kwargs=engine_kwargs,
66 )
68 # ExcelWriter replaced "a" by "r+" to allow us to first read the excel file from
69 # the file and later write to it
70 if "r+" in self._mode: # Load from existing workbook
File ~\anaconda3\lib\site-packages\pandas\io\excel\_base.py:1313, in ExcelWriter.__init__(self, path, engine, date_format, datetime_format, mode, storage_options, if_sheet_exists, engine_kwargs, **kwargs)
1309 self._handles = IOHandles(
1310 cast(IO[bytes], path), compression={"compression": None}
1311 )
1312 if not isinstance(path, ExcelWriter):
-> 1313 self._handles = get_handle(
1314 path, mode, storage_options=storage_options, is_text=False
1315 )
1316 self._cur_sheet = None
1318 if date_format is None:
File ~\anaconda3\lib\site-packages\pandas\io\common.py:734, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
732 # Only for write methods
733 if "r" not in mode and is_path:
--> 734 check_parent_directory(str(handle))
736 if compression:
737 if compression != "zstd":
738 # compression libraries do not like an explicit text-mode
File ~\anaconda3\lib\site-packages\pandas\io\common.py:597, in check_parent_directory(path)
595 parent = Path(path).parent
596 if not parent.is_dir():
--> 597 raise OSError(rf"Cannot save file into a non-existent directory: '{parent}'")
OSError: Cannot save file into a non-existent directory: 'data' please fix it
|
a56c82385cff05564443b81787500202
|
{
"intermediate": 0.395429790019989,
"beginner": 0.4756750762462616,
"expert": 0.12889517843723297
}
|
10,812
|
How to overcome this error in the code:
Error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-118-8825bf5b363f> in <cell line: 4>()
11
12 new_row = np.concatenate((next_day_input[0, 1:, :], next_day_extended), axis=0)
---> 13 X_test = np.append(X_test, [new_row], axis=0)
14
15 predictions = np.array(predictions).reshape(-1, 1)
2 frames
/usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 40 and the array at index 1 has size 39
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['h-l'] = data['high'] - data['low']
data['h-pc'] = abs(data['high'] - data['close'].shift(1))
data['l-pc'] = abs(data['low'] - data['close'].shift(1))
data['tr'] = data[['h-l', 'h-pc', 'l-pc']].max(axis=1)
data['atr'] = data['tr'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['high'] + data['low']) / 2 + multiplier * data['atr']
data['Lower Basic'] = (data['high'] + data['low']) / 2 - multiplier * data['atr']
data['Upper Band'] = data.apply(lambda x: x['Upper Basic'] if x['close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data.apply(lambda x: x['Lower Basic'] if x['close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.where(data['close'] > data['Upper Band'], data['Lower Band'], data['Upper Band'])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
print("Original columns:", stock_data.columns)
stock_data.columns = [col.lower() for col in stock_data.columns]
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['open', 'high', 'low', 'close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50, return_sequences=True))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label='Actual')
plt.plot(y_pred_inverse, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('Stock Price Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Define the parameters
ticker = '^NSEI' # Ticker symbol for Nifty
start_date = '2010-01-01'
end_date = '2023-06-01'
window_size = 40 # Number of previous days' data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1))
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}")
print(f"Mean Squared Error: {mse}")
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
upcoming_days = 5
predictions = []
for i in range(upcoming_days):
next_day_input = np.array([X_test[-1, 1:, :]])
next_day_pred = model.predict(next_day_input)
predictions.append(next_day_pred[0, 0])
next_day_extended = np.zeros((1, next_day_input.shape[2]))
next_day_extended[:, 3] = next_day_pred.T
new_row = np.concatenate((next_day_input[0, 1:, :], next_day_extended), axis=0)
X_test = np.append(X_test, [new_row], axis=0)
predictions = np.array(predictions).reshape(-1, 1)
predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1] # Inverse transform for Close prices
plt.figure(figsize=(14, 6))
plt.plot(predictions_inverse, marker="o", label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('NIFTY Stock Price Prediction for Upcoming 5 Days')
plt.legend()
plt.show()
|
38ba7e20d41b9c04f7c6d0eccc9368a9
|
{
"intermediate": 0.4724857807159424,
"beginner": 0.33074653148651123,
"expert": 0.19676770269870758
}
|
10,813
|
Create a script for a Kahoot game that predicts the next round's answer. The game has 4 boxes, each represented by a number: 1, 2, 3, and 4. I want the script to predict the color of the next round based on the previous round's data. The colors are Red (1), Blue (2), Yellow (3), and Green (4). The script should ask for the previous round's correct box number and predict the next round's color. Use machine learning to make the predictions. Every time it has made a prediction, it has to ask for the right answer, to then predict again using that data, so it keeps getting more and more data for better predictions. It also needs to say the most common color
|
b2c7882248b546dc2a365ca807710381
|
{
"intermediate": 0.24219182133674622,
"beginner": 0.1115756407380104,
"expert": 0.646232545375824
}
|
10,814
|
Please correct this code for prediction of next 5 days of stock market (You can also modify this code if it is incorrect):
Error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-124-5bae83635272> in <cell line: 3>()
1 # Define the number of days to predict and call the function
2 next_days = 5
----> 3 predictions = predict_next_days(model, X_test, scaler, next_days)
4
5 # Plot the predictions
3 frames
/usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 40 and the array at index 1 has size 39
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['h-l'] = data['high'] - data['low']
data['h-pc'] = abs(data['high'] - data['close'].shift(1))
data['l-pc'] = abs(data['low'] - data['close'].shift(1))
data['tr'] = data[['h-l', 'h-pc', 'l-pc']].max(axis=1)
data['atr'] = data['tr'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['high'] + data['low']) / 2 + multiplier * data['atr']
data['Lower Basic'] = (data['high'] + data['low']) / 2 - multiplier * data['atr']
data['Upper Band'] = data.apply(lambda x: x['Upper Basic'] if x['close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data.apply(lambda x: x['Lower Basic'] if x['close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.where(data['close'] > data['Upper Band'], data['Lower Band'], data['Upper Band'])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
print("Original columns:", stock_data.columns)
stock_data.columns = [col.lower() for col in stock_data.columns]
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['open', 'high', 'low', 'close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50, return_sequences=True))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label='Actual')
plt.plot(y_pred_inverse, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('Stock Price Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Define the parameters
ticker = '^NSEI' # Ticker symbol for Nifty
start_date = '2010-01-01'
end_date = '2023-06-01'
window_size = 40 # Number of previous days' data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1))
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}")
print(f"Mean Squared Error: {mse}")
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
def predict_next_days(model, X_test, scaler, next_days):
predictions = []
for i in range(next_days):
next_day_input = np.array([X_test[-1, 1:, :]])
next_day_pred = model.predict(next_day_input)
predictions.append(next_day_pred[0, 0])
next_day_extended = np.zeros((1, next_day_input.shape[2]))
next_day_extended[:, :3] = next_day_input[0, -1, :3]
next_day_extended[:, 3] = next_day_pred
next_day_extended[:, 4] = next_day_input[0, -1, 4]
new_row = np.concatenate((next_day_input[0, 1:, :], next_day_extended), axis=0)
X_test = np.append(X_test, [new_row], axis=0)
predictions = np.array(predictions).reshape(-1, 1)
predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1]
return predictions_inverse
# Define the number of days to predict and call the function
next_days = 5
predictions = predict_next_days(model, X_test, scaler, next_days)
# Plot the predictions
plt.figure(figsize=(14, 6))
plt.plot(predictions, marker="o", label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title(f'{ticker} Stock Price Prediction for Upcoming {next_days} Days')
plt.legend()
plt.show()
|
a39d676114085157c9eff506dada0905
|
{
"intermediate": 0.5341731905937195,
"beginner": 0.27762922644615173,
"expert": 0.1881975680589676
}
|
10,815
|
Hi there
|
5041b16c45ef009df7dae4345bfcb26a
|
{
"intermediate": 0.32728445529937744,
"beginner": 0.24503648281097412,
"expert": 0.42767903208732605
}
|
10,816
|
How to overcome this error in the code:
Error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-126-5bae83635272> in <cell line: 3>()
1 # Define the number of days to predict and call the function
2 next_days = 5
----> 3 predictions = predict_next_days(model, X_test, scaler, next_days)
4
5 # Plot the predictions
1 frames
/usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in concatenate(*args, **kwargs)
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 3 dimension(s)
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['h-l'] = data['high'] - data['low']
data['h-pc'] = abs(data['high'] - data['close'].shift(1))
data['l-pc'] = abs(data['low'] - data['close'].shift(1))
data['tr'] = data[['h-l', 'h-pc', 'l-pc']].max(axis=1)
data['atr'] = data['tr'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['high'] + data['low']) / 2 + multiplier * data['atr']
data['Lower Basic'] = (data['high'] + data['low']) / 2 - multiplier * data['atr']
data['Upper Band'] = data.apply(lambda x: x['Upper Basic'] if x['close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data.apply(lambda x: x['Lower Basic'] if x['close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.where(data['close'] > data['Upper Band'], data['Lower Band'], data['Upper Band'])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
print("Original columns:", stock_data.columns)
stock_data.columns = [col.lower() for col in stock_data.columns]
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['open', 'high', 'low', 'close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50, return_sequences=True))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label='Actual')
plt.plot(y_pred_inverse, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('Stock Price Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Define the parameters
ticker = '^NSEI' # Ticker symbol for Nifty
start_date = '2010-01-01'
end_date = '2023-06-01'
window_size = 40 # Number of previous days' data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1))
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}")
print(f"Mean Squared Error: {mse}")
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
def predict_next_days(model, X_test, scaler, next_days):
predictions = []
for i in range(next_days):
next_day_input = np.array([X_test[-1, 1:, :]])
next_day_pred = model.predict(next_day_input)
predictions.append(next_day_pred[0, 0])
next_day_extended = np.zeros((1, 1, X_test.shape[2]))
next_day_extended[0, 0, :3] = X_test[-1, -1, :3]
next_day_extended[0, 0, 3] = next_day_pred
next_day_extended[0, 0, 4] = X_test[-1, -1, 4]
new_row = np.concatenate((X_test[-1, 1:, :], next_day_extended), axis=1)
X_test = np.append(X_test, [new_row], axis=0)
predictions = np.array(predictions).reshape(-1, 1)
predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1]
return predictions_inverse
# Define the number of days to predict and call the function
next_days = 5
predictions = predict_next_days(model, X_test, scaler, next_days)
# Plot the predictions
plt.figure(figsize=(14, 6))
plt.plot(predictions, marker="o", label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title(f'{ticker} Stock Price Prediction for Upcoming {next_days} Days')
plt.legend()
plt.show()
|
636c5834084d2b17ed5fbe72131544eb
|
{
"intermediate": 0.46370527148246765,
"beginner": 0.34145641326904297,
"expert": 0.19483830034732819
}
|
10,817
|
В этот код хочу добавить свой объект в формате gltf . как это сделать?
код:
setMesh() {
const geometry = new THREE.BufferGeometry();
const firstPos = this.getGeometryPosition(new THREE.SphereBufferGeometry(1, 32, 32).toNonIndexed());
const secPos = this.getGeometryPosition(new THREE.TorusBufferGeometry(0.7, 0.3, 32, 32).toNonIndexed());
const thirdPos = this.getGeometryPosition(new THREE.TorusKnotBufferGeometry(0.6, 0.25, 300, 20, 6, 10).toNonIndexed());
const forthPos = this.getGeometryPosition(new THREE.CylinderBufferGeometry(1, 1, 1, 32, 32).toNonIndexed());
const fivePos = this.getGeometryPosition(new THREE.IcosahedronBufferGeometry(1.1, 0).toNonIndexed());
const material = new THREE.RawShaderMaterial({
vertexShader: `
attribute vec3 position;
attribute vec3 secPosition;
attribute vec3 thirdPosition;
attribute vec3 forthPosition;
attribute vec3 fivePosition;
uniform float u_sec1;
uniform float u_sec2;
uniform float u_sec3;
uniform float u_sec4;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
void main() {
vec3 toTorus = mix(position, secPosition, u_sec1);
vec3 toTorusKnot = mix(toTorus, thirdPosition, u_sec2);
vec3 toCylinder = mix(toTorusKnot, forthPosition, u_sec3);
vec3 finalPos = mix(toCylinder, fivePosition, u_sec4);
gl_Position = projectionMatrix * modelViewMatrix * vec4(finalPos, 1.0 );
gl_PointSize = 3.0;
}`,
fragmentShader: `
precision mediump float;
void main() {
vec2 temp = gl_PointCoord - vec2(0.5);
float f = dot(temp, temp);
if (f > 0.25 ) {
discard;
}
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}`,
uniforms: {
u_sec1: { type: "f", value: 0.0 },
u_sec2: { type: "f", value: 0.0 },
},
transparent: true,
blending: THREE.AdditiveBlending,
});
geometry.setAttribute("position", new THREE.BufferAttribute(firstPos, 3));
geometry.setAttribute("secPosition", new THREE.BufferAttribute(secPos, 3));
geometry.setAttribute("thirdPosition", new THREE.BufferAttribute(thirdPos, 3));
geometry.setAttribute("forthPosition", new THREE.BufferAttribute(forthPos, 3));
geometry.setAttribute("fivePosition",new THREE.BufferAttribute(fivePos, 3));
this.mesh = new THREE.Points(geometry, material);
this.group = new THREE.Group();
this.group.add(this.mesh);
this.stage.scene.add(this.group);
}
|
4d1a1eaceb10f3e4a5f74405fe01c158
|
{
"intermediate": 0.259650856256485,
"beginner": 0.47092577815055847,
"expert": 0.26942336559295654
}
|
10,818
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0})
max_trade_size = float(usdt_balance.get("balance", 0)) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
try:
markets = binance_futures.fetch_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
leverage = '100x'
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_type = {
"symbol":"symbol",
"type": "MARKET",
"side": "BUY" if signal == "buy" else "SELL",
"amount": "quantity"
}
try:
order_type['symbol'] = symbol
response = binance_futures.create_order(**order_type)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR:06/07/2023 22:18:26
BTC/USDT not found in the market
The signal time is: 2023-06-07 22:18:35 :buy
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 285, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 271, in order_execution
response = binance_futures.create_order(**order_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 4192, in create_order
request['quantity'] = self.amount_to_precision(symbol, amount)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3364, in amount_to_precision
result = self.decimal_to_precision(amount, TRUNCATE, market['precision']['amount'], self.precisionMode, self.paddingMode) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\decimal_to_precision.py", line 58, in decimal_to_precision
dec = decimal.Decimal(str(n))
^^^^^^^^^^^^^^^^^^^^^^^
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
|
008759b595903bb457f067d7e46dcf50
|
{
"intermediate": 0.34912174940109253,
"beginner": 0.45758527517318726,
"expert": 0.19329296052455902
}
|
10,819
|
Please modify this code for making prediction of next 5 days (use this code as starting point you can modify any function or make any new function):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['h-l'] = data['high'] - data['low']
data['h-pc'] = abs(data['high'] - data['close'].shift(1))
data['l-pc'] = abs(data['low'] - data['close'].shift(1))
data['tr'] = data[['h-l', 'h-pc', 'l-pc']].max(axis=1)
data['atr'] = data['tr'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['high'] + data['low']) / 2 + multiplier * data['atr']
data['Lower Basic'] = (data['high'] + data['low']) / 2 - multiplier * data['atr']
data['Upper Band'] = data.apply(lambda x: x['Upper Basic'] if x['close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data.apply(lambda x: x['Lower Basic'] if x['close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.where(data['close'] > data['Upper Band'], data['Lower Band'], data['Upper Band'])
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
print("Original columns:", stock_data.columns)
stock_data.columns = [col.lower() for col in stock_data.columns]
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['open', 'high', 'low', 'close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50, return_sequences=True))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label='Actual')
plt.plot(y_pred_inverse, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.title('Stock Price Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Define the parameters
ticker = '^NSEI' # Ticker symbol for Nifty
start_date = '2010-01-01'
end_date = '2023-06-01'
window_size = 40 # Number of previous days' data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1))
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}")
print(f"Mean Squared Error: {mse}")
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
|
d690b9e790f739c31efa368d85eb506e
|
{
"intermediate": 0.3566884398460388,
"beginner": 0.35542383790016174,
"expert": 0.28788766264915466
}
|
10,820
|
Can you generate a python code that can make prediction of future exams scores and modify itself
|
8942ba8c649840e061e2c751b6094852
|
{
"intermediate": 0.29378512501716614,
"beginner": 0.1363748461008072,
"expert": 0.5698400139808655
}
|
10,821
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0})
max_trade_size = float(usdt_balance.get("balance", 0)) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
try:
response = binance_futures.create_order(
symbol=symbol,
type=order_type,
side='BUY' if signal == 'buy' else 'SELL',
quantity=quantity,
positionSide=position_side,
price=price
)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: The signal time is: 2023-06-07 22:37:00 :
The signal time is: 2023-06-07 22:37:01 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 277, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 256, in order_execution
response = binance_futures.create_order(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: binance.create_order() got an unexpected keyword argument 'quantity'
|
d3e828109f85b973bca3f32f4da3adac
|
{
"intermediate": 0.3864240050315857,
"beginner": 0.44241565465927124,
"expert": 0.17116032540798187
}
|
10,822
|
if ($datos["id_tipo_pregunta"] == 6) {
$opciones = pg_Exec("SELECT * FROM {$_SESSION['ESQUEMA_BD']}.opciones WHERE id_pregunta={$datos['id_pregunta']} ORDER BY orden_opcion");
echo "<table class='table table-striped'>";
echo "<tbody>";
$optionIndex = 1;
$order = array(); // Initialize the $order array
while ($info = pg_fetch_array($opciones)) {
$optionId = $info['id_opcion']; // Option ID
$positionId = "position_$optionId"; // Generate a position ID for each option based on its ID
echo "<tr class='option-container' data-value='{$info['valor_opcion']}' draggable='true' ondragstart='dragStart(event)' ondragover='dragOver(event)' ondrop='drop(event)' data-index='$optionIndex'>";
echo "<td class='option-content'>";
echo "<span class='drag-icon'><i class='fas fa-arrows-alt'></i></span>";
echo "<div class='option'>{$info['nombre_opcion']}</div>";
echo "</td>";
echo "<td class='position' id='$positionId' data-position='$optionIndex'>$optionIndex</td>"; // Display the current position
echo "</tr>";
$order[$optionIndex] = array(
'id_opcion' => $optionId, // Option ID
'positionId' => $positionId, // Position ID
'position' => $optionIndex // Initial position
);
$optionIndex++;
}
echo "</tbody>";
echo "</table>";
// Fetch the existing response
$respuesta = pg_fetch_array(pg_Exec("SELECT valor_respuesta FROM {$_SESSION['ESQUEMA_BD']}.respuestas_empleados
WHERE id_encuesta=$id_encuesta AND cedula='$cedula' AND id_pregunta='{$datos['id_pregunta']}'"));
// Perform the calculation to determine the position of the dragged and dropped options
$draggedOption = isset($_POST['draggedOption']) ? $_POST['draggedOption'] : '';
$droppedOption = isset($_POST['droppedOption']) ? $_POST['droppedOption'] : '';
if ($draggedOption && $droppedOption) {
$draggedPosition = '';
$droppedPosition = '';
foreach ($order as $position => $option) {
if ($option['id_opcion'] == $draggedOption) {
$draggedPosition = $position;
} elseif ($option['id_opcion'] == $droppedOption) {
$droppedPosition = $position;
}
}
// Swap the positions of the dragged and dropped options in the $order array
$temp = $order[$draggedPosition];
$order[$draggedPosition] = $order[$droppedPosition];
$order[$droppedPosition] = $temp;
// Update the position values in the HTML table and data-position attribute
foreach ($order as $position => $option) {
$positionId = $option['positionId'];
echo "<script>document.getElementById('$positionId').textContent = $position;</script>";
echo "<script>document.getElementById('$positionId').setAttribute('data-position', $position);</script>";
}
// Update the valor_respuesta with the updated order
$orderString = implode(',', array_column($order, 'id_opcion'));
$respuesta['valor_respuesta'] = $orderString;
pg_query("UPDATE {$_SESSION['ESQUEMA_BD']}.respuestas_empleados SET valor_respuesta='{$respuesta['valor_respuesta']}'
WHERE id_encuesta=$id_encuesta AND cedula='$cedula' AND id_pregunta='{$datos['id_pregunta']}'");
}
// Display the valor_respuesta
echo "valor_respuesta: {$respuesta['valor_respuesta']}";
} i need to all the rows of options have a position id and if the position of the option change the position id changes too
|
20ed6fd957ce07c1c86146611c666484
|
{
"intermediate": 0.36696934700012207,
"beginner": 0.4439511299133301,
"expert": 0.18907959759235382
}
|
10,823
|
const Navbar = () => {
return (
<div className=“navbar”>
<div className=“navBarWrapper”>
<div className=“navLeft”>left</div>
<div className=“navRight”>right</div>
</div>
</div>
);
};
export default Navbar;
correct names of classes with BEM standard
|
776dc17e449a3ca222cec0b9ecb46ee6
|
{
"intermediate": 0.28282904624938965,
"beginner": 0.47961097955703735,
"expert": 0.23756003379821777
}
|
10,824
|
how to name classes with BEM methodology? Give multiple nested example
|
b5ab7666bd4ecb3e963e0e43d09730ee
|
{
"intermediate": 0.1921994984149933,
"beginner": 0.34834304451942444,
"expert": 0.4594574272632599
}
|
10,825
|
Write a factorial in C in the style of John Carmack.
|
2518161a5bf6b791b5acc4ae2322f547
|
{
"intermediate": 0.2206958830356598,
"beginner": 0.24882617592811584,
"expert": 0.5304779410362244
}
|
10,826
|
I need you to write a code for Manage.cshtml to display a list of "products" table coming from applicationdbcontext. we need to have a searchbar at the top of the page, what it does is that it removes any unmatching items with every charachter you type until you have a match. all this has to be done without reloading the page.
The entire page should be responsive with tailwindcss.
you can use this styling for the searchbar input: "<div class="mb-3">
<div class="relative mb-4 flex w-full flex-wrap items-stretch">
<input
type="search"
class="relative m-0 block w-[1px] min-w-0 flex-auto rounded border border-solid border-neutral-300 bg-transparent bg-clip-padding px-3 py-[0.25rem] text-base font-normal leading-[1.6] text-neutral-700 outline-none transition duration-200 ease-in-out focus:z-[3] focus:border-primary focus:text-neutral-700 focus:shadow-[inset_0_0_0_1px_rgb(59,113,202)] focus:outline-none dark:border-neutral-600 dark:text-neutral-200 dark:placeholder:text-neutral-200 dark:focus:border-primary"
placeholder="Search"
aria-label="Search"
aria-describedby="button-addon2" />
<!--Search icon-->
<span
class="input-group-text flex items-center whitespace-nowrap rounded px-3 py-1.5 text-center text-base font-normal text-neutral-700 dark:text-neutral-200"
id="basic-addon2">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="h-5 w-5">
<path
fill-rule="evenodd"
d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z"
clip-rule="evenodd" />
</svg>
</span>
</div>
</div>", and adjust the necessary.
|
e8d2ab599d76aaec609dba89592fd30e
|
{
"intermediate": 0.4608340263366699,
"beginner": 0.21604444086551666,
"expert": 0.323121577501297
}
|
10,827
|
обьясни работу кода
обьясни работу кода
обьясни работу кода
var request = require('request');
var cheerio = require('cheerio');
var queryString = require('querystring');
var flatten = require('lodash.flatten');
var baseURL = 'http://images.google.com/search?';
var imageFileExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'];
function gis(opts, done) {
var searchTerm;
var queryStringAddition;
var filterOutDomains = ['gstatic.com'];
if (typeof opts === 'string') {
searchTerm = opts;
} else {
searchTerm = opts.searchTerm;
queryStringAddition = opts.queryStringAddition;
filterOutDomains = filterOutDomains.concat(opts.filterOutDomains);
}
var url =
baseURL +
queryString.stringify({
tbm: 'isch',
q: searchTerm
});
if (filterOutDomains) {
url += encodeURIComponent(
' ' + filterOutDomains.map(addSiteExcludePrefix).join(' ')
);
}
if (queryStringAddition) {
url += queryStringAddition;
}
var reqOpts = {
url: url,
headers: {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}
};
// console.log(reqOpts.url);
request(reqOpts, parseGISResponse);
function parseGISResponse(error, response, body) {
if (error) {
done(error);
return;
}
var $ = cheerio.load(body);
var scripts = $('script');
var scriptContents = [];
for (var i = 0; i < scripts.length; ++i) {
if (scripts[i].children.length > 0) {
const content = scripts[i].children[0].data;
if (containsAnyImageFileExtension(content)) {
scriptContents.push(content);
}
}
}
done(error, flatten(scriptContents.map(collectImageRefs)));
function collectImageRefs(content) {
var refs = [];
var re = /\["(http.+?)",(\d+),(\d+)\]/g;
var result;
while ((result = re.exec(content)) !== null) {
if (result.length > 3) {
let ref = {
url: result[1],
width: +result[3],
height: +result[2]
};
if (domainIsOK(ref.url)) {
refs.push(ref);
}
}
}
return refs;
}
function domainIsOK(url) {
if (!filterOutDomains) {
return true;
} else {
return filterOutDomains.every(skipDomainIsNotInURL);
}
function skipDomainIsNotInURL(skipDomain) {
return url.indexOf(skipDomain) === -1;
}
}
}
}
function addSiteExcludePrefix(s) {
return '-site:' + s;
}
function containsAnyImageFileExtension(s) {
var lowercase = s.toLowerCase();
return imageFileExtensions.some(containsImageFileExtension);
function containsImageFileExtension(ext) {
return lowercase.includes(ext);
}
}
module.exports = gis;
|
735af859a44b1949dab118824ebf8029
|
{
"intermediate": 0.359440416097641,
"beginner": 0.5049818754196167,
"expert": 0.13557766377925873
}
|
10,828
|
hi, could you make a javascript code for my discord client that whenever someone pings me it automatically sends a message thats "hi"?
|
67607941d345b350c57c00c75490b948
|
{
"intermediate": 0.5286703109741211,
"beginner": 0.1820734292268753,
"expert": 0.2892562747001648
}
|
10,829
|
hi! could you make a code for my discord client console so whenever someone pings me i send a message in the same exact channel i was pinged in with the message "Hi"? the ping should just mention me, only me.
|
cfe2cadf35cb63ee38555426270a2444
|
{
"intermediate": 0.4243728220462799,
"beginner": 0.21658684313297272,
"expert": 0.35904034972190857
}
|
10,830
|
could you make an amazon price monitor?
|
ee0070dd287588041b1f41514be12163
|
{
"intermediate": 0.3114055097103119,
"beginner": 0.22203876078128815,
"expert": 0.46655574440956116
}
|
10,831
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
//VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, {0.0f, 0.0f} }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, {1.0f, 0.0f} }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, {1.0f, 1.0f} }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f }, {0.0f, 1.0f} }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth.spv", "C:/shaders/frag_depth.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->descriptorPool = descriptorPool;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
if (descriptorPool != VK_NULL_HANDLE) {
vkDestroyDescriptorPool(device, descriptorPool, nullptr);
descriptorPool = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
Mesh.h:
#pragma once
#include <vector>
#include <vulkan/vulkan.h>
#include <glm/glm.hpp>
#include "BufferUtils.h"
struct Vertex {
glm::vec3 position;
glm::vec3 color;
glm::vec2 texCoord;
};
class Mesh
{
public:
Mesh();
~Mesh();
void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
const std::vector<Vertex>& GetVertices() const;
const std::vector<uint32_t>& GetIndices() const;
VkBuffer GetVertexBuffer() const;
VkBuffer GetIndexBuffer() const;
void SetVertices(const std::vector<Vertex>& vertices);
void SetIndices(const std::vector<uint32_t>& indices);
std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const;
std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const;
private:
VkDevice device;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
};
Mesh.cpp:
#include "Mesh.h"
Mesh::Mesh()
: device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE)
{
}
Mesh::~Mesh()
{
Cleanup();
}
void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->vertices = vertices;
this->indices = indices;
this->device = device;
Initialize(device, physicalDevice, commandPool, graphicsQueue);
// Create vertex buffer and index buffer
// (assuming you have helper functions CreateBuffer and CopyBuffer)
// …
}
void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Create vertex buffer and index buffer
// (assuming you have helper functions CreateBuffer and CopyBuffer)
// …
// Declare and initialize stagingBuffer and bufferSize here
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size();
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
stagingBuffer, stagingBufferMemory);
void* data;
vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, vertices.data(), (size_t)bufferSize);
vkUnmapMemory(device, stagingBufferMemory);
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
vertexBuffer, vertexBufferMemory);
BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize);
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
bufferSize = sizeof(indices[0]) * indices.size();
VkBuffer stagingIndexBuffer;
VkDeviceMemory stagingIndexBufferMemory;
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
stagingIndexBuffer, stagingIndexBufferMemory);
vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, indices.data(), (size_t)bufferSize);
vkUnmapMemory(device, stagingIndexBufferMemory);
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
indexBuffer, indexBufferMemory);
BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize);
vkDestroyBuffer(device, stagingIndexBuffer, nullptr);
vkFreeMemory(device, stagingIndexBufferMemory, nullptr);
}
void Mesh::Cleanup()
{
if (device != VK_NULL_HANDLE)
{
if (vertexBuffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, vertexBuffer, nullptr);
vkFreeMemory(device, vertexBufferMemory, nullptr);
vertexBuffer = VK_NULL_HANDLE;
vertexBufferMemory = VK_NULL_HANDLE;
}
if (indexBuffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, indexBuffer, nullptr);
vkFreeMemory(device, indexBufferMemory, nullptr);
indexBuffer = VK_NULL_HANDLE;
indexBufferMemory = VK_NULL_HANDLE;
}
}
}
const std::vector<Vertex>& Mesh::GetVertices() const
{
return vertices;
}
const std::vector<uint32_t>& Mesh::GetIndices() const
{
return indices;
}
VkBuffer Mesh::GetVertexBuffer() const
{
return vertexBuffer;
}
VkBuffer Mesh::GetIndexBuffer() const
{
return indexBuffer;
}
void Mesh::SetVertices(const std::vector<Vertex>& vertices)
{
this->vertices = vertices;
}
void Mesh::SetIndices(const std::vector<uint32_t>& indices)
{
this->indices = indices;
}
std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const
{
std::vector<VkVertexInputBindingDescription> bindingDescriptions(1);
bindingDescriptions[0].binding = 0;
bindingDescriptions[0].stride = sizeof(Vertex);
bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescriptions;
}
std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const
{
std::vector<VkVertexInputAttributeDescription> attributeDescriptions(3);
// Position attribute
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, position);
// Color attribute
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, color);
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
return attributeDescriptions;
}
I want to convert the the geometry of squareTile from a tile to a cube. Can you modify the code to achieve this?
|
87ee2bdc5a782f28d608b072aa680248
|
{
"intermediate": 0.43474113941192627,
"beginner": 0.4049155116081238,
"expert": 0.16034337878227234
}
|
10,832
|
how to remove any outside css styiling in the my index.cshtml. in asp.net core mvc
|
969de94ff7ef82af5990b24c0f58b923
|
{
"intermediate": 0.379806786775589,
"beginner": 0.34373947978019714,
"expert": 0.2764537036418915
}
|
10,833
|
D ∙ Counting Pythagorean Triples
Time Limit: 2 seconds
Memory Limit: 128MB
A Pythagorean triple is a set of three positive integers, a, b and c, for which:
a² + b² = c²
A Pythagorean triple is a Primitive Pythagorean Triple (PPT) if a, b and c have no common factors.
Write a program which takes as input a positive integer, n, and outputs a count of:
1. The number of different PPTs in which n is the hypotenuse ( c ).
2. The number of non-primitive Pythagorean triples in which n is the hypotenuse ( c ).
3. The number of different PPTs in which n is one of the sides ( a or b ).
4. The number of non-primitive Pythagorean triples in which n is the one of the sides ( a or b ).
For the same a, b, c: b, a, c is the “same” as a, b, c (i.e it only counts once). Non-primitive
Pythagorean triples are Pythagorean triples which are not PPT.
For example, in the case of n = 65, the following are the cases for each of the criteria above:
1. 33, 56, 65; 63, 16, 65
2. 39, 52, 65; 25, 60, 65
3. 65, 72, 97; 65 2112 2113
4. 65, 420, 425; 65, 156, 169
Input
Input consists of a single line containing a single non-negative decimal integer n, (3 ≤ n ≤ 2500).
Output
There is one line of output. The single output line contains four decimal integers:
The first is the number of different PPTs in which n is the hypotenuse ( c ).
The second is the number of non-primitive Pythagorean triples in which n is the hypotenuse ( c).
The third is the number of different PPTs in which n is the one of the sides ( a or b ).
The fourth is the number of non-primitive Pythagorean triples in which n is the one of the sides (a or
b).
|
2154eca50f5f8f9a1eea3aaf1afd40a9
|
{
"intermediate": 0.357577919960022,
"beginner": 0.30584442615509033,
"expert": 0.3365776240825653
}
|
10,834
|
TypeError: '<' not supported between instances of 'int' and 'Timestamp'
|
3ca8899e428209f6c1948847175a5ee2
|
{
"intermediate": 0.3469167947769165,
"beginner": 0.39974352717399597,
"expert": 0.2533397078514099
}
|
10,835
|
center contnet in span elemnt
|
b3ad1f674b6a6e8ac44ef42a718692c1
|
{
"intermediate": 0.3418520390987396,
"beginner": 0.2716914713382721,
"expert": 0.3864564895629883
}
|
10,836
|
const Navbar = () => {
return (
<div className=“navbar”>
<div className=“container”>
<div className=“container__logo”>FABICO</div>
<div className=“container__iconsWrapper”>
<div className=“container__iconContainer”>
<NotificationsNone />
<span className=“container__iconBadge”>2</span>
</div>
<div className=“container__iconContainer”>
<Language />
<span className=“container__iconBadge”>2</span>
</div>
<div className=“container__iconContainer”>
<Settings />
</div>
<img src={adminPhoto} alt=“AdminPhoto” className=“container__image” />
</div>
</div>
</div>
);
};
refactor this
|
0c49f560ff016044c548ef4f7b20b21d
|
{
"intermediate": 0.36202365159988403,
"beginner": 0.3368004560470581,
"expert": 0.301175981760025
}
|
10,837
|
Write a program to build a schedule for a small school. You will ultimately need to figure out:
A schedule for each student
A schedule for each teacher
A roster for each teacher’s sections
Whether or not we need to hire another teacher and what that teacher would need to teach
Scheduling Requirements:
Every full-time teacher teaches 3 classes per day
Every student takes all 4 of their classes every day
Section sizes →
Minimum: 5 students
Maximum: 30 students
A teacher may teach any course within their department, but no courses outside their department
Programming Minimum Requirements:
Make use of Python Dictionaries (key-value pairs)
Include a Student class with the defined functions:
__init__ → name, courses
set_name
get_name
add_courses
get_courses
You may add anything else you deem necessary
Include a Teacher class with the defined functions:
__init__ → name, courses, department
set_name
get_name
set_department
get_department
add_courses
get_courses
You may add anything else you deem necessary
Here are the CSV files that you must use to complete the program:
Schedule Builder - Students.csv:
Student Name,English Course Recommendation ,Science Course Recommendation ,Math Course Recommendation ,History Course Recommendation
Maria,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Haley,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Ryan,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Andrei,Level 2.5,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Timothe,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Marvin,Level 3,Sheltered Chemistry,Mainstream Math Course,Mainstream History Course
Genesis,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Ashley,Level 3,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two
Rachelle,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Katia,Level 2,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two
Jorge,Level 3,Mainstream Science Course,Sheltered Algebra Two,Sheltered U.S. History Two
Juan,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Rosa,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Felipe,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Jennifer,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
Andrea,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Luis,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
Eddy,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Liza,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Shoshana,Level 2.5,Sheltered Chemistry,Sheltered Pre-Algebra,Sheltered U.S. History Two
Carlos,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Jesus,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Mohammed,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Naya,Level 3,Mainstream Science Course,Sheltered Algebra Two,Sheltered U.S. History Two
Francisco,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Jacques,Level 2,Sheltered Biology Two,Sheltered Geometry,Mainstream History Course
Abdi,Level 2,Sheltered Biology Two,Sheltered Algebra Two,Sheltered U.S. History One
Trinity,Level 2,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History One
Aleksandr,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Giovanna,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One
Giuliana,Level 2,Sheltered Biology Two,Sheltered Pre-Algebra,Sheltered U.S. History One
Hullerie,Level 3,Mainstream Science Course,Sheltered Algebra Two,Mainstream History Course
Sara,Level 2.5,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
David,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History Two
Paolo,Level 2,Mainstream Science Course,Sheltered Algebra One,Sheltered U.S. History Two
Ferdinand,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Fernando,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Lucia,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Lucas,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Damien,Level 2.5,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History Two
Boris,Level 2.5,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One
Sabrina,Level 2,Sheltered Biology Two,Sheltered Algebra Two,Sheltered U.S. History Two
Sabyne,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Miqueli,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Nicolly,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One
Nicolas,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Jaime,Level 2,Sheltered Biology Two,Sheltered Pre-Algebra,Sheltered U.S. History One
Daniel,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Daniela,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Michelle,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Carson,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Janaya,Level 2,Sheltered Biology One,Sheltered Pre-Algebra,Sheltered U.S. History Two
Janja,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Maria Fernanda,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Rafael,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Rafaela,Level 3,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Yves,Level 2.5,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Eva,Level 2.5,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
Amalia,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Denis,Level 2.5,Sheltered Chemistry,Sheltered Pre-Algebra,Sheltered U.S. History Two
Thelma,Level 2.5,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two
Esther,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Roberto,Level 3,Mainstream Science Course,Sheltered Algebra Two,Mainstream History Course
Diogo,Level 2,Sheltered Biology One,Sheltered Pre-Algebra,Sheltered U.S. History Two
Diego,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Samuel,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Harriet,Level 2.5,Mainstream Science Course,Sheltered Algebra One,Sheltered U.S. History Two
Cassie,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Chandra,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Louis,Level 3,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Marc,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Michael,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Jan Carlos,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One
Brayan,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Martin,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two
Simone,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Emilia,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Emillie,Level 2.5,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One
Catherine,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Darwin,Level 2,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Fiorella,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two
Carmelo,Level 3,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Savanna,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Emilio,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two
Antonio,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Steve,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Rosabella,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Isadora,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History One
Minnie,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Pedro,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Pierre,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Isaiah,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Kayla,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Adriana,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One
Jamily,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History One
Chiara,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Charlotte,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Zach,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Schedule Builder - Teachers.csv:
Teacher,Department
Orion,English
Leonard,English
Clovis,English
Hartford,English
Simiczek,Math
Rodrigues,Math
Martinez,Math
Canton,Math
Thibault,History
Lord,History
Vu,History
Bergerone,History
Domenico,Science
Daley,Science
Lopez,Science
DeMendonca,Science
|
655c17a57bb315e3507149183c983e56
|
{
"intermediate": 0.23592643439769745,
"beginner": 0.5078862905502319,
"expert": 0.2561873197555542
}
|
10,838
|
Write a program to build a schedule for a small school. Make it as efficient as possible. You will ultimately need to figure out:
A schedule for each student
A schedule for each teacher
A roster for each teacher’s sections
Whether or not we need to hire another teacher and what that teacher would need to teach
Scheduling Requirements:
Every full-time teacher teaches 3 classes per day
Every student takes all 4 of their classes every day
Section sizes →
Minimum: 5 students
Maximum: 30 students
A teacher may teach any course within their department, but no courses outside their department
Programming Minimum Requirements:
Make use of Python Dictionaries (key-value pairs)
Include a Student class with the defined functions:
init → name, courses
set_name
get_name
add_courses
get_courses
You may add anything else you deem necessary
Include a Teacher class with the defined functions:
init → name, courses, department
set_name
get_name
set_department
get_department
add_courses
get_courses
You may add anything else you deem necessary
The output should basically be
Teacher Name
Department:
Roster: [Students in roster]
Here are the CSV files that you must use to complete the program:
Schedule Builder - Students.csv:
Student Name,English Course Recommendation ,Science Course Recommendation ,Math Course Recommendation ,History Course Recommendation
Maria,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Haley,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Ryan,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Andrei,Level 2.5,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Timothe,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Marvin,Level 3,Sheltered Chemistry,Mainstream Math Course,Mainstream History Course
Genesis,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Ashley,Level 3,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two
Rachelle,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Katia,Level 2,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two
Jorge,Level 3,Mainstream Science Course,Sheltered Algebra Two,Sheltered U.S. History Two
Juan,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Rosa,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Felipe,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Jennifer,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
Andrea,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Luis,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
Eddy,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Liza,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Shoshana,Level 2.5,Sheltered Chemistry,Sheltered Pre-Algebra,Sheltered U.S. History Two
Carlos,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Jesus,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Mohammed,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Naya,Level 3,Mainstream Science Course,Sheltered Algebra Two,Sheltered U.S. History Two
Francisco,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Jacques,Level 2,Sheltered Biology Two,Sheltered Geometry,Mainstream History Course
Abdi,Level 2,Sheltered Biology Two,Sheltered Algebra Two,Sheltered U.S. History One
Trinity,Level 2,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History One
Aleksandr,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Giovanna,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One
Giuliana,Level 2,Sheltered Biology Two,Sheltered Pre-Algebra,Sheltered U.S. History One
Hullerie,Level 3,Mainstream Science Course,Sheltered Algebra Two,Mainstream History Course
Sara,Level 2.5,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
David,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History Two
Paolo,Level 2,Mainstream Science Course,Sheltered Algebra One,Sheltered U.S. History Two
Ferdinand,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Fernando,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Lucia,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Lucas,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Damien,Level 2.5,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History Two
Boris,Level 2.5,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One
Sabrina,Level 2,Sheltered Biology Two,Sheltered Algebra Two,Sheltered U.S. History Two
Sabyne,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Miqueli,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Nicolly,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One
Nicolas,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Jaime,Level 2,Sheltered Biology Two,Sheltered Pre-Algebra,Sheltered U.S. History One
Daniel,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Daniela,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Michelle,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Carson,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Janaya,Level 2,Sheltered Biology One,Sheltered Pre-Algebra,Sheltered U.S. History Two
Janja,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Maria Fernanda,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Rafael,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Rafaela,Level 3,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Yves,Level 2.5,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Eva,Level 2.5,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two
Amalia,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Denis,Level 2.5,Sheltered Chemistry,Sheltered Pre-Algebra,Sheltered U.S. History Two
Thelma,Level 2.5,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two
Esther,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Roberto,Level 3,Mainstream Science Course,Sheltered Algebra Two,Mainstream History Course
Diogo,Level 2,Sheltered Biology One,Sheltered Pre-Algebra,Sheltered U.S. History Two
Diego,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Samuel,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Harriet,Level 2.5,Mainstream Science Course,Sheltered Algebra One,Sheltered U.S. History Two
Cassie,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Chandra,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Louis,Level 3,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Marc,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Michael,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Jan Carlos,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One
Brayan,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Martin,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two
Simone,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Emilia,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Emillie,Level 2.5,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One
Catherine,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two
Darwin,Level 2,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two
Fiorella,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two
Carmelo,Level 3,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two
Savanna,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Emilio,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two
Antonio,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One
Steve,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Rosabella,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Isadora,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History One
Minnie,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Pedro,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Pierre,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course
Isaiah,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Kayla,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two
Adriana,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One
Jamily,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History One
Chiara,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course
Charlotte,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One
Zach,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two
Schedule Builder - Teachers.csv:
Teacher,Department
Orion,English
Leonard,English
Clovis,English
Hartford,English
Simiczek,Math
Rodrigues,Math
Martinez,Math
Canton,Math
Thibault,History
Lord,History
Vu,History
Bergerone,History
Domenico,Science
Daley,Science
Lopez,Science
DeMendonca,Science
GIVE THE COMPLETE CODE ONLY SO I CAN COPY AND PASTE!
|
038e8923d06f1c4927634a86219eb79a
|
{
"intermediate": 0.2239246517419815,
"beginner": 0.5071447491645813,
"expert": 0.2689306139945984
}
|
10,839
|
rust struct generic field set default value is None
|
b42a7bb9c75c852ab46292f43af23e59
|
{
"intermediate": 0.41124245524406433,
"beginner": 0.2517509162425995,
"expert": 0.3370066285133362
}
|
10,840
|
show me a picture of an anime style survivor of a zombie apocalypse that would fit a graphic novel style. she should be relativbly tall, quite thin, with short hair and makeshift armor
|
274ab30e7883b1e556af7ef6dff90e40
|
{
"intermediate": 0.3243086636066437,
"beginner": 0.2727149426937103,
"expert": 0.4029764235019684
}
|
10,841
|
ind all Pythagorean triples whose short sides are numbers smaller than 10. use
filter and comprehension.
|
89e72ca3cc2c6b4d7b963835cb23809a
|
{
"intermediate": 0.35044169425964355,
"beginner": 0.43458205461502075,
"expert": 0.21497631072998047
}
|
10,842
|
write 30 arabic keywords for a service that delievers a fully built, functional house from nothing. include building, furnishing.. etc. and write the keywords with a comma seperating them.
|
6c7637884dbf75b6179cdc8849e78b34
|
{
"intermediate": 0.34202417731285095,
"beginner": 0.26463407278060913,
"expert": 0.3933417797088623
}
|
10,843
|
what means this novalid_date: Optional[datetime, None] = None
|
dabe8b3cdf7fe9257a4ebc69a47e9372
|
{
"intermediate": 0.4006679654121399,
"beginner": 0.3270161747932434,
"expert": 0.2723158597946167
}
|
10,844
|
Текст <p><strong>Instrument:</strong> должен быть скрыт в профиле, если выбрана роль band. Однако, при регистрации в профиле текст Instrument: остается пустым, когда должно быть скрыто. p.s: пожалуйста, используй квадратные кавычки, иначе мой код не будет работать
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label">Instrument</label>
<select id="instrument" name="instrument">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="location">Location</label>
<input type="text" id="location" name="location" required>
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
if (role === 'Artist') {
document.querySelector('#instrument-label').style.display = 'block';
document.querySelector('#instrument').style.display = 'block';
} else {
document.querySelector('#instrument-label').style.display = 'none';
document.querySelector('#instrument').style.display = 'none';
}
}
</script>
</body>
</html>
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Role:</strong> <%= musician.role %></p>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong>
<% if (musician.role === 'band' && musician.instrument) { %>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<% } %>
</p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (musician.soundcloud) { %>
<iframe width="50%" height="150" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% } %>
<% if (musician.soundcloud1) { %>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="name">Role:</label>
<input type="role" id="role" name="role" value="<%= musician.role %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">Song 1:</label>
<input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud %>">
</div>
<div>
<label for="soundcloud">Song 2:</label>
<input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 %>">
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<!--
<div>
<input type="text" name="soundcloud[]" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div> -->
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
//скрыть плеер, если ссылка не внесена
const song1Input = document.getElementById("soundcloud");
const song2Input = document.getElementById("soundcloud1");
const player1 = document.getElementsByTagName('iframe')[0];
const player2 = document.getElementsByTagName('iframe')[1];
let songs = {
song: "",
song1: ""
}
function hidePlayer(player) {
player.src = "";
player.style.display = "none";
}
function updateSongs() {
songs.song = song1Input.value.trim();
songs.song1 = song2Input.value.trim();
}
function updatePlayers() {
if (songs.song !== "") {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (songs.song1 !== "") {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
song1Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
song2Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
updateSongs();
updatePlayers();
//Валидация ссылок с soundcloud
function updatePlayers() {
if (isValidSoundcloudUrl(songs.song)) {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (isValidSoundcloudUrl(songs.song1)) {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
function isValidSoundcloudUrl(url) {
const regex = /^https?:\/\/(soundcloud\.com|snd\.sc)\/(.*)$/;
return regex.test(url);
}
</script>
<style>
</style>
</body>
</html>
|
c2bb57bcd2342fec03f436bec3591553
|
{
"intermediate": 0.3059071898460388,
"beginner": 0.48506054282188416,
"expert": 0.20903229713439941
}
|
10,845
|
Instrument: должен быть скрыт в профиле, если выбрана роль band. Однако, при регистрации в профиле текст Instrument: остается пустым, когда должно быть скрыто полностью. p.s: пожалуйста, используй квадратные кавычки, иначе мой код не будет работать
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Role:</strong> <%= musician.role %></p>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong>
<% if (musician.role === 'Artist' && musician.instrument) { %>
<%= musician.instrument %>
<% } else if (musician.role === 'Band') { %>
<!-- Instrument field should be hidden for bands -->
<% } %>
</p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (musician.soundcloud) { %>
<iframe width="50%" height="150" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% } %>
<% if (musician.soundcloud1) { %>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="name">Role:</label>
<input type="role" id="role" name="role" value="<%= musician.role %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">Song 1:</label>
<input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud %>">
</div>
<div>
<label for="soundcloud">Song 2:</label>
<input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 %>">
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<!--
<div>
<input type="text" name="soundcloud[]" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div> -->
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
//скрыть плеер, если ссылка не внесена
const song1Input = document.getElementById("soundcloud");
const song2Input = document.getElementById("soundcloud1");
const player1 = document.getElementsByTagName('iframe')[0];
const player2 = document.getElementsByTagName('iframe')[1];
let songs = {
song: "",
song1: ""
}
function hidePlayer(player) {
player.src = "";
player.style.display = "none";
}
function updateSongs() {
songs.song = song1Input.value.trim();
songs.song1 = song2Input.value.trim();
}
function updatePlayers() {
if (songs.song !== "") {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (songs.song1 !== "") {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
song1Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
song2Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
updateSongs();
updatePlayers();
//Валидация ссылок с soundcloud
function updatePlayers() {
if (isValidSoundcloudUrl(songs.song)) {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (isValidSoundcloudUrl(songs.song1)) {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
function isValidSoundcloudUrl(url) {
const regex = /^https?:\/\/(soundcloud\.com|snd\.sc)\/(.*)$/;
return regex.test(url);
}
</script>
<style>
</style>
</body>
</html>
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label">Instrument</label>
<select id="instrument" name="instrument">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="location">Location</label>
<input type="text" id="location" name="location" required>
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
if (role === 'Artist') {
document.querySelector('#instrument-label').style.display = 'block';
document.querySelector('#instrument').style.display = 'block';
} else {
document.querySelector('#instrument-label').style.display = 'none';
document.querySelector('#instrument').style.display = 'none';
}
}
</script>
</body>
</html>
|
c862a057a3d1ac2c1f8c3810a5b05d94
|
{
"intermediate": 0.31517234444618225,
"beginner": 0.5269676446914673,
"expert": 0.15786007046699524
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.