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,731,369
4,948,889
Sending message to private Telegram channel fails using Bot API python
<p>I have tried sending message to a telegram channel using Telegram's BOT API with Python 3.11.0.</p> <p>At first I have tried making the channel Public and the code worked fine:</p> <pre><code>import requests # Replace YOUR_BOT_TOKEN with your actual bot token bot_token = BOT_API_KEY # Replace YOUR_CHAT_ID with the...
<python><python-3.x><python-requests><telegram><telegram-bot>
2023-03-14 09:40:10
1
7,303
Jaffer Wilson
75,731,226
6,734,243
How to create a custom sphinx directive that uses the image directive?
<p>I need to display a bunch of image that are stored in a json file (the list of our sponsors) like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;toto&quot;: &quot;path/to/image&quot;, &quot;tutu&quot;: &quot;path/to/image&quot;, ... } </code></pre> <p>I have colleagues that are not very go...
<python><python-sphinx>
2023-03-14 09:26:08
1
2,670
Pierrick Rambaud
75,731,212
14,169,836
Cumulative subtraction with two columns in pandas
<p>I have the table where I have 2 values for each day. I need to subtract the Val1 - Val2 row by row. E.g.:</p> <pre><code> day Val1 Val2 1 20230310 100 50 2 20230311 NaN 10 3 20230312 NaN 5 4 20230313 NaN -3 5 20230314 NaN 40 </code></pre> <p>How it sho...
<python><pandas><subtraction>
2023-03-14 09:25:00
1
329
Ulewsky
75,730,973
1,649,021
Converting string value to Boolean for dataframe
<p>Trying to easily convert values in my dataframe to Booleans. Each column can contain values like &quot;YES&quot;, &quot;NO&quot; or &quot;NaN&quot;.</p> <p>Converted the values with numpy to an ndarray in a list comprehension but if I convert it to a dataframe I get the error</p> <pre><code>ValueError: 5 columns pas...
<python><pandas><dataframe>
2023-03-14 09:02:50
0
5,077
Mark Molina
75,730,853
12,871,587
Keep only duplicated rows with a subset
<p>I have a dataframe that I'd like to explore and look only the duplicated rows based on two or more columns.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({&quot;A&quot;: [1, 6, 5, 4, 5, 6], &quot;B&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &qu...
<python><dataframe><python-polars>
2023-03-14 08:49:27
2
713
miroslaavi
75,730,699
13,423,321
How to turn off sqlite json query with JSON_QUOTE? There are different between SQLAlchemy's sqlite and mysql json query
<p>Common code</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, Integer, JSON Base = declarative_base() class Person(Base): __tablename__ = 'person' id = Column(In...
<python><mysql><json><sqlite><sqlalchemy>
2023-03-14 08:33:54
1
1,127
XerCis
75,730,659
8,428,347
AttributeError: /src/libmi.so: undefined symbol: logarithm
<p>I've tried to call function on C/C++ from python3 code and get the error from header. Earlier this C/C++ function could be imported in ppython works, but I forget how it was done.</p> <p>C/C++ function:</p> <pre><code>#ifdef __cplusplus extern &quot;C&quot; double logarithm(unsigned a) #else double logarithm(unsigne...
<python><c++><dll><dllimport>
2023-03-14 08:29:33
1
343
volkoshkursk
75,730,605
14,014,925
Visual Studio Code Debugger not being able to import modules from my Conda environment
<p>I'm trying to use the VS Code Python debugger with my Conda environment. If I run my code through the terminal or pressing the play button, it runs correctly. However, if I try to debug it, when I import an external module like pandas or numpy, I get</p> <pre><code>ModuleNotFoundError: No module named 'pandas' </cod...
<python><visual-studio-code><anaconda><conda><vscode-debugger>
2023-03-14 08:23:45
1
345
ignacioct
75,730,596
11,198,558
How to start multiple faust app in the same time?
<p>I'm new user of Faust and don't know how to fix the problem when I ran 3 faust apps in the same time. Specifically:</p> <p>I have 3 python file, In each, I run 1 service for listening from kafka server. Each file contains code as below, the different in each file is just the TOPIC_INPUT name.</p> <pre><code>app = fa...
<python><apache-kafka><faust>
2023-03-14 08:23:14
1
981
ShanN
75,730,577
12,319,746
Cannot send mail from inside a function
<pre><code>def send_mail(): recv = os.environ.get('mail_username') sender = 'alerts@.com' receivers = [recv] message = f&quot;&quot;&quot;From: QA-Security Gate Alerts &lt;alerts@.com&gt; To: To Person {recv} Subject: Azure function down Check Logs &quot;&quot;&quot; try: ...
<python>
2023-03-14 08:21:04
1
2,247
Abhishek Rai
75,730,369
6,797,250
Transforming pandas data frame. Sort of melting
<p>I have this data frame:</p> <pre class="lang-py prettyprint-override"><code>pd.DataFrame({'day': [1, 1, 2, 2], 'category': ['a', 'b', 'a', 'b'], 'min_feature1': [1, 2, 3, 4], 'max_feature1': [8, 9, 10, 11], 'min_feature2': [2, 3, 4, 5], 'max_feature2': [6, 9, 12, 13]}) </code></pre> <p>Th...
<python><pandas><dataframe>
2023-03-14 07:57:58
3
3,871
Andrey Lukyanenko
75,730,352
221,270
cx_Oracle config dsn
<p>I want to connect to an Oracle Apex table via Python to update the table and insert new data, what must I enter for the dsn parameter, if my workspace is under:</p> <pre><code>https://apex.oracle.com/pls/apex/r/meteor_sdr import cx_Oracle # Establish the database connection connection = cx_Oracle.connect(user=&quot...
<python><oracle-apex><cx-oracle>
2023-03-14 07:56:14
0
2,520
honeymoon
75,730,243
11,572,712
from pm4py.objects.log.util import func as functools -> ImportError
<p>I am running this code to import a module:</p> <pre><code>from pm4py.objects.log.util import func as functools </code></pre> <p>And get this ImportError:</p> <pre><code>ImportError Traceback (most recent call last) &lt;ipython-input-15-d14af87451f6&gt; in &lt;module&gt; 1 import p...
<python><importerror>
2023-03-14 07:44:32
1
1,508
Tobitor
75,730,103
21,295,456
How to continue to further train a pre-trained YOLOv8 model
<p>I've trained a YOLOv8 model for object detection with 4 classes on a custom dataset.</p> <p>Now I want to train it to detect more classes by increasing my dataset.</p> <p>Instead of training the model from the start can I further train it specifically on the new dataset?</p>
<python><machine-learning><object-detection><yolo>
2023-03-14 07:23:23
2
339
akashKP
75,729,807
4,490,974
Speech to Text - recognise the speaker's
<p>I am having an issue where we want to transcribe some audio of a press conference.</p> <p>However it is not picking up when the speakers change.</p> <p>For this demo I'll use a YouTube press conference (our script downloads it as mp3) <a href="https://www.youtube.com/watch?v=3fFkMrTYZTs" rel="nofollow noreferrer">ht...
<python><google-speech-to-text-api>
2023-03-14 06:41:33
1
895
Russell Harrower
75,729,733
14,109,040
Replace values in pandas columns based on starting value of column name
<p>I have a dataframe with the following structure:</p> <pre><code> Index1 Index2 -2 -1 0 1 2 -1 ph -2 ph 1 ph 2 ph 0 A W 0 0 28 29 18 -28 -28 1 -10 1 B X 0 20 26 21 27 -6 -26 -5 1 2 C Y 19 20 20 17 17 0 -1 -3 -3 3 ...
<python><pandas>
2023-03-14 06:30:09
1
712
z star
75,729,449
11,649,397
How to let producer know that consumer finishes work in python
<p>Hi I want to paralyze the process of reading and analyzing multiple text files. So I have a producer say <strong>Producer</strong> and two consumers <strong>TextAnalyzer A</strong> and <strong>TextAnalyzer B</strong>.</p> <p><strong>Producer</strong> has a RequstQueue which contains tasks for <strong>TextAnalyzer A<...
<python><multithreading><python-multithreading><producer-consumer><condition-variable>
2023-03-14 05:42:25
1
353
takanoha
75,729,285
9,906,395
Pandas: Find the left-most value in a pandas dataframe followed by all 1s
<p>I have the following dataset</p> <pre><code>data = {'ID': ['A', 'B', 'C', 'D'], '2012': [0, 1, 1, 1], '2013': [0, 0, 1, 1], '2014': [0, 0, 0, 1], '2015': [0, 0, 1, 1], '2016': [0, 0, 1, 0], '2017': [1, 0, 1,1]} df = pd.DataFrame(data) </code></pre> <p>For each ...
<python><pandas><sum><row>
2023-03-14 05:07:48
1
1,122
Filippo Sebastio
75,729,249
346,977
Pandas, timedeltas, and dividing by zero
<p><strong>Update: Apologies for the confusion this question caused: The issue was that the <code>timedelta</code> fields I was looking at had been cast into pandas as (non-timedelta) objects. Recasting them to time deltas resolved the issue</strong></p> <p>I have the following pandas dataframe:</p> <div class="s-table...
<python><pandas>
2023-03-14 05:00:43
2
12,635
PlankTon
75,729,220
5,302,323
Running all python codes saved in a folder from Jupyter Notebook
<p>Is there any python code I can use to automatically detect all ipynb files saved inside a specific folder and run them sequentially?</p> <p>I can identify them all using this function:</p> <pre class="lang-py prettyprint-override"><code>path = glob.iglob(f&quot;/Users/[...]&quot;) </code></pre> <p>But unfortunately ...
<python>
2023-03-14 04:56:04
1
365
Cla Rosie
75,729,192
6,451,136
Argon2 hash key output is over 32 bytes
<p>I am learning cryptography and started a simple project where I intend on using <code>Argon2</code> to hash my password with a randomly generated salt and then use this hash to generate cipher text and encrypt data using AES algorithm.</p> <p>However, my hash always seems to be over 32 bytes.</p> <p>For Hash key gen...
<python><encryption><cryptography><argon><argon2-cffi>
2023-03-14 04:50:29
0
345
Varun Pius Rodrigues
75,729,172
4,616,611
Creating nested json with list from pandas dataframe
<p>I have a DataFrame with these columns: <code>id, jan_x, jan_y, feb_x, feb_y, ..., dec_x, dec_y</code> that I would like export as a json that is structured like this:</p> <pre><code>{ &quot;id1&quot;: [ [jan_x, feb_x, ..., dec_x], [jan_y, feb_y, ..., dec_y] ], &quot;id2&quot;: [ [...
<python><json><pandas><parsing>
2023-03-14 04:47:52
2
1,669
Teodorico Levoff
75,729,141
14,109,040
Differencing all other(not selected) columns in a dataframe by another column
<p>I have a data frame with the following structure.</p> <pre><code> Index1 Index2 -2 -1 0 1 2 0 A W 20 25 28 29 18 1 B X 21 20 26 21 27 2 C Y 19 19 20 17 17 3 D Z 18 17 15 18 18 </code></pre> <p>I want to subtract the '0' column from all columns exce...
<python><python-3.x><pandas>
2023-03-14 04:41:33
1
712
z star
75,729,116
4,082,104
How to get numpy to interpret object array slice as single array?
<p>When you ask Numpy to make an array out of a collection including arbitrary objects, it will create an array of &quot;object&quot; type, which allows you to use index slicing across those objects, but since the object itself is unknown to numpy, you cannot index into the object in one go (even if that particular obj...
<python><numpy>
2023-03-14 04:34:44
1
6,060
Multihunter
75,728,785
5,059,995
Conflicting module dependence in python project
<p>ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. cosmic-ray 8.3.5 requires virtualenv&lt;=16.7.10, but you have virtualenv 20.21.0 which is incompatible.</p> <p>Cosmic-ray uses very old versi...
<python><dependencies><mutation-testing>
2023-03-14 03:12:32
1
311
Dipu Krishnan
75,728,717
16,971,617
Can i initialize optimizer before changing the last layer of my model
<p>Say I want to change the last layer of my code but my optimizer is defined on the top of my scripts, what is a better practise?</p> <pre><code>batch_size = 8 learning_rate = 2e-4 num_epochs = 100 cnn = models.resnet18(weights='DEFAULT') loss_func = nn.CrossEntropyLoss() optimizer = optim.Adam(cnn.parameters(), lr=l...
<python><pytorch>
2023-03-14 02:56:58
1
539
user16971617
75,728,582
4,390,160
Visibility of superclass constructor parameters in subclass constructor
<p>Consider this example:</p> <pre><code>class Foo: def __init__(self, bar: int, baz: str): self.bar = bar self.baz = baz class SubFoo(Foo): def __init__(self, qux: float, *args, **kwargs): super().__init__(*args, **kwargs) self.qux = qux some_sub_foo = SubFoo(1.0, 3, 'test')...
<python><oop>
2023-03-14 02:25:30
2
32,399
Grismar
75,728,510
736,312
Why does re.findall return a list of tuples containing empty strings but re.finditer works correctly?
<p>I am using python 3.9.13 version.<br> I am trying to use the findall function from re library but I am getting empty results.</p> <p>The regex I am using is:<br></p> <pre><code>_regex = re.compile(r&quot;(?:)0\d{1,4}(?:-?\d{2,4}-?\d{2,4}|\d{8}|\d(-)?\d{2,4}(-)?\d{3,4})&quot;) </code></pre> <p>I am testing that on th...
<python><python-re>
2023-03-14 02:09:48
1
796
Toyo
75,728,476
8,391,698
How to save HappyTransformer model in specified directory instead of ~/.cache
<p>I have this code that saved <a href="https://happytransformer.com" rel="nofollow noreferrer">HappyTransformer</a> model in <code>.cache/</code> directory by default</p> <pre><code>from happytransformer import HappyTextToText, TTSettings happy_tt = HappyTextToText(model_type= &quot;gpt&quot;) </code></pre> <p>I would...
<python><huggingface-transformers><huggingface-datasets>
2023-03-14 02:01:29
0
5,189
littleworth
75,728,463
7,742,405
Json data to raw data
<p>I need help from you, I need to transform this JSON data into raw data, but I don’t want to use a lot of for to iterate above this json, so do you guys have some idea how to do that in a better way?</p> <p>But I don't know how to do that in a &quot;easy&quot; way, I don't want to <code>for: for: for: for</code></p> ...
<python><json><csv>
2023-03-14 01:57:00
2
449
Oracy Martos
75,728,387
6,379,197
SGD Optimizer Not Working on cost function
<p>I wanted to make own neural network for Speech data set and for that using tensorflow.I am writing the code imported library and dataset then done one hot encoding and after all done the weights and baises assignment and then done the forward propagation with the random values and for back propagation and cost minim...
<python><tensorflow><speech-recognition><sgd>
2023-03-14 01:37:43
0
2,230
Sultan Ahmed
75,728,358
610,569
Is there a efficient way to prepend a list from items from another list?
<p>Given two list, the goal is to append the items from the 2nd list to the 1st and return the matrix of lists, e.g.</p> <pre><code>x = [1, 2, 3, 4, 5] y = [123, 456] # m no. of items def func(x, y): return [[i] + x for i in y] func(x, y) </code></pre> <p>[out]:</p> <pre><code>[[123, 1, 2, 3, 4, 5], [456, 1, 2, 3,...
<python><list><vectorization><prepend>
2023-03-14 01:30:08
1
123,325
alvas
75,728,328
6,676,101
In python, if a file opened using the `w` access flag opened using ASCII-encoding, UTF-8, Unicode, or something else?
<p>In python, if a file opened using the <code>w</code> access flag will the data written to file be:</p> <blockquote> <ul> <li>ASCII-encoded</li> <li>encoded using the UTF-8 scheme</li> <li>encoded using some other scheme?</li> </ul> </blockquote> <p>If it is platform or system specific, how do we find out which encod...
<python><python-3.x><file-io><io><output>
2023-03-14 01:24:45
1
4,700
Toothpick Anemone
75,728,204
9,599,508
Pythonic way to encode UTF-8 strings to ASCII/Hex and back again?
<p>I am using a black-box database to store objects from my python code which can only store ASCII characters. Let's assume this database cannot be swapped in for another, more friendly one. Unfortunately, the data I need to store is in UTF-8 and contains non-english characters, so simply converting my strings to ASCII...
<python><character-encoding>
2023-03-14 00:59:37
1
302
Mr. T
75,728,104
10,807,390
How do I make a correlation matrix for each subset of a column of my pandas dataframe?
<p>Here’s the head of my dataframe:</p> <pre><code> </code></pre> <p>There are 100 different loggers and 10 different years. I want to subset the table by logger and find the Pearson correlation values for year by avg_max_temp, avg_min_temp, and tot_precipitation for each logger. Because there are 100 loggers, I’d expe...
<python><pandas><dataframe><pearson-correlation>
2023-03-14 00:36:10
1
427
Tom
75,727,884
12,609,881
Manually create span with start and end timestamps - OpenTelemetry Python
<p>I am trying to trace the execution of a task in Celery through the Publisher -&gt; Queue -&gt; Consumer lifecycle. I am using OpenTelemetry 1.16.0 in Python 3.9.15 in order to instrument the application. I already know how to propagate a trace through the Queue as described in the answers to this stackoverflow quest...
<python><open-telemetry>
2023-03-13 23:48:46
1
911
Matthew Thomas
75,727,856
4,764,787
Send SIGINT to subprocess and also see output
<p>In a celery task, I am launching a <code>subprocess</code> and need (1) to be able to send a <code>SIGINT</code> while (2) also having access to the subprocess's stdout and stderr. I am able to do one or the other, but not both simultaneously.</p> <p>I can send <code>SIGINT</code> when the command in subprocess is ...
<python>
2023-03-13 23:41:26
1
381
Jaime Salazar
75,727,762
145,129
Graphing O(n^2) Function Using Quadratic Algorithm Returns Linear Graph instead of Standard O(n^2) Graph
<p>I'm trying to generate a simple graph to show O(n^2) over a thousand items. The code seems to work just fine, however when I plot it using matplotlib, the graph comes out in a linear fashion, meaning the graph of y seems to equal x. I would expect a nice O(n^2) graph like this:</p> <p><a href="https://www.section.io...
<python><algorithm><big-o>
2023-03-13 23:21:05
1
9,233
KingFish
75,727,688
2,312,801
Pandas findall re.IGNORECASE doesn't work
<p>I have a list of keywords:</p> <pre><code>keywords = ['fake', 'hoax', 'misleading', etc.] </code></pre> <p>I'd like to search the <code>text</code> column of DataFrame <code>df1</code> for the above keywords and return rows containing these keywords (exact match), both in uppercase and lowercase (case-insensitive).<...
<python><pandas><findall><keyword-search><ignore-case>
2023-03-13 23:05:37
1
2,459
mOna
75,727,685
781,938
How do I get a list of table-like objects visible to duckdb in a python session?
<p>I like how duckdb lets me query DataFrames as if they were sql tables:</p> <pre class="lang-py prettyprint-override"><code>df = pandas.read_parquet(&quot;my_data.parquet&quot;) con.query(&quot;select * from df limit 10&quot;).fetch_df() </code></pre> <p>I also like how duckdb has metadata commands like <code>SHOW TA...
<python><pandas><duckdb>
2023-03-13 23:05:26
2
6,130
william_grisaitis
75,727,555
10,807,390
How can I find the year has the highest value for each subset of a large dataframe using Pandas?
<p>I have a dataframe with 10 years of humidity and temperature data for each of 100 dataloggers. Here is the head:</p> <pre><code> </code></pre> <p>The loggers are labeled as L1 through L100.</p> <p>My end goal is to have a dataframe with three columns: year, the count of dataloggers where that year had the highest av...
<python><pandas>
2023-03-13 22:40:53
1
427
Tom
75,727,523
3,380,902
format string to json / dict
<p>I have a string that has the following contents:</p> <pre><code>print(&quot;json str:&quot;, type(json_str), json_str) json str: &lt;class 'str'&gt; json { &quot;word&quot;: [ &quot;table name&quot; ] } </code></pre> <p>I get an exception when I attempt to run:</p> <pre><code>import json j...
<python><json><string><dictionary>
2023-03-13 22:36:19
1
2,022
kms
75,727,004
13,215,988
How do I add widgets to the top left of Pyside Qt layout instead of having the items centered and evenly spaced?
<p>I have a PySide6 Qt screen that looks like this:<br /> <a href="https://i.sstatic.net/XUwKq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XUwKq.png" alt="enter image description here" /></a></p> <p>The problem is that I want the buttons &quot;0 test1.rtf,&quot; &quot;1 test2.rtf,&quot; &quot;2 test3...
<python><qt><pyside2><pyside6>
2023-03-13 21:21:46
0
1,212
ChristianOConnor
75,726,965
2,725,742
Why does my pySerial data get corrupted mid-stream?
<p>This works wonderfully on Windows, with Python 3.10. Incoming data has a delimiter, this delivers one message at a time, life is good...until I test on Linux. Specifically Ubuntu 18.04.</p> <p>On Linux, it receives a handful of messages successfully, and then it gets garbage, non-ascii values. Oddly it often turn...
<python><serial-port><embedded-linux><pyserial>
2023-03-13 21:16:42
1
448
fm_user8
75,726,959
11,048,519
How to reroute requests to a different URL/endpoint in FastAPI?
<p>I am trying to write a middleware in my FastAPI application, so that requests coming to endpoints matching a particular format will be rerouted to a different URL, but I am unable to find a way to do that since <code>request.url</code> is read-only.</p> <p>I am also looking for a way to update request headers before...
<python><fastapi><middleware><starlette><reroute>
2023-03-13 21:15:14
1
868
Aniket Tiratkar
75,726,867
19,299,757
interact with file open window in headless chrome
<p>I've an application which I am automating using headless chrome using selenium python. One of the feature of this application is to upload files and send it into the application for processing. For this there is a &quot;Drag and Drop&quot; button in the GUI which when clicked opens up the file &quot;Open&quot; windo...
<python><selenium-webdriver><pyautogui>
2023-03-13 21:01:57
1
433
Ram
75,726,722
7,984,318
How to append rows in pandas ,if column value is not in a external list
<p>I have a DataFrame you can have it by running this code:</p> <pre><code>df = &quot;&quot;&quot; Facility Quarter Price F1 Q1 2.1 F1 Q2 1.2 &quot;&quot;&quot; df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python') </code></pre> <p>And a list:</p> <pre><code>...
<python><python-3.x><pandas><dataframe>
2023-03-13 20:41:29
3
4,094
William
75,726,719
47,152
Confused by python async for loop--executes sequentially
<p>I am new to asyncio and trying to understand basic for loop behavior. The code below executes sequentially, but my naive assumption was that while the sleeps are occurring, other items could be fetched via the for loop and start processing. But that doesn't seem to happen.</p> <p>For example, while the code is &quot...
<python><python-asyncio>
2023-03-13 20:41:00
4
1,465
chacmool
75,726,487
18,086,775
Unable to reference a excel marco file while running a juypter-notebook from another notebook
<p>I'm trying to run a jupyter notebook file called <code>Seg_pivot.ipynb</code> from <code>main.ipynb</code>. The main.ipynb has one line of code: <code>%run &quot;fi/Seg_pivot.ipynb&quot;</code></p> <p>The current directory structure looks like the following: <a href="https://i.sstatic.net/2emDi.png" rel="nofollow no...
<python><excel><vba><jupyter-notebook>
2023-03-13 20:11:35
1
379
M J
75,726,455
4,534,466
Disable ssl verification on a third party module using HTTPX
<p>I'm using a module that uses <code>httpx</code> to make a request. Because of my company's network policy, I get a <code>CERTIFICATE_VERIFY_FAILED</code> every time I try to run my code. The data I'm sending and receiving in the request is not sensitive so I want to disable the SSL verification on the module.</p> <p...
<python><ssl><httpx>
2023-03-13 20:07:27
1
1,530
JoΓ£o Areias
75,726,452
10,335
Can I force the install of a package that requires a newer Python version than the one I have installed?
<p>I know it isn't a correct thing to do, but I would like to try to install package that requires Python 3.8, but my installed Python is 3.7.</p> <p>Is it possible using pip? Or I must clone the repository and change the <code>setup.py</code>?</p>
<python><pip>
2023-03-13 20:07:22
1
40,291
neves
75,726,343
119,527
Reconciling the differences between BinaryIO and RawIOBase
<p>My modest goal: Correctly annotate a function argument as an object supporting <code>read()</code> which returns <code>bytes</code>.</p> <ul> <li>If I use <a href="https://docs.python.org/3/library/typing.html#typing.BinaryIO" rel="nofollow noreferrer"><code>typing.BinaryIO</code></a>, I cannot accept a <code>serial...
<python><python-typing>
2023-03-13 19:52:20
2
138,383
Jonathon Reinhart
75,726,225
217,332
Type hinting decorator with bounded arguments
<p>An example of what I'd like to do is as follows:</p> <pre><code>@dataclass class Arg1: x = field() @dataclass class Arg2: x = field() @dataclass class Obj: y = field() T = TypeVar(&quot;T&quot;) R = TypeVar(&quot;R&quot;, bound=(Arg1 | Arg2)) C = TypeVar(&quot;C&quot;, bound=Callable[[Se...
<python><python-decorators><mypy><python-typing><python-3.11>
2023-03-13 19:37:26
2
83,780
danben
75,725,895
2,774,589
Changing `ylim` on `cartopy` with different `central_longitude`
<p>I want to create a map on Mercator projection from -60S to 60N but with -160W as the central longitude.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import cartopy.crs as ccrs fig = plt.figure() ax = fig.add_subplot(1,1,1, projection=ccrs.PlateCarree(central_longitude=...
<python><matplotlib><gis><cartopy>
2023-03-13 18:56:09
1
1,660
iury simoes-sousa
75,725,842
9,363,441
Continuous change of led params RPI from remote access
<p>I have RPI4 where have attached RGB LED. This led has to blink with certain frequency and color forever. I have such python service:</p> <pre><code>#libraries import RPi.GPIO as GPIO from time import sleep import os import schedule import time #disable warnings (optional) GPIO.setwarnings(False) #Select GPIO Mode G...
<python><linux><raspberry-pi>
2023-03-13 18:49:29
0
2,187
Andrew
75,725,836
18,749,472
"The request's session was deleted before the request completed" on heavier requests
<p>In my Django project I am frequently coming across the error:</p> <p><em>The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example.</em></p> <p>This happens across a number of views and because of a number of different processes within my websit...
<python><django><session><server><django-sessions>
2023-03-13 18:48:40
0
639
logan_9997
75,725,818
10,255,994
Loading Hugging face model is taking too much memory
<p>I am trying to load a large Hugging face model with code like below:</p> <pre><code>model_from_disc = AutoModelForCausalLM.from_pretrained(path_to_model) tokenizer_from_disc = AutoTokenizer.from_pretrained(path_to_model) generator = pipeline(&quot;text-generation&quot;, model=model_from_disc, tokenizer=tokenizer_fro...
<python><pytorch><nlp><huggingface-transformers><huggingface>
2023-03-13 18:46:57
1
483
Bud Linville
75,725,658
20,484,525
How can I update my Python version and keeping all the packages?
<p>I want to ask you a question about the Python update. If I wanted to update my Python version from the 3.10 to 3.11, what should I do? And, most important, do I have to reinstall all the packages like Pandas, Numpy, Matplotlib, ...? In your opinion, when is needed to update it?</p>
<python><python-3.x>
2023-03-13 18:28:48
2
429
Flavio Brienza
75,725,633
13,135,901
Filter queryset based on related object's field value
<p>I have two models:</p> <pre><code>class PartUse(models.Model): ... imported = models.BooleanField() class PartReturn(models.Model): partuse = models.ForeignKey(PartUse) ... imported = models.BooleanField() class PartUseListView(ListView): model = PartUse def get_queryset(self): ...
<python><django><django-models><django-views><django-admin>
2023-03-13 18:26:05
1
491
Viktor
75,725,261
3,696,490
Grid visualization of a graph from adjacency list
<p>I have a program that generated the following adjacency list: The data represent a 2D grid graph of size 4 by 14 but every node is not necessarily connected to all its neighbors.</p> <p>My adjacency list is:</p> <pre><code>list_ng2d={(0, 0): [(0, 1)], (0, 1): [(0, 2), (0, 0)], (0, 2): [(1, 2), (0, 3), (0, 1)], (0...
<python><graph><networkx>
2023-03-13 17:47:34
2
550
user206904
75,725,243
5,583,772
What is a good best practice way to log a nested-dict
<p>In a python simulation code, code outputs are located in a nested-dict. I'm interested to log this nested dict to file at the end of each iteration, and having trouble identifying the best practice approach. In a current method, the nest_dict is logged by passing it to a logger like:</p> <pre><code>self.logger.inf...
<python>
2023-03-13 17:45:43
1
556
Paul Fleming
75,725,137
11,665,178
Python Cloud functions use too much memory
<p>I am coming from an AWS backend using Lambda functions with python 3.9 runtime.</p> <p>I have decided to run the equivalent on GCP for another project and everything is fine, except the memory usage.</p> <p>On my AWS Lambda, I have a python function that consumes 79MB (you can see the memory usage in CloudWatch logs...
<python><google-cloud-functions>
2023-03-13 17:33:57
0
2,975
Tom3652
75,725,092
12,131,472
how do I insert each row of a dataframe before the matching rows in a different dataframe?
<p>I have one small and one big dataframe</p> <p>the small one</p> <pre><code> WS period shortCode identifier 6 197.78 2023-03-10 TC2-FFA spot 7 196.79 2023-03-10 TC5-FFA spot 8 253.13 2023-03-10 TC6-FFA spot 9 198.13 2023-03-13 TC12-FFA sp...
<python><pandas><dataframe>
2023-03-13 17:30:42
1
447
neutralname
75,725,091
1,764,353
How to run terraform apply inside an AWS Lambda function?
<p>I came accross an older <a href="https://github.com/FitnessKeeper/terraform-lambda" rel="nofollow noreferrer">repo</a> on github that seems like it's exactly what I need for my use case. Unfortunately, the code needs to be updated because lambda and/or python no longer support certain opperations.</p> <p>I keep gett...
<python><amazon-web-services><aws-lambda><terraform><terraform-provider-aws>
2023-03-13 17:30:38
1
389
John R
75,725,071
13,262,692
Pad sequence to multiple of a number TensorFlow
<p>I want to pad a sequence in Tensorflow to multiple of a number. The code I have tried is:</p> <pre><code>import tensorflow as tf def pad_to_multiple(tensor, multiple, dim=-1, value=0): seqlen = tf.shape(tensor)[dim] seqlen = tf.cast(seqlen, tf.float32) multiple = tf.cast(multiple, tf.float32) m = seq...
<python><tensorflow><tensorflow2.0>
2023-03-13 17:28:40
1
308
Muhammad Anas Raza
75,724,886
7,085,817
`func azure functionapp list-functions` returns unauthorised, 401
<p>I'm trying to deploy a function app using CLI and VS code plugin, and as the title states receiving 401. I tried logging out and in: when logged out the error is different. Documentation suggests checking Storage account keys - checked, rotated, doesn't help.</p> <p>As mentioned in the title even the command to list...
<python><azure><azure-functions><terraform-provider-azure>
2023-03-13 17:06:49
1
350
Alex Dembo
75,724,665
5,679,047
How to maximize performance of spaCy on an M1 Mac (currently much slower than Intel)
<p>I've observed that <code>nlp.pipe</code> is 30-40% slower on my almost brand new M1 Pro Macbook than on my old Macbook Pro from 2017. Most other functions are faster on the M1 by a similar margin, so this is not the performance I would expect.</p> <p>For a benchmark, I'm running the following code (with scispacy):</...
<python><spacy><apple-m1>
2023-03-13 16:43:02
1
681
Zorgoth
75,724,652
1,348,572
Cannot assign "default_connection" value to Tortoise ORM model with asyncpg driver?
<p>I'm writing a plugin-based system in my application that loads Tortoise-ORM (<code>tortoise-orm = {extras = [&quot;asyncpg&quot;], version = &quot;^0.19.3&quot;} </code>) models on demand. I've written a very simple test one, below, with some basic fields.</p> <pre class="lang-py prettyprint-override"><code>class P...
<python><tortoise-orm>
2023-03-13 16:41:22
2
349
robbmanes
75,724,561
7,776,781
Decorate behaviour of subclass methods of an abstract base class
<p>I have an inheritance scenario that looks like this:</p> <pre><code>import abc class A(metaclass=abc.ABCMeta): def __init__(self, x: int | None = None) -&gt; None: self.x = x @abc.abstractmethod def foo(self, x: int | None = None) -&gt; None: pass class B(A): def foo(self, x: int...
<python><python-3.x><inheritance>
2023-03-13 16:32:08
1
619
Fredrik Nilsson
75,724,490
8,040,369
DataFrame: convert different format of date in df column to same format
<p>I have a df as below</p> <pre><code>ID Date =================== 1 1/1/2023 2 2/1/2023 3 2/1/2023 4 31-01-2023 5 31-01-2023 </code></pre> <p>All the date mentioned above are for Jan, 2023 and will come in the same format as mentioned above. I need to convert it to a format <strong>YYYY-MM-DD</stron...
<python><pandas><dataframe><datetime>
2023-03-13 16:25:01
1
787
SM079
75,724,281
7,648
RuntimeError: Error(s) in loading state_dict
<p>I have the following PyTorch model:</p> <pre><code>import math from abc import abstractmethod import torch.nn as nn class AlexNet3D(nn.Module): @abstractmethod def get_head(self): pass def __init__(self, input_size): super().__init__() self.input_size = input_size self...
<python><deep-learning><pytorch>
2023-03-13 16:05:42
3
7,944
Paul Reiners
75,724,115
13,158,157
Azure blob storage directory download (win, python)
<p>My goal is to download part of the blob storage that looks like a directory inside other directories.</p> <p>Official <a href="https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-download-python" rel="nofollow noreferrer">Download to a file path</a> function request a self argument that I don't get ho...
<python><azure>
2023-03-13 15:49:51
1
525
euh
75,724,033
14,720,380
Set the media type of a custom Error Response via a pydantic model in FastAPI
<p>In my FastAPI application I want to return my errors as RFC Problem JSON:</p> <pre><code>from pydantic import BaseModel class RFCProblemJSON(BaseModel): type: str title: str detail: str | None status: int | None </code></pre> <p>I can set the response model in the OpenAPI docs with the <code>respons...
<python><swagger><fastapi><swagger-ui><openapi>
2023-03-13 15:40:44
1
6,623
Tom McLean
75,723,868
435,129
Avoid "-bash: __vsc_prompt_cmd_original: command not found" when launching Terminal from Python in macOS
<p>I have a basic macOS app (PyQt5) that launches Terminal.app and executes a command in it:</p> <pre class="lang-py prettyprint-override"><code> cmd = f&quot; cd {os.getcwd()}; bash -c ./backup.sh&quot; subprocess.run(['osascript', '-e', f'tell application &quot;Terminal&quot; to do script &quot;{cmd}&...
<python><bash><macos><terminal>
2023-03-13 15:26:27
0
31,234
P i
75,723,616
1,079,110
Does ZMQ have a mechanism to tell whether a connection is still alive?
<p>I have a ZMQ server that performs a heavy computation and thus sending the result back to the client via <code>server_socket.send()</code> can take several minutes. The client should wait indefinitely for the result of the computation. However, if the connection drops during the computation, then the client should f...
<python><zeromq><pyzmq>
2023-03-13 15:02:21
2
34,449
danijar
75,723,564
5,558,497
list re-order based on multi-level string match
<p>I have python a list that looks like the following:</p> <pre><code>['T20221019A_E3.B Allele Freq', 'T20221019A_E3.Log R Ratio', 'T20221019A_E3.Gtype', 'Father_FM.B Allele Freq', 'Father_FM.Log R Ratio', 'Father_FM.Gtype', 'Mother_FS.B Allele Freq', 'Mother_FS.Log R Ratio', 'Mother_FS.Gtype'] </code></pre> <p...
<python><python-3.x><list>
2023-03-13 14:58:14
1
2,249
BCArg
75,723,546
8,391,698
How to resolve "the size of tensor a (1024) must match the size of tensor b" in happytransformer
<p>I have the following code. This code uses the GPT-2 language model from the Transformers library to generate text from a given input text. The input text is split into smaller chunks of 1024 tokens, and then the GPT-2 model is used to generate text for each chunk. The generated text is concatenated to produce the fi...
<python><huggingface-transformers><huggingface><gpt-2>
2023-03-13 14:56:59
1
5,189
littleworth
75,723,462
6,036,058
Bold and italics with taipy-gui
<p>How to put a string in bold and italics on taipy-gui?</p> <p>For example, I would like the word <code>famous</code> to have both styles.</p> <pre><code>from taipy import Gui Gui(page=&quot;My *famous* app&quot;).run() </code></pre>
<python><python-3.x><taipy>
2023-03-13 14:49:56
1
667
Florian Vuillemot
75,723,386
15,112,773
Rank does not go in order if the value does not change
<p>I have a dataframe:</p> <pre><code>data = [['p1', 't1'], ['p4', 't2'], ['p2', 't1'],['p4', 't3'], ['p4', 't3'], ['p3', 't1'],] sdf = spark.createDataFrame(data, schema = ['id', 'text']) sdf.show() +---+----+ | id|text| +---+----+ | p1| t1| | p4| t2| | p2| t1| | p4| t3| | p4| t3| | p3| t1| +---+----...
<python><apache-spark><pyspark><apache-spark-sql><label-encoding>
2023-03-13 14:43:16
1
383
Rory
75,723,316
11,906,819
Django Admin - Show ManyToOne data on a model in admin
<p>I have 2 models <code>Patient</code> and <code>History</code>. I would like to show all <code>History</code> of a <code>Patient</code> inside the <code>Patient</code> model in django admin as table. I was thinking to use ManyToOne field as one patient can have more than 1 history and 1 history is only owned by 1 pat...
<python><django><django-models><django-forms><django-admin>
2023-03-13 14:37:07
1
375
Kevin Lee
75,723,093
14,269,252
Scatter plot with multiple Y axis using plotly express
<p>I have to plot my data with multiple Y axis, regarding the code below I am facing several issues.</p> <ul> <li><p>There is no coloring is shown.</p> </li> <li><p>Texts are overlapping for multiple Y axis.</p> </li> <li><p>Not showing all the values of Y axis.</p> </li> <li><p>On the X axis, it has to show the date s...
<python><plotly>
2023-03-13 14:18:10
1
450
user14269252
75,723,026
3,896,008
Meaning of this error message python version conflicts
<p>While trying to install package: line-profiler-pycharm, I install it using pip inside my conda environment called <code>wcs</code>. But when I try to run it, I get the following error:</p> <pre><code> 22:01 Error running 'prep_network': Could not do Profile Lines execution because the python package 'line-profile-...
<python><python-3.x><conda><environment>
2023-03-13 14:11:35
1
1,347
lifezbeautiful
75,723,005
12,596,824
Grouping by ID and getting multinomial distribution column
<p>I have a data frame like so:</p> <pre><code> id test 0 1 1.000000 1 2 0.582594 2 2 0.417406 3 3 0.016633 4 3 0.983367 5 4 1.000000 6 5 0.501855 7 5 0.498145 8 6 1.000000 9 7 1.000000 </code></pre> <p>I want to use the <code>np.random.multinomial()</code> function to gener...
<python><pandas><numpy>
2023-03-13 14:09:57
2
1,937
Eisen
75,722,941
4,907,339
Can I make order unimportant when localizing a timedelta?
<p>If I localize a <code>datetime()</code> object after it has been passed through <code>pandas.Timedelta()</code>, it has the correct date, time, timezone and timezone offset.</p> <p>However, if I localize a <code>datetime()</code> object before it has been passed through <code>pandas.Timedelta()</code>, it's timezone...
<python><pandas>
2023-03-13 14:02:19
1
492
Jason
75,722,878
6,067,528
Invalid ELF header when using pyarmor library even though installation matches my architecture
<p>I'm trying to test <code>pyarmor</code> with</p> <p><code>echo &quot;print(1)&quot; &gt; test.py</code></p> <p><code>pyarmor gen test.py</code></p> <p>But am receiving the following error:</p> <p><code>ERROR /usr/local/lib/python3.11/dist-packages/pyarmor/cli/core/pytransform3.so: invalid ELF header</code></p> <p...
<python><pip><pyarmor>
2023-03-13 13:57:04
0
1,313
Sam Comber
75,722,839
347,924
SendGrid - Email with Dynamic Template and Multiple Recipients only showing dynamic data for one of the recipients?
<p>I'm trying to use SendGrid to send out emails to multiple recipients. I don't want the recipients to see each other's email, so I've tried two methods of accomplishing that:</p> <ul> <li>adding <code>is_multiple=True</code> to the <code>Email</code> constructor and setting <code>to_emails</code></li> <li>adding pers...
<python><sendgrid><sendgrid-templates>
2023-03-13 13:54:24
1
4,700
naydichev
75,722,810
235,671
Preserve argument information for inspect when stacking decorators
<p>I'm writing a decorator that should pass a query to the function based on one of its parameters.</p> <p>This is how it currently looks like, but not finished yet (still experimenting):</p> <pre class="lang-py prettyprint-override"><code>def pass_query(service: str, query: str): def decorate(decoratee): @...
<python><python-3.x><dependency-injection><reflection><decorator>
2023-03-13 13:52:26
1
19,283
t3chb0t
75,722,781
1,975,199
Server Side Event not being received
<p>I've implemented some &quot;real time streaming&quot; to the browser. This method is using Server Side events, the backend is Python/FastAPI. I'm developing this primarily on my workstation. Theory of operation is: There are some custom devices on my network that send &quot;heartbeat/health&quot; information. I p...
<python><fastapi><server-sent-events>
2023-03-13 13:49:54
0
432
jgauthier
75,722,684
14,230,633
Jupyter Lab Autocomplete repeats text I've already input
<p>Example: suppose I'm writing <code>x = df.groupby('column')</code>. If I've typed <code>x = df.group</code> and then hit tab, it autofills to <code>x = x = df.groupby()</code> (notice the extra <code>x = </code>).</p> <p>Another example: if I'm writing <code>sns.histplot(df.my_column)</code> and I type <code>sns.his...
<python><jupyter-notebook><autocomplete><jupyter><jupyter-lab>
2023-03-13 13:41:18
0
567
dfried
75,722,675
2,255,168
Jinja2: Object of type Namespace is not JSON serializable
<p>To send my backend data to my frontend/javascript in my Jinja2 view i'm using something like :</p> <pre><code>{% for organization in team.organizations %} {{ teamOrganizations.append(organization.namespace) or &quot;&quot; }} {% endfor %} &lt;div data-json='{{ teamOrganizations|tojson }}'&gt;&lt;/div&gt; </code><...
<python><jinja2>
2023-03-13 13:40:58
0
1,380
Paul
75,722,645
13,345,744
How to convert categorial data to indices and print assignment?
<p><strong>Context</strong> I have a series with categorial data. My goal is to convert it to indices like in the example above. However, there are two other requirements:</p> <ul> <li>nan values should stay nan and not converted to an index e.g. -1</li> <li>I would like to print the assignment of category to index</li...
<python><pandas><categorical-data>
2023-03-13 13:37:58
2
1,721
christophriepe
75,722,627
6,492,292
Get text based on coordinates as same format as in PDF
<p>I have coordinate details, but I'm unable to find any method in pymupdf to fetch a block of data based on the coordinates. Is there any method in pymupdf that can do this? I'm open to other libraries, though I already used PDFQuery which is not working properly.</p> <p>Explanation: I want to read block of text withi...
<python><coordinates><pymupdf>
2023-03-13 13:36:51
0
1,721
m9m9m
75,722,594
11,261,546
boost smart pointer can cast but std cant?
<p>I'm working on a quite old code that has some functions that return an allocated raw pointer (here an oversimplication of what the function does):</p> <pre><code>MyClass* func(){ MyClass* myPtr = new MyClass(); return myPtr; } </code></pre> <p>I want to bind this class and the function that returns the point...
<python><c++><pybind11>
2023-03-13 13:34:32
1
1,551
Ivan
75,722,419
8,981,425
Which is the best way to define module variables in Python?
<p>I am developing a project with FastAPI and I have to connect to a database. I have decided to create a module with database-related functionality, like managing the connection or getting the table's metadata (I am using SQLAlchemy). I want to retrieve this information without recalculating it or duplicating the obje...
<python><module>
2023-03-13 13:20:20
1
367
edoelas
75,722,375
10,518,336
How to get zero values in list comprehension Python
<p>I would like every element in <code>ll</code> to be <code>0</code> where the corresponding element in <code>frac</code> is <code>0</code>. So the first value of <code>ll</code> should be <code>0</code> and the rest unchanged. Thank you.</p> <pre><code> frac = [0,.1,.5,.3,.7,1.1] ll = [[i + 1 for i in range(5) if i &...
<python><list>
2023-03-13 13:15:19
2
366
Expectation mean first moment
75,722,345
14,550,787
Accessing GCP Secret Version Value using Discovery.build with python
<p>Weird instance happening when trying to pull a secret version value using python. I created a client with the discovery.build method, here: <a href="https://googleapis.github.io/google-api-python-client/docs/dyn/secretmanager_v1.projects.secrets.versions.html" rel="nofollow noreferrer">https://googleapis.github.io/g...
<python><google-cloud-platform><google-secret-manager>
2023-03-13 13:12:57
1
583
ColeGulledge
75,722,326
15,959,591
slicing all the columns of a dataframe simultaneously
<p>I have a data frame of an ECG. The data frame consists of 12 columns (lead in ECG vocabulary). I want to cut some slices of all columns like the image below. I find the peak of the first column and define the length of the cut and slice all the columns simultaneously. <strong>Edit:</strong> In fact, I choose the hig...
<python><pandas><dataframe><data-processing>
2023-03-13 13:11:21
1
554
Totoro
75,722,293
1,862,965
How to send multiple file over Rest API and then read files and merge with pandas
<p>How can i send multiple file over Rest api and then read files and merge with pandas.</p> <p>Problem is: I have 4 or more Files. 2 Files are csv and filename contains *_data.csv 2 Files are csv and filename contains *_prices.csv</p> <p>How can i read only *_data.csv with df = pd.read_csv and also only *_prices.csv a...
<python><pandas>
2023-03-13 13:08:29
1
386
user1862965
75,722,285
19,369,310
New column based on the largest 3 elements in a group indexed by Group ID
<p>I have a dataframe that looks like</p> <pre><code>Group_ID probability 34883 0.002676 34883 0.17826266 34883 0.01399753 34883 0.04569782 34883 0.02799506 34883 0.02634829 34883 0.02923014 34883 0.13544669 34883 0.07595718 34883 0.192...
<python><python-3.x><pandas><dataframe><group-by>
2023-03-13 13:07:43
2
449
Apook
75,722,191
17,630,139
ValueError: Error code 'I2041' supplied to 'ignore' option does not match '^[A-Z]{1,3}[0-9]{0,3}$'
<p>Upon importing this <a href="https://pypi.org/project/flake8-import-restrictions/" rel="nofollow noreferrer">flake8 plugin</a> <code>flake8-import-restrictions==1.1.1</code>, I've notice this error appeared. I tried ignoring it by adding it to my setup.cfg file ignore option as shown below.</p> <pre class="lang-py p...
<python><flake8>
2023-03-13 13:00:01
1
331
Khalil