row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
17,080
#IMPORTS--------------------------------------------------------------- import PySimpleGUI as sg import sqlitedb as db from rpa_sql import * #IN BOOK IT DOES NOT SAY IMPORT THIS BUT YOU HAVE TO from rpa_gui_entry import show_rpa_form #VARIABLES/LISTS (I think)------------------------------------------------- sg.theme('Light Brown 1') FORM_FONT = 'Calibri 16' LABEL_SIZE = (10,1) BUTTON_SIZE = (7,1) BUTTON_PAD = ((10,0),(20,0)) BG = 'lightblue' db.db_file = rpa_database #IN BOOK IT SAYS db.db_file = mission_database BUT CHANGE IT TO db.db_file = rpa_database rpa_list = [] rpa_data = [] data_index = -1 #WINDOW/LAYOUT------------------------------------------------- form = [ [ sg.Text('Registration', size=LABEL_SIZE, background_color = BG), sg.Text('', key = 'reg', background_color = BG) ], [ sg.Text('Type', size=LABEL_SIZE, background_color = BG), sg.Text('', key = 'type', background_color = BG) ], ] layout = [ [ sg.Table(values = rpa_list, headings = ['Name','Type'], max_col_width=20, key = 'table', auto_size_columns = False, col_widths = [15,15], justification = 'left', display_row_numbers=False, num_rows = 10, background_color='white', alternating_row_color=('lightgray'), selected_row_colors=('white', 'black'), row_height=30, enable_events = True, font = FORM_FONT), ], [ sg.OK('OK', key = 'ok', pad=BUTTON_PAD, size=BUTTON_SIZE ), sg.Button('Add', key = 'add', pad=BUTTON_PAD, size=BUTTON_SIZE ), sg.Button('Edit', key = 'edit', pad=BUTTON_PAD, size=BUTTON_SIZE ), sg.Button('Delete', key = 'delete', pad=BUTTON_PAD, size=BUTTON_SIZE ), ] ] #FUNCTIONS--------------------------------------------------------------------- def rpa_data_to_list(): global rpa_list, data_index sql = """ SELECT rpa_reg, rpa_name, rpa_weight FROM rpa INNER JOIN rpa_type ON rpa.rpa_type_id = rpa_type.rpa_type_id """ rpa_list = db.query_table('SELECT rpa_reg FROM rpa') values = [] for rpa in rpa_list: values.append([rpa[0]]) window['table'].update(values = values) def rpa_data_to_form(reg): #Get values for the selected rpa global rpa_data if data_index > -1: if reg == None: reg = rpa_list[data_index][0] sql_query = ''' SELECT * FROM rpa INNER JOIN rpa_type ON rpa.rpa_type_id = rpa_type.rpa_type_id WHERE rpa_reg = ''' + '"'+reg+'";' rpa_data = db.query_table(sql_query) def rpa_type_name_to_id(s): sql_query = ''' SELECT * FROM rpa_type WHERE rpa_type_name = ''' + '"'+s+'";' #IN BOOKLET IT SAYS rpa_name = IN THE LINE ABOVE IT NEEDS TO BE rpa_type_name = d = db.query_table(sql_query) print('rpa_id_from_name = ' ,d) return d[0][0] #MISC STUFF------------------------------------------------------------------- window = sg.Window("RPA List", layout, finalize=True, font = FORM_FONT, margins = (10,20)) rpa_data_to_list() rpa_data_to_form(None) #MAIN LOOP-------------------------------------------------------------------- while True: event, values = window.read(timeout=10) if not event == '__TIMEOUT__': print(event,'|', values) if event in ["Exit", sg.WIN_CLOSED, 'ok']: break elif event == 'list': index = values['table'][0] data_index = index rpa_data_to_form(None) elif event in ['add','edit']: if event == 'edit' and data_index > -1: data = {} data['rpa_reg'] = rpa_data[0][1] data['rpa_type'] = rpa_data[0][4] else: data = None rpa_data = None data = show_rpa_form(data) if data != None: rpa = [] rpa.append(data['rpa_reg']) rpa.append(rpa_type_name_to_id(data['rpa_type'])) if rpa_data == None: #add to the list sql = """ INSERT INTO rpa(rpa_reg, rpa_type_id) VALUES(?,?); """ id = db.insert_record(sql, rpa) print('Added rpa record', id) else: #edit the list rpa.append(rpa_data[0][0]) sql = """ UPDATE rpa SET rpa_reg = ?, rpa_type_id = ? WHERE rpa_id = ? """ id = db.update_record(sql, rpa) print('Updated rpa record', id) rpa_data_to_list() rpa_data_to_form(data['rpa_reg']) elif event == 'delete': if rpa_data != None: data = [ rpa_data[0][0] ] sql = """ DELETE FROM rpa_type WHERE rpa_tyep_id = ? """ ok = db.update_record(sql, data) if ok: print('Record deleted') rpa_data_to_list() rpa_data_to_form(None) window.close() The error: Traceback (most recent call last): File "/Users/kory/mu_code/rpa_table.py", line 166, in <module> data = [ rpa_data[0][0] ] IndexError: list index out of range Help me fix my code please
2ee2b945bf2efee290fbbc52f91f0754
{ "intermediate": 0.5080114603042603, "beginner": 0.18885231018066406, "expert": 0.30313625931739807 }
17,081
we have input[a1,a2],[b1,b2] and we want to write a python script to get [max(a1,b1),max(a2,b2)]
c0ee83ecdd09db052b87876cd06be3d7
{ "intermediate": 0.2865667939186096, "beginner": 0.32604458928108215, "expert": 0.3873886168003082 }
17,082
corelation计算
044f3d6fac647307d77c5a9fc95525c3
{ "intermediate": 0.29759418964385986, "beginner": 0.47197219729423523, "expert": 0.2304335981607437 }
17,083
make scirpt from roblox studio that make you wear clothes like an account
7acb3c5d7105a39ab3c1b06658ddb0d1
{ "intermediate": 0.3781799376010895, "beginner": 0.2517862319946289, "expert": 0.370033860206604 }
17,084
can you make scirpt that make all players on the game wear like account in roblox in roblox studio
9ab9a6561144de320b782d15bf365769
{ "intermediate": 0.2793760597705841, "beginner": 0.1790153533220291, "expert": 0.5416086316108704 }
17,085
For indirection,use arrays,declare “var$n=value”, or (for sh) read/eval是什么意思?
7559b731f5a31706208c210af47b88f1
{ "intermediate": 0.19464902579784393, "beginner": 0.688780665397644, "expert": 0.11657031625509262 }
17,086
can you make movemenet speed and character scirpt in roblox studio
27ea6b770f03462a5a12caed6874ba16
{ "intermediate": 0.29861006140708923, "beginner": 0.16567589342594147, "expert": 0.5357140302658081 }
17,087
Hi, Please give me a step-by-step configuration guidance regarding how to integrate Azure AD with Amazon EKS cluster via OIDC. Also please share which document or link do your refer to generate the content
50a04ada8fb28b83825b724d48675433
{ "intermediate": 0.42284584045410156, "beginner": 0.2613515853881836, "expert": 0.31580251455307007 }
17,088
how to install tensorflow
873a87b9893ae17e335a438853866b9a
{ "intermediate": 0.43521228432655334, "beginner": 0.11383746564388275, "expert": 0.4509502053260803 }
17,089
Color of Power BI chart not changing even tough manually changing
41e470cc334f34772f838fe81b78af77
{ "intermediate": 0.32297632098197937, "beginner": 0.29405704140663147, "expert": 0.38296666741371155 }
17,090
im working on a decky plugin why does my custom websites variable get reset once the user enters for example google.com? import { ButtonItem, definePlugin, findSP, Menu, MenuItem, ModalRoot, ModalRootProps, PanelSection, PanelSectionRow, ServerAPI, showContextMenu, showModal, staticClasses, TextField, ToggleField, } from "decky-frontend-lib"; import { useContext, useEffect, useReducer, useState, VFC, createContext } from "react"; import { FaRocket } from "react-icons/fa"; // Define an action type for updating customWebsites type UpdateCustomWebsitesAction = { type: 'UPDATE_CUSTOM_WEBSITES'; customWebsites: string[]; }; // Define a reducer function for updating customWebsites const customWebsitesReducer = ( state: string[], action: UpdateCustomWebsitesAction ) => { console.log(`action: ${JSON.stringify(action)}`); switch (action.type) { case 'UPDATE_CUSTOM_WEBSITES': return action.customWebsites; default: return state; } }; // Create a context with an empty array as the default value const CustomWebsitesContext = createContext<{ customWebsites: string[]; dispatch: React.Dispatch<UpdateCustomWebsitesAction>; }>({ customWebsites: [], dispatch: () => {}, }); // Create a provider component that takes in children as a prop const CustomWebsitesProvider: React.FC = ({ children }) => { // Create a state variable and dispatch function for customWebsites const [customWebsites, dispatch] = useReducer(customWebsitesReducer, []); // Render the provider and pass in the customWebsites state and dispatch function as the value return ( <CustomWebsitesContext.Provider value={{ customWebsites, dispatch }}> {children} </CustomWebsitesContext.Provider> ); }; type SearchModalProps = ModalRootProps & { setModalResult?(result: string[]): void; promptText: string; }; const SearchModal: VFC<SearchModalProps> = ({ closeModal, setModalResult, promptText }) => { console.log('SearchModal rendered'); const [searchText, setSearchText] = useState(''); const handleTextChange = (e: React.ChangeEvent<HTMLInputElement>) => { setSearchText(e.target.value); }; const handleSubmit = () => { // Split the entered text by commas and trim any whitespace const websites = searchText.split(',').map((website) => website.trim()); console.log(`websites: ${JSON.stringify(websites)}`); setModalResult && setModalResult(websites); closeModal && closeModal(); }; return ( <ModalRoot closeModal={handleSubmit}> <form> <TextField focusOnMount={true} label="Websites" placeholder={promptText} onChange={handleTextChange} /> <p>You can separate multiple websites by using commas.</p> <button type="button" onClick={handleSubmit}>Submit</button> </form> </ModalRoot> ); }; const Content: VFC<{ serverAPI: ServerAPI }> = ({ serverAPI }) => { console.log('Content rendered'); // Use the useContext hook to access customWebsites and dispatch from the context const { customWebsites, dispatch } = useContext(CustomWebsitesContext); const [options, setOptions] = useState({ epicGames: false, gogGalaxy: false, origin: false, uplay: false, battleNet: false, amazonGames: false, eaApp: false, legacyGames: false, itchIo: false, humbleGames: false, indieGala: false, rockstar: false, glyph: false, minecraft: false, psPlus: false, dmm: false, xboxGamePass: false, geforceNow: false, amazonLuna:false, netflix:false, hulu:false, disneyPlus:false, amazonPrimeVideo:false, youtube:false }); const [progress, setProgress] = useState({ percent:0, status:'' }); const [separateAppIds, setSeparateAppIds] = useState(false); const [clickedButton, setClickedButton] = useState(''); useEffect(() => { console.log(`customWebsites updated:${JSON.stringify(customWebsites)}`); }, [customWebsites]); const handleButtonClick = (name:string) => { setOptions((prevOptions) => ({ ...prevOptions, [name]: !prevOptions[name], })); }; const handleInstallClick = async () => { console.log('handleInstallClick called'); const selectedLaunchers = Object.entries(options) .filter(([_, isSelected]) => isSelected) .map(([name, _]) => name.charAt(0).toUpperCase() + name.slice(1)) .join(', '); setProgress({ percent:0, status:`Calling serverAPI... Installing ${selectedLaunchers}` }); console.log(`Selected options:${JSON.stringify(options)}`); console.log(`customWebsites:${JSON.stringify(customWebsites)}`); try { const result = await serverAPI.callPluginMethod("install", { selected_options: options, custom_websites: customWebsites, separate_app_ids: separateAppIds, start_fresh: false // Pass true for the start_fresh parameter }); if (result) { setProgress({ percent:100, status:'Installation successful!' }); alert('Installation successful!'); } else { setProgress({ percent:100, status:'Installation failed.' }); alert('Installation failed.'); } } catch (error) { setProgress({ percent:100, status:'Installation failed.' }); console.error('Error calling _main method on server-side plugin:', error); } }; const handleStartFreshClick = async () => { console.log('handleStartFreshClick called'); // Call the install method on the server-side plugin with the appropriate arguments try { const result = await serverAPI.callPluginMethod("install", { selected_options: options, custom_websites: customWebsites, separate_app_ids: separateAppIds, start_fresh: true // Pass true for the start_fresh parameter }); if (result) { setProgress({ percent:100, status:'Installation successful!' }); alert('Installation successful!'); } else { setProgress({ percent:100, status:'Installation failed.' }); alert('Installation failed.'); } } catch (error) { setProgress({ percent:100, status:'Installation failed.' }); console.error('Error calling _main method on server-side plugin:', error); } }; const handleCreateWebsiteShortcutClick = async () => { console.log('handleCreateWebsiteShortcutClick called'); setClickedButton('createWebsiteShortcut'); showModal( <SearchModal promptText="Enter website" setModalResult={(result) => { console.log(`result:${JSON.stringify(result)}`); if (clickedButton === 'createWebsiteShortcut') { // Handle result for createWebsiteShortcut button dispatch({ type:'UPDATE_CUSTOM_WEBSITES', customWebsites:result }); } }} />, findSP() ); }; const optionsData = [ { name: 'epicGames', label: 'Epic Games' }, { name: 'gogGalaxy', label: 'Gog Galaxy' }, { name: 'origin', label: 'Origin' }, { name: 'uplay', label: 'Uplay' }, { name: 'battleNet', label: 'Battle.net' }, { name: 'amazonGames', label: 'Amazon Games' }, { name: 'eaApp', label: 'EA App' }, { name: 'legacyGames', label: 'Legacy Games' }, { name: 'itchIo', label: 'Itch.io' }, { name: 'humbleGames', label: 'Humble Games' }, { name: 'indieGala', label: 'IndieGala Client' }, { name: 'rockstar', label: 'Rockstar Games Launcher' }, { name: 'glyph', label: 'Glyph Laucnher' }, { name: 'minecraft', label: 'Minecraft' }, { name: 'psPlus', label: 'Playstation Plus' }, { name: 'dmm', label: 'DMM Games' }, { name: 'xboxGamePass', label: 'Xbox Game Pass' }, { name: 'geforceNow', label: 'GeForce Now' }, { name: 'amazonLuna', label: 'Amazon Luna' }, { name: 'netflix', label: 'Netflix' }, { name: 'hulu', label: 'Hulu' }, { name: 'disneyPlus', label: 'Disney+' }, { name: 'amazonPrimeVideo', label: 'Amazon Prime Video' }, { name: 'youtube', label: 'Youtube' } ]; const launcherOptions = optionsData.filter(({name}) => ['epicGames', 'gogGalaxy', 'origin', 'uplay', 'battleNet', 'amazonGames', 'eaApp', 'legacyGames', 'humbleGames', 'indieGala', 'minecraft', 'psPlus'].includes(name)); const streamingOptions = optionsData.filter(({name}) => ['xboxGamePass','geforceNow','amazonLuna','netflix','hulu','disneyPlus','amazonPrimeVideo','youtube'].includes(name)); return ( <> <PanelSectionRow style={{ fontSize: "16px", fontWeight: "bold", marginBottom: "10px" }}> Welcome to the decky plugin version of NonSteamLaunchers! I hope it works... aka nasty lawn chairs </PanelSectionRow> <PanelSectionRow style={{ fontSize: "12px", marginBottom: "10px" }}> Thank you for everyone's support and contributions, this is the plugin we have all been waiting for... installing your favorite launchers in the easiest way possible. Enjoy! </PanelSectionRow> <PanelSectionRow> <ToggleField label="Separate App IDs" checked={separateAppIds} onChange={setSeparateAppIds} /> </PanelSectionRow> <PanelSectionRow> <progress value={progress.percent} max={100} /> <div>{progress.status}</div> </PanelSectionRow> <PanelSection> <ButtonItem layout="below" onClick={handleInstallClick}> Install </ButtonItem> <ButtonItem layout="below" onClick={handleStartFreshClick}> Start Fresh </ButtonItem> <ButtonItem layout="below" onClick={handleCreateWebsiteShortcutClick}> Create Website Shortcut </ButtonItem> <PanelSectionRow> <ButtonItem layout="below" onClick={(e: React.MouseEvent) => showContextMenu( <Menu label="Menu" cancelText="CAAAANCEL" onCancel={() => {}}> <MenuItem onSelected={() => {}}>Item #1</MenuItem> <MenuItem onSelected={() => {}}>Item #2</MenuItem> <MenuItem onSelected={() => {}}>Item #3</MenuItem> </Menu>, e.currentTarget ?? window ) } > does nothing yet </ButtonItem> </PanelSectionRow> </PanelSection> <PanelSection title="Game Launchers"> <PanelSectionRow style={{ fontSize: "12px", marginBottom: "10px" }}> Here you choose your launchers you want to install and let NSL do the rest. Once Steam restarts your launchers will be in your library! </PanelSectionRow> <PanelSectionRow> {launcherOptions.map(({ name, label }) => ( <ButtonItem className={options[name] ? 'selected' : ''} layout="below" onClick={() => handleButtonClick(name)} > <span className="checkmark">{options[name] ? '✓' : ''}</span>{' '} {label} </ButtonItem> ))} </PanelSectionRow> </PanelSection> <PanelSection title="Game and Movie Streaming"> <PanelSectionRow style={{ fontSize: "12px", marginBottom: "10px" }}> Please install Google Chrome via the Discover Store in desktop mode first. NSL uses Chrome to launch these sites. Do NOT "Force Compatability" on these they will not open with proton. </PanelSectionRow> <PanelSectionRow> {streamingOptions.map(({ name, label }) => ( <ButtonItem className={options[name] ? 'selected' : ''} layout="below" onClick={() => handleButtonClick(name)} > <span className="checkmark">{options[name] ? '✓' : ''}</span>{' '} {label} </ButtonItem> ))} </PanelSectionRow> </PanelSection> <style> {` .checkmark { color: green; } .selected { background-color: #eee; } progress { display:block; width: 100%; margin-top: 5px; height: 20px; } pre { white-space: pre-wrap; } .decky-ButtonItem { margin-bottom: 10px; border-bottom: none; } .decky-PanelSection { border-bottom: none; } `} </style> </> ); }; export default definePlugin((serverApi: ServerAPI) => { return { title: <div className={staticClasses.Title}>NonSteamLaunchers</div>, content: ( <CustomWebsitesProvider> <Content serverAPI={serverApi} /> </CustomWebsitesProvider> ), icon: <FaRocket />, }; });
3a70bedeb101e0217f8eb242ab401cfb
{ "intermediate": 0.4527292549610138, "beginner": 0.3713034689426422, "expert": 0.1759672611951828 }
17,091
The cells in Column are text values presented in the following format dd/mm/yyyy The yyyy in Column A are different. In cells F1 and F2 are text values presented in the following format dd/mm. I want a formula that will extraxt the dd/mm in cell A1 and be able to determine which of the following values is smaller, (A1 - F1) or (F2 - A1). If (A1 - F1) is smaller then (F2 - A1) then the If statement will read "Date is closer to Previous Month" If (F2 - A1) is smaller than (A1 - F1) then the If statement will read "Date is closer to Next Month"
5c94193cfd314e9b55a35f2ee3e986dd
{ "intermediate": 0.3908330202102661, "beginner": 0.27456945180892944, "expert": 0.33459755778312683 }
17,092
hi there, please make a website with a table of 1 row with 4 cells [ I = 0,1,2,3]. in each cell should be a link. if click of cell [0] a global variable globali should be = 0; if cell[1] ===> globali = 1;
ed962290f7228bd27e631051f2f33830
{ "intermediate": 0.2592928409576416, "beginner": 0.3662562072277069, "expert": 0.3744509518146515 }
17,093
what does " BLG CQBK FEE " means?
7f0b7d02c6d429868c1d2b228175871f
{ "intermediate": 0.3291993737220764, "beginner": 0.3171546459197998, "expert": 0.3536459505558014 }
17,094
Original error was: No module named 'numpy.core._multiarray_umath'
349d4601544519406f345f2bfaefa8f1
{ "intermediate": 0.4092281460762024, "beginner": 0.2736719250679016, "expert": 0.3170998990535736 }
17,095
You are asked to answer the corresponding questions: As such, we should prompt the user to enter the number of employees, then in a loop we prompt the user to input the basic salary and calculate net salary as per the formula: (Net salary basic salary - 5% of the basic salary). For each entered salary, we should display the basic salary and the calculated net salary using a proper message : a- Draw the flowchart that represents the above problem. b- Write down the pseudocode of the above problem. c- Write the Python code of the above problem. Include a screenshot that shows the output after executing the program. The output should be like the below sample:
73f0ea2cc0a886a1592c19cb14a5240e
{ "intermediate": 0.23695990443229675, "beginner": 0.5445366501808167, "expert": 0.21850347518920898 }
17,096
мне нужно сделать 2 класса но чтобы не было дубляжа кода 1 должен быть без возможности провалить квест второй с этой возможностью public class VehicleStartState : IPayloadState<IQuest> { private readonly SessionQuestStateMachine stateMachine; private readonly FatalFailureConditionHandler fatalFailureConditionHandler; private readonly CompletionConditionHandler completionConditionHandler; private readonly IPublisher publisher; private List<IFailureCondition> conditionsForStartingCar; private IQuest quest; [Inject] private StatisticsProvider statisticsProvider; [Inject] private User user; public VehicleStartState( SessionQuestStateMachine stateMachine, FatalFailureConditionHandler fatalFailureConditionHandler, CompletionConditionHandler completionConditionHandler, IPublisher publisher) { this.stateMachine = stateMachine; this.fatalFailureConditionHandler = fatalFailureConditionHandler; this.completionConditionHandler = completionConditionHandler; this.publisher = publisher; } public void Enter(IQuest quest) { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.InProgress); Debug.Log($"Ожидание запуска двигателя автомобиля"); this.quest = quest; var completionConditions = quest.IsCarNeedReadyToMove ? new List<ICompletionCondition>() { new CarIsReadyToMove() } : new List<ICompletionCondition>(); conditionsForStartingCar = new List<IFailureCondition> { new DrivingWithoutSeatBelt(), new LowBeamHeadlightsNotIncluded(), new GearboxIsNotInNeutralPosition() }; fatalFailureConditionHandler.Start(conditionsForStartingCar, CompleteQuestWithFailure); completionConditionHandler.Start(completionConditions, CompleteQuestWithSuccess); } private void CompleteQuestWithFailure() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Failed); Debug.Log($"Квест завершен неудачей"); publisher.Publish(new QuestWithFailureMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } private void CompleteQuestWithSuccess() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Completed); switch (quest) { case QuestComposite quest: stateMachine.Enter<StartCompositeQuestState, QuestComposite>(quest); break; case Quest quest: stateMachine.Enter<StartQuestState, IQuest>(quest); break; default: break; } } public void Exit() { fatalFailureConditionHandler.Stop(); completionConditionHandler.Stop(); } }
925d84ae2e0ff4eb2365d8844a589b24
{ "intermediate": 0.3548637330532074, "beginner": 0.5164393782615662, "expert": 0.12869691848754883 }
17,097
мне нужно сделать 2 класса но чтобы не было дубляжа кода 1 должен быть без возможности провалить квест второй с этой возможностью public class VehicleStartState : IPayloadState<IQuest> { private readonly SessionQuestStateMachine stateMachine; private readonly FatalFailureConditionHandler fatalFailureConditionHandler; private readonly CompletionConditionHandler completionConditionHandler; private readonly IPublisher publisher; private List<IFailureCondition> conditionsForStartingCar; private IQuest quest; [Inject] private StatisticsProvider statisticsProvider; [Inject] private User user; public VehicleStartState( SessionQuestStateMachine stateMachine, FatalFailureConditionHandler fatalFailureConditionHandler, CompletionConditionHandler completionConditionHandler, IPublisher publisher) { this.stateMachine = stateMachine; this.fatalFailureConditionHandler = fatalFailureConditionHandler; this.completionConditionHandler = completionConditionHandler; this.publisher = publisher; } public void Enter(IQuest quest) { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.InProgress); Debug.Log($"Ожидание запуска двигателя автомобиля"); this.quest = quest; var completionConditions = quest.IsCarNeedReadyToMove ? new List<ICompletionCondition>() { new CarIsReadyToMove() } : new List<ICompletionCondition>(); conditionsForStartingCar = new List<IFailureCondition> { new DrivingWithoutSeatBelt(), new LowBeamHeadlightsNotIncluded(), new GearboxIsNotInNeutralPosition() }; fatalFailureConditionHandler.Start(conditionsForStartingCar, CompleteQuestWithFailure); completionConditionHandler.Start(completionConditions, CompleteQuestWithSuccess); } private void CompleteQuestWithFailure() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Failed); Debug.Log($"Квест завершен неудачей"); publisher.Publish(new QuestWithFailureMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } private void CompleteQuestWithSuccess() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Completed); switch (quest) { case QuestComposite quest: stateMachine.Enter<StartCompositeQuestState, QuestComposite>(quest); break; case Quest quest: stateMachine.Enter<StartQuestState, IQuest>(quest); break; default: break; } } public void Exit() { fatalFailureConditionHandler.Stop(); completionConditionHandler.Stop(); } }
ed28659040cb5e6f0a26c9785a4b079f
{ "intermediate": 0.3548637330532074, "beginner": 0.5164393782615662, "expert": 0.12869691848754883 }
17,098
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Returns: '/foo/bar/baz/asdf' why it does not returen /foo/bar/baz/asdf/quux
ed92d6aae162293bc3b0757ecb680804
{ "intermediate": 0.3453083336353302, "beginner": 0.41631364822387695, "expert": 0.23837798833847046 }
17,099
html to allign the text on top of the page
ed997a539c8a9f93be4f4340944e8f05
{ "intermediate": 0.2848566174507141, "beginner": 0.30820271372795105, "expert": 0.4069406986236572 }
17,100
how to use nanoid in nodejs
c38395f4ab232280fd18f96a20cb1057
{ "intermediate": 0.30619752407073975, "beginner": 0.07621252536773682, "expert": 0.6175900101661682 }
17,101
нужно из этого класса сделать класс без возможности провалить квест public class VehicleStartState : IPayloadState<IQuest> { private readonly SessionQuestStateMachine stateMachine; private readonly FatalFailureConditionHandler fatalFailureConditionHandler; private readonly CompletionConditionHandler completionConditionHandler; private readonly IPublisher publisher; private List<IFailureCondition> conditionsForStartingCar; private IQuest quest; [Inject] private StatisticsProvider statisticsProvider; [Inject] private User user; public VehicleStartState( SessionQuestStateMachine stateMachine, FatalFailureConditionHandler fatalFailureConditionHandler, CompletionConditionHandler completionConditionHandler, IPublisher publisher) { this.stateMachine = stateMachine; this.fatalFailureConditionHandler = fatalFailureConditionHandler; this.completionConditionHandler = completionConditionHandler; this.publisher = publisher; } public void Enter(IQuest quest) { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.InProgress); this.quest = quest; var completionConditions = quest.IsCarNeedReadyToMove ? new List<ICompletionCondition>() { new CarIsReadyToMove() } : new List<ICompletionCondition>(); conditionsForStartingCar = new List<IFailureCondition> { new DrivingWithoutSeatBelt(), new LowBeamHeadlightsNotIncluded(), new GearboxIsNotInNeutralPosition() }; fatalFailureConditionHandler.Start(conditionsForStartingCar, CompleteQuestWithFailure); completionConditionHandler.Start(completionConditions, CompleteQuestWithSuccess); } private void CompleteQuestWithFailure() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Failed); Debug.Log($"Квест завершен неудачей"); publisher.Publish(new QuestWithFailureMessage()); stateMachine.Enter<OutputOfQuestResultsState, IQuest>(quest); } private void CompleteQuestWithSuccess() { SessionResultsPuller.SetQuestResult(statisticsProvider, user, QuestResultType.Completed); switch (quest) { case QuestComposite quest: stateMachine.Enter<StartCompositeQuestState, QuestComposite>(quest); break; case Quest quest: stateMachine.Enter<StartQuestState, IQuest>(quest); break; default: break; } } public void Exit() { fatalFailureConditionHandler.Stop(); completionConditionHandler.Stop(); } }
fc1007b8f457333fbf53390627693dc4
{ "intermediate": 0.3224323093891144, "beginner": 0.5488648414611816, "expert": 0.12870286405086517 }
17,102
I want the vba code that will put the last date I clicked on a form button into F3 in the following format 'Last Update ddd/mmm/yyyy'
6ce64fbf748506cd2a07e3d49f7ba474
{ "intermediate": 0.4780864715576172, "beginner": 0.2181224822998047, "expert": 0.3037910759449005 }
17,103
You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init()
eddd09ead8ef3e0cac4fd10748f53529
{ "intermediate": 0.44554340839385986, "beginner": 0.2520657777786255, "expert": 0.30239084362983704 }
17,104
python deduplicate a list of items by field value
9e2ff45b0277ac8d829901fe59bb99dd
{ "intermediate": 0.3753410279750824, "beginner": 0.2198299914598465, "expert": 0.4048289954662323 }
17,105
us_id=findUser((long)msg.userID); error: invalid cast from type 'String' to type 'long int'
3272ea25dd06e97eac3e6faca44177ec
{ "intermediate": 0.44202515482902527, "beginner": 0.3250882625579834, "expert": 0.23288656771183014 }
17,106
write blender 3d script to create apple
9ffefd4ae1b49011e4c3c0498ee91ec0
{ "intermediate": 0.38975629210472107, "beginner": 0.24000044167041779, "expert": 0.37024328112602234 }
17,107
how to send multi banner_id and one item_id in this code of yii public static function _save($id = null) { $post = Util::getRawBody(); $post = Util::replace_post_digit($post); if ($id) { $model = CampaignTypeItem::findOne(['id' => $id]); } else { $model = new CampaignTypeItem(); } $transaction = Yii::$app->db->beginTransaction(); try { /* if (!$model->validate()) { $errors = $model->getErrors(); return ['success' => false, 'msg' => $errors]; } */ if (!empty($post['domain'])) { $website = Website::find()->where(['domain' => $post['domain']])->one(); if (!$website) { $website = new Website(); $website->domain = $post['domain']; $website->date_create = date('Y-m-d H:i:s'); if (!$website->save()) { throw new Exception('خطا در ذخیره دامین وب سایت' . $model->id); } } $post['website_id'] = $website->id; } Util::save_post_data($post, $model); if ($model->save()) { if (!empty($post['fields_val'])) { foreach ($post['fields_val'] as $key => $item) { $fieldVal = CampaignTypeItemCustomFieldValue::find()->where(['type_item_id' => $model->id, 'custom_field_id' => $key])->one(); if ($fieldVal) { $fieldVal->value = $item; } else { $fieldVal = new CampaignTypeItemCustomFieldValue(); $fieldVal->custom_field_id = $key; $fieldVal->type_item_id = $model->id; } if (!$fieldVal->save()) { throw new Exception('خطا در ذخیره مقادیر رسانه' . $model->id); } } } if (!empty($post['banner_id'])) { $itemBanner = new ItemHasCampaignBanner(); $itemBanner->item_id = $model->id; $itemBanner->banner_id = $post['banner_id']; $itemBanner->_save(); } $transaction->commit(); return ['success' => true, 'msg' => 'آیتم کمپین با موفقیت ذخیره شد', 'id' => $model->id]; } } catch (Exception $ex) { $transaction->rollBack(); return ['success' => false, 'msg' => 'Transaction failed:' . $ex->getMessage()]; } }
96455b7d12bffb8c76710009d7db50cf
{ "intermediate": 0.3690355122089386, "beginner": 0.3523506224155426, "expert": 0.2786138355731964 }
17,108
Please make a C# loop to multiply i with itself n times, it is NOT allowed to use Math.Pow()
e2a444d23da6e08e40fd173905afa758
{ "intermediate": 0.20244187116622925, "beginner": 0.6975041627883911, "expert": 0.10005390644073486 }
17,109
変数入れnextjs
2941b0179f7b24ccb34acc1910c87376
{ "intermediate": 0.4008687734603882, "beginner": 0.2759258449077606, "expert": 0.3232054114341736 }
17,110
<div class="transfers__item-body"> <div class="row"> <div class="col-12 col-md-7"> <label class="ui-label">Номер карты отправителя</label> <div class="ui-field"> <form:input class="ui-input js-mask-card" type="text" maxlength="19" autocomplete="off" path="pan1" id="cardFrom" placeholder="0000 0000 0000 0000" onkeypress="return checkCardNumber(event, this);" oninput="return CardNumberFormat(event);" aria-required="true"/> </div> <div class="ui-validate"></div> </div> как сделать, если карта не проходит валидацию, то к ui-field добавляется класс is-error и в форме отображается сообщение неверный номер карты?
534c7bb7397ea286a0a5f25bfea55e25
{ "intermediate": 0.2456110268831253, "beginner": 0.6334153413772583, "expert": 0.12097366899251938 }
17,111
python script to print 5 integers
df75b89f589e8e03260aef0f95baa158
{ "intermediate": 0.47958284616470337, "beginner": 0.2153528481721878, "expert": 0.30506432056427 }
17,112
write me a bunch of complex lines of code that can be run quickly on the command line, so that it looks like the computer is being hacked
64dbf088315011bdaaf9b1aec115ed85
{ "intermediate": 0.4100423753261566, "beginner": 0.23230405151844025, "expert": 0.35765358805656433 }
17,113
2. Create a new file called api/session.js and add the following code: import { withIronSession } from “next-iron-session”; const sessionOptions = { password: “your-password”, cookieName: “your-cookie-name”, // Other session options }; const handler = async (req, res) => { if (req.method === “POST”) { // Save data to session req.session.set(“username”, req.body.username); await req.session.save(); res.json({ message: “Data saved to session” }); } else if (req.method === “GET”) { // Get data from session const username = req.session.get(“username”); res.json({ username }); } }; export default withIronSession(handler, sessionOptions); how to pass arg to this session.js
dccce54aede08c12e7a71710be3813b8
{ "intermediate": 0.4962552785873413, "beginner": 0.29616379737854004, "expert": 0.20758096873760223 }
17,114
next-iron-session write in function
8fe87cdc9d14c5d7a1fbec3344297994
{ "intermediate": 0.2659011483192444, "beginner": 0.3280549645423889, "expert": 0.4060439169406891 }
17,115
Это один элемент RecyceleView сделай так чтобы его края были округлыми а ширина было 95 % от ширины экрана : <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" tools:ignore="UselessParent"> <com.google.android.material.imageview.ShapeableImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" /> <TextView android:id="@+id/titleTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceLarge" /> <TextView android:id="@+id/descriptionTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceMedium" /> </FrameLayout>
7c0638c8e3720ed2936d33901d39ecf2
{ "intermediate": 0.38824641704559326, "beginner": 0.2690242528915405, "expert": 0.3427293002605438 }
17,116
compare flutter and react
7a9650b37076956bcd138fda5ddd0861
{ "intermediate": 0.4336622655391693, "beginner": 0.24285590648651123, "expert": 0.32348179817199707 }
17,117
Это элемент RecyclerView сделай так чтобы все элементы имели скругленные края и имели отступы между собой : <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="200dp"> <com.google.android.material.imageview.ShapeableImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" /> <TextView android:id="@+id/titleTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceLarge" /> <TextView android:id="@+id/descriptionTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceMedium" /> </RelativeLayout>
dbc22407f0243b20be66f9de467d310f
{ "intermediate": 0.41022780537605286, "beginner": 0.26935428380966187, "expert": 0.3204179108142853 }
17,118
input_result_error { border: 1px solid #d37272 !important; }
f1d1148c9d15b1134c2ef321fc872196
{ "intermediate": 0.29805442690849304, "beginner": 0.34260696172714233, "expert": 0.3593386113643646 }
17,119
import numpy as np import scipy def clamp(z, vmin=0, vmax=1): return np.minimum(vmax * np.ones(z.shape), np.maximum(vmin * np.ones(z.shape), z)) def gradient_angle(z): dx, dy = np.gradient(z, axis=0), np.gradient(z, axis=1) return np.arctan2(dy, dx) def gradient_norm(z): dx, dy = np.gradient(z, axis=0), np.gradient(z, axis=1) return np.hypot(dx, dy) def gaussian_curvature(z, sigma=2): z = scipy.ndimage.gaussian_filter(z, sigma=sigma) zx, zy = np.gradient(z) zxx, zxy = np.gradient(zx) _, zyy = np.gradient(zy) # Gaussian curvature = K1 * K2 k = (zxx * zyy - (zxy**2)) / (1 + (zx**2) + (zy**2))**2 # mean curvature = (K1 + K2)/2 h = (zxx * (1 + zy**2) - 2 * zxy * zx * zy + zyy * (1 + zx**2)) / 2 / (1 + zx**2 + zy**2)**1.5 return k, h def hillshade(z, azimuth, zenith, talus_ref): azimuth_rad = np.pi * azimuth / 180 zenith_rad = np.pi * zenith / 180 aspect = gradient_angle(z) dn = gradient_norm(z) / talus_ref slope = np.arctan(dn) sh = np.cos(zenith_rad) * np.cos(slope) \ + np.sin(zenith_rad) * np.sin(slope) * np.cos(azimuth_rad - aspect) return (sh - sh.min()) / sh.ptp() can you convert that code to rust
9626894ebb147ff2d89c2c232e8b903e
{ "intermediate": 0.2979539632797241, "beginner": 0.26035454869270325, "expert": 0.4416915476322174 }
17,120
Could you make me a lua script so player won't lose specific tools when dies
28429f97e9e06ce6192b1cea4a436102
{ "intermediate": 0.5010364055633545, "beginner": 0.2659682035446167, "expert": 0.2329953908920288 }
17,121
Сделай так чтобы текст был на фоне картинки а сама картинка заполняла весь объем карточки : <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cardview="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="4dp" android:layout_marginTop="8dp" android:layout_marginEnd="4dp" android:layout_marginBottom="8dp" cardview:cardCornerRadius="8dp" cardview:cardElevation="2dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="200dp"> <com.google.android.material.imageview.ShapeableImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="120dp" android:adjustViewBounds="true" android:scaleType="centerCrop" /> <TextView android:id="@+id/titleTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/imageView" android:padding="8dp" android:text="Title" android:textAppearance="?android:textAppearanceLarge" /> <TextView android:id="@+id/descriptionTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/titleTextView" android:padding="8dp" android:text="Description" android:textAppearance="?android:textAppearanceMedium" /> </RelativeLayout> </androidx.cardview.widget.CardView>
d9b631f327c9c6989aea6aa11ef25b02
{ "intermediate": 0.32340770959854126, "beginner": 0.4168592095375061, "expert": 0.25973302125930786 }
17,122
Сделай так чтобы текст был на фоне картинки а сама картинка заполняла весь объем карточки , но помни что это карточка часть RecycleView : <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cardview="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="4dp" android:layout_marginTop="8dp" android:layout_marginEnd="4dp" android:layout_marginBottom="8dp" cardview:cardCornerRadius="8dp" cardview:cardElevation="2dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="200dp"> <com.google.android.material.imageview.ShapeableImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="120dp" android:adjustViewBounds="true" android:scaleType="centerCrop" /> <TextView android:id="@+id/titleTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/imageView" android:padding="8dp" android:text="Title" android:textAppearance="?android:textAppearanceLarge" /> <TextView android:id="@+id/descriptionTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/titleTextView" android:padding="8dp" android:text="Description" android:textAppearance="?android:textAppearanceMedium" /> </RelativeLayout> </androidx.cardview.widget.CardView>
65c07e55dc7dfcf878fbeff01790a7bf
{ "intermediate": 0.22542276978492737, "beginner": 0.5827377438545227, "expert": 0.19183945655822754 }
17,123
def gradient_angle(z): dx, dy = np.gradient(z, axis=0), np.gradient(z, axis=1) return np.arctan2(dy, dx) can you convert this oto rust and
7aa3f0d35a68cea49e94d299844e206b
{ "intermediate": 0.3006921410560608, "beginner": 0.4545244574546814, "expert": 0.24478338658809662 }
17,124
can you use a sigmoid function here to get the output in a signal 0,1 pip install keras_tuner import pandas as pd #We use Pandas to preprocess the data import numpy as np import matplotlib.pyplot as plt #We used Matplotlib library to visualize the data. It helped us know the data and find important trends. import keras #We use Keras to implement the machine learning models. import math import tensorflow as tf from numpy import array from tensorflow.keras.models import Sequential,Model,save_model from tensorflow.keras.layers import LSTM, Dense, Dropout, Flatten, Input from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score import seaborn as sns # Visualization sns.set_style('white', { 'axes.spines.right': False, 'axes.spines.top': False}) import io from google.colab import files from keras_tuner import RandomSearch from keras_tuner import Objective #uploaded = files.upload() #df = pd.read_csv(io.BytesIO(uploaded['VSIN1-a.csv'])) df = pd.read_excel("/content/BSAP1-a.xls").dropna()#.reset_index().drop(columns=['index']) #df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d') df['<DTYYYYMMDD>'] = pd.to_datetime(df['<DTYYYYMMDD>'], format='%Y%m%d') #df=df[::-1].reset_index(drop=True) df #df = df[~(df == 0).any(axis=1)] #df=df.reset_index(drop=True) dataset = df[['<CLOSE>']].dropna().values dataset = dataset.astype('float64') ''' df['dif'] = (df['<HIGH>']-df['<LOW>']).dropna() df['dif1'] = (df['<CLOSE>'].diff()).dropna() dataset = df[['<CLOSE>','dif', "dif1"]].dropna().values dataset = dataset.astype('float64') ''' ''' df.drop(df.tail(1).index,inplace=True) dataset = df[['<CLOSE>']].dropna().values dataset = dataset.astype('float64') ''' dataset plt.plot(df['<DTYYYYMMDD>'],df['<CLOSE>']) plt.grid() plt.show() # lookback -> timestep def create_dataset(dataset,look_back): data_x, data_y = [],[] #data_x is data and data_y is label for i in range(len(dataset)-look_back): #we want if data be beyond len(sequendatasetce), the command will not continue # اگر داده بیشتر از #len(sequendatasetce) #باشد، فرمان ادامه نمی‌یابد. data_x.append(dataset[i:(i+look_back),:]) data_y.append(dataset[i+look_back,:]) return np.array(data_x) , np.array(data_y) train_size = int(len(dataset) * 0.80) train , test = dataset[:train_size,:] , dataset[train_size:,:] scaler = StandardScaler() train = scaler.fit_transform(train) test = scaler.fit_transform(test) n_steps = 5 #timestep or look_up train_x , train_y = create_dataset(train, n_steps) test_x , test_y = create_dataset(test, n_steps) print(train_x.shape , train_y.shape) print(test_x.shape , test_y.shape) trainxr = np.reshape(train_x,(train_x.shape[0],train_x.shape[1],1)) testxr = np.reshape(test_x,(test_x.shape[0],test_x.shape[1],1)) train_x = trainxr test_x = testxr print(trainxr.shape) print(testxr.shape) def R2_Score(y_true, y_pred): SS_res = tf.reduce_sum(tf.square(y_true - y_pred)) SS_tot = tf.reduce_sum(tf.square(y_true - tf.reduce_mean(y_true))) return 1 - SS_res/(SS_tot + tf.keras.backend.epsilon()) def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) def build_model(hp): model = Sequential() model.add(LSTM(units=hp.Int('units1', min_value = 64, max_value = 512, step = 32), input_shape=(train_x.shape[1], train_x.shape[2]), return_sequences=True, kernel_regularizer=keras.regularizers.l1_l2(l1=0.01, l2=0.01))) model.add(Dropout(hp.Choice('Dropout', values = [0.2, 0.3, 0.4]))) model.add(LSTM(units=hp.Int('units2', min_value = 64, max_value = 256, step = 32))) model.add(Dense(units=1, activation='linear')) model.compile(loss = 'mse', optimizer = keras.optimizers.Adam(hp.Choice('learning_rate', values = [1e-2, 1e-3, 1e-4])), metrics=[rmse]) #early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5) #history = model.fit(train_x, train_y, validation_split=0.2, callbacks=[early_stopping], epochs=100) return model tuner = RandomSearch( build_model, objective = Objective('val_rmse', direction='min'), max_trials=3, executions_per_trial=2, directory='project_dir', project_name='test5') tuner.search(train_x, train_y, epochs=10, validation_data=(test_x, test_y)) best_model = tuner.get_best_models(num_models=1)[0] best_model.save('/content/savemodel') # loading model #new_model = tf.keras.saving.load_model('/content/savedata') predict_train = best_model.predict(train_x) predict_test = best_model.predict(test_x) print('predicted y(train):', np.reshape(predict_train[:5],-1)) print('real y(train):', train_y[:5]) predict_train = scaler.inverse_transform(predict_train) trainy = scaler.inverse_transform(train_y) predict_test = scaler.inverse_transform(predict_test) testy = scaler.inverse_transform(test_y) Answer1 = pd.DataFrame({ "Predicted": predict_train.ravel(), "real": trainy.ravel() }) Answer1.head() #train Answer1.plot(title="outcome of training data", figsize=(20,10)); plt.grid() <div dir=rtl> <font face="XB Zar" size=5> <hr /> نمایش ارور </font> </div> error=Answer1['real']-Answer1['Predicted'] error.plot(title="error of training data") plt.grid() errorr=(Answer1['real']-Answer1['Predicted'])/Answer1['real'] errorr.plot(title="error of training data (%)") plt.grid() <div dir=rtl> <font face="XB Zar" size=5> <hr /> ساخت دیتافریم و رسم مقادیر آزمایشی واقعی و پیش‌بینی شده </font> </div> Answer2 = pd.DataFrame({ "Predicted": predict_test.ravel(), "real": testy.ravel() }) Answer2.tail() #test Answer2.plot(title="outcome of test data", figsize=(20,10)); plt.grid() error1=Answer2['real']-Answer2['Predicted'] error1.plot(title="error of test data") plt.grid() <div dir=rtl> <font face="XB Zar" size=5> <hr /> نمایش درصد خطای مدل </font> </div> error2=(Answer2['real']-Answer2['Predicted'])/Answer2['real'] error2.plot(title="error of test data") plt.grid() score = best_model.evaluate(test_x, test_y, verbose = 0) print('Test loss:', score[0]) predict_train trainy train_score = math.sqrt(mean_squared_error(trainy[:,0],predict_train[:,0]))#.reshape(-1) print('RMSE of trian', train_score) test_score = math.sqrt(mean_squared_error(test_y[:,0].reshape(-1),predict_test[:,0])) print('RMSE of test', test_score) RMSE of trian 943.3192753323997 RMSE of test 26628.738837928475 $(∑ y-x)/n$ train_score1 = math.sqrt(mean_absolute_error(trainy[:,0].reshape(-1),predict_train[:,0])) print('RMAE of train', train_score1) test_score1 = math.sqrt(mean_absolute_error(test_y[:,0].reshape(-1),predict_test[:,0])) print('RMAE of test', test_score1) RMAE of train 12.706159751886348 RMAE of test 6.442473942269808 print("Train data R2 score:", r2_score(trainy[:,0].reshape(-1), predict_train[:,0])) print("Test data R2 score:", r2_score(test_y[:,0].reshape(-1), predict_test[:,0])) price_today = testy[0][-1] predicted_price = np.round(predict_test[-1][0], 2) change_percent = np.round(100 - (price_today * 100)/predicted_price, 2) end_date=df.iloc[-1]['<DTYYYYMMDD>'] print(f'The close price for Iran Khodro at {end_date} was {price_today}') print(f'The predicted close price is {predicted_price} ({change_percent}%)') <a name="lstmpred10"></a> #### Predicting next 10 days x_input=test[len(test)-n_steps:].reshape(1,-1) temp_input=list(x_input) temp_input=temp_input[0].tolist() lst_output=[] i=0 print('How many days ahead do you want to predict?') pred_days = int(input()) while(i<pred_days): if(len(temp_input)>n_steps): x_input=np.array(temp_input[1:]) #print("{} day input {}".format(i,x_input)) x_input = x_input.reshape(1,-1) x_input = x_input.reshape((1, n_steps, 1)) yhat = best_model.predict(x_input, verbose=0) #print("{} day output {}".format(i,yhat)) temp_input.extend(yhat[0].tolist()) temp_input=temp_input[1:] #print(temp_input) lst_output.extend(yhat.tolist()) i=i+1 else: x_input = x_input.reshape((1, n_steps,1)) yhat = best_model.predict(x_input, verbose=0) temp_input.extend(yhat[0].tolist()) lst_output.extend(yhat.tolist()) i=i+1 print("Output of predicted next days: ", scaler.inverse_transform(np.array(lst_output[-1]).reshape(-1,1)).reshape(1,-1)) print("Output of predicted next days: ", scaler.inverse_transform(np.array(lst_output).reshape(-1,1)).reshape(1,-1))
500c652f291347e09ba522d55dce31a2
{ "intermediate": 0.42320793867111206, "beginner": 0.33203673362731934, "expert": 0.24475529789924622 }
17,125
You are a service that translates user requests into JSON objects of type "HintResponse" according to the following TypeScript definitions:
95fdbfc302eeef95104ce07db26351ef
{ "intermediate": 0.3405829071998596, "beginner": 0.33040452003479004, "expert": 0.32901254296302795 }
17,127
I used this code: def get_klines(symbol, interval, lookback): API_KEY_BINANCE = 'your-api-key' # Replace with your Binance API key symbol = symbol.replace("/", "") # remove slash from symbol url = "https://api.binance.com/api/v3/klines" end_time = int(dt.datetime.now().timestamp() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago params = { 'symbol': symbol, 'interval': interval, 'startTime': start_time, 'endTime': end_time } headers = { 'X-MBX-APIKEY': API_KEY_BINANCE, } response = requests.get(url, params=params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print('No data found for the given timeframe and symbol') return None ohlcv = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0] / 1000).strftime('%Y-%m-%d %H:%M:%S') ohlcv.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlcv) df.set_index('Open time', inplace=True) return df interval = '1m' lookback = 10080 df = get_klines(symbol, interval, lookback) # Import the necessary libraries import numpy as np def signal_generator(df): if df is None or len(df) < 2: return '' # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] depth_analysis = [] depth_threshold = 100 for i in range(1, len(bid_depth)): if ( float(bid_depth[i][0]) >= depth_threshold and float(bid_depth[i - 1][0]) < depth_threshold ): depth_analysis.append('buy') elif ( float(ask_depth[i][0]) >= depth_threshold and float(ask_depth[i - 1][0]) < depth_threshold ): depth_analysis.append('sell') # After adding your algorithm logic, check if there is a buy or sell signal if 'buy' in depth_analysis: return 'buy' elif 'sell' in depth_analysis: return 'sell' else: return '' end_time = int(time.time() * 1000) start_time = end_time - lookback * 60 * 1000 TradeType = "BUY" or "SELL" secret_key = API_KEY_BINANCE # Replace with your actual secret key obtained from MXC Exchange access_key = API_SECRET_BINANCE # Replace with your actual access key obtained from MXC Exchange import binance while True: lookback = 10080 df = get_klines(symbol, interval, lookback) if df is not None: signals = signal_generator(df) print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Signals: {signals}") mark_price = client.ticker_price(symbol=symbol) if signals == 'buy': try: quantity = 0.1 client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) print("Long order executed!") stop_loss_price = float(mark_price) - (float(mark_price) * 0.002) print(f"Stop loss set at: {stop_loss_price}") try: client.new_order( symbol=symbol, side='SELL', type='STOP_MARKET', quantity=0.1, stopPrice=stop_loss_price ) print("Stop loss order placed!") except binance.error.ClientError as e: print(f"Error placing stop loss order: {e}") time.sleep(1) except binance.error.ClientError as e: print(f"Error executing long order: {e}") time.sleep(1) if signals == 'sell': try: quantity = 0.1 client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) print("Short order executed!") stop_loss_price = float(mark_price) + (float(mark_price) * 0.002) print(f"Stop loss set at: {stop_loss_price}") try: client.new_order( symbol=symbol, side='BUY', type='STOP_MARKET', quantity=0.1, stopPrice=stop_loss_price ) print("Stop loss order placed!") except binance.error.ClientError as e: print(f"Error placing stop loss order: {e}") time.sleep(1) except binance.error.ClientError as e: print(f"Error executing short order: {e}") time.sleep(1) time.sleep(1) But it doesn't give me any signals
4a28cef02b3c822e19a8c1273db3aa1b
{ "intermediate": 0.33613255620002747, "beginner": 0.40068018436431885, "expert": 0.2631871998310089 }
17,128
how to invoke DarkLaf jar look and feel with uimanager , dont use flatdarklaf
ac7a3c6f99e58a2f0e7b8198459eedc3
{ "intermediate": 0.6087881922721863, "beginner": 0.0841706171631813, "expert": 0.3070412278175354 }
17,129
Как грамотно уменьшить высоту , когда я это делаю снижая параметр layout_height , то иконка деформируется , я хочу чтобы иконки остались пропорциональными и высоты нижнего меню уменьшилась
1ccb86bf0998d9e2e11abe1763be7b95
{ "intermediate": 0.37425535917282104, "beginner": 0.2926502823829651, "expert": 0.3330943286418915 }
17,130
java : how to invoke darcula jar look and feel with uimanager
c7e7543ec78d99758673c4b8fc61c626
{ "intermediate": 0.6840868592262268, "beginner": 0.11792516708374023, "expert": 0.19798797369003296 }
17,131
what is the error? ERROR - Task failed with exception Traceback (most recent call last): File "/home/airflow/.local/lib/python3.7/site-packages/airflow/operators/python.py", line 175, in execute return_value = self.execute_callable() File "/home/airflow/.local/lib/python3.7/site-packages/airflow/operators/python.py", line 192, in execute_callable return self.python_callable(*self.op_args, **self.op_kwargs) File "/opt/airflow/dags/gs_clients_costs.py", line 191, in write_costs df = files[files["external_file"] == spreadseet_name] IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
37f286b685265d33f5fdaceef8e2769b
{ "intermediate": 0.5657912492752075, "beginner": 0.2067805677652359, "expert": 0.22742821276187897 }
17,132
Little Naruto along with his father went to a shopping mall. He is very eager to see the gaming zone of the mall. In the gaming zone, Naruto's father found an interesting game related to numbers and addition. So he suggested him to play that game so that Naruto could have fun and learn math at the same time. The game is as follows, there will be a list of N numbers displayed on the screen and they are moving from left to right. Before the number moves away from the screen, he is expected to remove all the occurrences of the highest and smallest digits from the number and type the remaining number on the screen in the same order. The total tickets he gets will be equal to the sum of all the correctly entered numbers after the required modification. Naruto was typing all the numbers correctly and He was continuously asking his father about the number of tickets he won in the game for different lists of numbers. Can you help with a program that accepts a list of N numbers and print the total tickets little naruto got? Read the input from STDIN and write the output to STDOUT You should not write arbitrary strings while reading the input and while printing as these contribute to the standard output. Constraints: N>2 Input Format: The first line of input contains N, the total numbers displayed on the screen. The next line of input should consists of N integers, list of numbers, each separated by single white space Output Format: The sinlge line of output must display the rewarded amount. Sample Input 1: 4 2345 3567 3450 3987 Sample Output 1: 211 Explanation 1: Here, from the Sample Input 1, we have: the total numbers displayed on the screen, N is 4 and the numbers are 2345, 3567, 3450, and 3987. Write program in c++
e6809d12c6f61bd1c70d96ff262a8743
{ "intermediate": 0.436787486076355, "beginner": 0.25464820861816406, "expert": 0.30856433510780334 }
17,133
Consider a board with M*N cells, each of which is either an empty cell (0) or a restricted cell (X). Any two adjacent (ie, sharing a horizontal or vertical boundary, but not diagonal) empty cells can be combined to form a coupled cell. Your aim is to create as many coupled cells as possible. Write a program to find the number of single cells (including both empty and restricted cells) that will remain after the cells are converted to coupled cells most optimally. Read the input from STDIN and write the output to STDOUT Do not write arbitrary strings while reading the input or while printing, as these contribute to the standard output and test cases will fail. Constraint: 1) 1 < M,N <=300Input Format: The first line of input contains M and N, separated by a single white space. The next M lines of input contains N characters each without any space between them. Each character can either be O or X, which represent empty and restricted cells respectively.Output Format: The output contains the number of single cells remaining after coupling all possible cells optimally.Sample input:3 3OOOOXXXXXSample Output:5Write program in C++
d3e651288f6e8c3d775742f5c7db7e70
{ "intermediate": 0.4518674314022064, "beginner": 0.22523298859596252, "expert": 0.32289960980415344 }
17,134
#include <iostream> #include <vector> int maxOptimalCoupledCells(int M, int N, std::vector<std::vector<char>>& board) { std::vector<std::vector<int>> visited(M, std::vector<int>(N, 0)); auto isValid = [&](int x, int y) { return 0 <= x && x < M && 0 <= y && y < N; }; auto isCoupled = [&](int x, int y) { return board[x][y] == 'O' && visited[x][y] == 0; }; auto dfs = [&](int x, int y) -> int { visited[x][y] = 1; int count = 1; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; for (int k = 0; k < 4; ++k) { int nx = x + dx[k]; int ny = y + dy[k]; if (isValid(nx, ny) && isCoupled(nx, ny)) { count += dfs(nx, ny); } } return count; }; int coupled_cells = 0; for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { if (isCoupled(i, j)) { int count = dfs(i, j); coupled_cells += count / 2; } } } return M * N - 2 * coupled_cells; } int main() { int M = 4; int N = 4; std::vector<std::vector<char>> board = { {'O', 'X', 'O', 'O'}, {'O', 'O', 'O', 'X'}, {'X', 'X', 'X', 'O'}, {'X', 'O', 'O', 'X'} }; int result = maxOptimalCoupledCells(M, N, board); std::cout << "Number of remaining single cells: " << result << std::endl; return 0; } Correct the program
3175b63be5f55cc664f7f2015a196f8b
{ "intermediate": 0.3270418047904968, "beginner": 0.36513206362724304, "expert": 0.30782607197761536 }
17,135
Write me a python code to calibrate a Generalized beta distribution based on methods moments
07629d247deef48b65f7ce995b89508f
{ "intermediate": 0.30069610476493835, "beginner": 0.12391064316034317, "expert": 0.5753933191299438 }
17,136
Explain me what this code do
747ec249c312f7f3271168da12bef00f
{ "intermediate": 0.3439602553844452, "beginner": 0.3482173681259155, "expert": 0.3078223466873169 }
17,137
:-1: ошибка: :-1: ошибка: Команда «D:\Program\SDK_AND_NDK\platform-tools\adb.exe -s emulator-5554 pull /system/bin/app_process32 C:\Users\void_\Documents\build-AndroidTest-Android_Qt_6_5_1_Clang_x86_64-Debug\app_process» завершилась с кодом 1. :-1: ошибка: Команда «D:\Program\SDK_AND_NDK\platform-tools\adb.exe -s emulator-5554 pull /system/bin/linker C:\Users\void_\Documents\build-AndroidTest-Android_Qt_6_5_1_Clang_x86_64-Debug\linker» завершилась с кодом 1. :-1: ошибка: Развёртывание пакета: не удалось получить «/system/bin/linker» в «C:\Users\void_\Documents\build-AndroidTest-Android_Qt_6_5_1_Clang_x86_64-Debug\linker». :-1: ошибка: Команда «D:\Program\SDK_AND_NDK\platform-tools\adb.exe -s emulator-5554 pull /system/lib/libc.so C:\Users\void_\Documents\build-AndroidTest-Android_Qt_6_5_1_Clang_x86_64-Debug\libc.so» завершилась с кодом 1. :-1: ошибка: Развёртывание пакета: не удалось получить «/system/lib/libc.so» в «C:\Users\void_\Documents\build-AndroidTest-Android_Qt_6_5_1_Clang_x86_64-Debug\libc.so».
d5da2af1cb162df3dc21df8610155c86
{ "intermediate": 0.4984874725341797, "beginner": 0.2327536940574646, "expert": 0.2687588930130005 }
17,138
The game mode is REVERSE: You do not have access to the statement. You have to guess what to do by observing the following set of tests: 01 Test 1 Input Expected output 2 22 2 02 Test 2 Input Expected output 3 333 33 3 03 Test 3 Input Expected output 4 4444 444 44 4 04 Test 4 Input Expected output 5 55555 5555 555 55 5 05 Test 5 Input Expected output 6 666666 66666 6666 666 66 6 06 Test 6 Input Expected output 7 7777777 777777 77777 7777 777 77 7 Please solve this with C# code.
ef16a7348834901faaadfb32f3e56287
{ "intermediate": 0.332219660282135, "beginner": 0.5115463733673096, "expert": 0.15623396635055542 }
17,139
how to use the Virgil3d virtio-gpu paravirtualized device driver with a NVIDIA card?
3c9a5f3b001a33c187061abc864b8f33
{ "intermediate": 0.3374081254005432, "beginner": 0.1894492208957672, "expert": 0.47314268350601196 }
17,140
Create a MQL5 (not MQL4, please double check code to make sure to distinguish the two different languages) indicator code to display three LWMAs with different colors of the periods: 3, 60 and 300 with the names MA1, MA2, MA3. Create an array with the price values of all MAs and sort them and calculate the difference and display that difference number continuously on the chart. Compare the difference in pips with a extern input called "Max_MA_Range" and if the difference is less or equal to the Max_MA_Range, draw a range box around the area where the MAs are within the range of the difference. Draw a text saying "BREAKOUT" and send a notification to mobile when price closes outside of this box.
4c7e38513c7f73184f111d95aa4aaf76
{ "intermediate": 0.6007573008537292, "beginner": 0.1448633223772049, "expert": 0.2543793022632599 }
17,141
initializeKeycloak() { return new Promise((resolve, reject) => { const keycloak = new Keycloak({ url: "http://192.168.1.8:8080/", realm: "sinno", clientId: "sinno_pd_manager", }); keycloak.init({ onLoad: "login-required", checkLoginIframe: false, // otherwise it would reload the window every so seconds enableLogging: true, pkceMethod: 'S256', flow: 'standard', // redirectUri:'/' }).then(async (authenticated) => { if (authenticated) { this.keycloak = keycloak //把注册的keycloak存到store里 //添加定时器 await this.createRefreshTokenTimer(keycloak); Cookies.set('token',keycloak.token) resolve(`首次登录,Keycloak授权成功!\nToken:\n${this.keycloak.token}`) } else { reject.error(new Error(`Keycloak授权失败!${authenticated}`)) window.location.reload() } }) }).then(async (success_msg) => { console.log(success_msg) }).catch((error) => { console.error("首次登录,Keycloak授权失败!", error) window.location.reload() }) },把这段代码改为同步的
c0fac92dc03dc0528e29533b25f6caf0
{ "intermediate": 0.3454556465148926, "beginner": 0.35480353236198425, "expert": 0.2997407913208008 }
17,142
почему не работает этот код: export const remove = async (req, res) => { try { console.log(1); const projectName = req.params.name; ProjectModel.findOneAndDelete({ name: projectName }, (err, doc) => { if (err) { return res.status(500).json({ error: true, message: 'Failed to delete the project' }); } if (!doc) { return res.status(404).json({ error: true, message: 'Project not found' }); } res.json({ success: true }) }); } catch (err) { console.log(err); res.status(500).json({ error: true, message: 'Failed to delete the project' }) } };
4f158d358f1a8593293a0721a51ac433
{ "intermediate": 0.37293124198913574, "beginner": 0.3993076682090759, "expert": 0.22776104509830475 }
17,143
what's the weather like?
8e24d193dee18af441b62f515cba41fa
{ "intermediate": 0.3218054175376892, "beginner": 0.3962952196598053, "expert": 0.2818993628025055 }
17,144
how can I link between the phone and the computer
4bb5f5d8ef51fdd52a69fb88436c9cb2
{ "intermediate": 0.3251138925552368, "beginner": 0.22255976498126984, "expert": 0.45232635736465454 }
17,145
What are your sources for understanding mql4 and mql5 and do you distinguish them as two seperate langauges?
774f02a0e0b8c503641f35a7d012e39a
{ "intermediate": 0.3992908000946045, "beginner": 0.2838740348815918, "expert": 0.3168352246284485 }
17,146
async submit() { axios.post("http://192.168.11.250:8092/vems/cxfService/external/extReq", { Headers: { 'Access-Control-Allow-Orign': '*' }, Params: { "biz_content": { "car_code": this.cranumshow, "owner": this.name, "visit_name": "访客车辆", "phonenum": this.phonenumber, "reason": "来访", "operator": this.name, "operate_time": this.startdate, "visit_time": { "start_time": this.startdate, "end_time": this.enddate } }, "charset": "utf-8", "command": "ADD_VISITOR_CAR", "device_id": "00000000000000000000001497121A38", "message_id": "8308", "sign": "00000000000000000000000000000000", "sign_type": "MD5", "timestamp": "20230804143800" } }).then(res => { if (res.status === 200) { this.name = ""; this.phonenumber = ""; this.startdate = date.formatDate(Date.now(), 'YYYY-MM-DD HH:mm:ss'); this.enddate = date.formatDate(Date.now(), 'YYYY-MM-DD') + " 17:00:00"; this.carnum = []; this.$router.push({ path: '/submitFinish' }) } else { this.$router.push({ path: '/submitError' }) } }) },这段代码有什么问题
80dd65acd3d663da6debc3db5b8be02a
{ "intermediate": 0.3353561758995056, "beginner": 0.42847323417663574, "expert": 0.23617057502269745 }
17,147
make card just like daraz with hiver
1ddc9a38a006b2fb2cb22e31eacb9c18
{ "intermediate": 0.48465466499328613, "beginner": 0.2540658116340637, "expert": 0.26127952337265015 }
17,148
What can be used instead of kconfig to manage the configuration of a complex project? A complex project consists of modules. Each module has its own configuration file. It is necessary that the solution be built on yaml.
6442ccd22869d696ed131f6299d1e6db
{ "intermediate": 0.40887147188186646, "beginner": 0.33830976486206055, "expert": 0.2528187930583954 }
17,149
Hi there! How to get first true value of an object and return the corresponding value in JS?
52acd31626215ee69b078f45bbf1fcc4
{ "intermediate": 0.5151094794273376, "beginner": 0.21722421050071716, "expert": 0.2676663100719452 }
17,150
Create a class Product that represents a product sold in a shop. A product has a price, amount and name. The class should have: A constructor public Product(string name, double priceAtStart, int amountAtStart) A method public void PrintProduct() that prints a product in the following form: Banana, price 1.1, amount 13 Test your code by creating a class with main method and add three products there: "Logitech mouse", 70.00 EUR, 14 units "iPhone 5s", 999.99 EUR, 3 units "Epson EB-U05", 440.46 EUR, 1 units Print out information about them. Add new behaviour to the Product class: possibility to change quantity possibility to change price Reflect your changes in a working application. Hi, please solve this with C# code.
78beb203753d8cfa5f0f3f3e4bc8a55e
{ "intermediate": 0.28108906745910645, "beginner": 0.6243278384208679, "expert": 0.09458309412002563 }
17,151
Active code page: 65001 Debug Mode PaddleOCR-json v1.2.1 OCR init completed. {"code":100,"data":[{"box":[[47,42],[72,42],[72,59],[47,59]],"score":0.9723867774009705,"text":"107"}]} OCR exit. 这是output.txt的文本内容,要求用bat文件提取"text"后面的数字串到number.txt
61eeb0b4d9ebfdb0f066f3c1b3b3b203
{ "intermediate": 0.40157684683799744, "beginner": 0.29842710494995117, "expert": 0.2999959886074066 }
17,152
write the python code for mining attribute implications from formal context
42ece9e93092ab9cfa6fb1a8ecdc5c32
{ "intermediate": 0.3911723494529724, "beginner": 0.23406729102134705, "expert": 0.37476035952568054 }
17,153
how to print all lines in a file in python
e240dda0b8ef3dc0dd0cb8740348220a
{ "intermediate": 0.4023790955543518, "beginner": 0.25737321376800537, "expert": 0.3402476906776428 }
17,154
hey...give me the code in windows that Ican check presence of mariadb in my computer
bdb33c814f4fc8a80ae6aaac8d300962
{ "intermediate": 0.5295989513397217, "beginner": 0.17801114916801453, "expert": 0.292389839887619 }
17,155
explain Closures in js
e5776cab33deded824f007394a6c2e2e
{ "intermediate": 0.39405253529548645, "beginner": 0.2407836616039276, "expert": 0.36516380310058594 }
17,156
SQL Service如何把SELECT查询出的结果变成INSERT语句
12bc73a60a8c594709285cd943e67ad4
{ "intermediate": 0.31398242712020874, "beginner": 0.4068830609321594, "expert": 0.27913448214530945 }
17,157
help me install ballerina using apt
2f64fcac1088087d7eec867213016c4e
{ "intermediate": 0.44190412759780884, "beginner": 0.23849421739578247, "expert": 0.3196016848087311 }
17,158
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] depth_analysis = [] depth_threshold = 100 for i in range(1, len(bid_depth)): if ( float(bid_depth[i][0]) >= depth_threshold and float(bid_depth[i - 1][0]) < depth_threshold ): depth_analysis.append('buy') elif ( float(ask_depth[i][0]) >= depth_threshold and float(ask_depth[i - 1][0]) < depth_threshold ): depth_analysis.append('sell') # After adding your algorithm logic, check if there is a buy or sell signal if 'buy' in depth_analysis: return 'buy' elif 'sell' in depth_analysis: return 'sell' else: return '' end_time = int(time.time() * 1000) start_time = end_time - lookback * 60 * 1000 TradeType = "BUY" or "SELL" secret_key = API_KEY_BINANCE # Replace with your actual secret key obtained from MXC Exchange access_key = API_SECRET_BINANCE # Replace with your actual access key obtained from MXC Exchange import binance while True: lookback = 10080 df = get_klines(symbol, interval, lookback) if df is not None: signals = signal_generator(df) print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Signals: {signals}") mark_price = client.ticker_price(symbol=symbol) if signals == 'buy': try: quantity = 0.1 client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) print("Long order executed!") stop_loss_price = float(mark_price) - (float(mark_price) * 0.002) print(f"Stop loss set at: {stop_loss_price}") try: client.new_order( symbol=symbol, side='SELL', type='STOP_MARKET', quantity=0.1, stopPrice=stop_loss_price ) print("Stop loss order placed!") except binance.error.ClientError as e: print(f"Error placing stop loss order: {e}") time.sleep(1) except binance.error.ClientError as e: print(f"Error executing long order: {e}") time.sleep(1) if signals == 'sell': try: quantity = 0.1 client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) print("Short order executed!") stop_loss_price = float(mark_price) + (float(mark_price) * 0.002) print(f"Stop loss set at: {stop_loss_price}") try: client.new_order( symbol=symbol, side='BUY', type='STOP_MARKET', quantity=0.1, stopPrice=stop_loss_price ) print("Stop loss order placed!") except binance.error.ClientError as e: print(f"Error placing stop loss order: {e}") time.sleep(1) except binance.error.ClientError as e: print(f"Error executing short order: {e}") time.sleep(1) time.sleep(1) Can you set in signal_generator if buy orders qty > sell order qty return 'bullish' If bullish price > mark price return buy elif : if sell orders qty > buy order qty return 'bearish' If bearish price > mark price return sell
9db6b0fac9b2a169e589e8481a75e7c7
{ "intermediate": 0.3172347843647003, "beginner": 0.3804941177368164, "expert": 0.3022710978984833 }
17,159
improve code async using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Linq; using System.Text; using System.Threading.Tasks; using Tax1402.Application.Interfaces.DataBaseIdentityContexts; using Tax1402.Common.Dto; using Tax1402.Domain.Entities; namespace Tax1402.Application.Services.TaxApiKey.Commands.RemoveTaxApiKeyService { public class RemoveTaxApiKeyService : IRemoveTaxApiKeyService { private readonly IDataBaseIdentityContext _context; private static readonly NLog.Logger nlog = NLog.LogManager.GetCurrentClassLogger(); public RemoveTaxApiKeyService(IDataBaseIdentityContext context) { _context = context; } public async Task<ResultDto<ResulRemoveTaxApiKeyServiceDto>> ExecuteAsync(RequestDeleteTaxApiKeyServiceDto request) { try { var resultTaxApiKey = _context.TaxApiKeys .Where(p => p.CustomerId == request.CustomerId) .Where(p => p.Id == request.TaxApiKeyId) .FirstOrDefault(); resultTaxApiKey.IsActive = false; resultTaxApiKey.DeleteAt = DateTime.Now; _context.TaxApiKeys.Update(resultTaxApiKey); var result = await _context.SaveChangesAsync(); if (result >= 1) { return new ResultDto<ResulRemoveTaxApiKeyServiceDto>() { Data = new ResulRemoveTaxApiKeyServiceDto() { Id = resultTaxApiKey.Id }, IsSuccess = true, Message = " کلید یکتای مالیاتی با موفقیت حذف شد" }; } else { nlog.Warn("حذف کلید یکتای مالیاتی با خطا مواجه شد"); return new ResultDto<ResulRemoveTaxApiKeyServiceDto>() { IsSuccess = false, Message = "حذف کلید یکتای مالیاتی با خطا مواجه شد" }; } } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { // Get entry DbEntityEntry entry = item.Entry; string entityTypeName = entry.Entity.GetType().Name; // Display or log error messages foreach (DbValidationError subItem in item.ValidationErrors) { string message = string.Format("Error '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); nlog.Error(message, ex); } } return new ResultDto<ResulRemoveTaxApiKeyServiceDto>() { IsSuccess = false, Message = "حذف کلید یکتای مالیاتی با خطا مواجه شد" }; } } } public interface IRemoveTaxApiKeyService { Task<ResultDto<ResulRemoveTaxApiKeyServiceDto>> ExecuteAsync(RequestDeleteTaxApiKeyServiceDto requestRemoveTaxApiKeyServiceDto); } public class RequestDeleteTaxApiKeyServiceDto { public int TaxApiKeyId { get; set; } public string CustomerId { get; set; } } public class ResulRemoveTaxApiKeyServiceDto { public int Id { get; set; } } }
6e5300be17ba66e1d64afddd7417dc82
{ "intermediate": 0.33726179599761963, "beginner": 0.510991632938385, "expert": 0.15174655616283417 }
17,160
give me a c-code example of KDF x9.63 usage to derive both: an AES-128 key and an HMAC-SHA512 key
faa8c2cda8aa81c0a77c717241dac10c
{ "intermediate": 0.4054092466831207, "beginner": 0.14959335327148438, "expert": 0.4449974000453949 }
17,161
package com.rumikuru.skdumobile.components.template.viewModels import android.content.ContentValues import android.content.ContentValues.TAG import android.content.Context import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.rumikuru.skdumobile.logic.local_dao.AppDatabase import com.rumikuru.skdumobile.logic.local_dao.DatabaseProvider import com.rumikuru.skdumobile.models.ListMessage import com.rumikuru.skdumobile.models.Message import com.rumikuru.skdumobile.models.User import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.jgroups.JChannel import org.jgroups.Receiver import org.jgroups.View data class MessageViewModel( val context: Context? = null, ) : ViewModel(), Receiver { private val _uiState = MutableStateFlow(ListMessage()) val uiState: StateFlow<ListMessage> = _uiState.asStateFlow() private var channel: JChannel? = null private var messageRecive: MutableLiveData<MutableList<Message>> = MutableLiveData() private var db: AppDatabase? = context?.let { DatabaseProvider.getInstance(it) } private var user: User? = null init { user = DatabaseProvider.getInstance(context!!).userDao().getUser() viewModelScope.launch(Dispatchers.IO) { start() getData() } } @Throws(Exception::class) private suspend fun start() { channel = JChannel() channel!!.receiver = this channel!!.connect("ChatCluster") } private suspend fun getData() { val messageDao = db?.messageDao() val messages = messageDao?.getMessages() //messageRecive.value = messages _uiState.update { currentState -> currentState.copy(messages = messages!!) } } // Метод для отправки сообщений в кластер @Throws(Exception::class) fun sendMessage(message: String?) { val mesg = Message( user?.firstName ?: "Не известный", message!!, user?.numberVagon ?: -1, user!!.address ) val msg: org.jgroups.Message = org.jgroups.Message(null, mesg) Log.d( TAG, "Сообщений отправилось $message, " + "\n имя: ${user!!.firstName} " + "\n фамилия ${user!!.surname} " + "\n отчество ${user!!.patronymic} " + "\n UUID ${user!!.address}" ) channel!!.send(msg) viewModelScope.launch { db?.messageDao()?.insert(msg.getObject()) } } // Метод для обработки входящих сообщений override fun receive(msg: org.jgroups.Message) { //Log.d(TAG, msg.getObject<Message>().textMessage) //messageRecive = messageRecive + msg.getObject<Message>() if (context != null) { viewModelScope.launch { if (msg.getObject<Message>().userAddress != user!!.address) { db?.messageDao()?.insert(msg.getObject()) } val tempListMessage = db?.messageDao()?.getMessages() _uiState.update { newState -> newState.copy(messages = tempListMessage!!) } } } } override fun viewAccepted(newView: View) { Log.d( ContentValues.TAG, "-- Кластер состоит из " + newView.size() + " участников: " + newView + " --" ) } fun getUserLogin(): Boolean { return user?.firstName != null } } Сделай так что бы сообщения отображались через библиотеку Paginator 3 (интегрируй Paginator 3 в код)
b8f56ab712ef6c1f9d7b08a45f4e97aa
{ "intermediate": 0.29011160135269165, "beginner": 0.5943394899368286, "expert": 0.11554894596338272 }
17,162
html document
447e93ba19c4f6880ce7246a0062d745
{ "intermediate": 0.286286860704422, "beginner": 0.35780927538871765, "expert": 0.3559038043022156 }
17,163
I have a sheet called 'Links Page' that has the following details; A2 value = SERVICE PROVIDERS B2 value = G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\zzzz ServProvDocs\ How should I write the code below to use the values in sheet 'Links Page' Set wdDoc = wdApp.Documents.Open("G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\zzzz ServProvDocs\SrvPlnJulAug.docm")
5c950548de983031efb98487d64d5c70
{ "intermediate": 0.460974782705307, "beginner": 0.22821316123008728, "expert": 0.3108120262622833 }
17,164
index.html:47 Uncaught ReferenceError: array is not defined at index.html:47:19
7fc84315c1b870329ef8a9c51dc1a0f7
{ "intermediate": 0.31801411509513855, "beginner": 0.44143736362457275, "expert": 0.2405485212802887 }
17,165
How to create double donut chart in Power BI&
82c67274988ed6cd456c4d414d9574bd
{ "intermediate": 0.23511937260627747, "beginner": 0.20656293630599976, "expert": 0.5583176612854004 }
17,166
$ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3', CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_URL => $url )); if ($savefile) { curl_setopt($ch, CURLOPT_FILE, $savefile); } $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (!in_array($code, [200])) { throw new Exception('cURL: ошибка запроса. Статус - ' . $code . '. Ответ: ' . $response); } return $response; Отдаёт 301 как исправить
b64971edc52f64cd2267eeabc8cd9342
{ "intermediate": 0.47067904472351074, "beginner": 0.27268391847610474, "expert": 0.2566370368003845 }
17,167
suduku game cod
f65de96623dd95d61f30c3ded4ec0c40
{ "intermediate": 0.3022381067276001, "beginner": 0.42443403601646423, "expert": 0.27332788705825806 }
17,168
Hello, can you write a WebRTC application that connects users with a similar language connected?
2443d20f454e186131d41dc7b91dae00
{ "intermediate": 0.33064937591552734, "beginner": 0.3802817761898041, "expert": 0.2890688478946686 }
17,169
I have a table in Power BI with Payer, Product, Date, Start Date, Final Date columns, where Payer is customer code, Product is product code, Date is date of transaction, Start and Final Dates and the beginning and ending date of promo. Date falls between Start and Final Dates. Each Product can be sold using promo at different time ranges. See the short example: Payer Product Date Start Date Final Date 1 10 06.01.2022 06.01.2023 12.01.2023 1 10 07.01.2022 06.01.2023 12.01.2023 1 10 25.01.2022 20.01.2023 30.01.2023 1 10 03.02.2023 02.02.2023 10.02.2023 1 10 05.02.2023 02.02.2023 10.02.2023 1 10 09.02.2023 02.02.2023 10.02.2023 1 20 09.03.2022 06.03.2023 12.03.2023 1 20 09.03.2022 06.03.2023 12.03.2023 Write the DAX measures that are required to answer the following two questions: 1) How to determine the number of days when each Product for each Payer is not sold using promo (it means there are no such promo periods in the table)? The slicer is used to determine the time frame. This time frame should include promo and non-promo periods. 2) How to determine all starting and ending dates for periods without promo for each Product and Payer? Also, take into account the selected slicer.
fd8c53c45dc9094f08c6b55a6e1cfe28
{ "intermediate": 0.3336067795753479, "beginner": 0.32327526807785034, "expert": 0.34311792254447937 }
17,170
I have a sheet called 'Links Page' that has the following details; A2 value = SERVICE PROVIDERS B2 value = G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\zzzz ServProvDocs\ How should I change the code below to use the address values in the sheet 'Links Page' Set wdDoc = wdApp.Documents.Open("G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\zzzz ServProvDocs\SrvPlnJulAug.docm")
4c93013db9bbffecda1d617165b7b437
{ "intermediate": 0.43950268626213074, "beginner": 0.20968981087207794, "expert": 0.3508075177669525 }
17,171
app.get('/books', (req, res) => { let books = [] db?.collection('books'). find(). forEach(book => books.push(book)) .then(() => { res.status(200).json(books) }) .catch(() => { res.status(500).json({ message: "Could not fetch the documents" }) }) res.json({ message: 'connect to api' }) }) res.status(500).json({ message: "Could not fetch the documents" }) this line of code complainr a error:cannot set headers after they are sent to the client,
27233bb8496c7150920c70c17c50f067
{ "intermediate": 0.5748028755187988, "beginner": 0.25844740867614746, "expert": 0.1667497754096985 }
17,172
how to create my own repository for dart/flutter packages?
eaed9142bc2b802cea1bcb60b6b61a76
{ "intermediate": 0.5750420093536377, "beginner": 0.17025253176689148, "expert": 0.25470542907714844 }
17,173
use wxpython html2 to load *.zip file's html, and can show its image
ac8e82f42149fc2b9c7813aa0b6972f0
{ "intermediate": 0.47868114709854126, "beginner": 0.20051640272140503, "expert": 0.3208024501800537 }
17,174
I have a pandas dataframe and some_python_list I need to filter that dataframe by few columns - df[col_1] < 200 AND I also want to filter out all the values in df[col_2] which are present in some_python_list
74e708e262b516b7697f7d042a63c732
{ "intermediate": 0.6105993390083313, "beginner": 0.15788009762763977, "expert": 0.23152056336402893 }
17,175
i have label consists of two words , in small screen the two words intersect each other how to split these two words in two lines in small screens css
ea2ee3ea2c3fc1158d172cd2b09d8bb6
{ "intermediate": 0.42238572239875793, "beginner": 0.27605220675468445, "expert": 0.3015621304512024 }
17,176
builder.AddIfTrue(() => metadata.ParticipantsEntitiesIds?.Count > 0, q => q.Terms(t => t.Field("value.ParticipantEntity.Ids").Terms(metadata.ParticipantsEntitiesIds))); se puede poner un or en esta sentencia?
502ffcd575cb640b10a9a234699b67e3
{ "intermediate": 0.46147653460502625, "beginner": 0.25210413336753845, "expert": 0.2864193320274353 }
17,177
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signals = [] # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if buy_qty > sell_qty: signals.append('bullish') elif sell_qty > buy_qty: signals.append('bearish') if signals == 'bullish' and float(mark_price) < buy_price: return 'buy' elif signals == 'bearish' and float(mark_price) > sell_price: return 'sell' else: return '' But it deosn't give me any signals
95715e4923bb83ea1a8daf0092316c02
{ "intermediate": 0.3720819354057312, "beginner": 0.4392555058002472, "expert": 0.1886625438928604 }
17,178
In CMake, at build-time, how can a project download some other piece of software without building it?
eaf834488deb07f281c8875a069d80cc
{ "intermediate": 0.5093873143196106, "beginner": 0.2604549825191498, "expert": 0.23015765845775604 }
17,179
How to install qemu VirtIO?
5e8c72c91c00b467a4d90f1112a70a84
{ "intermediate": 0.4533720910549164, "beginner": 0.1195346862077713, "expert": 0.42709317803382874 }
17,180
import React, {useEffect, useState} from "react"; import {Box, Grid, Typography, useTheme} from "@mui/material"; import {XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ComposedChart, Bar} from "recharts"; import {updateDiaryWidget, Widget} from "../../../actions/cicap-diary-widgets"; import {useAuthContext} from "../../AuthProvider/AuthProvider"; interface ProfitWeekdaysChartProps { data: number[]; widget: Widget; onWidgetUpdate: (id: string) => void; } const ProfitWeekdaysChart = ({data, widget, onWidgetUpdate}: ProfitWeekdaysChartProps) => { return ( <> <Grid display="flex" > { periodProfitWeekdaysChart.map((p, i) => <Grid key={i}> <Typography onClick={(e) => { //@ts-ignore onChangePeriodProfitWeekdaysChart(e.target.outerText); }} fontSize={13} sx={{ cursor: "pointer", mr: ".25rem", display: "flex", flexWrap: "wrap", justifyContent: "center", alignContent: "center", height: "24px", padding: "2px 10px 1px", backgroundColor: !p.checked ? !darkTheme ? "#E6E6E6" : "#242424" : !darkTheme ? "#C3463B" : "#B41C18", color: !p.checked ? !darkTheme ? "rgba(91, 91, 91, 0.6)" : "#999999" : "#fff", borderRadius: "1rem", }}> {p.title} </Typography> </Grid> ) } </Grid> <ResponsiveContainer width="100%" height="100%"> <ComposedChart data={formattedSeriesData} layout="vertical" margin={{ top: 30, right: 20, bottom: 20, left: -25, }} > <CartesianGrid horizontal={false} strokeDasharray="3 3" stroke={darkTheme ? "#5c5a57" : "#ccc"} /> <YAxis dataKey="name" interval={0} axisLine={darkTheme ? false : {stroke: "#EBEBEB"}} tickLine={false} fontSize="12" type="category" scale="band" tick={({x, y, payload, width}) => { return ( <text x={x - 10} y={y + 10} textAnchor="middle" fill="#9E9B98" fontSize={13} > {payload.value} </text> ); }} /> <XAxis type="number" axisLine={false} tickLine={false} tick={({x, y, payload}) => { return ( <text x={x} y={y + 10} textAnchor="middle" fill="#9E9B98" fontSize={13} > { +payload.value >= 0 ? `$${Math.abs(+payload.value)}` : `-$${Math.abs(+payload.value)}` } </text> ); }} /> <Tooltip content={<CustomTooltip />} /> <Bar dataKey="profit" radius={[0, 8, 8, 0]} barSize={60} fill={darkTheme ? "#0F3B2B" : "#F3C9CE"} /> </ComposedChart> </ResponsiveContainer> </> ); }; нужно сделть высота баров по оси x высотой в 24px, цвет баров в темной теме, если value отрицательный, то #0F3B2B, если положительный то #89ADA0. Так же сделать чтобы при наедении мышко
f217ea153af602e2d6a3399fbf255a24
{ "intermediate": 0.48432549834251404, "beginner": 0.35195857286453247, "expert": 0.16371586918830872 }