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
⌀
77,452,645
127,508
How to use lxml with 0(1) memory?
<p>I am trying to work with a ~72G XML file. I would like to convert it to CSV.</p> <p>Here is the code that I assumed to be using iterators in the background as I might have read it somewhere about lxml.</p> <pre><code>from lxml import etree import csv file_name = &quot;data/discogs_20231001_releases.xml&quot; # file...
<python><lxml>
2023-11-09 11:07:59
1
8,822
Istvan
77,452,563
5,606,265
python windows service only runs when started as -debug
<p>I've got a Windows Service that runs hypercorn. Everything worked fine in python 3.7. Now we want to move our service to python 3.11, but when starting the service I get the error:</p> <pre><code>Traceback (most recent call last): File &quot;...\service.py&quot;, line 108, in main run_hypercorn(app, self.host,...
<python><python-asyncio><python-3.11><hypercorn>
2023-11-09 10:56:44
1
559
Tekay37
77,452,484
6,281,103
pick_event seems to return the wrong index
<p>I have a 3D scatter plot using Matplotlib and Python. My goal is to highlight a point if it has been clicked. Theoretically, the documentation shows exactly what I want: <a href="https://matplotlib.org/stable/users/explain/figure/event_handling.html" rel="nofollow noreferrer">Simple Picking Example</a>. Also, I've s...
<python><matplotlib>
2023-11-09 10:46:33
1
366
patwis
77,452,478
893,254
Is it possible to render a histogram without vertical line artifacts?
<p>As can be seen in the screenshot below, I have plotted a histogram with Matplotlib. On close inspection it can be seen that there are slight vertical line artifacts.</p> <p>There could be a number of causes.</p> <ol> <li>The PDF rendering in VS Code causes the artifacts, and other PDF readers produce different rende...
<python><matplotlib><histogram>
2023-11-09 10:46:06
1
18,579
user2138149
77,452,380
3,336,423
Python: typing, how to use an inner class from another inner class?
<p>Is it possible to specify a parameter of an inner class function as being types as another inner class?</p> <pre><code>class MyClass(): class InnerClass1(): pass class InnerClass2(): def func(self, param: InnerClass1): pass if __name__ == '__main__': obj...
<python><inner-classes><python-typing>
2023-11-09 10:31:50
1
21,904
jpo38
77,452,376
14,661,648
How to concatenate bytes from a Content-Range HTTP request to a fully working MP4 file?
<p>This is my code so far, but when it concatenates the temporary files from the request to one MP4 file, the MP4 file doesn't play. The file is the same size as the uploaded file however.</p> <pre><code>@app.route('/admin/upload', methods=['POST']) @app_key def admin_dashboard_upload_endpoint(): # Headers file...
<python><http><flask>
2023-11-09 10:31:17
1
1,067
Jiehfeng
77,451,973
3,162,884
Read csv with unquoted carriage return
<p>I'm creating a csv file in python using the csv writer, i then try and read the file but because one of the values has a carriage return in it the csv reader doesn't parse the rows correctly, it sees the \r as a row separator, example code:</p> <pre><code>import csv value = 'a string with \r in it' with open('test...
<python><python-3.x><csv>
2023-11-09 09:33:37
1
520
Binyamin
77,451,769
17,580,381
How to pass arguments to TCPServer handler class
<p>Here's a piece of experimental/educational code written solely to &quot;play&quot; with <em>socketserver</em> functionality.</p> <p>The code works without error. All it does is open and read a file sending the file's contents over a TCP connection to a TCPServer. The server prints the received data during the overri...
<python><socketserver>
2023-11-09 09:03:05
2
28,997
Ramrab
77,451,725
9,072,753
How to type annotate different return type depending on if a parameter is given like in case of next() function?
<p><code>next()</code> function has a special property, that <code>next(iterable)</code> returns the element or raises an exception, but <code>next(iterable, None)</code> returns an element or None.</p> <p>How to type annotate it? Consider the following, I am using pyright to check:</p> <pre><code>from typing import Ty...
<python><python-typing><pyright>
2023-11-09 08:56:18
1
145,478
KamilCuk
77,451,645
108,802
Python: propagate exceptions from paho (MQTT) thread to the main thread
<p>I have a python application, which uses threads to receive topics from an MQTT broker, as well as monitors messages on UART. Running on a Raspberry Pi.</p> <p>The paho MQTT library's interface offers callbacks to handle receiving messages, and a <code>loop_start()</code> that apparently starts a new thread then retu...
<python><multithreading><exception><paho>
2023-11-09 08:45:35
1
42,411
Gauthier
77,451,371
6,255,138
Cannot use asterisk as glob pattern normally in Snakemake
<p>I want to use asterisk as glob pattern to stand for &quot;any string of characters except /&quot; (as stated in <a href="https://en.wikipedia.org/wiki/Glob_(programming)" rel="nofollow noreferrer">glob Wikipedia</a>) in Snakemake rule file in its <code>shell</code> section. But noticed that I cannot use it normally ...
<python><shell><glob><snakemake>
2023-11-09 07:55:59
1
341
Xiaokang
77,451,191
3,161,120
How to use two renderers with structlog?
<p>Would anyone of you know how to use two different renderers in <a href="https://www.structlog.org/en/stable/" rel="nofollow noreferrer">structlog</a>?</p> <p>I'd like to use <a href="https://www.structlog.org/en/stable/api.html#structlog.dev.ConsoleRenderer" rel="nofollow noreferrer">ConsoleRenderer</a> with colors ...
<python><logging><python-logging><structlog>
2023-11-09 07:22:23
0
1,830
gbajson
77,451,118
9,678,361
Long execution times for executing python/pip commands in virtual env of WSL2
<p>Can anyone explain this weird long execution times for getting versions of pip (And of course other pip-related commands) on WSL2? And potentially a workaround for it?</p> <h3>When on a virtual environment (venv) (32 seconds!)</h3> <pre class="lang-none prettyprint-override"><code>(venv) root@mohsen:/mnt/c# time pyt...
<python><pip><windows-subsystem-for-linux>
2023-11-09 07:08:05
1
1,127
Mohsen Taleb
77,450,678
1,167,374
gunicorn randomly getting term and not restarting in systemd
<p>I'm running gunicorn in production with systemd. I periodically get <code>[INFO] Handling signal: term</code> and then <code>Error while closing socket [Errno 9] Bad file descriptor</code> and then it won't start up again saying <code>Connection in use: ('127.0.0.1', 8000)</code>. This has been driving me nuts becau...
<python><fastapi><gunicorn>
2023-11-09 05:32:43
0
662
Jonathan Mugan
77,450,546
4,898,202
How do I pass one or more arguments to python, match them against an optional filter argument, and add only matching arguments to an array?
<p>I want to:</p> <ol> <li>pass <em>one or more (</em>)* <code>named</code> arguments to a python script,</li> <li>pass an optional <code>filter</code> argument also to the script,</li> <li>match all other <code>arguments</code> against the <code>filter</code> <em>(if supplied)</em>,</li> <li>add all <code>arguments</c...
<python><dependencies><arguments><argparse><optional-parameters>
2023-11-09 04:58:19
1
1,784
skeetastax
77,450,468
17,889,840
Combining Video Swin Transformer and 2D-CNN Features for Video Captioning
<p>For a video captioning model, I have sampled each video with 16 frames. I've employed a Video Swin Transformer to extract video features, resulting in a tensor of shape (batch_size, 768, 4, 7, 7). Additionally, I've used a 2D-CNN to extract frame-level features, resulting in a tensor of shape (batch_size, 16, 768). ...
<python><conv-neural-network><feature-extraction>
2023-11-09 04:29:06
0
472
A_B_Y
77,450,463
2,774,823
Incomplete/confusing display of Altair datetime axis when zooming in with selection
<p>I have a timeseries graph defined like this</p> <pre class="lang-py prettyprint-override"><code>zoom = alt.selection_interval(bind='scales') dbm_timeseries = alt.Chart(df) .mark_circle() .encode( y=alt.Y('signal_dbm', title='RSSI (dBm)'), x=alt.X(&quot;datetime:T&quot;, scale=alt.Scal...
<python><altair><vega-lite>
2023-11-09 04:27:28
0
498
zylatis
77,450,368
16,853,253
Stripe API payload Format issue
<p>I'm trying to integrate stripe API in my python application therefore not using python stripe library instead using stripe API endpoints only. The issue I'm facing is with the payload especially when sending array or nested dictionary like below:</p> <pre><code>def create_payment_intent(api_key, authorized_amt): hea...
<python><stripe-payments>
2023-11-09 03:53:34
1
387
Sins97
77,450,305
2,955,827
Why import numpy create threads?
<p><code>mytest.py</code>:</p> <pre class="lang-py prettyprint-override"><code>import time import numpy time.sleep(1000) print(1) </code></pre> <p>Excute it and check threads with:</p> <pre class="lang-bash prettyprint-override"><code>ps -eaf -T | grep mytest </code></pre> <p>And 24 lines show up.</p> <p>But if I remov...
<python><linux><multithreading><numpy>
2023-11-09 03:31:47
1
3,295
PaleNeutron
77,450,149
2,482,149
Azure Pipelines - Prevent PR Update Trigger Upon PR Merge
<p>I am struggling with this issue. I have an <code>azure-pipelines.yml</code> which is set to build a python artifact in three different ways- one upon merge to <code>master</code>(1.0.x), to <code>develop</code> (0.5.xrc) and otherwise just a dev artifact (0.3.x.dev0), x being the incremental number.</p> <p>I underst...
<python><azure-devops><continuous-integration><azure-pipelines><azure-pipelines-yaml>
2023-11-09 02:40:14
2
1,226
clattenburg cake
77,450,020
21,107,707
Trying to draw a parallelogram on this gray band. Why does it *sometimes* not align with the gray band?
<p>To make it simple, I'm working with one contour, which is a very close approximation to a parallelogram. I need to draw a line through the contour such that the line fits under the contour perfectly.</p> <p>Here's a minimum reproducible example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np ...
<python><opencv><computer-vision><geometry>
2023-11-09 02:04:17
1
801
vs07
77,449,906
5,821,880
Are there any obvious bottlenecks in my MariaDB UPDATE?
<p>I have a MariaDB table with 28 million rows. I need to update all the rows (locally) with a new value in a column. This is the code in Python to batch update:</p> <pre><code>update_query = &quot;UPDATE table SET column = %s WHERE `index` = %s&quot; %time cursor.executemany(update_query, update_data) </code></pre> <p...
<python><mysql><mariadb>
2023-11-09 01:27:58
1
517
Dima
77,449,675
5,635,892
Keep order of diagonal elements when diagonalizing a matrix in Python
<p>I have a non-diagonal matrix, but with the non-diagonal elements much smaller than the diagonal ones, so upon diagonalization, I expect that the diagonal elements will change, but just a little. I am currently just using <code>numpy.linalg.eig</code> to get the eigenvalues, however I would like the order of these va...
<python><matrix><diagonal>
2023-11-09 00:04:26
4
719
Silviu
77,449,601
3,566,313
difference between running a query to yahoo finance calendar earning in browser and running the same query in python?
<p>I want to get all the historical earnings dates for GE from yahoo finance. If I run the query in the firefox browser it works but in code it does not. It returns not just GE but all earnings for all companies for day. I don't understand what is going on??</p> <p>if I run this in the browser</p> <pre><code>https://fi...
<python><pandas><yahoo-finance>
2023-11-08 23:36:37
0
546
theakson
77,449,414
1,139,069
How do you register dill in copyreg to pickle a non pickable module?
<p>I have a setup where a python package I'm using is trying to pickle my code. A reduced example looks like</p> <p><code>constraint.py</code></p> <pre><code>manifest = [] </code></pre> <p><code>constraint_loader.py</code></p> <pre><code>import importlib class constraint_loader: def __init__(self): self.co...
<python><pickle><dill>
2023-11-08 22:44:56
1
1,645
user1139069
77,449,380
8,869,570
Converting pandas dataframe to dict (timestamp->datetime conversions)
<p>I have a dataframe <code>df</code> with a column <code>dt</code>. When I do <code>df.to_dict(orient=&quot;records&quot;)</code>, the type of the <code>dt</code> column values get converted to a pandas timestamp in the dict entries.</p> <p>So I was thinking of doing something like this:</p> <pre><code>list_of_dicts =...
<python><pandas><datetime><timestamp>
2023-11-08 22:35:17
1
2,328
24n8
77,449,379
14,010,653
Python script calling issue from a R script in docker container
<p>I have a docker image this is the file/folder structure</p> <pre><code>docker exec -it ec71a4e7a /bin/sh # ls bin dev etc home lib media methylKit.R opt proc run sbin sys usr boot environment.yml filter_parse.py HOME lib64 merge_me...
<python><r><docker>
2023-11-08 22:35:15
0
1,016
PesKchan
77,449,371
3,930,612
Process a pandas DataFrame in Chunks or optimize memory usage for aggregation features
<p>I'm working on a Jupyter notebook in Python with Pandas for data analysis.</p> <p>When creating new aggregation features, I encounter a &quot;MemoryError&quot; due to the memory capacity of my system.</p> <p>Before this error occurs, I'm performing operations similar to the following code:</p> <pre class="lang-py pr...
<python><python-3.x><pandas><dataframe><data-analysis>
2023-11-08 22:33:20
1
395
FedeG
77,449,356
13,394,817
Avoid edgelines or overlaps for coloring a plot using cmap and plt.imshow
<p>How to color a plot from red to green continuously (changing smoothly) based on 4 different styles along <code>y</code> axis, using <code>cmap</code>, where the first and the last sections are colored by constant colors red and green respectively. I want to use <code>plt.imshow</code> in this regard, if it could. I ...
<python><matplotlib>
2023-11-08 22:28:22
1
2,836
Ali_Sh
77,449,347
7,721,999
pip Authentication to Gitlab Private PyPI Registry
<p>I've got a PyPI Package hosted in Gitlab. I am able to succesfully download and install it by adding a <code>--index-url</code> parameter to the <code>pip install</code> command:</p> <pre><code># This works pip install MY-PACKAGE \ --index-url https://__token__:&lt;your_personal_token&gt;@gitlab.com/api/v4/project...
<python><pip><gitlab>
2023-11-08 22:26:30
1
810
Andrew
77,449,311
3,842,845
python how to insert result of data frame into read_block function
<p>I am trying to use the result of data frame that I generated from Azure Blob Storage and apply to the next step (where it extracts data in certain way).</p> <p>I have tested both sides (generating data from Azure Blob Storage &amp; extracting data using Regex (and it works if I tested separately)), but my challenge ...
<python><pandas><regex><azure><azure-blob-storage>
2023-11-08 22:20:06
1
1,324
Java
77,449,308
11,934,963
How to iterate through Pandas and return first match found in sublist
<p>I need a pandas apply function to iterate through sublists and return the first value found for each sublist.</p> <p>I have a dataframe like this:</p> <pre><code>data = {'project_names': [['Datalabor', 'test', 'tpuframework'], ['regETU', 'register', 'tpuframework'], [], ['gpuframework', 'cpuframework']]} df = pd.Dat...
<python><pandas><list-comprehension><apply>
2023-11-08 22:18:40
2
470
Daniel
77,449,254
1,404,135
Iterate over list of YouTube/RTSP streams, add text overlays, and expose as a fixed RTSP endpoint
<p>My goal is a shell script or Python utility that cycles through list (.csv, .yaml, or .json) of YouTube/RSTP source streams in a format similar to the following (.csv) example below:</p> <pre><code>url,overlay_text,delay_ms rtsp://admin:12345@192.168.1.210:554/Streaming/Channels/101,THIS IS OVERLAY TEXT,5000 https:/...
<python><bash><video-streaming><gstreamer><python-gstreamer>
2023-11-08 22:06:52
1
1,113
3z33etm
77,449,130
13,046,093
Create a column based on a max value among several columns with the corresponding column name (instead of column value)
<p>I have a following dataframe named df_test that shows the score for each product per region. I want to create a column calls &quot;highest score product&quot; that shows the corresponding product name with highest score per region.</p> <p>I used the max() function to get the highest product score, but the desired ou...
<python><pandas><dataframe>
2023-11-08 21:41:29
1
460
user032020
77,449,101
1,333,025
How can I call Scons from a Python program as a library?
<p>I have a Python program, whose workflow over a set of files that could be nicely expressed using &quot;build&quot; dependencies with Scons as follows:</p> <ul> <li>Construct a temporary <code>SConstruct</code> file that describes the dependencies and rules to build targets. <ul> <li>Represent the Python functions th...
<python><scons>
2023-11-08 21:36:26
1
63,543
Petr
77,448,920
4,668,368
print multiple regex in python loop, currently only printing one
<p>In the below <code>python 3.7</code> script, the below code executes but returns no results. However, if I change the <code>if t is not None:</code> and <code>print(t.group())</code>, I get the match result for only <code>t</code>. I can not seem to adjust in to get both match results for <code>t</code> and <code>c<...
<python><python-3.x>
2023-11-08 21:00:39
0
3,022
justaguy
77,448,552
1,602,022
Is there a simple way to install every Ansible azure-mgmt-* Python package?
<p>Every time I run</p> <pre><code>ansible localhost -m azure.azcollection.azure_rm_resourcegroup -a &quot;name=resourceGroup location=eastus&quot; </code></pre> <p>I get an error regarding a missing <code>azure.mgmt.*</code> module, e.g.</p> <pre><code>An exception occurred during task execution. To see the full trace...
<python><azure><ansible>
2023-11-08 19:51:18
0
1,426
theillien
77,448,528
512,480
AWS API Gateway, lambda function with path parameter in python?
<p>Does someone have an example of an API Gateway lambda function that receives a path parameter, that is written in python? Every example I can find is written in javascript, and doesn't quite connect for me.</p> <p>Here's what I mean: from my-template.yaml:</p> <pre><code>Events: Call: Type: Api Propertie...
<python><amazon-web-services><aws-api-gateway><path-variables>
2023-11-08 19:46:58
1
1,624
Joymaker
77,448,439
4,449,191
str or byte confusion when reading json data in Python
<p>I'm reading a file with a chat export from Facebook in python with the following example:</p> <pre><code>jsonMessages = [] with open(&quot;Facebook/message_1.json&quot;, 'rb') as file1: json1 = json.load(file1) jsonMessages.extend(json1['messages']) jsonMessages[0]['content'] for msg in jsonMessages: ...
<python><json><python-3.x>
2023-11-08 19:32:43
0
493
jared
77,448,293
496,136
why does this sample code from office365.sharepoint repo fails?
<p>Using Python 3.10 and trying to learn and use Office365-REST-Python-Client to manipulate SharePoint files.</p> <p>I need to be able to move files around and I came across the following code on their file examples:</p> <p><a href="https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/f...
<python><office365-rest-client>
2023-11-08 19:07:12
1
6,448
reza
77,448,212
6,534,818
Fill between known values and stop
<p>How can I fill just between known values?</p> <p>Consider the following example:</p> <pre><code>localdf = spark.createDataFrame( sc.parallelize( [ [1, 24, None, None], [1, 23, None, None], [1, 22, 1, 1], [1, 21, None, 1], [1, 20, None, 1], [...
<python><apache-spark><pyspark><apache-spark-sql>
2023-11-08 18:50:52
1
1,859
John Stud
77,448,143
9,477,275
Python Async Programming: Getting Gift info with TikTokLive Library
<p>I am trying TikTokLive library to get the username who gives gift and feed to my GUI program. But I screwed up with how to use Async function.</p> <p>TikTokLive Library <a href="https://github.com/isaackogan/TikTokLive" rel="nofollow noreferrer">https://github.com/isaackogan/TikTokLive</a></p> <p>My code:</p> <pre><...
<python><asynchronous><tiktok>
2023-11-08 18:39:42
0
399
idiot one
77,448,106
3,337,089
Query CDF of discrete distribution at arbitrary points in PyTorch
<p>I have a discrete distribution say <code>x=[1,2,4,5]; P(x)=[0.1, 0.2, 0.3, 0.4]</code>. CDF is given by <code>F(x)=[0.1, 0.3, 0.6, 1]</code>. Here the <code>P</code> and <code>F</code> arrays denote the corresponding values at the given <code>x</code>. In my case, <code>P</code> is not actually a discrete distributi...
<python><pytorch><vectorization><probability-distribution><cumulative-distribution-function>
2023-11-08 18:32:14
0
7,307
Nagabhushan S N
77,448,000
1,187,621
Does anyone see changes I can make to my Python GEKKO IPOPT code to help converge?
<p>With the following code in Python GEKKO, IPOPT throws an error:</p> <blockquote> <p>Restoration phase is called at point that is almost feasible, with constraint violation 0.000000e+00. Abort.</p> </blockquote> <pre><code>from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt import math #consta...
<python><gekko><ipopt>
2023-11-08 18:12:01
1
437
pbhuter
77,447,942
480,118
pandas: resample data by date and another group
<p>I have the following data:</p> <pre><code>import pandas as pd data = [['01/01/2000', 'aaa', 101, 102], ['01/02/2000', 'aaa', 201, 202], ['01/01/2000', 'bbb', 301, 302], ['01/02/2000', 'bbb', 401, 402],] df = pd.DataFrame(data, columns=['date', 'id', 'val1', 'val2']) df['date'] = pd.to_datet...
<python><pandas><numpy>
2023-11-08 18:01:15
2
6,184
mike01010
77,447,921
14,820,295
Extract best values from string column in pandas dataframe (Python)
<p>I need to retrieve the first and last name of the person who has the highest percentage within a string column.</p> <p><em><strong>Example of my dataset:</strong></em></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name_percentage</th> </tr> </thead> <tbody> <tr> <td>1</td> ...
<python><python-3.x><pandas><dataframe>
2023-11-08 17:57:39
1
347
Jresearcher
77,447,863
11,025,049
Timeout for python function
<p>I'm using a lib/SDK to control a fingerprint reader.</p> <p>I wrote this:</p> <pre class="lang-py prettyprint-override"><code>import ctypes SDK_ERRORS = { -23: &quot;Not Connected&quot;, -22: &quot;SDK not started&quot;, } class FingerPrintReader: def __init__(self): self.sdk = None tr...
<python><python-multithreading>
2023-11-08 17:49:10
1
625
Joey Fran
77,447,681
9,357,484
Installation guide for Python 3.7 for Windows 11
<p>How can I install Python 3.7 for my 64-bit Windows 11 Home Edition? I found that status of Python 3.7 is &quot;End of Life&quot;. Link <a href="https://devguide.python.org/versions/#versions" rel="nofollow noreferrer">here</a></p> <p>I am required to install it because one of my projects has software requirements li...
<python><python-3.x><tensorflow><keras>
2023-11-08 17:19:40
2
3,446
Encipher
77,447,591
10,856,631
Seeking Proven Workarounds for Twitter Data Scraping Challenges Post API V2 Update
<p>I'm currently grappling with Twitter's API v2 updates, which have significantly impacted the effectiveness of data scraping libraries like Tweepy and Scrapy. </p> <p>The new rate limits and access restrictions have introduced a set of challenges that I'm trying to navigate.</p> <p>Specifically, I'm encountering prob...
<python><selenium-webdriver><web-scraping><twitter><tweepy>
2023-11-08 17:06:37
0
364
Gbadegesin Taiwo
77,447,580
226,473
How to "flatten" a dataframe where one column contains a space-separated list?
<p>my df looks like this:</p> <pre><code> A | B | C 1 2 3|location|code </code></pre> <p>what I want to do is make the df look like this:</p> <pre><code>A| B | C 1|location|code 2|location|code 3|location|code </code></pre> <p>effectively repeating the row for each space-separated value in the first column...
<python><pandas>
2023-11-08 17:05:14
3
21,308
Ramy
77,447,365
4,348,880
Custom `predict` method not working after serializing Keras model
<p>I am encountering an issue with a custom <code>predict</code> method in a Keras model after serializing and reloading the model. Here's a simplified example of the problem:</p> <p>I have a Keras model defined as follows:</p> <pre class="lang-py prettyprint-override"><code>class MyModel(tf.keras.Model): def __ini...
<python><tensorflow><machine-learning><keras>
2023-11-08 16:34:11
1
1,016
Salman
77,447,360
2,532,408
import from typing within TYPE_CHECKING block?
<p>Does it make sense to import from <code>typing</code> inside a <code>TYPE_CHECKING</code> block?</p> <p>Is this good/bad or does it even matter?</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from typing import TYPE_CHECKING, Protocol, runtime_checkable if TYPE_CHECKING: ...
<python><python-typing>
2023-11-08 16:33:42
1
4,628
Marcel Wilson
77,447,324
13,142,245
How to get all cloud formation exports Boto3
<p>I'm confused as how to use Boto3's <a href="https://boto3.amazonaws.com/v1/documentation/api/1.9.42/reference/services/cloudformation.html#CloudFormation.Client.list_exports" rel="nofollow noreferrer">list_exports method</a>.</p> <pre><code>response = client.list_exports( NextToken='string' ) </code></pre> <bloc...
<python><aws-cloudformation><boto3>
2023-11-08 16:29:43
1
1,238
jbuddy_13
77,447,294
7,433,770
Python plot of connected graph with control over one coordinate of node position, but other axis optimized
<p>I have a situation in which I want to generate a graph such as the following sketch I have a set of discrete items A -- J, each of which has a univariate measurement (say the quality measurement of item i). There is a known connectivity graph of edges for these items (corresponding to the nodes), some of which may ...
<python><plot><graph><networkx>
2023-11-08 16:24:52
2
483
Sam A.
77,447,026
18,380,493
Multi level import of tensorflow modules not working as expected
<p>Consider the following four pieces of code. Among them, 1, 2, and 3 work. I believe 4 is similar to 2 and should work. But it doesn't. I get the following error: <code>module 'tensorflow._api.v2.lite' has no attribute 'tools'</code></p> <p>What is the difference? Is the behavior of a multi-level import different tha...
<python><tensorflow>
2023-11-08 15:44:42
1
326
moriaz
77,447,024
850,781
Construct a python function programmatically from given components
<p>I have a list of python functions, e.g.,</p> <pre><code>def f1(x, a): return x + a def f2(x, y, a, b): return x * a + y * b def f3(c, d, e): return c * d - e def f4(y, z): return 2 * y - z ... my_functions = [f1, f2, f3, f4 ...] </code></pre> <p>and I want to combine all pairs of them in a predefined way, e.g., by t...
<python><function><eval>
2023-11-08 15:44:39
3
60,468
sds
77,446,984
1,996,496
Error when running Selenium / Chromedriver twice at the same moment
<p>I have a piece of code that is executed &quot;on-demand&quot; taking a screenshot of a locally hosted website (https://) meaning there's a possibility that it runs twice in the same second. It executes perfectly fine hundreds of times if it doesn't execute in the same second, but when it does then one of them gives ...
<python><google-chrome><selenium-webdriver><selenium-chromedriver><chromium>
2023-11-08 15:38:50
1
990
theplau
77,446,905
1,383,029
Requests library: Passing boolean values in params
<p>I have this code which sends request to an API</p> <pre><code>request_parameters = { &quot;headers&quot;: myheaders, &quot;params&quot;: { &quot;myparam&quot;: True } } response = requests.get(myurl, **request_parameters) </code></pre> <p>Value of <code>response.url</code> is <code>myurl?myparam=Tru...
<python><json><python-requests>
2023-11-08 15:27:31
1
2,155
user1383029
77,446,833
12,915,097
Keep keys order of JSON objects stored in Snowflake ARRAY type field
<p>I have stablished a connection to Snowflake from python, using:</p> <pre><code>import snowflake.connector params = dict( user=&lt;my_user&gt;, password=&lt;my_pass&gt;, account=&lt;my_acc&gt;, warehouse=&lt;my_wh&gt;, database=&lt;my_db&gt;, sch...
<python><snowflake-cloud-data-platform>
2023-11-08 15:17:15
0
390
Jose Rondon
77,446,653
583,464
match specific list name values with another name value
<p>This is a continuation from <a href="https://stackoverflow.com/questions/77445115/fill-with-none-to-specific-position-in-accordance-with-another-list/77445618?noredirect=1#77446272">here</a>.</p> <p>Now, I have this dataset with the addition of <code>CODE</code>.</p> <pre><code>thelist = [[ [['AA', '24', '', Non...
<python>
2023-11-08 14:56:23
1
5,751
George
77,446,605
471,136
Running Python Poetry unit test in Github actions
<p>I have my unittests in a top level <code>tests/</code> folder for my Python project that uses poetry (<a href="https://github.com/pathikrit/fixed_income_annuity" rel="noreferrer">link</a> to code). When I run my tests locally, I simply run:</p> <pre><code>poetry run python -m unittest discover -s tests/ </code></pre...
<python><github-actions><python-poetry>
2023-11-08 14:49:09
1
33,697
pathikrit
77,446,604
4,898,202
How do I create a nested `dict` of arrays in Python?
<p>I need to '<em>pivot</em>' an array of arrays like this:</p> <pre class="lang-py prettyprint-override"><code>mytable = [ [117, 12, 'wer'], [117, 23, 'hgr'], [42, 33, 'hgj'], [910, 27, 'sfr'], [910, 31, 'mhn'], [910, 98, 'wlc'], [453, 11, 'nlj'], [453, 65, 'nfg'], [312, 17, 'fyg'],...
<python><dictionary><multidimensional-array><tree><pivot-table>
2023-11-08 14:48:53
1
1,784
skeetastax
77,446,419
2,017,943
Callback in LLM chain doesn't get executed
<p>The following code do not do what it is supposed to do:</p> <pre class="lang-py prettyprint-override"><code>from langchain.callbacks.base import BaseCallbackHandler from langchain import PromptTemplate from langchain.chains import LLMChain from langchain.llms import VertexAI class MyCustomHandler(BaseCallbackHandl...
<python><langchain><google-cloud-vertex-ai><py-langchain>
2023-11-08 14:26:03
4
1,649
DarioB
77,446,399
16,383,578
How to properly implement Minimax AI for Tic Tac Toe?
<p>I want to implement Minimax AI for Tic Tac Toe of orders 3, 4, 5.</p> <p>Rules of the game:</p> <ul> <li><p>For an order n Tic Tac Toe game, there is a board comprising of n rows and n columns, for a total of n<sup>2</sup> cells. The board is initially empty.</p> </li> <li><p>There are two players, players move alte...
<python><algorithm><tic-tac-toe><minimax>
2023-11-08 14:23:46
2
3,930
Ξένη Γήινος
77,446,396
2,725,810
Hitting a limit with Lambda concurrency at just 10 instances
<p>I have produced a simple experiment whereby a parent Lambda function invokes in parallel 10 instances of the child Lambda function. For some reason, one of the child instances does not begin for almost a second after the other 9 instances returned their response. Here is the code for easy reproduction of the problem...
<python><amazon-web-services><multithreading><aws-lambda><parallel-processing>
2023-11-08 14:23:33
1
8,211
AlwaysLearning
77,446,169
10,507,036
ModuleNotFoundError when installing Cython module through pip on Windows, but not on Linux
<p>I'm trying to build a python module in the folder <code>mymodule</code> containing some cython code. However, on Windows, installing it via pip, it cannot find Cython even though it is installed. On Linux, no such problem occurs.</p> <p>As a minimal example, let's say I have a cython file <code>calculations.pyx</cod...
<python><cython><cythonize>
2023-11-08 13:56:36
1
2,066
sunnytown
77,446,148
627,259
How to read table from this particular PDF - nothing works: tabula.io, pdfplumber, camelot
<p>I am trying to read a table using Python from this PDF file <a href="https://vrtecrad.splet.arnes.si/files/2023/10/Tedenski-jedilnik-od-5.pdf" rel="nofollow noreferrer">Tedenski-jedilnik-od-5.pdf</a></p> <p>But nothing seems to work for me, I have tried tabula.io, camelot (this doesn't even run due to some libraries...
<python><python-camelot><tabula-py><pdfplumber>
2023-11-08 13:54:25
2
2,085
Samo
77,446,083
1,394,697
pandas StataWriter: Writing an iterator for large queries; .dta file corrupt
<p>I'm trying to subclass the pandas <code>StataWriter</code> to allow passing a SQL query with <code>chunksize</code> to avoid running out of memory on very large result sets. I've gotten most of the way there, but am getting an error when I try to open up the file that is written by pandas in STATA: <code>.dta file c...
<python><pandas><dataframe><sqlalchemy><stata>
2023-11-08 13:46:42
1
14,401
FlipperPA
77,446,035
2,628,868
is it possible to parse the jwt token with out key in python
<p>When I use this code to parse the jwt token in Python 3.10(pyjwt==2.8.0):</p> <pre><code>import jwt if __name__ == '__main__': access_token = &quot;eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiSW5kaXZpZHVhbCIsInVzZXJJZCI6Ikp5UHZaczhTVUVwYkZXQkpsLzRwK2RBclRhRE5Tc28wVzZaVTVXN2k1L1E9IiwiZW1haWwiOiJGU3A2SmNvakR...
<python><python-3.x><jwt>
2023-11-08 13:40:08
0
40,701
Dolphin
77,445,992
4,898,202
How do I sort a 2D array in Python by multiple columns?
<p>I have a two-dimensional (2D) Python array (array of arrays):</p> <pre class="lang-py prettyprint-override"><code>arr = [[130, 175, 75, 152], [96, 132, 122, 112], [174, 218, 141, 196], [661, 701, 21, 683], [707, 746, 375, 724], [957, 998, 305, 980], [768, 806, 26, 788], [957, 998, 394, 974], [768, 806, 286, ...
<python><arrays><sorting><multidimensional-array>
2023-11-08 13:35:55
2
1,784
skeetastax
77,445,914
8,580,469
dask import errors, dataframe/client - version conflicts with pandas?
<p>Not all versions of <code>dask.dataframe</code> and <code>pandas</code> are compatible. This has been already addressed in <a href="https://stackoverflow.com/q/76322899/8580469">this question</a></p> <p>I have tried several combinations but in combinations with more recent dask versions, where I get <code>dask.dataf...
<python><pandas><dask><dask-distributed><dask-dataframe>
2023-11-08 13:26:36
1
377
Waterkant
77,445,863
4,399,016
Pandas data frame transformations
<p>I have this data frame:</p> <pre><code>import pandas as pd url = &quot;https://www-genesis.destatis.de/genesisWS/rest/2020/data/tablefile?username=DEB924AL95&amp;password=P@ssword123&amp;name=45213-0005&amp;area=all&amp;compress=false&amp;transpose=false&amp;startyear=1900&amp;endyear=&amp;timeslices=&amp;regionalv...
<python><pandas><data-wrangling>
2023-11-08 13:16:44
1
680
prashanth manohar
77,445,628
14,649,310
Can multiple routers be registered at once in FastAPI?
<p>I have found in the documentation that routers are registered like this:</p> <pre><code>app.include_router(router1) app.include_router(router2) </code></pre> <p>but this seems unnecessarily verbose if I jut want to include a list of routers (like if i have 100 i have to repeat this 100 times? Is there a way to pass ...
<python><fastapi>
2023-11-08 12:42:51
4
4,999
KZiovas
77,445,115
583,464
fill with None to specific position in accordance with another list
<p>I have this kind of dataset:</p> <pre><code>thelist = [[ [['AA', '24', '', None]], [['AA', 'Title', 'A/A agr'], ['48079687', 'Pers', '5', '']], [['AA', 'Syg.', 'Cro'], ['1', 'YES', 'Animal', 'Ksiriki']], [['AA', '26', '', None]], [['AA', 'Title', 'A/A agr'], ['56779687'...
<python>
2023-11-08 11:23:39
2
5,751
George
77,444,832
15,414,616
Dask LocalCluster creating threads inside subprocesses
<p>I'm new to dask and I seem to have some issues with something that should be fairly straight forward so I'm sure I'm missing something.</p> <p>I have a program that supposed to poll messages from kafka, then sends chucks of messages per partition to subprocess and then creates a new thread per message and then each ...
<python><dask><dask-distributed>
2023-11-08 10:43:33
1
437
Ema Il
77,444,695
22,326,950
How to validate customtkinter entry with pattern if invalidcommand is not implemented?
<p>I am currently working on translating my <em>classic</em> tkinter app to customtkinter for GUI design improvement reasons.</p> <p>While most of the original app is <em>translated</em> without major problems I now face a problem with entry validation. The issue is that <code>customtkinter</code> does not provide the ...
<python><validation><tkinter><customtkinter>
2023-11-08 10:26:29
1
884
Jan_B
77,444,679
16,861,953
Pyspark "TypeError: Cannot convert pyarrow.lib.ChunkedArray to pyarrow.lib.Array"
<p>On Databricks, I have a streaming pipeline where the bronze source and silver target are in delta format. I have a pandas udf that uses the requests_cache library to retrieve something from an url (Which can be quite compute expensive).</p> <p>As long as there is no big backlog in the bronze table (Low <code>numByte...
<python><pyspark><databricks><pyarrow><pandas-udf>
2023-11-08 10:25:03
2
379
gamezone25
77,444,489
5,452,365
Pylance shows error when variable type changes
<p>How to avoid this VSCode + Pylance static type check error?</p> <pre><code>def process_row(row: dict[str, Any]): row = SimpleNamespace(**row) </code></pre> <p>For this, vscode shows red underline for <code>SimpleNamespace(**row)</code> with messsage: Expression of type &quot;SimpleNamespace&quot; cannot be assig...
<python><python-typing><pyright>
2023-11-08 09:58:24
2
11,652
Rahul
77,444,465
6,597,296
In argparse's add_argument, can const access the default value?
<p>Suppose you have a Python program that has one option and no positional arguments. The option itself takes an optional argument (an iteger). If no option is specified, a default value should be used. If the option is specified without argument, the <em>same</em> default value should be used. Otherwise the value spec...
<python><argparse>
2023-11-08 09:54:52
2
578
bontchev
77,444,332
2,513,309
OpenAI Python Package Error: 'ChatCompletion' object is not subscriptable
<p>After updating my OpenAI package to version 1.1.1, I got this error when trying to read the ChatGPT API response:</p> <blockquote> <p>'ChatCompletion' object is not subscriptable</p> </blockquote> <p>Here is my code:</p> <pre class="lang-py prettyprint-override"><code>messages = [ {&quot;role&quot;: &quot;sy...
<python><typeerror><openai-api><chatgpt-api>
2023-11-08 09:35:53
2
2,912
Sadegh Ghanbari
77,444,309
534,238
Cannot insert data into BigQuery from Dataflow (using Python SDK)
<p>I am trying to figure out the proper schema that BigQuery is expecting when I am trying to write from Dataflow into BigQuery.</p> <p>I took the Apache Beam <a href="https://github.com/apache/beam/blob/master/sdks/python/apache_beam/examples/streaming_wordcount.py" rel="nofollow noreferrer">streaming pubsub-to-pubsub...
<python><google-bigquery><streaming><google-cloud-dataflow><apache-beam>
2023-11-08 09:33:05
3
3,558
Mike Williamson
77,444,193
16,027,663
Compare Elements in One Array with Two Other Arrays by Position in Numpy
<p>I have a numpy array (a_array) and I need to compare each element with the elements in the same position in b_array and c_array, returning the lower of those two values.</p> <pre><code>a_array = [5031 5038 5040] b_array = [5050 5055 5870] c_array = [5611 5743 5780] </code></pre> <p>So in the above example:</p> <p>i....
<python><numpy>
2023-11-08 09:15:53
1
541
Andy
77,444,032
7,441,757
How to interpolate in pandas using multiple neigbouring points?
<p>If I use <code>df.interpolate</code> with <code>linear</code> it draws straight lines between the last and first point. I see the options for <code>spline</code> or <code>polynominal</code>, but can you make it consider several neighbours using a linear regression?</p> <p>Example:</p> <pre><code> A B 0 1.0 ...
<python><pandas><interpolation>
2023-11-08 08:49:48
1
5,199
Roelant
77,443,992
6,777,238
SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain
<p>I'm trying a get request using the certs I downloaded from <code>https://host:port</code>.</p> <p><a href="https://i.sstatic.net/YGcKd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YGcKd.png" alt="enter image description here" /></a></p> <pre><code>url = 'https://host:port' x = requests.get(url, ve...
<python><python-3.x><openssl><ssl-certificate>
2023-11-08 08:43:39
1
939
gjin
77,443,773
8,341,298
How to customize a config file as specified by the values of a directory
<p>I have a configuration file which has some lines commented out with a '#' which looks like this.</p> <pre><code>#year=1889 #model=foo #size=small working=y </code></pre> <p>Now I get some variables from another place in the code which are stored in a dictionary. Values that appear in the config should be commented i...
<python><python-3.x><dictionary><config>
2023-11-08 08:04:52
1
676
schande
77,443,607
4,898,202
How do I calculate the sum and the average of all values in a python dict by key name?
<p>I have a <code>dict</code> object from which I want to calculate the <strong>sum</strong> and the <strong>mean</strong> of specific named <code>values</code>.</p> <p><strong>Setup:</strong></p> <pre class="lang-py prettyprint-override"><code>tree_str = &quot;&quot;&quot;{ 'trees': [ { 'tree_i...
<python><dictionary><sum><average><key-value>
2023-11-08 07:38:46
3
1,784
skeetastax
77,443,464
3,728,184
How to switch bar charts using plotly animation in Python?
<p>Using the interactive plotly library in Python, I'd like to display a bar chart that transitions to different values upon the click of a button (see the animated gif I created in Keynote as a demonstration).</p> <p><a href="https://i.sstatic.net/630Qk.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/63...
<python><plotly><visualization>
2023-11-08 07:14:42
1
2,005
Markus
77,443,428
16,886,597
How can I check if an instance of a class exists in a List in Python 3 according to value semantics instead of object identity?
<p>In Python 3, I have a list (<code>my_array</code>) that contains an instance of the <code>Demo</code> class with a certain attribute set on that instance. In my case, the attribute is <code>value: int = 4</code>.</p> <p>Given an instance of the <code>Demo</code> class, how can I determine if that instance already ex...
<python><list><class>
2023-11-08 07:07:49
3
674
cocomac
77,443,290
1,609,428
how to flatten a nested, mixed array of structs in pyspark?
<p>Consider the following schema in a PySpark dataframe <code>df</code>:</p> <pre><code>root |-- mydoc: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- Driver: long (nullable = true) | | |-- Information: array (nullable = true) | | | |-- element: struct (contains...
<python><pandas><apache-spark><pyspark><apache-spark-sql>
2023-11-08 06:40:44
1
19,485
ℕʘʘḆḽḘ
77,443,201
2,805,482
Open CV: pasting one image over another changes its color
<p>I am getting the colored part from one image and posting it on another, however when I paste it on another image, I see the color is getting changed and it is a bit transparent too. How can I make sure the color is not changing and its not transparent . Below is my code:</p> <p>Note: Both soruce and target image are...
<python><opencv><python-imaging-library>
2023-11-08 06:19:38
0
1,677
Explorer
77,443,047
4,399,016
csv response to pandas dataframe
<p>I have this code:</p> <pre><code>import requests import json import pandas as pd import io response = requests.request(&quot;GET&quot;, url, headers=headers, data=payload) </code></pre> <p>It returns a response:</p> <pre><code>print(response.text) </code></pre> <blockquote> <pre><code>GENESIS-Tabelle: 45213-0005 T...
<python><pandas><csv><python-requests>
2023-11-08 05:33:45
2
680
prashanth manohar
77,442,845
308,827
Use relplot to plot a pandas dataframe leading to error
<p>I want to plot the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import seaborn as sns data = {'Description': {0: 'Growing degree days (sum of Tmean &gt; 4 C)', 1: 'Maximum number of consecutive frost days (Tmin &lt; 0 C)', 2: 'Number of Frost Days (...
<python><pandas><seaborn><relplot>
2023-11-08 04:31:30
1
22,341
user308827
77,442,575
12,242,085
How to aggregate values in Data Frame for a few columns to have NaN in case of sum NaN instead of 0 in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <p><strong>Input data:</strong></p> <pre><code>df = pd.DataFrame({ 'id' : [999, 999, 999, 185, 185, 185, 999, 999, 999], 'target' : [1, 1, 1, 0, 0, 0, 1, 1, 1], 'event': ['2023-01-01', '2023-01-01', '2023-02-03', '2023-01-01', '2023-01-02', '2023-01-03',...
<python><pandas><dataframe><sum><aggregate>
2023-11-08 02:48:53
1
2,350
dingaro
77,442,403
6,379,348
Cannot log lightGBM parameter using log_params in mlflow/hyperopt
<p>I'm using hyperopt to optimize hyperparameter of lightGBM. The code I use are shown below. I'm trying to log hyperparameters using log_params() in the objective function.</p> <pre><code>from sklearn.metrics import f1_score import lightgbm as lgbm import hyperopt from hyperopt import fmin, tpe, hp, STATUS_OK, space_e...
<python><mlflow><lightgbm><hyperopt>
2023-11-08 01:52:11
1
11,903
zesla
77,442,361
14,256,643
Django rest how to serializers all child comment under it's parent comment
<p>Now my API response look like this</p> <pre><code> &quot;results&quot;: [ { &quot;id&quot;: 12, &quot;blog_slug&quot;: &quot;rest-api-django&quot;, &quot;comment&quot;: &quot;Parent Comment&quot;, &quot;main_comment_id&quot;: null }, { ...
<python><python-3.x><django><dictionary><django-rest-framework>
2023-11-08 01:31:52
2
1,647
boyenec
77,442,227
9,989,308
Log Analytics Workspace: Logs Ingestion API with python script hosted on a Linux server
<p>I have a Python script that I want to run daily that produces a Pandas dataframe.</p> <p>I want this dataframe to be added daily to my log analytics workspace.</p> <p>I have a Linux server that I can use to run my Python script.</p> <p>What do I need to do to make this work using <a href="https://learn.microsoft.com...
<python><azure><azure-log-analytics>
2023-11-08 00:34:57
1
868
HarriS
77,442,182
8,030,794
How to run some vps together with database in another server?
<p>I need to run django site and some scripts together on vps server. But scripts has a large load on the server. Therefore, I assume creating 4 VPS, 1 for the site, the second for the database and the remaining 2 for scripts. And i need to somehow connect them to the database. What technology can be used to achieve th...
<python><django><postgresql>
2023-11-08 00:16:46
0
465
Fresto
77,442,172
1,351,691
SSL: CERTIFICATE_VERIFY_FAILED certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))
<p>I'm working on scripts to connect to AWS from Win10. When I try to install a python module or execute a script I get the following error:</p> <pre class="lang-none prettyprint-override"><code>[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129) </code></pre...
<python>
2023-11-08 00:14:45
15
589
Jeff A
77,442,162
1,129,074
Converting large integer (uint64+) into hex
<p>While importing things into bigquery my hex strings got converted into float. I understand I need to fix the import but I'd like to do a best effort recovery of some of the data.</p> <p>I'm trying my best to convert them back into hex, however, trying toy examples creates unexpected behaviors.</p> <p>Ex. Given the f...
<python><floating-point><integer><hex><int128>
2023-11-08 00:10:25
1
307
yingw
77,442,067
9,613,054
Tensorflow: Could not find matching concrete function to call loaded from the SavedModel
<p>I'm trying to save and load a model across two files.</p> <p>in file 1:</p> <pre><code>rf = tfdf.keras.RandomForestModel(task=tfdf.keras.Task.REGRESSION, verbose=1, num_trees=318, max_depth=20) rf.compile(metrics=[&quot;mse&quot;, &quot;accuracy&quot;, 'mae']) # Optional, you can use this to include a list of eval ...
<python><tensorflow><machine-learning><random-forest>
2023-11-07 23:38:32
0
944
MM1