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
79,059,024
10,972,079
TensorFlow - InvalidArgumentError: Shapes of all inputs must match
<p>I am currently following the TensorFlow guide/tutorial on seq2seq NMT models (<a href="https://www.tensorflow.org/text/tutorials/nmt_with_attention" rel="nofollow noreferrer">https://www.tensorflow.org/text/tutorials/nmt_with_attention</a>) using a Jupyter Notebook. Upon running the following code,</p> <pre><code># ...
<python><numpy><tensorflow><keras>
2024-10-06 12:05:09
1
1,338
CauseYNot
79,058,867
17,889,492
Passing colors as a list to matplotlib
<p>I have a plot with x of shape 180 and y of shape 36, 180. So I have 36 lines when I call plot. How do I set the first 30 to blue and the last six to red without calling a loop?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 180) y = np.random.rand(36, 180) colors = ['b...
<python><matplotlib>
2024-10-06 10:34:36
0
526
R Walser
79,058,798
19,198,552
Prevent window resize when widget is forgotten by PanedWindow
<p>When I &quot;forget&quot; or &quot;add&quot; a widget to a PanedWindow widget before any resize of the root window, then the root window size is changed by this actions. But after resizing the root window by the mouse pointer, &quot;forget&quot; or &quot;add&quot; do not change the size of the window anymore, but on...
<python><tkinter>
2024-10-06 10:05:32
1
729
Matthias Schweikart
79,058,615
4,451,521
Docker fails when trying to install libraries
<p>I am trying to build a docker image and it fails in the</p> <pre><code>RUN pip install -r requirements_inference.txt </code></pre> <p>The error message is</p> <pre><code>182.3 ERROR: Could not find a version that satisfies the requirement pytorch-lighning==1.2.10 (from versions:none) 128.3. ERROR: No matching distri...
<python><docker><pip><dockerfile>
2024-10-06 08:00:46
1
10,576
KansaiRobot
79,058,530
4,947,594
Python sort lib different behavior with different comparing functions, some comparing function will not work
<p>I want get a max alphabetically order by sub string, so I need to have a comparing method. For the comparing function function</p> <pre class="lang-py prettyprint-override"><code>from functools import cmp_to_key def compare(a,b): print(a,b, a+b,b+a,a+b&gt;b+a) return (a+b)&gt;(b+a) # first comparing functio...
<python><string><compare><sortcomparefunction>
2024-10-06 07:04:38
1
804
wherby
79,058,420
20,999,526
Cannot download unlisted Odysee video using Python
<p>I am using the below code to fetch the <code>contentUrl</code> of an <strong>unlisted</strong> video on Odysee.</p> <pre><code>import requests, ast def getVideoMetadata(url,timeout=7): return ast.literal_eval(requests.get(url,timeout=timeout).text.split('&lt;script type=&quot;application/ld+json&quot;&gt;')[1]....
<python><url><request>
2024-10-06 05:33:22
0
337
George
79,058,350
8,487,193
Module 'numpy' has no attribute 'bool8' In cartpole problem openai gym
<p>I'm beginner &amp; trying to run this simple code but it is giving me this exception &quot;module 'numpy' has no attribute 'bool8'&quot; as you can see in screenshot below. Gym version is 0.26.2 &amp; numpy version is 2.1.1. I've tried downgrading both but visual studio won't let me do that. I have installed latest ...
<python><python-3.x><numpy><reinforcement-learning><openai-gym>
2024-10-06 04:19:17
4
325
Jitender
79,058,264
9,983,652
sys.path.insert(0, '..') not working in py file while working in juyter notebook
<p>I have a <code>py</code> file saved in a subfolder, and it need to import a module in main folder which is one level up. I am using <code>sys.path.insert(0, '..')</code>.</p> <p>Then it works when the code is executed in cell in <code>jupyter notebook</code>. However, it doesn't work when code is written in <code>py...
<python><sys.path>
2024-10-06 02:40:16
0
4,338
roudan
79,058,228
6,059,506
How to get fine grained smaller time resolution srt from google cloud speech to text API?
<p>I have a working code in python which generates an srt file using google cloud speech to text.</p> <pre class="lang-py prettyprint-override"><code>from google.api_core.client_options import ClientOptions from google.cloud.speech_v2 import SpeechClient from google.cloud.speech_v2.types import cloud_speech import json...
<python><google-cloud-platform><speech-to-text><google-cloud-speech><srt>
2024-10-06 01:57:54
0
2,067
theprogrammer
79,058,101
19,502,111
Preventing weights update for certain samples in Keras3
<p>I have a custom layer called <code>ControlledBackward</code> that accepts <code>prev_layer</code> and <code>input_layer_of_mask</code>:</p> <pre><code>class ControlledBackward(Layer): def __init__(self, **kwargs): super(ControlledBackward, self).__init__(**kwargs) def call(self, inputs): mask, prev_laye...
<python><arrays><numpy><tensorflow><keras>
2024-10-05 23:10:30
1
353
Citra Dewi
79,058,037
2,103,394
Python 3.10+: call async function within a property in a way that does not produce errors if that property is accessed in an async function
<p>I have built a library that includes an ORM with the following use pattern:</p> <pre class="lang-py prettyprint-override"><code>class Model(SqlModel): columns = ('id', 'details', 'parent_id') parent: RelatedModel Model.parent = belongs_to(Model, Model, 'parent_id') ... def example(some_id, some_other_id): ...
<python><python-3.x><async-await><python-asyncio>
2024-10-05 22:25:57
0
1,216
Jonathan Voss
79,057,984
3,753,826
Multiple versions of single Jupyter Notebook for different audiences (e.g. tutors/students) using tags
<p>I'm working on creating assignments for students using Jupyter Notebooks. My goal is to generate different versions of the same Notebook to distribute to tutors and students.</p> <p>I need certain cells, such as those containing exercise solutions, to be included only in the tutor's version, while other cells should...
<python><jupyter-notebook>
2024-10-05 21:38:28
2
17,652
divenex
79,057,748
2,276,054
Flask and logging - some questions
<p>I. When creating a Flask application, <strong>where exactly do I initialize logging</strong>?<br /> Right before <code>app = Flask(__name__)</code> ?<br /> Right after it?</p> <p>II. By default, Flask logs HTTP requests in the common format, i.e.</p> <pre><code>- 127.0.0.1 - - [05/Oct/2024 20:39:49] &quot;GET / HTTP...
<python><flask>
2024-10-05 18:59:27
1
681
Leszek Pachura
79,057,745
13,392,257
Can't create objects on start
<p>I created a function and want to run it automatically on start. The function creates several objects</p> <p>I have an error <code>AppRegistryNotReady(&quot;Apps aren't loaded yet.&quot;)</code> Reason is clear - the function imports objects from another application (parser_app)</p> <p>I am starting app like this <co...
<python><django>
2024-10-05 18:58:46
2
1,708
mascai
79,057,675
302,274
In Django, how to retrieve an id to use in a dynamic link?
<p>I have a Django app. In my sidebar I have a navigation link that goes to a list of reports. That link needs an id to get the correct list of reports.</p> <p>The <code>&lt;li&gt;</code> element in base.html that links to the ga_reports page is below. This link needs the <code>app_config.id</code> to resolve correctly...
<python><django>
2024-10-05 18:15:45
1
3,035
analyticsPierce
79,057,531
22,407,544
How to get the estimated remaining time of an already started Celery task?
<p>I am using django with Celery and redis. I would like that when a user initiates a Celery task my app estimates the amount of time left until the task is completed(so that I can, for example, represent this data to the frontend as a progress bar).</p> <p>For example, given this polling function:</p> <p>views.py:</p>...
<python><django><celery>
2024-10-05 17:05:38
0
359
tthheemmaannii
79,057,529
18,769,241
IndexError: index 7 is out of bounds for axis 0 with size 7
<p>I am trying to assess whether the lips of a person are moving too much while the mouth is closed (to conclude it is chewing).</p> <p>The mouth closed part is done without any issue, but when I try to assess the lip movement through landmarks (<code>dlib</code>) there seems to be a problem with the last landmark of t...
<python><numpy><face-recognition><dlib><face-landmark>
2024-10-05 17:04:24
1
571
Sam
79,057,462
1,084,865
How to calculate expected value of softmax values in Tensorflow?
<p>I have a model with a final softmax layer for N categories. These categories are ordered and numerical, so it's meaningful to calculate statistics over the probability distribution given by softmax.</p> <p>Assume the category values are simply an increasing index sequence. So, the first has value 0, the second 1, ...
<python><tensorflow><keras><softmax>
2024-10-05 16:29:05
1
785
jensph
79,057,245
2,826,018
Why can't my LSTM determine if a sequence is odd or even in the number of ones?
<p>I am trying to understand LSTMs and wanted to implement a simple example of classifying a sequence as &quot;0&quot; if the number of &quot;1&quot; in the sequence is odd and as &quot;1&quot; if the number of &quot;1&quot; is even. This is my data generation and training routine:</p> <pre><code>import torch import nu...
<python><pytorch><lstm>
2024-10-05 14:32:22
1
1,724
binaryBigInt
79,057,188
1,090,446
unable to recognize my inputs in python plotty - dash
<pre><code>dash_app = dash.Dash(__name__) dash_app.layout = html.Div([ html.Div([ html.P(&quot;Range: &quot;, style={'margin-right': '10px'}), dcc.Input(id='user-min-strike', type='number', value=5600, style={'margin-right': '10px'}), dcc.Input(id='user-max-strike', type='number', value=5800...
<python><plotly-dash>
2024-10-05 13:46:31
1
1,159
shd
79,057,058
4,910,962
Usage of .net syntax in python
<p>I'm trying to translate a programm written in .net to python. I'm using clr and pythonnet</p> <pre><code>clr.AddReference(&quot;System&quot;) clr.AddReference(&quot;System.IO&quot;) clr.AddReference(&quot;System.Drawing&quot;) from System.Reflection import Assembly from System import String, Func, Action, Array, In...
<python><c#><.net><sdk><flir>
2024-10-05 12:32:57
0
354
Papageno
79,056,958
13,634,560
boxplots showing flat line instead of box and whiskers, plotly python
<p>I am attempting to chart a few boxplots, organized by a categorical variable with go.Box. However, when I plot the data, there is just a flat line that shows up. [Note: this question seems well-documented in R, but I have not found a similar question for Python. please link to it if you find one.]</p> <p>Plotting wi...
<python><plotly>
2024-10-05 11:32:37
1
341
plotmaster473
79,056,727
11,149,556
LALR Grammar for transforming text to csv
<p>I have a processor trace output that has the following format:</p> <pre class="lang-none prettyprint-override"><code>Time Cycle PC Instr Decoded instruction Register and memory contents 905ns 86 00000e36 00a005b3 c.add x11, x0, x10 x11=00000e5c x10:00000e5c 915ns ...
<python><regex><grammar><ebnf><lark-parser>
2024-10-05 09:19:50
2
479
ex1led
79,056,011
10,473,393
http.client works but requests throws read timeout
<p>I'm just trying to understand. When using <code>requests</code> the request throws 403 (when without headers) or Read Timeout (when with headers). Doing the same thing with <code>http.client</code> gets 200 status code as response.</p> <p>The url i'm trying to fetch is: <a href="https://img.uefa.com/imgml/uefacom/ue...
<python>
2024-10-04 22:58:43
1
1,739
Alexander Santos
79,055,995
3,802,331
Airflow Python Operator TypeError: got multiple values for keyword argument 'op_kwargs'
<pre><code>Broken DAG: [&lt;redacted&gt;] Traceback (most recent call last): File &quot;&lt;redacted&gt;&quot;, line 198, in &lt;module&gt; some_task_op() &gt;&gt; Transfer &gt;&gt; short_circuit() &gt;&gt; Process &gt;&gt; Summarize ^^^^^^^^^^^^^^ File &quot;/python/env/lib/python3.12/site-packages/airflow...
<python><airflow>
2024-10-04 22:49:29
1
390
404
79,055,903
9,827,719
How can I create a Google Cloud Virtual Machine in Python using a Google Cloud Instance Template with reserved regional IP?
<p>My code can create Virtual Machines from a Instance Template. However I need to use a reserved regional IP.</p> <p>I have created the regional IP with the CLI like this:</p> <pre><code>gcloud compute addresses create test-regional-ip --region europe-north1 --project=sindre-dev </code></pre> <p>I list the IPs and see...
<python><google-cloud-platform>
2024-10-04 21:52:42
1
1,400
Europa
79,055,895
4,875,641
Multiprocessing pool stops operating - Windows 11
<p>The following code start 5 multiprocessing tasks. Those tasks print a message then go to sleep a random period of time then do this again. That is repeated 10 time so the entire set of tasks should complete in about 50 seconds at most.</p> <p>When the pool is first created, the addresses of the 5 pool objects are pr...
<python><multiprocessing><resources><python-multiprocessing><windows-11>
2024-10-04 21:46:16
2
377
Jay Mosk
79,055,872
9,827,719
With Python how can I specify which region (Location) that a Google Cloud Instance Template should be stored in?
<p>I have a code that can create Google Cloud Compute Engine Instance Templates, but I cannot manage to make it create the instance templates regional (for example in europe-north1).</p> <p><a href="https://i.sstatic.net/v83KFxso.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/v83KFxso.png" alt="enter im...
<python><google-cloud-platform><google-cloud-vm>
2024-10-04 21:27:11
1
1,400
Europa
79,055,835
10,034,073
Python Virtual Environment Error Configuring SDK in PyCharm
<p>I'm trying to create a Python virtual environment in PyCharm but keep getting this error:</p> <blockquote> <p><strong>Error Configuring SDK</strong></p> <p>Error configuring SDK: No flavor detected for B:/myproject/.venv/Scripts/python.exe sdk. Please make sure that B:\myproject\.venv\Scripts\python.exe is a valid h...
<python><pip><pycharm><python-venv>
2024-10-04 21:07:01
1
444
kviLL
79,055,738
1,812,993
Limit depth of model_dump in pydantic
<p>Pydantic will convert a complex model into a dictionary if you call model_dump. For example:</p> <pre><code>class Level3(BaseModel): deep_field: str class Level2(BaseModel): mid_field: str level3: Level3 class Level1(BaseModel): top_field: str level2: Level2 class DepthLimitedModel(BaseMode...
<python><serialization><pydantic>
2024-10-04 20:25:41
0
7,376
melchoir55
79,055,661
5,678,057
Pandas: Nested use of .loc returns different 'type' for the same field
<p>Why do I get 2 different data types while indexing using <code>.loc</code>, even though i retrieve a single value/cell.</p> <p>Background: I'm looking up values of <code>df_source</code> in <code>df_map</code>. I do not get string datatype for the matches when I do the below indexing.</p> <pre><code># Just for repro...
<python><pandas><indexing><pandas-loc>
2024-10-04 19:49:39
1
389
Salih
79,055,424
19,155,645
Transformers - ValueError: Asking to pad but the tokenizer does not have a padding token
<p>Im running a RAG pipeline using Haystack (<code>haystack-ai==2.6.0</code>) and HF model &amp; the transformers library (<code>transformers==4.39.3</code>). <br> This is how my code looks:</p> <pre><code>tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=mymodel, cache_dir=cache_dir) if tokenizer...
<python><padding><huggingface-transformers><tokenize><haystack>
2024-10-04 18:20:29
0
512
ArieAI
79,055,370
515,368
Disable short multi-line string concatenation in Ruff
<p>If I have an intentionally short multi-line string like this:</p> <pre class="lang-py prettyprint-override"><code>html += ( '&lt;p&gt;Regards,&lt;/p&gt;\n' '&lt;p&gt;Tom Cruise&lt;/p&gt;\n' ) </code></pre> <p>Ruff will automatically reformat as:</p> <pre class="lang-py prettyprint-override"><code>html += '&l...
<python><ruff>
2024-10-04 17:58:26
0
3,162
supermitch
79,055,149
3,475,434
Multiple dispatch based on object attribute types in python with multimethod
<p>I'm a Python noob having a tough time trying to implement multiple dispatch (based on object attributes types) using multimethod.</p> <p>To be more precise, as long as I use functions this works lovely</p> <pre class="lang-py prettyprint-override"><code> from dataclasses import dataclass from multimethod import mul...
<python><python-3.x><dispatch>
2024-10-04 16:28:23
0
3,253
Luca Braglia
79,054,914
10,517,777
Python generator implementation is not reducing memory consumption
<p>I have three json.gz files. Those three files contains different data (restaurants, menus and matchings) grouped by different Ids. I must read all of them and create new json files by Id with the respective data from those three files. I have one virtual machine and I have some memory restrictions when running my co...
<python><generator>
2024-10-04 15:19:55
1
364
sergioMoreno
79,054,907
1,429,549
Superset: error saving charts or dashboard
<p>I have just installed Superset on a brand new machine over Docker and everything works fine but I can't save a chart or dashboard. I always get &quot;Unable to save slice&quot; error message.</p> <p>I can save queries and datasources though without problem and if I access to a chart though a permalink I can see the ...
<python><docker><apache-superset>
2024-10-04 15:17:38
1
738
Coluccini
79,054,792
8,964,393
Apply pandas dictionary with gt/lt conditions as keys
<p>I have created the following pandas dataframe:</p> <pre><code>ds = {'col1':[1,2,2,3,4,5,5,6,7,8]} df = pd.DataFrame(data=ds) </code></pre> <p>The dataframe looks like this:</p> <pre><code>print(df) col1 0 1 1 2 2 2 3 3 4 4 5 5 6 5 7 6 8 7 9 8 </code></pre> <p>I have then ...
<python><pandas><dataframe><dictionary><calculated-columns>
2024-10-04 14:47:44
1
1,762
Giampaolo Levorato
79,054,570
561,243
Saving region properties from skimage.measure to a pickle file raises RecursionError: maximum recursion depth exceeded
<p>In my analysis code, I am performing some image properties analysis using skimage.measure.regionprops.</p> <p>In order to save processing time, I would like to save the region properties to a file and I was thinking to use pickle as I often do.</p> <p>Here is my piece of code.</p> <pre class="lang-py prettyprint-ove...
<python><pickle><scikit-image><recursionerror>
2024-10-04 13:39:51
0
367
toto
79,054,484
19,500,571
Add plotly graphs dynamically
<p>Say I have the following example that combines two Plotly graphs</p> <pre><code>import plotly.express as px import plotly.graph_objects as go df = px.data.iris() fig1 = px.line(df, x=&quot;sepal_width&quot;, y=&quot;sepal_length&quot;) fig1.update_traces(line=dict(color = 'rgba(50,50,50,0.2)')) fig2 = px.scatter(d...
<python><plotly>
2024-10-04 13:22:04
1
469
TylerD
79,054,106
2,381,348
pandas eval: creating column names with spaces giving odd names
<p>My <code>df</code> contains columns <code>m 1</code> and <code>n</code>.</p> <p>I was trying to create a duplicate of column <code>m 1</code> as <code>m 2</code> using <code>eval</code>. Came across <a href="https://stackoverflow.com/questions/50697536/pandas-query-function-not-working-with-spaces-in-column-names">t...
<python><pandas>
2024-10-04 11:45:28
2
3,551
RatDon
79,054,018
14,366,906
PyPlot.Table working with different colspans and rowspans
<p>I'm looking for a way to add columns that can span multiple rows, and rows that can span multiple columns.</p> <p>I currently have the code below to get the first row in.</p> <pre class="lang-py prettyprint-override"><code># Calculate log-scaled widths table_widths = [0.001, 0.002, 0.063, 2.0, 63.0, 150.0] log_table...
<python><matplotlib>
2024-10-04 11:18:16
1
335
Wessel van Leeuwen
79,053,898
7,347,911
prefect warning message regarding task performance for longer running tasks
<p>i have been getting the below warning message with tasks with larger run time most of my tasks take more than 10 seconds</p> <p>it says</p> <pre><code>Try wrapping large task parameters with `prefect.utilities.annotations.quote` for increased performance </code></pre> <p>how can i do that for better performance</p> ...
<python><orchestration><prefect>
2024-10-04 10:45:13
1
404
manoj
79,053,880
14,649,310
Create an SQLAlchemy table that only has maximum one entry
<p>I want to store a secret key encrypted and I want to ensure there is always either none or exactly one entry in this SQLAlchemy model/table. How can this be enforced?</p>
<python><postgresql><sqlalchemy>
2024-10-04 10:38:50
2
4,999
KZiovas
79,053,771
942,179
What exactly is a "seed package" in Python?
<p>In the context of virtual environments I often see people speaking of &quot;seed packages&quot;, e.g. <code>uv venv --seed</code> with help text <em>&quot;Install seed packages (one or more of: <code>pip</code>, <code>setuptools</code>, and <code>wheel</code>) into the virtual environment.&quot;</em> or <em>&quot;Yo...
<python><virtualenv><python-venv><uv>
2024-10-04 10:03:35
1
1,576
Elmar Zander
79,053,709
4,602,359
How to generate a flattened list of all members and types in a C++ struct or class?
<p>I’m trying to generate a flattened output of all the members and their types for a given C++ struct or class, including inherited members.</p> <p>For example, given the following classes:</p> <pre class="lang-cpp prettyprint-override"><code>class ParentClass { int a; std::string b; }; class MemberA { in...
<python><c++><reflection><doxygen>
2024-10-04 09:50:41
0
348
A. Ocannaille
79,053,433
13,606,345
Django serializer to convert list of dictionary keys to model fields
<p>I am using pandas <code>openpyxl</code> to read excel file in my project. After reading the excel file I end up with list of dictionaries. These dictionaries have keys such as &quot;Year 2024&quot;, &quot;Range&quot;, &quot;Main Point&quot;, and etc.</p> <p>I have a field in my Django app that has these fields such ...
<python><django><django-rest-framework><django-serializer>
2024-10-04 08:38:14
1
323
Burakhan Aksoy
79,053,320
10,710,625
Add an image in prompt for AzureOpenAI gpt4-mini?
<p>I am able to use the web interface of azure OpenAI studio in the chat playground to analyze images but I would like to do the same using python. It seems that it's not working and I could not (so far) find a reference online on how to include an image in the prompt. Could anyone please help or provide a reference on...
<python><large-language-model><azure-openai><gpt-4><gpt-4o-mini>
2024-10-04 07:59:47
0
739
the phoenix
79,053,161
17,973,259
How to load chat messages in batches in Django using StreamingHttpResponse?
<p>I'm working on a Django project that streams chat messages between two users using StreamingHttpResponse and async functions. I want to load messages in batches (e.g 20 at a time) instead of loading all the messages at once to optimize performance and reduce initial load time.</p> <p>Here’s my current view code:</p>...
<python><django><async-await>
2024-10-04 07:07:30
1
878
Alex
79,053,119
21,446,483
Testing async method with pytest does not show calls to patched method
<p>I'm currently writing some tests for a FastAPI middleware component using pytest. This component is a class-type middleware and works exactly as it should, very happy with it. However, when writing tests I'm trying to execute the <code>dispatch</code> method within the component to then make assertions on the output...
<python><pytest><fastapi><pytest-asyncio>
2024-10-04 06:47:18
1
332
Jesus Diaz Rivero
79,052,799
10,722,752
!pip install smartsheet-dataframe is not working, getting ModuleNotFoundError: No module named 'smartsheet' Error
<p>I need to read in data from smartsheet to pandas dataframe. I installed <code>smartsheet-dataframe</code> library, but when I try to import it, getting <code>ModuleNotFoundError: No module named 'smartsheet'</code>.</p> <pre><code>!pip install smartsheet-dataframe ... ... Downloading smartsheet_dataframe-0.3.4-py3-n...
<python><pandas><smartsheet-api>
2024-10-04 04:08:50
1
11,560
Karthik S
79,052,681
10,418,143
ValueError: If no `decoder_input_ids` or `decoder_inputs_embeds` are passed, `input_ids` cannot be `None`
<p>I am trying to get the decoder hidden state of the florence 2 model. I was following this <a href="https://huggingface.co/microsoft/Florence-2-large/blob/main/modeling_florence2.py" rel="nofollow noreferrer">https://huggingface.co/microsoft/Florence-2-large/blob/main/modeling_florence2.py</a> to understand the param...
<python><machine-learning><pytorch><huggingface-transformers><huggingface>
2024-10-04 02:40:48
0
352
user10418143
79,052,587
4,582,026
VS Code 1.94 - Run selection/line in Python terminal very slow
<p>I've just started using VSCode (moving over from Spyder) and I regularly run lines/selections from my code in the terminal.</p> <p>When I have a terminal open, shift + enter runs my selection in a new terminal and is incredibly slow.</p> <p>The below takes about 5 seconds to send</p> <pre><code> print(1) </code></pr...
<python><visual-studio-code>
2024-10-04 01:05:33
1
549
Vik
79,052,556
4,003,134
gradio how to hide a webcam interface
<p>In <strong>Python 3.10</strong> with <strong>gradio 4.44.1</strong> on <strong>Windows 10</strong>, I struggle to hide a webcam &quot;live&quot; image with a button click. Currently, I am stuck with the following code:</p> <pre class="lang-py prettyprint-override"><code>import gradio as gr import numpy as np def fl...
<python><gradio>
2024-10-04 00:32:06
1
1,029
x y
79,052,411
4,582,026
VSCode - shift+enter treatment
<p>I have VSCode installed in two windows machines, with the same extensions installed (Pylance, Python, and Python debugger).</p> <p>I'm getting different results when pressing shift+enter on a selection:</p> <ul> <li>On one machine, it runs the selection in the terminal (which is what I want).</li> <li>On the other m...
<python><visual-studio-code>
2024-10-03 22:51:24
0
549
Vik
79,052,337
1,336,758
Understanding a subclass of "TypedDict" with just one field defined
<p>Despite reading the <code>TypedDict</code> documentation and numerous examples, I can't understand the code-snippet below. I'm definitely missing something (a concept).</p> <p><code>MyClass</code> specifies one field (<code>messages</code>), but shouldn't it have at least two? For <code>key</code> and <code>value</c...
<python><python-typing>
2024-10-03 22:16:46
1
5,759
nmvega
79,052,322
5,635,892
Amplitude of FFT in python
<p>I have the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.fft import fft, fftfreq def polarization(t): f = x*np.cos(2*np.pi*omega*t)/np.sqrt(1+(x*np.cos(2*np.pi*omega*t))**2) return f omega = 100 x = 5 N = 10000 t_max = 1 t = np.linspace(0,t_max,N) yf = fft(p...
<python><fft>
2024-10-03 22:09:55
0
719
Silviu
79,052,117
6,471,140
huggingface model inference: ERROR: Flag 'minloglevel' was defined more than once (in files 'src/error.cc' and ..)
<p>I'm trying to use llama 3.1 70b from huggingface(end goal is to quantize it and deploy it in amazon <code>sagemaker</code>), but I'm facing:</p> <blockquote> <p>ERROR: Flag 'minloglevel' was defined more than once (in files 'src/error.cc' and 'home/conda/feedstock_root/build_artifacts/abseil-split_1720857154496/work...
<python><artificial-intelligence><large-language-model><huggingface><llama>
2024-10-03 20:46:31
1
3,554
Luis Leal
79,052,005
4,434,941
Error loading page with scrapy and scrapy playwright - Says to enable javascript
<p>I am trying to access a webpage with scrapy and scrapy-playwright, however, I keep getting a 'Please enable JS and disable any ad blocker' messaged coupled with a timeout error. I have tried a variety of solutions but none seem to have worked...</p> <pre><code>import scrapy from scrapy.selector import Selector from ...
<python><scrapy><playwright><scrapy-playwright>
2024-10-03 19:55:16
1
405
jay queue
79,051,885
23,260,297
styling dataframe with multi-index and export to excel
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'Counterparty': ['foo', 'fizz', 'fizz', 'fizz','fizz'], 'Commodity': ['bar', 'bar', 'bar', 'bar','bar'], 'DealType': ['Buy', 'Buy', 'Buy', 'Buy', 'Buy'], 'StartDate': ['07/01/2024', '09/01/2024', '10/01/2024', '11/01/202...
<python><pandas><dataframe>
2024-10-03 19:05:04
2
2,185
iBeMeltin
79,051,741
3,949,008
pandas.read_sas() fails when bad timestamps exist
<p>I have a file with some bad timestamps and the <code>read_sas</code> method in <code>pandas</code> fails. There seems to be no recourse. The file is read fine in R using the <code>haven</code> package, and the bad timestamps are identifiable.</p> <pre><code>df = pd.read_sas('my_sas_file.sas7bdat') Traceback (most r...
<python><pandas><sas><r-haven>
2024-10-03 18:12:46
1
10,535
Gopala
79,051,710
1,564,070
Rendering issue with ttk.TreeView
<p>I'm trying to use the ttk treeview widget. I'm able to create and populate it, and it seems to work properly. However it is rendering with a large empty &quot;column&quot; on the left side and I can't figure out what is causing it. I've verified that column(0) is the first column I defined so don't know where thi...
<python><tkinter><treeview><ttk>
2024-10-03 18:04:32
2
401
WV_Mapper
79,051,504
16,869,946
counting the number of success after certain date every year in Pandas using groupby cumsum
<p>I have a data frame that looks like</p> <pre><code>Date Student_ID Exam_Score 2020-12-24 1 79 2020-12-24 3 100 2020-12-24 4 88 2021-01-19 1 100 2021-01-19 2 100 2021-01-19 3 99 2021-01-19 4 72 2022-09...
<python><pandas><dataframe><group-by><cumsum>
2024-10-03 16:55:59
1
592
Ishigami
79,051,434
6,464,525
How can I dynamically define a function signature for pylance etc.?
<p>I am creating a framework built on <code>pydantic.BaseModel</code> that will manage the putting and getting of records from dynamodb.</p> <p>An example of a model is as follows:</p> <pre class="lang-py prettyprint-override"><code>class User(DynamoDanticBaseModel): user_id: str first_name: str @classmethod ...
<python><python-typing><pyright>
2024-10-03 16:35:49
1
344
hi im Bacon
79,051,361
54,873
What is the most efficient way in Pandas to search for dates entries in a dataframe before or after a given date?
<p>I am trying to determine whether a given set of obstetrics patients have recieved their flu shots in the current flu season.</p> <p>That is, I have essentially three dataframes:</p> <pre><code>&gt;&gt;&gt; edds name expected_delivery_date 0 Susan 2024-12-01 1 Susan 2023-10-01 2 Marie ...
<python><pandas>
2024-10-03 16:14:05
1
10,076
YGA
79,051,188
12,131,013
Expression replacement with Wildcard variable only works in isolation
<p>I am trying to replace a subexpression. There are many questions on this topic, but I've found that using a wildcard variable as a multiplier seems to work in isolation but not when there are extra terms. For example:</p> <pre class="lang-py prettyprint-override"><code>import sympy as smp x, y, z, a = smp.symbols(&...
<python><sympy>
2024-10-03 15:21:17
1
9,583
jared
79,051,146
14,843,373
Pandas apply function behaving differently based on input size?
<p>I have a function which works fine with a tiny Pandas Dataframe and returns the adjustments as expected, but when I apply it to a non-test Dataframe, which is only a small df (300 x 20), it gets completely messed up.</p> <p>Using the example below as a reference, it would populate columns 3 - 7 with the same list of...
<python><pandas><dataframe>
2024-10-03 15:11:39
2
361
beautysleep
79,051,021
11,857,547
Why "PyRun_SimpleString("from PIL import Image")" does not work in debug mode?
<p>I'm writing a c++ program that use Python library EasyOCR to read some text. I wrote such code:</p> <pre class="lang-cpp prettyprint-override"><code>Py_Initialize(); PyRun_SimpleString(&quot;import sys&quot;); PyRun_SimpleString(&quot;import easyocr&quot;); //Other codes </code></pre> <p>When I run it in <code>Relea...
<python><c++><python-imaging-library><python-3.11><easyocr>
2024-10-03 14:35:39
0
305
Object Unknown
79,051,008
19,155,645
RAG pipeline using Haystack - error with Pipeline embedder
<p>I'm trying to run a RAG pipeline using Haystack (and Milvus) on my cluster instance using python (3.10.12).<br> The Imports and relevant packages I have in this env are shown at the end of this question.</p> <p>my code is: <br></p> <ol> <li>model embedding &amp; generator functions:</li> </ol> <pre><code>@component ...
<python><rag><haystack>
2024-10-03 14:30:59
1
512
ArieAI
79,050,855
23,260,297
add specific values in dataframe with groupby.agg
<p>I am processing files that contain data in an unusable format. After processing one of the files I am left with a dataframe and a singular value.</p> <p>The dataframe looks like this:</p> <pre><code> df = pd.DataFrame({ 'A': ['foo', 'foo', 'foo', 'fizz', 'fizz', 'fizz', 'fizz'], 'B': ['bar', 'bar', '...
<python><pandas>
2024-10-03 13:51:07
1
2,185
iBeMeltin
79,050,619
10,430,926
How do I manage a python subprocess with an infinite loop
<p>I want to read input from a subprocess in python, interact with it, see the results of that interaction, and then kill the process. I have the following parent and child processes.</p> <pre><code>child.py from random import randint x = 1 while x &lt; 9: x = randint(0, 10) print(&quot;weeeee got&quot;, x) ...
<python><python-3.x><curio>
2024-10-03 12:52:39
1
557
Edward
79,050,437
12,415,855
Parse data from local html-file using bs4?
<p>i try to parse a local html-document using the following code -</p> <pre><code>import os, sys from bs4 import BeautifulSoup path = os.path.abspath(os.path.dirname(sys.argv[0])) fnHTML = os.path.join(path, &quot;inp.html&quot;) page = open(fnHTML) soup = BeautifulSoup (page.read(), 'lxml') worker = soup.find(&qu...
<python><beautifulsoup>
2024-10-03 11:57:33
2
1,515
Rapid1898
79,050,277
9,681,081
Create hybrid table with Snowflake SQLAlchemy
<p>I want to add Snowflake <a href="https://docs.snowflake.com/en/user-guide/tables-hybrid" rel="nofollow noreferrer">hybrid tables</a> to my database schema using SQLAlchemy.</p> <p>Per <a href="https://github.com/snowflakedb/snowflake-sqlalchemy/issues/461" rel="nofollow noreferrer">this issue</a>, support for hybrid...
<python><sqlalchemy><snowflake-cloud-data-platform>
2024-10-03 11:15:36
1
2,273
Roméo Després
79,050,009
4,751,700
Typehint *args for variable length heterogenous return values like asyncio.gather()
<p>I'm having some trouble with the typesystem here. I need something like <code>asyncio.gather()</code> where the return value is the return values of the coroutines in the same order as given in the args.</p> <pre class="lang-py prettyprint-override"><code>async def f1() -&gt; int: ... async def f2() -&gt; str: ... a...
<python><python-typing>
2024-10-03 09:54:50
2
391
fanta fles
79,049,807
6,221,742
Genetic algorithm for kubernetes allocation
<p>I am trying to allocate Kubernetes pods to nodes using a genetic algorithm, where each pod is assigned to one node. Below is my implementation:</p> <pre><code>from string import ascii_lowercase import numpy as np import random from itertools import compress import math import pandas as pd import random def create_p...
<python><algorithm><optimization><genetic-algorithm>
2024-10-03 09:03:13
1
339
AndCh
79,049,699
14,368,551
Why do i get "ImportError: sys.meta_path is None, Python is likely shutting down" when trying to run Milvus
<p>I have very simple code:</p> <pre><code>from pymilvus import MilvusClient client = MilvusClient(&quot;milvus.db&quot;) print(&quot;hello&quot;) </code></pre> <p>which prints out this:</p> <pre><code>hello Exception ignored in: &lt;function ServerManager.__del__ at 0x7f1b80758ea0&gt; Traceback (most recent call last...
<python><vector-database><milvus><rag>
2024-10-03 08:25:41
2
573
VanechikSpace
79,049,608
3,083,022
Inconsistent ratings when drawing using Trueskill
<p>I'm using <a href="https://trueskill.org/" rel="nofollow noreferrer">Trueskill</a> to try to create a rating system for a tennis tournament among my friends. Games are 1v1, so I'm trying out the following:</p> <pre><code>from trueskill import Rating, quality_1vs1, rate_1vs1 alice, bob = Rating(25), Rating(25) print...
<python><ranking><rating><leaderboard><rating-system>
2024-10-03 07:56:34
1
567
user3083022
79,049,047
17,889,492
Plotly wireframe running along both directions
<p>I wanted to create a wireframe surface in plotly. However the following code only runs the wires along one axis. How do I convert these parallel wires into a mesh?</p> <pre><code>import numpy as np import plotly.graph_objects as go import plotly.io as pio x = np.linspace(-5, 5, 20) y = np.linspace(-5, 5, 20) x, y =...
<python><plotly>
2024-10-03 03:42:28
1
526
R Walser
79,048,982
2,838,281
PyArrow error while using Streamlit agraph component
<p>While running 'https://github.com/ChrisDelClea/streamlit-agraph/examples/karate_club_graph.py' as is, got following error:</p> <pre><code>StreamlitAPIException: To use Custom Components in Streamlit, you need to install PyArrow. To do so locally: pip install pyarrow And if you're using Streamlit Cloud, add &quot;p...
<python><streamlit><pyarrow>
2024-10-03 02:42:48
1
505
Yogesh Haribhau Kulkarni
79,048,979
1,413,856
Change terminal command colour in PyCharm
<p>I’m running a fairly current version of PyCharm on Windows 10. It’s an older version of Windows, so I can’t run the very latest PyCharm.</p> <p>I have chosen a light them, which works well enough until it comes to the Terminal. The terminal, it appears uses PowerShell. The real problem is that commands, such as <cod...
<python><powershell><pycharm>
2024-10-03 02:40:56
2
16,921
Manngo
79,048,862
17,005,119
Python decode() mangles bytes object (either returns empty string, or only last line of text)
<p>For the life of me, I can't figure out what's happening here...</p> <p>I'm capturing the output of a command line utility via <code>subprocess.popen()</code>, and processing the stdout line by line via <code>process.stdout.readline()</code> (which returns a bytes object). I want to convert each stdout line to a stri...
<python><python-3.x><decode>
2024-10-03 01:17:18
1
617
bikz
79,048,641
12,011,020
Python polars write / read csv handling of linebreaks (eol)
<p>I want to read in mockup data that contains a linebreak (eol) char. Here I utilize the faker package to simulate some data.</p> <p>I initialize a polars.DataFrame and write it to .csv. When I later on try to read the csv (see below), I receive an error, which indicates that the match between the column-name, the dty...
<python><dataframe><csv><python-polars><eol>
2024-10-02 22:32:39
0
491
SysRIP
79,048,626
1,306,779
How can I run a loop forever until a termination condition or for a fixed number of iterations?
<p>I have a program that runs an operation either a fixed number of times, or &quot;forever&quot; until some condition is reached. The implementation was fine, but I was having trouble getting a code structure I was happy with.</p> <p>My initial logic boiled down to:</p> <pre><code>max_iterations = 5 # Either an intege...
<python><python-3.x><loops><logic>
2024-10-02 22:24:59
3
1,575
jfowkes
79,048,606
9,213,069
Poetry init in Google Colab is running for hour
<p>I'm trying to run langgraph using my Google Colab. So I used following command to install <code>poetry</code> in my Google Colab.</p> <pre><code>from google.colab import drive drive.mount('/content/gdrive') # Move in your Drive %cd /content/gdrive/MyDrive/ # Create and move in the new project directory !rm -rf refle...
<python><google-colaboratory><python-poetry><langgraph>
2024-10-02 22:13:25
1
883
Tanvi Mirza
79,048,410
6,691,064
Error in pip command - directory not installable
<p>I am new to python and trying to setup using this-</p> <p><a href="https://github.com/facebookresearch/CodeGen/blob/main/install_env.sh" rel="nofollow noreferrer">https://github.com/facebookresearch/CodeGen/blob/main/install_env.sh</a></p> <p>in google collab notebook.</p> <p>But, it is throwing error in the below l...
<python><pip>
2024-10-02 20:40:13
1
1,509
vikash singh
79,048,003
20,591,261
Following and Count of State Changes Between Columns in Polars
<p>I have a dataframe with multiple IDs and corresponding states. I want to analyze how the states have changed over time and present this information effectively.</p> <p>Here is an example:</p> <pre><code>import polars as pl df = pl.DataFrame({ &quot;ID&quot;: [1, 2, 3], &quot;T0&quot;: [&quot;A&quot;, &quot;...
<python><python-polars>
2024-10-02 18:13:54
1
1,195
Simon
79,047,912
8,536,621
Testing constraints of pydantic models
<p>Say I have a model</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class Book(BaseModel): name: str description: str = Field(min_length=1, max_length=64, pattern=&quot;^[a-z]+$&quot;) </code></pre> <p>I would like to write unit tests ensuring the model has properly been define...
<python><unit-testing><pydantic><pydantic-v2>
2024-10-02 17:38:17
1
818
Abel
79,047,909
7,215,853
How to ensure compatibility between my local dev environment and AWS Lambda runtime (AWS CDK V2)
<p>I am currently having an issue with Python packages on AWS Lambda.</p> <p>I have defined a Lambda layer like this:</p> <pre><code> my_layer = _lambda.LayerVersion( self, &quot;MyLayer&quot;, code=_lambda.Code.from_asset(&quot;layer_code_directory&quot;), compatible_runtimes=[_lambda.R...
<python><amazon-web-services><aws-lambda><aws-cdk>
2024-10-02 17:38:04
2
320
MrTony
79,047,784
7,116,385
transformers[agents] library doesn't work properly on Linux systems
<p>I'm following a huggingface tutorial <a href="https://huggingface.co/docs/transformers/en/agents" rel="nofollow noreferrer">Huggingface agent 101</a>. I installed the library by executing <code>pip install transformers[agents]</code> on colab and when I imported the tool using <code>from transformers import tool</co...
<python><huggingface-transformers>
2024-10-02 16:55:41
0
467
Ashish Johnson
79,047,727
610,569
How to implement SwiGLU activation? Why does SwiGLU takes in two tensors?
<p>The SwiGLU variant introduced in <a href="https://arxiv.org/pdf/2002.05202" rel="nofollow noreferrer">https://arxiv.org/pdf/2002.05202</a> is simply &quot;divine benevolence&quot; and the implementation on Flash-Attention just works out of the box <a href="https://github.com/Dao-AILab/flash-attention/tree/main" rel=...
<python><deep-learning><pytorch><large-language-model><flash-attn>
2024-10-02 16:39:09
1
123,325
alvas
79,047,570
8,564,676
Kafka external client receives other name than in ADVERTISED_LISTENERS
<p>On a local network, I have a broker at cgw.local and a client at rpi.local, connected to the same switch. No matter what I put into <code>kafka.advertised.listeners</code>: <code>PLAINTEXT://cgw.local:9092</code> or <code>PLAINTEXT://20.5.28.284:9092</code>, or whether the (Python's) client <code>BOOTSTRAP_SERVERS</...
<python><apache-kafka><kafka-python>
2024-10-02 15:55:09
0
513
scriptfoo
79,047,541
446,786
Making instances of Django records with a through model
<p>Let's say you have a concept of a Battle, and in that battle there are Players and Enemies. The players are a simple ManyToMany, but Enemies require a Through model, because if there's a DB entry for &quot;Goblin&quot;, players need to fight an INSTANCE of the Goblin model. Players may fight many Goblins, and each ...
<python><django><database><django-models><orm>
2024-10-02 15:47:42
1
311
Josh
79,047,285
5,924,007
opentelemetry.instrumentation.instrumentor - DependencyConflict: requested: "psycopg2 >= 2.7.3.1" but found: "None"
<p>Has someone tried to get the OTEL for the PostgresSQL queries ? We have a fass-lambda that makes simple queries We are trying get info about how long the query took to execute by adding opentelemetry-instrumentation-psycopg2. Adding psycopg2 to requirements.txt doesn't work. We get the following error:</p> <pre><co...
<python><psycopg2><open-telemetry>
2024-10-02 14:44:09
0
4,391
Pritam Bohra
79,047,250
2,955,541
Numba cuda.jit and njit giving different results
<p>In the following example, I have a simple CPU function:</p> <pre><code>import numpy as np from numba import njit, cuda @njit def cpu_func(a, b, c, d): for i in range(len(a)): for l in range(d[i], 0, -1): for j in range(l): a[i, j] = (b[i] * a[i, j] + (1.0 - b[i]) * a[i, j + 1...
<python><numpy><cuda><precision><numba>
2024-10-02 14:35:47
1
6,989
slaw
79,047,117
3,663,124
UV showing warning of incorrect Python version
<p>I'm using uv to manage my Python version and dependencies in a project I'm working on.</p> <p>When I run <code>uv run pytest</code> to test said project I get the following:</p> <pre><code>============================================================================= test session starts ==============================...
<python><pytest><uv>
2024-10-02 14:03:29
2
1,402
fedest
79,047,095
4,451,315
Does `row_number() over ()` have any guarantees when called on an in-memory dataframe?
<p>If I run</p> <pre class="lang-py prettyprint-override"><code>duckdb.sql('select *, row_number() over () as index from df') </code></pre> <p>on a pandas/Polars dataframe, then does the row number always enumerate the rows in order of appearance?</p> <p>This seems to be the case:</p> <pre class="lang-py prettyprint-ov...
<python><duckdb>
2024-10-02 13:57:41
0
11,062
ignoring_gravity
79,047,058
5,993,062
How can I bind a user license to a unique fingerprint in an app running in Docker container?
<p>I'm working on a Python application deployed inside a Docker container, and I need to bind a user's license to a unique fingerprint. The goal is to ensure that each license can only be used by one instance of the application at a time.</p> <p>However, I cannot use any hardware information (e.g. using <code>lshw</cod...
<python><docker><licensing><fingerprint>
2024-10-02 13:50:09
1
469
Steve Lukis
79,046,766
9,609,843
How to cancel long running asyncio.Task?
<p>I have the following example of code:</p> <pre class="lang-py prettyprint-override"><code>import asyncio import concurrent.futures import functools import time async def run_till_first_success(tasks, timeout=None): results = [] exceptions = [] while tasks: try: async with asyncio.ti...
<python><python-asyncio>
2024-10-02 12:32:19
1
8,600
sanyassh
79,046,568
4,041,117
Netgraph Animation — how to display frame numbers
<p>I'm trying to add a frame number to a simulation visualization modified from <a href="https://netgraph.readthedocs.io/en/latest/sphinx_gallery_animations/plot_02_animate_edges.html#sphx-glr-sphinx-gallery-animations-plot-02-animate-edges-py" rel="nofollow noreferrer">here</a>. Is there any simple way to add a frame ...
<python><matplotlib><frame><netgraph>
2024-10-02 11:42:30
1
481
carpediem
79,046,498
8,379,035
How can i correctly format string widths inside of a discord Embed?
<p>I’m working on a Discord bot using the <code>discord.py</code> library and encountered an issue where the printed console output is correct, but the output in the Discord embed is not displaying as expected - the String width is not correct.</p> <p>Here is the relevant part of my code:</p> <pre class="lang-py pretty...
<python><string><discord><discord.py><monospace>
2024-10-02 11:26:42
1
891
Razzer
79,046,492
12,962,917
How may I free memory allocated by foreign C calls in Python?
<p>TlDr: my Python code makes external C library calls. Internally, the Python scripts use a few hundred Mb of RAM but the external C calls are using many Gb, even when I no longer need the data they have outputted. I would like to know how to free this memory in Python - I don't fully understand how Python memory work...
<python><c><memory-management><memory-leaks><sage>
2024-10-02 11:24:25
0
381
FShrike