eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Hello SO & Django community, My problem is related to Django 4, as the feature to use passfile to connect to Postgres has appeared in this version. Though I have went through the similar error message related questions about previous versions, I had no success in solving my problem. What I am trying to do I want to connect Postgres database DB_MyProject to a django MyProject. In Django 4, you may use a passfile instead of providing all user/password information in the settings.py. The documentation about this new feature is here. The concept of password file in Postgres is explained here, you may also read about connection service here. Having followed these docs to my best understanding, I have done the following:  Created the following DATABASES entry in settings.py of the Django project, as advised here:   'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'db_service', 'passfile': '.pgpass', }, } }   In the pg configuration directory (pg_config --sysconfdir), created file pg_service.conf with following information, as in pg docs and django docs:  [db_service] host=localhost port=5432 dbname=DB_MyProject user=my_postgres_user   Created a .pgpass file, as in pg docs:  localhost:5432:DB_MyProject:my_postgres_user:my_passwd  Now, this .pgpass file exists in several locations, as a result of the quest to make this work:  in pg configuration directory (pg_config --sysconfdir) in my regular user home directory ~/ in django MyProject root directory  all of these files are exact copies with the same permission level: -rw------- 1 my_regular_user my_group 52 Mar 2 18:47 .pgpass   I also created a DB in PGAdmin with the specified name, and made sure user has permission with the specified password.  Now I assumed it should be working OK. But instead, when I try to makemigrations or migrate or runserver, I get this:    django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied  What have I tried already  verified compatibility: Django v4.0.3, PostgreSQL v14.0, psycopg2 v2.9.3 created an environment variable PGPASSFILE with a path to ~./.pgpass changed ownership of ~/.pgpass from my_regular_user to my_postgres_user for testing, was given the same result installed direnv, created .envrc file in the project root directory, containing:  export PGPASSFILE=~/.pgpass  Thank you in advance for your help. I would also be happy to be pointed out any misconceptions in my thinking, as I am a newbie developer.

Answer:  Created the following DATABASES entry in settings.py of the Django project:   'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'db_service', 'passfile': '.pgpass', }, } }   In user home directory, created file ~/.pg_service.conf with following information:  [db_service] host=localhost port=5432 dbname=DB_MyProject user=my_postgres_user   Created a .pgpass file in django MyProject root directory and change the permissions of the file chmod 0600 MyProject/.pgpass:  localhost:5432:DB_MyProject:my_postgres_user:my_passwd
Question: I'm trying to annotate a few figures I created in python. So, I'm generating an image containing the specified text (using PIL ImageDraw) and concatenating it with the image. Now, I want to include a math notation into the text. Is there a way to write text in latex math when creating the image of text? This answer suggests a work-around by using unicode text, but I would prefer writing the text in latex directly. MWE: from PIL import ImageFont, Image, ImageDraw from matplotlib import pyplot def get_annotation(image_shape: tuple, title: str, font_size: int = 50): frame_height, frame_width = image_shape[:2] times_font = ImageFont.truetype('times-new-roman.ttf', font_size) text_image = Image.new('RGB', (frame_width, frame_height), (255, 255, 255)) drawer = ImageDraw.Draw(text_image) w, h = drawer.textsize(title, font=times_font) drawer.text(((frame_width - w) / 2, (frame_height - h) / 2), text=title, fill=(0, 0, 0), font=times_font, align='center') annotation = numpy.array(text_image) return annotation if __name__ == '__main__': anno = get_annotation((100, 300), 'frame $f_n$') pyplot.imshow(anno) pyplot.show()  I tried passing frame $f_n$ to title parameter, but dollars got printed in the text image. PS: times-new-roman.ttf can be obtained here

Answer: I found an alternative with sympy here import sympy sympy.preview(r'frame $f_n$', dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600"], viewer='file', filename='test.png', euler=False)
Question: *My Training Model* def train(model,criterion,optimizer,iters): epoch = iters train_loss = [] validaion_loss = [] train_acc = [] validation_acc = [] states = ['Train','Valid'] for epoch in range(epochs): print("epoch : {}/{}".format(epoch+1,epochs)) for phase in states: if phase == 'Train': model.train() *training the data if phase is train* dataload = train_data_loader else: model.eval() dataload = valid_data_loader run_loss,run_acc = 0,0 *creating variables to calculate loss and acc* for data in dataload: inputs,labels = data inputs = inputs.to(device) labels = labels.to(device) labels = labels.byte() optimizer.zero_grad() #Using the optimizer with torch.set_grad_enabled(phase == 'Train'): outputs = model(inputs) loss = criterion(outputs,labels.unsqueeze(1).float()) predict = outputs>=0.5 if phase == 'Train': loss.backward() #backward propagation optimizer.step() acc = torch.sum(predict == labels.unsqueeze(1)) run_loss+=loss.item() run_acc+=acc.item()/len(labels) if phase == 'Train': #calulating train loss and accucracy epoch_loss = run_loss/len(train_data_loader) train_loss.append(epoch_loss) epoch_acc = run_acc/len(train_data_loader) train_acc.append(epoch_acc) else: #training validation loss and accuracy epoch_loss = run_loss/len(valid_data_loader) validaion_loss.append(epoch_loss) epoch_acc = run_acc/len(valid_data_loader) validation_acc.append(epoch_acc) print("{}, loss :{},accuracy:{}".format(phase,epoch_loss,epoch_acc)) history = {'Train_loss':train_loss,'Train_accuracy':train_acc, 'Validation_loss':validaion_loss,'Validation_Accuracy':validation_acc} return model,history[enter image description here][1]  I was experiencing the error as 0D or 1D target tensor expected, multi-target not supported could you please help in rectifying the code which is described above. Referred the previous related articles but unable to get the desired result. What are the code snippets I had to change so that my model will run successfully. Any suggestions are mostly welcome. Thanks in Advance.

Answer: Your problem is that labels have the correct shape to calculate the loss. When you add .unsqueeze(1) to labels you made your labels with this shape [32,1] which is not consistent to the requirment to calcualte the loss. To fix the problem, you only need to remove .unsqueeze(1) for labels. If you read the documentation of CrossEntropLoss, the arguments:  Input should be in (N,C) shape which is outputs in your case and [32,3]. Target should be in N shape which is labels in your case and should be [32]. Therefore, the loss function expects labels to be in 1D target not multi-target.
Question: In Python, Python has Union type, which is convenient when a method can accept multi types: from typing import Union def test(x: Union[str,int,float,]): print(x) if __name__ == '__main__': test(1) test('str') test(3.1415926)  Raku probably doesn't have Union type as Python, but a where clause can achieve a similar effect: sub test(\x where * ~~ Int | Str | Rat) { say(x) } sub MAIN() { test(1); test('str'); test(3.1415926); }  I wander if Raku have a possibility to provide the Union type as Python? # vvvvvvvvvvvvvvvvvvvv - the Union type doesn't exist in Raku now. sub test(Union[Int, Str, Rat] \x) { say(x) } 

Answer: My answer (which is very similar to your first solution ;) would be: subset Union where Int | Rat | Str; sub test(Union \x) { say(x) } sub MAIN() { test(1); test('str'); test(pi); } Constraint type check failed in binding to parameter 'x'; expected Union but got Num (3.141592653589793e0)  (or you can put a where clause in the call signature, as you have it) In contrast to Python:  this is native in raku and does not rely on a package like "typing" to be imported Python Union / SumTypes are used for static hinting, which is good for eg. IDEs but these types are unenforced in Python (per @freshpaste comment and this SO), in raku they are checked and will fail at runtime  So - the raku syntax is there to do what you ask ... sure, it's a different language so it does it in a different way. Personally I think that a typed language should fail if type checks are breached. It seems to me that type hinting that is not always enforced is a false comfort blanket. On a wider point, raku also offers built in Allomorph types for IntStr, RatStr, NumStr and ComplexStr - so you can work in a mixed mode using both string and math functions
Question: Is it possible to change the Input Keyboard Layouts by programmatically in Pyqt5? My first and second text box accepts Tamil letters. IN Tamil So many keyboard Layouts available. By default in Windows 10, Tamil Phonetic, Tamil99 and Tamil Traditional Keyboards are available. Now I want to select Keybaord layouts programmatically... For example. In My First textbox, I need to assign a "Tamil99" keyboard layout and in the second textbox, I need to assign a "Tamil Phonetic" keyboard layout. How to assign it, programmatically? import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class Diff_Language(QWidget): def __init__(self): super().__init__() self.setWindowTitle("InPut Different languges in Different Textbox") self.lbl1 = QLabel("Input Language - Tamil99 Keyboard") self.lbl2 = QLabel("Input Language - Tamil phonetic keyboard") self.tbox1 = QLineEdit() self.tbox1.setFont(QFont('senthamil', 10, QFont.Bold)) self.tbox2 = QLineEdit() self.tbox2.setFont(QFont('senthamil', 30, QFont.Bold)) self.vbox = QVBoxLayout() self.vbox.addWidget(self.lbl1) self.vbox.addWidget(self.tbox1) self.vbox.addWidget(self.lbl2) self.vbox.addWidget(self.tbox2) self.setLayout(self.vbox) def main(): app = QApplication(sys.argv) mainscreen = Diff_Language() app.setStyle("Fusion") mainscreen.show() sys.exit(app.exec_()) if __name__ == '__main__': main() 

Answer: So Qt doesn't offer this, but you can ask your OS to do it for you. Assuming you're just looking at Windows, you can change the current keyboard layout in python using pywin32, which lets you easily access the Windows API from your script. Once installed into your Python environment you can import win32api and then use a call like win32api.LoadKeyboardLayout('00000809',1) to set the layout (the values I've put here set it to UK English). The first parameter is a string representing the keyboard layout to use, and the second is a flag. See documentation. I found this list of KLIDs (Keyboard Layout IDs), which shows two for Tamil keyboards. "00000449" is Tamil, "00020449" is Tamil 99. The 449 at the end means Tamil, and the two digits before set which subtype of Tamil keyboard to use (e.g. 20 for Tamil 99) - I can't find one for Tamil phonetic, but maybe you'll be able to find it. You can set up your program to call these functions whenever you want it to switch keyboard (for example, when your user activates a specific text input box). Also, if you want to check the current keyboard layout you can use win32api.GetKeyboardLayout(0) (doc). Maybe you can use this to figure out what the IDs are for each of the Tamil keyboards you want to use. Mind that it returns an int for the locale id rather than a string. Other useful keyboard related functions are win32api.GetKeyboardLayoutList() (to find all the locales installed on the current machine), win32api.GetKeyboardLayoutName() and win32api.GetKeyboardState - documentation for all these can be found here.
Question: I have a python script that previously worked but that now throws the error:ImportError: DLL load failed while importing _gdal: The specified module could not be found. I am trying to upload a shapefile using fiona and originally the message read: ImportError: DLL load failed while importing _fiona: The specified module could not be found. I am using anaconda navigator as my IDE on windows 11. I am aware that this is a question that has been asked before and I have read the answers to those questions. The solutions, however, hove not worked either due to my circumstance or my misinterpretation and action in following through with it. So my question is either how do I fix this, or, if it is not that simple, to better understand the problem. I have looked inside the DLLs folder within the environment folder that I am using and there is nothing in there with name fiona, gdal or geopandas. My attempts so far: 1. uninstall and re-install fiona gdal and geopandas (as I believe they are dependent). 2. update all libraries and anaconda to latest verions. 3. download Visual C++ Redistributable for Visual Studio 2015. Ran into issue during download as it was already installed on my computer, likely because it is a windows computer. Is it possible that this would help if i moved it to a different path/folder? 4. Uninstall and re-install anaconda navigator on cumputer. Re-create virtual environemt and import necessary libraries. result: error in line: import geopandas as gpd: ImportError: DLL load failed while importing _datadir: The specified module could not be found. If there is a fix that I have not mentioned or if you suspect that I attempted one of the above fixed incorrectly because of my limited understanding of how python libraries are stored please make a suggestion! Thank you

Answer: I was struggling badly with the same problem for the last couple of days. Using conda, I've tried everything I found on the internet such as: conda update gdal conda update -n base -c defaults conda  Creating new environments (over and over again). Despite it's not recommended I even tried it with  pip install... but no results. At the end what worked for me was to create a new environment with Python version 3.6 conda create -n env python=3.6 gdal spyder  Let me know if it worked.
Question: The documentation of coverage.py says that Many people choose to use the pytest-cov plugin, but for most purposes, it is unnecessary. So I would like to know what is the difference between these two? And which one is the most efficient ? Thank you in advance

Answer: pytest-cov uses coverage.py, so there's no different in efficiency, or basic behavior. pytest-cov auto-configures multiprocessing settings, and ferries data around if you use pytest-xdist.
Question: I'm working on a project that specifies its dependencies using Poetry and a pyproject.toml file to manage dependencies. The documentation for one of the libraries I need suggests pip-installing with an "extra" option to one of the dependencies, like this: pip install google-cloud-bigquery[opentelemetry]  How should I reflect this requirement in the pyproject.toml file? Currently, there are a few lines like this: [tool.poetry.dependencies] python = "3.7.10" apache-beam = "2.31.0" dynaconf = "3.1.4" google-cloud-bigquery = "2.20.0"  Changing the last line to google-cloud-bigquery[opentelemetry] = ">=2.20.0"  yields Invalid TOML file /home/jupyter/vertex-monitoring/pyproject.toml: Unexpected character: 'o' at line 17 col 22  Other variants that don't seem to be parsed properly: google-cloud-bigquery["opentelemetry"] = "2.20.0"  There are other StackOverflow questions which look related, as well as several different PEP docs, but my searches are complicated because I'm not sure whether these are "options" or "extras" or something else.

Answer: You can add it by poetry add "google-cloud-bigquery[opentelemetry]". This will result in: [tool.poetry.dependencies] ... google-cloud-bigquery = {extras = ["opentelemetry"], version = "^2.34.2"}
Question: I've built an image for Lambda using public.ecr.aws/lambda/python:3.8 but always get this error. Tried changing up the function and file names, but not getting any more details for debugging. Also I've run the function locally and the entrypoint/cmd works. START RequestId: cb4ba88c-c347-4e7d-b1ca-031a2e02fde4 Version: $LATEST IMAGE Launch error: fork/exec /lambda-entrypoint.sh: exec format error Entrypoint: [/lambda-entrypoint.sh] Cmd: [index.lambda_handler] WorkingDir: [/var/task]IMAGE Launch error: fork/exec /lambda-entrypoint.sh: exec format error Entrypoint: [/lambda-entrypoint.sh] Cmd: [index.lambda_handler] WorkingDir: [/var/task]END RequestId: cb4ba88c-c347-4e7d-b1ca-031a2e02fde4 REPORT RequestId: cb4ba88c-c347-4e7d-b1ca-031a2e02fde4 Duration: 12.86 ms Billed Duration: 13 ms Memory Size: 128 MB Max Memory Used: 3 MB RequestId: cb4ba88c-c347-4e7d-b1ca-031a2e02fde4 Error: fork/exec /lambda-entrypoint.sh: exec format error Runtime.InvalidEntrypoint 

Answer: Turned out to be an architecture compatibility issue - Needed to make sure the arch matched between the lambda function, and the docker image. Locally I was building on an M1 with arm64 but the function is configured by default to use amd64 I changed my build command to docker buildx build --platform linux/amd64 -t <image_name>:<image_tag> Although I could have also updated the arch type for the lambda function to use arm64
Question: So right now I hardcode to url, which is a bit annoying if you move endpoints. This is my current setup for my navbar items. # in base.html {% include 'components/navbar/nav-item.html' with title='Event Manager' url='/eventmanager/' %}  # in components/navbar/nav-item.html <li> <a href="{{ url }}">{{ title }}</a> </li>  See how I use the url right now? What I now want is this: {% include 'components/navbar/link.html' with title='Event Manager' url={% url 'event_manager:index' %} %}  But apparently, this is invalid syntax. How do I do it? If it is not possible, how do I create an app that somehow creates a view where I can pass all the URLs with context variable? In theory, this sounds easy but I'd have to somehow insert that view in every other view.

Answer: You can pass it as a variable not django's url tag, use like this: {% url 'event_manager:index' as myurl %} {% include 'components/navbar/link.html' with myurl %}  Now you can pass it to include tag.
Question: Using a jupyter notebook in VSCode, I'm trying to run the following code from this documentation: import numpy as np from IPython.display import Audio framerate = 44100 t = np.linspace(0,5,framerate*5) data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t) Audio(data, rate=framerate)  However, I only get this  If I press play button, then nothing happens...

Answer: As of today, it seems VSCode Jupyter extension does not support audio. You can track the issue here on their Github. One solution can be merging this pull request and rebuilding VSCode, which is not suggested. The preferred alternate solution is using jupyter lab instead of VSCode for such use cases.
Question: I want to display all the Routes in an app built with Django, something like what Laravel does with the command: php artisan route:list  Is there a way to get all the Routes?

Answer: django-extensions has command show_urls, sou after instalation you can do: python manage.py show_urls
Question: I'm trying to compute average values of shifted diagonals of a square array. Given input matrix like (in reality much larger than 3x3): [[a, b, c], [d, e, f], [g, h, i]]  correct answer would be [g, (d+h)/2, (a+e+i)/3, (b+f)/2, c]  A code to compute such average could be: import numpy as np def offset_diag_mean(mat): n = len(mat) return np.array([np.mean(np.diag(mat,k)) for k in range(-n+1,n)])  I assume one can do without a list comprehension (speed is quite important for me). Any clever solutions I'm missing?

Answer: On efficient solution is to accumulate lines of the input 2D array directly in the output array at a specific position and then perform the division. The idea is to zero-initialize an output array, then add [a, b, c] to output[2:5], then add [d, e, f] to output[1:4] and then add [g, h, i] to output[0:3]. Finally, we can divide result by [1, 2, 3, 2, 1]. Here is an implementation: # Use the decorator @nb.njit here to use Numba def compute(mat): n = mat.shape[0] output = np.zeros(n*2-1, dtype=np.float64) for i in range(n-1, -1, -1): output[i:i+n] += mat[n-1-i] output[0:n] /= np.arange(1, n+1, 1, dtype=np.float64) output[n:] /= np.arange(n-1, 0, -1, dtype=np.float64) return output  Here is the resulting performance on my machine on a 1000x1000 array: Initial code: 15.31 ms Kevin's code: 3.26 ms ( x4.7) This code: 1.42 ms (x10.8) This code + Numba: 0.66 ms (x23.2)  Thus, this implementation is 10.8 times faster than the initial implementation and 2.3 times faster than the fastest alternative version. Note that using Numba results in an even faster code with almost not change to the code: this Numba version is 23.2 times faster than the initial implementation.
Question: python points to my system's default python interpreter, instead of my pyenv python interpreter. I created the python virtual environment and activated it as follows: pyenv virtualenv 3.8.12 test3 pyenv activate test3  Then, running python gives me a python 3.7 interpreter (which is my system's default python interpreter), instead of 3.8.12. Why?  Full command outputs: root@server:/home/code-base/f# pyenv virtualenv 3.8.12 test3 Looking in links: /tmp/tmp1yp95sav Requirement already satisfied: setuptools in /root/.pyenv/versions/3.8.12/envs/test3/lib/python3.8/site-packages (56.0.0) Requirement already satisfied: pip in /root/.pyenv/versions/3.8.12/envs/test3/lib/python3.8/site-packages (21.1.1) root@server:/home/code-base/f# pyenv activate test3 pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior. (test3) root@server:/home/code-base/f# python Python 3.7.11 (default, Jul 27 2021, 14:32:16) [GCC 7.5.0] :: Anaconda, Inc. on linux  Additionally:  pyenv which python returns /root/.pyenv/versions/test3/bin/python command -v python returns /opt/conda/bin/python $PATH inside my virtualenv: /root/.pyenv/plugins/pyenv-virtualenv/shims:/root/.pyenv/bin:/opt/conda/bin:/app/python/bin:/opt/conda/bin:/usr/local/mpi/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/bin ls -la /root/.pyenv/plugins/pyenv-virtualenv/shims contains two folders: activate and deactivate. 

Answer: Given the new informations you gave us it is most likely that your a missing a eval "$(pyenv init --path)" in your ~/.profile (or in your Dockerfile as you are using K8s) as /root/.pyenv/shim is not part of $PATH. Old answer: Two possible solutions here: Either you did not select your 3.8.12 binary as a system default via: $ pyenv global 3.8.12 $ python -V Python 3.8.12 $ pyenv versions system 2.7.15 * 3.8.12 (set by /home/realpython/.pyenv/version)  or /opt/conda/bin/ has a higher priority in your $PATH then your pyenv installation.