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
78,682,498
18,482,459
Combine list of dataframes into one big dataframe avoiding duplicates on columns and indices
<p>Multiple data points are in a list. I want to combine them into one pandas DataFrame. Minimal example:</p> <pre><code>list_of_frames = [pd.DataFrame({'name':'adam', 'height':'180'}, index=[0]), pd.DataFrame({'name':'adam', 'weight':'80'}, index=[1]), pd.DataFrame({'name':'eve', 'height':'190'}, index=[2])] </code></...
<python><pandas><dataframe>
2024-06-28 12:36:06
2
405
Firefighting Physicist
78,682,424
1,722,444
SeleniumBase: Web Crawler being affected by human verification system (Select Similar Images)
<p>While crawling a courier website using SeleniumBase for taking screenshot of tracking page, the bot is getting detected and &quot;Select Similar Images&quot; verification box is being shown.</p> <p>URL: <a href="https://www.royalmail.com/track-your-item#/tracking-results/QF085212272GB" rel="nofollow noreferrer">http...
<python><selenium-chromedriver><undetected-chromedriver><seleniumbase>
2024-06-28 12:20:25
1
345
Vivek
78,682,382
5,418,176
Json & PySpark - read value from a struct that may be null
<p>I have a list of <code>.json files</code> that contain person information. One file contains info of one person. I want to load this data into table using <code>pyspark</code> in an Azure Databricks notebook.</p> <p>Let's say the files are built like this:</p> <pre><code>{ &quot;id&quot;: 1, &quot;name&quot;...
<python><json><pyspark><databricks><azure-databricks>
2024-06-28 12:13:51
2
928
DenStudent
78,682,381
386,861
How to debug a module that is imported using a notebook file in VSCode
<p>I've built a utilities.py script to hold functions that I need to regularly perform on a dataset. It is largely in pandas.</p> <p>I then have a notebook, call it process.ipynb, that imports the script with <code>import utilities as ut</code>. So far so good.</p> <p>I've got a step in the process that I know I want t...
<python><visual-studio-code>
2024-06-28 12:13:33
0
7,882
elksie5000
78,682,369
5,180,979
Create limited Tables from ForeignKey dependency map in SQLAlchemy ORM
<p>I have the following code:</p> <pre><code>from sqlalchemy import (create_engine, Column, String, Integer, Float, ForeignKeyConstraint) from sqlalchemy.orm import (DeclarativeBase, relationship) class Base(DeclarativeBase): pass class Process(Base): __tablename__ = 'process' run_...
<python><oracle-database><sqlalchemy><python-3.11>
2024-06-28 12:11:44
1
315
CharcoalG
78,682,300
353,337
B-Spline through 3 points in 3D space
<p>I have three points in 3D and I'd like to a find a smooth curve (e.g., a spline) that goes through all points. With 4 points or more, I can use SciPy's B-splines:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy.interpolate import splev, splprep import matplotlib.pyplot as plt dim ...
<python><scipy>
2024-06-28 11:55:56
1
59,565
Nico Schlömer
78,682,002
7,123,797
Definition of the term "value of an object" in CPython
<p>Is it possible to give a formal definition of the term &quot;value of an object&quot; in CPython? After briefly reading some reference articles and Python tutorials, I came to the conclusion that in most cases this term means one of the following two things (depending on the context). Is this conclusion correct or n...
<python><object><language-lawyer><cpython>
2024-06-28 10:44:48
2
355
Rodvi
78,681,955
2,706,344
Force python to write namespace in root tag
<p>I'm using python to generate an XML document for a third party. The third party has very precise ideas about how the final xml file shall look like. In my case it wants me to define a namespace in the root tag which is never used in the document. The <code>ET.ElementTree.write</code> method is quite smart and define...
<python><xml><elementtree><xml-namespaces>
2024-06-28 10:33:36
0
4,346
principal-ideal-domain
78,681,656
5,269,892
Pandas read csv simultaneously passing usecols and names args
<p>When reading a CSV file as a pandas dataframe, an error is raised when trying to select a subset of columns based on original column names (<code>usecols=</code>) and renaming the selected columns (<code>names=</code>). Passing renamed column names to <code>usecols</code> works, but all columns must be passed to <co...
<python><pandas><dataframe><read-csv>
2024-06-28 09:26:10
3
1,314
silence_of_the_lambdas
78,681,428
17,614,576
Temporal SKD does not return all workflow executions
<p>I have an error in logs which tells that I have error in workflow with 'execute-flow-97bc4090-4cb4-4652-9841-7f01b8fda6f8' id:</p> <pre><code>Completing activity as failed ({'activity_id': '1', 'activity_type': 'send_email', 'attempt': 23928, 'namespace': 'default', 'task_queue': 'execute-flow-task-queue', 'workflow...
<python><temporal><temporal-workflow>
2024-06-28 08:34:14
1
436
Prosto_Oleg
78,681,318
289,784
Using a programmatically generated type in type hints
<p>For some external reasons I'm generating a set of dataclasses dynamically with <code>make_dataclass</code>. In other parts of my codebase, I want to use these types in type hints. But both <code>mypy</code> and <code>pyright</code> complain.</p> <pre class="lang-none prettyprint-override"><code>$ pyright dynamic_t...
<python><python-typing><python-dataclasses>
2024-06-28 08:06:08
1
4,704
suvayu
78,681,300
4,983,469
S3 PutObject works but List/Delete fails
<p>I am creating a session token by setting the permissions like this. This is done in kotlin.</p> <pre><code> val stsClient = applicationContext.getBean(&quot;awsSecurityTokenClient&quot;, awsClient.getBasicCredentials()) as AWSSecurityTokenService val folderName = &quot;&lt;folder&gt;&quot; val keyRights =...
<python><amazon-web-services><kotlin><amazon-s3><boto3>
2024-06-28 08:01:43
1
1,997
leoOrion
78,681,138
6,141,238
In Python: Can I reverse the order in which several matplotlib plot windows are visible / in focus?
<p>When I display several (say, 10 or so) matplotlib plots in either IDLE or VS Code, they generally appear as a cascading stack of plots from top left to bottom right. In this stack, the first plot is on the bottom and last plot is on top (that is, fully visible). To view any plot in the stack other than the last, I...
<python><matplotlib><plot><window>
2024-06-28 07:22:54
1
427
SapereAude
78,680,919
7,227,146
ModuleNotFoundError: No module named 'setuptools.extern.six'
<p>I'm trying to <code>pip install streamlit-wordcloud</code> (<a href="https://github.com/rezaho/streamlit-wordcloud" rel="nofollow noreferrer">here</a>), but I get the following error:</p> <pre><code>ModuleNotFoundError: No module named 'setuptools.extern.six' </code></pre> <p>My Python and pip versions are:</p> <pre...
<python><pip><setuptools>
2024-06-28 06:22:41
0
679
zest16
78,680,681
200,794
Why are pyparsing's `DelimitedList` and `Dict` so awkward to use together?
<p>Pyparsing offers the <code>ParseElementEnhance</code> subclass <code>DelimitedList</code> for parsing (typically comma-separated) lists:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; kv_element = pp.Word(pp.alphanums) &gt;&gt;&gt; kv_list = pp.DelimitedList(kv_element) &gt;&gt;&gt; kv_list.parse_s...
<python><parsing><pyparsing>
2024-06-28 04:42:43
1
2,191
FeRD
78,680,547
11,143,113
How to not show double quotes in ansible run output while displaying contents of a file?
<p>clean.txt file having data without any double quotes below.</p> <pre><code>[wladmin@linuxhost ~]$ cat clean.txt REPL session history will not be persisted. WDA-EMEA-PROD { db: 'WDA-EMEA-PROD', collections: 53, ok: 1, '$clusterTime': { clusterTime: Timestamp({ t: 1719475282, i: 1 }), signature: { ...
<python><ansible><text-formatting>
2024-06-28 03:23:38
0
3,175
Ashar
78,680,411
5,049,813
How to predict the resulting type after indexing a Pandas DataFrame
<p>I have a Pandas <code>DataFrame</code>, as defined <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.index.html" rel="nofollow noreferrer">here</a>:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Aritra'], 'Age': [25, 30, 35], ...
<python><pandas><dataframe><indexing>
2024-06-28 02:14:41
1
5,220
Pro Q
78,680,399
1,033,217
Create Process in Debug Using Python ctypes
<p>The following code is supposed to start a new process <code>calc.exe</code> in debug mode. However, it fails with the code 2 or <code>ERROR_FILE_NOT_FOUND</code>. However, this file <code>calc.exe</code> does exist on the system. What could be wrong with this code? Is there an issue with the path that can be improve...
<python><python-3.x><windows><ctypes><kernel32>
2024-06-28 02:06:31
1
795
Utkonos
78,680,132
7,773,898
NLTK throws FileNotFoundError: [Errno 2] No usable temporary directory found in ['/tmp', '/var/tmp', '/usr/tmp', '/']
<p>Hey can anyone tell what is the reason of <code>FileNotFoundError: [Errno 2] No usable temporary directory found in ['/tmp', '/var/tmp', '/usr/tmp', '/']</code></p> <p>I am running on Docker ecs fargate task and this throws error.</p> <p>I have tried to build and run image on local it works fine but on ecs fargate t...
<python><docker-compose><amazon-ecs>
2024-06-27 23:24:56
0
383
ALTAF HUSSAIN
78,680,120
12,946,401
Video codec for 3D volumetric video datasets
<p>I have 3D volumetric MRI scans representing a time series. So the sequence of these 3D volumes presents a video composed of voxels rather than the conventional 2D pixels from traditional 2D videos. But I noticed that 2D or RGB videos have several codecs available at their disposal to compress the video so it can be ...
<python><multidimensional-array><3d><compression><image-compression>
2024-06-27 23:14:39
0
939
Jeff Boker
78,680,003
1,592,821
Az.cmd closes immediately
<p>When I Run az.cmd on my windows 10 screen some information flashes by and the screen closes. When I right click the shortcut and choose Edit I see</p> <blockquote> <p>:: :: Microsoft Azure CLI - Windows Installer - Author file components script :: Copyright (C) Microsoft Corporation. All Rights Reserved. ::</p> <p>@...
<python><powershell><azure-cli>
2024-06-27 22:23:13
1
18,788
Kirsten
78,679,962
25,413,271
Gitlab CI, artefacts
<p>I am doing my first CI project and I have recently got confused about artefacts...</p> <p>Say I have config with next jobs:</p> <pre><code>cleanup_build: tags: - block_autotest stage: cleanup script: - Powershell $env:P7_TESTING_INSTALLATION_PATH\client\p7batch.exe --log-level=error --run $env:JOBS_FOL...
<python><gitlab><gitlab-ci><gitlab-ci-runner>
2024-06-27 22:04:09
1
439
IzaeDA
78,679,925
119,527
How to get groups of rows bounded by specific values in Pandas?
<h2>Data</h2> <p>I have data which resembles the following:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( [ [&quot;start&quot;, &quot;&quot;], [&quot;data&quot;, 10], [&quot;data&quot;, 11], [&quot;stop&quot;, &quot;&quot;], [&qu...
<python><pandas>
2024-06-27 21:45:27
3
138,383
Jonathon Reinhart
78,679,917
3,311,728
How do I edit a yaml file with python in a way that preserves format, comments, anchors, etc.?
<p>Let's say I have this source yaml file:</p> <pre class="lang-yaml prettyprint-override"><code>top_level: &amp;TL field0: somestring field1: &quot;this one has quotes&quot; field2: [1,2,3] # This comment describes something very important about field3 field3: deep_list: - name: foo field1:...
<python><yaml><formatting><roundtrip>
2024-06-27 21:43:01
0
2,461
RBF06
78,679,818
5,049,813
Terminology for ordinal index versus dataframe index
<p>I've <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.index.html" rel="nofollow noreferrer">set up a dataframe</a>:</p> <pre><code>df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Aritra'], 'Age': [25, 30, 35], 'Location': ['Seattle', 'New York', 'Kona']}, ...
<python><pandas><dataframe><terminology>
2024-06-27 21:08:56
1
5,220
Pro Q
78,679,802
12,158,757
How to make a `functools.reduce` implementation that looks similarly as `Reduce` in R?
<p>Here is an R example of using <code>Reduce</code></p> <pre><code>x &lt;- c(1, 2, 2, 4, 10, 5, 5, 7) Reduce(\(a, b) if (tail(a, 1) != b) c(a, b) else a, x) # equivalent to `rle(x)$values` </code></pre> <p>The code above is to sort out the extract unique values in terms of run length, which can be easily obtained by <...
<python><r><arrays><reduce>
2024-06-27 21:04:06
2
105,741
ThomasIsCoding
78,679,769
2,661,491
Multi-key GroupBy with shared data on one key
<p>I am working with a large dataset that includes multiple unique groups of data identified by a date and a group ID. Each group contains multiple IDs, each with several attributes. Here’s a simplified structure of my data:</p> <pre><code>| date | group_id | inner_id | attr_a | attr_b | attr_c | |------------|--...
<python><pandas><pyspark>
2024-06-27 20:52:42
1
5,572
evan.oman
78,679,538
1,028,270
How is protobuf generating this method and is it impossible to get auto-complete for it?
<p>I was looking at a code base (GCP SDK's monitoring API) trying to drill down to get familiar with some methods, but I hit a wall here: <a href="https://cloud.google.com/monitoring/custom-metrics/creating-metrics#monitoring_create_metric-python" rel="nofollow noreferrer">https://cloud.google.com/monitoring/custom-met...
<python><protocol-buffers><protobuf-python>
2024-06-27 19:34:33
1
32,280
red888
78,679,512
5,009,293
Dtypes Data Frame Assigns nvarchar(MAX) by default
<p>So I have this snippet. When the code runs to insert into a new table, it declares all columns as nvarchar(max). Clearly, this is undesirable behavior. My question is, is there a way to define a length here? So that it isn't MAX?</p> <p>I know I have two options from my research, which are:</p> <ol> <li>Use a dict t...
<python><pandas><dataframe>
2024-06-27 19:27:19
1
7,207
Doug Coats
78,679,475
9,363,441
Python serial send byte array with byte values
<p>I would like to send such array for example via pyserial:</p> <pre><code>[49, 56, 48] or [82] </code></pre> <p>I tried such solution before sending:</p> <pre><code>print(list(str(180).encode())) </code></pre> <p>And it gives me array as I want. But when I tried to send it via pySerial, it said that I need to have bu...
<python><arduino><pyserial><python-bytearray>
2024-06-27 19:17:27
1
2,187
Andrew
78,679,465
6,622,697
Session management in Flask-SQLAlchemy-Lite
<p>I'm moving from vanilla SQLAlchemy to Flask-SQLAlchemy-Lite.</p> <p>What is the best practice for session management? Can I still do something like this:</p> <pre><code> with db.session as session, session.begin(): </code></pre> <p>if I want the block to automatically commit?</p>
<python><sqlalchemy><flask-sqlalchemy-lite>
2024-06-27 19:15:51
2
1,348
Peter Kronenberg
78,679,339
1,867,328
Calculate 6 months forward date from a dataframe of dates
<p>I have below code</p> <pre><code>import pandas as pd from dateutil.relativedelta import relativedelta date = pd.to_datetime(['2001-01-01', '2003-01-01']) date + relativedelta(months = +6) </code></pre> <p>Basically I am trying to calculate 6 months ahead date from a dataframe of dates.</p> <p>Above code is failing.<...
<python><pandas>
2024-06-27 18:39:53
1
3,832
Bogaso
78,679,269
19,155,645
Milvus ConnectionRefusedError: how to connect locally
<p>I am trying to run a RAG pipeline using haystack &amp; Milvus.</p> <p>Its my first time using Milvus, and I seem to have an issue with it.</p> <p>I'm following this tutorial, with some basic changes: <a href="https://milvus.io/docs/integrate_with_haystack.md" rel="nofollow noreferrer">https://milvus.io/docs/integrat...
<python><database-connection><large-language-model><milvus><haystack>
2024-06-27 18:09:32
3
512
ArieAI
78,679,112
5,405,684
Issue with ANSI Escape Codes in Output When Running Shell Script via Python Subprocess
<p>I have a bioinformatics pipeline that builds and runs <code>.sh</code> files in Python. I run the <code>.sh</code> through a subprocess module so I can use parallel computing.</p> <p>This worked about 6 months ago, but now has stopped. It seems like for some reason the ANSI escape codes are being inserted in the com...
<python><shell><subprocess><ansi-escape>
2024-06-27 17:31:52
1
537
lstbl
78,679,016
13,187,876
Load Registered Component in Azure ML for Pipeline using Python sdk v2
<p>I'm working in Azure Machine Learning Studio to create components that I will run together in a pipeline. In this basic example, I have a single <code>python</code> script and a single <code>yml</code> file that make up my component, along with a notebook I am using to define, instantiate and run a pipeline. See an ...
<python><azure><machine-learning><components><azureml-python-sdk>
2024-06-27 17:10:34
1
773
Matt_Haythornthwaite
78,678,993
20,122,390
Is redis in Python asynchronous?
<p>I have the following Python code:</p> <pre><code>import redis from app.infra.services.notifications import INotifier from app.schemas.notification import NotificationMessage from app.config import settings REDIS_CLIENT_PUBSUB = redis.StrictRedis( host=settings.REDIS_HOST, port=settings.REDIS_PORT, pas...
<python><async-await><redis>
2024-06-27 17:03:48
2
988
Diego L
78,678,954
830,429
Visual Studio Code Terminal is Not Using Correct Python Interpreter
<p>I have Visual Studio Code (v 1.9) running on a Windows 10 machine. I want to use ESRI's Python interpreter and I selected that per this image:</p> <p><a href="https://i.sstatic.net/f5iDdWA6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/f5iDdWA6.png" alt="Compiler Selection" /></a></p> <p>After that,...
<python><visual-studio-code><pythoninterpreter>
2024-06-27 16:54:02
2
1,779
IrfanClemson
78,678,899
2,153,235
Python code elements to allow indention without flow control structures
<p>When using Vim, I prefer to have one scheme for demarcating folds across all programming languages and even text files for meeting notes. It saves me from having to finagle different schemes. It has worked for decades, but now that I'm trying to develop Python experience, it is running into a kink. I can't arbitr...
<python><indentation>
2024-06-27 16:38:31
0
1,265
user2153235
78,678,587
14,301,545
Numpy for loop vectorization - points, triangles, area, volume calculation
<p>I have two numpy arrays - one containing coordinates of 3D points and the second with triangles composed from those points. I need to calculate top surface 2D area and volume of this triangles (tetrahedrons?) with base height of the lowest point.</p> <p>Minimal working example of what I got. It work OK, but is slow....
<python><numpy><vectorization>
2024-06-27 15:28:22
1
369
dany
78,678,566
20,122,390
Which is more efficient between Socket.io or WebSockets raw with Redis Pub/Sub?
<p>I currently have an application that uses Socket.IO to send notifications in real time (using server-side Python). We have about 30 instances of the service that handles these websockets. However, we have had problems with this functionality, so we have decided to migrate the websockets part directly to Go. In Go th...
<python><go><websocket><redis><socket.io>
2024-06-27 15:24:16
0
988
Diego L
78,678,322
10,795,473
StatsForecast AutoARIMA taking too long to fit
<p>I'm experiencing a rather “strange” issue with Nixtla's StatsForecast that's severely blocking my progress. I'm explaining it here to see if anyone has any ideas to try, or if those of you who have it installed can test if it works for you.</p> <p>The case is that until yesterday it was running reasonably fast, and ...
<python><time-series><statsforecast>
2024-06-27 14:38:47
0
309
aarcas
78,678,288
2,397,318
Plotting rolling average on top of a stacked bar chart in pandas
<p>I am trying to plot how many daily events of each category happened, together with a 7 days rolling average of the total. Concretely my data has the shape:</p> <pre><code>date_range = pd.date_range(start='2023-01-01', periods=10) data = { 'Category A': np.random.randint(1, 10, 10), 'Category B': np.random.ra...
<python><pandas><matplotlib><rolling-average>
2024-06-27 14:31:40
1
3,769
meto
78,678,138
4,532,062
How to apply hierarchical numbering to indented titles?
<p>I have a table of content in the form of indention to track the hierarchy like:</p> <pre><code>- title1 -- title1-1 -- title1-2 --- title1-2-1 --- title1-2-2 - title2 -- title2-1 -- title2-2 - title3 - title4 </code></pre> <p>I want to translate them with a numbering format like:</p> <pre><code>1 title1 1.1 title1-1...
<python><tableofcontents>
2024-06-27 14:01:08
2
839
Jim
78,678,067
3,925,023
Spacy detect correctly GPE
<p>I've a set of string where I shall detetect the country its belongs to, referring to detected GPE.</p> <pre><code>sentences = [ &quot;I watched TV in germany&quot;, &quot;Mediaset ITA canale 5&quot;, &quot;Je viens d'Italie&quot;, &quot;Ich komme aus Deutschland&quot;, &quot;He is from the UK&quo...
<python><nlp><spacy-3>
2024-06-27 13:44:57
0
687
user3925023
78,677,834
5,377
Python function to assert a type and cast
<p>Functions like <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html" rel="nofollow noreferrer">scipy.optimize.fsolve</a> have, uh, interesting APIs where setting the <code>full_output</code> parameter to a truthy value changes the return type in a way that type checkers can't infe...
<python><python-typing>
2024-06-27 13:02:29
0
6,458
aaronstacy
78,677,547
5,530,553
Django web app was blocked due to MIME type (“text/html”) mismatch
<p>I am trying to build a web-app with Django with a front-end made with Vue.js.</p> <p>Here is how my dir is organized -</p> <pre><code>reco_system_app/urls.py reco_system_app/settings.py recommender/urls.py recommender/views.py vueapp/ static/ templates/ </code></pre> <p><code>reco_system_app/urls.py</code> is</p> ...
<python><python-3.x><django><docker><vue.js>
2024-06-27 12:07:31
0
3,300
Ananda
78,677,469
3,197,404
Remove gap between two graphs with shared axis
<h2>Objective</h2> <p>I want to generate a 'double ended' barchart, showing gained points (of some metric) vis-a-vis missed points, something like this:</p> <p><a href="https://i.sstatic.net/65CTgW6B.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/65CTgW6B.png" alt="graph I want to make" /></a></p> <h2>R...
<python><visualization><altair>
2024-06-27 11:56:26
2
931
dkapitan
78,677,364
5,790,653
How to store all key/values of a dictionary in a single line to store?
<p>This is the sample code:</p> <pre class="lang-py prettyprint-override"><code>my_list = [ {'name': 'Saeed', 'source_country': 'IR', 'destination_country': 'IT', 'email': 'sample1@gmail.com'}, {'name': 'Vahid', 'source_country': 'US', 'destination_country': 'DE', 'email': 'sample2@gmail.com'}, {'name': 'Al...
<python><dictionary>
2024-06-27 11:34:42
1
4,175
Saeed
78,677,266
2,876,079
How to debug scripts for PyPSA-EUR?
<p>I would like to set some VisualStudioCode or PyCharm breakpoints for the script</p> <p><a href="https://github.com/PyPSA/pypsa-eur/blob/master/scripts/prepare_sector_network.py" rel="nofollow noreferrer">https://github.com/PyPSA/pypsa-eur/blob/master/scripts/prepare_sector_network.py</a></p> <p>and then run and debu...
<python><snakemake><pypsa>
2024-06-27 11:11:49
2
12,756
Stefan
78,677,249
13,823,647
Second instance of a class suppresses/deletes the first one in my Python program
<p>I am creating the Pong game using the Turtle module in Python. So far, I have one file for the paddles (the bars that players control to hit the ball) called paddles.py and a second file for the main gameplay control called game.py. I still plan on making a file for the ball and another for score-keeping.</p> <p>In ...
<python><class><instance><turtle-graphics><python-turtle>
2024-06-27 11:08:01
0
417
Aya Noaman
78,676,973
10,200,497
How can I preserve the previous value to find the row that is greater than it?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'start': [3, 11, 9, 19, 22], 'end': [10, 17, 10, 25, 30] } ) </code></pre> <p>And expected output is creating column <code>x</code>:</p> <pre><code> start end x 0 3 10 10 1 11 17 17 2 9...
<python><pandas><dataframe>
2024-06-27 10:11:33
4
2,679
AmirX
78,676,966
5,838,180
How to access data in an h5 file?
<p>I downloaded an astronomical data file called <code>sources.h5</code> from this <a href="https://portal.nersc.gov/project/sobs/users/Radio_WebSky/" rel="nofollow noreferrer">webpage</a>. I am trying to access it to no avail. What I achieved doing is:</p> <pre><code>source_cat = h5py.File('sources.h5', 'r') print(sou...
<python><h5>
2024-06-27 10:09:43
1
2,072
NeStack
78,676,877
2,307,441
Read Excel merged cells strike and non strike data and write to separate files
<p>I have an Excel file where some of the cells got merged and some cells have warp Text with Strike and Non Strike in it.</p> <p><a href="https://i.sstatic.net/Ap7Anz8J.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Ap7Anz8J.png" alt="Sampledata_Image" /></a></p> <p>I want to write the data that non st...
<python><excel><openpyxl>
2024-06-27 09:55:14
1
1,075
Roshan
78,676,853
4,784,914
How could I accomplish the equivalent of a ROS service in ZeroMQ?
<p>In short: <strong>How could I realize something like a &quot;Service&quot; from ROS in ZMQ?</strong></p> <hr /> <p>ROS2 is typically based on subscribers and publishers to topics, in the same way that ZeroMQ uses them: messages are published under a path and only clients that are subscribed to (a base of) that path ...
<python><network-programming><ros><zeromq>
2024-06-27 09:51:03
2
1,123
Roberto
78,676,837
1,520,647
How to convert a string in python to separate strings
<p>I have a pandas dataframe with only one column containing symbols. I need to separate those symbols in groups of 13 and 39 inside a single string.</p> <pre><code>symbol 3IINFOTECH 3MINDIA 3PLAND 20MICRONS 3RDROCK 5PAISA 63MOONS 7SEASL ANNAINFRA AFEL ABCOTS.ST ABINFRA AKCAPIT AAL ASMTEC AAPLUSTRAD A2ZINFRA AMJUMBO AA...
<python><string><replace><text-extraction>
2024-06-27 09:46:41
2
1,841
Hamza Ahmed
78,676,743
2,049,685
Unable to strip whitespace from a string using pyparsing set_parse_action()
<p>I've got a generic &quot;text block&quot; element, for which I copied the whitespace-stripping code from the <a href="https://pyparsing-docs.readthedocs.io/en/latest/pyparsing.html" rel="nofollow noreferrer">documentation</a>:</p> <pre><code>import pyparsing as pp text_block = pp.Group( pp.OneOrMore( pp...
<python><string><whitespace><pyparsing><removing-whitespace>
2024-06-27 09:30:30
1
631
Michael Henry
78,676,602
2,575,970
How can I determine whether a Word document has a password?
<p>I am trying to read word documents using Python. However, I am stuck in places where the document is password protected, as I do not have the password for the file(s).</p> <p>How can I detect if the file has password, so can I ignore such files from opening?</p> <p>Currently, the below code opens a dialog/prompt win...
<python><passwords><win32com><doc>
2024-06-27 09:03:31
1
416
WhoamI
78,676,407
241,515
Polars: pandas equivalent of selecting column names from a list
<p>I have two DataFrames in polars, one that describes the meta data, and one of the actual data (LazyFrames are used as the actual data is larger):</p> <pre><code>import polars as pl df = pl.LazyFrame( { &quot;ID&quot;: [&quot;CX1&quot;, &quot;CX2&quot;, &quot;CX3&quot;], &quot;Sample1&quot;: [1, 1...
<python><python-polars>
2024-06-27 08:26:10
3
4,973
Einar
78,676,400
1,686,814
Customizing pygtk file chooser dialog
<p>I am creating a Gtk file chooser dialog as follows (see below for full example):</p> <pre><code>dialog = Gtk.FileChooserDialog( title=&quot;Select a File&quot;, action=Gtk.FileChooserAction.OPEN) </code></pre> <p>I would also like to add a checkbox and dropdown combobox as extra widgets. Adding one extra wid...
<python><user-interface><pygtk><filechooser>
2024-06-27 08:24:03
1
17,210
January
78,676,296
485,330
AWS Lambda Custom JWT Validation
<hr /> <p>I've built that first validates the JWT Token and then extracts the user unique ID (&quot;sub&quot;).</p> <p>In a non Lambda environment the script works fine, however in the AWS Lambda I'm having an error message.</p> <p><strong>What could be the problem?</strong></p> <blockquote> <p>Unexpected error during ...
<python><amazon-web-services><aws-lambda><jwt><amazon-cognito>
2024-06-27 08:05:38
1
704
Andre
78,676,276
8,005,367
pip install | How to install private project from the local file system when using requirements.txt?
<p>I'm trying to figure out how to properly use <code>python3.8 -m pip install</code> to install the requirements from <code>requirements.txt</code> AND simultaneously install certain packages from the local file system instead of from the repo. We have a few different private repos that we may need to work on simultan...
<python><python-3.x><pip>
2024-06-27 08:02:09
3
1,030
Ryan Pierce Williams
78,676,239
14,282,714
Column layout inside submit form streamlit
<p>I would like to have two <code>selectbox</code> elements side by side in a <a href="https://docs.streamlit.io/develop/api-reference/execution-flow/st.form" rel="nofollow noreferrer"><code>st.form</code></a> using a <code>st.columns</code> layout. Unfortunately the select boxes are out of the form. Here is some repro...
<python><streamlit>
2024-06-27 07:54:59
1
42,724
Quinten
78,676,206
20,920,790
How to avoid error ('cannot mix list and non-list, non-null values', 'Conversion failed for column position with type object') in Airflow?
<p>I got this task in my dag:</p> <pre><code>@task def get_result_from_records_api(api, tries: int, result_from_salons_api: list): salon_ids_list = result_from_salons_api[1] # result is 4 pd.DataFrames result_from_records_api = get_data_or_raise_error_with_retry(api.get_records_staff_sales_of_services_goods...
<python><airflow>
2024-06-27 07:47:40
1
402
John Doe
78,676,114
1,064,416
How to serve static files for django-cms on DigitalOcean?
<p>I have deployed a django-cms app on DigitalOcean following the steps in this tutorial:</p> <p><a href="https://www.digitalocean.com/community/tutorials/how-to-deploy-django-to-app-platform" rel="nofollow noreferrer">https://www.digitalocean.com/community/tutorials/how-to-deploy-django-to-app-platform</a></p> <p>The ...
<python><django><digital-ocean><django-cms>
2024-06-27 07:27:07
1
1,021
Rockbot
78,676,037
14,463,396
Turn a list of tuples into pandas dataframe with single column
<p>I have a list of tuples like:</p> <pre><code>tuple_lst = [('foo', 'bar'), ('bar', 'foo'), ('ping', 'pong'), ('pong', 'ping')] </code></pre> <p>And I want to create a Dataframe with one column containing each tuple pair, like:</p> <pre><code>| one col | | -------- | | ('foo', 'bar') | | ('bar',...
<python><pandas>
2024-06-27 07:09:19
1
3,395
Emi OB
78,675,981
4,578,454
python selenium Headless chrome doesn't scroll
<p>I'm working on a web scrapper to collect Facebook post comments for analytics purposes.</p> <p>On Facebook, after login, we can scroll the post page to get all the comments. Which dynamically loads the comments on the page scroll. Unfortunately, I can't get the page to scroll in the <code>headless</code> mode, thoug...
<python><google-chrome><selenium-webdriver>
2024-06-27 06:58:16
1
4,667
silverFoxA
78,675,968
6,936,582
Pandas compact rows when data is missing
<p>I have a list of dicts where each dict can have different keys. I want to create a dataframe with one row where each key is a column and the row is its value:</p> <pre><code>import pandas as pd data = [{&quot;A&quot;:1}, {&quot;B&quot;:2}, {&quot;C&quot;:3}] df = pd.DataFrame(data) print(df.to_string(index=False)) #...
<python><pandas><dataframe>
2024-06-27 06:55:16
2
2,220
Bera
78,675,944
3,486,684
Indexing numpy array of shape `(A, B, C)` with `[[a, b], [c, d], :]` (`0 <= a, b < A`, `0 <= c, d < B`) produces shape `(2, C)` instead of `(2, 2, C)`
<p>Here's the example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np A = np.random.randint(100) B = np.random.randint(100) C = np.random.randint(100) print(f&quot;{A=}, {B=}, {C=}&quot;) x = np.random.random((A, B, C)) print(f&quot;{x.shape=}&quot;) a = np.random.randint(0, A) b = np.random....
<python><numpy><numpy-slicing>
2024-06-27 06:50:32
1
4,654
bzm3r
78,675,541
7,478,147
Launch multiple server apps in localhost with different port numbers within the same container in Cloud Run
<p>I'm creating a webapp with 2 main services: Flask and <a href="https://docs.chainlit.io/get-started/pure-python" rel="nofollow noreferrer">Chainlit</a>.</p> <p>When I launch my webapp locally on <code>localhost:8080</code>, on my landing page, when I click on the &quot;chat&quot; button, it redirects me to my second...
<python><docker><flask><google-cloud-run><chainlit>
2024-06-27 04:32:45
1
359
Boubacar Traoré
78,675,466
2,955,827
Can I create a helper function for both async and sync environment?
<p>I'm trying to create helper function for my projects, but some legacy projects are in sync environment.</p> <p>my helper function looks like:</p> <pre class="lang-py prettyprint-override"><code>def func_for_async_and_sync(session, data): statement = select(Obj).where(Obj.id == data['id']) # and more code ...
<python><asynchronous>
2024-06-27 03:44:43
1
3,295
PaleNeutron
78,675,294
12,231,242
Tkinter place geometry manager not overlapping
<p>Over the past several years I've been using a full-featured combobox widget that I made by stitching together other Tkinter widgets. (Because I like it better than ttk.Combobox.) For the dropdown I've always used a Toplevel widget since it overlaps other widgets instead of pushing them aside. I've never been able to...
<python><tkinter>
2024-06-27 02:04:03
1
574
Luther
78,675,096
6,622,697
How to prevent flask-security from using db_session.query_property()
<p>I'm trying to setup flask-security using the example at <a href="https://flask-security-too.readthedocs.io/en/stable/quickstart.html" rel="nofollow noreferrer">https://flask-security-too.readthedocs.io/en/stable/quickstart.html</a>. I am using SQLAlchemy, not flask-sqlalchemy. I was able to get the example to work...
<python><flask><sqlalchemy><flask-security>
2024-06-27 00:04:24
1
1,348
Peter Kronenberg
78,675,005
9,952,624
Google Cloud Function error 401 by using service account key
<p>I am trying to authenticate in Python to GCP in order to call Cloud Functions.</p> <p>I have set up a service account with roles as follows <a href="https://i.sstatic.net/vvyDmTo7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vvyDmTo7.png" alt="enter image description here" /></a></p> <p>and created...
<python><google-cloud-platform><google-cloud-functions><google-iam>
2024-06-26 23:09:58
1
462
davide m.
78,674,923
20,295,949
Selenium WebDriver returns empty DataFrame when scraping CoinGecko in headless mode
<p>I'm trying to scrape Bitcoin market data from CoinGecko using Selenium in headless mode, but the script returns an empty DataFrame. The table rows are not being detected even though I've added a wait time. Here is a simplified version of the code I'm using to set up the WebDriver, navigate to the page, and extract t...
<python><selenium-webdriver>
2024-06-26 22:40:55
1
319
HamidBee
78,674,771
1,601,831
How to access app dependency in FastAPI when not injecting to endpoint
<p>FastApi app is defined in <code>main.py</code>. I need to do some initialization where I load from a database into a cache.</p> <p>When my app runs normally, it calls a get_db() function to return a <code>SqlServer</code> session and this get_db function is used in endpoints using <code>session=Depends(get_db)</code...
<python><unit-testing><dependencies><pytest><fastapi>
2024-06-26 21:41:16
2
417
dam
78,674,718
20,295,949
How to Bypass HTTP 403 Error When Scraping CoinGecko with Python?
<p>I am trying to scrape the Bitcoin markets section from CoinGecko using Python. However, I keep encountering a HTTP 403 error. I have tried using the requests library with custom headers to mimic a real browser, but I still get the same error.</p> <p>Here is the code I am using:</p> <pre><code>import requests import ...
<python><web-scraping><python-requests>
2024-06-26 21:23:37
1
319
HamidBee
78,674,589
8,322,295
Adjusting figure to center plots along bottom row
<p>I'm generating a figure with a variable number of plots. At the moment, if I use a number of plots that is not a multiple of three, the final plot(s) is left-aligned: <a href="https://i.sstatic.net/nKevFrPN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nKevFrPN.png" alt="enter image description here...
<python><matplotlib><plot><figure>
2024-06-26 20:39:08
0
1,546
Jim421616
78,674,475
985,573
Django is too slow when processing exception
<p>The view where the exception happens is processing a big dictionary with about ~350K entries. The exception is a KeyError.</p> <p>From what I can see from the CProfile logs, Django is trying to iterate the dictionary to get traceback data.</p> <p>This is simplified code from the view:</p> <pre><code>@login_required ...
<python><django><performance><exception>
2024-06-26 20:11:30
1
859
Aikanáro
78,674,456
4,691,343
Excel hangs in Python script to export excel as a pdf in Task Scheduler, but works normally
<p>I'm trying to just automate creating a pdf from an excel file to email it out everyday. It should be simple, but it isn't. If I run these files in command line, they will run, create the pdf, and close out of excel correct.</p> <p>But if I run it in task scheduler, not only does it refuse to create the pdf, but Exce...
<python><excel><powershell><scheduled-tasks><xlwings>
2024-06-26 20:08:04
1
453
arsarc
78,674,378
20,176,161
FastAPI: Loading a Model through Pickle and Making a Prediction. What is the best way to do it?
<p>I am building an API where I need to load a model through pickle and make a prediction</p> <p>The code is below:</p> <pre><code>from fastapi import FastAPI import uvicorn import joblib from utilities import * # upload the functions from schema import Customer # load the schema from sklearn.linear_model import Logi...
<python><async-await><python-asyncio><fastapi><pickle>
2024-06-26 19:46:01
1
419
bravopapa
78,674,335
3,486,684
Creating an enum with members whose attributes can be initialized
<p>From <a href="https://stackoverflow.com/a/62601113/3486684">this answer</a> I learned how to create an enum with attributes (i.e. additional data):</p> <pre><code>from typing import NamedTuple class EnumAttr(NamedTuple): data: str class EnumWithAttrs(EnumAttr, Enum): GREEN = EnumAttr(data=&quot;hello&quot;)...
<python><enums>
2024-06-26 19:35:13
2
4,654
bzm3r
78,673,978
8,150,186
Pydantic does not give precedence to os environment
<p>I am tyring to implement proper environment variable management across dev, prod and staging environments. Using Pydantic is critical since Pydantic is everywhere in the application.</p> <p>Testing this application becomes challenging due to the setting of os-based environment variables under production and dev env...
<python><pydantic><pydantic-settings>
2024-06-26 17:53:41
1
1,032
Paul
78,673,630
8,565,759
Pandas dataframe get location of col if name contains string and slice into multiple dataframes
<p>I am reading a .csv that has multiple time series columns, but each has a different name based on packets. My goal is to find the col names that contain the string 'TIME' and get their col numbers so that I can slice the df into multiple dfs with cols beginning with the time series col and ending before the next tim...
<python><pandas><dataframe>
2024-06-26 16:30:45
3
420
Brain_overflowed
78,673,610
23,260,297
Boolean indexing: How to select a specific value to create new column
<p>I have a dataframe which looks like this:</p> <pre><code>col1 col2 col3 X1 Nan Nan foo bar baz foo bar baz X2 Nan Nan foo bar baz foo bar baz X3 Nan Nan foo bar baz foo bar baz </code></pre> <p>I have filtered to look like this:</p> <pre><code>m = df.notna() print(m) </code></pre> <pre><code>co...
<python><pandas>
2024-06-26 16:27:24
2
2,185
iBeMeltin
78,673,568
2,066,572
Discovering which argument caused an error with Python CFFI
<p>I'm using the Python CFFI module to wrap functions that have multiple arguments of the same type. If I pass the wrong type to one of the arguments, CFFI gives an error identifying the actual type and the expected type, but not the variable name or position in the argument list.</p> <p>For example, the following code...
<python><python-cffi>
2024-06-26 16:17:25
1
438
jhaiduce
78,673,334
13,806,869
Why is my matplotlib boxplot completely blank?
<p>I have a pandas dataframe named 'target', with the following structure:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 200000 entries, 0 to 199999 Data columns (total 1 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 0 200000 non-null fl...
<python><matplotlib>
2024-06-26 15:25:13
0
521
SRJCoding
78,673,277
13,392,257
Can't find video tag
<p>I am trying to fetch tag url-content from the HTML code of site <a href="https://95jun.kinoxor.pro/984-univer-13-let-spustja-2024-07-06-19-54.html" rel="nofollow noreferrer">https://95jun.kinoxor.pro/984-univer-13-let-spustja-2024-07-06-19-54.html</a></p> <p>The site is triky. You can open it from this page (the fi...
<python><selenium-webdriver><seleniumwire>
2024-06-26 15:14:49
3
1,708
mascai
78,673,228
9,363,181
Unable to read text file in Glue job
<p>I am trying to read the <code>schema</code> from a <code>text</code> file under the same package as the code but cannot read that file using the <strong>AWS glue job</strong>. I will use that <code>schema</code> for creating a dataframe using <code>Pyspark</code>. I can load that file locally. I am zipping the code ...
<python><python-3.x><amazon-web-services><pyspark><aws-glue>
2024-06-26 15:03:12
2
645
RushHour
78,673,098
14,642,180
Does the Intensity of color in OpenCV image matter?
<p>Here is a simple code which puts a text value onto a black frame and displays it:</p> <pre><code>frame = np.zeros((50,200,3)) org=(0,45) font=cv2.FONT_HERSHEY_SIMPLEX fontScale=1 fontColor=(1,0,0) ##rgb out_img = cv2.putText(frame, &quot;text&quot; , org, font, fontScale, fontColor) plt.imshow(out_img) </code><...
<python><numpy><opencv><matplotlib><image-processing>
2024-06-26 14:40:30
0
1,475
Allohvk
78,673,089
9,640,238
Streamlit session variable does not persist on chat
<p>I am trying to implement a chat with Streamlit, where I need to keep a counter of words being exchanged, essentially starting from <a href="https://quickstarts.snowflake.com/guide/asking_questions_to_your_own_documents_with_snowflake_cortex/#4" rel="nofollow noreferrer">this</a>.</p> <p>So I initialize a session var...
<python><streamlit>
2024-06-26 14:39:23
1
2,690
mrgou
78,672,909
5,552,507
pyvista export does not preserve multiline texts
<p>I am rendering a mesh with Pyvista (version 0.43.5) and I have a problem with multiline texts at export.</p> <p>In the interactive window and when I take a screenshot, a multiline title (or any other multiline text) is rendered well. But when I export to svg, the multiline is gone:</p> <div class="s-table-container"...
<python><vtk><pyvista>
2024-06-26 14:03:05
1
307
PiWi
78,672,808
8,315,819
Sub-domain Enumeration - socket.gaierror: [Errno 11001] getaddrinfo failed
<p>I am trying to do sub-domain enumeration in my organization. Part of the python code is to get the IPs of the already enumerated sub-domains which are included in a text file . Used the below code</p> <pre><code>import socket file = open(r'C:\Users****\Downloads\sublist.txt') domain_list = [] for x in file.readline...
<python><dns><vpn>
2024-06-26 13:44:43
1
445
Biswa
78,672,803
9,506,773
Azure keyword recognition model (`.table`) not working when feeding it wave files
<p>I have the following script:</p> <pre class="lang-py prettyprint-override"><code>import time import azure.cognitiveservices.speech as speechsdk import logging # Configure logging logging.basicConfig(level=logging.INFO) # The phrase your keyword recognition model triggers on. KEYWORD = &quot;KEYWORD&quot; def rec...
<python><azure><azure-speech>
2024-06-26 13:43:45
1
3,629
Mike B
78,672,622
14,282,714
Insert data to supabase with python
<p>I would like to import some data to a <code>supabase</code> using Python. I followed the documentation like <a href="https://supabase.com/docs/reference/python/insert" rel="nofollow noreferrer">here</a>, which suggests that we can use the <code>supabase.table</code> attribute to <code>.insert</code> data. I tried th...
<python><supabase>
2024-06-26 13:10:22
2
42,724
Quinten
78,672,585
15,913,281
Python "Explode" Keys in Dict
<p>Given a dict like the one below how do I &quot;explode&quot; the keys to create a new dict with the keys split out? Each key should be split on &quot; n &quot;.</p> <pre><code>original_dict = {&quot;AB n DC&quot;: [12, 13], &quot;JH n UY&quot;: [22, 1]} new_dict = {&quot;AB&quot;: [12, 13], &quot;DC&quot;: [12, 13]...
<python>
2024-06-26 13:01:57
3
471
Robsmith
78,672,415
539,490
Pydantic model field with default value does not pass type checking
<p>The following code shows a pylance (pyright) error for <code>AModel()</code> of <code>Argument missing for parameter &quot;field_b&quot;</code>:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel, Field from typing import Optional, Any class AModel(BaseModel): field_a: str = Field...
<python><python-typing><pydantic><pyright>
2024-06-26 12:29:14
1
29,009
AJP
78,672,251
20,920,790
How fix error Object of type *** is not JSON serializable in Airflow?
<p>I make custom library for working with API. But I get error then trying to use it in my dag.</p> <p>Then I run my dag I get error for <code>connect_to_api</code> task:</p> <pre><code>{python.py:202} INFO - Done. Returned value was: [&lt;yclients.yclientsapi object at 0x7f5a0fb87890&gt;] {xcom.py:664} ERROR - Object ...
<python><airflow>
2024-06-26 11:55:06
2
402
John Doe
78,672,244
2,177,047
Debugging Pandas to_sql function
<p>I use the following code to insert a DataFrame into an MS SQL Server database.</p> <p><code>data</code> is a pd.DataFrame that has the same columns as the database.</p> <pre><code>from sqlalchemy import create_engine engine = create_engine(f'mssql+pyodbc:///?odbc_connect={connection_string}', fast_executemany=True) ...
<python><sql-server><pandas><sqlalchemy><pyodbc>
2024-06-26 11:53:58
1
2,136
Ohumeronen
78,671,947
5,594,490
Flask login to a custom page
<p>By Default when using flask login it expects a path /login. I am trying to use another page /test/login but it is not working and giving error. Here is the required code snippet. Please let me know what I am doing wrong here</p> <pre><code>login_manager.login_view = &quot;test/login&quot; @app.route('/test/login') ...
<python><flask-login>
2024-06-26 10:52:47
1
481
Amol
78,671,781
10,829,044
pandas dataframe index to html merged cell
<p>I have a pandas dataframe like as below</p> <pre><code>import pandas as pd data = { 'A': [1, 1, 2, 2, 3], 'B': [10, 10, 20, 20, 30], 'C': [100, 101, 200, 201, 300], 'D': ['X', 'X', 'Y', 'Y', 'Z'], 'E': ['Alpha', 'Beta', 'Beta', 'Gamma', 'Gamma'], 'F': [1000, 1001, 1002, 1003, 1004] } df = pd....
<python><html><css><pandas><dataframe>
2024-06-26 10:17:05
1
7,793
The Great