content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Make mouse movements follow windmouse algorithm Not sure if I'm asking the right question, but is it possible to make python move my mouse with things like pyautogui/selenium actions/or preferably all mouse movements following this algorithm? I want to make my mouse movements as real as possible for a bot I'd like...
Make mouse movements follow windmouse algorithm
Not sure if I'm asking the right question, but is it possible to make python move my mouse with things like pyautogui/selenium actions/or preferably all mouse movements following this algorithm? I want to make my mouse movements as real as possible for a bot I'd like to make. How would I go about doing this if possible...
[ "The algorithm you found is going to make human like mouse movement, instead of moving the mouse physically on your screen it will just help you plot the movements on the screen.\nTo help you see the plot, you can see in the same blog the writer/programmer has used Python matplotlib.\nimport matplotlib.pyplot as pl...
[ 0 ]
[]
[]
[ "pyautogui", "python", "selenium" ]
stackoverflow_0074084989_pyautogui_python_selenium.txt
Q: Why am I getting a figure size plotting error in Python? My python Code is no longer working. I messed around with terminal commands (on mac) uninstalling and re installing matplot lib, etc...And think I messed something up. For this specific problem, code that I know worked before, no longer does. I have this co...
Why am I getting a figure size plotting error in Python?
My python Code is no longer working. I messed around with terminal commands (on mac) uninstalling and re installing matplot lib, etc...And think I messed something up. For this specific problem, code that I know worked before, no longer does. I have this code where I load in data and plot a fit over it: data = np.load...
[ "I ran part of your script that relates to matplotlib:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt('sample_data.txt', skiprows = 1) #<============ Just to test my sample data\n\nx = data[:,0]\ny = data[:,1]\n\nymod = y #<============ Just to test\n\nplt.figure(figsize=(7.5,5))\nplt.rc(...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074176835_python.txt
Q: How to increase the validation accuracy in Neural Network? I want to create a machine learning in ANN to predict a Multiclass Classification problem. The validation accuracy was stucked somewehere around 0.4 to 0.5 but the training accuracy was high and increasing along the epochs. The dataset looks like this: pro...
How to increase the validation accuracy in Neural Network?
I want to create a machine learning in ANN to predict a Multiclass Classification problem. The validation accuracy was stucked somewehere around 0.4 to 0.5 but the training accuracy was high and increasing along the epochs. The dataset looks like this: project_type_id_Apartemen project_type_id_Bandara project_type_id...
[ "Your model is obviously overfitting. The most common cause is that the model has too many parameters which allows it to fit perfectly to training data but in doing so it loses the ability to generalise.\nThen I'd reduce the number of trainable parameters in the model. Start with removing some of the Dense layers. ...
[ 0 ]
[]
[]
[ "keras", "machine_learning", "neural_network", "python", "tensorflow" ]
stackoverflow_0074176675_keras_machine_learning_neural_network_python_tensorflow.txt
Q: Message handlers aren't invoked in aiogram bot on webhooks I'm launching an aiogram bot on webhooks locally using ngrok tunnel, but instead of proper responses, the bot returns 200 OK with almost nothing in response body, thus a user doesn't see anything in a chat. Bot's main.py driver looks like this: from aiogra...
Message handlers aren't invoked in aiogram bot on webhooks
I'm launching an aiogram bot on webhooks locally using ngrok tunnel, but instead of proper responses, the bot returns 200 OK with almost nothing in response body, thus a user doesn't see anything in a chat. Bot's main.py driver looks like this: from aiogram import executor from loader import dp, bot, cache from handle...
[ "As it turns out, the problem was in the structure of the bot.\nI used aiogram's built-in FSM tooling which assigns a state value to a dialogue with a specific user and lets you filter messages based on that:\n@message_handler(state=Manager.choose_action)\nasync def f(message: Message, state: FSMContext):\n ...\...
[ 0 ]
[]
[]
[ "aiogram", "docker", "python", "webhooks" ]
stackoverflow_0073789627_aiogram_docker_python_webhooks.txt
Q: How is my list assignment is out of range? I'm new to python and trying to understand 2D arrays. I'm trying to write a code in which someone inputs and stores the employee ID, department, and salary for 10 employees. Which is then stored using a 2D array The following will be outputted: All the information with t...
How is my list assignment is out of range?
I'm new to python and trying to understand 2D arrays. I'm trying to write a code in which someone inputs and stores the employee ID, department, and salary for 10 employees. Which is then stored using a 2D array The following will be outputted: All the information with the appropriate column title How many employees a...
[ "Python is zero-indexed. When inputting EmpDetails, use indexes 0, 1, 2 instead.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074177029_python.txt
Q: Import numpy in vsCode could not be resolved I am currently working in VSCode and attempting to import various libraries into my file. I am currently using the interpreter image of interpreter. The remainder of my code is shown remainder of code. I do not understand why my numpy is unable to be imported. A: Do C...
Import numpy in vsCode could not be resolved
I am currently working in VSCode and attempting to import various libraries into my file. I am currently using the interpreter image of interpreter. The remainder of my code is shown remainder of code. I do not understand why my numpy is unable to be imported.
[ "Do Ctrl + Shift + P, then in the pop-up type select python interpreter and choose the same python version where you installed numpy package.\n", "Use the following code to print the current interpreter environment,\nimport sys\nprint(sys.executable)\n\nCopy the interpreter path and install numpy with\n C:\\WorkS...
[ 0, 0 ]
[]
[]
[ "python", "pythoninterpreter", "visual_studio_code" ]
stackoverflow_0074156395_python_pythoninterpreter_visual_studio_code.txt
Q: New to programing can't figure this out def LangConverter(): lang1 = input("Please select a language ") if lang1 == "English": lang2 = input("what langauge would you like to convert to ") if lang2 == "Spanish": greeting = input("what would you like to say ") if greeting == "hel...
New to programing can't figure this out
def LangConverter(): lang1 = input("Please select a language ") if lang1 == "English": lang2 = input("what langauge would you like to convert to ") if lang2 == "Spanish": greeting = input("what would you like to say ") if greeting == "hello": print("Hola") words1 ...
[ "You have the wrong indentation:\nThe if statement is actually inside the\nif lang1 == \"english\"\n\nThis code should work\ndef LangConverter():\nlang1 = input(\"Please select a language \")\nif lang1 == \"English\":\n lang2 = input(\"what langauge would you like to convert to \") \n if lang2 == \"Spanish\":...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074177083_python.txt
Q: How to create a Duration column in Python from Start and Stop times? I am trying to make a column with time duration (hours - first one would be 1.424 hrs for example). My data looks like this. Clock_Start and Clock_Stop are objects. I have tried the following: df['Duration'] = (df_nyc['Clock_Stop'] - df['Clock_...
How to create a Duration column in Python from Start and Stop times?
I am trying to make a column with time duration (hours - first one would be 1.424 hrs for example). My data looks like this. Clock_Start and Clock_Stop are objects. I have tried the following: df['Duration'] = (df_nyc['Clock_Stop'] - df['Clock_Start']).astype('timedelta64[m]').astype(int) ... But I get the following...
[ "Time alone cannot be added or subtracted. You need to convert to Timedelta. There is a stop time that is before the start time, which I assume is because it goes past midnight. In that case, add 24 hours to the result:\nh = (pd.to_timedelta(df[\"Clock_Stop\"]) - pd.to_timedelta(df[\"Clock_Start\"])) / pd.Timedelta...
[ 1, 1 ]
[]
[]
[ "datetime", "numpy", "pandas", "python", "timedelta" ]
stackoverflow_0074175563_datetime_numpy_pandas_python_timedelta.txt
Q: python manage.py runserver keeps reloading stating file has changed I've been working on a django project with no issues. I've pulled updated code from the remote repository and now if i do python manage.py runserver in cmd, i keep getting error Starting development server at http://127.0.0.1:8000/ Quit the serve...
python manage.py runserver keeps reloading stating file has changed
I've been working on a django project with no issues. I've pulled updated code from the remote repository and now if i do python manage.py runserver in cmd, i keep getting error Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. D:\some_project\someapp\schemes\models.py changed, rel...
[ "You may be experiencing this issue due to your development environment. If you are using a Vagrant server or similar, the reloading of the files would be due to the Vagrant server refreshing the files from your local machine.\nThe --noreload flag is suitable for situations like this.\n", "I just restart the serv...
[ 5, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0061007749_django_python.txt
Q: How to scrape polygon from maps using request into a file that can be imported into google maps? I have a web https://jakartasatu.jakarta.go.id/portal/apps/experiencebuilder/experience/?id=be77dd30a600425e9a76d11c6b6b0272&page=page_5 Where I want to get all the polygons value for the layer rencana detail tata ruan...
How to scrape polygon from maps using request into a file that can be imported into google maps?
I have a web https://jakartasatu.jakarta.go.id/portal/apps/experiencebuilder/experience/?id=be77dd30a600425e9a76d11c6b6b0272&page=page_5 Where I want to get all the polygons value for the layer rencana detail tata ruang I am currently stuck at converting the values scraped into something I can use in: https://services6...
[ "Replace f=pbf with f=json in your query to get json response (see also the discussion here):\n\n" ]
[ 0 ]
[]
[]
[ "geospatial", "python", "python_requests" ]
stackoverflow_0074172343_geospatial_python_python_requests.txt
Q: asyncio.Event is not set from signal handler import signal import asyncio from typing import Optional from types import FrameType async def main() -> None: server = ( await asyncio.start_server( lambda reader, writer: None, '127.0.0.1', 7070 ) ) task...
asyncio.Event is not set from signal handler
import signal import asyncio from typing import Optional from types import FrameType async def main() -> None: server = ( await asyncio.start_server( lambda reader, writer: None, '127.0.0.1', 7070 ) ) tasks = ( asyncio.create_task(server.serve_fo...
[ "An interrupt can happen at any time and the handler is called between two Python bytecode instructions. In general, there are only few simple functions that are safe to call in a signal handler, beacause buffers or internal data may be in an inconsistent state. The recommendation is only to set a flag that is peri...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074174242_python.txt
Q: How to focus on a window with pygame? I made a Python game using Pygame. I try to make it so when it starts, it loads the shell, and entering a raw input would display the pygame window and start the game so that I can make the game playable without having to close the shell. It works, however, the window starts m...
How to focus on a window with pygame?
I made a Python game using Pygame. I try to make it so when it starts, it loads the shell, and entering a raw input would display the pygame window and start the game so that I can make the game playable without having to close the shell. It works, however, the window starts minimized. The game is a simple "dodge the o...
[ "For anyone in the future who stumbles across this question:\nAs of 2022, pygame v2.1.2 has an experimental module ._sdl2 where: Window.focus() is used to make a window to be moved at the top and set focus. Windows.focus() supports optional input_only bool parameter for whenever the window should be moved at the to...
[ 1, 0 ]
[]
[]
[ "pygame", "python", "window" ]
stackoverflow_0027351387_pygame_python_window.txt
Q: How to multiply or divide (N, 50) numpy array with (N, 1) numpy array? paths.shape (525600, 50) T.shape (525600,) how do I divide or multiply paths by T? More specifically I want to do this S = pd.DataFrame(paths) d1 = S.divide(np.sqrt(T), axis=0) but not using pandas want to use numpy only A: 2 arrays: In [...
How to multiply or divide (N, 50) numpy array with (N, 1) numpy array?
paths.shape (525600, 50) T.shape (525600,) how do I divide or multiply paths by T? More specifically I want to do this S = pd.DataFrame(paths) d1 = S.divide(np.sqrt(T), axis=0) but not using pandas want to use numpy only
[ "2 arrays:\nIn [17]: paths = np.arange(12).reshape(4,3); T = np.arange(1,5) \nIn [18]: paths.shape, T.shape\nOut[18]: ((4, 3), (4,)) # not (4,1)\n\nYour pandas approach:\nIn [19]: S = pd.DataFrame(paths) \nIn [20]: d1 = S.divide(np.sqrt(T), axis=0) \nIn [21]: S\nOut[21]: \n 0 1 2\n0 0 1...
[ 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074176265_numpy_python.txt
Q: Methods for post_order and in_order? My professor provided me with some of this code to use for our assignment and I've been trying to understand it for the last couple of hours. I saw that some methods such as post order and inorder were missing and I didn't see any of those methods in the lectures. Can someone p...
Methods for post_order and in_order?
My professor provided me with some of this code to use for our assignment and I've been trying to understand it for the last couple of hours. I saw that some methods such as post order and inorder were missing and I didn't see any of those methods in the lectures. Can someone possibly add the methods for post order and...
[ "In-order traversal looks like this:\n\ntraverse left node\nprint current node\ntraverse right node\n\nAnd post-order traversal looks like this:\n\ntraverse left node\ntraverse right node\nprint current node\n\nI would enourage you to look at what the code is doing in pre_order_traversal_helper() and pre_order_trav...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074177059_python.txt
Q: Tring to use after cancel after press a button in Tkinter but its dosent work I am tring to use after and after cancel method in tkinter to show a text in canvas its normaly works but when a user press a button before the text writing in canvas in compelete it showing wrong information and scaping to show some dat...
Tring to use after cancel after press a button in Tkinter but its dosent work
I am tring to use after and after cancel method in tkinter to show a text in canvas its normaly works but when a user press a button before the text writing in canvas in compelete it showing wrong information and scaping to show some data on canvas here is my code i dont get any error but its dont work well def get_nex...
[ "here is my final code thank you @Bryan Oakley its work well and typing question letter by letter on canvas\nfrom tkinter import *\nfrom quiz_brain import QuizBrain\n\nCOLOR = \"#375362\"\ntext_map = []\ncorrect_answer = \"\"\nFONT = (\"Zippy\", 20)\nkeep = None\npress = True\n\n\nclass QuizInterFace:\n\n def __...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074090220_python_tkinter.txt
Q: Conditional Django Middleware (or how to exclude the Admin System) I want to use some middleware I wrote across the whole of my site (large # of pages, so I chose not to use decorators as I wanted to use the code for all pages). Only issue is that I don't want to use the middleware for the admin code, and it seems...
Conditional Django Middleware (or how to exclude the Admin System)
I want to use some middleware I wrote across the whole of my site (large # of pages, so I chose not to use decorators as I wanted to use the code for all pages). Only issue is that I don't want to use the middleware for the admin code, and it seems to be active on them. Is there any way I can configure the settings.py ...
[ "A general way would be (based on piquadrat's answer)\ndef process_request(self, request):\n if request.path.startswith(reverse('admin:index')):\n return None\n # rest of method\n\nThis way if someone changes /admin/ to /django_admin/ you are still covered. \n", "You could check the path in process_r...
[ 39, 10, 1, 0 ]
[]
[]
[ "django", "django_admin", "django_middleware", "python" ]
stackoverflow_0001028019_django_django_admin_django_middleware_python.txt
Q: How to run t threads to a specific CPU? I am new at multiprocessing. So, I have t threads and p CPU (machine threads). What I want is to equally distribute the threads into each CPU. But I am puzzling about the I saw this documentation on how to to set the CPU affinity mask of a process indicated by the specified ...
How to run t threads to a specific CPU?
I am new at multiprocessing. So, I have t threads and p CPU (machine threads). What I want is to equally distribute the threads into each CPU. But I am puzzling about the I saw this documentation on how to to set the CPU affinity mask of a process indicated by the specified process id. os.sched_setaffinity() method I'm...
[ "At least in Linux, you can set the pid argument of os.sched_setaffinity() to 0 or threading.get_native_id(), to change the affinity of the current thread.\nIf you want to do that with ThreadPool, do like this for example.\ndef init_worker_thread():\n masks = ...\n os.sched_setaffinity(0, masks)\npool = ThreadP...
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0074175771_multiprocessing_multithreading_python.txt
Q: How to create new database connection in django I need to create a new database connection(session) to avoid an unexpected commit from a MySql procedure in my django transaction. How to set up it in django? I have tried to duplicate the database configuration in setting file. It worked for me but it seems not a go...
How to create new database connection in django
I need to create a new database connection(session) to avoid an unexpected commit from a MySql procedure in my django transaction. How to set up it in django? I have tried to duplicate the database configuration in setting file. It worked for me but it seems not a good solution. See my code for more detail. @classmetho...
[ "If you have a look at the django.db module, you can see that django.db.connection is a proxy for django.db.connections[DEFAULT_DB_ALIAS] and django.db.connections is an instance of django.db.utils.ConnectionHandler.\nPutting this together, you should be able to get a new connection like this:\nfrom django.db impor...
[ 13, 1 ]
[]
[]
[ "django", "mysql", "python", "transactions" ]
stackoverflow_0056733112_django_mysql_python_transactions.txt
Q: Assign counts from .count() to a dataframe + column names - pandas python Hoping someone can help me here - i believe i am close to the solution. I have a dataframe, of which i have am using .count() in order to return a series of all column names of my dataframe, and each of their respective non-NAN value counts....
Assign counts from .count() to a dataframe + column names - pandas python
Hoping someone can help me here - i believe i am close to the solution. I have a dataframe, of which i have am using .count() in order to return a series of all column names of my dataframe, and each of their respective non-NAN value counts. Example dataframe: feature_1 feature_2 1 1 2 NaN 3 2 4 NaN 5 3...
[ "Add Series.reset_index instead Series.to_frame for 2 columns DataFrame - first column from index, second from values of Series:\ndf = data.count().reset_index()\ndf.columns = ['Feature', 'Count']\nprint (df)\n Feature Count\n0 feature_1 5\n1 feature_2 3\n\nAnother solution with name parameter and ...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074177214_dataframe_pandas_python.txt
Q: Compile C# code once and execute it multiple times in python I'm getting weird numbers on my C# sorting algorithm times that I think is caused by python recompiling the code every loop. How can I change this function to compile the C# code once and then execute the same compilation with different command line argu...
Compile C# code once and execute it multiple times in python
I'm getting weird numbers on my C# sorting algorithm times that I think is caused by python recompiling the code every loop. How can I change this function to compile the C# code once and then execute the same compilation with different command line arguments? Is that even possible? In theory the code should follow a c...
[ "Because you compile the C# code every time by dotnet run. Check out dotnet run options to find something which prevents build.\n", "The suggestions by @Rezaeimh7 and @jeremy-lakeman to use --no-build did provide a flat speed boost compared to the original code, but that wasn't really what I was after.\nWhat I en...
[ 0, 0 ]
[]
[]
[ "c#", "compilation", "performance", "python", "sorting" ]
stackoverflow_0074176655_c#_compilation_performance_python_sorting.txt
Q: How can i access the values of a StringGrid with pywinauto I have the following control identifiers. There is a StringGrid whose values I can not copy with right click or ctrl + c which is why I would like to get its values with pywinauto. How can I access the values within the grid? This is how it looks like : c...
How can i access the values of a StringGrid with pywinauto
I have the following control identifiers. There is a StringGrid whose values I can not copy with right click or ctrl + c which is why I would like to get its values with pywinauto. How can I access the values within the grid? This is how it looks like : child_window(title="Werte bestimmter Wellenlängen", class_name="T...
[ "This is custom control that is not supported by pywinauto (and MS UI Automation API) by default. But the application developers can use DelphiUIAutomation to enable UI Automation capabilities on the application side. It means pywinauto will be able to automate TStringGrid. But it's usually hard to reach developers...
[ 1 ]
[]
[]
[ "automation", "python", "pywinauto", "winapi" ]
stackoverflow_0074107669_automation_python_pywinauto_winapi.txt
Q: I want to subtract one from "cd" variable every time the function activates. How can I do that? def cdvalue(): cd = cd - 1 def Cd(): root.after(1000, cdvalue) I want to subtract one from "cd" variable every time the function activates. How can I do that? A: def cdvalue(): global cd cd = cd - 1 ...
I want to subtract one from "cd" variable every time the function activates. How can I do that?
def cdvalue(): cd = cd - 1 def Cd(): root.after(1000, cdvalue) I want to subtract one from "cd" variable every time the function activates. How can I do that?
[ "def cdvalue():\n global cd\n cd = cd - 1\n\ndef Cd():\n root.after(1000, cdvalue)\n\nIf that's not what you want to achieve or you wanna use the fact that functions are objects in python, check out this Access a function variable outside the function without using \"global\"\n" ]
[ 1 ]
[]
[]
[ "function", "loops", "math", "python", "variables" ]
stackoverflow_0074177213_function_loops_math_python_variables.txt
Q: Why i can't get variable name from Django I have a Django project that i'm working on. I need to print something to CLI to make it easier to debug. This is what i need print('============================================') print('VARIABLE_NAME_IN_CAPS') print(variable) print(f'LENGTH : {len(variable)}') print('====...
Why i can't get variable name from Django
I have a Django project that i'm working on. I need to print something to CLI to make it easier to debug. This is what i need print('============================================') print('VARIABLE_NAME_IN_CAPS') print(variable) print(f'LENGTH : {len(variable)}') print('============================================') thi...
[ "In Django you should not use globals() unless it's really needed. Instead use environment variables that can be set in settings.py and imported from there or import from file directly in the function (if the file may change - read it while executing).\nHow to use env files in Django\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074170166_django_python.txt
Q: count how many tensor in each tensor between 2 tensors are exactly equal Since I have learned metric 0/1 loss for multi-label classification, and I need to create that metric so I would like to def check that could count and return how many inside tensor between two tensors are actually matched For Example # Only ...
count how many tensor in each tensor between 2 tensors are exactly equal
Since I have learned metric 0/1 loss for multi-label classification, and I need to create that metric so I would like to def check that could count and return how many inside tensor between two tensors are actually matched For Example # Only second inside tensor are exactly equal a = torch.tensor([[1,0,1,1], [1,0,1,1]...
[ "I'm answering my question, Thanks to the combination of @Zwang\nand @LudvigH advice,\n\nThere are many ways you can do this, subtracting one tensor from the\nother then summing values and finding the non zero tensors, to simply\nusing python's built in == function. What have you tried? - Zwang\n\nI tried one of hi...
[ 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074177023_python_pytorch.txt
Q: using wait in pywinauto times out but sleep works fine I am trying to automate some GUI stuff in Windows. I open a settings window but when waiting for it to open before continuing, it times out: from pywinauto import Application app = Application() app.start(r"explorer shell:::{05d7b0f4-2121-4eff-bf6b-ed3f69b894...
using wait in pywinauto times out but sleep works fine
I am trying to automate some GUI stuff in Windows. I open a settings window but when waiting for it to open before continuing, it times out: from pywinauto import Application app = Application() app.start(r"explorer shell:::{05d7b0f4-2121-4eff-bf6b-ed3f69b894d9}") app.window(title_re=".*Notification Area Icons*").wait...
[ "It's possible there are few explorer.exe processes. You can try process-agnostic way:\nfrom pywinauto import Desktop\nwindow_wrapper = Desktop(backend=\"uia\").window(title_re=\".*Notification Area Icons*\").wait(\"exists\", timeout=20)\nprint(window_wrapper.process_id())\n# and compare with print(app.process)\n\n...
[ 0 ]
[]
[]
[ "python", "pywinauto" ]
stackoverflow_0074083351_python_pywinauto.txt
Q: How to find all undefined and unresolved references in a Python project I'm working on a Python project on VScode and facing some debugging issues: The built-in debugger does not detect errors inside functions. For example, it doesn't care the following invocation of an undefined method inside the function unless...
How to find all undefined and unresolved references in a Python project
I'm working on a Python project on VScode and facing some debugging issues: The built-in debugger does not detect errors inside functions. For example, it doesn't care the following invocation of an undefined method inside the function unless function1 is called in the main thread. Because mine is a Flask project, the...
[ "Enable linting\n\n\n\nOr add the following configuration in the settings.json\n \"python.analysis.typeCheckingMode\": \"strict\",\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x", "visual_studio_code", "vscode_debugger" ]
stackoverflow_0074164468_python_python_3.x_visual_studio_code_vscode_debugger.txt
Q: React Router not render I tried using react router but it doesn't work. I already know that React Router Dom v6 has changed from Switch to Routes but when I run the program it just shows a blank screen. Does anyone know how to fix this? Here is my code: App.js ''' import React, {Component} from "react"; import...
React Router not render
I tried using react router but it doesn't work. I already know that React Router Dom v6 has changed from Switch to Routes but when I run the program it just shows a blank screen. Does anyone know how to fix this? Here is my code: App.js ''' import React, {Component} from "react"; import { BrowserRouter as Router } ...
[ "The error is that \"You cannot render a Router inside another Router \" occurs when we have 2 Router components in the same React application.\nSo if u see u are calling in App.js and when u call Homepage from app.js it renders again. Thats why everything becomes blank.\nand avoid using p tag inside render funct...
[ 1 ]
[]
[]
[ "django", "javascript", "python", "reactjs" ]
stackoverflow_0074174826_django_javascript_python_reactjs.txt
Q: How to correctly input windows path to python subprocess argument I would like to open a windows application by using python subprocess, I can open the application in shell by command: start "C:\Windows\notepad.exe", however when I try to use subprocess it gives FileNotFoundError, I tired: subprocess.run(['start',...
How to correctly input windows path to python subprocess argument
I would like to open a windows application by using python subprocess, I can open the application in shell by command: start "C:\Windows\notepad.exe", however when I try to use subprocess it gives FileNotFoundError, I tired: subprocess.run(['start', '"C:\\Windows\\notepad.exe"']) subprocess.run(['start', "C:\\Windows\\...
[ "I just check another related thread (python subprocess Popen environment PATH?).\nEDIT:Subprocess with default options uses Shell=False, you need the Shell because you invoke a shell program.\nFrom docs.python.org :\n\nOn Windows with shell=True, the COMSPEC environment variable specifies\nthe default shell. The...
[ 0 ]
[]
[]
[ "path", "python", "windows" ]
stackoverflow_0074176795_path_python_windows.txt
Q: How do I get arrays to couple multiple numbers? I'm making a game with a saving system in Python, but it doesn't work as intended. thingcount = saveArray[0] The code above is supposed to set thingcount to 5454, as shown in the saveArray: [5454, 0, 1] But it only sets thingcount to 5. Does anyone know how to do t...
How do I get arrays to couple multiple numbers?
I'm making a game with a saving system in Python, but it doesn't work as intended. thingcount = saveArray[0] The code above is supposed to set thingcount to 5454, as shown in the saveArray: [5454, 0, 1] But it only sets thingcount to 5. Does anyone know how to do this?
[ "As some of the comments have noted, if saveArray truly equals [5454, 0, 1], then the command print(thingcount) will yield your desired output of [5454]\nIf thingcount[0] yields an output of 5, then at some point in your code, saveArray is being set to 5454 only - Maybe as a string, but not the full list of [5454, ...
[ 3 ]
[]
[]
[ "arrays", "python", "tkinter" ]
stackoverflow_0074176800_arrays_python_tkinter.txt
Q: Python - append a list with uncertain length to specific columns in order I have a program returns a list with uncertain length of numbers each time, and I want to append the list to dataframe. Each time, I know the column order to append but I don't know the length of the list. df = DataFrame(columns = ['A', 'B',...
Python - append a list with uncertain length to specific columns in order
I have a program returns a list with uncertain length of numbers each time, and I want to append the list to dataframe. Each time, I know the column order to append but I don't know the length of the list. df = DataFrame(columns = ['A', 'B', 'C', 'D', 'E', 'F'] If the column order is B, C, D, E, F and the list return ...
[ "Try using .loc:\nimport pandas as pd \n\ndata = pd.DataFrame(columns=[\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"])\n\ndatum = [2, 3, 4]\norder = [\"A\", \"C\", \"D\"]\n\ndata.loc[len(data.index), order] = datum\nprint(data)\n\nThis gives:\n A B C D E F\n0 2 NaN 3 4 NaN NaN\n\ndata.index stores the...
[ 1, 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074171978_dataframe_python.txt
Q: Can't install pywhatkit I want to install the pywhatkit package, but I got an error like this: ERROR: Command errored out with exit status 1: command: /data/data/com.termux/files/usr/bin/python2 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/data/data/com.termux/files/usr/tmp/pip-install-JBqkiU/pyw...
Can't install pywhatkit
I want to install the pywhatkit package, but I got an error like this: ERROR: Command errored out with exit status 1: command: /data/data/com.termux/files/usr/bin/python2 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/data/data/com.termux/files/usr/tmp/pip-install-JBqkiU/pywhatkit/setup.py'"'"'; __file_...
[ "You are using python version 2 /data/data/com.termux/files/usr/bin/python2\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0072336037_python.txt
Q: DRF multiple update with reduced database hits I'm using DRF's example of multiple updates which works fine except every self.child.update is a separate update query to the database. Is there a way I can rewrite this to call the updates as one query as a bulk update? class BookListSerializer(serializers.ListSerial...
DRF multiple update with reduced database hits
I'm using DRF's example of multiple updates which works fine except every self.child.update is a separate update query to the database. Is there a way I can rewrite this to call the updates as one query as a bulk update? class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data...
[ "Django has a command bulk_update\nDocs: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-update\nI'd write up a full example but I'm not sure what validated_data looks like\n", "A few suggestions:\n\n - Use ModelSerializer, as mentioned. It will handle updates/creates automatically and more effic...
[ 0, 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074155522_django_django_rest_framework_python.txt
Q: How do you sort a dictionary by key from highest to lowest Hi I have a dictionary that is currently the one below: dictionary={1:'a',2:'b',3:'c'} my desired output is to have a dictionary with the highest keys to the left and the lowest keys to the right like below: dictionary={3:'c',2:'b',1:'a'} how do you do t...
How do you sort a dictionary by key from highest to lowest
Hi I have a dictionary that is currently the one below: dictionary={1:'a',2:'b',3:'c'} my desired output is to have a dictionary with the highest keys to the left and the lowest keys to the right like below: dictionary={3:'c',2:'b',1:'a'} how do you do that in python 3.7?
[ "You want to get the keys from the dictionary with dictionary.keys(), then sort it in reverse with sorted(dictionary.keys(), reverse=True), and then you can use that in a dictionary comprehension:\n{k: dictionary[k] for k in sorted(dictionary.keys(), reverse=True)}\n# {3: 'c', 2: 'b', 1: 'a'}\n\nOf course, if we us...
[ 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074177392_dictionary_python.txt
Q: Efficient way to add a pandas Series to a pandas DataFrame I have a large large DataFrame. And I want to add a series to every row of it. The following is the current way for achieving my goal: print(df.shape) # (31676, 3562) diff = 4.1 - df.iloc[0] # I'd like to add diff to every row of df for i in range(len(df)...
Efficient way to add a pandas Series to a pandas DataFrame
I have a large large DataFrame. And I want to add a series to every row of it. The following is the current way for achieving my goal: print(df.shape) # (31676, 3562) diff = 4.1 - df.iloc[0] # I'd like to add diff to every row of df for i in range(len(df)): df.iloc[i] = df.iloc[i] + diff The method takes a lot of...
[ "You can subtract Series for vectorize operation, a bit faster should be subtract by numpy array:\nnp.random.seed(2022) \n \ndf = pd.DataFrame(np.random.rand(1000,1000))\n\n\nIn [51]: %timeit df.add(4.1).sub(df.iloc[0])\n7.99 ms ± 389 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [52]: %timeit df...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074177345_dataframe_pandas_python.txt
Q: hide label and conf. value in YOLOv5 I loaded a model (local in my laptop). I tried to remove (hide) label and conf. value from images using (model.hide_labels = True) and (model.hide_conf = True). It didn't work. How can I hide labels and conf. value? I only want boxes. model = torch.hub.load('ultralytics/yolov5...
hide label and conf. value in YOLOv5
I loaded a model (local in my laptop). I tried to remove (hide) label and conf. value from images using (model.hide_labels = True) and (model.hide_conf = True). It didn't work. How can I hide labels and conf. value? I only want boxes. model = torch.hub.load('ultralytics/yolov5', 'custom', './yolov5s/best.pt') # custo...
[ "I solved it by using results.show(labels=False)\n" ]
[ 0 ]
[]
[]
[ "detection", "label", "python", "pytorch", "yolov5" ]
stackoverflow_0074174388_detection_label_python_pytorch_yolov5.txt
Q: Why no error for the code as else is un-indented? WHy doesn't this code gives an error in python as the else part is un-indented and doesn't have a starting if block. guess=7 c=1 for c in range(1,6): g = int(input("guess a number from 1 to 20:")) if (g==guess): print("you win") break else: print("yo...
Why no error for the code as else is un-indented?
WHy doesn't this code gives an error in python as the else part is un-indented and doesn't have a starting if block. guess=7 c=1 for c in range(1,6): g = int(input("guess a number from 1 to 20:")) if (g==guess): print("you win") break else: print("you lose")
[ "That else is for the for loop. If the for loop is completed without a break, it is not implemented, if not the else block will be executed.\nguess=7\nc=1\nfor c in range(1,6):\n g = int(input(\"guess a number from 1 to 20:\"))\n if (g==guess):\n print(\"you win\")\n break \nelse: # This else is for \"for ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074177447_python.txt
Q: Django ORM question about methods for the QuerySet Object Can someone explain to me why you can use a method like count() for a QuerySet Object but something like pop() does not work. A: The reason is that, unlike a list, a QuerySet is a special type that isn't evaluated unless you perform any computation on its...
Django ORM question about methods for the QuerySet Object
Can someone explain to me why you can use a method like count() for a QuerySet Object but something like pop() does not work.
[ "The reason is that, unlike a list, a QuerySet is a special type that isn't evaluated unless you perform any computation on its data. Its purpose is to store query results and can be manipulated using query methods such as .filter(), .order_by(), etc. As opposed to a list of objects that consumes RAM space, a Query...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074155494_django_django_models_django_rest_framework_python.txt
Q: python grade calculator to drop lowest score im working on a python grade calculator for class where i can only use if/else/elif statements to drop the lowest score and then average the scores. this is what i have so far but i dont know how to determine the lowest score from the input using ONLY if/else statements...
python grade calculator to drop lowest score
im working on a python grade calculator for class where i can only use if/else/elif statements to drop the lowest score and then average the scores. this is what i have so far but i dont know how to determine the lowest score from the input using ONLY if/else statements. any help is appreciated! # Input sName = str(inp...
[ "Test the first two to find the smallest of those. Now compare the other two in turn to smallest and update smallest if necessary.\nif iTest1 < iTest2:\n smallest = iTest1\nelse:\n smallest = iTest2\n\nif iTest3 < smallest:\n smallest = iTest3\n\nif iTest4 < smallest:\n smallest = iTest4\n\nOf course, all of th...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074177466_python.txt
Q: Filter a column based on another column in another df Say I have a df where time is in time format. Time lat lon 1/10/2022 11:30 22.12 113.15 1/10/2022 11:32 22.13 113.14 1/10/2022 11:45 22.15 113.19 1/10/2022 12:01 22.11 113.13 1/10/2022 12:11 22.17 113.19 Here is the code df['Time']= pd.to_datetime(df['Time...
Filter a column based on another column in another df
Say I have a df where time is in time format. Time lat lon 1/10/2022 11:30 22.12 113.15 1/10/2022 11:32 22.13 113.14 1/10/2022 11:45 22.15 113.19 1/10/2022 12:01 22.11 113.13 1/10/2022 12:11 22.17 113.19 Here is the code df['Time']= pd.to_datetime(df['Time']) df['Time'] = df['Time'].dt.time Now, I would like ...
[ "If you want to use isin it is a better idea to use str:\ndf[df['Time'].astype(str).isin(dates['Time'].astype(str))]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074177472_dataframe_pandas_python.txt
Q: I'm trying to web scrape ebay using python and BeautifulSoup, but I'm getting a list index out of rangeerror As in the title, I'm trying to write a Ebay web-scrape program, yet when I try to find the price, it creates a list error, yet it works for getting the product name. The url is: https://www.ebay.com.au/sch/...
I'm trying to web scrape ebay using python and BeautifulSoup, but I'm getting a list index out of rangeerror
As in the title, I'm trying to write a Ebay web-scrape program, yet when I try to find the price, it creates a list error, yet it works for getting the product name. The url is: https://www.ebay.com.au/sch/i.html?_from=R40&_nkw=switch&_sacat=0&_pgn=1 import bs4 from urllib.request import urlopen as uReq from bs4 import...
[ "if you see containers in which at index 0 there is no product or price info so you can start from index 1 and also you can use try-except instead of that\nimport requests\nfrom bs4 import BeautifulSoup\n\n\npage = requests.get(\"https://www.ebay.com.au/sch/i.html?_from=R40&_nkw=switch&_sacat=0&_pgn=1\")\nsoup=Beau...
[ 0, 0 ]
[]
[]
[ "ebay_api", "html", "python" ]
stackoverflow_0068125408_ebay_api_html_python.txt
Q: Extract certain dataframes of lists of dataframes I have a list of dataframes. Each is build up as followed: No i want to extract the dataframes beginning at a certain time. Collection=[] for i in range(len(subdfs)): if any(subdfs[i]['Zeitpunkt'][subdfs[i]['Zeitpunkt'].dt.hour.eq(12)]): Collection.append...
Extract certain dataframes of lists of dataframes
I have a list of dataframes. Each is build up as followed: No i want to extract the dataframes beginning at a certain time. Collection=[] for i in range(len(subdfs)): if any(subdfs[i]['Zeitpunkt'][subdfs[i]['Zeitpunkt'].dt.hour.eq(12)]): Collection.append(subdfs[i]['Zeitpunkt']) With this code i am able to e...
[ "Try:\nCollection = [subdf for subdf in subdfs if subdf.iloc[0, subdf.columns.get_loc('Zeitpunkt')].hour == 12]\n\n", "It worked with:\nCollection = [subdfs for subdfs in subdfs if subdfs.iloc[0, 1].hour == 12]\n\n" ]
[ 0, 0 ]
[]
[]
[ "dataframe", "extract", "list", "python" ]
stackoverflow_0074177396_dataframe_extract_list_python.txt
Q: Finding value in a column and delete the value if not found in pandas Comparing the columns df1_user and df2_user. If multiple values of df2_user is found in df1_user then merge those values in a new column with a delimiter. I have a dataframe (df1) look like this: df1: df1_ID df1_Tag df1_Info df1_user 1 ...
Finding value in a column and delete the value if not found in pandas
Comparing the columns df1_user and df2_user. If multiple values of df2_user is found in df1_user then merge those values in a new column with a delimiter. I have a dataframe (df1) look like this: df1: df1_ID df1_Tag df1_Info df1_user 1 Test1 Pass 100,200,300 2 Test2 Pass 400,500,600,70...
[ "Use custom lambda function for test if match splitted values in set from column df2['df2_user']:\ns = set(df2['df2_user'].astype(str))\n\nf = lambda x: (','.join(y for y in x.split(',') if y in s))\ndf1['df3_user'] = df1['df1_user'].apply(f)\nprint (df1)\n df1_ID df1_Tag df1_Info df1_user df3_...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074177615_pandas_python.txt
Q: How to fix jupyter lab installation error I'm usint gcp ubu ntu 18.04 server and i wanted to install jupyterlab, but it doesn't work A: Based on the screenshot you have provided it looks like you are using the Python 3.6 version. In accordance with @JohnHanely, I agree that you need to upgrade your Python versi...
How to fix jupyter lab installation error
I'm usint gcp ubu ntu 18.04 server and i wanted to install jupyterlab, but it doesn't work
[ "Based on the screenshot you have provided it looks like you are using the Python 3.6 version. In accordance with @JohnHanely, I agree that you need to upgrade your Python version to 3.7. According to this PEP 563, this functionality from __future__ import annotations is available starting Python3.7\nTo install, us...
[ 1 ]
[]
[]
[ "google_cloud_platform", "jupyter_lab", "python" ]
stackoverflow_0074162233_google_cloud_platform_jupyter_lab_python.txt
Q: How to setup Pylance (or other Linter) to check for Python 2.7 Syntax in VS Code? All support seems to be for Python version 3. Surely there must be a way to get correct syntax highlighting / basic linting for Python 2.7 in VS Code? I am doing a piece of uni coursework that requires us to use version Python 2.7 an...
How to setup Pylance (or other Linter) to check for Python 2.7 Syntax in VS Code?
All support seems to be for Python version 3. Surely there must be a way to get correct syntax highlighting / basic linting for Python 2.7 in VS Code? I am doing a piece of uni coursework that requires us to use version Python 2.7 and want to be able to get this set up and working within VS Code for easy development an...
[ "\nFor auto-completion, you can turn off auto-completions, or select Pylance as your language server as it may provide a good experience if the code is compatible enough with Python 3. We will continue to support selecting Python 2.7 as an interpreter in your workspace. For tools that keep support for Python 2.7 in...
[ 0 ]
[]
[]
[ "python", "python_2.7", "visual_studio_code" ]
stackoverflow_0074174313_python_python_2.7_visual_studio_code.txt
Q: Is there a way to use exec inside a function? The function: def thefunction(): exec("x = 'text'") return x print(thefunction()) and it doesnt work... this is for python 3 A: Give it a dict as a storage for variables. def thefunction(): vars = {} exec("x = 'text'", vars) return vars['x'] print(thefun...
Is there a way to use exec inside a function?
The function: def thefunction(): exec("x = 'text'") return x print(thefunction()) and it doesnt work... this is for python 3
[ "Give it a dict as a storage for variables.\ndef thefunction():\n vars = {}\n exec(\"x = 'text'\", vars)\n return vars['x']\n\nprint(thefunction())\n\nIn any case, read the documentation and warnings about exec.\n", "you need to pass in your locals or it will only be local to that ...\ndef thefunction():\n m...
[ 2, 0 ]
[]
[]
[ "exec", "function", "python", "python_3.x" ]
stackoverflow_0074177710_exec_function_python_python_3.x.txt
Q: How to close all the apps open in an Android device with Python in Appium? My device has a small RAM capacity and when too many apps are open, it starts to slow down and disturbs the execution of my script. So I would like to close all the apps open on my smartphone before running my automation script. So my idea ...
How to close all the apps open in an Android device with Python in Appium?
My device has a small RAM capacity and when too many apps are open, it starts to slow down and disturbs the execution of my script. So I would like to close all the apps open on my smartphone before running my automation script. So my idea was to get the list of all apps open on the device and then kill them one by one...
[ "I don't know about Appium, but to list all currently running third party apps via adb (Android Debug Bridge) it is the following command:\n adb shell pm list packages -e -3\n\n" ]
[ 0 ]
[]
[]
[ "appium", "appium_android", "python", "python_3.x", "python_appium" ]
stackoverflow_0074177496_appium_appium_android_python_python_3.x_python_appium.txt
Q: How to extract date information from the text data? Here is the text data: text = 'PRINT EDITIONNew Survey Suggests An Alarming Increase In Physician Burnout|September 30, 2022, Page A25' I want the the only information "September 30, 2022". A: You may do a regex find all on the pattern: \w+ \d{1,2}, \d{4} Sam...
How to extract date information from the text data?
Here is the text data: text = 'PRINT EDITIONNew Survey Suggests An Alarming Increase In Physician Burnout|September 30, 2022, Page A25' I want the the only information "September 30, 2022".
[ "You may do a regex find all on the pattern:\n\\w+ \\d{1,2}, \\d{4}\n\nSample script:\ntext = 'PRINT EDITIONNew Survey Suggests An Alarming Increase In Physician Burnout|September 30, 2022, Page A25'\ndates = re.findall(r'\\w+ \\d{1,2}, \\d{4}', text)\nprint(dates) # ['September 30, 2022']\n\n" ]
[ 0 ]
[]
[]
[ "extract", "python", "string" ]
stackoverflow_0074177786_extract_python_string.txt
Q: Can't drop columns from dataframe I have a dataframe call df_col: print (df_col) c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 \ 0 5 4 4 5 4 4 4 4 4 5 4 4 3 3 4 3 1 3 4 3 4 4 5 3 5 3 3 5 3 3 2 3 3 2 ...
Can't drop columns from dataframe
I have a dataframe call df_col: print (df_col) c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 \ 0 5 4 4 5 4 4 4 4 4 5 4 4 3 3 4 3 1 3 4 3 4 4 5 3 5 3 3 5 3 3 2 3 3 2 4 4 5 5 4 4 4 4 4 ...
[ "You can compare numpy array from list for not matched minimal values and filter in DataFrame.loc:\na = np.array(each_c)\ndf = df_col.loc[:, a != a.min()]\n\nOr if convert to Series aslo pass index by column from df_col:\ns = pd.Series(each_c, index=df_col.columns)\ndf = df_col.loc[:, s != s.min()]\n\n\nprint (df)\...
[ 0 ]
[]
[]
[ "dataframe", "drop", "pandas", "python" ]
stackoverflow_0074177827_dataframe_drop_pandas_python.txt
Q: How to organize fields in dataframe by repetition and drop duplicates I have this id phone1 phone2 1 300 301 1 303 300 1 300 303 2 400 401 Want this id phone1 phone2 phone3 1 300 303 301 2 400 401 I have tried group by id and column phone1, apply count function, iterate over it adding...
How to organize fields in dataframe by repetition and drop duplicates
I have this id phone1 phone2 1 300 301 1 303 300 1 300 303 2 400 401 Want this id phone1 phone2 phone3 1 300 303 301 2 400 401 I have tried group by id and column phone1, apply count function, iterate over it adding to a list verifying if is already there the id and phone and sum the third...
[ "You can melt to reshape the phone columns to rows, then remove the duplicates per group. Finally, pivot to reshape back to wide format.\nout = (df\n .melt('id')\n .drop_duplicates(['id', 'value'])\n .assign(col=lambda d: d.groupby('id').cumcount().add(1))\n .pivot_table(index='id', columns='col', values='v...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074166087_dataframe_pandas_python.txt
Q: How to convert element to Z value using mean, std for each column? I want to know how to convert each column's value to some value using pandas and numpy. import pandas as pd import numpy as np matrix = [[1,2,3], [4,5,6], [7,8,9]] Original Matrix a b c 1 2 3 4 5 6 7 8 9 Output Matrix a b c -1.22 2 3 0 5 ...
How to convert element to Z value using mean, std for each column?
I want to know how to convert each column's value to some value using pandas and numpy. import pandas as pd import numpy as np matrix = [[1,2,3], [4,5,6], [7,8,9]] Original Matrix a b c 1 2 3 4 5 6 7 8 9 Output Matrix a b c -1.22 2 3 0 5 6 1.22 8 9 For examples, column 'a' is [1, 4, 7]...
[ "Use:\nmatrix = [[1,2,3], [4,5,6], [7,8,9]]\ndf = pd.DataFrame(matrix, columns=list('abc'))\n\nIf need processing all columns subtract all values by means and divide by DataFrame.std with set ddof=0, because default is ddof=1.\ndf = df.sub(df.mean()).div(df.std(ddof=0))\nprint (df)\n a b c\...
[ 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074177917_dataframe_numpy_pandas_python.txt
Q: Remove every special character from start of string and store it in a variable I am trying to build a Pig Latin translator. I want to remove all the characters on the start of a string and store them in a variable. I have already done it to the end, but for some reason when I try and do it the the start it messes ...
Remove every special character from start of string and store it in a variable
I am trying to build a Pig Latin translator. I want to remove all the characters on the start of a string and store them in a variable. I have already done it to the end, but for some reason when I try and do it the the start it messes up the word. For example, when I input *test* it returns *stteay* when it should ret...
[ "I just found the answer... It was a silly little mistake. On line 63 for c in i: needed to be for c in i_temp: Thankyou to @JustLearning for the advice.\n" ]
[ 0 ]
[]
[]
[ "python", "string_interpolation" ]
stackoverflow_0074176739_python_string_interpolation.txt
Q: How to Import Pyqt5 Widget In Another File First File first.py import pyqt5py ret=pyqt5py.confirm() print(ret) Second File Having PYQT5 name: pyqt5py.py import sys from PyQt5 import QtWidgets, uic class Ui(QtWidgets.QDialog): def __init__(self,button1='Ok',button2='Cancel',text='Are You Sure?'): s...
How to Import Pyqt5 Widget In Another File
First File first.py import pyqt5py ret=pyqt5py.confirm() print(ret) Second File Having PYQT5 name: pyqt5py.py import sys from PyQt5 import QtWidgets, uic class Ui(QtWidgets.QDialog): def __init__(self,button1='Ok',button2='Cancel',text='Are You Sure?'): super(Ui, self).__init__() # Call the inherited ...
[ "As suggested by bfris you should rewrite the last lines of pyqt5py.py as follows:\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv) \n window = Ui(button1='Ok',button2='Cancel',text='Are You Sure?')\n app.exec_()\n\nThat way you can run this file directly for debbugging purposes, but al...
[ 0 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0074098749_pyqt5_python.txt
Q: Create Time-Series Dataframe for Regression in Python I have a crime dataset where each row is a recorded crime, and the relevant columns are Date, Crime Type, District. Here is an example with only 2 Districts and 2 Crime Types over a week: I want to expand it to a dataframe that can be used to run regressions. ...
Create Time-Series Dataframe for Regression in Python
I have a crime dataset where each row is a recorded crime, and the relevant columns are Date, Crime Type, District. Here is an example with only 2 Districts and 2 Crime Types over a week: I want to expand it to a dataframe that can be used to run regressions. In this simple example, I need the columns to be Date, Dist...
[ "I will try to answer my own question here. I think I figured it out, but would appreciate any input on my method. I was able to do it without looping, but rather using pivot_table and merge.\nImport packages:\nimport pandas as pd\nfrom datetime import datetime\nimport numpy as np\n\nImport crime dataset:\ncrime_df...
[ 0 ]
[]
[]
[ "dataframe", "python", "regression", "time_series" ]
stackoverflow_0074163043_dataframe_python_regression_time_series.txt
Q: Trying to add collision but it traps my player in the top left corner? Adding collision to the black tiles but it doesn't work and traps my character in the top left corner unable to move. class platform(): def __init__(self, data): self.tile_list = [] #load images rectangle_img = pyga...
Trying to add collision but it traps my player in the top left corner?
Adding collision to the black tiles but it doesn't work and traps my character in the top left corner unable to move. class platform(): def __init__(self, data): self.tile_list = [] #load images rectangle_img = pygame.image.load('image/rect.png') row_count = 0 for row in da...
[ "What anyway are collisions?\nCollisions are when two shapes overlap with some area.\n\nIf you want to \"resolve\" collision (move elements in the way that they don't collide anymore), you need the information about the overlapping area.\nResolving collisions\nOn the image it is clear how you want to move things ap...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074175829_pygame_python.txt
Q: Scipy cdist maximum distance New to scipy. I am trying to use the cdist function to pick the greatest distance between vectors. My attempt is dm = cdist(XA, XB, lambda u, v: np.max(np.sqrt(((u-v)**2).sum()))) but it doesn't seem to produce the correct result. Any suggestions? A: The cdist function returns a NxM...
Scipy cdist maximum distance
New to scipy. I am trying to use the cdist function to pick the greatest distance between vectors. My attempt is dm = cdist(XA, XB, lambda u, v: np.max(np.sqrt(((u-v)**2).sum()))) but it doesn't seem to produce the correct result. Any suggestions?
[ "The cdist function returns a NxM matrix containing all distances between the N vectors of XA and M vectors of XB. If you want the max distance, regardless of the vectors that originate it, you need to ravel() the 2D array into a 1D array and then look for the max() value:\ndm = cdist(XA, XB,metric='euclidean').rav...
[ 0 ]
[]
[]
[ "python", "scikit_learn", "scipy" ]
stackoverflow_0074177860_python_scikit_learn_scipy.txt
Q: Unable connect to MongoDB listening on localhost (on host) from within a docker container On Linux Ubuntu 22.04 I have created a docker container with a simple python script that has to connect to a MongoDB instance working on the host and listening on localhost. To have a reproducible example consider what follow...
Unable connect to MongoDB listening on localhost (on host) from within a docker container
On Linux Ubuntu 22.04 I have created a docker container with a simple python script that has to connect to a MongoDB instance working on the host and listening on localhost. To have a reproducible example consider what follows. The Dockerfile is: FROM ubuntu RUN apt-get update RUN apt-get install curl pip micro netcat ...
[ "Finally solved as following.\nI had to add directConnection=True in the connection string to MongoDB and I had to set bindIp: 0.0.0.0 in MongoDB configuration file (in /etc/mongod.conf).\nTo be clearer I changed motor_client as follows:\nmotor_client = AsyncIOMotorClient(\n username=\"user\",\n password=\"secret\"...
[ 0 ]
[]
[]
[ "docker", "mongodb", "python", "tornado_motor" ]
stackoverflow_0074169159_docker_mongodb_python_tornado_motor.txt
Q: Why does my cube bounce at the left side but not at the right side? import pygame import sys def main(): x=375 y=400 y_velocity = 0 acceleration = 0.1 bg_color=(183,255,183) shape_color=(0,255,255) x_minus = None pygame.init() DISPLAY = pygame.display.set_mode((800,800)) ic...
Why does my cube bounce at the left side but not at the right side?
import pygame import sys def main(): x=375 y=400 y_velocity = 0 acceleration = 0.1 bg_color=(183,255,183) shape_color=(0,255,255) x_minus = None pygame.init() DISPLAY = pygame.display.set_mode((800,800)) icon = pygame.image.load("assets/firedash.ico") pygame.display.set_capt...
[ "You wrote:\nif x > 750:\n x*=-1\n x_minus = True\n\nSo if x is for example 755 you will switch it to -755 and start moving to the left. Next loop it will be < 0 so you will switch it to +755 plus something and start moving to the right... and so on. It will be always out of bounds!\nTo debug these kinds of i...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074177935_pygame_python.txt
Q: Comparing two files with python...iterating line by line I have two files that I want to compare: -File 1 contains SHA1 hash values and the file path of executable files. (Each line is a different file.) -File 2 is a file containing known files and their SHA1 hash value and other data. (Again, each line is a diffe...
Comparing two files with python...iterating line by line
I have two files that I want to compare: -File 1 contains SHA1 hash values and the file path of executable files. (Each line is a different file.) -File 2 is a file containing known files and their SHA1 hash value and other data. (Again, each line is a different file.) I want to compare each line of file 1 against each...
[ "A few remarks:\n\nWhen using with open(..) you don't need to close your file, it's closed automatically at the end of the block\niterating through the lines of a file f is as simple as for line in f:\n\nSo you can do the following:\nimport sys\n\nwith open(sys.argv[3], 'w') as f3:\n f3.write('Hash Values of Unk...
[ 1 ]
[]
[]
[ "linux", "python", "python_3.x" ]
stackoverflow_0074177720_linux_python_python_3.x.txt
Q: exchangelib, traverse all folders and only messages for shared_postbox in shared_postboxes: account = Account(shared_postbox, credentials=credentials, autodiscover=True) top_folder = account.root email_folders = [f for f in top_folder.walk() if f.CONTAINER_CLASS == 'IPF.Note'] for folder in e...
exchangelib, traverse all folders and only messages
for shared_postbox in shared_postboxes: account = Account(shared_postbox, credentials=credentials, autodiscover=True) top_folder = account.root email_folders = [f for f in top_folder.walk() if f.CONTAINER_CLASS == 'IPF.Note'] for folder in email_folders: for m in folder.all().only...
[ "The error comes from the fact that the list of folders you're searching contains the AllContacts folder which cannot contain items with a sender field.\nA better filter for folders containing messages could be:\nfrom exchangelib.folders import Messages\n\nemail_folders = [f for f in top_folder.walk() if isinstance...
[ 1 ]
[]
[]
[ "exchange_server", "exchangelib", "exchangewebservices", "python", "traversal" ]
stackoverflow_0074153826_exchange_server_exchangelib_exchangewebservices_python_traversal.txt
Q: ImportError django is not found I installed django framework in virtual env and now it is given me an import error. (WebEnvironment) D:\conda project\web\mysite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_comma...
ImportError django is not found
I installed django framework in virtual env and now it is given me an import error. (WebEnvironment) D:\conda project\web\mysite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No mod...
[ "If you want to create a new virtual environment, you can follow the steps below.\n mkdir djangoproject\n \n cd djangoproject/\n \n pip install virtualenv\n \n virtualenv myvenv\n\nThus, you create a new virtual environment.\n pip freeze\n \n which python\n \n source myvenv/bin/a...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0054040545_django_django_rest_framework_python_python_3.x.txt
Q: tensorflow.python.eager.polymorphic_function No module error on imports I have tried checking around for the solution for this error but all solutions I have found are not working. I am requesting for more assistance. I have this tensorflow error --------------------------------------------------------------------...
tensorflow.python.eager.polymorphic_function No module error on imports
I have tried checking around for the solution for this error but all solutions I have found are not working. I am requesting for more assistance. I have this tensorflow error --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call...
[ "it is easy to backward compatibilities try searching for version compatibilities and checkout from this website TFLite Authoring Tool they had the same problem and me testing it on the same from Git.\nI am testing and found that the update link is targeting the incorrect path where I am using AMD. ( Prepending upd...
[ 1 ]
[]
[]
[ "python", "python_3.x", "tensorflow" ]
stackoverflow_0074177865_python_python_3.x_tensorflow.txt
Q: Altering height of Python/Dash Navigation Pills? I have a Python/Dash application with a vertical nav-bar and I wish to alter the height of the nav-pills. I'm using the bootstrap "SLATE" theme with the CSS-file stored locally in the /asset directory. The sidebar code: SIDEBAR_STYLE = { "position": "fixed", ...
Altering height of Python/Dash Navigation Pills?
I have a Python/Dash application with a vertical nav-bar and I wish to alter the height of the nav-pills. I'm using the bootstrap "SLATE" theme with the CSS-file stored locally in the /asset directory. The sidebar code: SIDEBAR_STYLE = { "position": "fixed", "top": 0, "left": 0, "bottom": 0, "width...
[ "\nYou should create an assets folder in the same directory where the python file exists.\n\nCreate a CSS file in the assets folder and put your CSS style.\n\nmain_file.py\nassets/\n|-- style.css\n\n\nRun your python file, the CSS file will be applied automatically.\n\n\n" ]
[ 0 ]
[]
[]
[ "css", "nav_pills", "plotly_dash", "python" ]
stackoverflow_0074177619_css_nav_pills_plotly_dash_python.txt
Q: Save a modied FASTA file with Biopython I have used Biopython to remove some sequences due to they are too short. However, I don't know how to save the printed new sequences in a txt file. This is the code that I have: from Bio import SeqIO for seq_record in SeqIO.parse("aminoacid_example.txt", "fasta"): if len(s...
Save a modied FASTA file with Biopython
I have used Biopython to remove some sequences due to they are too short. However, I don't know how to save the printed new sequences in a txt file. This is the code that I have: from Bio import SeqIO for seq_record in SeqIO.parse("aminoacid_example.txt", "fasta"): if len(seq_record.seq)>=30: print(">",seq_record....
[ "it should go something like this:\ntext_list=[]\nfor seq_record in SeqIO.parse(\"aminoacid_example.txt\", \"fasta\"):\n if len(seq_record.seq)>=30:\n elem1=\">\"+seq_record.id\n elem2=seq_record.seq\n text_list.extend([elem1, elem2])\nwith open('filetowrite.txt', 'w') as f:\n f.write('\\...
[ 0 ]
[]
[]
[ "biopython", "dna_sequence", "python", "sequence", "string" ]
stackoverflow_0074177841_biopython_dna_sequence_python_sequence_string.txt
Q: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? --> WSGI.PY file When I try to execute py manage.py runserver I had the following message: raise ImportError( Import Error: Couldn't import Django. Are you sure it's installed and available on your PYTHONPA...
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? --> WSGI.PY file
When I try to execute py manage.py runserver I had the following message: raise ImportError( Import Error: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? )
[ "I found a lot of possible solutions on the internet. I suggest first try the following:\nGo to the wsgi.py file, inside MySite and go to this line:\nfrom django.core.wsgi import get_wsgi_application\n\nVerify that Django is imported. I use Pycharm, the IDE allowed me to import directly from there.\nAfter this I wa...
[ 2, 0 ]
[ "Run the command as follows:\npython .\\manage.py runserver\n\nIf you're on a Windows machine, you may be calling OS' python, not the one inside your virtual environment.\n" ]
[ -1 ]
[ "django", "python", "wsgi" ]
stackoverflow_0065479892_django_python_wsgi.txt
Q: Download Historic NSE Futures Data I need to download NSE Futures data since 2012 for my strategy backtesting. I tried NSEpy and jugaad-data libraries but they are giving one day's data at a time. I tried Getbhavcopy as well but the data is not accurate there. Is there any other free source to download the same. T...
Download Historic NSE Futures Data
I need to download NSE Futures data since 2012 for my strategy backtesting. I tried NSEpy and jugaad-data libraries but they are giving one day's data at a time. I tried Getbhavcopy as well but the data is not accurate there. Is there any other free source to download the same. Thanks, Mohit
[ "I've used NSEpy, this is basically scraping from the NSE website, better to use some API which actually has the right to provide the data. e.g: Samco, angel one APIs.\nthey are free as well.\n", "You can get as follows .....\nfrom datetime import timedelta, date\nfrom nsepy import get_history\n\ndef importdata(s...
[ 0, 0 ]
[]
[]
[ "python", "stockquotes" ]
stackoverflow_0070486337_python_stockquotes.txt
Q: How can I reduce an operation with a subscript? expenses = [ ('Dinner', 80), ('Car repair', 120), ('csgo skins', 200) ] # Version with for-loop sum = 0 for expense in expenses: sum += expense[1] print(sum) # Version using lambda+reduce sum2 = reduce((lambda a, b: a[1] + b[1]), expenses) print(sum...
How can I reduce an operation with a subscript?
expenses = [ ('Dinner', 80), ('Car repair', 120), ('csgo skins', 200) ] # Version with for-loop sum = 0 for expense in expenses: sum += expense[1] print(sum) # Version using lambda+reduce sum2 = reduce((lambda a, b: a[1] + b[1]), expenses) print(sum2) I'm trying to obtain, with lambda and reduce, the...
[ "Recall that reduce calls itself with the result from the previous reduce operation as its first argument. So a[1] no longer makes sense because on the second and subsequent iterations, a is the sum returned from the previous iteration.\nYou can painfully get around this with an explicit special case, of course; or...
[ 2, 2 ]
[]
[]
[ "lambda", "python", "reduce" ]
stackoverflow_0074178016_lambda_python_reduce.txt
Q: Add dropdown menu (nested list) to Google Spreadsheat with gspread / Google Spread API to whole column I am struggling to insert a dropdown menu into a Google Spreadsheet using the gspread module in python. This question explains how to get a dropdown menu in a spreadsheet: How to add a nested list with gspread? H...
Add dropdown menu (nested list) to Google Spreadsheat with gspread / Google Spread API to whole column
I am struggling to insert a dropdown menu into a Google Spreadsheet using the gspread module in python. This question explains how to get a dropdown menu in a spreadsheet: How to add a nested list with gspread? However, even if I change the startColumnIndex and endColumnIndex the dropdown menu only shows up in one cell...
[ "I believe your goal is as follows.\n\nWhen column \"C\" is not empty, you want to insert a dropdown list to column \"D\".\nYou want to achieve this using gspread for python.\n\nIn this case, how about the following sample script?\nSample script:\n# Please use your gspread client.\n\nspreadsheetId = \"###\" # Pleas...
[ 0 ]
[]
[]
[ "google_sheets", "google_sheets_api", "gspread", "python" ]
stackoverflow_0074153097_google_sheets_google_sheets_api_gspread_python.txt
Q: Error 400: invalid_scope ["https://www.googleapis.com/auth/apps.reporting.audit"] unable to set up email monitor with googleAPI python client I began following the code sample given on googleapis github page to help me understand how the Email audit API works. The sample initialized the API service like this: from...
Error 400: invalid_scope ["https://www.googleapis.com/auth/apps.reporting.audit"] unable to set up email monitor with googleAPI python client
I began following the code sample given on googleapis github page to help me understand how the Email audit API works. The sample initialized the API service like this: from googleapiclient import sample_tools service, flags = sample_tools.init( argv, "audit", "v1", __doc__, __file__, scope="ht...
[ "The sample code mentioned actually refers to the (now deprecated) Enterprise Activity API. This service was moved to Reports API and as Enterprise Activity API, it is only available for Workspace domains.\nSo indeed, this script is outdated. If you want to use Reports API to manage Activities, you may want to refe...
[ 0 ]
[]
[]
[ "google_admin_sdk", "google_api", "google_api_python_client", "google_email_audit_api", "python" ]
stackoverflow_0074163993_google_admin_sdk_google_api_google_api_python_client_google_email_audit_api_python.txt
Q: how to extract only POS out of its lemma I have Tibetan word and it's POS, as below: སྩོལ་ VERB སྐབས་ NOUN ཆོས་ NOUN ཞུ་བ་ VERB ཚོས་ NOUN དེབ་ NOUN how can i extract only the pos as shown : VERB NOUN NOUN VERB NOUN NOUN code I tried : file = # given input file containing word and pos for line in file: ...
how to extract only POS out of its lemma
I have Tibetan word and it's POS, as below: སྩོལ་ VERB སྐབས་ NOUN ཆོས་ NOUN ཞུ་བ་ VERB ཚོས་ NOUN དེབ་ NOUN how can i extract only the pos as shown : VERB NOUN NOUN VERB NOUN NOUN code I tried : file = # given input file containing word and pos for line in file: word = line.split(' ')[0] pos = ...
[ "Try using list comprehension with string.ascii_uppercase\nimport string\n\ntext = \"\"\"སྩོལ་ VERB\nསྐབས་ NOUN\nཆོས་ NOUN\nཞུ་བ་ VERB\nཚོས་ NOUN\nདེབ་ NOUN\"\"\"\n\n\nfor line in text.split('\\n'):\n POS = ''.join([i for i in line if i in string.ascii_uppercase]) \n print(POS)\n\nor from a file:\nwith ope...
[ 0, 0 ]
[]
[]
[ "for_loop", "loops", "nlp", "python", "python_3.x" ]
stackoverflow_0074177184_for_loop_loops_nlp_python_python_3.x.txt
Q: Searching Dataframe Using Two Criteria I have a dataframe called test_df (below) and I am trying to search for the ID based on two criteria: the Factor and the name. Here's my code: test_id = test_df.loc[test_df['Name'].str.contains(test_name, case=False) & test_df['Factor'].str.contains(test_factor, case=False), ...
Searching Dataframe Using Two Criteria
I have a dataframe called test_df (below) and I am trying to search for the ID based on two criteria: the Factor and the name. Here's my code: test_id = test_df.loc[test_df['Name'].str.contains(test_name, case=False) & test_df['Factor'].str.contains(test_factor, case=False), 'ID'].item() But I get the following error:...
[ "Problem is no match any value, so DataFrame.loc return empty Series.\nPossible solution is use next + iter for assign default value if no match:\nmask = test_df['Name'].str.contains(test_name, case=False) & \n test_df['Factor'].str.contains(test_factor, case=False)\n\n#if no match assign 'no match'\ntest_id ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074178193_pandas_python.txt
Q: QuestDB installation on a VPS web infrastructure newbie - moving I have a fx vol model which I have written in python / questdb on my local machine. The standalone model works as an application in my machine and I also have lots of feeds written which are constantly updating the local machine questdb instance. Now...
QuestDB installation on a VPS web infrastructure newbie - moving
I have a fx vol model which I have written in python / questdb on my local machine. The standalone model works as an application in my machine and I also have lots of feeds written which are constantly updating the local machine questdb instance. Now I want to move to web and have my application and database on the web...
[ "Lots of good questions there. Will try to help with all of them (disclaimer, I work for QuestDB as a developer advocate)\n\nWhat sort of VPS service to look for:\n\nAnything will work, but depending on the volume you are going to ingest/query, you will greatly benefit from a fast drive. In many cases the default d...
[ 0 ]
[]
[]
[ "feed", "python", "questdb", "vps" ]
stackoverflow_0074173116_feed_python_questdb_vps.txt
Q: Flatten last layer of nested list using comprehension How can I flatten the last layer of a nested list? lista = [['a'],['b']] listb = [['c']] nested = [lista, listb] # [[['a'], ['b']], [['c']]] # how to get [['a', 'b'], ['c']]? [[x for x in y] for y in nested] # gives [[['a'], ['b']], [['c']]] I tried with unp...
Flatten last layer of nested list using comprehension
How can I flatten the last layer of a nested list? lista = [['a'],['b']] listb = [['c']] nested = [lista, listb] # [[['a'], ['b']], [['c']]] # how to get [['a', 'b'], ['c']]? [[x for x in y] for y in nested] # gives [[['a'], ['b']], [['c']]] I tried with unpacking but it is disallowed in list comprehension. For more...
[ "lista = [['a'],['b']]\nlistb = [['c']]\nnested = [lista, listb]\n\n# [[['a'], ['b']], [['c']]]\n# how to get [['a', 'b'], ['c']]?\n\nprint([[x for x in y] for y in nested])\n# gives [[['a'], ['b']], [['c']]]\n\n\n#simple solution:\nprint([[x[0] for x in y] for y in nested])\n# gives [['a', 'b'], ['c']]\n\n\n#solut...
[ 3, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074178150_python.txt
Q: Sort columns from multiple excel sheets I have a big dataset with 88 Excel sheets in one excel file. I want to sort the data from column 4 and 6 (not index). Every sheet have the same pattern of columns. The pattern of sheets I want to sort is the following: Sheet 1,2,3,4,...,9,10,11,12,...,17,18,19,20.... and so ...
Sort columns from multiple excel sheets
I have a big dataset with 88 Excel sheets in one excel file. I want to sort the data from column 4 and 6 (not index). Every sheet have the same pattern of columns. The pattern of sheets I want to sort is the following: Sheet 1,2,3,4,...,9,10,11,12,...,17,18,19,20.... and so on (the last one's would be sheets 81,82,83 a...
[ "You could try something like below:\n# Import statement\nimport pandas as pd\n\n# Generate our list of target sheets\nsheet_skip_amount = 5 # Number of sheets to skip between groups\nend_of_first_sheetlist = 3 # Python lists start at 0\ntargetRange = [0,1,2,3]\nsheetCount = 87 # One less than 88 because lists star...
[ 0 ]
[]
[]
[ "excel", "pandas", "python", "sorting" ]
stackoverflow_0074172888_excel_pandas_python_sorting.txt
Q: Python: import file not working in the if statement This is a main file in which I start an other.py script. The initial import works, it executes the other.py on line 1. But when this has ran the other.py, it will ask input to to restart other.py once more. The 'no' answer is working, the 'yes' answer just keeps ...
Python: import file not working in the if statement
This is a main file in which I start an other.py script. The initial import works, it executes the other.py on line 1. But when this has ran the other.py, it will ask input to to restart other.py once more. The 'no' answer is working, the 'yes' answer just keeps giving me the same prompt. So the import is not working i...
[ "Once python has imported a module it won't import it again. You have to specifically ask python to reload a module if you want it to reload it.\nTry and remove the import other from the top and run your app.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074178268_python.txt
Q: Is there a way where I can replace the first '.' with '-' in my code for a domain generator last time I've gotten some help on making a website name generator. I feel bad but i'm stuck at the moment and I need some help again to improve it. in my code there's a .txt file called combined which included these lines....
Is there a way where I can replace the first '.' with '-' in my code for a domain generator
last time I've gotten some help on making a website name generator. I feel bad but i'm stuck at the moment and I need some help again to improve it. in my code there's a .txt file called combined which included these lines. After that i created a variable to add to the domain web = 'web' suffix = 'co.id' And then i w...
[ "Sure just iterate through a list of delimiters to add each of them to the output.\nweb = 'web'\nsuffix = 'co.id'\noutput_count = 50\nsubdomain_count = 2\ndelimeters = [ '-', '.']\nfor i in range(output_count):\n out = []\n for j in range(subdomain_count):\n out.append(random.choice(Test))\n for del...
[ 1, 0, 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074177754_jupyter_notebook_python.txt
Q: An error occurred while importing the package(m1 macbook pro) ImportError: C extension: dlopen(mach-o file, but is an incompatible architecture (have (x86_64), need (arm64e))) not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --force' to build the C e...
An error occurred while importing the package(m1 macbook pro)
ImportError: C extension: dlopen(mach-o file, but is an incompatible architecture (have (x86_64), need (arm64e))) not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --force' to build the C extensions first. How to roslove this problem? Thank you for your he...
[ "It has been solved, it is a problem with the virtual environment\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074168503_python.txt
Q: Row by row mapping keys of dictionary of dataframes to new dictionary of dataframes I have two dictionaries of data frames LP3 and ExeedenceDict. The ExeedenceDict is a dictionary of 4 dataframes with keys 'two','ten','twentyfive','onehundred'. The LP3 dictionary has keys 'LP_DevilMalad', 'LP_Bloomington', 'LP_Dev...
Row by row mapping keys of dictionary of dataframes to new dictionary of dataframes
I have two dictionaries of data frames LP3 and ExeedenceDict. The ExeedenceDict is a dictionary of 4 dataframes with keys 'two','ten','twentyfive','onehundred'. The LP3 dictionary has keys 'LP_DevilMalad', 'LP_Bloomington', 'LP_DevilEvans', 'LP_Deep', 'LP_Maple', 'LP_CubMaple', 'LP_Cottonwood', 'LP_Mill', 'LP_CubNrPres...
[ "Can't test it without a reproducible example, but I would do something along the lines:\nindex_map = {\n \"two\": 6,\n \"ten\": 9,\n \"twentyfive\": 10,\n \"onehundred\": 12\n}\n\ncol_of_interest = [\"Annual Exceedence\", \"With Reg Skew\", \"Without Reg Skew\", \"5% Lower\", \"95% Upper\"]\n\nfor inde...
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "dictionary_comprehension", "pandas", "python" ]
stackoverflow_0074175624_dataframe_dictionary_dictionary_comprehension_pandas_python.txt
Q: xpath give empty output using selenium I am not getting price they give me empty output this is page link https://www.amazon.com/dp/B00M0DWQYI?th=1 from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdrive...
xpath give empty output using selenium
I am not getting price they give me empty output this is page link https://www.amazon.com/dp/B00M0DWQYI?th=1 from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support.select import Select from selenium...
[ "You may want to wait for that element to properly load, prior to locating it:\n[...]\nwait = WebDriverWait(driver, 10)\n\n\nitem['price'] = wait.until(EC.element_to_be_clickable((By.XPATH, \"//div[@id='corePrice_feature_div']//span[@class='a-offscreen']\"))).text\n\nSelenium documentation can be found at https://w...
[ 1, 0, 0 ]
[]
[]
[ "python", "selenium", "web_scraping", "webdriverwait", "xpath" ]
stackoverflow_0074173166_python_selenium_web_scraping_webdriverwait_xpath.txt
Q: How to assert a method has been called from another complex method in Python? I am adding some tests to existing not so test friendly code, as title suggest, I need to test if the complex method actually calls another method, eg. class SomeView(...): def verify_permission(self, ...): # some logic to ve...
How to assert a method has been called from another complex method in Python?
I am adding some tests to existing not so test friendly code, as title suggest, I need to test if the complex method actually calls another method, eg. class SomeView(...): def verify_permission(self, ...): # some logic to verify permission ... def get(self, ...): # some codes here I am...
[ "There are a number of points made in the comments that I strongly disagree with, but to your actual question first.\nThis is a very common scenario. The suggested approach with the standard library's unittest package is to utilize the Mock.assert_called... methods.\nI added some fake logic to your example code, ju...
[ 0 ]
[]
[]
[ "python", "python_unittest" ]
stackoverflow_0074168043_python_python_unittest.txt
Q: dropna=True behaviour in pandas.DataFrame.groupby and pandas.DataFrame.pivot_table I'm trying to inspect the behaviour of the pandas.DataFrame.groupby and pandas.DataFrame.pivot_table methods and I've come up to this difference which I can't explain by myself. It seems that the specification of dropna=True (defaul...
dropna=True behaviour in pandas.DataFrame.groupby and pandas.DataFrame.pivot_table
I'm trying to inspect the behaviour of the pandas.DataFrame.groupby and pandas.DataFrame.pivot_table methods and I've come up to this difference which I can't explain by myself. It seems that the specification of dropna=True (default for both) has different consequences in the two cases, which might be somehow enforced...
[ "The main difference is that for .groupby() the dropna=True refers to the groups you are creating, NOT to the values. In fact if you add a row to your df:\nrow = {'age':50,'country_live':np.nan,'employment_status':'Partially employed by a company / organization'}\n\ndf = df.append(row, ignore_index=True)\n\nthe piv...
[ 1, 1 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074175367_group_by_pandas_python.txt
Q: Detect if sensor data is trending upwards with value overflow I am reading data from sensor over time and I need to check whether it is trending upwards. I know how to do that, but sensor at some point reaches max value and starts over and I need to be able to ignore this rollover. How to correctly deal with this ...
Detect if sensor data is trending upwards with value overflow
I am reading data from sensor over time and I need to check whether it is trending upwards. I know how to do that, but sensor at some point reaches max value and starts over and I need to be able to ignore this rollover. How to correctly deal with this so that I correctly find the data trend, but also correctly deal wi...
[ "I am not too sure how would you normally check if there is a data overflow after 255 or it's a descending trend.\nI think that you could put a threshold (considering your data differences, a threshold of 100 should be enough) which would verify if 2 consecutive values could be differentiated by the data overflow o...
[ 0, 0 ]
[]
[]
[ "data_science", "python" ]
stackoverflow_0074177881_data_science_python.txt
Q: Discord.py - How do I save commands in a different folder? I'm trying to save my commands in a folder instead of in one file to keep things organized, but I don't know how to import the commands. This is the main file: import discord from discord.ext import commands client = commands.Bot(command_prefix=">") @cli...
Discord.py - How do I save commands in a different folder?
I'm trying to save my commands in a folder instead of in one file to keep things organized, but I don't know how to import the commands. This is the main file: import discord from discord.ext import commands client = commands.Bot(command_prefix=">") @client.event async def on_connect(): print(f'Logged In As {clie...
[ "You're looking for Cogs and Extensions.\nCogs will group commands together (possibly in separate files), extensions allow you to register commands in a different file. Don't import your commands in your main, that's very ugly.\nCogs docs (with examples): https://discordpy.readthedocs.io/en/stable/ext/commands/cogs...
[ 2 ]
[ "The test command you made should use the command decorator function from discord.ext.commands module. That way the dependency on the client is removed until you can register the command to the bot.\nimport discord\nfrom discord.ext import commands\n\n@commands.command()\nasync def ping(ctx):\n delay = ctx.bot.l...
[ -3 ]
[ "discord.py", "import", "python", "python_3.x" ]
stackoverflow_0074175412_discord.py_import_python_python_3.x.txt
Q: How to ping several IP addresses without using the same line of code for every IP address? I need to ping several IPs a not all at once but one by one. My problem is that I do not want to use the same if else clause for every IP address. As you can see I have only done it for 10.10.10.5 but i do not want to repea...
How to ping several IP addresses without using the same line of code for every IP address?
I need to ping several IPs a not all at once but one by one. My problem is that I do not want to use the same if else clause for every IP address. As you can see I have only done it for 10.10.10.5 but i do not want to repeat it for every other IP i know it is bad practice but i have no idea how to write a algorithm or...
[ "I think you've answered your own question by saying you need 'to iterate'. You should put the ip addresses in a list and iterate over them:\nip_addressses = [.....]\nfor ip in ip_addresses:\n supprocess.run(...)\n\n", "You can iterate over a list of ip addresses, and then run your lohic using a match statemen...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074178362_python_python_3.x.txt
Q: Accessing class variable defined in parent class in python I want to set a class variable in a parent class and then manipulate it in a child class. I have code like this: class Parent(): def unique_to_parent(self): self.c = "D" class Child(Parent): def blah(self): print(self.c) if __name...
Accessing class variable defined in parent class in python
I want to set a class variable in a parent class and then manipulate it in a child class. I have code like this: class Parent(): def unique_to_parent(self): self.c = "D" class Child(Parent): def blah(self): print(self.c) if __name__ == '__main__': thing = Child() thing.blah() But this...
[ "Solution\nTo access an attribute of a parent class, the attribute has to be created first. To do this the function in which the variable is declared (In your case unique_to_parent) has to be called. To do this there are two ways:\n\nOne, is to initialize the parent in the constructor of the child class and then ca...
[ 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074134267_oop_python.txt
Q: zsh command cannot found aws2-wrap I'm trying to run aws2-wrap in my macos. I did python3 -m pip install aws2-wrap DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussio...
zsh command cannot found aws2-wrap
I'm trying to run aws2-wrap in my macos. I did python3 -m pip install aws2-wrap DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebre...
[ "you need to export the .local/bin\nexport PATH=~/.local/bin:$PATH\n\n" ]
[ 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0069288400_macos_python.txt
Q: Return list from API response across multiple symbols I need to return a list of symbols only if they have 'position_value' > 0. From there I want to get more data corresponding to the symbol like side, unrealised_pnl etc, possibly into some easily readable format like a pandas dataframe. So far I use this to get ...
Return list from API response across multiple symbols
I need to return a list of symbols only if they have 'position_value' > 0. From there I want to get more data corresponding to the symbol like side, unrealised_pnl etc, possibly into some easily readable format like a pandas dataframe. So far I use this to get the whole JSON response, but the moment I move beyond 'resu...
[ "After being JSON-loaded, the result is a list of dictionaries. You can't directly access the keys of each dict in that list until you have the whole dict first. So you'd iterate over it like this:\nfor item in res['result']:\n data = item['data'] # to get the value stored in the 'data' key\n\nWhat do you expec...
[ 1 ]
[]
[]
[ "bybit", "python" ]
stackoverflow_0074177752_bybit_python.txt
Q: How do i get the value of an html dropped item in Python? I'm trying to complete a project whereby a user can select various exercises from a dropdown menu and drag them to a series of boxes in order to create a workout. I'm supposed to use Python, Javascript and CSS in the project but i'm very new to this and i'm...
How do i get the value of an html dropped item in Python?
I'm trying to complete a project whereby a user can select various exercises from a dropdown menu and drag them to a series of boxes in order to create a workout. I'm supposed to use Python, Javascript and CSS in the project but i'm very new to this and i'm struggling. My problem is that once the text has been dropped ...
[ "open up the browser inspection and look at network and you should see what you're posting in the network tab.\nForms will post your <input> fields but I can't see any of those in your html code. Form submission will not post the values in any <div>s.\n" ]
[ 0 ]
[]
[]
[ "drop", "html", "key_value", "python" ]
stackoverflow_0074178457_drop_html_key_value_python.txt
Q: Work or not : python TypeError: 'NoneType' object is not subscriptable I use this code to recognize QR and EAN codes. It works fine. But after few hours it stops with error. Even when i do not use it. Why it happens? The error is below. It says that samothing is wrong with sky = frame[800:1200,330:1500]. I am new ...
Work or not : python TypeError: 'NoneType' object is not subscriptable
I use this code to recognize QR and EAN codes. It works fine. But after few hours it stops with error. Even when i do not use it. Why it happens? The error is below. It says that samothing is wrong with sky = frame[800:1200,330:1500]. I am new with Python so i do not have a clue. error: sky = frame[800:1200,330:1500] p...
[ "Maybe frame is not available yet, you can make sure it is by assessing\nif frame is None:\n continue\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074178489_python.txt
Q: How to authenticate MS graph requests? I am using https://developer.microsoft.com/en-us/graph/graph-explorer to make requests I am trying to convert them to Python to use for general automation. I always copy from browser>postman>code, so I have all the cookies/tokens/etc. I need, and my python request will work u...
How to authenticate MS graph requests?
I am using https://developer.microsoft.com/en-us/graph/graph-explorer to make requests I am trying to convert them to Python to use for general automation. I always copy from browser>postman>code, so I have all the cookies/tokens/etc. I need, and my python request will work until something expires. In this case, that s...
[ "Access tokens are short lived. Refresh them after they expire to continue accessing resources.\n\nPlease refer this document: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token\nHope this helps.\n" ]
[ 1 ]
[]
[]
[ "authentication", "microsoft_graph_api", "oauth_2.0", "postman", "python" ]
stackoverflow_0074172186_authentication_microsoft_graph_api_oauth_2.0_postman_python.txt
Q: problem when download a image from website using beautiful soap i am wrtiting this code to get information about top movies and also download the image blong to the movie but on some image they downloaded but their size are 0 but they have size on disk when i kilick on the link of the image that i cant download it...
problem when download a image from website using beautiful soap
i am wrtiting this code to get information about top movies and also download the image blong to the movie but on some image they downloaded but their size are 0 but they have size on disk when i kilick on the link of the image that i cant download it well its opening well and there is no problem in link for exampele t...
[ "i found my problem in some movie name there was \":\" and as you knwo you cant user \":\"\nin file names i fix the code with .replace()\nmovie_name.replace(\":\", \"\")\n\n", "Once you get a response, check if it's empty before writing to disk. Might need to retry or the link may be bad.\n" ]
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_requests" ]
stackoverflow_0074177320_beautifulsoup_python_python_requests.txt
Q: Easy way to import functions from another folder , but to work with pytest I am looking for a easy way to import functions from another folder: |--mylib | |--__init__.py | |--mylib2.py | |--mytest | |--other.py | |--test_one.py | |--mymain.py mylib2.py def suma(a,b): return a+b mymain.py from mylib.m...
Easy way to import functions from another folder , but to work with pytest
I am looking for a easy way to import functions from another folder: |--mylib | |--__init__.py | |--mylib2.py | |--mytest | |--other.py | |--test_one.py | |--mymain.py mylib2.py def suma(a,b): return a+b mymain.py from mylib.mylib2 import suma def main(): a=3 b=4 c=suma(a,b) print(c) if ...
[ "TL;DR: You should also add __init__.py inside mytest folder.\nExplanation:\nIt's easy to misunderstand the concepts between module and package. I'm still not sure that I have fully understanding them even after years programming on Python. Plz correct me if I'm wrong.\n\nIf mytest folder don't have __init__.py, th...
[ 2 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0074178540_pytest_python.txt
Q: Explain regular expression in Python Can you help me to understand this code line by line please? def word(w) pattern = re.compile(r'^[^aeiouAEIOU]+') if re.findall(r'[^aeiouAEIOU]y[^aeiouAEIOU]', w): pattern = re.compile(r'^[^aeiouAEIOUy]+') beginning = re.findall(pattern, word) w...
Explain regular expression in Python
Can you help me to understand this code line by line please? def word(w) pattern = re.compile(r'^[^aeiouAEIOU]+') if re.findall(r'[^aeiouAEIOU]y[^aeiouAEIOU]', w): pattern = re.compile(r'^[^aeiouAEIOUy]+') beginning = re.findall(pattern, word) w = pattern.sub('', w) w += str(beg...
[ "For the regular expression [^aeiouAEIOU]y[^aeiouAEIOU] we can break it down into:\n\n[^aeiouAEIOU] - not a vowel\ny - the letter 'y'\n[^aeiouAEIOU] - not a vowel\n\nSpecifically, [aeiou] would be a set of all lowercase vowels, so that matches on one character of \"aeiou\". The caret ^ means not, so [^aeiou] would ...
[ 0 ]
[]
[]
[ "expression", "nlp", "python", "regular_language" ]
stackoverflow_0074178604_expression_nlp_python_regular_language.txt
Q: Apply boolean mask with datetime to extract specific month with a Pandas dataframe I have a dataframe with a column ["DATE"]. I converted the column as a datetime object with : df["DATE"] = pd.to_datetime(df["DATE"]) Now I want to extract only june month with a boolean mask, but I have an error : df["DATE"].loc[...
Apply boolean mask with datetime to extract specific month with a Pandas dataframe
I have a dataframe with a column ["DATE"]. I converted the column as a datetime object with : df["DATE"] = pd.to_datetime(df["DATE"]) Now I want to extract only june month with a boolean mask, but I have an error : df["DATE"].loc[ df["DATE"] == (datetime.strftime(df["DATE"], "%m") == "06") ] The error : descriptor '...
[ "Use Series.dt.month:\ndf[\"DATE\"] = pd.to_datetime(df[\"DATE\"])\ndf[df[\"DATE\"].dt.month == 6]\n\nYour solution working with Series.dt.strftime:\ndf[\"DATE\"] = pd.to_datetime(df[\"DATE\"])\ndf[df[\"DATE\"].dt.strftime('%m') == '06']\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074178594_dataframe_datetime_pandas_python.txt
Q: dual axis chart with two secondary y axis I want to create a dual axis chart showing monthly user trips with the two secondary y axis showing average duration per month for each user type. ds = {"duration":['1.02', '1.03', '1.08', '1.07', '2.02', '1,01'], "start_time": ['2019-01-01 00:07:10.576', '2019-01-3...
dual axis chart with two secondary y axis
I want to create a dual axis chart showing monthly user trips with the two secondary y axis showing average duration per month for each user type. ds = {"duration":['1.02', '1.03', '1.08', '1.07', '2.02', '1,01'], "start_time": ['2019-01-01 00:07:10.576', '2019-01-31 23:48:50.0920', '2019-01-01 00:11:03.441', '2...
[ "It makes more sense to have more than one month in your dataset so I've changed that\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nds = {\"duration\": [1.02, 1.03, 1.08, 1.07, 2.02, 1.01],\n \"start_time\": ['2019-01-01 00:07:10.576', '2019-01-31 23:48:50.0920', '2019-01-01 00:1...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074176963_matplotlib_pandas_python.txt
Q: Multilevel concatenation grouped by a common index (pandas) I'm trying to combine multiple dataframes into one. I need the combined dataframe to have multilevel headers, as in the example below. I also need the dataframe to be grouped on multiple index columns. I've seen answers for some part of the above but not ...
Multilevel concatenation grouped by a common index (pandas)
I'm trying to combine multiple dataframes into one. I need the combined dataframe to have multilevel headers, as in the example below. I also need the dataframe to be grouped on multiple index columns. I've seen answers for some part of the above but not combined, and I can't figure it out. I'd really appreciate some h...
[ "Use concat with keys parameter:\ndf = pd.concat([A, B, C], axis=1, keys=('A','B','C'))\nprint (df)\n A B C \n 'a' 'b' 'a' 'b' 'b' 'c'\n'index1.1' 'index1.2' 'index1.3' 9 8 6 2 3 0\n'index2.1' 'index2.2' 'index2.3' 6 3 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074178628_dataframe_pandas_python.txt
Q: How to search graph database using Python? I want to search graphs inside Python without the burden of having to learn a new query language. I extensively use pydantic library and I wonder if the two can work together. A: You can use GQLAlchemy. It is an open source object graph mapper, and it is created using t...
How to search graph database using Python?
I want to search graphs inside Python without the burden of having to learn a new query language. I extensively use pydantic library and I wonder if the two can work together.
[ "You can use GQLAlchemy. It is an open source object graph mapper, and it is created using the pydantic library. You can check the implementation at GiHub repo.\nGQLAlchemy lets you connect with Memgraph more easily and helps you if you’re not familiar with Cypher query language.\nHere is an example of how to build...
[ 0 ]
[]
[]
[ "memgraphdb", "pydantic", "python" ]
stackoverflow_0074178653_memgraphdb_pydantic_python.txt
Q: trying to build insert rows function in python sqlite3 I'm trying to develop a function that will insert rows into a database in sqlite3 for me. import pandas as pd import sqlite3 as sql import os sea_level_df = pd.read_csv(r"C:\Users\slaye\OneDrive\Desktop\SeaLevel.csv", skiprows=3) display(sea_level_df) conn = s...
trying to build insert rows function in python sqlite3
I'm trying to develop a function that will insert rows into a database in sqlite3 for me. import pandas as pd import sqlite3 as sql import os sea_level_df = pd.read_csv(r"C:\Users\slaye\OneDrive\Desktop\SeaLevel.csv", skiprows=3) display(sea_level_df) conn = sql.connect(r"C:\Users\slaye\OneDrive\Desktop\sqlite\db\z.db"...
[ "\nYou don't need a class (and as it is, you're missing a self parameter, so calling that method on an instance of the class wouldn't work).\nYou can (and should) reuse the conn you have in the outer scope (or just pass it in to the function).\n\nOn that note, sqlite3.connect('z') would create a database file calle...
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074178664_python_sqlite.txt
Q: How to get all parameters related to a Databricks job run into python? I am trying to get all parameters related to a Databricks job and import them into python. These parameters should include the date, start time, duration, Status of the job(successful or failed) and all other parameters related to it. I want to...
How to get all parameters related to a Databricks job run into python?
I am trying to get all parameters related to a Databricks job and import them into python. These parameters should include the date, start time, duration, Status of the job(successful or failed) and all other parameters related to it. I want to use these parameters to generate a daily report using python and the report...
[ "You can use Databricks Jobs REST API for that - you can list all jobs, and for each jobs get all runs. The main problem is that you will scrape that API again & again.\nAnother possibility will be to get information about executed logs from the diagnostic logs on Azure or audit log on AWS - from it you can get ext...
[ 1, 0 ]
[ "You can use Databricks Jobs REST API based Python code here\n" ]
[ -1 ]
[ "azure_databricks", "databricks", "python" ]
stackoverflow_0069660588_azure_databricks_databricks_python.txt
Q: why return value is -1 in this sorted list [2, 3, 12, 100, 200] target value is 100? I practice some selection sort and given a sorted list found a number with the binary search but is not working. Why output comes index -1. def selectionsort(lst, target): first = 0 last = len(lst) - 1 for step...
why return value is -1 in this sorted list [2, 3, 12, 100, 200] target value is 100?
I practice some selection sort and given a sorted list found a number with the binary search but is not working. Why output comes index -1. def selectionsort(lst, target): first = 0 last = len(lst) - 1 for step in range(len(lst)): min_idx = step for i in range(step + 1, len(lst))...
[ "Your code was missing some return and variable assignments. Also binary search should be out of the loop. Also, return -1 shouldn't be there. Here is the fixed code.\ndef selectionsort(lst, target):\n first = 0\n last = len(lst) - 1\n for step in range(len(lst)-1):\n for i in range(step + 1, len(ls...
[ 0 ]
[]
[]
[ "algorithm", "binary_search", "python", "selection_sort" ]
stackoverflow_0074161623_algorithm_binary_search_python_selection_sort.txt
Q: Feature engineering, key error in python? I am currently creating some additional features for my ML project. I created one feature (f1), insert it as a new column and want to use it now to calculate another feature, but I get a KeyError. df['f1'] = df['column1'] - df['column2'] -->works fine f1 has dtype: timede...
Feature engineering, key error in python?
I am currently creating some additional features for my ML project. I created one feature (f1), insert it as a new column and want to use it now to calculate another feature, but I get a KeyError. df['f1'] = df['column1'] - df['column2'] -->works fine f1 has dtype: timedelta64, e.g. '0 days', '43 days'. Then I want to...
[ "Like the order you have written should works, if it gives error that f1 keys does not exist, maybe you are runing these lines in a notebook, and you are executing the second line before f1 created (like first line)\n" ]
[ 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074178534_dataframe_jupyter_notebook_pandas_python.txt