eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm trying to upload a file to a FastAPI server using requests. I've boiled the problem down to its simplest components. The client using requests: import requests files = {'file': ('foo.txt', open('./foo.txt', 'rb'))} response = requests.post('http://127.0.0.1:8000/file', files=files) print(response) print(response.json())  The server using fastapi: from fastapi import FastAPI, File, UploadFile import uvicorn app = FastAPI() @app.post('/file') def _file_upload(my_file: UploadFile = File(...)): print(my_file) if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=8000, log_level="debug")  Packages installed:  fastapi python-multipart uvicorn requests  Client Output: <Response [422]> {'detail': [{'loc': ['query', 'my_file'], 'msg': 'field required', 'type': 'value_error.missing'}]} Server Output: INFO: 127.0.0.1:37520 - "POST /file HTTP/1.1" 422 Unprocessable Entity What am I missing here?

Answer: FastAPI expecting the file in the my_file field and you are sending it to the file field. it should be as import requests url = "http://127.0.0.1:8000/file" files = {'my_file': open('README.md', 'rb')} res = requests.post(url, files=files) Also, you don't need a tuple to manage the upload file (we're dealing with a simple upload, right?)
Question: I have a string variable input = "A very very long string from user input", how can I loop through the string and add a line break \n after 20 characters then save the formatted string in a variable new_input? So far am only able to get the first 20 characters as such input[0:20] but how do you do this through the entire string and add line breaks at that point?

Answer: You probably want to do something like this inp = "A very very long string from user input" new_input = "" for i, letter in enumerate(inp): if i % 20 == 0: new_input += '\n' new_input += letter # this is just because at the beginning too a `\n` character gets added new_input = new_input[1:]
Question: I often debug my python code by plotting NumPy arrays in the vscode debugger. Often I spend more than 3s looking at a plot. When I do vscode prints the extremely long warning below. It's very annoying because I then have to scroll up a lot all the time to see previous debugging outputs. Where is this PYDEVD_WARN_EVALUATION_TIMEOUT variable? How do I turn this off? I included the warning below for completeness, thanks a lot for your help!  Evaluating: plt.show() did not finish after 3.00s seconds. This may mean a number of things:  This evaluation is really slow and this is expected. In this case it's possible to silence this error by raising the timeout, setting the PYDEVD_WARN_EVALUATION_TIMEOUT environment variable to a bigger value.  The evaluation may need other threads running while it's running: In this case, it's possible to set the PYDEVD_UNBLOCK_THREADS_TIMEOUT environment variable so that if after a given timeout an evaluation doesn't finish, other threads are unblocked or you can manually resume all threads. Alternatively, it's also possible to skip breaking on a particular thread by setting a pydev_do_not_trace = True attribute in the related threading.Thread instance (if some thread should always be running and no breakpoints are expected to be hit in it).  The evaluation is deadlocked: In this case you may set the PYDEVD_THREAD_DUMP_ON_WARN_EVALUATION_TIMEOUT environment variable to true so that a thread dump is shown along with this message and optionally, set the PYDEVD_INTERRUPT_THREAD_TIMEOUT to some value so that the debugger tries to interrupt the evaluation (if possible) when this happens.   

Answer: If found a way to adapt the launch.json which takes care of this problem. { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "debugpy", "request": "launch", "program": "${file}", "env": {"PYTHONPATH": "${workspaceRoot}", "PYDEVD_WARN_EVALUATION_TIMEOUT": "500"}, "cwd": "${workspaceFolder}", "console": "integratedTerminal" } ] }
Question: I want to install the hdbcli package (SAP HANA connector). When I search with pip the package is being found, but when I want to install it, pip can't find the package. Specifiying the current package also yields no results. pip install hdbcli==2.6.61  How do I solve this? > pip search hbdcli hdbcli (2.6.61) - SAP HANA Python Client > pip install hdbcli ERROR: Could not find a version that satisfies the requirement hdbcli (from versions: none) ERROR: No matching distribution found for hdbcli 

Answer: This usually means pip could not find any distribution of that project that would be compatible with your python environment:  Python implementation (CPython, or PyPy, etc.) Python interpreter major and minor version (3.10, or 3.11, etc.) operating system (Windows, or Linux, etc.) CPU bitness (64 bits or 32 bits) version of glibc and other libraries (that's why pip on Alpine Linux might ignore Linux distributions that require glibc)  This project does not seem to have published any source distribution (sdist) ever. So it has to be a compatible wheel. Are you by chance on Python 3.9? As far as I can tell there are no wheel distributions for Python 3.9. Use path/to/pythonX.Y -m pip debug --verbose to get a list of "Compatible tags". Then compare this list with the list of available wheel distributions for that project.
Question: Can I specify a pandas DataFrame index name in the constructor? Said otherwise, I would like to do the following: df = pd.DataFrame({"a":[1,2],"b":[3,4]}) df.rename_axis(index='myindex', inplace=True)  with a single line of code (by calling only the constructor)

Answer: You can pass an index to the DataFrame constructor with the given name that you want. import pandas as pd df = pd.DataFrame({"a":[1,2],"b":[3,4]}, index=pd.Index([], name='myIndex')) df   a b myIndex 0 1 3 1 2 4
Question: I got the next url related to an online store https://www.tiendasjumbo.co/buscar?q=mani and I can't extract the product label an another fields: from selenium import webdriver import time from random import randint driver = webdriver.Firefox(executable_path= "C:\Program Files (x86)\geckodriver.exe") driver.implicitly_wait(10) time.sleep(4) url = "https://www.tiendasjumbo.co/buscar?q=mani" driver.maximize_window() driver.get(url) driver.find_element_by_xpath('//h1[@class="impulse-title"]')  What am I doing wrong, I also tried to switch the iframes but there is no way to achieve my goal? any help is welcome.

Answer: The products within the website https://www.tiendasjumbo.co/buscar?q=mani are located within a #shadow-root (open).   Solution To extract the product label you have to use shadowRoot.querySelector() and you can use the following Locator Strategy:  Code Block: driver.get('https://www.tiendasjumbo.co/buscar?q=mani') item = driver.execute_script("return document.querySelector('impulse-search').shadowRoot.querySelector('div.group-name-brand h1.impulse-title span.formatted-text')") print(item.text)   Console Output: La especial mezcla de nueces, maní, almendras y marañones x 450 g     References You can find a couple of relevant discussions in:  Unable to locate the Sign In element within #shadow-root (open) using Selenium and Python How to locate the First name field within shadow-root (open) within the website https://www.virustotal.com using Selenium and Python   Microsoft Edge and Google Chrome version 96 Chrome v96 has changed the shadow root return values for Selenium. Some helpful links:  Java - full example on GitHub Shadow DOM in Selenium Python - full example on GitHub Shadow DOM and Selenium with Chromium 96 C# - full example on GitHub Shadow DOM in Ruby Selenium Ruby - full example on GitHub
Question: I am creating a cookiecutter template and would like to add a folder (and the files it contains) only if a variable has a given value. For example cookiecutter.json: { "project_slug":"project_folder" "i_want_this_folder":['y','n'] }  and my template structure looks like: template └── {{ cookiecutter.project_slug }} ├── config.ini ├── data │ └── data.csv ├── {% if cookiecutter.i_want_this_folder == 'y' %}my_folder{% endif %} └── some_files  However, when running cookiecutter template and choose 'n' I get an error Error: "~/project_folder" directory already exists  Is my syntax for the folder name correct?

Answer: I was facing the same issue having the option to add or no folders with different contents (all folders can exist at the same time). The structure of the project is the following: ├── {{cookiecutter.project_slug}} │ │ │ ├── folder_1_to_add_or_no │ │ ├── file1.py │ │ ├── file2.py │ │ └── file3.txt │ │ │ ├── folder_2_to_add_or_no │ │ ├── image.png │ │ ├── data.csv │ │ └── file.txt │ │ │ └── folder_3_to_add_or_no │ ├── file1.py │ └── some_dir │ ├── hooks │ └── post_gen_project.py │ └── cookiecutter.json  where the cookiecutter.json contains the following { "project_owner": "some-name", "project_slug": "some-project", "add_folder_one": ["yes", "no"], "add_folder_two": ["yes", "no"], "add_folder_three": ["yes", "no"], }  as each directory folder_X_to_add_or_no contains different files, the trick is to remove those folders that the answer is "no", you can do this through a hook. Inside the post_gen_project.py file # post_gen_project.py import os import shutil from pathlib import Path # Current path path = Path(os.getcwd()) # Source path parent_path = path.parent.absolute() def remove(filepath): if os.path.isfile(filepath): os.remove(filepath) elif os.path.isdir(filepath): shutil.rmtree(filepath) folders_to_add = [ 'folder_one', 'folder_two', 'folder_three' ] for folder in folders_to_add: # Check if user wants the folder cookiecutter_var = '{{cookiecutter.' + f'{folder}' + '}}' add_folder = cookiecutter_var == 'yes' # User does not want folder so remove it if not add_folder: folder_path = os.path.join( parent_path, '{{cookiecutter.project_slug}}', 'folder' ) remove(folder_path)  Now the folders the user choose not to add will be removed. Select add_folder_one: 1 - yes 2 - no Choose from 1, 2 [1]:  References This answer is based on briancapello answer on this github issue
Question: I am new to streamlit. I tried to set a default value for sidebar.selectbox. The code is below. I appreciate the help! Thank you in advance. st.sidebar.header('Settings') fichier = st.sidebar.selectbox('Dataset', ('djia', 'msci', 'nyse_n', 'nyse_o', 'sp500', 'tse')) window_ANTICOR = st.sidebar.selectbox('Window ANTICOR', ['<select>',3, 5, 10, 15, 20, 30]) if window_ANTICOR == '<select>': window_ANTICOR == 30 window_OLMAR = st.sidebar.selectbox('Window OLMAR', ['<select>',3, 5, 10, 15, 20, 30]) if window_OLMAR == '<select>': window_OLMAR == 5 eps_OLMAR = st.sidebar.selectbox('Eps OLMAR', ['<select>', 3, 5, 10, 15, 20, 30]) if eps_OLMAR == '<select>': eps_OLMAR == 10 eps_PAMR = st.sidebar.selectbox('Eps PAMR', ['<select>',0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]) if eps_PAMR == '<select>': eps_PAMR == 0.5 variant = st.sidebar.selectbox('Variant PAMR', (0, 1, 2)) if variant == '<select>': eps_PAMR == 0 

Answer: Use the index keyword of the selectbox widget. Pass the index of the value in the options list that you want to be the default choice. E.g. if you wanted to set the default choice of the selectbox labeled 'Window ANTICOR' to 30 (which you appear to be trying to do), you could simply do this: values = ['<select>',3, 5, 10, 15, 20, 30] default_ix = values.index(30) window_ANTICOR = st.sidebar.selectbox('Window ANTICOR', values, index=default_ix)  Source: https://docs.streamlit.io/library/api-reference/widgets/st.selectbox
Question: I encounter an issue when I use the Jupyter Notebook in VS code. The screen shows "Python 3.7.8 requires ipykernel to be installed". I followed the pop-up to install ipykernel. It still does not work. The screenshot is attached. It bothers me a lot. Could anyone help me with it? Tons of thanks. 

Answer: I had the same issue and spent the whole day trying to resolve it. What worked for me was installing the Jupyter dependencies for anaconda: > conda install jupyter I installed this in my base environment. After this VSCode worked without any errors.
Question: without using iSpyder DOS shell commands, how can an .ipynb (Jupyter Notebook) be opened directly into Spyder on Windows? Even the online Jupyter Notebook site prompts for a relative directory path where the file is stored.  Why isn't there something that just loads the Notebook how it's supposed to look without typing a bunch of directory commands, and why does Spyder's RUN button become greyed out when it loads the .ipynb file? I have no idea what the .ipynb file format is compared to regular .py files  Opening lines of the .ipynb when loaded in Spyder are: { "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": {  This does not look like python code whatsoever

Answer: You may check out https://github.com/spyder-ide/spyder-notebook Once you install this, you can open native .ipynb files in spyder From the website:  Spyder plugin to use Jupyter notebooks inside Spyder. Currently it supports basic functionality such as creating new notebooks, opening any notebook in your filesystem and saving notebooks at any location. You can also use Spyder's file switcher to easily switch between notebooks and open an IPython console connected to the kernel of a notebook to inspect its variables in the Variable Explorer.
Question: I am always using system('cls') in C language before using Dev-C++. Now I am studying Python and using Pycharm 2020.2.3. I tried to use os.system('cls'). Here is my program: import os print("clear screen") n = int(input("")) if n == 1: os.system('cls')  There is no error in my program but it is not clearing the recent output. This is the output of my program:  What seems to be the problem why it is not clearing the recent output?

Answer: PhCharm displays the output of your running module using the output console. In order for your terminal commands under os.system() to work, you need to emulate your terminal inside the output console.  Select 'Edit Configurations' from the 'Run' menu. Under the 'Execution' section, select 'Emulate terminal in output console'   JetBrains Sergey Karpov Adds:  Our Run window doesn't support some of the things that one can do in the terminal. One of them is clearing the output. When trying to clear the output in a 'non-terminal' output window, PyCharm even shows that the TERM environment variable is not set. Setting that variable manually may help in some cases, but other terminal-specific things are still missing, which is why we have an option to emulate the terminal in the Run window.
Question: I'd like to catch nicely the error when "No hostkey for host *** is found" and give an appropriate message to the end user. I tried this: import pysftp, paramiko try: with pysftp.Connection('1.2.3.4', username='root', password='') as sftp: sftp.listdir() except paramiko.ssh_exception.SSHException as e: print('SSH error, you need to add the public key of your remote in your local known_hosts file first.', e)  but unfortunately the output is not very nice: SSH error, you need to add the public key of your remote in your local known_hosts file first. No hostkey for host 1.2.3.4 found. Exception ignored in: <function Connection.__del__ at 0x00000000036B6D38> Traceback (most recent call last): File "C:\Python37\lib\site-packages\pysftp\__init__.py", line 1013, in __del__ self.close() File "C:\Python37\lib\site-packages\pysftp\__init__.py", line 784, in close if self._sftp_live: AttributeError: 'Connection' object has no attribute '_sftp_live'  How to nicely avoid these last lines / this "exception ignored" with a try: except:?

Answer: The analysis by @reverse_engineer is correct. However:  It seems that an additional attribute, self._transport, also is defined too late. The problem can be temporarily corrected until a permanent fix comes by subclassing the pysftp.Connection class as follows:  import pysftp import paramiko class My_Connection(pysftp.Connection): def __init__(self, *args, **kwargs): self._sftp_live = False self._transport = None super().__init__(*args, **kwargs) try: with My_Connection('1.2.3.4', username='root', password='') as sftp: l = sftp.listdir() print(l) except paramiko.ssh_exception.SSHException as e: print('SSH error, you need to add the public key of your remote in your local known_hosts file first.', e)  Update I could not duplicate this error on my desktop. However, I see in the source for pysftp in the code where it initializes its _cnopts attribute with self._cnopts = cnopts or CnOpts() where cnopts is a keyword parameter to the pysftp.Connection constructor and there is a possibilty of the CnOpts constructor throwing a HostKeysException exception if no host keys are found resulting in the _cnopts attribute not being set. Try the following updated code and let me know if it works: import pysftp import paramiko class My_Connection(pysftp.Connection): def __init__(self, *args, **kwargs): try: if kwargs.get('cnopts') is None: kwargs['cnopts'] = pysftp.CnOpts() except pysftp.HostKeysException as e: self._init_error = True raise paramiko.ssh_exception.SSHException(str(e)) else: self._init_error = False self._sftp_live = False self._transport = None super().__init__(*args, **kwargs) def __del__(self): if not self._init_error: self.close() try: with My_Connection('1.2.3.4', username='root', password='') as sftp: l = sftp.listdir() print(l) except paramiko.ssh_exception.SSHException as e: print('SSH error, you need to add the public key of your remote in your local known_hosts file first.', e)
Question: I am trying to build a basic machine learning algorithm, and to do so I am using the Anaconda interpreter for Python. However, even though Visual Studio Code appears to have recognized Conda as the interpreter, and I have the Anaconda 3 shell working as a separate application, I cannot get Conda to work in Visual Studio Code. Whenever I try to check for Conda, I get the following error: conda : The term 'conda' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + conda activate base + ~~~~~ + CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException  I have tried the fixes linked here: 'Conda' is not recognized as internal or external command However, they did not work for me. I tried setting Conda to my path, yet I still got the same error.

Answer: Try the following:  Run Anaconda/Miniconda Activate the environment there:  conda activate your-env   Start Visual Studio Code from the Anaconda/Miniconda terminal:  code   Then Visual Studio Code should recognize conda:
Question: I am using PyCaret and get an error. AttributeError: 'SimpleImputer' object has no attribute '_validate_data'  Trying to create a basic instance. # Create a basic PyCaret instance import pycaret from pycaret.regression import * mlb_pycaret = setup(data = pycaret_df, target = 'pts', train_size = 0.8, numeric_features = ['home', 'first_time_pitcher'], session_id = 123)  All my variables are numeric (I coerced two of them, which are boolean). My target variable is label and this is by default. I also installed PyCaret, imported its regression, and re-installed scikit learn, imported SimpleImputer as from sklearn.impute import SimpleImputer OBP_avg Numeric SLG_avg Numeric SB_avg Numeric RBI_avg Numeric R_avg Numeric home Numeric first_time_pitcher Numeric park_ratio_OBP Numeric park_ratio_SLG Numeric SO_avg_p Numeric pts_500_parkadj_p Numeric pts_500_parkadj Numeric SLG_avg_parkadj Numeric OPS_avg_parkadj Numeric SLG_avg_parkadj_p Numeric OPS_avg_parkadj_p Numeric pts_BxP Numeric SLG_BxP Numeric OPS_BxP Numeric whip_SO_BxP Numeric whip_SO_B Numeric whip_SO_B_parkadj Numeric order Numeric ops x pts_500 order15 Numeric ops x pts_500 parkadj Numeric ops23 x pts_500 Numeric ops x pts_500 orderadj Numeric whip_p Numeric whip_SO_p Numeric whip_SO_parkadj_p Numeric whip_parkadj_p Numeric pts Label  My traceback is the following: 

Answer: The problem here is with the imputation. The default per pycaret documentation is 'simple' but in this case, you need to make that imputation_type='iterative' for it to work.
Question: Whenever audio is playing in windows 10, whether it is from Spotify, Firefox, or a game. When you turn the volume, windows has a thing in the corner that says the song artist, title, and what app is playing like the photo below (sometimes it only says what app is playing sound if a game is playing the sound)  I want to somehow get that data with python. My end goal, is to mute an application if it is playing something I don't like, such as an advertisement.

Answer: I am getting the titles of the windows to get the song information. Usually, the application name is displayed in the title, but when it is playing a song, the song name is shown. Here is a function that returns a list of all the window titles. from __future__ import print_function import ctypes def get_titles(): EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW IsWindowVisible = ctypes.windll.user32.IsWindowVisible titles = [] def foreach_window(hwnd, lParam): if IsWindowVisible(hwnd): length = GetWindowTextLength(hwnd) buff = ctypes.create_unicode_buffer(length + 1) GetWindowText(hwnd, buff, length + 1) titles.append(buff.value) return True EnumWindows(EnumWindowsProc(foreach_window), 0) return titles