row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
13,160
|
I have two collections (FutureMK, PastMK). User searchs for smth and gets the result, after that they can look into details by clicking Подробнее
import { Text, View, Image, Pressable } from 'react-native';
import { gStyle } from '../styles/style';
import React from 'react';
export default function Result({ item }) {
return (
<View style={[gStyle.bookedMK, {flex:1}]}>
<View style={{ flexDirection: 'column' }}>
<View style={gStyle.ProfileDetails1}>
<Image source={{uri:item.image}} style={gStyle.ProfileImg1}/>
<View style={gStyle.ProfileDescription}>
<Text style={gStyle.ProfileTitleOfMK1}>{item.name}</Text>
<Text>
{item.description.length > 100
? item.description.substring(0, 100)+'...'
: item.description
}
</Text>
</View>
</View>
</View>
<Pressable
style={gStyle.readmore}
>
<Text style={gStyle.readmoretxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.ProfileLine}></Text>
</View>
);
}
and i have already have two screens for PastMK
import { Text, View, Image, ScrollView, Pressable} from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';
import { useEffect, useState } from 'react';
export default function PastMKInfo({route}) {
const [pastMK, setPastMK]=useState([]);
useEffect(()=>{
const pastMKRef=firebase.firestore().collection('PastMK');
pastMKRef.onSnapshot((querySnapshot)=>{
const list=[];
querySnapshot.forEach((doc)=>{
const {name, time, description, image}=doc.data();
list.push({
id:doc.id,
name,
description,
image,
time,
collection:'PastMK'
})
})
setPastMK(list);
});
return()=>pastMKRef();
},[]);
const navigation = useNavigation();
const {mkData}=route.params;
const handleGoBack=()=>{
navigation.goBack();
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{new Intl.DateTimeFormat('ru-RU',{
day:'numeric',
month:'long',
year:'numeric'
}).format(mkData.time.toDate())}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:mkData.image}}
style={gStyle.SupImg}
/>
<Text style={gStyle.SupDescription}>
{mkData.description}
</Text>
</View>
</View>
<Pressable style={gStyle.goback}
onPress={handleGoBack}
>
<Text style={gStyle.gobacktxt1}>Назад</Text>
</Pressable>
</View>
<Footer/>
</ScrollView>
</View>
);
}
and the FutureMK
import { Text, View, Image, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import React, {useState, useEffect} from 'react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';
import {firebase} from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
export default function SignUpForMK({route}) {
const [futureMK, setFutureMK]=useState([]);
useEffect(()=>{
const futureMKRef = firebase.firestore().collection('FutureMK');
futureMKRef.onSnapshot((querySnapshot)=>{
const list =[];
querySnapshot.forEach((doc)=>{
const {name, time, description, image}=doc.data();
list.push({
id:doc.id,
name,
time,
description,
image,
collection:'FutureMK'
})
});
setFutureMK(list);
});
return()=>futureMKRef();
},[]);
const [userAuthenticated, setUserAuthenticated] = useState(false);
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUserAuthenticated(true);
} else {
setUserAuthenticated(false);
}
});
return unsubscribe;
}, []);
const {mkData}=route.params;
const navigation = useNavigation();
const bookMK=()=>{
const currentUserID=firebase.auth().currentUser.uid;
const bookedMKData={
name:mkData.name,
time:mkData.time.toDate().toISOString(),
image:mkData.image,
price:mkData.price
};
firebase
.database()
.ref(`users/${currentUserID}/bookedMK`)
.push(bookedMKData)
.then(()=>{
navigation.navigate('Profile');
})
}
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{new Intl.DateTimeFormat('ru-RU',{
day:'numeric',
month:'long',
year:'numeric',
hour:'numeric',
minute:'numeric',
hour12:false
}).format(mkData.time.toDate())}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:mkData.image}}
style={gStyle.SupImg}
/>
<View style={gStyle.SupForm}>
<View style={gStyle.SupPrice}>
<Text style={gStyle.SupPrice1}>Цена: </Text>
<Text style={gStyle.SupNumber}>{mkData.price} Р.</Text>
</View>
</View>
<Text style={gStyle.SupDescription}>
{mkData.description}
</Text>
<Text style={gStyle.SupLine}></Text>
<View style={gStyle.SupContaier1}>
<View style={gStyle.SupBox1}>
<Ionicons name="person-outline" size={30} color="black" />
<Text style={gStyle.SupPerson}>{mkData.person} человек</Text>
</View>
<View style={gStyle.SupBox1}>
<MaterialCommunityIcons
name="clock-time-four-outline"
size={30}
color="black"
/>
<Text style={gStyle.SupAlarm}>{mkData.timeOfMK} час(а)</Text>
</View>
</View>
<Text style={gStyle.SupLine}></Text>
{userAuthenticated ?
<Pressable style={gStyle.SupMoreDetails}
onPress={bookMK}
>
<Text style={gStyle.SupBtn}>Забронировать</Text>
</Pressable>
:
<Pressable style={gStyle.SupMoreDetails}
onPress={()=>navigation.navigate('Auth')}
>
<Text style={gStyle.SupBtn}>Забронировать</Text>
</Pressable>
}
</View>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
How can user be redirected from result to the FutureMK or the PastMK?
|
63fb53fe81a96502006f75fbc1694f5b
|
{
"intermediate": 0.4343874752521515,
"beginner": 0.45158660411834717,
"expert": 0.11402590572834015
}
|
13,161
|
ما هذا الخطأ Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 6
video_urls = input(“Enter urls separated by space: “).split()
^
SyntaxError: invalid character '“' (U+201C)
[Program finished]
|
2fbfae96831e9a3bffd6735d397ecfd6
|
{
"intermediate": 0.3023793697357178,
"beginner": 0.444307416677475,
"expert": 0.253313273191452
}
|
13,162
|
from SP500 what are the top 10 stocks with the most gains and lower volatility. Create an indicator that balances growth with less volatility
|
c539e670bfab1eb204030cd6159cfddf
|
{
"intermediate": 0.3980473577976227,
"beginner": 0.270133376121521,
"expert": 0.3318192660808563
}
|
13,163
|
Мне нужно сделать так, чтобы пользователь, который ввел что-то в поиске и нашел результат и, если захотел перейти, то редирект произойдет на экран с детальной информацией о посте, но у меня там две коллекции, то есть, если пользователь нашел пост из PastMK, то его должно перекинуть на экран с информацией об этом посте, а если из коллекции FutureMK, то так же. Вот код
import { Text, View, Image, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import React, {useState, useEffect} from 'react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';
import {firebase} from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
export default function SignUpForMK({route}) {
const [userAuthenticated, setUserAuthenticated] = useState(false);
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUserAuthenticated(true);
} else {
setUserAuthenticated(false);
}
});
return unsubscribe;
}, []);
const {mkData}=route.params;
const navigation = useNavigation();
const bookMK=()=>{
const currentUserID=firebase.auth().currentUser.uid;
const bookedMKData={
name:mkData.name,
time:mkData.time.toDate().toISOString(),
image:mkData.image,
price:mkData.price
};
firebase
.database()
.ref(`users/${currentUserID}/bookedMK`)
.push(bookedMKData)
.then(()=>{
navigation.navigate('Profile');
})
}
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{new Intl.DateTimeFormat('ru-RU',{
day:'numeric',
month:'long',
year:'numeric',
hour:'numeric',
minute:'numeric',
hour12:false
}).format(mkData.time.toDate())}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:mkData.image}}
style={gStyle.SupImg}
/>
<View style={gStyle.SupForm}>
<View style={gStyle.SupPrice}>
<Text style={gStyle.SupPrice1}>Цена: </Text>
<Text style={gStyle.SupNumber}>{mkData.price} Р.</Text>
</View>
</View>
<Text style={gStyle.SupDescription}>
{mkData.description}
</Text>
<Text style={gStyle.SupLine}></Text>
<View style={gStyle.SupContaier1}>
<View style={gStyle.SupBox1}>
<Ionicons name="person-outline" size={30} color="black" />
<Text style={gStyle.SupPerson}>{mkData.person} человек</Text>
</View>
<View style={gStyle.SupBox1}>
<MaterialCommunityIcons
name="clock-time-four-outline"
size={30}
color="black"
/>
<Text style={gStyle.SupAlarm}>{mkData.timeOfMK} час(а)</Text>
</View>
</View>
<Text style={gStyle.SupLine}></Text>
{userAuthenticated ?
<Pressable style={gStyle.SupMoreDetails}
onPress={bookMK}
>
<Text style={gStyle.SupBtn}>Забронировать</Text>
</Pressable>
:
<Pressable style={gStyle.SupMoreDetails}
onPress={()=>navigation.navigate('Auth')}
>
<Text style={gStyle.SupBtn}>Забронировать</Text>
</Pressable>
}
</View>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
import { Text, View, Image, ScrollView, Pressable} from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';
export default function PastMKInfo({route}) {
const navigation = useNavigation();
const {mkData}=route.params;
const handleGoBack=()=>{
navigation.goBack();
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{new Intl.DateTimeFormat('ru-RU',{
day:'numeric',
month:'long',
year:'numeric'
}).format(mkData.time.toDate())}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:mkData.image}}
style={gStyle.SupImg}
/>
<Text style={gStyle.SupDescription}>
{mkData.description}
</Text>
</View>
</View>
<Pressable style={gStyle.goback}
onPress={handleGoBack}
>
<Text style={gStyle.gobacktxt1}>Назад</Text>
</Pressable>
</View>
<Footer/>
</ScrollView>
</View>
);
}
import { Text, View, Image, Pressable } from 'react-native';
import { gStyle } from '../styles/style';
import React from 'react';
export default function Result({ item }) {
return (
<View style={[gStyle.bookedMK, {flex:1}]}>
<View style={{ flexDirection: 'column' }}>
<View style={gStyle.ProfileDetails1}>
<Image source={{uri:item.image}} style={gStyle.ProfileImg1}/>
<View style={gStyle.ProfileDescription}>
<Text style={gStyle.ProfileTitleOfMK1}>{item.name}</Text>
<Text>
{item.description.length > 100
? item.description.substring(0, 100)+'...'
: item.description
}
</Text>
</View>
</View>
</View>
<Pressable
style={gStyle.readmore}
>
<Text style={gStyle.readmoretxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.ProfileLine}></Text>
</View>
);
}
|
1812615e3ffaa9e8da094aefac15ad66
|
{
"intermediate": 0.35371696949005127,
"beginner": 0.45744243264198303,
"expert": 0.18884062767028809
}
|
13,164
|
Напиши код на python для дискорд бота на disnake, чтобы он отслеживал сколько человек наиграл часов в игре в стиме и отправлял сообщение ник (steam id) - сколько часов
|
8e7ff48858abcc4d09ed7e26268956fd
|
{
"intermediate": 0.40904152393341064,
"beginner": 0.22525304555892944,
"expert": 0.3657054901123047
}
|
13,165
|
I need to redirect user on the screen with detailed data about PastMK or FutureMK, depends on what the user found. i need it to be simple so i would understand. i already have screens with detailed info
PastMK:
import { Text, View, Image, ScrollView, Pressable} from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';
export default function PastMKInfo({route}) {
const navigation = useNavigation();
const {mkData}=route.params;
const handleGoBack=()=>{
navigation.goBack();
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{new Intl.DateTimeFormat('ru-RU',{
day:'numeric',
month:'long',
year:'numeric'
}).format(mkData.time.toDate())}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:mkData.image}}
style={gStyle.SupImg}
/>
<Text style={gStyle.SupDescription}>
{mkData.description}
</Text>
</View>
</View>
<Pressable style={gStyle.goback}
onPress={handleGoBack}
>
<Text style={gStyle.gobacktxt1}>Назад</Text>
</Pressable>
</View>
<Footer/>
</ScrollView>
</View>
);
}
FutureMK:
import { Text, View, Image, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import React, {useState, useEffect} from 'react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';
import {firebase} from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
export default function SignUpForMK({route}) {
const [userAuthenticated, setUserAuthenticated] = useState(false);
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUserAuthenticated(true);
} else {
setUserAuthenticated(false);
}
});
return unsubscribe;
}, []);
const {mkData}=route.params;
const navigation = useNavigation();
const bookMK=()=>{
const currentUserID=firebase.auth().currentUser.uid;
const bookedMKData={
name:mkData.name,
time:mkData.time.toDate().toISOString(),
image:mkData.image,
price:mkData.price
};
firebase
.database()
.ref(`users/${currentUserID}/bookedMK`)
.push(bookedMKData)
.then(()=>{
navigation.navigate('Profile');
})
}
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{new Intl.DateTimeFormat('ru-RU',{
day:'numeric',
month:'long',
year:'numeric',
hour:'numeric',
minute:'numeric',
hour12:false
}).format(mkData.time.toDate())}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:mkData.image}}
style={gStyle.SupImg}
/>
<View style={gStyle.SupForm}>
<View style={gStyle.SupPrice}>
<Text style={gStyle.SupPrice1}>Цена: </Text>
<Text style={gStyle.SupNumber}>{mkData.price} Р.</Text>
</View>
</View>
<Text style={gStyle.SupDescription}>
{mkData.description}
</Text>
<Text style={gStyle.SupLine}></Text>
<View style={gStyle.SupContaier1}>
<View style={gStyle.SupBox1}>
<Ionicons name="person-outline" size={30} color="black" />
<Text style={gStyle.SupPerson}>{mkData.person} человек</Text>
</View>
<View style={gStyle.SupBox1}>
<MaterialCommunityIcons
name="clock-time-four-outline"
size={30}
color="black"
/>
<Text style={gStyle.SupAlarm}>{mkData.timeOfMK} час(а)</Text>
</View>
</View>
<Text style={gStyle.SupLine}></Text>
{userAuthenticated ?
<Pressable style={gStyle.SupMoreDetails}
onPress={bookMK}
>
<Text style={gStyle.SupBtn}>Забронировать</Text>
</Pressable>
:
<Pressable style={gStyle.SupMoreDetails}
onPress={()=>navigation.navigate('Auth')}
>
<Text style={gStyle.SupBtn}>Забронировать</Text>
</Pressable>
}
</View>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
its the component from where the user must be redirected:
import { Text, View, Image, Pressable } from 'react-native';
import { gStyle } from '../styles/style';
import React from 'react';
export default function Result({ item, onPress }) {
return (
<View style={[gStyle.bookedMK, {flex:1}]}>
<View style={{ flexDirection: 'column' }}>
<View style={gStyle.ProfileDetails1}>
<Image source={{uri:item.image}} style={gStyle.ProfileImg1}/>
<View style={gStyle.ProfileDescription}>
<Text style={gStyle.ProfileTitleOfMK1}>{item.name}</Text>
<Text>
{item.description.length > 100
? item.description.substring(0, 100)+'...'
: item.description
}
</Text>
</View>
</View>
</View>
<Pressable
style={gStyle.readmore}
onPress={()=>onPress(item)}
>
<Text style={gStyle.readmoretxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.ProfileLine}></Text>
</View>
);
}
its search screen:
import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity, Image } from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation, useRoute } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState} from 'react';
import Result from '../components/Result';
export default function Search() {
const navigation = useNavigation();
const route = useRoute();
const results = route.params?.results || [];
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<Text style={gStyle.header}>Результаты поиска</Text>
<View style={[gStyle.bookedMK, {flex:1}]}>
<View style={{ flexDirection: 'column' }}>
{results.length > 0 ? (
results.map((item, index)=>(
<Result key={index} item={item}/>))
): (
<Text style={gStyle.nothing}>По вашему запросу ничего{"\n"}не найдено.</Text>
)}
</View>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
|
113ce9e450612214b73fa46efedcf4e0
|
{
"intermediate": 0.4129067063331604,
"beginner": 0.3995349109172821,
"expert": 0.1875583976507187
}
|
13,166
|
extract this pdf to tabular data
|
994377e9cbc61e709fc72601ef0bccab
|
{
"intermediate": 0.37090548872947693,
"beginner": 0.25014474987983704,
"expert": 0.37894973158836365
}
|
13,167
|
In polybar, is there a way to have the time and the date display in different fonts?
|
8b9304c57929cfd00d4784372455b8ae
|
{
"intermediate": 0.39661338925361633,
"beginner": 0.2661586105823517,
"expert": 0.3372279703617096
}
|
13,168
|
Would semi-implicit euler integration help remain close to the ideal mathematically determined trajectories in a physics simulation for a video game?
|
30b9f314d7dde314e6cf988ace1ef301
|
{
"intermediate": 0.31270116567611694,
"beginner": 0.2267383337020874,
"expert": 0.4605604410171509
}
|
13,169
|
Tell me about the paper 'noise reduction in ecg signal using an effective hybrid scheme' by pingping bing, wei liu, zhong wang, and zhihua zhang
|
f8322244c616491d5cfba2bdb224fd20
|
{
"intermediate": 0.06235190108418465,
"beginner": 0.0571259967982769,
"expert": 0.8805221319198608
}
|
13,170
|
What is the genrail structure for an Oversight Council
|
4b4195bcc03ce6d7f81b9c8293af3565
|
{
"intermediate": 0.24997329711914062,
"beginner": 0.14585039019584656,
"expert": 0.6041762828826904
}
|
13,171
|
can you tell me the most expensive Fornecedor from and unstructure text of invoice data
|
c1c0a59d0196cd69cd9dd047c7f5f38f
|
{
"intermediate": 0.3569355607032776,
"beginner": 0.3460172414779663,
"expert": 0.2970471978187561
}
|
13,172
|
on debian how do i run ducky scipts on a usb flash drive
|
6ea913e373b1172ad40dbe147fb0e8a1
|
{
"intermediate": 0.4698258638381958,
"beginner": 0.22431036829948425,
"expert": 0.30586376786231995
}
|
13,173
|
how much is the price of a new pair of sneakers?
|
172e629c0f8be7c2e7e35a531d3cabae
|
{
"intermediate": 0.2575050890445709,
"beginner": 0.3900783658027649,
"expert": 0.3524165153503418
}
|
13,174
|
<div>
<span>Refresh </span>
<Select
defaultValue={refreshTime}
style={{
width: 120,
}}
onChange={handleSelect}
options={[
{
value: 5,
label: '5s',
},
{
value: 10,
label: '10s',
},
{
value: 15,
label: '15s',
},
{
value: 20,
label: '20s',
},
]}
/>
</div> как расположить span и Select по правому краю?
|
b8e5ee4f6d1b4aed4170b26f4559c1fd
|
{
"intermediate": 0.30573102831840515,
"beginner": 0.4635690152645111,
"expert": 0.23070000112056732
}
|
13,175
|
show me a graphic displaying each Fornecedor and Processado value
|
c423397d96ffb7979e39d66f14666388
|
{
"intermediate": 0.555536150932312,
"beginner": 0.17099237442016602,
"expert": 0.2734713852405548
}
|
13,176
|
import time
import os
os.system("clear")
start_time = time.time()
custom_characters = "abcdefghijjklmnopqrstuvwxyz" #iredcters
for num_letters in range(0, 5):
num_combinations = len(custom_characters) ** num_letters
for i in range(num_combinations):
combination = ''.join([custom_characters[(i // (len(custom_characters) ** (num_letters - pos - 1))) % len(custom_characters)] for pos in range(num_letters)])
f = open("combonation.txt", "a")
f.write(combination)
f.close()
#open and read the file after the appending:
f = open("combonation.txt", "r")
print(f.read())
end_time = time.time()
execution_time = end_time - start_time
execution_time_minutes = execution_time / 60
print(f"Code execution finished. Total execution time: {execution_time_minutes} minutes.")
input("Press enter to quit combo-nator >> ")
why is my code not writing a in a file from a varible
|
ac3ceeb083dfbc3e17170e2b616c7145
|
{
"intermediate": 0.43807271122932434,
"beginner": 0.342783123254776,
"expert": 0.21914421021938324
}
|
13,177
|
what is the difference between *args and **kwargs in python
|
c9009e9b7f8101989253b85629f1f9aa
|
{
"intermediate": 0.40031948685646057,
"beginner": 0.28063350915908813,
"expert": 0.31904706358909607
}
|
13,178
|
say hello
|
cefe2bd03281f9b05bd6c615b8c7a7db
|
{
"intermediate": 0.336365282535553,
"beginner": 0.2994164824485779,
"expert": 0.36421823501586914
}
|
13,179
|
improve this code
/* == SIMPLE ASM-x32 HOOKING ENGINE v1.2 ==
DESC:
- automatic nops insertion for original instruction size alignment
- automatic hook jump addresses calculation and non-relative code relocation
- multiple serial hooks installation, already patched code detection
- simple automatic memory management and pages allocation
- user-defined size hook memory and code sections
- hook user-defined sections initialization (zero data & place nops in code sections)
- hook user-program installation
- page protection saving before installation process and restoring after
- checks if memory page at the modifiable regions is accessible
- returns original trampoline content if return pointer is not NULL (v1.2)
I/O (I=input, O=output):
(I) install_offset - relative starting address (to process base) for hook installation
(I) trampoline_sz - size in bytes of original code to swap (replace with jump instr, fill with nops leftovers and place original instr at the start of hook code section)
(I) code_sz - size of user code section
(I) *p_asm_prog - pointer to user asm-prog byte array, if NULL - no prog installation
(I) data_sz - size of user data section
(I/O) *p_data - if not NULL then returns pointer to first (lower addr) user data byte (void* for type support)
(I/O) *p_orig_trampoline - if not NULL then fills pointed buffer with original trampoline content (new v1.2)
(O) - returns pointer to first user code byte
[!] WARNING: only 32-bit processes and only instruction swapping without relative addresses supported at the moment
*/
BYTE *aip_mbapi_asm_install_hook(DWORD install_offset, BYTE trampoline_sz, WORD code_sz, BYTE *p_asm_prog, WORD data_sz, void *p_data, BYTE *p_orig_trampoline)
{
static DWORD mem_page_pos = 0, mem_page_start = 0;
static WORD hook_no = 0;
const BYTE jump_instr_sz = 1 + sizeof(DWORD);
BYTE p_jump_instr[jump_instr_sz];
p_jump_instr[0] = 0xE9; //jump instr
++hook_no;
AIP_CORE_PRINT(AIP_CORE_STRM_DEBUG, "New hook params: offset=0x%08lX, code_sz=%u, data_sz=%u", install_offset, code_sz, data_sz);
BYTE *p_install_addr = (BYTE *)(aip_mbapi.base_address + install_offset);
aip_mbapi_asm_check_mem_is_accessible(p_install_addr, trampoline_sz); //target mem is ok?
DWORD oldProtect, newProtect;
AIP_CORE_CHECK_ERROR(!VirtualProtect(p_install_addr, trampoline_sz, PAGE_EXECUTE_READWRITE, &oldProtect), AIP_EC_WINAPI_PAGE_PROTECTION_CHANGE_FAIL);
if (oldProtect == PAGE_EXECUTE) //we need read access after hook installation
oldProtect = PAGE_EXECUTE_READ;
if (p_orig_trampoline != NULL) // new v1.2 - return original trampoline data
memcpy(p_orig_trampoline, p_install_addr, trampoline_sz);
BYTE *p_custom_code_addr = NULL, *p_custom_data_addr = NULL;
if (p_install_addr[0] == p_jump_instr[0]) { //already patched?
DWORD *rel_addr_to_old_hook = (DWORD *)(p_install_addr + 1);
DWORD old_hook_addr = ((DWORD)(*rel_addr_to_old_hook)) + aip_mbapi.base_address + install_offset + jump_instr_sz; //give me old hook address!
p_custom_data_addr = (BYTE *)(old_hook_addr - data_sz);
if (p_data != NULL)
memcpy(p_data, &p_custom_data_addr, sizeof(void *));
p_custom_code_addr = (BYTE *)old_hook_addr;
AIP_CORE_PRINT(AIP_CORE_STRM_DEBUG, "Detected installed hook#%u at address: 0x%08lX (p_data:0x%p, p_code:0x%p)", hook_no, old_hook_addr, p_custom_data_addr, p_custom_code_addr);
VirtualProtect(p_install_addr, trampoline_sz, oldProtect, &newProtect);
return p_custom_code_addr; //return pointer to first nop
} //NOTE: new hooks is better to place on the new page even if there is some free space on detected hook page...
BYTE *p_hook_addr = NULL;
WORD hook_sz_full = data_sz + code_sz + trampoline_sz + jump_instr_sz;
//new v1.3 - analyze trampoline and exclude it from hook if all opcodes are nops
BYTE trampoline_sz_optimized = trampoline_sz; BOOL is_nops = TRUE;
for (BYTE i = 0; i < trampoline_sz; ++i) {
if (((BYTE)*(p_install_addr + i)) != 0x90) {is_nops = FALSE; break;}
}
if (is_nops) {
AIP_CORE_PRINT(AIP_CORE_STRM_DEBUG, "Detected empty trampoline, optimizing hook size...");
hook_sz_full -= trampoline_sz; trampoline_sz_optimized = 0;
}
if ( (mem_page_pos != 0) && ((mem_page_pos + hook_sz_full) < (mem_page_start + aip_mbapi.page_size)) ) { //check if we can use already allocated page
AIP_CORE_PRINT(AIP_CORE_STRM_DEBUG, "Installing hook in already allocated page...");
p_hook_addr = (BYTE *)mem_page_pos;
*(p_hook_addr - 1) = 0x90; //fix - replace 00 with nop to fix disasm view
} else { //no allocated page or not enough bytes on current page
p_hook_addr = VirtualAlloc(NULL, hook_sz_full, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
AIP_CORE_PRINT(AIP_CORE_STRM_DEBUG, "New page for hook allocated at address 0x%p", p_hook_addr);
mem_page_start = (DWORD)p_hook_addr;
}
AIP_CORE_CHECK_ERROR((p_hook_addr == NULL), AIP_EC_WINAPI_MEM_ALLOC_FAIL); //WHAT?!
aip_mbapi_asm_check_mem_is_accessible(p_hook_addr, hook_sz_full); //hook mem is ok?
p_custom_data_addr = (BYTE *)p_hook_addr;
if (p_data != NULL) //if data pointer is valid
memcpy(p_data, &p_custom_data_addr, sizeof(void *)); //then save first data byte address into it
memset(p_hook_addr, 0x00, data_sz); //make sure that data section contains only zeros
p_hook_addr += data_sz; //shift from data section
hook_sz_full -= data_sz; //reduce size due to shift
memset(p_hook_addr, 0x90, hook_sz_full); //fill code section with nops
BYTE *p_hook_trampoline_addr = (BYTE *)(p_hook_addr + code_sz); //address where trampoline first byte is located inside hook
if (trampoline_sz_optimized != 0)
AIP_CORE_CALL_IF_BUILD_ALIVE(memcpy, p_hook_trampoline_addr, p_install_addr, trampoline_sz_optimized); //! memcpy(p_hook_trampoline_addr, p_install_addr, trampoline_sz_optimized); //copy stolen bytes at the end of hook
BYTE *p_return_from_hook_addr = (BYTE *)(p_hook_addr + hook_sz_full - jump_instr_sz); //create custom hook asm code before patch
DWORD rel_addr_from_hook = (DWORD)(p_install_addr - p_return_from_hook_addr - jump_instr_sz + trampoline_sz); //jump AFTER trampoline
memcpy((BYTE *)(p_jump_instr + 1), &rel_addr_from_hook, sizeof(DWORD)); //assign jump address
memcpy(p_return_from_hook_addr, p_jump_instr, jump_instr_sz); //append jump from hook instr
DWORD rel_addr_to_hook = (DWORD)(p_hook_addr - p_install_addr - jump_instr_sz); //mb code patching - redirect code flow to custom section
memcpy((BYTE *)(p_jump_instr + 1), &rel_addr_to_hook, sizeof(DWORD)); //assign jump address
BYTE p_install_addr_patch[trampoline_sz];
memset(p_install_addr_patch, 0x90, trampoline_sz); //don't show me garbage in debugger!
memcpy(p_install_addr_patch, p_jump_instr, jump_instr_sz); //full patch with jump and nops
memcpy(p_install_addr, p_install_addr_patch, trampoline_sz); //append this shit
VirtualProtect(p_install_addr, trampoline_sz, oldProtect, &newProtect); //restore page protection
p_custom_code_addr = p_hook_addr; //NEW - place custom code at the start of hook code section
AIP_CORE_PRINT(AIP_CORE_STRM_DEBUG, "Hook#%u installed at address: 0x%p (p_data:0x%p, p_code:0x%p)", hook_no, p_hook_addr, p_custom_data_addr, p_custom_code_addr);
if (p_asm_prog != NULL)
aip_mbapi_asm_install_prog(p_custom_code_addr, p_asm_prog, code_sz);
mem_page_pos = (DWORD)(p_hook_addr + hook_sz_full + 1); //set page pos to end of current hook + 1 nop
AIP_CORE_PRINT(AIP_CORE_STRM_DEBUG, "Page address for next hook: 0x%08lX", mem_page_pos);
return p_custom_code_addr; //return pointer to first NOP instr in hook
}
|
f1c20ff9edb0f1e1240fc616413f50e2
|
{
"intermediate": 0.44192740321159363,
"beginner": 0.3660123944282532,
"expert": 0.192060187458992
}
|
13,180
|
hello
|
78331c0d6149120b482c1ff070a0dc86
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
13,181
|
write assembler hook in C
|
87a0d9da24c41bbc9cc28c717b81708d
|
{
"intermediate": 0.42454785108566284,
"beginner": 0.32820621132850647,
"expert": 0.24724604189395905
}
|
13,182
|
how to copy repo grom git
|
a1673ad66aeca06963909adb3ded2a62
|
{
"intermediate": 0.4997495412826538,
"beginner": 0.2536284327507019,
"expert": 0.24662195146083832
}
|
13,183
|
hi. i'm working with tableau, and i need some help
|
131f1f5ffbb9d04979babd2556ea990a
|
{
"intermediate": 0.35470208525657654,
"beginner": 0.3840416371822357,
"expert": 0.26125627756118774
}
|
13,184
|
class InvoiceSaleDetailController extends GetxController with AppControllerMixin {
final List<InvoiceSaleDetail> saleDetails = [];
int saleId;
InvoiceSaleDetailController({required this.saleId});
@override
Future<void> onReady() async {
saleDetails.addAll(
await AppDatabase.instance.invoiceSaleDetailDao.getAll(saleId: saleId),
);
update();
super.onReady();
}
Future<void> onNew() async {
final saleDetail = await Get.to(() => NewSaleDetailView(),
binding: NewSaleDetailBinding());
if (saleDetail != null) {
saleDetail.saleId = saleId;
final id = await AppDatabase.instance.invoiceSaleDetailDao.create(saleDetail);
saleDetails.add(saleDetail.copyWith(id: id));
update();
}
}
Future<void> onNewBatch() async {
final newDetails = await Get.to(() => NewSaleDetailBatchView(),
binding: NewSaleDetailBinding());
if (newDetails != null) {
for (var detail in newDetails) {
detail.saleId = saleId;
final id = await AppDatabase.instance.invoiceSaleDetailDao.create(detail);
saleDetails.add(detail.copyWith(id: id));
}
update();
}
}
Future<void> onEdited(InvoiceSaleDetail saleDetail) async {
final result = await Get.to(() => NewSaleDetailView(),
arguments: saleDetail, binding: NewSaleDetailBinding());
if (result != null) {
await AppDatabase.instance.invoiceSaleDetailDao.update(result);
final index =
saleDetails.indexWhere((element) => element.id == result.id);
saleDetails[index] = result;
update();
}
}
Future<void> onDeleted(InvoiceSaleDetail saleDetail) async {
saleDetails.removeWhere((element) => element.id == saleDetail.id);
update();
await AppDatabase.instance.invoiceSaleDetailDao.delete(saleDetail);
}
Future<void> onDeleteAll() async {
saleDetails.clear();
update();
await AppDatabase.instance.invoiceSaleDetailDao.deleteBySaleId(saleId: saleId);
}
Future<void> onAddToExisting(int productId, int quantity) async {
final productIndex = saleDetails.indexWhere((element) => element.productId == productId);
if (productIndex != -1) {
final updatedDetail = saleDetails[productIndex].copyWith(amountSale: saleDetails[productIndex].amountSale + quantity);
saleDetails[productIndex] = updatedDetail;
await AppDatabase.instance.invoiceSaleDetailDao.update(updatedDetail);
} else {
final product = await AppDatabase.instance.productDao.get(productId);
if (product != null) {
final newDetail = InvoiceSaleDetail(
measureUnit: product.unit,
amountSale: quantity,
priceSaleForOneProduct: product.sellPrice,
totalPrice: product.sellPrice * quantity,
saleId: saleId,
productId: productId,
discount: 0,
bonus: 0,
);
final id = await AppDatabase.instance.invoiceSaleDetailDao.create(newDetail);
saleDetails.add(newDetail.copyWith(id: id));
}
}
update();
}
} add methods to insert multi product and most node available of product in invontory if available it dont insert
|
e69eb24a335e99204073d29533abfd68
|
{
"intermediate": 0.31534820795059204,
"beginner": 0.48259568214416504,
"expert": 0.20205610990524292
}
|
13,185
|
Create class manager to controll in print as pdf in flutter
|
1ab105242da9d0da4c002f580514a77b
|
{
"intermediate": 0.34038105607032776,
"beginner": 0.41769853234291077,
"expert": 0.24192041158676147
}
|
13,186
|
can you make an endermite with double health
|
3cd0c6094a68ae2a1abbdcdc14f6b878
|
{
"intermediate": 0.3324952721595764,
"beginner": 0.3095657229423523,
"expert": 0.3579390048980713
}
|
13,187
|
How can I change colors on a menu using rofi?
|
c3817b216e059b56e7005fbaef859f23
|
{
"intermediate": 0.4209226369857788,
"beginner": 0.11137760430574417,
"expert": 0.46769973635673523
}
|
13,188
|
ethtool -p eno1
|
d1e0a58d226b4359a6aa43eb57dd8476
|
{
"intermediate": 0.2634564936161041,
"beginner": 0.21072052419185638,
"expert": 0.5258229970932007
}
|
13,189
|
Write mini injector in C
|
bd5661420d196bb2c32c64a45b120893
|
{
"intermediate": 0.3257175087928772,
"beginner": 0.2228766679763794,
"expert": 0.451405793428421
}
|
13,190
|
:root {
--card_width: 400px;
--row_increment: 1px;
--card_border_radius: 0px;
--card_small: 200;
--card_large: 400;
}
i have the above css. how to use javascript to modify the card_width value from 400px to 420px?
|
16d26ff75758f07b7b919d408429e4e5
|
{
"intermediate": 0.5321218371391296,
"beginner": 0.2554222643375397,
"expert": 0.21245580911636353
}
|
13,191
|
Write xorshift random number generator in assembler x86
|
144fbae720c6bf88d17a86b1ae359092
|
{
"intermediate": 0.2912349998950958,
"beginner": 0.2058151662349701,
"expert": 0.5029497742652893
}
|
13,192
|
how can I use np.select in numpy
|
4517012adab0e0c907522a3964ab715f
|
{
"intermediate": 0.46889063715934753,
"beginner": 0.22675935924053192,
"expert": 0.30435001850128174
}
|
13,193
|
Write simple demo neural network in c
|
eb3eafad2169e72ed1e4a6f707dfedca
|
{
"intermediate": 0.15398795902729034,
"beginner": 0.1301964819431305,
"expert": 0.7158156037330627
}
|
13,194
|
what would it retur for ttk.combobox.current() if none is chosen
|
22e82a91dabaee7e860284c9b882623e
|
{
"intermediate": 0.35301223397254944,
"beginner": 0.34121087193489075,
"expert": 0.30577683448791504
}
|
13,195
|
Spark sample code
|
2b8bbc030a33517bb8bc8f308f7abef5
|
{
"intermediate": 0.40124383568763733,
"beginner": 0.23759877681732178,
"expert": 0.3611574172973633
}
|
13,196
|
Spark sample code
|
c69abc5f6098162a2c09cc2626b6be26
|
{
"intermediate": 0.40124383568763733,
"beginner": 0.23759877681732178,
"expert": 0.3611574172973633
}
|
13,197
|
write a code for web scraping in python
|
9d922e98e3912fb6ed748a5623bca9ae
|
{
"intermediate": 0.42134588956832886,
"beginner": 0.19895611703395844,
"expert": 0.3796980082988739
}
|
13,198
|
use law of sines to solve this triangle: a=100m A=37.51 degrees C=24.32 degrees, what is the measure of angle B?
|
9c9ccf680eda285f2efcdf4812f82989
|
{
"intermediate": 0.3545248508453369,
"beginner": 0.30343499779701233,
"expert": 0.34204018115997314
}
|
13,199
|
下面是我的程式碼
import kuroshiro from "kuroshiro";
import KuromojiAnalyzer from "kuroshiro-analyzer-kuromoji";
const contractions = {
"i'm": "I am",
"i'll": "I will",
"you've": "You have",
"he's": "He is",
"she's": "She is",
"it's": "It is",
"we're": "We are",
"they're": "They are",
"you're": "You are",
"i'd": "I would",
"you'd": "You would",
"he'd": "He would",
"she'd": "She would",
"we'd": "We would",
"they'd": "They would",
"can't": "Cannot",
"won't": "Will not",
"don't": "Do not",
"doesn't": "Does not",
"isn't": "Is not",
"aren't": "Are not",
"wasn't": "Was not",
"weren't": "Were not",
"haven't": "Have not",
"hasn't": "Has not",
"hadn't": "Had not",
"couldn't": "Could not",
"wouldn't": "Would not",
"shouldn't": "Should not",
"mightn't": "Might not",
"mustn't": "Must not",
"let's": "Let us",
"that's": "That is",
"who's": "Who is",
"what's": "What is",
"where's": "Where is",
"when's": "When is",
"why's": "Why is",
"how's": "How is",
"she'll": "She will",
"he'll": "He will",
"it'll": "It will",
"we'll": "We will",
"they'll": "They will",
"you'll": "You will",
"that'd": "That would",
"who'd": "Who would",
"what'd": "What would",
"where'd": "Where would",
"when'd": "When would",
"why'd": "Why would",
"how'd": "How would",
"i'd've": "I would have",
"you'd've": "You would have",
"he'd've": "He would have",
"she'd've": "She would have",
"we'd've": "We would have",
"they'd've": "They would have",
"y'all": "You all",
"i'ma": "I am going to",
"i'mo": "I am going to",
"it'd've": "It would have",
"that's": "That has",
"who's": "Who has",
"what's": "What has",
"where's": "Where has",
"when's": "When has",
"why's": "Why has",
"how's": "How has",
"she's": "She has",
"he's": "He has",
"it's": "It has",
"i've": "I have",
};
function expandContractions(text, contractions) {
text = text.replace(/’/g, "'");
return text
.split(" ")
.map((word) => contractions[word.toLowerCase()] || word)
.join(" ");
}
export default async function correctWithLCS(submit, answer, lang) {
let originalAnswer, submitWords, answerWords;
if (lang === "jp") {
const kuroshiroInstance = new kuroshiro();
await kuroshiroInstance.init(new KuromojiAnalyzer({ dictPath: "/dict" }));
originalAnswer = Array.from(answer);
submit = await kuroshiroInstance.convert(submit, { to: "hiragana" });
answer = await kuroshiroInstance.convert(answer, { to: "hiragana" });
submitWords = Array.from(
submit.toLowerCase().replace(/[\s。、,「」!?……——・]/g, "")
);
answerWords = Array.from(
answer.toLowerCase().replace(/[\s。、,「」!?……——・]/g, "")
);
} else {
let expandedSubmit = expandContractions(submit, contractions);
let expandedAnswer = expandContractions(answer, contractions);
originalAnswer = answer.split(" ");
submitWords = expandedSubmit
.toLowerCase()
.replace(/[.,\/#!?$%\^&\*;:{}=\-_`~()]/g, "")
.split(" ");
answerWords = expandedAnswer
.toLowerCase()
.replace(/[.,\/#!?$%\^&\*;:{}=\-_`~()]/g, "")
.split(" ");
}
const [m, n] = [submitWords.length, answerWords.length];
const dp = new Array(m);
for (let i = 0; i < m; ++i) {
dp[i] = new Array(n);
dp[i].fill(0);
}
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (i == 0 && j == 0) {
dp[i][j] = submitWords[0] == answerWords[0] ? 1 : 0;
} else if (i == 0) {
dp[0][j] = submitWords[0] == answerWords[j] ? 1 : dp[0][j - 1];
} else if (j == 0) {
dp[i][0] = submitWords[i] == answerWords[0] ? 1 : dp[i - 1][0];
} else {
dp[i][j] =
submitWords[i] == answerWords[j]
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
let res = answerWords.map((e, idx) => ({
word: originalAnswer[idx],
correct: false,
}));
let [i, j, tmp] = [m - 1, n - 1, undefined];
while (dp[i][j] != 0) {
tmp = [i, j, dp[i][j]];
if (i == 0 && j == 0) {
res[0].correct = true;
break;
} else if (i == 0) {
--j;
} else if (j == 0) {
--i;
} else {
if (submitWords[i] == answerWords[j]) {
--i, --j;
} else if (dp[i - 1][j] < dp[i][j - 1]) {
--j;
} else {
--i;
}
}
if (tmp[2] - dp[i][j] == 1) {
res[tmp[1]].correct = true;
}
}
console.assert(
res.reduce((acc, curr) => (curr.correct ? ++acc : acc), 0) ==
dp[m - 1][n - 1],
"something wrong"
);
const acc = ((dp[m - 1][n - 1] / answerWords.length) * 100).toFixed(2);
return { accuracy: acc, result: res };
}
當 answer 是 The current vogue in the fashion industry presents some intriguing elements. What's your preferred sartorial style? ,submit 是 The current vogue in the fashion industry presents some intriguing elements. What is your preferred sartorial style?
但最後 result 的 The current vogue in the fashion industry presents some intriguing elements. What's your preferred sartorial style? 的 "your" 會被判斷錯誤,可以幫我調整一下程式碼嗎
|
02978e8f1cf91bbf3d61574e53202c5d
|
{
"intermediate": 0.30149006843566895,
"beginner": 0.42417699098587036,
"expert": 0.2743329703807831
}
|
13,200
|
import React, {useCallback, useEffect, useRef, useState} from “react”;
import {
init,
dispose,
Chart,
IndicatorFigureStylesCallbackData,
Indicator,
IndicatorStyle,
KLineData,
utils,
ActionType,
} from “klinecharts”;
import {CandleChartProps} from “./CandleChart.props”;
import CandleChartToolbar from “./CandleChartToolbar”;
import {Box, Button, ButtonGroup, CircularProgress, Icon, IconButton, Stack, useTheme} from “@mui/material”;
import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”;
import drawTrade from “./utils/drawTrade.util”;
import drawTradeLines from “./utils/drawTradeLines.util”;
import {BasketIcon, ScreenIcon} from “…/…/icons”;
import {FullScreen, useFullScreenHandle} from “react-full-screen”;
import dayjs from “dayjs”;
import {fetchSymbolsKlines} from “…/…/…/actions/binance”;
import {useSnackbar} from “notistack”;
import {useSelector} from “react-redux”;
import {AppState} from “…/…/…/store/store”;
import useComponentResizeListener from “…/…/…/hooks/componentResizeListener”;
import {chartStyles} from “./ChartStyles”;
interface Vol {
volume?: number
}
export const CandleChart = ({
candles,
uniqueId,
symbolName,
orders,
amount,
openPrice,
closePrice,
onScreenshotCreated,
chartInterval,
setChartInterval,
waiting,
setWaiting,
height,
showIntervalSelector,
}: CandleChartProps) => {
const chart = useRef<Chart|null>(null);
const paneId = useRef<string>(“”);
const [figureId, setFigureId] = useState<string>(“”);
const ref = useRef<HTMLDivElement>(null);
const handle = useFullScreenHandle();
const {enqueueSnackbar} = useSnackbar();
const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbolName.toUpperCase()]);
const kline = useSelector((state: AppState) => state.binanceKline.futures[${symbolName.toLocaleLowerCase()}@kline_${chartInterval}]) || null;
const size = useComponentResizeListener(ref);
const theme = useTheme();
const darkMode = theme.palette.mode === “dark”;
const chartResize = useCallback(() => {
if (null !== chart.current) {
chart.current.resize();
}
}, [chart.current]);
useEffect(() => {
if (precision && null !== chart.current) {
chart.current.setPriceVolumePrecision(precision?.price || 4, precision?.quantity || 2);
}
}, [chart.current, precision]);
useEffect(() => {
if (kline && null !== chart.current) {
chart.current.updateData(kline);
}
}, [kline, chart.current]);
useEffect(() => {
chartResize();
}, [size]);
useEffect(() => {
// @ts-ignore
chart.current = init(chart-${uniqueId}, {styles: chartStyles(theme)});
return () => dispose(chart-${uniqueId});
}, [uniqueId]);
useEffect(() => {
if (chart.current) {
chart.current.setStyles({
grid: {
horizontal: {
color: theme.palette.grey[50],
},
vertical: {
color: theme.palette.grey[50],
},
},
xAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
yAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
separator: {
color: theme.palette.grey[50],
},
});
}
}, [theme]);
useEffect(() => {
if (null !== chart.current) {
window.addEventListener(“resize”, chartResize);
}
return () => window.removeEventListener(“resize”, chartResize);
}, []);
useEffect(() => {
chart.current?.applyNewData(candles);
chart.current?.overrideIndicator({
name: “VOL”,
shortName: “Объем”,
calcParams: [],
figures: [
{
key: “volume”,
title: “”,
type: “bar”,
baseValue: 0,
styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => {
const kLineData = data.current.kLineData as KLineData;
let color: string;
if (kLineData.close > kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string;
} else if (kLineData.close < kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string;
} else {
color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string;
}
return {color};
},
},
],
}, paneId.current);
chart.current?.createIndicator(“VOL”, false, {id: paneId.current});
}, [candles]);
useEffect(() => {
if (!orders || orders.length === 0 || candles.length === 0 || !amount || amount.length === 0) return;
const minTime = orders[0].time;
const maxTime = orders[orders.length - 1].time;
const needleTime = minTime + (maxTime - minTime) / 2;
chart.current?.scrollToTimestamp(needleTime + 50 * getMinutesTickSizeByInterval(chartInterval) * 60 * 1000);
drawTrade(chart, paneId, orders, chartInterval, amount);
if (openPrice && closePrice) {
let openTime = Infinity;
let closeTime = -Infinity;
orders.forEach(order => {
if (openTime > order.time) {
openTime = order.time;
}
if (closeTime < order.time) {
closeTime = order.time;
}
});
drawTradeLines(
chart,
openPrice,
openTime,
closePrice,
closeTime,
orders[0].position,
paneId,
precision.price,
precision.quantity,
);
}
}, [orders, candles, uniqueId]);
const removeFigure = () => {
chart.current?.removeOverlay({
id: figureId,
});
setFigureId(“”);
};
const onButtonClick = async() => {
const url = chart.current?.getConvertPictureUrl(true);
if (!url || !onScreenshotCreated) {
return;
}
onScreenshotCreated(url);
};
useEffect(() => {
if (candles.length === 0) return;
chart.current?.subscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
return (() => {
chart.current?.unsubscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
});
}, [chart.current, candles]);
let isLoading = false;
let onScrollbarPositionChanged = () => {
const chartWidth = chart.current?.getSize()?.width;
const barSpace = chart.current?.getBarSpace();
const rightDistance = chart.current?.getOffsetRightDistance();
const dataList = chart.current?.getDataList();
const from = chart.current?.getVisibleRange().realFrom;
if (!dataList || isLoading || !chartWidth || !barSpace) return;
if (rightDistance) {
if (0 < rightDistance && rightDistance !== 50) {
let startTime = dataList[dataList.length - 1].timestamp;
if (isLastCandleToday(startTime, chartInterval)) return;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, startTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
isLoading = false;
setWaiting(false);
return;
} else {
const newData = […dataList, …newCandles];
chart.current?.applyNewData(newData, true);
const newRightDistance = (-barSpace * newCandles.length) + rightDistance;
chart.current?.setOffsetRightDistance(newRightDistance + 140);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
}
if (from === 0) {
let endTime = dataList[0].timestamp;
let prevTime: number | null = null;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, undefined, endTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
return;
} else {
if (prevTime === newCandles[newCandles.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
if (newCandles[newCandles.length - 1].timestamp === dataList[dataList.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
prevTime = newCandles[newCandles.length - 1].timestamp;
chart.current?.applyMoreData(newCandles);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
};
const isLastCandleToday = (lastCandleTimestamp: number, interval: string) => {
const lastCandleDate = dayjs(lastCandleTimestamp);
const today = dayjs();
if (interval.includes(“m”) || interval.includes(“h”) || interval.includes(“d”)) {
return lastCandleDate.isSame(today, “day”);
}
return false;
};
return (<>
<FullScreen handle={handle}>
<Box height=“100%” sx={{borderRadius: “1rem”, position: “relative”, background: theme => theme.palette.background.paper}}>
{
showIntervalSelector &&
<Stack sx={{
padding: “0 5px”, width: “100%”, height: 40,
justifyContent: “space-between”, flexDirection: “row”, borderBottom: theme => 2px solid ${theme.palette.grey[50]},
}}>
<ButtonGroup>
{
[“1m”, “3m”, “5m”, “15m”, “30m”, “1h”, “4h”, “12h”, “1d”].map(interval => (
<Button
key={interval}
color=“inherit”
sx={{px: 1, py: .5,
color: interval === chartInterval ? darkMode ? “#fff” : “#677294” : “#999999”,
fontSize: “.75rem”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”},
}}
variant={“text”}
onClick={() => setChartInterval && setChartInterval(interval)}
>{interval}</Button>
))
}
</ButtonGroup>
<IconButton sx={{borderRadius: 2, fontFamily: “Mont”, mr: 1, color: darkMode ? “#999” : “#677294”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={onButtonClick}>
<Icon sx={{width: 90}} component={ScreenIcon} />
</IconButton>
</Stack>
}
{
waiting ? (
<CircularProgress
style={{position: “absolute”, marginLeft: “1rem”}}
color=“inherit”
size={32}
/>
) : (<></>)
}
<Stack direction=“row” height={height && !handle.active ? 550 : “100%” || “calc(100% - 140px)”} width=“100%”>
<CandleChartToolbar
setFigureId={setFigureId}
chart={chart}
paneId={paneId}
handle={handle}
/>
<Box
ref={ref}
id={chart-${uniqueId}}
width=“calc(100% - 55px)”
height=“100%”
sx={{borderLeft: theme => 2px solid ${theme.palette.grey[50]}}}
>
{
figureId.length > 0 &&
<Stack
sx={{
backgroundColor: darkMode ? “#474747” : “#CBD4E3”,
borderRadius: 1,
position: “absolute”,
zIndex: 10,
right: 80,
top: 30,
border: theme => 2px solid ${theme.palette.grey[50]},
}}
spacing={2}
>
<IconButton sx={{borderRadius: 1}} onClick={removeFigure}>
<Icon component={BasketIcon} />
</IconButton>
</Stack>
}
</Box>
</Stack>
</Box>
</FullScreen>
</>);
};
CandleChart.displayName = “CandleChart”;
import {Icon, IconButton, Stack, useTheme} from “@mui/material”;
import {BasketIcon, FullScreenIcon} from “…/…/icons”;
import React from “react”;
import {CandleChartToolbarProps} from “./CandleChartToolbar.props”;
import RectTool from “./Tools/RectTool”;
import FibonacciLineTool from “./Tools/FibonacciLineTool”;
import HorizontalStraightLineTool from “./Tools/HorizontalStraightLineTool”;
import ParallelStraightLineTool from “./Tools/ParallelStraightLineTool”;
import RayLineTool from “./Tools/RayLineTool”;
import PriceLineTool from “./Tools/PriceLineTool”;
import SegmentTool from “./Tools/SegmentTool”;
import StraightLineTool from “./Tools/StraightLineTool”;
import RulerTool from “./Tools/RulerTool”;
const CandleChartToolbar = ({chart, paneId, setFigureId, handle}: CandleChartToolbarProps) => {
const darkMode = useTheme().palette.mode === “dark”;
const removeOverlay = () => {
chart.current?.removeOverlay();
setFigureId(“”);
};
const fullScreenHandle = () => {
if(handle.active) {
handle.exit();
} else {
handle.enter();
}
};
return <>
<Stack
className=“scroll-block”
direction=“column”
alignItems=“center”
spacing={1}
sx={{
width: “55px”,
height: “100%”,
overflowY: “scroll”,
scrollbarWidth: “thin”,
“&::-webkit-scrollbar”: {
width: “8px”,
},
“&::-webkit-scrollbar-track”: {
background: theme => theme.palette.background.paper,
},
“&::-webkit-scrollbar-thumb”: {
backgroundColor: theme => theme.palette.grey[300],
border: theme => 3px solid ${theme.palette.white.main},
},
}}
>
<PriceLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<HorizontalStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RayLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<SegmentTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<StraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<ParallelStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<FibonacciLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RulerTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RectTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} style={{height: 40}} onClick={fullScreenHandle}>
<Icon component={FullScreenIcon} sx={{height: 18}} />
</IconButton>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={removeOverlay}>
<Icon component={BasketIcon}/>
</IconButton>
</Stack>
</>;
};
export default CandleChartToolbar;
Мы рисуем фигуры, которые рисуем в CandleChartToolbar
нужно сделать сохранение того, что ты нарисовал в localStorage
|
8d014a092a21502e2e0ebd9c439895a0
|
{
"intermediate": 0.33216920495033264,
"beginner": 0.43792814016342163,
"expert": 0.22990262508392334
}
|
13,201
|
import React, {useCallback, useEffect, useRef, useState} from “react”;
import {
init,
dispose,
Chart,
IndicatorFigureStylesCallbackData,
Indicator,
IndicatorStyle,
KLineData,
utils,
ActionType,
} from “klinecharts”;
import {CandleChartProps} from “./CandleChart.props”;
import CandleChartToolbar from “./CandleChartToolbar”;
import {Box, Button, ButtonGroup, CircularProgress, Icon, IconButton, Stack, useTheme} from “@mui/material”;
import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”;
import drawTrade from “./utils/drawTrade.util”;
import drawTradeLines from “./utils/drawTradeLines.util”;
import {BasketIcon, ScreenIcon} from “…/…/icons”;
import {FullScreen, useFullScreenHandle} from “react-full-screen”;
import dayjs from “dayjs”;
import {fetchSymbolsKlines} from “…/…/…/actions/binance”;
import {useSnackbar} from “notistack”;
import {useSelector} from “react-redux”;
import {AppState} from “…/…/…/store/store”;
import useComponentResizeListener from “…/…/…/hooks/componentResizeListener”;
import {chartStyles} from “./ChartStyles”;
interface Vol {
volume?: number
}
export const CandleChart = ({
candles,
uniqueId,
symbolName,
orders,
amount,
openPrice,
closePrice,
onScreenshotCreated,
chartInterval,
setChartInterval,
waiting,
setWaiting,
height,
showIntervalSelector,
}: CandleChartProps) => {
const chart = useRef<Chart|null>(null);
const paneId = useRef<string>(“”);
const [figureId, setFigureId] = useState<string>(“”);
const ref = useRef<HTMLDivElement>(null);
const handle = useFullScreenHandle();
const {enqueueSnackbar} = useSnackbar();
const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbolName.toUpperCase()]);
const kline = useSelector((state: AppState) => state.binanceKline.futures[${symbolName.toLocaleLowerCase()}@kline_${chartInterval}]) || null;
const size = useComponentResizeListener(ref);
const theme = useTheme();
const darkMode = theme.palette.mode === “dark”;
const chartResize = useCallback(() => {
if (null !== chart.current) {
chart.current.resize();
}
}, [chart.current]);
useEffect(() => {
if (precision && null !== chart.current) {
chart.current.setPriceVolumePrecision(precision?.price || 4, precision?.quantity || 2);
}
}, [chart.current, precision]);
useEffect(() => {
if (kline && null !== chart.current) {
chart.current.updateData(kline);
}
}, [kline, chart.current]);
useEffect(() => {
chartResize();
}, [size]);
useEffect(() => {
// @ts-ignore
chart.current = init(chart-${uniqueId}, {styles: chartStyles(theme)});
return () => dispose(chart-${uniqueId});
}, [uniqueId]);
useEffect(() => {
if (chart.current) {
chart.current.setStyles({
grid: {
horizontal: {
color: theme.palette.grey[50],
},
vertical: {
color: theme.palette.grey[50],
},
},
xAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
yAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
separator: {
color: theme.palette.grey[50],
},
});
}
}, [theme]);
useEffect(() => {
if (null !== chart.current) {
window.addEventListener(“resize”, chartResize);
}
return () => window.removeEventListener(“resize”, chartResize);
}, []);
useEffect(() => {
chart.current?.applyNewData(candles);
chart.current?.overrideIndicator({
name: “VOL”,
shortName: “Объем”,
calcParams: [],
figures: [
{
key: “volume”,
title: “”,
type: “bar”,
baseValue: 0,
styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => {
const kLineData = data.current.kLineData as KLineData;
let color: string;
if (kLineData.close > kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string;
} else if (kLineData.close < kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string;
} else {
color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string;
}
return {color};
},
},
],
}, paneId.current);
chart.current?.createIndicator(“VOL”, false, {id: paneId.current});
}, [candles]);
useEffect(() => {
if (!orders || orders.length === 0 || candles.length === 0 || !amount || amount.length === 0) return;
const minTime = orders[0].time;
const maxTime = orders[orders.length - 1].time;
const needleTime = minTime + (maxTime - minTime) / 2;
chart.current?.scrollToTimestamp(needleTime + 50 * getMinutesTickSizeByInterval(chartInterval) * 60 * 1000);
drawTrade(chart, paneId, orders, chartInterval, amount);
if (openPrice && closePrice) {
let openTime = Infinity;
let closeTime = -Infinity;
orders.forEach(order => {
if (openTime > order.time) {
openTime = order.time;
}
if (closeTime < order.time) {
closeTime = order.time;
}
});
drawTradeLines(
chart,
openPrice,
openTime,
closePrice,
closeTime,
orders[0].position,
paneId,
precision.price,
precision.quantity,
);
}
}, [orders, candles, uniqueId]);
const removeFigure = () => {
chart.current?.removeOverlay({
id: figureId,
});
setFigureId(“”);
};
const onButtonClick = async() => {
const url = chart.current?.getConvertPictureUrl(true);
if (!url || !onScreenshotCreated) {
return;
}
onScreenshotCreated(url);
};
useEffect(() => {
if (candles.length === 0) return;
chart.current?.subscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
return (() => {
chart.current?.unsubscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
});
}, [chart.current, candles]);
let isLoading = false;
let onScrollbarPositionChanged = () => {
const chartWidth = chart.current?.getSize()?.width;
const barSpace = chart.current?.getBarSpace();
const rightDistance = chart.current?.getOffsetRightDistance();
const dataList = chart.current?.getDataList();
const from = chart.current?.getVisibleRange().realFrom;
if (!dataList || isLoading || !chartWidth || !barSpace) return;
if (rightDistance) {
if (0 < rightDistance && rightDistance !== 50) {
let startTime = dataList[dataList.length - 1].timestamp;
if (isLastCandleToday(startTime, chartInterval)) return;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, startTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
isLoading = false;
setWaiting(false);
return;
} else {
const newData = […dataList, …newCandles];
chart.current?.applyNewData(newData, true);
const newRightDistance = (-barSpace * newCandles.length) + rightDistance;
chart.current?.setOffsetRightDistance(newRightDistance + 140);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
}
if (from === 0) {
let endTime = dataList[0].timestamp;
let prevTime: number | null = null;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, undefined, endTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
return;
} else {
if (prevTime === newCandles[newCandles.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
if (newCandles[newCandles.length - 1].timestamp === dataList[dataList.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
prevTime = newCandles[newCandles.length - 1].timestamp;
chart.current?.applyMoreData(newCandles);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
};
const isLastCandleToday = (lastCandleTimestamp: number, interval: string) => {
const lastCandleDate = dayjs(lastCandleTimestamp);
const today = dayjs();
if (interval.includes(“m”) || interval.includes(“h”) || interval.includes(“d”)) {
return lastCandleDate.isSame(today, “day”);
}
return false;
};
return (<>
<FullScreen handle={handle}>
<Box height=“100%” sx={{borderRadius: “1rem”, position: “relative”, background: theme => theme.palette.background.paper}}>
{
showIntervalSelector &&
<Stack sx={{
padding: “0 5px”, width: “100%”, height: 40,
justifyContent: “space-between”, flexDirection: “row”, borderBottom: theme => 2px solid ${theme.palette.grey[50]},
}}>
<ButtonGroup>
{
[“1m”, “3m”, “5m”, “15m”, “30m”, “1h”, “4h”, “12h”, “1d”].map(interval => (
<Button
key={interval}
color=“inherit”
sx={{px: 1, py: .5,
color: interval === chartInterval ? darkMode ? “#fff” : “#677294” : “#999999”,
fontSize: “.75rem”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”},
}}
variant={“text”}
onClick={() => setChartInterval && setChartInterval(interval)}
>{interval}</Button>
))
}
</ButtonGroup>
<IconButton sx={{borderRadius: 2, fontFamily: “Mont”, mr: 1, color: darkMode ? “#999” : “#677294”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={onButtonClick}>
<Icon sx={{width: 90}} component={ScreenIcon} />
</IconButton>
</Stack>
}
{
waiting ? (
<CircularProgress
style={{position: “absolute”, marginLeft: “1rem”}}
color=“inherit”
size={32}
/>
) : (<></>)
}
<Stack direction=“row” height={height && !handle.active ? 550 : “100%” || “calc(100% - 140px)”} width=“100%”>
<CandleChartToolbar
setFigureId={setFigureId}
chart={chart}
paneId={paneId}
handle={handle}
/>
<Box
ref={ref}
id={chart-${uniqueId}}
width=“calc(100% - 55px)”
height=“100%”
sx={{borderLeft: theme => 2px solid ${theme.palette.grey[50]}}}
>
{
figureId.length > 0 &&
<Stack
sx={{
backgroundColor: darkMode ? “#474747” : “#CBD4E3”,
borderRadius: 1,
position: “absolute”,
zIndex: 10,
right: 80,
top: 30,
border: theme => 2px solid ${theme.palette.grey[50]},
}}
spacing={2}
>
<IconButton sx={{borderRadius: 1}} onClick={removeFigure}>
<Icon component={BasketIcon} />
</IconButton>
</Stack>
}
</Box>
</Stack>
</Box>
</FullScreen>
</>);
};
CandleChart.displayName = “CandleChart”;
import {Icon, IconButton, Stack, useTheme} from “@mui/material”;
import {BasketIcon, FullScreenIcon} from “…/…/icons”;
import React from “react”;
import {CandleChartToolbarProps} from “./CandleChartToolbar.props”;
import RectTool from “./Tools/RectTool”;
import FibonacciLineTool from “./Tools/FibonacciLineTool”;
import HorizontalStraightLineTool from “./Tools/HorizontalStraightLineTool”;
import ParallelStraightLineTool from “./Tools/ParallelStraightLineTool”;
import RayLineTool from “./Tools/RayLineTool”;
import PriceLineTool from “./Tools/PriceLineTool”;
import SegmentTool from “./Tools/SegmentTool”;
import StraightLineTool from “./Tools/StraightLineTool”;
import RulerTool from “./Tools/RulerTool”;
const CandleChartToolbar = ({chart, paneId, setFigureId, handle}: CandleChartToolbarProps) => {
const darkMode = useTheme().palette.mode === “dark”;
const removeOverlay = () => {
chart.current?.removeOverlay();
setFigureId(“”);
};
const fullScreenHandle = () => {
if(handle.active) {
handle.exit();
} else {
handle.enter();
}
};
return <>
<Stack
className=“scroll-block”
direction=“column”
alignItems=“center”
spacing={1}
sx={{
width: “55px”,
height: “100%”,
overflowY: “scroll”,
scrollbarWidth: “thin”,
“&::-webkit-scrollbar”: {
width: “8px”,
},
“&::-webkit-scrollbar-track”: {
background: theme => theme.palette.background.paper,
},
“&::-webkit-scrollbar-thumb”: {
backgroundColor: theme => theme.palette.grey[300],
border: theme => 3px solid ${theme.palette.white.main},
},
}}
>
<PriceLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<HorizontalStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RayLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<SegmentTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<StraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<ParallelStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<FibonacciLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RulerTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RectTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} style={{height: 40}} onClick={fullScreenHandle}>
<Icon component={FullScreenIcon} sx={{height: 18}} />
</IconButton>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={removeOverlay}>
<Icon component={BasketIcon}/>
</IconButton>
</Stack>
</>;
};
export default CandleChartToolbar;
Мы рисуем фигуры, которые отрисовываем в CandleChartToolbar
нужно сделать сохранение того, что ты нарисовал в localStorage
|
9aa9520f0668d43dd51c12051d8ae252
|
{
"intermediate": 0.33216920495033264,
"beginner": 0.43792814016342163,
"expert": 0.22990262508392334
}
|
13,202
|
import React, {useCallback, useEffect, useRef, useState} from “react”;
import {
init,
dispose,
Chart,
IndicatorFigureStylesCallbackData,
Indicator,
IndicatorStyle,
KLineData,
utils,
ActionType,
} from “klinecharts”;
import {CandleChartProps} from “./CandleChart.props”;
import CandleChartToolbar from “./CandleChartToolbar”;
import {Box, Button, ButtonGroup, CircularProgress, Icon, IconButton, Stack, useTheme} from “@mui/material”;
import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”;
import drawTrade from “./utils/drawTrade.util”;
import drawTradeLines from “./utils/drawTradeLines.util”;
import {BasketIcon, ScreenIcon} from “…/…/icons”;
import {FullScreen, useFullScreenHandle} from “react-full-screen”;
import dayjs from “dayjs”;
import {fetchSymbolsKlines} from “…/…/…/actions/binance”;
import {useSnackbar} from “notistack”;
import {useSelector} from “react-redux”;
import {AppState} from “…/…/…/store/store”;
import useComponentResizeListener from “…/…/…/hooks/componentResizeListener”;
import {chartStyles} from “./ChartStyles”;
interface Vol {
volume?: number
}
export const CandleChart = ({
candles,
uniqueId,
symbolName,
orders,
amount,
openPrice,
closePrice,
onScreenshotCreated,
chartInterval,
setChartInterval,
waiting,
setWaiting,
height,
showIntervalSelector,
}: CandleChartProps) => {
const chart = useRef<Chart|null>(null);
const paneId = useRef<string>(“”);
const [figureId, setFigureId] = useState<string>(“”);
const ref = useRef<HTMLDivElement>(null);
const handle = useFullScreenHandle();
const {enqueueSnackbar} = useSnackbar();
const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbolName.toUpperCase()]);
const kline = useSelector((state: AppState) => state.binanceKline.futures[${symbolName.toLocaleLowerCase()}@kline_${chartInterval}]) || null;
const size = useComponentResizeListener(ref);
const theme = useTheme();
const darkMode = theme.palette.mode === “dark”;
const chartResize = useCallback(() => {
if (null !== chart.current) {
chart.current.resize();
}
}, [chart.current]);
useEffect(() => {
if (precision && null !== chart.current) {
chart.current.setPriceVolumePrecision(precision?.price || 4, precision?.quantity || 2);
}
}, [chart.current, precision]);
useEffect(() => {
if (kline && null !== chart.current) {
chart.current.updateData(kline);
}
}, [kline, chart.current]);
useEffect(() => {
chartResize();
}, [size]);
useEffect(() => {
// @ts-ignore
chart.current = init(chart-${uniqueId}, {styles: chartStyles(theme)});
return () => dispose(chart-${uniqueId});
}, [uniqueId]);
useEffect(() => {
if (chart.current) {
chart.current.setStyles({
grid: {
horizontal: {
color: theme.palette.grey[50],
},
vertical: {
color: theme.palette.grey[50],
},
},
xAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
yAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
separator: {
color: theme.palette.grey[50],
},
});
}
}, [theme]);
useEffect(() => {
if (null !== chart.current) {
window.addEventListener(“resize”, chartResize);
}
return () => window.removeEventListener(“resize”, chartResize);
}, []);
useEffect(() => {
chart.current?.applyNewData(candles);
chart.current?.overrideIndicator({
name: “VOL”,
shortName: “Объем”,
calcParams: [],
figures: [
{
key: “volume”,
title: “”,
type: “bar”,
baseValue: 0,
styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => {
const kLineData = data.current.kLineData as KLineData;
let color: string;
if (kLineData.close > kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string;
} else if (kLineData.close < kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string;
} else {
color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string;
}
return {color};
},
},
],
}, paneId.current);
chart.current?.createIndicator(“VOL”, false, {id: paneId.current});
}, [candles]);
useEffect(() => {
if (!orders || orders.length === 0 || candles.length === 0 || !amount || amount.length === 0) return;
const minTime = orders[0].time;
const maxTime = orders[orders.length - 1].time;
const needleTime = minTime + (maxTime - minTime) / 2;
chart.current?.scrollToTimestamp(needleTime + 50 * getMinutesTickSizeByInterval(chartInterval) * 60 * 1000);
drawTrade(chart, paneId, orders, chartInterval, amount);
if (openPrice && closePrice) {
let openTime = Infinity;
let closeTime = -Infinity;
orders.forEach(order => {
if (openTime > order.time) {
openTime = order.time;
}
if (closeTime < order.time) {
closeTime = order.time;
}
});
drawTradeLines(
chart,
openPrice,
openTime,
closePrice,
closeTime,
orders[0].position,
paneId,
precision.price,
precision.quantity,
);
}
}, [orders, candles, uniqueId]);
const removeFigure = () => {
chart.current?.removeOverlay({
id: figureId,
});
setFigureId(“”);
};
const onButtonClick = async() => {
const url = chart.current?.getConvertPictureUrl(true);
if (!url || !onScreenshotCreated) {
return;
}
onScreenshotCreated(url);
};
useEffect(() => {
if (candles.length === 0) return;
chart.current?.subscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
return (() => {
chart.current?.unsubscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
});
}, [chart.current, candles]);
let isLoading = false;
let onScrollbarPositionChanged = () => {
const chartWidth = chart.current?.getSize()?.width;
const barSpace = chart.current?.getBarSpace();
const rightDistance = chart.current?.getOffsetRightDistance();
const dataList = chart.current?.getDataList();
const from = chart.current?.getVisibleRange().realFrom;
if (!dataList || isLoading || !chartWidth || !barSpace) return;
if (rightDistance) {
if (0 < rightDistance && rightDistance !== 50) {
let startTime = dataList[dataList.length - 1].timestamp;
if (isLastCandleToday(startTime, chartInterval)) return;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, startTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
isLoading = false;
setWaiting(false);
return;
} else {
const newData = […dataList, …newCandles];
chart.current?.applyNewData(newData, true);
const newRightDistance = (-barSpace * newCandles.length) + rightDistance;
chart.current?.setOffsetRightDistance(newRightDistance + 140);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
}
if (from === 0) {
let endTime = dataList[0].timestamp;
let prevTime: number | null = null;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, undefined, endTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
return;
} else {
if (prevTime === newCandles[newCandles.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
if (newCandles[newCandles.length - 1].timestamp === dataList[dataList.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
prevTime = newCandles[newCandles.length - 1].timestamp;
chart.current?.applyMoreData(newCandles);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
};
const isLastCandleToday = (lastCandleTimestamp: number, interval: string) => {
const lastCandleDate = dayjs(lastCandleTimestamp);
const today = dayjs();
if (interval.includes(“m”) || interval.includes(“h”) || interval.includes(“d”)) {
return lastCandleDate.isSame(today, “day”);
}
return false;
};
return (<>
<FullScreen handle={handle}>
<Box height=“100%” sx={{borderRadius: “1rem”, position: “relative”, background: theme => theme.palette.background.paper}}>
{
showIntervalSelector &&
<Stack sx={{
padding: “0 5px”, width: “100%”, height: 40,
justifyContent: “space-between”, flexDirection: “row”, borderBottom: theme => 2px solid ${theme.palette.grey[50]},
}}>
<ButtonGroup>
{
[“1m”, “3m”, “5m”, “15m”, “30m”, “1h”, “4h”, “12h”, “1d”].map(interval => (
<Button
key={interval}
color=“inherit”
sx={{px: 1, py: .5,
color: interval === chartInterval ? darkMode ? “#fff” : “#677294” : “#999999”,
fontSize: “.75rem”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”},
}}
variant={“text”}
onClick={() => setChartInterval && setChartInterval(interval)}
>{interval}</Button>
))
}
</ButtonGroup>
<IconButton sx={{borderRadius: 2, fontFamily: “Mont”, mr: 1, color: darkMode ? “#999” : “#677294”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={onButtonClick}>
<Icon sx={{width: 90}} component={ScreenIcon} />
</IconButton>
</Stack>
}
{
waiting ? (
<CircularProgress
style={{position: “absolute”, marginLeft: “1rem”}}
color=“inherit”
size={32}
/>
) : (<></>)
}
<Stack direction=“row” height={height && !handle.active ? 550 : “100%” || “calc(100% - 140px)”} width=“100%”>
<CandleChartToolbar
setFigureId={setFigureId}
chart={chart}
paneId={paneId}
handle={handle}
/>
<Box
ref={ref}
id={chart-${uniqueId}}
width=“calc(100% - 55px)”
height=“100%”
sx={{borderLeft: theme => 2px solid ${theme.palette.grey[50]}}}
>
{
figureId.length > 0 &&
<Stack
sx={{
backgroundColor: darkMode ? “#474747” : “#CBD4E3”,
borderRadius: 1,
position: “absolute”,
zIndex: 10,
right: 80,
top: 30,
border: theme => 2px solid ${theme.palette.grey[50]},
}}
spacing={2}
>
<IconButton sx={{borderRadius: 1}} onClick={removeFigure}>
<Icon component={BasketIcon} />
</IconButton>
</Stack>
}
</Box>
</Stack>
</Box>
</FullScreen>
</>);
};
CandleChart.displayName = “CandleChart”;
import {Icon, IconButton, Stack, useTheme} from “@mui/material”;
import {BasketIcon, FullScreenIcon} from “…/…/icons”;
import React from “react”;
import {CandleChartToolbarProps} from “./CandleChartToolbar.props”;
import RectTool from “./Tools/RectTool”;
import FibonacciLineTool from “./Tools/FibonacciLineTool”;
import HorizontalStraightLineTool from “./Tools/HorizontalStraightLineTool”;
import ParallelStraightLineTool from “./Tools/ParallelStraightLineTool”;
import RayLineTool from “./Tools/RayLineTool”;
import PriceLineTool from “./Tools/PriceLineTool”;
import SegmentTool from “./Tools/SegmentTool”;
import StraightLineTool from “./Tools/StraightLineTool”;
import RulerTool from “./Tools/RulerTool”;
const CandleChartToolbar = ({chart, paneId, setFigureId, handle}: CandleChartToolbarProps) => {
const darkMode = useTheme().palette.mode === “dark”;
const removeOverlay = () => {
chart.current?.removeOverlay();
setFigureId(“”);
};
const fullScreenHandle = () => {
if(handle.active) {
handle.exit();
} else {
handle.enter();
}
};
return <>
<Stack
className=“scroll-block”
direction=“column”
alignItems=“center”
spacing={1}
sx={{
width: “55px”,
height: “100%”,
overflowY: “scroll”,
scrollbarWidth: “thin”,
“&::-webkit-scrollbar”: {
width: “8px”,
},
“&::-webkit-scrollbar-track”: {
background: theme => theme.palette.background.paper,
},
“&::-webkit-scrollbar-thumb”: {
backgroundColor: theme => theme.palette.grey[300],
border: theme => 3px solid ${theme.palette.white.main},
},
}}
>
<PriceLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<HorizontalStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RayLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<SegmentTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<StraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<ParallelStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<FibonacciLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RulerTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RectTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} style={{height: 40}} onClick={fullScreenHandle}>
<Icon component={FullScreenIcon} sx={{height: 18}} />
</IconButton>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={removeOverlay}>
<Icon component={BasketIcon}/>
</IconButton>
</Stack>
</>;
};
export default CandleChartToolbar;
Мы рисуем фигуры, которые отрисовываем в CandleChartToolbar
нужно сделать сохранение того, что ты нарисовал в localStorage
|
3518b5ff78383e812eec8944590d1a6f
|
{
"intermediate": 0.33216920495033264,
"beginner": 0.43792814016342163,
"expert": 0.22990262508392334
}
|
13,203
|
import React, {useCallback, useEffect, useRef, useState} from “react”;
import {
init,
dispose,
Chart,
IndicatorFigureStylesCallbackData,
Indicator,
IndicatorStyle,
KLineData,
utils,
ActionType,
} from “klinecharts”;
import {CandleChartProps} from “./CandleChart.props”;
import CandleChartToolbar from “./CandleChartToolbar”;
import {Box, Button, ButtonGroup, CircularProgress, Icon, IconButton, Stack, useTheme} from “@mui/material”;
import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”;
import drawTrade from “./utils/drawTrade.util”;
import drawTradeLines from “./utils/drawTradeLines.util”;
import {BasketIcon, ScreenIcon} from “…/…/icons”;
import {FullScreen, useFullScreenHandle} from “react-full-screen”;
import dayjs from “dayjs”;
import {fetchSymbolsKlines} from “…/…/…/actions/binance”;
import {useSnackbar} from “notistack”;
import {useSelector} from “react-redux”;
import {AppState} from “…/…/…/store/store”;
import useComponentResizeListener from “…/…/…/hooks/componentResizeListener”;
import {chartStyles} from “./ChartStyles”;
interface Vol {
volume?: number
}
export const CandleChart = ({
candles,
uniqueId,
symbolName,
orders,
amount,
openPrice,
closePrice,
onScreenshotCreated,
chartInterval,
setChartInterval,
waiting,
setWaiting,
height,
showIntervalSelector,
}: CandleChartProps) => {
const chart = useRef<Chart|null>(null);
const paneId = useRef<string>(“”);
const [figureId, setFigureId] = useState<string>(“”);
const ref = useRef<HTMLDivElement>(null);
const handle = useFullScreenHandle();
const {enqueueSnackbar} = useSnackbar();
const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbolName.toUpperCase()]);
const kline = useSelector((state: AppState) => state.binanceKline.futures[${symbolName.toLocaleLowerCase()}@kline_${chartInterval}]) || null;
const size = useComponentResizeListener(ref);
const theme = useTheme();
const darkMode = theme.palette.mode === “dark”;
const chartResize = useCallback(() => {
if (null !== chart.current) {
chart.current.resize();
}
}, [chart.current]);
useEffect(() => {
if (precision && null !== chart.current) {
chart.current.setPriceVolumePrecision(precision?.price || 4, precision?.quantity || 2);
}
}, [chart.current, precision]);
useEffect(() => {
if (kline && null !== chart.current) {
chart.current.updateData(kline);
}
}, [kline, chart.current]);
useEffect(() => {
chartResize();
}, [size]);
useEffect(() => {
// @ts-ignore
chart.current = init(chart-${uniqueId}, {styles: chartStyles(theme)});
return () => dispose(chart-${uniqueId});
}, [uniqueId]);
useEffect(() => {
if (chart.current) {
chart.current.setStyles({
grid: {
horizontal: {
color: theme.palette.grey[50],
},
vertical: {
color: theme.palette.grey[50],
},
},
xAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
yAxis: {
axisLine: {
color: theme.palette.grey[50],
},
},
separator: {
color: theme.palette.grey[50],
},
});
}
}, [theme]);
useEffect(() => {
if (null !== chart.current) {
window.addEventListener(“resize”, chartResize);
}
return () => window.removeEventListener(“resize”, chartResize);
}, []);
useEffect(() => {
chart.current?.applyNewData(candles);
chart.current?.overrideIndicator({
name: “VOL”,
shortName: “Объем”,
calcParams: [],
figures: [
{
key: “volume”,
title: “”,
type: “bar”,
baseValue: 0,
styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => {
const kLineData = data.current.kLineData as KLineData;
let color: string;
if (kLineData.close > kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string;
} else if (kLineData.close < kLineData.open) {
color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string;
} else {
color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string;
}
return {color};
},
},
],
}, paneId.current);
chart.current?.createIndicator(“VOL”, false, {id: paneId.current});
}, [candles]);
useEffect(() => {
if (!orders || orders.length === 0 || candles.length === 0 || !amount || amount.length === 0) return;
const minTime = orders[0].time;
const maxTime = orders[orders.length - 1].time;
const needleTime = minTime + (maxTime - minTime) / 2;
chart.current?.scrollToTimestamp(needleTime + 50 * getMinutesTickSizeByInterval(chartInterval) * 60 * 1000);
drawTrade(chart, paneId, orders, chartInterval, amount);
if (openPrice && closePrice) {
let openTime = Infinity;
let closeTime = -Infinity;
orders.forEach(order => {
if (openTime > order.time) {
openTime = order.time;
}
if (closeTime < order.time) {
closeTime = order.time;
}
});
drawTradeLines(
chart,
openPrice,
openTime,
closePrice,
closeTime,
orders[0].position,
paneId,
precision.price,
precision.quantity,
);
}
}, [orders, candles, uniqueId]);
const removeFigure = () => {
chart.current?.removeOverlay({
id: figureId,
});
setFigureId(“”);
};
const onButtonClick = async() => {
const url = chart.current?.getConvertPictureUrl(true);
if (!url || !onScreenshotCreated) {
return;
}
onScreenshotCreated(url);
};
useEffect(() => {
if (candles.length === 0) return;
chart.current?.subscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
return (() => {
chart.current?.unsubscribeAction(ActionType.OnScroll, onScrollbarPositionChanged);
});
}, [chart.current, candles]);
let isLoading = false;
let onScrollbarPositionChanged = () => {
const chartWidth = chart.current?.getSize()?.width;
const barSpace = chart.current?.getBarSpace();
const rightDistance = chart.current?.getOffsetRightDistance();
const dataList = chart.current?.getDataList();
const from = chart.current?.getVisibleRange().realFrom;
if (!dataList || isLoading || !chartWidth || !barSpace) return;
if (rightDistance) {
if (0 < rightDistance && rightDistance !== 50) {
let startTime = dataList[dataList.length - 1].timestamp;
if (isLastCandleToday(startTime, chartInterval)) return;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, startTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
isLoading = false;
setWaiting(false);
return;
} else {
const newData = […dataList, …newCandles];
chart.current?.applyNewData(newData, true);
const newRightDistance = (-barSpace * newCandles.length) + rightDistance;
chart.current?.setOffsetRightDistance(newRightDistance + 140);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
}
if (from === 0) {
let endTime = dataList[0].timestamp;
let prevTime: number | null = null;
isLoading = true;
setWaiting(true);
fetchSymbolsKlines(symbolName, chartInterval, undefined, endTime).then((data) => {
if (undefined === data) return;
const newCandles = data?.map((item: any[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5],
}));
if (!newCandles || newCandles.length === 0) {
return;
} else {
if (prevTime === newCandles[newCandles.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
if (newCandles[newCandles.length - 1].timestamp === dataList[dataList.length - 1].timestamp) {
isLoading = false;
setWaiting(false);
return;
}
prevTime = newCandles[newCandles.length - 1].timestamp;
chart.current?.applyMoreData(newCandles);
}
isLoading = false;
setWaiting(false);
})
.catch((error) => {
enqueueSnackbar(error.message, {variant: “error”});
isLoading = false;
setWaiting(false);
});
}
};
const isLastCandleToday = (lastCandleTimestamp: number, interval: string) => {
const lastCandleDate = dayjs(lastCandleTimestamp);
const today = dayjs();
if (interval.includes(“m”) || interval.includes(“h”) || interval.includes(“d”)) {
return lastCandleDate.isSame(today, “day”);
}
return false;
};
return (<>
<FullScreen handle={handle}>
<Box height=“100%” sx={{borderRadius: “1rem”, position: “relative”, background: theme => theme.palette.background.paper}}>
{
showIntervalSelector &&
<Stack sx={{
padding: “0 5px”, width: “100%”, height: 40,
justifyContent: “space-between”, flexDirection: “row”, borderBottom: theme => 2px solid ${theme.palette.grey[50]},
}}>
<ButtonGroup>
{
[“1m”, “3m”, “5m”, “15m”, “30m”, “1h”, “4h”, “12h”, “1d”].map(interval => (
<Button
key={interval}
color=“inherit”
sx={{px: 1, py: .5,
color: interval === chartInterval ? darkMode ? “#fff” : “#677294” : “#999999”,
fontSize: “.75rem”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”},
}}
variant={“text”}
onClick={() => setChartInterval && setChartInterval(interval)}
>{interval}</Button>
))
}
</ButtonGroup>
<IconButton sx={{borderRadius: 2, fontFamily: “Mont”, mr: 1, color: darkMode ? “#999” : “#677294”, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={onButtonClick}>
<Icon sx={{width: 90}} component={ScreenIcon} />
</IconButton>
</Stack>
}
{
waiting ? (
<CircularProgress
style={{position: “absolute”, marginLeft: “1rem”}}
color=“inherit”
size={32}
/>
) : (<></>)
}
<Stack direction=“row” height={height && !handle.active ? 550 : “100%” || “calc(100% - 140px)”} width=“100%”>
<CandleChartToolbar
setFigureId={setFigureId}
chart={chart}
paneId={paneId}
handle={handle}
/>
<Box
ref={ref}
id={chart-${uniqueId}}
width=“calc(100% - 55px)”
height=“100%”
sx={{borderLeft: theme => 2px solid ${theme.palette.grey[50]}}}
>
{
figureId.length > 0 &&
<Stack
sx={{
backgroundColor: darkMode ? “#474747” : “#CBD4E3”,
borderRadius: 1,
position: “absolute”,
zIndex: 10,
right: 80,
top: 30,
border: theme => 2px solid ${theme.palette.grey[50]},
}}
spacing={2}
>
<IconButton sx={{borderRadius: 1}} onClick={removeFigure}>
<Icon component={BasketIcon} />
</IconButton>
</Stack>
}
</Box>
</Stack>
</Box>
</FullScreen>
</>);
};
CandleChart.displayName = “CandleChart”;
import {Icon, IconButton, Stack, useTheme} from “@mui/material”;
import {BasketIcon, FullScreenIcon} from “…/…/icons”;
import React from “react”;
import {CandleChartToolbarProps} from “./CandleChartToolbar.props”;
import RectTool from “./Tools/RectTool”;
import FibonacciLineTool from “./Tools/FibonacciLineTool”;
import HorizontalStraightLineTool from “./Tools/HorizontalStraightLineTool”;
import ParallelStraightLineTool from “./Tools/ParallelStraightLineTool”;
import RayLineTool from “./Tools/RayLineTool”;
import PriceLineTool from “./Tools/PriceLineTool”;
import SegmentTool from “./Tools/SegmentTool”;
import StraightLineTool from “./Tools/StraightLineTool”;
import RulerTool from “./Tools/RulerTool”;
const CandleChartToolbar = ({chart, paneId, setFigureId, handle}: CandleChartToolbarProps) => {
const darkMode = useTheme().palette.mode === “dark”;
const removeOverlay = () => {
chart.current?.removeOverlay();
setFigureId(“”);
};
const fullScreenHandle = () => {
if(handle.active) {
handle.exit();
} else {
handle.enter();
}
};
return <>
<Stack
className=“scroll-block”
direction=“column”
alignItems=“center”
spacing={1}
sx={{
width: “55px”,
height: “100%”,
overflowY: “scroll”,
scrollbarWidth: “thin”,
“&::-webkit-scrollbar”: {
width: “8px”,
},
“&::-webkit-scrollbar-track”: {
background: theme => theme.palette.background.paper,
},
“&::-webkit-scrollbar-thumb”: {
backgroundColor: theme => theme.palette.grey[300],
border: theme => 3px solid ${theme.palette.white.main},
},
}}
>
<PriceLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<HorizontalStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RayLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<SegmentTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<StraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<ParallelStraightLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<FibonacciLineTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RulerTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<RectTool chart={chart} paneId={paneId} setFigureId={setFigureId}/>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} style={{height: 40}} onClick={fullScreenHandle}>
<Icon component={FullScreenIcon} sx={{height: 18}} />
</IconButton>
<IconButton sx={{borderRadius: 2, “&:hover”: {backgroundColor: darkMode ? “#2b2b2b !important” : “”}}} onClick={removeOverlay}>
<Icon component={BasketIcon}/>
</IconButton>
</Stack>
</>;
};
export default CandleChartToolbar;
Мы рисуем фигуры, которые отрисовываем в CandleChartToolbar
нужно сделать сохранение того, что ты нарисовал в localStorage
|
1b48d0631e24030ed4b458176c70f9e5
|
{
"intermediate": 0.33216920495033264,
"beginner": 0.43792814016342163,
"expert": 0.22990262508392334
}
|
13,204
|
"$(PlatformTarget)_$(Configuration)" in .target file in msbuild resolves to "x64_Release". How to make it display "$(PlatformTarget)_$(Configuration)" instead of "x64_Release".
|
b53ec49dfcef3aac382ce5557fd88629
|
{
"intermediate": 0.4947340488433838,
"beginner": 0.3048899173736572,
"expert": 0.20037606358528137
}
|
13,206
|
详细说明每个步骤的含义及作用
1.导入所需的库:导入需要使用的Python库,包括NumPy、Pandas、MXNet等。这些库提供了数据处理、机器学习和深度学习的功能。
|
002de5f1e9d00839ceef1b1a79487eab
|
{
"intermediate": 0.4113995134830475,
"beginner": 0.2268843799829483,
"expert": 0.361716091632843
}
|
13,207
|
解释代码
1.导入所需的库:导入需要使用的Python库,包括NumPy、Pandas、MXNet等。这些库提供了数据处理、机器学习和深度学习的功能。
|
8d1485e9f711fd9ac9c9d21c330d65ee
|
{
"intermediate": 0.432971715927124,
"beginner": 0.19705326855182648,
"expert": 0.3699750602245331
}
|
13,208
|
详细解释每一步的含义
1.导入所需的库:导入需要使用的Python库,包括NumPy、Pandas、MXNet等。这些库提供了数据处理、机器学习和深度学习的功能。
|
db970c7f1c8b3f4bc25b2d9748efc85a
|
{
"intermediate": 0.43411463499069214,
"beginner": 0.20966142416000366,
"expert": 0.3562239706516266
}
|
13,209
|
[ERROR] Failed to execute goal on project endowment-server-archive-building: Could not resolve dependencies for project com.bluebalance:endowment-server-archive-building:jar:1.0-SNAPSHOT: Failed to collect dependencies at com.deepoo
ve:poi-tl:jar:1.12.1 -> org.apache.xmlgraphics:batik-codec:jar:1.14 -> org.apache.xmlgraphics:batik-bridge:jar:1.14 -> org.apache.xmlgraphics:batik-anim:jar:1.14 -> org.apache.xmlgraphics:batik-dom:jar:1.14 -> xalan:xalan:jar:2.7.2:
Failed to read artifact descriptor for xalan:xalan:jar:2.7.2: Could not transfer artifact xalan:xalan:pom:2.7.2 from/to nexus-aliyun (https://maven.aliyun.com/nexus/content/groups/public): transfer failed for https://maven.aliyun.c
om/nexus/content/groups/public/xalan/xalan/2.7.2/xalan-2.7.2.pom: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project endowment-server-archive-building: Could not resolve dependencies for project com.bluebalance:endowment-server-archive-building:jar:1.0-SNAPSH
OT: Failed to collect dependencies at com.deepoove:poi-tl:jar:1.12.1 -> org.apache.xmlgraphics:batik-codec:jar:1.14 -> org.apache.xmlgraphics:batik-bridge:jar:1.14 -> org.apache.xmlgraphics:batik-anim:jar:1.14 -> org.apache.xmlgraph
ics:batik-dom:jar:1.14 -> xalan:xalan:jar:2.7.2
|
2204786659632ad81dc58981a5aa37ff
|
{
"intermediate": 0.33973705768585205,
"beginner": 0.268429160118103,
"expert": 0.3918337821960449
}
|
13,210
|
详细解释每一步的含义
1.导入所需的库:导入需要使用的Python库,包括NumPy、Pandas、MXNet等。这些库提供了数据处理、机器学习和深度学习的功能。
|
a602fa94d4dc339d8b5a7b344585cc70
|
{
"intermediate": 0.4385896623134613,
"beginner": 0.21232061088085175,
"expert": 0.34908971190452576
}
|
13,211
|
Hello
|
a85232d7133249c39421222bf47fa55b
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
13,212
|
b_user_edge = find_latest_1D(np.array(ratings.iloc[batch]['user_id']), adj_user_edge, adj_user_time, ratings.iloc[batch]['timestamp'].tolist())
b_user_edge = torch.from_numpy(b_user_edge).to(device)
b_users = torch.from_numpy(np.array(ratings.iloc[batch]['user_id'])).to(device)
#print ("b_user",b_users)
b_item_edge = find_latest_1D(np.array(ratings.iloc[batch]['item_id']), adj_item_edge, adj_item_time, ratings.iloc[batch] ['timestamp'].tolist())
b_item_edge = torch.from_numpy(b_item_edge).to(device)
b_items = torch.from_numpy(np.array(ratings.iloc[batch]['item_id'])).to(device)
timestamps = torch.from_numpy(np.array(ratings.iloc[batch]['timestamp'])).to(device)
negative_samples = sampler(items_in_data, adj_user, ratings.iloc[batch]['user_id'].tolist() ,1)
neg_edge = find_latest(negative_samples, adj_item_edge, adj_item_time, ratings.iloc[batch]['timestamp'].tolist())
negative_samples = torch.from_numpy(np.array(negative_samples)).to(device)
negative_samples = negative_samples.squeeze()
neg_edge = torch.from_numpy(neg_edge).to(device)
neg_edge = neg_edge.squeeze()
time0 = time.time()
user_embeddings = model(b_users, b_user_edge, timestamps, config.n_layer, nodetype='user')
item_embeddings = model(b_items, b_item_edge, timestamps, config.n_layer, nodetype='item')
negs_embeddings = model(negative_samples, neg_edge, timestamps, config.n_layer, nodetype='item')
می خواهم پارامترهای تابع زیر را با توجه به کد بالا تغییر دهم چگونه تغییر دهم
def hard_neg_sample(u, seq, pos, neg, hard_items, cnt_items, args):
def update_hard_negs(u, pos, hard_items, all_logits, all_labels, all_samples, args):
|
c92e93d753ac5bb42bd24954a20df485
|
{
"intermediate": 0.32248455286026,
"beginner": 0.4490225613117218,
"expert": 0.2284928560256958
}
|
13,213
|
换成英文半角标点 import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
object SparkLogProcessing {
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder()
.appName(“Spark Log Processing”)
.master(“local[]")
.getOrCreate()
// Read in log file
val logData = spark.read.text(“access.log”)
// Parse log data
val parsedData = logData.select(regexp_extract(col(“value”), "^([\d.]+) ", 1).alias(“ip”),
regexp_extract(col(“value”), "\[(.?)\]”, 1).alias(“timestamp”),
regexp_extract(col(“value”), “”(.*?)“”, 1).alias(“url”),
regexp_extract(col(“value”), “HTTP/\S+” (\d+)“, 1).cast(“integer”).alias(“code”))
// Calculate statistics
val numEntries = parsedData.count()
val numUniqueIPs = parsedData.select(countDistinct(col(“ip”))).first().getLong(0)
val mostFrequentIPs = parsedData.groupBy(col(“ip”)).count().orderBy(desc(“count”)).limit(10)
val urlCounts = parsedData.groupBy(col(“url”)).count().orderBy(desc(“count”)).limit(10)
// Output results
println(s"Number of log entries: numEntries")
println(s"Number of unique IPs:
numUniqueIPs”)
println(“Top 10 IP addresses with the most requests:”)
mostFrequentIPs.show()
println(“Top 10 most requested URLs:”)
urlCounts.show()
spark.stop()
}
}
|
473a5d45026c7750498250a00d0be924
|
{
"intermediate": 0.5057210326194763,
"beginner": 0.34379369020462036,
"expert": 0.15048523247241974
}
|
13,214
|
how to use libvf.io
|
0f21691bca75b5c9e15db0805fd8cd51
|
{
"intermediate": 0.5545189380645752,
"beginner": 0.21432308852672577,
"expert": 0.23115794360637665
}
|
13,215
|
How to use vGPUs on a consumer GPU
|
19b74e844a8cab53fe8b32f43f137795
|
{
"intermediate": 0.25459370017051697,
"beginner": 0.15542170405387878,
"expert": 0.5899845361709595
}
|
13,216
|
sort an array of map typed Map<TipoAttoRegolamentare, string>() by it's values (string)
|
1b3ca652bb631b92aa78dda2a943b589
|
{
"intermediate": 0.43680405616760254,
"beginner": 0.20897749066352844,
"expert": 0.35421842336654663
}
|
13,217
|
refactoring this kotlin code. I want clean solution
|
ecad471a6bc6a56ea4d049e8a50cfabe
|
{
"intermediate": 0.3802797198295593,
"beginner": 0.38623103499412537,
"expert": 0.2334892600774765
}
|
13,218
|
are there any GAN models that can have been proved helpful to generate Chest X-ray images with mlti-stage model ? show me the code with PyTorch framework please
|
21c8f28f1ec6b76e55f63e91baa98237
|
{
"intermediate": 0.18718655407428741,
"beginner": 0.04396713525056839,
"expert": 0.7688462734222412
}
|
13,219
|
write a python code of triangle
|
a81f7dbba981b1de86fcf4e0b948a880
|
{
"intermediate": 0.28558865189552307,
"beginner": 0.3166261315345764,
"expert": 0.3977851867675781
}
|
13,220
|
please draw a chart comparing the confirmed positive COVID-19 cases, from January 2021 to 2023, for Europe Union, Hong Kong and China
|
c87f499baf658b65619e7c8cae00bbfa
|
{
"intermediate": 0.37161561846733093,
"beginner": 0.232320636510849,
"expert": 0.39606374502182007
}
|
13,221
|
#include <iostream>
using namespace std;
int main(){
int t,n,i,k,p=0,l;
cin>>n;
bool S[2*n];
for(k=0; k<=n*2; ++k)
S[k]=true;
for(k=2; k*k<=n*2; ++k)
if(S[k]) for(l=k*k; l<=2*n; l+=k) S[l]=false;
for(k=n+1; k<=n*2; ++k)
if(S[k]) p++;
cout<<p;
return 0;} обьясни решение
|
6262fc175ef76cdbb663e52bcd5e19d8
|
{
"intermediate": 0.3205709457397461,
"beginner": 0.4861040711402893,
"expert": 0.1933249980211258
}
|
13,222
|
can you convert function in c# to python ?
|
dcb206adddb282b6c147c9d555efa17a
|
{
"intermediate": 0.3947330415248871,
"beginner": 0.39369383454322815,
"expert": 0.21157310903072357
}
|
13,223
|
write a apex class that If we select the quote from the dropdown list then that quote should be turned as primary quote and the other quotes should go as non-primary
|
d9f2805b4400e5ced22b28bab6b43134
|
{
"intermediate": 0.2969762682914734,
"beginner": 0.38618865609169006,
"expert": 0.3168350160121918
}
|
13,224
|
update attribute value dom4j xml
|
14f7d6d209fd62f59348674b0084c411
|
{
"intermediate": 0.4220273196697235,
"beginner": 0.22584755718708038,
"expert": 0.3521251380443573
}
|
13,225
|
wit Tomcat Jdk, how to create a keystore?
|
29026d40366cf3b1a754f58216b8adda
|
{
"intermediate": 0.43147408962249756,
"beginner": 0.060781482607126236,
"expert": 0.5077443718910217
}
|
13,226
|
how to calculate vertical shear in python?
|
b135e7fbc12ea00b7eac9fe119f776c1
|
{
"intermediate": 0.286443829536438,
"beginner": 0.09627082943916321,
"expert": 0.6172853112220764
}
|
13,227
|
how to calculate horizontal wind gradient (du/dx and du/dy) in specific level in python script with gfs data?
|
6a3b24d834ce2a30373db3b6195364c3
|
{
"intermediate": 0.39934292435646057,
"beginner": 0.10560759156942368,
"expert": 0.49504950642585754
}
|
13,228
|
You are kotlin developer. i will pass you days that can be Long type or null. For example days=60L. You have token.date field that is Instant object. You need write code that will determinate is token date passed days or not.
|
2e9badf2203b0da41fcd61a40a93afa1
|
{
"intermediate": 0.6409670114517212,
"beginner": 0.13934935629367828,
"expert": 0.2196836620569229
}
|
13,229
|
I have a JS object that looks like this - properties: {uniqueId: value, uniqueId: value}. I need to convert it to this - properties: [{id: uniqueId, fieldValue: value}, {id: uniqueId, fieldValue: value}]
|
53940443a4f8dcae56b38fc2282eaf82
|
{
"intermediate": 0.3915124833583832,
"beginner": 0.2848900854587555,
"expert": 0.32359743118286133
}
|
13,230
|
how to calculate sqrt in python?
|
d8d56c822e32da13775dcab30ae55ad6
|
{
"intermediate": 0.3722664415836334,
"beginner": 0.11764920502901077,
"expert": 0.510084331035614
}
|
13,231
|
SELECT Account.id as "AccountID", Account.name, Account.accountnumber, Account.batch, Account.additionalemailaddresses,
contact.firstname, contact.lastname, contact.workemail, contact.personalemail,
Invoice.amount, Invoice.balance, Invoice.duedate, Invoice.invoicedate, Invoice.invoicenumber,
Invoice.status, Invoice.id,
date_diff('day', Invoice.duedate, current_date) as "duedays",
Subscription.id as "SubscriptionID", Subscription.name, Subscription.status
FROM InvoiceItem IT
JOIN Account on IT.accountid = Account.id
JOIN Invoice on IT.invoiceid = Invoice.id
JOIN contact on contact.id = Account.BillToId
JOIN Subscription on IT.subscriptionid = Subscription.id
WHERE (date_diff('day', invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.a}}' AS BOOLEAN) AS BIGINT)
OR date_diff('day', invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.b}}' AS BOOLEAN) AS BIGINT)
OR date_diff('day', invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.c}}' AS BOOLEAN) AS BIGINT)
OR date_diff('day', invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.d}}' AS BOOLEAN) AS BIGINT)
OR date_diff('day', invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.e}}' AS BOOLEAN) AS BIGINT))
AND Invoice.balance>0
AND Invoice.status = 'Posted'
AND Account.Batch = 'Batch1'
|
ef3e766a8cc324bc09fb4362b7dd8dbb
|
{
"intermediate": 0.2967066168785095,
"beginner": 0.39895913004875183,
"expert": 0.30433425307273865
}
|
13,232
|
Please introduce AIC and mention how and why WAIC and LOO have superseded the metric for selecting models.
|
2522b5b4e80086215ca0bef75b1070d4
|
{
"intermediate": 0.198353111743927,
"beginner": 0.11270041018724442,
"expert": 0.6889464855194092
}
|
13,233
|
how to get the current status of checkbutton in tkinter
|
a8ec7a648a9f1ed2baeff06ce2c4ef30
|
{
"intermediate": 0.39821282029151917,
"beginner": 0.2569577395915985,
"expert": 0.34482938051223755
}
|
13,234
|
java code to create a JFrame with layer on top of it, so that i can drag a JLabel from center screen to any position
|
6a20e46a45e2542b76d2167efb36c05f
|
{
"intermediate": 0.7304532527923584,
"beginner": 0.08170277625322342,
"expert": 0.1878439486026764
}
|
13,235
|
const createdQuotation = await tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation!.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: item.UoMCode,
})),
},
},
status: QuotationStatus.BRANCH_APPROVED,
creationStatus: QuotationCreationStatus.IMPORTED,
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
console.log("CreatedQuotation: ", createdQuotation);
fs.appendFileSync(
"output.txt",
`Quotation: ${util.inspect(createdQuotation, {
depth: null,
})}\n`
);
fs.appendFileSync(
"output.txt",
`Quotation Quotes: ${util.inspect(createdQuotation!.quotes, { depth: null })}\n`
);
await Promise.all(
quotation.quotes!.map(async (quote: any, index) => {
// if (!quote || !quote.id) {
// console.log("Skipping quote with missing or null ID");
// return;
// }
fs.appendFileSync(
"outputInside.txt",
`Quotation Quotes: ${util.inspect(
quotation!.quotes,
{ depth: null }
)}\n`
);
fs.appendFileSync(
"outputQuotes.txt",
`Quotes: ${util.inspect(
quotation.quotes!.map(
(quote: any) => quote.id
),
{ depth: null }
)}\n`
);
interpolatedQuotePromises.push(
tx.interpolatedQuote.create({
data: {
quoteId: quote.id,
quotationId: createdQuotation.id,
price: quote.price,
measurementUnit: item.SmUCode,
quantity: quote.quantity,
},
})
);
cleanedQuotePromises.push(
tx.cleanedQuote.create({
data: {
quoteId: quote.id,
quotationId: createdQuotation.id,
price: quote.price,
measurementUnit: item.SmUCode,
quantity: quote.quantity,
questionnaireId: createdQuotation.questionnaireId,
itemCode: createdQuotation.itemCode,
},
})
);
})
);
based on this code section the file writers above the "await Promise.all(
quotation.quotes!.map(async (quote: any, index) " return the createdquotations correctly with their asscociated quotes and the quoteIds are created as well and returned but when it goes into await Promise.all(
quotation.quotes!.map(async (quote: any, index) => { and i try to log the quoteids they are undefined
|
8cac8d44db090131141f22a13b1bb9e0
|
{
"intermediate": 0.3877391219139099,
"beginner": 0.461932510137558,
"expert": 0.1503283828496933
}
|
13,236
|
how can I make a code for that "when I select a row in datagridview1 it automaticaly select a row in datagridview2 that has the same Item name "
|
65448c960f2cda7cc6eb1e672a3de452
|
{
"intermediate": 0.5860342979431152,
"beginner": 0.1034156009554863,
"expert": 0.31055015325546265
}
|
13,237
|
const createdQuotation = await tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation!.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: item.UoMCode,
})),
},
},
status: QuotationStatus.BRANCH_APPROVED,
creationStatus: QuotationCreationStatus.IMPORTED,
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
console.log("CreatedQuotation: ", createdQuotation);
fs.appendFileSync(
"output.txt",
`Quotation: ${util.inspect(createdQuotation, {
depth: null,
})}\n`
);
fs.appendFileSync(
"output.txt",
`Quotation Quotes: ${util.inspect(createdQuotation!.quotes, { depth: null })}\n`
);
await Promise.all(
quotation.quotes!.map(async (quote: any, index) => {
// if (!quote || !quote.id) {
// console.log("Skipping quote with missing or null ID");
// return;
// }
fs.appendFileSync(
"outputInside.txt",
`Quotation Quotes: ${util.inspect(
quotation!.quotes,
{ depth: null }
)}\n`
);
fs.appendFileSync(
"outputQuotes.txt",
`Quotes: ${util.inspect(
quotation.quotes!.map(
(quote: any) => quote.id
),
{ depth: null }
)}\n`
);
interpolatedQuotePromises.push(
tx.interpolatedQuote.create({
data: {
quoteId: quote.id,
quotationId: createdQuotation.id,
price: quote.price,
measurementUnit: item.SmUCode,
quantity: quote.quantity,
},
})
);
cleanedQuotePromises.push(
tx.cleanedQuote.create({
data: {
quoteId: quote.id,
quotationId: createdQuotation.id,
price: quote.price,
measurementUnit: item.SmUCode,
quantity: quote.quantity,
questionnaireId: createdQuotation.questionnaireId,
itemCode: createdQuotation.itemCode,
},
})
);
})
);
based on this code section the file writers above the "await Promise.all(
quotation.quotes!.map(async (quote: any, index) " return the createdquotations correctly with their asscociated quotes and the quoteIds are created as well and returned but when it goes into await Promise.all(
quotation.quotes!.map(async (quote: any, index) => { and i try to log the quoteids they are undefined
|
570c5ff783a5be9305b9476803bc638c
|
{
"intermediate": 0.3877391219139099,
"beginner": 0.461932510137558,
"expert": 0.1503283828496933
}
|
13,238
|
SELECT Account.id as "AccountID", Account.name, Account.accountnumber, Account.batch, Account.additionalemailaddresses,
contact.firstname, contact.lastname, contact.workemail, contact.personalemail,
Invoice.amount, Invoice.balance, Invoice.duedate, Invoice.invoicedate, Invoice.invoicenumber,
Invoice.status, Invoice.id,
date_diff('day', Invoice.duedate, current_date) as "duedays",
Subscription.id as "SubscriptionID", Subscription.name, Subscription.status
FROM InvoiceItem IT
JOIN Account on IT.accountid = Account.id
JOIN Invoice on IT.invoiceid = Invoice.id
JOIN contact on contact.id = Account.BillToId
JOIN Subscription on IT.subscriptionid = Subscription.id
WHERE (date_diff('day', invoice.duedate, current_date) = CAST('{{Data.Workflow.a}}' AS BIGINT)
OR date_diff('day', Invoice.duedate, current_date) = CAST('{{Data.Workflow.b}}' AS BIGINT)
OR date_diff('day', Invoice.duedate, current_date) = CAST('{{Data.Workflow.c}}' AS BIGINT)
OR date_diff('day', Invoice.duedate, current_date) = CAST('{{Data.Workflow.d}}' AS BIGINT)
OR date_diff('day', Invoice.duedate, current_date) = CAST('{{Data.Workflow.e}}' AS BIGINT))
AND Invoice.balance>0
AND Invoice.status = 'Posted'
AND Account.Batch = 'Batch1' which is the boolean in given query
|
69c5a4fec380851047f8848ecd2390db
|
{
"intermediate": 0.3330416679382324,
"beginner": 0.35104477405548096,
"expert": 0.3159136176109314
}
|
13,239
|
Hi
|
f116df1493de6525176a9a5991839e1e
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
13,240
|
the code won't run ,correct it import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
object SparkLogProcessing {
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder()
.appName("Spark Log Processing")
.master("local[]")
.getOrCreate()
// Read in log file
val logData = spark.read.text("access.log")
// Parse log data
val parsedData = logData.select(regexp_extract(col("value"), "^([\d.]+) ", 1).alias("ip"),
regexp_extract(col("value"), "\[(.?)\]", 1).alias("timestamp"),
regexp_extract(col("value"), ""(.*?)"", 1).alias("url"),
regexp_extract(col("value"), "HTTP/\S+" (\d+)", 1).cast("integer").alias("code"))
// Calculate statistics
val numEntries = parsedData.count()
val numUniqueIPs = parsedData.select(countDistinct(col("ip"))).first().getLong(0)
val mostFrequentIPs = parsedData.groupBy(col("ip")).count().orderBy(desc("count")).limit(10)
val urlCounts = parsedData.groupBy(col("url")).count().orderBy(desc("count")).limit(10)
// Output results
println(s"Number of log entries: numEntries")
println(s"Number of unique IPs:
numUniqueIPs")
println("Top 10 IP addresses with the most requests:")
mostFrequentIPs.show()
println("Top 10 most requested URLs:")
urlCounts.show()
spark.stop()
}
}
|
7d3cade2ceed5f1690db1da285d82638
|
{
"intermediate": 0.5290343165397644,
"beginner": 0.3392316997051239,
"expert": 0.13173401355743408
}
|
13,241
|
same code but add method to auto move instead by hand drag, move slowly from center to top right corner: this was your code: public DragLabelExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(“Drag Label Example”);
// Create a panel to hold the label and add it to the frame
JPanel panel = new JPanel();
panel.setLayout(null); // This allows us to position components manually
add(panel);
// Create a label to drag around and add it to the panel
label = new JLabel(“Drag me!”);
label.setBounds(200, 200, 100, 30);
panel.add(label);
// Add a mouse listener to the label to handle drag events
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
// Remember where the mouse was clicked relative to the label
mouseX = e.getX();
mouseY = e.getY();
// Remember the label’s current position
labelX = label.getX();
labelY = label.getY();
// Start dragging
dragging = true;
}
public void mouseReleased(MouseEvent e) {
// Stop dragging
dragging = false;
}
});
// Add a mouse motion listener to the label to handle drag events
label.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (dragging) {
// Calculate the difference between the current mouse position and the position of the JLabel
int dx = e.getX() - mouseX;
int dy = e.getY() - mouseY;
// Calculate the new position of the JLabel based on the mouse movement
int newX = labelX + dx;
int newY = labelY + dy;
// Constrain the JLabel’s position to within the panel
newX = Math.max(0, Math.min(panel.getWidth() - label.getWidth(), newX));
newY = Math.max(0, Math.min(panel.getHeight() - label.getHeight(), newY));
// Move the JLabel to its new position
label.setLocation(newX, newY);
// Remember the new position of the JLabel as the current position
labelX = newX;
labelY = newY;
}
}
});
// Set the size of the frame and make it visible
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
new DragLabelExample();
}
}
|
b9346dbcdaa7c567669c67b3b532d9a8
|
{
"intermediate": 0.3430598974227905,
"beginner": 0.4564669132232666,
"expert": 0.20047320425510406
}
|
13,242
|
binding the key press event to a callback in tkinter
|
11d96ab7d2457a692a8d127c13b8faf2
|
{
"intermediate": 0.3937680423259735,
"beginner": 0.1555267721414566,
"expert": 0.45070523023605347
}
|
13,243
|
how to deploy openvpn server on k8s cluster and create clients?
|
d9007e87aed7920a7c63b35651218f41
|
{
"intermediate": 0.43210628628730774,
"beginner": 0.23324190080165863,
"expert": 0.3346518576145172
}
|
13,244
|
how do i break into a new line in python print
|
b24910d949937c0e0a5f4bb78fbc1556
|
{
"intermediate": 0.3391096591949463,
"beginner": 0.4075620472431183,
"expert": 0.25332826375961304
}
|
13,245
|
const createdQuotation = await tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation!.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: item.UoMCode,
})),
},
},
status: QuotationStatus.BRANCH_APPROVED,
creationStatus: QuotationCreationStatus.IMPORTED,
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
}); await Promise.all(
createdQuotation.quotes!.map(async(quote) => {
const quoteId = quote.id;
// if (!quote || !quote.id) {
// console.log("Skipping quote with missing or null ID");
// return
// }
fs.appendFileSync(
"outputInside.txt",
`Quotation Quotes: ${util.inspect(createdQuotation!.quotes, {
depth: null,
})}\n`
);
fs.appendFileSync(
"outputId.txt",
`Quotation Quotes: ${util.inspect(quoteId, {
depth: null,
})}\n`
);
fs.appendFileSync(
"outputQuotes.txt",
`Quotes: ${util.inspect(
createdQuotation.quotes!.map((quote: any) => quote.id),
{ depth: null }
)}\n`
);
interpolatedQuotePromises.push(
tx.interpolatedQuote.create({
data: {
quoteId: quoteId,
quotationId: createdQuotation.id,
price: quote.price,
measurementUnit: item.SmUCode,
quantity: quote.quantity,
},
})
);
cleanedQuotePromises.push(
tx.cleanedQuote.create({
data: {
quoteId: quoteId,
quotationId: createdQuotation.id,
price: quote.price,
measurementUnit: item.SmUCode,
quantity: quote.quantity,
questionnaireId: createdQuotation.questionnaireId,
itemCode: createdQuotation.itemCode,
},
})
);
})
); based on this code the quoteId which is being accessed fromt he createdQuotation is throwing errors when trying to create interpolatedquotes
|
c8a599c6fd2ede4f619484a3e968cb69
|
{
"intermediate": 0.3751981556415558,
"beginner": 0.4730144441127777,
"expert": 0.1517874151468277
}
|
13,246
|
Please update this code to have 4 cutoff points and 5 ratings:
# Ordinal intuition
library(tidyverse)
d <-
tibble(z = seq(from = -3, to = 3, by = .1)) %>%
mutate(`p(z)` = dnorm(z, mean = 0, sd = 1),
`Phi(z)` = pnorm(z, mean = 0, sd = 1))
library(scico)
sl <- scico(palette = "lajolla", n = 9)
scales::show_col(sl)
theme_set(
theme_linedraw() +
theme(panel.grid = element_blank(),
strip.background = element_rect(color = sl[9], fill = sl[9]),
strip.text = element_text(color = sl[1]))
)
p1 <-
d %>%
ggplot(aes(x = z, y = `p(z)`)) +
geom_area(aes(fill = z <= 1),
show.legend = F) +
geom_line(linewidth = 1, color = sl[3]) +
scale_fill_manual(values = c("transparent", sl[2])) +
scale_y_continuous(expand = expansion(mult = c(0, 0.05))) +
labs(title = "Normal Density",
y = expression(p(italic(z))))
p2 <-
d %>%
ggplot(aes(x = z, y = `Phi(z)`)) +
geom_area(aes(fill = z <= 1),
show.legend = F) +
geom_line(linewidth = 1, color = sl[3]) +
scale_fill_manual(values = c("transparent", sl[2])) +
scale_y_continuous(expand = expansion(mult = c(0, 0)), limits = 0:1) +
labs(title = "Cumulative Normal",
y = expression(Phi(italic(z))))
library(patchwork)
p1 / p2 &
scale_x_continuous(breaks = -2:2) &
coord_cartesian(xlim = c(-2.5, 2.5))
(theta_1 <- seq(from = 1.5, to = 6.5, by = 1))
(label_1 <- 1:7)
den <-
# define the parameters for the underlying normal distribution
tibble(mu = 4,
sigma = 1.5) %>%
mutate(strip = str_c("mu==", mu, "~~sigma==", sigma)) %>%
# this will allow us to rescale the density in terms of the bar plot
mutate(multiplier = 26 / dnorm(mu, mu, sigma)) %>%
# we need values for the x-axis
expand_grid(y = seq(from = -1, to = 9, by = .1)) %>%
# compute the density values
mutate(density = dnorm(y, mu, sigma)) %>%
# use that multiplier value from above to rescale the density values
mutate(percent = density * multiplier)
head(den)
bar <-
# define the parameters for the underlying normal distribution
tibble(mu = 4,
sigma = 1.5) %>%
mutate(strip = str_c("mu==", mu, "~~sigma==", sigma)) %>%
# take random draws from the underlying normal distribution
mutate(draw = map2(mu, sigma, ~rnorm(1e4, mean = .x, sd = .y))) %>%
unnest(draw) %>%
# bin those draws into ordinal categories defined by `theta_1`
# and named by `label_1`
mutate(y = case_when(
draw < theta_1[1] ~ label_1[1],
draw < theta_1[2] ~ label_1[2],
draw < theta_1[3] ~ label_1[3],
draw < theta_1[4] ~ label_1[4],
draw < theta_1[5] ~ label_1[5],
draw < theta_1[6] ~ label_1[6],
draw >= theta_1[6] ~ label_1[7]
)) %>%
# summarize
count(y) %>%
mutate(percent = (100 * n / sum(n)) %>% round(0)) %>%
mutate(percent_label = str_c(percent, "%"),
percent_max = max(percent))
head(bar)
bar %>%
ggplot(aes(x = y, y = percent)) +
geom_area(data = den,
fill = sl[3]) +
geom_vline(xintercept = theta_1, color = "white", linetype = 3) +
geom_col(width = .5, alpha = .85, fill = sl[7]) +
geom_text(aes(y = percent + 2, label = percent_label),
size = 3.5) +
annotate(geom = "text",
x = theta_1, y = -5.55, label = theta_1,
size = 3) +
scale_x_continuous(NULL, expand = c(0, 0),
breaks = theta_1,
labels = parse(text = str_c("theta[", 1:6, "]"))) +
scale_y_continuous(NULL, breaks = NULL, expand = expansion(mult = c(0, 0.06))) +
coord_cartesian(ylim = c(0, 28.5), clip = F) +
theme(plot.margin = margin(5.5, 5.5, 11, 5.5)) +
facet_wrap(~ strip, labeller = label_parsed)
|
35c90ffa6a4b26ab64e84c2ae06a22f9
|
{
"intermediate": 0.3493333160877228,
"beginner": 0.4353485107421875,
"expert": 0.2153182178735733
}
|
13,248
|
I want to implement a feature that changes the Valaszok style based on if it's selected or not and I want it to save the style so when I horizontally scroll through the flatlist, when I scroll back to it, it would still show it as selected and when I press EllenorzesButton it would behave the same. My problem is the style is not saved with my current implementation, how can I fix it? Please write down the whole code with comments where it changes something
import React, { useCallback, useEffect, useRef, useState} from 'react';
import { Dimensions, FlatList, ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import Feladatok from "./Feladatok";
import { fetchAllData } from "../Database/Db";
import { Feladat } from '../Database/Feladat';
import { SafeAreaView } from 'react-native-safe-area-context';
import styles from './Teszt.style';
import { AntDesign as Icon } from '@expo/vector-icons';
const Darab = () => {
const [feladatok, setFeladatok] = useState<Feladat[]>([]);
const [ellenorizve, setEllenorizve] = useState<boolean>(false);
const [answeredQuestions, setAnsweredQuestions] = useState<number[]>([]);
const [index, setIndex] = useState(0);
const { width: windowWidth } = Dimensions.get("window");
const indexRef = useRef(index);
indexRef.current = index;
useEffect(() => {
handleFetchFeladatok();
}, []);
const handleFetchFeladatok = () => {
fetchAllData()
.then((result) => {
setFeladatok(result);
})
.catch((err) => {
console.error("Error fetching feladatok: ", err);
});
};
const ellenorzes = () => {
setEllenorizve(true);
setAnsweredQuestions((prevIndices) => [...prevIndices, index]);
};
const renderItem = ({ item, index }: { item: Feladat; index: number }) => {
const isAnswered = answeredQuestions.includes(index);
return <Feladatok feladat={item} ellenorizve={isAnswered} />;
}
const onScroll = useCallback((event: any) => {
const slideSize = event.nativeEvent.layoutMeasurement.width;
const index = event.nativeEvent.contentOffset.x / slideSize;
const roundIndex = Math.round(index);
const distance = Math.abs(roundIndex - index);
const isNoMansLand = 0.4 < distance;
if (roundIndex !== indexRef.current && !isNoMansLand) {
setIndex(roundIndex);
const currentPageAnswered = answeredQuestions.includes(roundIndex);
setEllenorizve(currentPageAnswered);
}
}, [answeredQuestions]);
const flatListOptimizationProps = {
pagingEnabled: true,
horizontal: true,
initialNumToRender: 0,
maxToRenderPerBatch: 3,
scrollEventThrottle: 16,
windowSize: 8,
getItemLayout: useCallback(
(_: any, index: number) => ({
index,
length: windowWidth,
offset: index * windowWidth,
}),
[windowWidth]
),
};
return (
<SafeAreaView style={styles.screen}>
<FlatList
keyExtractor={(item) => String(item.ID)}
overScrollMode="never"
data={feladatok}
renderItem={renderItem}
showsHorizontalScrollIndicator={false}
onScroll={onScroll}
{...flatListOptimizationProps}
/>
<View style={styles.navContainer}>
<View style={styles.navBar}>
<View style={[styles.navBtnContainer, styles.prev]}>
<TouchableOpacity style={styles.nextOrPrevBtn}>
<Icon style={styles.nextOrPrevBtnIcon} name="leftcircle" size={50} color="#222222" />
</TouchableOpacity>
</View>
<View style={styles.ellenorzesBtnContainer}>
<TouchableOpacity
style={!ellenorizve ? [styles.ellenorzesBtn, styles.activeBtn] : [styles.ellenorzesBtn, styles.inActiveBtn]}
onPress={ellenorzes}
disabled={ellenorizve}
>
<Text
style={!ellenorizve ? [styles.ellenorzesBtnText, styles.activeText] : [styles.ellenorzesBtnText, styles.inActiveText]}
>
Ellenőrzés
</Text>
</TouchableOpacity>
</View>
<View style={[styles.navBtnContainer]}>
<TouchableOpacity style={styles.nextOrPrevBtn}>
<Icon style={styles.nextOrPrevBtnIcon} name="rightcircle" size={50} color="#222222" />
</TouchableOpacity>
</View>
</View>
</View>
</SafeAreaView>
);
};
export default Darab;
import React, { useCallback, useState } from 'react';
import { Text, View, Dimensions, StyleSheet } from 'react-native';
import { SvgXml } from 'react-native-svg';
import MathJax from './MathJax';
import styles from "./Teszt.style";
import ValaszokGroup from "./ValaszokGroup";
import { svgs } from '../../constants';
import { Feladat } from '../Database/Feladat';
import { ScrollView } from 'react-native';
//SplashScreen.preventAutoHideAsync();
interface FeladatokProps {
feladat: Feladat;
ellenorizve: boolean
}
const { width: windowWidth, height: windowHeight } = Dimensions.get("window");
const stylesDarab = StyleSheet.create({
kerdesWrapper: {
width: windowWidth,
},
});
const Feladatok: React.FC<FeladatokProps> = ({ feladat, ellenorizve }) => {
const [selectedValaszIndex, setSelectedValaszIndex] = useState<number>(-1);
const handleSelection = useCallback((index: number) => {
setSelectedValaszIndex(index);
}, []);
let svgValue : string | null = null;
for (const [property, value] of Object.entries(svgs)) {
if (property === feladat.Kerdes2) {
svgValue = value.toString();
break;
}
}
return(
<View key={feladat.ID} style={stylesDarab.kerdesWrapper}>
<View>
<View style={styles.feladatSzamTextContainer}>
<Text style={styles.feladatSzamText}>{feladat.Feladatszam}.</Text>
</View>
<View style={styles.kerdesContainer}>
<MathJax style={styles.kerdesMathJax} html={
`<div class='kerdes'>${feladat.Kerdes}</div>`
}/>
{feladat.Kerdes2 && <SvgXml width={300} height={300} xml={svgValue}/>}
{feladat.Kerdes3 && (
<MathJax style={styles.kerdesMathJax} html={
`<div class='kerdes'>${feladat.Kerdes3}</div>`
}/>)}
</View>
</View>
<ValaszokGroup
key={feladat.ID}
valasz={[feladat.Valasz1, feladat.Valasz2, feladat.Valasz3, feladat.Valasz4]}
selectedIndex={selectedValaszIndex}
onSelection={handleSelection}
jo={feladat.Megoldas}
ellenorizve={ellenorizve}
/>
</View>
);
}
export default Feladatok
import React, { useState, useEffect } from "react";
import { StyleProp, View, ViewStyle } from 'react-native';
import styles from "./ValaszokGroup.style";
import Valaszok from "./Valaszok";
interface ValaszokGroupProps {
valasz: string[];
selectedIndex: number;
onSelection: (index: number) => void;
jo: number;
ellenorizve: boolean;
}
const ValaszokGroup: React.FC<ValaszokGroupProps> = ({
valasz,
selectedIndex,
onSelection,
jo,
ellenorizve,
}) => {
const [selectedAnswerIndex, setSelectedAnswerIndex] = useState(selectedIndex);
useEffect(() => {
setSelectedAnswerIndex(selectedIndex);
}, []);
useEffect(() => {
console.warn(selectedAnswerIndex);
}, [selectedAnswerIndex]);
const handleSelection = (index: number) => {
setSelectedAnswerIndex(index);
onSelection(index);
};
return (
<View style={styles.container}>
{valasz.map((object, i) => {
const isSelected = selectedAnswerIndex === i;
const itemStyle = isSelected ? styles.selected : styles.unSelected;
return (
<Valaszok
key={"key" + i}
valasz={object}
jo={jo === i + 1}
isSelected={isSelected}
ellenorizve={ellenorizve}
onSelection={() => handleSelection(i)}
itemStyle={itemStyle}
/>
);
})}
</View>
);
}
export default ValaszokGroup;
import React from "react";
import { StyleProp, TouchableOpacity, ViewStyle } from 'react-native';
import MathJax from './MathJax';
import styles from "./Valaszok.style";
interface ValaszokProps {
valasz: string;
isSelected: boolean;
onSelection: () => void;
jo: boolean;
ellenorizve: boolean;
itemStyle: StyleProp<ViewStyle>; // New prop to hold the item style
}
const Valaszok: React.FC<ValaszokProps> = ({
valasz,
isSelected,
onSelection,
jo,
ellenorizve,
itemStyle,
}) => {
return (
<TouchableOpacity
style={[styles.valaszButton, itemStyle]} // Apply the itemStyle here
onPress={onSelection}
disabled={ellenorizve}
>
<MathJax
style={styles.valaszMathJax}
html={`<span class='valasz' style='overflow: hidden; user-select: none; display: table; margin: 0 auto; font-size: 7vw;'>${valasz}</span>`}
/>
</TouchableOpacity>
);
}
export default Valaszok;
|
f59ec1a0b65151de877fa7754c50dbcd
|
{
"intermediate": 0.3755645155906677,
"beginner": 0.3490844964981079,
"expert": 0.2753509283065796
}
|
13,249
|
write a method of python aplication for class ImageHolder this metod called init(), at root folder it is open folder income, and in this folder should be pairs of files first file of pair is image in png formate, and second file with same to image file name but with txt extension have an description of image inside. method reads files from "imcome"subfolder and form from it for each pair of files an list in which it stories fields: index - a number of pair ascending, pathtoimage - path to image file to access; pathtodescription - path to txt desciption of image to file with same name to png image from pair, preview - fied with generated preview of image with size of 128px in its width, field edited with default value false, it is marking when content was changed and required saving. for creating and editing images it supposed to use open-cv library
|
57994853269f33d4223ab0d443e3a678
|
{
"intermediate": 0.6436477303504944,
"beginner": 0.12115105241537094,
"expert": 0.23520122468471527
}
|
13,250
|
как избавится от yTrain?
var xTrain = await sentenceEncoder.embed(sentences);
var yTrain = tf.tensor2d(
trainingData.map(t => [t.type == "greeting" ? 1 : 0, t.type == "goodbye" ? 1 : 0, t.type == "insult" ? 1 : 0, t.type == "compliment" ? 1 : 0, t.type == "all" ? 1 : 0])
)
const model = tf.sequential();
model.add(
tf.layers.dense({
inputShape: [xTrain.shape[1]],
activation: "softmax",
units: 5
})
)
model.compile({
loss: "categoricalCrossentropy",
optimizer: tf.train.adam(0.001),
metrics: ["accuracy"]
});
const onBatchEnd = (batch, logs) => {
console.log('Accuracy', logs.acc);
}
// Train Model
await model.fit(xTrain, yTrain, {
batchSize: 32,
validationSplit: 0.1,
shuffle: true,
epochs: 300,
callbacks: { onBatchEnd }
}).then(info => {
console.log('Final accuracy', info.history.acc);
});
return model;
|
14e4c0531bea260c46008dacc67c8dc0
|
{
"intermediate": 0.3518863022327423,
"beginner": 0.19500772655010223,
"expert": 0.45310595631599426
}
|
13,251
|
please check this etsy shop and tells me what can be improved https://www.etsy.com/fr/shop/IISephiraII?ref=l2-about-shopname
|
575ea5346a40960a7532a5ccf3dac0c7
|
{
"intermediate": 0.34722429513931274,
"beginner": 0.3178582787513733,
"expert": 0.3349173963069916
}
|
13,252
|
Code me a website that uses HTML, CSS, JavaScript and Firebase. I want it to have an account system with a sign up page and a log in page, when somene logs in or creates a new account it will save their session to their browser allowing them to stay signed in unless they clcik the sign out button, there will be a page to create a new forum / thread which you will be able to give a title and contents, once a thraed is created it will give you a link to it and will appaer on the home page for one of the most recent threads and the link it provided and where it on the home page leads to is a page specifically for that thread which users can reply to if signed in
|
1b06acfc0f67e21f2686aa818f7e8394
|
{
"intermediate": 0.6609074473381042,
"beginner": 0.16830365359783173,
"expert": 0.17078885436058044
}
|
13,253
|
(date_diff('day', Invoice.duedate, current_date) = CAST('{{Data.Workflow.a}}' AS INTEGER) what this mean by?
|
c7a55ac44cf4d6bcd7832af4febc47b0
|
{
"intermediate": 0.34075993299484253,
"beginner": 0.38629117608070374,
"expert": 0.2729489207267761
}
|
13,254
|
Welcome to your first project. Develop a catalog for a company. Assume that this company sells three different Items. The seller can sell individual items or a combination of any two items. A gift pack is a special combination that contains all three items. Here are some special considerations:
If a customer purchases individual items, he does not receive any discount.
If a customer purchases a combo pack with two unique items, he gets a 10% discount.
If the customer purchases a gift pack, he gets a 25% discount.
|
1d8517cb7b004901225af9e1e829b80d
|
{
"intermediate": 0.27200064063072205,
"beginner": 0.39614537358283997,
"expert": 0.331853985786438
}
|
13,255
|
Make a Scratch code draft for a B10 game mode, it should have 3 sprites: Menubar (to navigate using starting the game), fireball and segments (to shoot segments to the bar) and progress bar (to collect segments)
|
9dbbd51d85fc96c439ecbe4c62a4cec9
|
{
"intermediate": 0.3812495172023773,
"beginner": 0.22621475160121918,
"expert": 0.3925356864929199
}
|
13,256
|
<Controller
control={control}
name={`step1.${input.label.toLowerCase()}`}
rules={{ required: true }}
render={({ field }) => (
<Input
{...input}
{...field}
error={formState.errors[input.label.toLowerCase()]}
/>
)}
/>
I have such controller, using react-hook-form. The required is set to 'true'. though I'm still able to submit the form is fields are empty. What am I missing?
|
fc68f029a42cd6eaa4da9b12a135275e
|
{
"intermediate": 0.5322191715240479,
"beginner": 0.24135495722293854,
"expert": 0.2264259159564972
}
|
13,257
|
Найди и исправь в этом коде следующую ошибку - В задании с подменю, многократный клик по ссылке должен открывать и закрывать подменю. В вашей реализации подменю одно подменю больше не откроется (если не кликать по другим подменю)
let arr = []
function click (){
const thisClosest = this.closest('.menu__item')
if (thisClosest.querySelector(".menu__item")){
event.preventDefault();
thisClosest.querySelector(".menu .menu_sub").classList.add("menu_active");
if (arr.length > 0) {
arr.pop().classList.remove("menu_active");
}
arr.push(thisClosest.querySelector(".menu .menu_sub"));
}
}
let menuLink = Array.from(document.querySelectorAll(`.menu__link`))
for (let i = 0; i < menuLink.length; i++) {
menuLink[i].addEventListener("click", click)
}
|
bef243b12036d3825d7b33919dcec04d
|
{
"intermediate": 0.38279926776885986,
"beginner": 0.3535323739051819,
"expert": 0.2636682987213135
}
|
13,258
|
Make a Scratch code draft for this thing:
Drag a progress bar.
Catching segments.
Blue = right, Orange = wrong, Light Blue = 2x blue, Red = BSOD, Pink = minus, Gray = empty, Green = fills with 100% blue progress,
Popups:
Annoying popup, Clippy (moves), Mine (touch to get a BSOD), Clippy Mine (moves and gets a BSOD if you touch)
Taskbar:
Begin button to open a menu
A fake time
Begin menu
Start the game to the latest level
Start the game from level 1
Adjust settings
A copy of DOS called ProgressDOS
Get help of the game
Restart and shutdown
|
4d6ac2f5a2fb1a3924024afa4a3fc7fc
|
{
"intermediate": 0.36149293184280396,
"beginner": 0.29058241844177246,
"expert": 0.34792467951774597
}
|
13,259
|
def redraw(self):
# Clear the screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Set up the projection matrix
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, self.width / self.height, 0.1, 100.0)
# Set up the model-view matrix
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(self.xpos, self.ypos, -5.0)
# Draw the cube from the buffer
glEnableClientState(GL_VERTEX_ARRAY)
glBindBuffer(GL_ARRAY_BUFFER, self.vertex_buffer)
glVertexPointer(3, GL_FLOAT, 0, None)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.index_buffer)
glDrawElements(GL_QUADS, self.indices.size, GL_UNSIGNED_INT, None)
glDisableClientState(GL_VERTEX_ARRAY) this redraw is never updating
|
7b048e5354f5782d97fe83cf870d54c0
|
{
"intermediate": 0.44721850752830505,
"beginner": 0.3021875321865082,
"expert": 0.25059401988983154
}
|
13,260
|
убрать категории
var yTrain = tf.tensor2d(
trainingData.map(t => [t.type == "greeting" ? 1 : 0, t.type == "goodbye" ? 1 : 0, t.type == "insult" ? 1 : 0, t.type == "compliment" ? 1 : 0, t.type == "all" ? 1 : 0])
)
|
68c3d796dbf0d52204b80419cb87af28
|
{
"intermediate": 0.25146952271461487,
"beginner": 0.21696603298187256,
"expert": 0.5315644145011902
}
|
13,261
|
write java program in GUI that change 5 currencies
|
f158377e7715baa8d6a24fa8f322c04b
|
{
"intermediate": 0.3544567823410034,
"beginner": 0.3398043215274811,
"expert": 0.3057389557361603
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.