QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,278,725
1,034,153
can I use LoadTestShape to specify a custom parameter in my Locust.io tasks? (Python)
<p>I am finding Locust.io awesome for tweaking certain parameters that will trigger specific implementation behavior in my web application. I want to measure how performance changes based on different config parameters in my web application. Adopting <code>LoadTestShapes</code> and <code>ticks</code> to simulate K6-sty...
<python><load-testing><locust>
2023-01-29 22:05:58
1
1,081
Luca P.
75,278,688
836,026
I have nii.gz volume and I need to display it as one image
<p>I have nii.gz volume and I need to display it as one image. I could display one slice as shown below.</p> <pre><code>mri_file = '/tmp/out_img/case0001_gt.nii.gz' img = nib.load(mri_file) mg_data = img.get_fdata() mid_slice_x = img_data[ :, :,119] plt.imshow(mid_slice_x.T, cmap='gray', origin='lower') plt.xlabel('Fir...
<python><pytorch><medical-imaging>
2023-01-29 21:59:03
1
11,430
user836026
75,278,649
8,026,274
plotting a grouped bar chart with bins
<p>I have a dataframe similar to like this:</p> <pre><code>Create Date count1 count2 count3 count4 2018-01 12 21 12 123 2018-02 11 25 12 145 2018-08 12 26 12 145 2019-03 13 28 12 334 2019-06 15 22 12 345 2019-07 ...
<python><dataframe><plot>
2023-01-29 21:52:26
1
339
Mikasa
75,278,638
6,577,503
Finding basis of affine space in python?
<p>Suppose I am given an affine space as some conjunction of equalities say:</p> <pre><code>x + y + z = 2 &amp;&amp; x - 3z = 4 </code></pre> <p>which I represent in python as:</p> <pre><code>[ [1,1,1,2] , [1,0,-3,4] ] </code></pre> <p>I would like to find the basis of this affine set. Does python have any such library...
<python><numpy><scipy><computational-geometry>
2023-01-29 21:50:57
2
441
Anon
75,277,911
20,947,319
Django and AWS S3 returns This backend doesn't support absolute paths
<p>I am working on a Django project whereby when users register their profiles get automatically created using the signals.py. Everything works fine in the localhost, but now I want to migrate to the AWS S3 bucket before deploying my project to Heroku. After configuring my AWS settings in settings.py, I get the error <...
<python><django><amazon-web-services><amazon-s3><django-models>
2023-01-29 19:51:25
1
446
victor
75,277,797
11,825,717
How do I set padding on a convolutional decoder?
<p>I'm building a convolutional decoder that takes an input Tensor of size <code>1x96x4x4</code> and feeds it into three convolutional tranpose layers. How do I set <code>padding</code> and <code>output_padding</code> so that the output is of size <code>1x9x30x30</code>?</p> <pre><code>import torch # Input. x = torch....
<python><pytorch><conv-neural-network><autoencoder>
2023-01-29 19:35:39
0
2,343
Jeff Bezos
75,277,647
2,091,247
Transform table into smaller table (animation)
<p>I wrote a short animation in Manim library, that first highlight two rows and then transform the table into a smaller one only with these two rows. I'm using the following lib versions:</p> <ul> <li><p>python 3.10.7</p> </li> <li><p>manim 0.17.2</p> <pre><code> from manim import * # creeate map dictionary map = {...
<python><manim>
2023-01-29 19:12:30
0
10,731
Radim Bača
75,277,556
1,922,589
Can't load env variable path properly in crontab environment
<p>If I ran manually on my terminal, working fine.</p> <pre><code>/usr/bin/python3 /home/myproject/handler.py </code></pre> <p>My command in crontab -e is</p> <pre><code>* * * * * . /home/&lt;user&gt;/.bashrc; /usr/bin/python3 /home/myproject/handler.py &gt; /home/&lt;user&gt;/testfile.txt 2&gt;&amp;1 </code></pre> <p>...
<python><ubuntu><cron>
2023-01-29 18:57:14
0
24,027
Nurdin
75,277,260
18,758,062
Gunicorn logging gets AttributeError: 'NoneType' object has no attribute 'write'
<p>I'm trying to get gunicorn 20.1.0 with flask 2.2.2 to write log messages to file. When writing a log message, gunicorn is throwing the error:</p> <pre><code>Traceback (most recent call last): File &quot;/usr/lib/python3.10/logging/__init__.py&quot;, line 1103, in emit stream.write(msg + self.terminator) File...
<python><flask><logging><gunicorn><python-logging>
2023-01-29 18:12:54
0
1,623
gameveloster
75,277,258
7,713,770
api call method and viewset
<p>I try to create a api call:</p> <pre><code>class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() @action(methods=['get'], detail=False) def mainGroups(self,request): mainGroups = Category.objects.filter(category_id_...
<python><django><django-rest-framework>
2023-01-29 18:12:40
1
3,991
mightycode Newton
75,277,154
14,391,210
Is this bad programming? Dictionary key instead of if statement for calling class methods
<p>I'm making a game in python with a UI in the terminal where the user has to navigate by pressing keys.</p> <p>I have my Game() class being the following.</p> <pre><code>class Game(): def __init__(self, config='default', **kwargs): print('\n'*20) # self.game_s...
<python><class><dictionary><if-statement>
2023-01-29 18:00:34
2
621
Marc
75,277,011
19,600,130
how to call a function as a context in django
<pre><code>class User(AbstractUser): GENDER_STATUS = ( ('M', 'Male'), ('F', 'Female') ) address = models.TextField(null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) gender = models.CharField(max_l...
<python><django><django-models><django-views><django-templates>
2023-01-29 17:40:33
2
983
HesamHashemi
75,276,979
6,077,239
Polars message: eval_binary_same_type!(left_aexpr, +, right_aexpr) = None
<p>I have encountered a message as in the title when running some simple polars code. Example code and its outputs are provided below:</p> <pre><code>import datetime import polars as pl df = pl.DataFrame( { &quot;a&quot;: [datetime.date(2022, 12, 1), datetime.date(2022, 1, 1)], &quot;b&quot;: [date...
<python><python-polars>
2023-01-29 17:37:31
1
1,153
lebesgue
75,276,860
6,499,765
Cannot assign "OrderItem.product" must be a "Product" instance
<p>I am trying to create a &quot;create order&quot; endpoint, i keep getting</p> <pre><code>Cannot assign &quot;&lt;django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.&lt;locals&gt;.ManyRelatedManager object at 0x7f50dad00f70&gt;&quot;: &quot;OrderItem.product&quot; must be a &quot;Product&...
<python><django>
2023-01-29 17:20:46
0
431
blockhead
75,276,583
18,758,062
Serving over HTTPS with Gunicorn/Flask: ERR_CERT_AUTHORITY_INVALID
<p>Looking for a quick way to serve an API over HTTPS for testing purposes. The API app is created using <code>flask</code> and being served on port 443 using <code>gunicorn</code>.</p> <pre><code>gunicorn --certfile=server.crt --keyfile=server.key --bind 0.0.0.0:443 wsgi:app </code></pre> <p>When my React app (served ...
<python><flask><https><openssl><gunicorn>
2023-01-29 16:43:01
2
1,623
gameveloster
75,276,563
12,349,101
Tkinter - Scroll with touchpad / mouse gestures / two fingers scrolling in tkinter?
<p>I wanted to implement two finger scrolling in tkinter. Here is the result of my own attempt:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk class Scene: def __init__(self, canvas): self.canvas = canvas self.elements = [ { &quot;type&quot;: &q...
<python><tkinter><scroll><tk-toolkit><tkinter-canvas>
2023-01-29 16:40:29
1
553
secemp9
75,276,554
9,476,917
FastAPI: How to post dictionary with String and Bytes object to an endpoint?
<p>I want to post a <code>payload</code> dict to my FastAPI endpoint that holds metadata like a file name and a bytesObject.</p> <p>I accomplished to send the bytes object stand-alone using the <code>File()</code> Class of Fast API, but not in a dict structure.</p> <p>For my FastAPI Endpoint I tried two approches.</p> ...
<python><python-requests><fastapi>
2023-01-29 16:39:27
0
755
Maeaex1
75,276,523
470,081
Truly dynamic DateField values in Django
<p>Some of my app models define date ranges (e.g. of contracts), where the current instance has no fixed end date (i.e. it should always evaluate to today). Setting the <code>default</code> parameter on the <code>end</code> field –</p> <pre><code>class Contract(models.Model): building = models.ForeignKey(Building, ...
<python><django><postgresql><django-models>
2023-01-29 16:35:51
1
461
janeden
75,276,400
11,170,350
Input and output shape to GRU layer in PyTorch
<p>I am getting confused about the input shape to GRU layer. I have a batch of 128 images and I extracted 9 features from each images. So now my shape is <code>(1,128,9)</code>.</p> <p>This is the GRU layer</p> <pre><code>gru=torch.nn.GRU(input_size=128,hidden_size=8,batch_first=True) </code></pre> <p><strong>Question ...
<python><pytorch><gated-recurrent-unit>
2023-01-29 16:16:15
1
2,979
Talha Anwar
75,276,238
6,063,706
Sum of specific indices in pytorch?
<p>I have a neural network that outputs a tensor of size 12. After applying some calculations to this tensor, I need to reduce it to size 8 by adding the first four pairs and turning those into 1 dimension.</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] -&gt; [3, 7, 11, 15, 9, 10, 11, 12] </code></pre> <p>Is th...
<python><pytorch>
2023-01-29 15:52:11
1
1,035
Tob
75,276,204
9,879,869
How to write to Django FileField from a tempfile?
<p>I am processing an image within a Django app. I used rasterio to process the geospatial image. I want to save the output directly to a FileField in a Model. I used a tempfile to write the output from rasterio, and used the method <code>Model.FileField.save</code> to hopefully write it with a reference to my Model in...
<python><django><temporary-files><rasterio>
2023-01-29 15:45:40
1
1,572
Nikko
75,276,170
1,538,049
Conda cannot see Cuda version
<p>I am trying to install the newest Tensorflow GPU version to an Ubuntu environment. The Cuda drivers are correctly installed and working, which I can confirm with the following commands:</p> <pre><code>nvcc --version </code></pre> <p>With output:</p> <pre><code>nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005...
<python><tensorflow><cudnn>
2023-01-29 15:40:16
1
3,679
Ufuk Can Bicici
75,276,168
2,321,643
VS Code + Pylance does not find venv-installed modules while venv is activated
<p>I use VS Code Version: 1.74.3 on MacOS 13.2. <code>python -V</code> returns <code>Python 3.11.1</code>.</p> <p>I get the following error message: <code>Import &quot;django.shortcuts&quot; could not be resolved from source Pylance(reportMissingModuleScource)</code>.</p> <p><a href="https://i.sstatic.net/s0VFK.png" re...
<python><django><visual-studio-code><pylance>
2023-01-29 15:39:58
4
6,116
tjati
75,275,702
1,654,143
Bits per channel in Python
<p>In Photoshop I can find the number of bits per channel of an image with:</p> <pre><code>// BitsPerChannelType var bits = app.activeDocument.bitsPerChannel </code></pre> <p>What is the Pythonic equivalent to this and what modules are needed?</p> <p>bits = ??? # where the returned result is 8, 16 or 24</p>
<python><image><photoshop>
2023-01-29 14:33:52
1
7,007
Ghoul Fool
75,275,604
13,309,379
(Theoreticaly) Fast performing Routine for tensor manipulation going slower than not optimized version
<p>The goal of this implementation is to manipulate a 4 dimensional tensor in order to contact it with himself and then truncate the inflated indexes back to their original length.</p> <p>I have two routines that differ in the following point:</p> <ul> <li><strong>Routine One</strong> memory complexity scales with the ...
<python><numpy><performance><tensor>
2023-01-29 14:19:35
0
712
Indiano
75,275,563
1,497,139
AttributeError: module 'sqlalchemy' has no attribute '__all__'
<p>In my GitHub CI I get errors like the one below since today:</p> <pre class="lang-none prettyprint-override"><code>File &quot;/home/runner/.local/lib/python3.8/site-packages/fb4/login_bp.py&quot;, line 12, in &lt;module&gt; from fb4.sqldb import db File &quot;/home/runner/.local/lib/python3.8/site-packages/fb4...
<python><sqlalchemy>
2023-01-29 14:15:01
3
15,707
Wolfgang Fahl
75,275,547
1,307,905
Determine currently selected Outlook profile
<p>I'm dealing with several Office installations that have two profiles, primarily in order for the Exchange connection in one profile not to break normal (caldav) based calendars in the other profile.</p> <p>There are some actions that only should only be applied when a particular profile is active. I detect if Outloo...
<python><outlook><win32com><profile><office-automation>
2023-01-29 14:12:29
1
78,248
Anthon
75,275,534
6,762,755
Polars equivalent to SQL `COUNT(DISTINCT expr,[expr...])`, or other method of checking uniqueness
<p>When processing data, I often add a check after each step to validate that the data still has the unique key I think it does. For example, I might check that my data is still unique on <code>(a, b)</code>. To accomplish this, I would typically check that the number of distinct combinations of columns <code>a</code> ...
<python><dataframe><python-polars>
2023-01-29 14:09:22
3
28,795
IceCreamToucan
75,275,508
6,658,422
Is it possible to separate menu entry and event string in PySimpleGui right-click menus?
<p>Is it possible to separate the menu entry in a <a href="https://www.pysimplegui.org/en/latest/#right-click-menus" rel="nofollow noreferrer">right-click menu</a> from the event string that is assigned when the event is thrown?</p> <p>E.g., when adding a right-click menu to a list box via</p> <pre class="lang-py prett...
<python><pysimplegui>
2023-01-29 14:05:49
0
2,350
divingTobi
75,275,485
1,169,091
Why does the y-intercept from the model not match the graph?
<p>This code generates a graph of the regression line but the y-intercept taken from the LR model does not match the y-intercept on the graph. What am I missing? The script prints the y-intercept, taken from the model, as 152 but the graph shows it to be less than 100.</p> <pre><code># Adapted from https://scikit-learn...
<python><matplotlib><scikit-learn><linear-regression>
2023-01-29 14:01:59
1
4,741
nicomp
75,275,434
10,781,096
Django testing fails with object not found in response.context even though it works when actually running
<p>I'm trying to test if my <code>PlayerPoint</code> model can give me the top 5 players in regards to their points. This is the <code>Player</code> model:</p> <pre class="lang-py prettyprint-override"><code>class Player(AbstractUser): phone_number = models.CharField( max_length=14, unique=True, ...
<python><django><django-testing><django-tests>
2023-01-29 13:55:09
2
488
NegassaB
75,275,429
15,154,700
How to comment on clickup with python?
<p>I want to comment on a specific task in clickup but it responses 401 error.</p> <pre><code>url = &quot;https://api.clickup.com/api/v2/task/861m8wtw3/comment&quot; headers = { &quot;Authorization&quot;: &quot;Bearer &lt;my api key&gt;&quot;, &quot;Content-Type&quot;: &quot;application/json&quot; } # comment...
<python><python-requests><clickup-api>
2023-01-29 13:54:17
2
545
Sadegh Pouriyan Zadeh
75,275,393
9,776,466
Processing multiple columns in the dataset into one column for modeling
<p>I want to predict spatio-temporal data and I found STNN (Spatio Temporal Neural Network) research with the github repository here (<a href="https://github.com/edouardelasalles/stnn" rel="nofollow noreferrer">https://github.com/edouardelasalles/stnn</a>), at the end of the repo description, it is explained regarding ...
<python><pandas><machine-learning><statistics><data-preprocessing>
2023-01-29 13:48:43
0
561
Hermawan Wiwid
75,274,940
10,654,410
peewee.OperationalError: (3995, "Character set 'utf8mb4_unicode_ci' cannot be used in conjunction with 'binary' in call to regexp_like.")
<p>I had a peewee query (against a mysql 8.0 server) working a few months ago, and now it gives me the following error:</p> <pre><code>peewee.OperationalError: (3995, &quot;Character set 'utf8mb4_unicode_ci' cannot be used in conjunction with 'binary' in call to regexp_like.&quot;) </code></pre> <p>The line of code pro...
<python><mysql><peewee>
2023-01-29 12:36:13
1
399
SimonB
75,274,655
20,078,696
Why does plt.cla() only work on one of the plots?
<p>I am trying to create a program that has two different plots at the same time:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np plt.ion() for i in range(100): x = np.arange(i, i + 50, 0.2) plt.cla() for subplotId in range(1, 3): plt.subpl...
<python><matplotlib><plot>
2023-01-29 11:51:31
1
789
sbottingota
75,274,484
10,924,836
Change variable on the basis of last character
<p>I need to change the text variable in the data set below. Namely, each row has categorical values in the object format that need to be changed, depending on the <code>last character</code> in the data set. Below you can see my dataset.</p> <pre><code>import pandas as pd import numpy as np data = { 'stores'...
<python><pandas>
2023-01-29 11:22:59
2
2,538
silent_hunter
75,274,455
1,276,022
Pass a variable to macro in Jinja
<p>I am trying to pass a variable to a macro in jinja but every time I try to do that I get an error message saying</p> <blockquote> <p>jinja2.exceptions.TemplateSyntaxError: unexpected '}', expected ')'</p> </blockquote> <p>Here is my code:</p> <pre><code>{{ my_macro(value='{{var1}} - {{var2}}') }} </code></pre> <p>It...
<python><flask><jinja2>
2023-01-29 11:18:48
1
634
Youstanzr
75,274,446
12,709,265
Limit volume to a certain range
<p>I have a certain program which changes the volume of a computer using the <code>pulsectl</code> module in python. The following is the code:</p> <pre><code>if(distance &gt; self.threshold): self.pulse.volume_change_all_chans(self.sink, 0.02) else: self.pulse.volume_change_all_chans(self.sink, -0.02) </code><...
<python><python-3.x>
2023-01-29 11:17:30
1
1,428
Shawn Brar
75,274,334
11,381,978
Automatically converting .py file to .pyx using python type hints
<p>Recently I had to convert a module written in pure python to pyx in in order to compile with cython. The procedure for converting from py to pyx was very straight forward since the all the variables and functions were type hinted. So it was a just a matter of looking up the cython static type for each types in pytho...
<python><cython>
2023-01-29 10:58:47
1
324
Samm Flynn
75,274,332
16,383,578
How to draw Android lock screen patterns using Python
<p>This may seem trivial but I Googled it and found no relevant results. And I don't have access to ChatGPT because unfortunately I was born in China.</p> <p>I want to find out all the ways a polyline can pass through n*n evenly spaced lattice points without crossing itself.</p> <p>Basically like a typical Android lock...
<python><user-interface>
2023-01-29 10:58:09
1
3,930
Ξένη Γήινος
75,274,241
3,054,437
t() expects a tensor with <= 2 dimensions, but self is 3D
<p>I'm new to <strong>PyTorch</strong> and wrote a simple code as following to classify some inputs. The model input has 8*2 with batch size of 2 and the input layer in the model has 2 nodes. I don't know what is wrong!</p> <pre><code>X1=np.array([[2,1],[3,2],[-4,-1],[-1,-3],[2,-1],[3,-3],[-2,1],[-4,-2]]) Y1=np.array([...
<python><machine-learning><deep-learning><pytorch><runtime-error>
2023-01-29 10:38:06
1
500
mohammad
75,274,070
2,552,108
Super Resolution using OpenCV and Python appears to have no effect
<p>I am trying to follow the code shown in this <a href="https://learnopencv.com/super-resolution-in-opencv/" rel="nofollow noreferrer">link</a> to apply Super Rez using OpenCV <code>cv2.dnn_superres.DnnSuperResImpl_create()</code> function.</p> <p>I have downloaded the super res models from each repo (<a href="https:/...
<python><opencv><deep-learning><neural-network><conv-neural-network>
2023-01-29 10:03:57
0
1,170
user2552108
75,273,915
1,591,921
Prefer binary package in setup.cfg
<p>My project (<a href="https://github.com/locustio/locust" rel="nofollow noreferrer">https://github.com/locustio/locust</a>) depends on <code>greenlet</code>, but whenever there is a new release of that, there is a brief period when no binary version is available, and many of my users have issues with installing from ...
<python><pip><setuptools><python-packaging><greenlets>
2023-01-29 09:37:36
0
11,630
Cyberwiz
75,273,852
2,833,774
How to list objects of one depth level without listing sub-objects by GCP Cloud Storage Python API?
<p>The Cloud Storage Python API allows to list objects using prefix, which limits the listing to certain sub-branches of objects in the bucket.</p> <pre><code>bucket_name = &quot;my-bucket&quot; folders = &quot;logs/app&quot; storage_client.list_blobs(bucket_name, prefix=folders) </code></pre> <p>This operations will r...
<python><google-cloud-storage>
2023-01-29 09:26:09
1
374
Alexander Goida
75,273,603
6,218,173
python index [-1] shows wrong element
<p>As I learned, in python index -1 is the last number. for instant in:</p> <pre><code>values = [1, 2 , 3, 4, 5, 6, 7, 8, 9, 10] print(value[-1]) </code></pre> <p>returns 10 in output.</p> <p>Now, if I want to insert a number in the last position with insert method, I do:</p> <pre><code>value.insert(-1,11) </code></p...
<python><python-3.x><indexing><methods>
2023-01-29 08:38:50
3
491
Majid
75,273,498
9,576,988
How to pivot a column's values, making new, enumerated columns with pandas dataframe
<p>I have a dataframe like:</p> <pre class="lang-py prettyprint-override"><code> id diag a_date 0 1 d1 55 1 1 d2 88 2 2 d5 22 3 2 d3 44 4 2 d4 88 5 2 d4 89 6 3 d1 11 7 3 d1 13 8 3 d1 15 9 3 d5 27 10 3 d5 28 ...
<python><pandas><dataframe><pivot><reshape>
2023-01-29 08:20:10
2
594
scrollout
75,273,422
12,875,740
Requests in multiprocessing fail python
<p>I'm trying to query data from a website, but it takes 6 seconds to query. For all 3000 of my queries, I'd be sitting around for 5 hours. I heard there was a way to parallelize this stuff, so I tried using multiprocessing to do it. It didn't work, and I tried asyncio, but it gave much the same result. Here's the mult...
<python><multithreading><python-requests><parallel-processing><multiprocessing>
2023-01-29 08:04:34
0
896
James Huang
75,273,413
17,696,880
How to prevent the capture groups of this regex from overlapping so that they cannot capture the substrings correctly?
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;En esta alejada ciudad por la tarde circulan muchos camiones con aquellos acoplados rojos, grandes y bastante pesados, llevándolos por esos trayectos bastante empedrados, polvorientos, y un tanto arenosos. Y incluso bastante desde lejos ya se...
<python><regex>
2023-01-29 08:03:01
0
875
Matt095
75,272,945
14,037,055
How can i convert images into grayscale?
<p>I have 1000 of images. Now I like to convert those images into grayscale?</p> <pre><code>import tensorflow as tf from tensorflow.keras.utils import img_to_array #df['image_name'] = df['image_name'].apply(str) df_image = [] for i in tqdm(range(df.shape[0])): img = image.load_img('/content/drive/MyDrive/Predict DF...
<python><tensorflow><image-processing><conv-neural-network><grayscale>
2023-01-29 06:13:48
1
469
Pranab
75,272,857
3,247,006
Cannot reduce "SELECT" queries with "select_related()" and "prefetch_related()" in one-to-one relationship in Django
<p>I have <code>Person</code> and <code>PersonDetail</code> models in <strong>one-to-one relationship</strong> as shown below. *I use <strong>Django 3.2.16</strong>:</p> <pre class="lang-py prettyprint-override"><code>class Person(models.Model): name = models.CharField(max_length=20) def __str__(self): ...
<python><django><django-models><django-select-related><django-prefetch-related>
2023-01-29 05:48:46
1
42,516
Super Kai - Kazuya Ito
75,272,803
6,025,866
Error when importing tensorflow even when tensorflow is installed on MacOS M1 Pro
<p>I am getting the following error after I have installed tensorflow using conda. The error is as follows</p> <pre><code> Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/lib/python3.10/site-packages/ten...
<python><tensorflow><keras>
2023-01-29 05:32:56
0
441
adhok
75,272,745
13,359,498
Grad Cam outputs for all the images are the same
<p>I am using grad cam to see which regions of the test images are most important for the prediction of <code>resnet50</code>. The output I got has some errors.</p> <p>Code Snippets:</p> <pre><code>from tensorflow.keras.models import Model import tensorflow as tf import numpy as np import cv2 class GradCAM: def __...
<python><tensorflow><keras><conv-neural-network><visualization>
2023-01-29 05:15:53
1
578
Rezuana Haque
75,272,443
8,888,469
Issue while pattern replacement in column value in pandas dataframe
<p>I have a dataframe <code>new_df</code> as shown below .</p> <p>I have issue that my current code contain replace if numeric value or special character value comes after character value in column in dataframe like <code>70317380CH71</code> or <code>70317380CH%(</code></p> <p><strong>Current output Dataframe</strong>...
<python><pandas><regex><dataframe>
2023-01-29 03:26:46
1
933
aeapen
75,272,295
6,114,832
Shapely smoothing with dilate and erode
<p>I am trying to implement a polygon smoothing operation with shapely. I am doing this with the combination of erode and dilate (polygon.buffer function with positive and negative numbers). The specification of my smooth function goes something like this:</p> <ol> <li>The operation must be conservative. There must not...
<python><polygon><shapely><mathematical-morphology>
2023-01-29 02:41:09
1
1,117
Stefan Karlsson
75,272,189
2,392,151
Python pandas dataframe ne method issue
<p>I have 2 dataframes like</p> <p>here is the original data: dataframe:1</p> <pre><code> coverage_level_identifier data_status_code last_change_date last_change_user_name creation_date creation_user_name minimum_coverage_level_percentage erp_factor 0 1 ...
<python><pandas>
2023-01-29 02:04:38
0
363
Bill
75,272,097
5,551,722
Set z-order of Edges in Pandas Dataframe
<p>I'm using OSMnx to create some plots of road networks with data shown by colour, below is an example which produces an image with colour showing betweenness centrality. The problem I'm having is that, due to the zordering, some of the lighter regions are covered by other edges, especially around junctions with lots ...
<python><pandas><matplotlib><networkx><osmnx>
2023-01-29 01:39:19
2
673
George Willcox
75,272,008
14,593,213
No performance bonus using multithreading with pytube
<p>I am using the pytube library to retrieve stream information for a list of YouTube videos. I have implemented the retrieval of streams using a simple loop, as well as using the concurrent.futures and multiprocessing libraries for multithreading. However, I am not seeing the performance boost I was expecting and all ...
<python><multithreading><python-multithreading><concurrent.futures><pytube>
2023-01-29 01:05:45
0
355
Davi A. Sampaio
75,271,947
583,044
Version number in pyinstaller and application
<p>I have an application that I want to include some version information within, and only have it defined in one location. I am running on Windows, so want to set the executable version resource, and am using pyinstaller to build the executable, but also want to be able to access the version infomration within the appl...
<python><version><pyinstaller>
2023-01-29 00:48:49
1
6,651
tinman
75,271,720
9,576,988
Sorting enumerated elements in a list using another list as an order
<p>I have a master list:</p> <pre class="lang-py prettyprint-override"><code>l = ['gala_apple', 'gala_lime', 'fuji_apple', 'fuji_lime'] </code></pre> <p>Through some manipulation, I end up with a variant of <code>l</code>:</p> <pre class="lang-py prettyprint-override"><code>r = [ 'fuji_apple_1', 'fuji_apple_2',...
<python><list><sorting>
2023-01-28 23:53:47
2
594
scrollout
75,271,606
1,380,285
How do I display matplotlib.pyplot plots from a remote Ubuntu platform on a local Windows machine?
<p>There are alot of similar questions and answers to this one on this site. But nothing that I find is working. If I try the default backend, I get an error when I load <code>matplotlib.pyplot</code> to the effect that there is no <code>_tkinter</code> module. I'm told to solve this by installing <code>python-tk</c...
<python><matplotlib><ubuntu><backend>
2023-01-28 23:24:36
0
6,713
bob.sacamento
75,271,441
12,242,085
How to make loop with features selection by features importance where deleted features with imp = 0 or below mean imp in each iteration in Python?
<p>I have DataFrame in Python Pandas like below:</p> <p><strong>Input data:</strong></p> <ul> <li>Y - binary target</li> <li>X1...X5 - predictors</li> </ul> <p><strong>Source code of DataFrame:</strong></p> <pre><code>import pandas as pd import numpy as np from xgboost import XGBClassifier df = pd.DataFrame() df[&quo...
<python><loops><for-loop><machine-learning><feature-selection>
2023-01-28 22:47:52
1
2,350
dingaro
75,271,424
215,761
Select / browse to a file / folder from a cgi (python) form invoking the system dialog (a Finder on Mac)
<p>I am trying to implement (in Python) something like a browser's &quot;File/Open...&quot; or &quot;Select to upload&quot; functionality:</p> <p>that is, - with help of a system dialog (specifically Finder on MAC), - browse to a file / a folder, select it, press a button and get the file/folder name (path) back into m...
<python><cgi><finder>
2023-01-28 22:43:54
0
320
Vlad K.
75,271,373
1,019,129
Normalize vectors in the complex space : mean=0 and std-dev=1/sqrt(n)
<p>I have a Vector Or bunch of vectors (stored in 2D array, by rows)</p> <p>The vectors are generated as :</p> <blockquote> <p>MEAN=0, STD-DEV=1/SQRT(vec_len)</p> </blockquote> <p>and before or after operations have to be normalized in the same form</p> <p>I want to normalize them in the complex space. Here is the wrap...
<python><fft><normalization><complex-numbers>
2023-01-28 22:35:04
1
7,536
sten
75,271,285
14,256,643
Fastapi how to convert string to list when calling get methos?
<p>I am using mysql database and it's doesn't support list if I stored sting like &quot;apple&quot;,&quot;banana&quot; in my mysql database then when using get method fastapi how to convert theme from string to list like [&quot;apple&quot;,&quot;banana&quot;]. I tried this but didn't work and also not getting the image...
<python><mysql><arrays><python-3.x><fastapi>
2023-01-28 22:15:10
2
1,647
boyenec
75,271,262
16,332,690
Converting timezone aware datetime column to string with UTC time offset
<p><strong>Update:</strong> This was fixed by <a href="https://github.com/pola-rs/polars/pull/6673" rel="nofollow noreferrer">pull/6673</a></p> <hr /> <p>I have the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = ( pl.DataFrame( { &quot;int&quot;: [1, 2, 3], ...
<python><datetime><timezone><strftime><python-polars>
2023-01-28 22:11:34
1
308
brokkoo
75,271,187
523,612
How can I fix a TypeError that says an operator (<, <=, >, >=) is not supported between x and y?
<p>I often see error messages that look like any of:</p> <pre><code>TypeError: '&lt;' not supported between instances of 'str' and 'int' </code></pre> <p>The message can vary quite a bit, and I guess that it has many causes; so rather than ask again every time for every little situation, I want to know: <strong>what ap...
<python><python-3.x><debugging><typeerror>
2023-01-28 21:57:37
1
61,352
Karl Knechtel
75,271,184
19,916,174
Space Complexity with no variables defined
<p>Suppose I had some code:</p> <pre class="lang-py prettyprint-override"><code>def foo(forest: list[list[int]]) -&gt; int: return sum([1 for tree in forest for leaf in tree]) </code></pre> <p>In this code, no variables are defined. Everything is evaluated in one line, which means to my knowledge the data isn't bei...
<python><time-complexity><list-comprehension><nested-lists><space-complexity>
2023-01-28 21:57:20
1
344
Jason Grace
75,271,150
6,552,836
Apply a function to a dataframe which includes the previous row
<p>I have an input data frame for daily grocery spend which looks like this:</p> <p><code>input_df1</code></p> <pre><code>Date Potatoes Spinach Lettuce 01/01/22 10 47 0 02/01/22 0 22 3 03/01/22 11 0 3 04/01/22 3 9 ...
<python><python-3.x><pandas><dataframe><data-wrangling>
2023-01-28 21:51:36
1
439
star_it8293
75,271,146
3,968,048
pip - is it possible to preinstall a lib, so that any requirements.txt that is run containing that lib won't need to re-build it?
<p>So my scenario is that I'm trying to create a Dockerfile that I can build on my Mac for running Spacy in production. The production server contains a Nvidia GPU with CUDA. To get Spacy to use GPU, I need the lib <code>cupy-cuda117</code>. That lib won't build on my Mac because it can't find the CUDA GPU. So what I'm...
<python><pip>
2023-01-28 21:51:05
0
3,536
Peter R
75,271,094
386,861
How to split a pandas dataframe based on regex string
<p>I have a CSV of questions and results. Built a simple bit of code to turn into a a list of dataframes for analysis.</p> <p>But last one refused to split out , I think because simple startswith and endswith couldn't handle the fact that the startswith on every question startswith &quot;&lt;Q&quot;</p> <pre><code>def ...
<python><pandas><dataframe><split>
2023-01-28 21:40:14
1
7,882
elksie5000
75,270,910
12,242,085
How to modify loop builing ML models and generated DataFrame with column presented variable removed in each iteration of for-loop in Python?
<p>I have Pandas DataFrame like below:</p> <p><strong>Input data:</strong></p> <ul> <li>Y - binary target</li> <li>X1...X5 - predictors</li> </ul> <p><strong>Source code of DataFrame:</strong></p> <pre><code>import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metric...
<python><loops><for-loop><machine-learning>
2023-01-28 21:10:18
1
2,350
dingaro
75,270,603
5,156,025
Type checking error: views.py:24: error: "HttpRequest" has no attribute "tenant"
<p>I am creating a Django application which is multi-tenanted. The custom middleware I use attaches a <code>tenant</code> object to the request.</p> <p>My issue is when type checking, my views are not aware of extra attribute on the <code>HttpRequest</code> class.</p> <p>I have tried creating a <code>TenantHttpClass</c...
<python><django><python-typing><mypy>
2023-01-28 20:21:05
2
494
Adam Birds
75,270,582
123,654
Unexpected Apache Beam (Dataframe API) behavior gives tuples instead of dictionaries, breaking BigQuery upload
<p>Learning Apache Beam with the dataframe API at the moment and coming across some unexpected behavior that I was hoping an expert could explain to me.</p> <p>Here's the simplest version of my issue I could drill it down to (in the real version the dataframe transform is something more complex):</p> <pre><code>class L...
<python><dataframe><google-cloud-dataflow><apache-beam>
2023-01-28 20:18:34
1
1,631
Will
75,270,546
4,507,231
Running pyinstaller on code containing relative paths
<p>I have a large Python codebase developed inside PyCharm. I want to use PyInstaller for obvious reasons; however, I'm struggling with relative paths for data files due to the project code file hierarchy.</p> <p>The file hierarchy was a usual top-down structure, i.e., the point of execution is within a file found in t...
<python><pyinstaller>
2023-01-28 20:08:45
0
1,177
Anthony Nash
75,270,261
6,273,451
Pandas .iloc indexing coupled with boolean indexing in a Dataframe
<p>I looked into existing threads regarding indexing, none of said threads address the present use case.</p> <p>I would like to alter specific values in a <code>DataFrame</code> based on their position therein, ie., I'd like the values in the second column from the first to the 4th row to be <code>NaN</code> and values...
<python><pandas><numpy><indexing>
2023-01-28 19:23:12
1
334
Mehdi Rezzag Hebla
75,269,939
1,001,938
Have a result be both a class and destructurable as a tuple
<p>I came across a method in Python that returns a class, but can be destructured as if it's a tuple.</p> <p>How can you define a result of a function to be both an instance of a class AND use destructure assignment as if it's a tuple?</p> <p>An example where you see this behavior:</p> <pre><code>import scipy.stats as ...
<python>
2023-01-28 18:30:29
2
64,248
Don P
75,269,700
6,203,472
pre-commit fails to install isort 5.11.4 with error "RuntimeError: The Poetry configuration is invalid"
<p><a href="https://pre-commit.com/" rel="noreferrer">pre-commit</a> suddenly started to fail installing the <a href="https://github.com/pycqa/isort" rel="noreferrer">isort</a> hook in our builds today with the following error</p> <pre><code>[INFO] Installing environment for https://github.com/pycqa/isort. [INFO] Once ...
<python><pre-commit><pre-commit.com><isort>
2023-01-28 17:54:09
5
6,474
bagerard
75,269,696
10,842,351
Fast creation of 2d+ memory views in Cython
<p>We are developing a project where we create a lot of typed memory views as numpy arrays but we often have to deal with arrays of small size so that the creation of memory views as np.ndarray is impacting a lot because it has lots of interactions with Python. I found that there are some “tricks” to improve the initia...
<python><arrays><c><cython>
2023-01-28 17:53:34
0
665
Tortar
75,269,596
11,607,243
Unable to run NumPy on VS Code
<p>I have installed Anaconda (with Python 3.9) and Python (3.11) separately. After installing VS Code, I have also created a separated Anaconda environment <code>Env01</code> . Now, when I open a VS Code file, I have three available environments to choose from</p> <p>a) base Python 3.11</p> <p>b) base Conda 3.9</p> <p>...
<python><numpy><visual-studio-code><anaconda3>
2023-01-28 17:38:46
1
525
newtothis
75,269,487
1,953,475
Pass in any variable while guaranteeing predefined relationship
<p>I have a simple formula taking basic arithmetic calculations given several inputs.</p> <pre><code>a = 1 b = 2 c = a + b #3=1+2 d = 4 e = c + d #7=3+4 </code></pre> <p><a href="https://i.sstatic.net/RPoL8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RPoL8.png" alt="graph of relationship" /></a></p>...
<python><sympy>
2023-01-28 17:24:24
3
19,728
B.Mr.W.
75,269,387
871,910
dataclasses.asdict doesn't work on Python 3.11?
<p>I tried the following code:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import asdict, dataclass @dataclass class DC: a: int b: int c = DC(a=10, b=5) dc = asdict(c) print(dc) </code></pre> <p>On Python 3.10 it works as expected, printing a dictionary as expected. When I try the sa...
<python><python-dataclasses><python-3.11>
2023-01-28 17:10:16
1
39,097
zmbq
75,269,244
156,180
Is a loop in a loop really the best way to output nested dict items in Python?
<p>I have a dict from a json API call that looks like this:</p> <pre><code>{ 'id': '63d08d5c57abd98fdeea7985', 'pageName': 'Some Page Name', 'bodyContent': [{ 'children': [{ 'alpha': 'foo foo foo', 'beta': 'bar bar bar' }] }], 'date': '2023-01-25T02:01:00.965Z' } </code></pre...
<python><for-loop><jinja2><nested-loops><nested-for-loop>
2023-01-28 16:46:17
1
2,872
Jeff
75,269,161
2,036,464
Python: import docx Error: " from exceptions import PendingDeprecationWarning "
<p>I want to convert multiple txt files to docx. I use this code:</p> <pre><code>from docx import Document import re import os path = 'd://2022_12_02' direct = os.listdir(path) for i in direct: document = Document() document.add_heading(i, 0) myfile = open('d://2022_12_02'+i).read() myfile = re.sub(r'...
<python><python-3.x>
2023-01-28 16:31:45
1
1,065
Just Me
75,268,750
1,938,410
How to print line number of error that is inside a function using except in Python?
<p>I want to print an error's line number and error message in a nicely displayed way. The follow is my code, which uses <em>linecache</em>:</p> <pre><code>import linecache def func(): if xx == 1: print('ok') try: func() except: exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno...
<python><exception>
2023-01-28 15:30:55
3
507
SamTest
75,268,748
210,867
How to introspect a Click application?
<p>I have a Click app called &quot;DC&quot; starting with click.Group <code>cli()</code>, which has many subcommands. I'm trying to produce a text file with a list of all commands, arguments, options, and help text as a convenient reference. How do I introspect a Click application?</p> <p>I experimented using the <a hr...
<python><python-click>
2023-01-28 15:30:37
1
8,548
odigity
75,268,657
18,749,472
preserve multiple GET parameters in Django URL
<p>In my django project I have a page displaying a list of times. On this page there is 3 GET forms which are for:</p> <ul> <li><p>Parsing through pages</p> </li> <li><p>Selecting graph data</p> </li> <li><p>Sorting items</p> </li> </ul> <p>If a user is to select a field in all of these forms the URL should look someth...
<python><html><django><request><get>
2023-01-28 15:16:54
1
639
logan_9997
75,268,571
10,220,116
Decorating with arguments a Class Declaration
<p>I'm trying to create a Class representing a regex to execute for my application. For each regex I have a link to the regex101.com page where users can find unit tests. I wanna use this solution to have near the class declaration this link but without having them in the class code. The code I think about has to look ...
<python><design-patterns><python-decorators>
2023-01-28 15:04:03
1
310
Daniele Tentoni
75,268,498
518,012
ModuleNotFoundError: No module named 'delta.tables'; 'delta' is not a package
<p>I'm trying to get my PySpark to work with Delta table.</p> <p>I did &quot;pip install delta&quot; as well as &quot;pip install delta-spark&quot;</p> <p>This is my delta.py script:</p> <pre><code>from delta.tables import * from pyspark.sql.functions import * deltaTable = DeltaTable.forPath(spark, &quot;/tmp/delta-ta...
<python><apache-spark><pyspark><delta-lake>
2023-01-28 14:50:35
0
15,684
Eugene Goldberg
75,268,393
3,885,446
YOLOV8 how does it handle different image sizes
<p>Yolov8 and I suspect Yolov5 handle non-square images well. I cannot see any evidence of cropping the input image, i.e. detections seem to go to the enge of the longest side. Does it resize to a square 640x604 which would change the aspect ratio of objects making them more difficult to detect?</p> <p>When training on...
<python><deep-learning><conv-neural-network><yolo>
2023-01-28 14:33:43
1
575
Alan Johnstone
75,268,350
10,411,973
Tosca parser ImportError: "No modules named". The modules already installed in dist-packages success
<p>I have gone through similar questions but I still cant resolve the problem I have install the package and success but when I run my script it will always return no module name error.</p> <p>I suspect something todo with the python path where the module may not in python path This is my code</p> <pre><code>from tosc...
<python><path><tosca>
2023-01-28 14:27:14
0
565
chenoi
75,268,283
16,332,690
How to extract date from datetime column in polars
<p>I am trying to move from pandas to polars but I am running into the following issue.</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame( { &quot;integer&quot;: [1, 2, 3], &quot;date&quot;: [ &quot;2010-01-31T23:00:00+00:00&quot;, &quot;2010-02-01T00:00:...
<python><date><datetime><timezone><python-polars>
2023-01-28 14:17:20
2
308
brokkoo
75,268,174
8,958,754
pygame maintain a points position around a rotated image
<p>In pygame I have an image object of a frigate at 0 degrees of rotation. On it i have turrets, i need to calculate their new position if the frigate rotates by say 90 degrees.</p> <p>After rotating the image like so,</p> <pre><code>rotatedFrigate = pygame.transform.rotate(gui.frigate[0], facingAngle) </code></pre> <...
<python><image><pygame><pygame-surface>
2023-01-28 13:58:27
1
855
Murchie85
75,268,149
20,266,647
Read parquet in MLRun, "Unable to infer schema for Parquet. It must be specified manually."
<p>I got this issue, when I ingested/wrote data to FeatureSet (part of MLRun FeatureStore) and than I read the data via PySpark (it seems as invalid parquet). See exception:</p> <pre><code>AnalysisException Traceback (most recent call last) &lt;ipython-input-8-a8c688f9ceb5&gt; in &lt;module&gt; ...
<python><pyspark><parquet><feature-store><mlrun>
2023-01-28 13:54:14
1
1,390
JIST
75,267,907
4,576,519
How to import a cached numba function without a Python definition
<p>Consider the following function in <code>numba</code>, which just serves as an example:</p> <pre class="lang-py prettyprint-override"><code>import numba as nb import numpy as np @nb.njit('float64(float64[::1])', cache=True) def total (x): ''' Sum the elements of an array. ''' total = 0 for i in range(x...
<python><caching><import><numba><jit>
2023-01-28 13:12:57
1
6,829
Thomas Wagenaar
75,267,745
20,520
How can I share a large data structure among forked Python processes?
<p>I'm creating a 58 GB graph in a Python program, which I then want to process through multiple (Linux) processes. For that I'm using a <code>ProcessPoolExecutor</code> with a <code>fork</code> context, passing to each process just an integer associated with the chunk associated with it.</p> <pre class="lang-py prett...
<python><concurrency><fork>
2023-01-28 12:41:46
0
19,463
Diomidis Spinellis
75,267,719
20,646,427
Trying to get and update or create model from json in Django
<p>Im trying to get and update or create object in model from json list of dicts but i got an error btw my code is creating objects but cant update them:</p> <p>&quot;TypeError: Tried to update field authentication.CounterParty.GUID with a model instance, &lt;CounterParty: CounterParty object (3)&gt;. Use a value compa...
<python><django>
2023-01-28 12:37:21
0
524
Zesshi
75,267,643
1,045,755
ScatterGeo vs ScatterMapbox in Plotly.JS (Performance vs. coloring options)
<p>I have a little conundrum I was hoping someone could shed a bit of light on.</p> <p>Basically I have a bunch of paired coordinates (roughly 3000), i.e. two points that needs to be connected with a line. Depending on some value, this line (plus the two data points) needs to have a certain color. In my situation, I ne...
<python><reactjs><plotly><mapbox><plotly.js>
2023-01-28 12:24:30
0
2,615
Denver Dang
75,267,629
10,613,037
Create a view that accepts a post request and performs an action regardless of if the instance has been created or not
<p>I've got a view that takes in a phone number, and if the phone number isn't created, it'll send an SMS otp with <code>send_otp</code>. Now I want to also implement it so that if a phone number is sent to the endpoint but has already been registered to a user, then the view will send an otp all the same.</p> <p>Right...
<python><django-rest-framework>
2023-01-28 12:22:37
1
320
meg hidey
75,267,623
5,567,893
How to set the DGL node features from networkx graph
<p>I'd like to convert the networkx graph to dgl data. <br /> But when I tried using <code>dgl.from_networkx</code> like tutorial, there was unexpected result.</p> <pre class="lang-py prettyprint-override"><code>import dgl import networkx as nx import numpy as np import torch #Construct the networkx graph G containing...
<python><networkx><directed-graph><pytorch-geometric><dgl>
2023-01-28 12:21:55
1
466
Ssong
75,267,582
11,944,499
Python environment setup seems complicated and unsolvable
<p>I've been a developer for about three years, primarily working in TypeScript and Node.js. I'm trying to broaden my skillset by learning Python (and eventually expanding my learning of <a href="https://en.wikipedia.org/wiki/Computer_vision" rel="nofollow noreferrer">computer vision</a>, <a href="https://en.wikipedia....
<python><python-3.x>
2023-01-28 12:16:11
3
351
this