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
76,344,199
1,812,732
How to read FastAPI UploadFile as text one line at a time
<p>I am making a REST API using FastAPI and Python. For example here is an api that takes an uploaded file, and returns an array that with the length of each line.</p> <pre><code>router = APIRouter() @router.post('/api/upload1') async def post_a_file(file: UploadFile): result = [] f = io.TextIOWrapper(fil...
<python><post><fastapi>
2023-05-26 21:11:37
1
11,643
John Henckel
76,344,145
2,749,397
Explain the error produced using plt.legend in a 3D stacked bar plot
<p><a href="https://i.sstatic.net/m5OIV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/m5OIV.png" alt="enter image description here" /></a></p> <p>The figure above was produced by this code</p> <pre><code>%matplotlib import numpy as np import matplotlib.pyplot as plt x = y = np.array([1, 2]) fig = plt....
<python><matplotlib><legend><matplotlib-3d><bar3d>
2023-05-26 20:58:19
1
25,436
gboffi
76,344,134
343,159
In Python, how to yield the results of the call to another class's function?
<p>Very little experience of Python, struggling with the best pattern here.</p> <p>I have a generator function, and I would like this function to <code>yield</code> the return value of another function until exhausted. This is using the streaming feature of <a href="https://docs.haystack.deepset.ai/docs/prompt_node#str...
<python><grpc-python><haystack>
2023-05-26 20:56:11
1
12,750
serlingpa
76,344,056
4,419,423
Pandas: sequence data over date based on column change
<p>i have timeseries data spanning multiple days that i need to sequence (i.e., create a column each time a value changes). i have the sequencing working without groupby, but i'm a little lost on how to apply the same or similar code to the grouped data.</p> <p>my data looks like:</p> <pre><code>index timestamp ...
<python><pandas><group-by><sequence>
2023-05-26 20:37:45
1
3,984
niko
76,343,899
1,018,733
Python doctest dictionary equality test with a strange failure (python bug?)
<p>This test isn't failing appropriately. What is wrong?</p> <p>This incorrectly passes!?</p> <pre><code>def drop_keys_conditionally(some_dict): &quot;&quot;&quot;Weird bug where the dictionary equality shouldn't pass but does &gt;&gt;&gt; d = {'check': '...lala...', 'a': 'a', 'b': 'b', 'key': 'val', 'c': ...
<python><pytest><doctest>
2023-05-26 19:57:31
1
4,510
SwimBikeRun
76,343,898
3,507,584
AWS EB CLI - 'eb' is not recognized as an internal or external command
<p>I installed AWS with Python 3.11 in my PC. later I uninstalled Python 3.11 to use Python 3.10 but when I run <code>aws --version</code> it still shows Python 3.11.</p> <p><a href="https://i.sstatic.net/JK9VS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JK9VS.png" alt="enter image description here" ...
<python><amazon-web-services><amazon-elastic-beanstalk><aws-cli>
2023-05-26 19:57:26
1
3,689
User981636
76,343,773
13,793,478
typeError: fromisoformat: argument must be str,
<p>I trie many solutions from the internet nothing worked.. thanks in advance</p> <p>Error</p> <pre><code>typeError: fromisoformat: argument must be str </code></pre> <p>view.py</p> <pre><code>def notes(request): now = datetime.datetime.now() month = now.month year = now.year cal = HTMLCalendar() ...
<python><django>
2023-05-26 19:32:53
1
514
Mt Khalifa
76,343,741
14,057,599
How to get a batch of binary masks from segmentation map without using `for` loop
<p>suppose I have a segmentation map <code>a</code> with dimension of <code>(1, 1, 6, 6)</code></p> <pre><code>print(a) array([[[[ 0., 0., 0., 0., 0., 0.], [ 0., 15., 15., 16., 16., 0.], [ 0., 15., 15., 16., 16., 0.], [ 0., 13., 13., 9., 9., 0.], [ 0., 13., 13., 9., 9., ...
<python><numpy>
2023-05-26 19:27:42
1
317
Qimin Chen
76,343,683
12,404,524
Running multiple processes in each iteration of loop in Python
<p>I have two functions <code>func_1</code> and <code>func_2</code>. They both take an array of integers as input.</p> <p>I have a loop that creates arrays of length <code>i</code> in the <code>i</code>th iteration.</p> <p>I have two predefined lists <code>list_1</code> and <code>list_2</code> intended to store the out...
<python><multiprocessing><cpython>
2023-05-26 19:16:13
2
1,006
amkhrjee
76,343,624
3,948,658
AWS CDK Failing with: "Error: There are no 'Public' subnet groups in this VPC. Available types:"
<p>I am using the AWS CDK in Python to spin up infrastructure. However whenever I add the CDK code to create an EC2 instance resource I get the following error when running <strong>cdk deploy</strong>:</p> <blockquote> <p>Error: There are no 'Public' subnet groups in this VPC. Available types:</p> </blockquote> <p>And ...
<python><amazon-web-services><amazon-ec2><aws-cdk><amazon-vpc>
2023-05-26 19:05:48
2
1,699
dredbound
76,343,623
13,982,165
match.group for array of named groups / strings python
<p>I'm parsing strings with following format:</p> <pre><code>ADD id='5' titulo='The Diary of a Young Girl' autor='Anne Frank' ADD id='5' titulo='The Diary of a Young Girl' autor='Anne Frank' SEARCH id='5' REMOVE id='10' REMOVE id='5' SEARCH id='5' ADD id='8' titulo='The Fault in Our Stars' autor='John Green' ADD i...
<python><regex>
2023-05-26 19:04:50
0
375
nluizsoliveira
76,343,508
9,780,918
Reading csv with pandas and it gets NA values
<p>How can I solve in pandas when I want to read a csv file and it has a NaN somewhere?</p> <p>it returns:</p> <blockquote> <p>ValueError: Integer column has NA values in column 22</p> </blockquote> <pre><code>def read_csv_file(filename): dtypes = { 'transaction': int, 'kev': int, 'companyNa...
<python><pandas>
2023-05-26 18:44:07
1
760
Julián Oviedo
76,343,486
19,055,149
setuptools: include converted data files into the wheel, keeping originals in the source distribution
<p>In my case, parsing the original data is slower than deserialising pickles. I'm trying to transform data during <code>setuptools</code> build:</p> <pre class="lang-py prettyprint-override"><code>from setuptools.command.build_py import build_py ROOT = Path(__file__).resolve().parent DATA_DIR = ROOT / 'data' OUT_DIR ...
<python><setuptools><setup.py><python-packaging>
2023-05-26 18:40:08
0
419
Nil Admirari
76,343,407
6,457,407
Python equivalent to `PyArrayContiguousFromAny`?
<p>Is there a Python equivalent to the C API's function:</p> <pre><code>PyArray_ContiguousFromAny(PyObject* op, int typenum, int min_depth, int max_depth) </code></pre> <p><code>numpy.ascontiguousarray(a, dtype)</code> seems close, but it doesn't take a <code>min_depth</code> or <code>max_depth</code> argument giving ...
<python><numpy><swig>
2023-05-26 18:25:08
0
11,605
Frank Yellin
76,343,217
1,305,420
Setting maxBytes on RotatingFileHandler causes Formatter.format() to be called twice per record
<p>Can someone explain why setting <code>maxBytes</code> on <code>RotatingFileHandler</code> causes <code>DerivedFormatter.format()</code> to be called twice per log record? Ultimately, only 1 entry makes it to the log file, but I want to have some logic performed in <code>DerivedFormatter.format()</code> that shouldn'...
<python><logging>
2023-05-26 17:48:06
1
368
kernelk
76,343,191
554,481
Understanding large difference in cache hits
<p>I'm working on a Leetcode hard-tagged dynamic programming <a href="https://leetcode.com/problems/profitable-schemes/description/" rel="nofollow noreferrer">problem</a>. My solution is 16x slower than a solution I found in the discussion section, and I'd like to better understand why.</p> <p>Historically the recurren...
<python><dynamic-programming>
2023-05-26 17:44:59
0
2,075
user554481
76,343,100
15,170,662
How to convert WMF/EMF to PNG/JPEG in Python?
<p>I need to convert a <code>.wmf</code> file to a <code>.png</code> format.</p> <p>I can't use libraries under the *GPL license.</p> <p>Solutions that use external dependencies (such as inkscape or libreoffice in a subprocess) are also not suitable for my project. Using external libraries in the system(installed by <c...
<python><image><python-imaging-library><vector-graphics><wmf>
2023-05-26 17:28:18
0
415
Meetinger
76,342,866
897,041
How to decide if a command execution is complete while interacting with a CLI tool through python?
<p>I'm running beeline.sh through a python script and reading its output after submitting numerous sequential SQL queries to be executed through it. I can't send all queries in a single run, I have to run each of these queries and inspect their effect individually.</p> <p>Unfortunately I can't reliably decide if a quer...
<python><python-3.x><stream><command-line-interface><beeline>
2023-05-26 16:48:50
0
4,028
Muhammad Gelbana
76,342,657
16,383,578
How to optimize NumPy Sieve of Eratosthenes?
<p>I have made my own Sieve of Eratosthenes implementation in NumPy. I am sure you all know it is for finding all primes below a number, so I won't explain anything further.</p> <p>Code:</p> <pre><code>import numpy as np def primes_sieve(n): primes = np.ones(n+1, dtype=bool) primes[:2] = False primes[4::2]...
<python><python-3.x><numpy><primes><sieve-of-eratosthenes>
2023-05-26 16:18:29
1
3,930
Ξένη Γήινος
76,342,437
10,108,332
How can I scrape an embedded image url from xlsx spreadsheet
<p>I have Excel spreadsheets that have an image per row, scraping the image using <a href="https://stackoverflow.com/questions/62039535/extract-images-from-excel-file-with-python">this example</a> works. However what I want to do instead of scraping the image of the spreadsheet is I want to extract the url associated w...
<python><pandas><excel><xlsx><imageurl>
2023-05-26 15:56:50
1
1,070
Sharp Dev
76,342,420
1,761,521
Polars get unique values from List[Any]
<p>I want to get a list of unique values from a column of list[str],</p> <pre><code>import polars as pl data = [ {&quot;name&quot;: &quot;foo&quot;, &quot;tags&quot;: [&quot;A&quot;, &quot;B&quot;]}, {&quot;name&quot;: &quot;bar&quot;, &quot;tags&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]}, {&quo...
<python><python-polars>
2023-05-26 15:53:47
2
3,145
spitfiredd
76,342,379
8,087,322
`__main__.py` structure with argparse, pytest and sphinxdoc
<p>For a small module, I want to have a <code>__main__.py</code> file that is executed via Pythons <code>-m</code> argument. As per basic docs, this file looks like</p> <pre><code>import argparse from . import MyClass def getparser(): parser = argparse.ArgumentParser() # […] return parser if __name__ ==...
<python><pytest><python-sphinx><runpy>
2023-05-26 15:48:43
1
593
olebole
76,342,215
13,874,745
Can't instantiate abstract class when I use `Dataset` in torch_geometric
<p>I try to establish a class that inherit from <code>Dataset</code> of <code>torch_geometric</code>, the codes are:</p> <pre class="lang-py prettyprint-override"><code>from torch_geometric.data import Data, Dataset import numpy as np class GraphTimeSeriesDataset(Dataset): def __init__(self): # Initialize ...
<python><pytorch><pytorch-dataloader><pytorch-geometric>
2023-05-26 15:26:48
1
451
theabc50111
76,342,140
11,649,050
Error when applying Pytorch pre-trained weights' transform on Huggingface dataset
<p>I'm trying to train/fine-tune the MobileNetV3 model on the CIFAR100 dataset. I'm using Pytorch and Huggingface to simplify things like training loop which I'm not used to having to do manually coming from Tensorflow/Keras.</p> <p>However, I get an error when trying to apply the pre-trained weights' transform (prepro...
<python><pytorch><huggingface-datasets>
2023-05-26 15:17:50
1
331
Thibaut B.
76,341,832
2,110,476
How to pass a variable from init to parse_item in Scrapy CrawlSpider?
<p>Maybe it's the wrong approach alltogether. I'd be happy about an alternative approach as well, if you have an idea.</p> <ol> <li>Connect to my DB, get the next batch of seed URLs (as a dict, with some other info)</li> <li>Add their URL/domains to <code>start_urls</code> and <code>allowed_domains</code></li> <li>With...
<python><scrapy>
2023-05-26 14:36:15
0
1,357
Chris
76,341,802
13,154,227
pyodbc: works in 3.7.2 but breaks in 3.11.3
<pre><code>import pyodbc my_db_path = r'C:\testing\mydb.accdb' my_db_pw = r'djw85nawj12' conn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;PWD=%s' % (my_db_path, my_db_pw)) #in python 3.7.2 (pyodbc 4.0.32) -&gt; works, returns conn object #in python 3.11.3 (pyodbc 4.0.39) -&gt; error:...
<python><python-3.x><pyodbc><python-3.11>
2023-05-26 14:33:09
0
609
R-obert
76,341,655
1,823,476
Store and evaluate a condition in an instance variable
<p>I start my question by describing the use case:</p> <p>A context-menu should be populated with actions. Depending on the item for which the menu is requested, some actions should be hidden because they are not allowed for that specific item.</p> <p>So my idea is to create actions like this:</p> <pre class="lang-py p...
<python><lambda><pyqt5><qaction>
2023-05-26 14:12:11
1
711
chrset
76,341,623
158,668
Error: "Subprocess exited with error 9009" when running cdk
<p>I've installed the <a href="https://aws.amazon.com/cdk/" rel="nofollow noreferrer">AWS CDK (Cloud Development Kit)</a> on Windows 10 and have tried to deploy an existing CDK stack using python on my AWS account.</p> <p>When running different <code>cdk</code> commands, I get the following error message:</p> <pre><cod...
<python><windows><amazon-web-services><aws-cdk>
2023-05-26 14:09:04
1
51,850
Dennis Traub
76,341,381
6,195,489
Get dict from list of dicts with the maximum of two items
<p>I would like to get the dict in a list of dicts which has the maximum of two values:</p> <pre><code>manager1={&quot;id&quot;:&quot;1&quot;,&quot;start_date&quot;:&quot;2019-08-01&quot;,&quot;perc&quot;:20} manager2={&quot;id&quot;:&quot;2&quot;,&quot;start_date&quot;:&quot;2021-08-01&quot;,&quot;perc&quot;:20} manag...
<python><list><dictionary>
2023-05-26 13:41:10
1
849
abinitio
76,341,366
8,869,570
How to generalize an inherited method call and a composed method call
<p>At work, I'm running into an issue where a piece of code takes in a class object, <code>obj</code>, where the object can be one of multiple classes. The code makes the following call:</p> <pre><code>obj.compute() </code></pre> <p>For one of the classes, <code>MyClass</code>, I made a refactorization from using inher...
<python><inheritance><composition>
2023-05-26 13:39:51
1
2,328
24n8
76,341,333
512,480
Coloring the background of a ttk button
<p>I got some helpful code from GeeksForGeeks and modified it slightly. It colors the text, but no, I wanted something different: I wanted to make the background blue. I tried what I hoped would work, but no, background means &quot;what it looks like when the window is in the background&quot;. And anyway, it doesn't w...
<python><tkinter><button><ttk>
2023-05-26 13:36:15
1
1,624
Joymaker
76,341,318
2,304,575
Calling MPI subprocess within python script run from SLURM job
<p>I am having trouble launching a SLURM job calling a <code>mpirun</code> subprocess from a python script. Inside the python script (let's call it <code>script.py</code>) I have this <code>subprocess.run</code>:</p> <pre><code> import subprocess def run_mpi(config_name, np, working_dir): data_path = working_dir ...
<python><subprocess><mpi><slurm><hpc>
2023-05-26 13:34:49
0
692
Betelgeuse
76,341,244
3,870,664
Ruff Ignore Inline or Function Rule Check
<p>I am using <code>ruff==0.0.265</code> I have a single function I expect to have complexity and do not wish to change that.</p> <pre><code>src/exceptions.py:109:5: C901 `convert_py4j_exception` is too complex (11 &gt; 10) src/exceptions.py:109:5: PLR0911 Too many return statements (10 &gt; 6) </code></pre> <p>How do ...
<python><python-3.x><ruff>
2023-05-26 13:25:44
1
1,508
vfrank66
76,341,205
5,889,169
Python - Pass a function as argument/parameter to create a dynamic script
<p>I have a python script that reads messages from a Kafka topic, run some custom filtering, and produce a new message to another Kafka topic.</p> <p>Currently the script accepts 2 arguments: <code>--source_topic</code> and <code>--target_topic</code>. script pseudo code:</p> <pre><code>for each message in source_topic...
<python><apache-kafka>
2023-05-26 13:20:50
1
781
shayms8
76,341,124
2,463,948
scipy.signal not defined, but works after importing skimage
<p>I would like to use <code>scipy.signal.convolve2d()</code> function from <a href="https://scipy.org/" rel="nofollow noreferrer">SciPy</a>, but <code>signal</code> is undefined:</p> <pre><code>&gt;&gt;&gt; import scipy ... &gt;&gt;&gt; conv = scipy.signal.convolve2d(data, kernel, mode=&quot;same&quot;) Error: Traceb...
<python><python-3.x><scipy>
2023-05-26 13:10:48
1
12,087
Flash Thunder
76,340,986
14,860,526
SSLError in python requests due to self-signed certificate
<p>I'm working for a company that has a an internal network. When I connect to the website <em>https://engine.my_company.com</em> through the browser everything is ok, even if I look at the certificates in the browser they seem legit. However if I run a request to the website with python:</p> <pre><code>url = &quot;htt...
<python><python-requests><ssl-certificate>
2023-05-26 12:49:24
1
642
Alberto B
76,340,978
3,182,044
Relative import of a module with a dependency
<p>I have a python script that imports another class called <code>myClass</code> from a relative path. Next to <code>myClass.py</code> lies a csv-file from which a dataframe is generated when calling <code>myClass()</code>. This dependency on the file forces me to change the directory to the relative path when creating...
<python><python-import>
2023-05-26 12:48:06
0
345
dba
76,340,960
21,346,793
CUDA to docker-container
<p>I need to make docker of my server, but it works only with cuda, how can i add it in my Dockerfile?</p> <pre><code>FROM python:3.10 ENV FLASK_RUN_PORT=5000 RUN sudo nvidia-ctk runtime configure # Here COPY . /app WORKDIR /app RUN pip install --no-cache-dir -r requirements.txt EXPOSE 5000 CMD [&quot;python&quo...
<python><docker><deployment><dockerfile>
2023-05-26 12:44:24
1
400
Ubuty_programmist_7
76,340,789
7,678,074
How to avoid/stop webpage flickering with python selenium firefox
<p>I am trying to scrape a webpage to download some images. For this I need to:</p> <ul> <li>get image elements</li> <li>loop through them and download each one, where download means: <ul> <li>right-click</li> <li>press download button</li> </ul> </li> <li>scroll down the page to get new elements</li> </ul> <p>However,...
<python><selenium-webdriver><web-scraping><firefox>
2023-05-26 12:24:11
0
936
Luca Clissa
76,340,729
3,813,064
Persisting TemporaryFile in Python without rewriting it | Call linkstat in python on fd
<p>I have a library that provides me with a <code>TemporaryFile</code> object which I would like to persist on the file system it was stored, <strong>without rewriting it</strong>: The file could be quite huge and performance is critical. I am working in an Linux/POSIX environment.</p> <p>The <a href="https://docs.pyth...
<python><python-3.x><posix><ctypes><cpython>
2023-05-26 12:15:41
0
2,711
Kound
76,340,691
13,158,157
Power Automate Flow HTTP request: know when flow is done
<p>I am triggering my Power Automate Flow with an HTTP request send thru pythons request module. The response I get is 202, what stands for request is accepted to processing.</p> <p>How can I make python wait until Power Automate is finished or alternatively is there a way to to make Power Automate send additional resp...
<python><http><python-requests><power-automate>
2023-05-26 12:11:19
0
525
euh
76,340,611
6,195,489
Get information from xml with element tree
<p>I am trying to use elementTree to get at information in an xml response.</p> <p>The response <code>xmlresponse.xml</code> looks like:</p> <pre><code>&lt;result xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;https://somewhere.co.uk/&quot;&gt; &lt;count&gt;1&lt;/count&gt; ...
<python><xml><elementtree>
2023-05-26 12:00:49
1
849
abinitio
76,340,526
1,341,855
How to merge 2 datasets with Python / Pandas?
<p>I have two pandas datasets:</p> <pre><code> Name A B 1 Michael 1 2 2 Peter 3 4 </code></pre> <p>and</p> <pre><code> Name C D 1 Peter 8 9 2 John 5 6 </code></pre> <p>How can I merge these datasets to get the following result:</p> <pre><code> Name ...
<python><pandas><numpy>
2023-05-26 11:49:24
1
538
Michael
76,340,511
6,876,149
gurobi basic example how to print the total minimal cost?
<p>I am using gurobipy to solve a transportation problem in python. Transportation Problem, is a linear programming (LP) problem that identifies an optimal solution for transporting one type of product from sources (i) to destinations (j) at the minimum cost (z). You can read more about it in <a href="https://www.linke...
<python><gurobi>
2023-05-26 11:47:11
1
2,826
C.Unbay
76,340,245
11,720,193
GET file from URL and store in S3
<p>I am required to download a <code>.gz</code> file (using GET) from a URL, <code>uncompress</code> it and then store it in <code>S3</code>.</p> <p>I have written the following code to download file to a directory but I am struggling to uncompress it and store it in S3.</p> <pre><code>URL= https://api.botify.com/v1/jo...
<python><amazon-web-services><amazon-s3><python-requests>
2023-05-26 11:12:28
0
895
marie20
76,340,102
6,389,268
Reverse pandas string / reverse extract pandas DF
<p>Good day,</p> <p>I got files with path in column thus:</p> <pre><code>pd.DataFrame({'path':[ 'C:/some_1_path/file_1.zip', 'C:/some_1_path/file_2.zip'] </code></pre> <p>I wish to extract the pattern _\d from this like this:</p> <pre><code>'C:/some_1_path/file_1.zip'| '_1' 'C:/some_1_path/file_2.zip'| '_2' </code></p...
<python><pandas><dataframe><extract><reverse>
2023-05-26 10:54:47
2
1,394
pinegulf
76,340,028
166,229
Overwrite type hint of 3rd party library (for monkey patching)
<p>I am monkey-patching a class from a 3rd party library (playwright in my case) and also want to adjust the type hinting to include my adjustment. Is there a way somehow to overwrite or augment types from 3rd party libraries?</p> <pre class="lang-py prettyprint-override"><code>## # Monkey-patching ## from playwright.s...
<python><python-typing><pyright>
2023-05-26 10:43:44
0
16,667
medihack
76,339,979
18,018,869
Separate axis in two parts, give each a label and put it in a box
<p>My current approach does not automatically center the 'HIGH' and 'LOW' descriptions. I would like them automatically centered at 25% and 75% of corresponding axis. Another phrasing: I want the 'HIGH' label exactly centered inside its surrounding box.</p> <p>Maybe I chose a too complicated approach... Maybe a <code>B...
<python><matplotlib>
2023-05-26 10:35:56
1
1,976
Tarquinius
76,339,879
5,807,524
How to prevent/warn on reassignment to Python function arguments?
<p>I would like to prevent function arguments being reassigned in Python, like Java's <code>final</code> or C's <code>const</code> modifer.</p> <p>For example, the following code should not be considered valid:</p> <pre class="lang-python prettyprint-override"><code>def update_bars_in_foos(foo: Foo, bars: List[str]): ...
<python>
2023-05-26 10:20:38
1
475
Patryk Koryzna
76,339,790
8,055,025
Python support for NSTREAM?
<p>Does NSTREAM (formerly know as SWIM) have Python support? I can see the documentations and development in Java, but not on Python.</p>
<python>
2023-05-26 10:07:31
2
2,063
Ankit Sahay
76,339,607
1,736,407
Invoking a dataproc workflow from yaml file using cloud function
<p>I am trying to write a Google cloud function that invokes a Dataproc workflow from a YAML template stored in a storage bucket. The template must accept parameters. I have pieced together what I have so far from various sources, and I feel like I am running in circles trying to get this right.</p> <p>The relevant bit...
<python><google-cloud-platform><google-cloud-functions><google-cloud-dataproc><google-workflows>
2023-05-26 09:47:31
0
2,220
Cam
76,339,555
4,438,445
How to monkeypatch '__name__' with pytest
<p>I have a file 'mymodule.py' that I want to test with 100% coverage using pytest. This is the content of the file:</p> <pre><code>def important_function(): print('I can test this function easily.') if __name__ == '__main__': print('I want to test this part.') assert False </code></pre> <p>I want to test ...
<python><pytest>
2023-05-26 09:40:50
0
745
Marcos
76,339,453
10,715,700
IPython web server or other alternatives?
<p>Does IPython have a web server mode to run code submitted through REST APIs? I couldn't find any info on this. Are there any alternatives to this?</p> <p>My use case is similar to an online interpreter, but I want the code to run on the machine where the server is running (to be able to import packages and modules, ...
<python>
2023-05-26 09:27:00
1
430
BBloggsbott
76,339,434
3,751,931
build ignores specified version value
<p>I am building a python project using this <code>pyproject.toml</code> file</p> <pre><code>[tool.poetry] name = &quot;my_package&quot; version = &quot;1.0.0&quot; description = &quot;My precious&quot; readme = &quot;README.md&quot; [tool.poetry.dependencies] pandas = &quot;1.4.3&quot; numpy = &quot;1.22.4&quot; scik...
<python><build>
2023-05-26 09:24:10
1
2,391
shamalaia
76,339,387
274,460
Is there a good way of referring to a collection of exceptions?
<p>I have a database access layer that I maintain. There are some operations that can raise a variety of exceptions, some of them local to the library and some of them builtins or from other libraries. Is there a good way to declare a collection of them so that users of the library can refer to them easily?</p> <p>I'...
<python><python-3.x><exception>
2023-05-26 09:19:26
1
8,161
Tom
76,339,232
14,076,103
Pyspark pivot with Dynamic columns
<p>I have Pyspark Dataframe as follows,</p> <p><a href="https://i.sstatic.net/aWjCk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aWjCk.png" alt="enter image description here" /></a></p> <p>I am pivoting the data based Month and T columns and need to produce the following output.</p> <p><a href="https...
<python><apache-spark><pyspark><apache-spark-sql><pivot>
2023-05-26 08:58:16
1
415
code_bug
76,339,162
1,422,096
pythonnet clr: how to get the signature of a function/method?
<p>When importing a .NET library in Python with:</p> <pre><code>import clr clr.AddReference(r&quot;C:\foo.dll&quot;) from foo import * my_foo = Foo() print(my_foo.my_method) # &lt;bound method 'my_method'&gt; </code></pre> <p>I'd like to know the signature of the function (its parameters). This doesn't work:</p> <pre>...
<python><clr><signature><python.net><method-signature>
2023-05-26 08:48:15
1
47,388
Basj
76,339,153
8,869,003
makemigrations-command doesn't do anything
<p>My production django-server uses postgres 12.12, django 32 and python 3.7. My test-server uses the exactly same software, but postgress 12.15.</p> <p>After adding a new table 'etusivu_heroimg' I copied contents of the production postgres into my test postgres database and run <code>python manage.py makemigrations</c...
<python><django><postgresql>
2023-05-26 08:46:02
0
310
Jaana
76,339,133
3,789,481
Is it possible to deploy Flask to Azure with external directories?
<p>Let's say I have following structure</p> <pre><code>root/ - app/ - flask_app.py - requirements.txt - shared_libs/ - lib.py - others/ </code></pre> <p>The shared folder is used for either flask_app.py and other processing that can reference to. As it is stored outside of the flask_app, it could only run in loca...
<python><flask><azure-web-app-service>
2023-05-26 08:44:12
1
2,086
Alfred Luu
76,339,067
13,154,227
pyodbc with msaccess: too few parameters. Trying to set date to yesterday in a column
<pre><code>import pyodbc conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\testing\mydb.accdb') crs = conn.cursor() crs.execute('UPDATE [testtable] SET &quot;dateoflastchange&quot; = DATEADD(&quot;d&quot;, -1, DATE())') # Too few parameters. Expected 1 </code></pre> <p>I tried replacing DA...
<python><ms-access><pyodbc>
2023-05-26 08:34:59
2
609
R-obert
76,338,888
1,021,819
How can I use a third-party context manager to run a custom-class's method?
<p>In python, I'd like to use a <code>with</code>-statement context manager when using a particular third-party package because their context manager will handle clean-up for me in a best-practice way.</p> <p>Right now I have (say):</p> <pre class="lang-py prettyprint-override"><code>class MyClass(object): def __i...
<python><object><with-statement><contextmanager>
2023-05-26 08:11:09
1
8,527
jtlz2
76,338,880
8,547,163
How to save large set of rows and columns from .xlsx output in a file
<p>I have a <code>.xlsx</code> file with large set of rows and columns, and I would like to save the desired output in .csv or .txt file.</p> <pre><code>import pandas as pd def foo(): data = pd.read_excel('file/path/filename.xlsx') print(data) f = open('Output.txt', 'w') print(data.head(50),file = f...
<python><pandas>
2023-05-26 08:10:17
2
559
newstudent
76,338,851
716,682
Using Pybind11 and access C++ objects through a base pointer
<p>Suppose I have the following C++ classes:</p> <pre class="lang-cpp prettyprint-override"><code>class Animal { public: virtual void sound() = 0; }; class Dog : public Animal { public: void sound() override { std::cout &lt;&lt; &quot;Woof\n&quot;; } }; class Cat : public Animal { publ...
<python><c++><pybind11>
2023-05-26 08:06:59
1
2,057
Pibben
76,338,850
8,770,170
Python output highlighting in Quarto
<p>Continuing on <a href="https://stackoverflow.com/q/74981820/8770170">this question</a> about code output highlighting in Quarto: Is it also possible to make this work with Python output?</p> <p>A minimal working example:</p> <pre><code>--- title: &quot;Output line highlighting&quot; format: revealjs editor: visual f...
<python><r><lua><quarto><reveal.js>
2023-05-26 08:06:50
1
551
Frans Rodenburg
76,338,694
1,342,516
Split array into intervals with given limits
<p>From an array, how to take only the parts within given intervals? E.g. from</p> <pre><code>x = np.linspace(0,10,51) intervals = [[2, 2.5], [8.1, 9]] </code></pre> <p>get</p> <pre><code>[[2, 2.2, 2.4], [8.2, 8.4, 8.6, 8.8]] </code></pre>
<python><numpy>
2023-05-26 07:45:51
2
539
user1342516
76,338,652
2,828,006
jira python API get active Sprint
<p>I am using atlassian python API connector for writing script which can get the active sprint for the project.</p> <p>API doc : <a href="https://atlassian-python-api.readthedocs.io/" rel="nofollow noreferrer">https://atlassian-python-api.readthedocs.io/</a></p> <p>In this API doc i am not able to find any method whic...
<python><jira>
2023-05-26 07:41:09
0
1,474
Scientist
76,338,557
1,145,666
How can I set the character set encoding for serving static files?
<p>I am using a simple setup for serving static files in CherryPy:</p> <pre><code>class StaticServer(object): pass config = { '/': { 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.staticdir.on': True, 'tools.staticdir.dir': fullpath, 'tools.staticdir.i...
<python><encoding><cherrypy>
2023-05-26 07:29:04
0
33,757
Bart Friederichs
76,338,475
17,973,259
Argument of type "str" cannot be assigned to parameter "__key" of type "slice" in function "__setitem__" "str" is incompatible with "slice"
<p>My code is running with no errors but VS Code warns me with a warning message after I added the <code>_update_scale</code> method in this class:</p> <pre><code>class AlienAnimation: &quot;&quot;&quot;This class manages the animation of an alien, based on its level prefix. The alien frames are chosen base...
<python><python-3.x>
2023-05-26 07:17:13
1
878
Alex
76,338,218
17,530,552
How to skip a row of zeros with np.loadtxt?
<p>I have a .txt file that contains many rows of numeric values. Each row looks as follows <code>3.896784 0.465921 1.183185 5.468042 ...</code>, where the values differ depending on the row.</p> <p>Furthermore, every row contains 900 values. Some rows do not contain real data, but only 900 zeros as follows <code>0 0 0 ...
<python><numpy><txt>
2023-05-26 06:38:56
2
415
Philipp
76,338,089
11,357,695
Failed building wheel for backports-zoneinfo
<p><em><strong>EDIT</strong></em></p> <p>I tried <a href="https://stackoverflow.com/a/61762308/11357695">clearing my pip cache</a> due to the error line <code>Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB)</code> (maybe the cached version is broken/old and incompatible with other packages) - but this made no diff...
<python><visual-c++><pip><conda><python-wheel>
2023-05-26 06:17:34
1
756
Tim Kirkwood
76,337,429
10,984,994
No attribute "append" error while writing data using pandas DataFrame
<p>I am getting below error, <code>AttributeError: 'DataFrame' object has no attribute 'append'. Did you mean: '_append'?</code></p> <p>I am trying to write in <code>result_df</code> variable with all the device name corresponding values on each rows using for loop. But I am getting no attribute error.</p> <p>what cou...
<python><python-3.x><pandas><dataframe>
2023-05-26 03:14:51
2
1,009
ilexcel
76,337,361
3,247,006
Is there the parameter to pass a billing address to "Payments" on Stripe Dashboard after a payment on Stripe Checkout?
<p>I'm trying to pass a billing address to <strong>Payments</strong> on <strong>Stripe Dashboard</strong> but I couldn't find the parameter to do it in <a href="https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_intent_data" rel="nofollow noreferrer">payment_intent_data</a>.</p> <p>So ...
<python><django><stripe-payments><checkout>
2023-05-26 02:49:23
1
42,516
Super Kai - Kazuya Ito
76,337,141
13,444,774
How to forecast with new dataset by "MarkovAutoregression" model in Statsmodels?
<p>I'd like to fit a MarkovAutoregression model with training time-seriese dataset(train_data) and make it forecast with validation time-seriese dataset(val_data). Training part is like below and I don't find any errors.</p> <pre><code>import numpy as np from statsmodels.tsa.regime_switching.markov_autoregression impor...
<python><machine-learning><statsmodels><forecasting><markov>
2023-05-26 01:34:53
1
353
Ihmon
76,337,133
10,284,437
How to enhance speed to compare a list of ID to a known list of ID from MongoDB?
<p>In my code, I use a process that takes a lot of time, this is web-scraping, I need to know which ID is already known:</p> <pre><code>from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') mydb = client['db'] mycol = mydb['collection'] if __name__ == '__main__': [...] for item in ...
<python><mongodb><selenium-webdriver><web-scraping>
2023-05-26 01:32:23
1
731
Mévatlavé Kraspek
76,337,109
4,390,160
Unexpected type warning in `__new__` method for `int` subclass
<p>The following code:</p> <pre><code>class Foo(int): def __new__(cls, x, *args, **kwargs): x = x if isinstance(x, int) else 42 return super(Foo, cls).__new__(cls, x, *args, **kwargs) </code></pre> <p>Results in a warning (in PyCharm): &quot;<code>Expected type 'str | bytes | bytearray', go...
<python><subclassing>
2023-05-26 01:22:38
1
32,399
Grismar
76,337,096
825,227
Calculate a trailing average using day of year closest to anchor date in Python
<p>I have a dataframe of weekly values for different series identifiers as follows. The week entries are made for each series every week but don't coincide year after year (eg, 1/1 one year, 1/3 the next, 1/2, etc.):</p> <pre><code>period series value 2017-05-12 R33 720 2017-05-12 R33 1057 2017-05-12 ...
<python><python-3.x><pandas><algorithm>
2023-05-26 01:19:50
1
1,702
Chris
76,337,068
9,186,481
URLError: <urlopen error [Errno 97] Address family not supported by protocol>
<p>I am trying to get <code>secure string</code> variable stored AWS <code>parameter store</code>, from AWS <code>lambda</code>. I follow this <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html" rel="nofollow noreferrer">document</a>, and have already deploy this...
<python><amazon-web-services><aws-lambda><aws-parameter-store>
2023-05-26 01:09:49
0
361
UMR
76,337,058
9,218,849
How to generate sentiment scores using predefined aspects with deberta-v3-base-absa-v1.1 Huggingface model?
<p>I have a dataframe , where there is text in 1st column and predefine aspect in another column however there is no aspects defined for few text ,for example row 2.</p> <pre><code>data = { 'text': [ &quot;The camera quality of this phone is amazing.&quot;, &quot;The belt is poor quality&quot;, ...
<python><nlp><huggingface-transformers><sentiment-analysis><large-language-model>
2023-05-26 01:06:19
1
572
Dexter1611
76,337,052
14,459,861
How to get specific phrases from data frame in python?
<p>I filtered a column in my data frame that contains the word &quot;no&quot;. I want to print the phrases that have &quot;no&quot; in them.</p> <p>For instance, if this is my dataset:</p> <pre><code>index | Column 1 ------------------------------------------------------------------------ 0 | no school for the res...
<python><pandas><string><dataframe>
2023-05-26 01:04:39
2
325
shorttriptomars
76,337,049
1,631,414
How to pass keyword arguments to another method or class in python?
<p>I'm running into something strange as I'm reading someone's code and trying to make use of it.</p> <p>I need to instantiate a class they wrote. I was looking at their example which is currently being run in production so me mimicking it should be working correctly. Anyway, in their code, I see them passing a kwarg...
<python><arguments><keyword-argument>
2023-05-26 01:04:05
1
6,100
Classified
76,337,035
1,946,418
python - get classname and assign to class variable
<p>Can use <code>self.__class__.__name__</code> inside an instance method, but I need to do something like this</p> <pre class="lang-py prettyprint-override"><code>class Utilities: className = Utilities.__name__ </code></pre> <p>I am hoping to assign the class name to <code>className</code> (and do something with i...
<python>
2023-05-26 00:54:23
0
1,120
scorpion35
76,336,780
7,846,884
Unexpected keyword filePath in rule definition
<p>my snakemake fails to lunch with error</p> <pre><code>$snakemake -s bsmooth_Snakefile.smk -np --forcerun SyntaxError in file /scripts/bsmooth_snakemake/bsmooth_Snakefile.smk, line 9: Unexpected keyword filePath in rule definition (bsmooth_Snakefile.smk, line 9) </code></pre> <p>here's how actual snakefile looks like...
<python><snakemake>
2023-05-25 23:21:21
1
473
sahuno
76,336,655
2,988,730
Operate on columns with the same name in the second level in a dataframe
<p>I have a dataframe with a multi-index on the columns:</p> <pre><code>df = pd.DataFrame({('a', 'status'): [0.1, 0.2, 0.3], ('a', 'value'): [1.1, 1.2, 1.3], ('b', 'status'): [0.1, 0.2, 0.3], ('b', 'value'): [2.1, 2.2, 2.3], ('c', 'status'): [0...
<python><pandas><multi-index>
2023-05-25 22:43:10
2
115,659
Mad Physicist
76,336,566
3,380,902
Mosaic `st_buffer` doesn't return geometry of type Point or Polygon
<p>I am expecting to create a buffer around <code>point</code> geometry that would be of <code>Polygon</code> type. For example, I run the following code to obtain the geometries.</p> <pre><code>import pyspark.sql.functions as F df = spark.createDataFrame([ (37.775, -122.418), (40.714, -74.006), (41.007, ...
<python><apache-spark><pyspark><databricks><geospatial>
2023-05-25 22:17:28
1
2,022
kms
76,336,539
504,717
How To Fix: TypeError: No positional arguments allowed' in python List object with gRPC
<p>I have already looked at this <a href="https://stackoverflow.com/questions/58752816/how-to-fix-typeerror-no-positional-arguments-allowed-in-python-with-grpc">post</a>, which doesn't answer my problem</p> <p>Here is how my proto file looks like</p> <pre><code>message GetWarehousesRequest { CreateAttributes base_wh ...
<python><arrays><protocol-buffers><grpc><python-3.7>
2023-05-25 22:10:21
1
8,834
Em Ae
76,336,493
926,918
Dask DataFrame of strings works too slow on row-wise apply
<p>I have a Dask dataframe with no missing values. I am trying to apply a function to all but first two columns to do the following:</p> <ul> <li>col_1 is called R</li> <li>col_2 is called A</li> <li>col_i (i&gt;2) contains binary strings</li> <li>All col_i (i&gt;2) should be translated such that '0' and '1' are replac...
<python><parallel-processing><dask><dask-distributed><dask-dataframe>
2023-05-25 21:57:07
1
1,196
Quiescent
76,336,434
1,812,732
How to change TabNine to use single quotes in the Python suggested code
<p>I just started using TabNine for python in VS Code. It makes some great suggestions. However, it always uses <strong>double quotes</strong> for the string constants. For me this is irksome. All the other code in my project is using single quotes. Is there a way to tell the AI to please use single quotes for stri...
<python><visual-studio-code><tabnine>
2023-05-25 21:45:01
0
11,643
John Henckel
76,336,153
1,952,857
External merge-sort, but for dictionaries
<p>I have the following case:</p> <p>Very large file of lines of of integers of random length each, i.e.,</p> <p><strong>input.dat</strong></p> <pre><code>1 3 5 6 3 5 7 2 3 7 8 </code></pre> <p>I need to bring this file to the following form represented by a dictionary:</p> <p><strong>final dict</strong></p> <pre><code...
<python>
2023-05-25 20:44:40
0
1,636
ealione
76,336,133
12,096,670
Multivariate linear hypothesis testing using statsmodels in Python
<p>I am trying to run a multivariate regression model using statsmodels, but there appears to be no implementation of that yet, so in the meantime, what I did was to run a manova model on the data like below:</p> <pre><code># the modules import pandas as pd from statsmodels.multivariate.manova import MANOVA from statsm...
<python><linear-regression><statsmodels><multivariate-testing>
2023-05-25 20:42:14
0
845
GSA
76,335,993
20,999,526
pytube takes too long to stream a video in Android
<p>I am using <em>pytube</em> to stream a video in Android, with the help of <strong>chaquopy</strong>.</p> <p><em><strong>videofile.py</strong></em></p> <pre><code>from pytube import YouTube def video(link): yt = YouTube(f'https://www.youtube.com/watch?v=' + link) stream_url = yt.streams.get_highest_resolution...
<python><android><pytube><chaquopy><android-thread>
2023-05-25 20:18:16
1
337
George
76,335,866
9,218,849
Extract key as string from list of dictionary
<p>This is for example , I have below list of dictionary which has 1000's of dictionary and need key string for each dictionary as row</p> <p>The example is just for understanding purpose</p> <pre><code>Corp =[{'boy':1}, {}, {'kids': 3, 'parents' :4}] </code></pre> <p>I need below output in pandas with on...
<python><string><list><dictionary>
2023-05-25 19:57:14
1
572
Dexter1611
76,335,727
9,138,148
Botocore Not Recognising Region in Docker Container when AWS credentials are mapped
<p>Not sure if more details are required, but I'm running a docker container to execute boto3 commands and I have already been using them outside of the container. So upon mapping them to the container as such:</p> <pre><code>docker run --name store -v $HOME/.aws:/root/.aws my-store python ./mystore/manage.py test stor...
<python><docker><boto3>
2023-05-25 19:39:32
1
463
momo668
76,335,403
4,866,010
Solve inequality in Sympy
<p>I'm trying to solve a simple linear inequality in Sympy but can't seem to get it to work. Basically, I want to be able to calculate the optimal values of <code>a</code> when the inequality happens to be false.</p> <pre><code>import sympy num_attractors = 4 attractor_size = 64 network_size = 256 a, s, n = sympy.symb...
<python><sympy><inequality>
2023-05-25 18:49:32
1
449
Thomas Tiotto
76,335,314
1,918,965
Why global variable is empty in AppFilter (logging.basicConfig)?
<p>I use Python and Logging facility for Python.</p> <p>I have config.py:</p> <pre><code>MY_VARIABLE = '' </code></pre> <p>I have main.py:</p> <pre><code>from log import * from config import MY_VARIABLE for i in range(3): global MY_VARIABLE print(f&quot;main.py Old: '{MY_VARIABLE}'&quot;) MY_VARIABLE = i ...
<python><logging><global-variables>
2023-05-25 18:34:50
1
1,455
Olga
76,335,241
11,986,167
how to identify sequence order and cumsum the transactions?
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'id':[1,1,1,2,2,3,3,4,5,6,6,6,6,6,8,8,9,11,12,12],'letter':['A','A','Q','Q','Q','F','F','G','D','G','I','I','K','Q','E','S','S','I','I','F']}) </code></pre> <p>My objective is to add another column tx that shows the followings: if it finds Q and there...
<python><pandas><cumsum>
2023-05-25 18:24:24
3
741
ProcolHarum
76,335,157
7,648
Unexpected collapse of dimension when calling np.tile()
<p>I am creating a multi-dimension <em>numpy</em> matrix like this:</p> <pre><code>a = np.array([255, 0]) mins_and_maxes = np.tile(a, [9, 2, 43]) </code></pre> <p>I'm expecting <code>mins_and_maxes</code> to be a 4-D array with a shape of <em>(9, 2, 43, 2)</em>. However, <code>mins_and_max...
<python><python-3.x><numpy><matrix><tile>
2023-05-25 18:12:34
1
7,944
Paul Reiners
76,335,115
19,989,634
Stop paypal access token from refreshing so frequently
<p>Straight forward and simple question;</p> <p>What is the best way to stop PayPal access token from refreshing so frequently?</p> <p>I have tried to do curl command with extended 'expires_in': command. Doesn't work. Still refreshes after 24hr</p>
<python><django><paypal><paypal-rest-sdk>
2023-05-25 18:05:29
1
407
David Henson
76,335,101
10,553,098
Reinitialization of dataclass object does not reinitialize nested dataclass objects
<p>I'm having trouble reinitializing nested dataclass object.</p> <p>I have 2 nested dataclasses set up like so:</p> <pre><code>from dataclasses import dataclass, field from typing import Dict @dataclass class MyNestedClass(): field1: str = &quot;&quot; field2: int = 0 field3: Dict[str, float] = field(defa...
<python><nested><initialization><reinitialization>
2023-05-25 18:03:09
1
2,177
John
76,334,937
2,398,040
How do I fill in missing factors in a polars dataframe?
<p>I have this dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({ 'date':['date1','date1','date1','date2','date3','date3'], 'factor':['A','B','C','B','B','C'], 'val':[1,2,3,3,1,5] }) </code></pre> <pre><code>shape: (6, 3) ┌───────┬────────┬─────┐ │ date ┆ factor ┆ val │ │ --- ...
<python><dataframe><python-polars>
2023-05-25 17:35:03
2
1,057
ste_kwr
76,334,911
11,485,896
Formula and encoding issues when saving df to Excel
<p>I'm developing a script which gathers some YouTube data. The script of course creates a <code>pandas</code> dataframe which is later exported to Excel. I'm experiencing two major issues which somehow seem to be related to each other.</p> <p>So, Excel 365 allows users to insert an image to a cell using <code>IMAGE()<...
<python><pandas><excel><excel-formula><xlsxwriter>
2023-05-25 17:30:40
1
382
Soren V. Raben