QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,539,601
143,397
How to add command-line options to pytest with a custom plugin located in a subdirectory?
<p>Summary: my custom pytest plugin, located in a subdirectory, is imported but the implemented hook function <code>pytest_addoption()</code> is not called.</p> <hr /> <p>I have a custom pytest plugin that I want to store in its own directory, <code>bar/</code>, alongside but separate from my tests:</p> <pre><code>. ├─...
<python><unit-testing><plugins><pytest>
2023-02-23 00:49:44
0
13,932
davidA
75,539,437
15,569,921
non-symmetric square matrix with given eigenvalues
<p>Given an array of eigenvalues, how can I generate a <strong>non-symmetric</strong> square matrix which has those eigenvalues?</p> <p>I have tried the QR decomposition, but it returns a symmetric one. Here's what I have done so far.</p> <pre><code>from scipy.stats import ortho_group eigenvalues = [0.63, 0.2, 0.09, 0...
<python><matrix><random><scipy><eigenvalue>
2023-02-23 00:17:55
1
390
statwoman
75,539,347
7,766,024
Getting a ValueError: Not enough values to unpack for Python dictionary items unpacking
<p>I have a dictionary with a single key-value pair where the key is a string and the value is a set of integers (i.e., <code>dict[str, set[int]]</code>).</p> <p>I want to unpack the key and value by <code>key, value = some_dict.items()</code> but am getting a <code>ValueError: not enough values to unpack (expected 2, ...
<python>
2023-02-22 23:59:42
1
3,460
Sean
75,539,283
5,693,152
when is it "safe" to mix path separators in Python strings representing Windows paths?
<p>This minimal example: (Running in PyCharm debugger)</p> <pre><code>import os from os.path import join import subprocess src_path = r'C:/TEMP/source' dest_path = r'C:/TEMP/dest' if __name__ == &quot;__main__&quot;: for root, _, files in os.walk(src_path): for name in files: src_file_path = ...
<python><windows><shell><path-separator>
2023-02-22 23:47:10
1
925
geneSummons
75,539,146
2,458,922
How to Take Subset of a Tensor based on set of Index , in Tensorflow
<p>Given a: tensor([[3., 5.], [1., 2.],[5., 7.],[4., 6.],[3., 5.]]) index: tensor( [0,0],[3,1])</p> <p>Is there any Way to Get a[index] is [3,6]</p>
<python><tensorflow><tensor>
2023-02-22 23:24:56
0
1,731
user2458922
75,539,085
10,743,830
how to speed up following pandas dataframe iteration and loc indexing
<p>The following is just a part of the whole dataset. Whole dataset is milions of rows so the computation should be super fast. In any case data looks as follows:</p> <p>Link to the h5 file: <a href="https://drive.google.com/file/d/16aI3plRFa3M6nSIiT1XioUIgsPYl1Wg8/view?usp=sharing" rel="nofollow noreferrer">https://dr...
<python><pandas>
2023-02-22 23:12:17
2
352
Noah Weber
75,539,078
13,231,896
How to use static image as watermark for every page when printing pdf using django-wkhtmltopdf
<p>I need to be able to use a static image as watermark when printing a pdf from a django template using django-wkhtmltopdf. I was trying using the following code, but the document has several pages and the background does not apply to every page individually. Instead it tries to apply the background to the whole docum...
<python><django><wkhtmltopdf><django-wkhtmltopdf>
2023-02-22 23:11:35
2
830
Ernesto Ruiz
75,539,007
10,629,530
Custom validation for FastAPI's query parameter using pydatinc causes Internal Server Error
<p>My <code>GET</code> endpoint receives a query parameter that needs to meet the following criteria:</p> <ol> <li>be an <code>int</code> between 0 and 10</li> <li>be even number</li> </ol> <p><code>1.</code> is straight forward using <code>Query(gt=0, lt=10)</code>. However, it is not quiet clear to me how to extend <...
<python><exception><fastapi><valueerror><pydantic>
2023-02-22 23:00:58
1
743
ooo
75,538,966
10,737,147
numpy e^i(theta) and trigonometric cos(theta) + isin(theta) does not match
<p>I read,</p> <p><a href="https://i.sstatic.net/OwDrH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OwDrH.png" alt="enter image description here" /></a></p> <p>So I tried to do apply this to a list of points as shown below</p> <p><a href="https://i.sstatic.net/5ExHQ.png" rel="nofollow noreferrer"><img...
<python><numpy><math>
2023-02-22 22:55:19
2
437
XYZ
75,538,846
13,132,728
How to swap multiple values within a row based on a conditional in pandas
<h2>Description of my problem</h2> <p>I pulled some data from an api that is unfortunately formatted. In particular, there are four columns I need to utilize in some way to solve my issue. They are <code>label_1</code>, <code>odds_1</code>, <code>label_2</code>, and <code>line_2</code>. The <code>odds_</code> columns c...
<python><pandas><dataframe>
2023-02-22 22:37:42
2
1,645
bismo
75,538,781
3,832,467
Why IIS HTTPS Redirect doesn't work with API?
<p>I am using the following rule to redirect a HTTPS request to HTTP. It works fine when I access my application via the browser. But accessing it via the Python API leads to an error &quot;Your Api endpoint at xxx is not available or not responding.&quot;</p> <p>Any ideas why the API behavior might be different to the...
<python><iis>
2023-02-22 22:29:08
0
496
HansHupe
75,538,581
2,540,669
Does python's WSGI specification have anything to say about websockets?
<p>I know that there are options out there for WSGI servers that can handle websockets. Ex: <a href="https://flask-socketio.readthedocs.io/en/latest/deployment.html" rel="nofollow noreferrer">this</a> allows running flask + websockets in gunicorn, which is a WSGI server. But I thought the WSGI spec was only concerned w...
<python><websocket><wsgi><flask-socketio>
2023-02-22 22:01:33
1
3,181
augray
75,538,575
4,338,000
How do I create ordinal value from continuous value if they fall per 2?
<p>If I want to create ordinal value from continuous value, how can I split per 2? I can use cut function to create 2 bins or 50 bins if I had 100 data and are incremental. If I had random dataset, how can I create ordinal value per 2 for instance? For example if I have a columns with <code>[1,2,3,2,2,4,5,10,15,20]</co...
<python><pandas><dataframe>
2023-02-22 22:00:57
2
1,276
Sam
75,538,456
6,202,327
Why does scipy's quadrature function throw an error when using arrays?
<p>I have two versions of a snippet; one works and one doesn't.</p> <p>This works:</p> <pre><code>f = lambda x : x * 2.0 * pi print(scipy.integrate.quadrature(f, 0.0, 1.0)) </code></pre> <p>This fails:</p> <pre><code>f = lambda x : math.exp(x * 2.0 * pi)` print(scipy.integrate.quadrature(f, 0.0, 1.0)) </code></pre> <p>...
<python><math><scipy><integral>
2023-02-22 21:44:20
1
9,951
Makogan
75,538,416
588,804
Compare dataframe with database: insert new values, update changed values
<p>I've been looking into other solutions but haven't found anything that shows what I'm trying to do. This is the structures of my data:</p> <p>My database has these columns; id is the primary key, inserted_date is auto generated:</p> <pre><code>+----+------------+-------+---------------+ | id | fruit | price | i...
<python><pandas><dataframe>
2023-02-22 21:39:39
0
1,428
raygo
75,538,326
7,455,960
how to query latest row in relational table after joining needed data
<p>i've done some digging around the past couple days on this site and elsewhere and i can't seem to find an answer to a specific query i want to run</p> <p>i have 4 tables: Posts, PrivateMessagePosts, Users, and Offenses. Offenses are tied to either a <code>Post.id</code> or <code>PrivateMessagePost.id</code> but not ...
<python><mysql><sql><sqlalchemy>
2023-02-22 21:27:41
0
329
Marty
75,538,278
1,341,731
SQLAlchemy with server side cursors and need to close the result set early - but the program hangs till the resultset is exhausted?
<p>I'm trying to use the following coding style with SQLAlchemy to process millions of rows of data, and have a need to abort the result fetch part way through. How can I close a result set and force the underlying connection to stop sending unwanted data and halt the query?</p> <p>In other words when #close() is calle...
<python><sqlalchemy><mariadb>
2023-02-22 21:21:02
1
310
Michael Conrad
75,538,270
7,747,759
How to change rescale tick label for imshow in python?
<p>I am not able to change the tick labels. For example, I create a heatmap using imshow, and the indices for the heatmap don't correspond to the intensity values. Here is a snippet of code to demonstrate my question:</p> <pre><code>iters=100 A=np.arange(0,iters+1)/(iters) B=np.arange(0,iters+1)/(iters) C = np.zeros((l...
<python><matplotlib>
2023-02-22 21:19:47
1
511
Ralff
75,538,238
11,678,574
python subprocess.run("npx prettier --write test.ts", shell=True) does not work but running "npx prettier --write test.ts" in terminal does not
<p>My file structure:</p> <ul> <li>test.py</li> <li>test.ts</li> </ul> <p>and I am attempting to format the TypeScript file using a Python script. (Running this on Command prompt in Windows) However, when I run my python file with <code>subprocess.run(&quot;npx prettier --write test.ts&quot;, shell=True)</code> shows</...
<python><typescript><subprocess><prettier><npx>
2023-02-22 21:16:11
1
313
g999
75,538,210
13,919,791
How do I use Scalene to profile my Pytest test suit?
<p>I want to use Scalene to profile my Pytest test suit</p> <p>Typically I run the test suit by running</p> <pre><code>pytest </code></pre> <p>So I tried</p> <pre><code>scalene pytest </code></pre> <p>which doesn't work as I expect.</p> <p>What is the correct way to run my test suit through scalene?</p>
<python><pytest><profiler><scalene>
2023-02-22 21:12:19
1
845
snowskeleton
75,538,202
10,963,057
How can I change the distance between the axis title and the axis values in a 3D scatterplot in Plotly (Python)?
<p>i have the following example code of a 3d Scatterplot in plotly and i want to place the x,y and z title with more distance to the axis.</p> <pre><code>import plotly.graph_objects as go # set up data x = [1,2,3,4,5] y = [2,4,6,8,10] z = [2,4,6,8,10] # create the figure fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z...
<python><3d><plotly><scatter-plot><axis>
2023-02-22 21:11:22
1
1,151
Alex
75,538,119
7,687,256
Python-telegram-bot not returning expected values
<p>I've written a Python code to get a set of NFT prices from opensea's API and return it's total USD value below:</p> <pre><code># Downgraded to python-telegram-bot 13.7 : pip install python-telegram-bot==13.7 # Set your bot token here. bot_token = '' # Import necessary libs import os import requests from telegram.e...
<python><telegram-bot><python-telegram-bot>
2023-02-22 21:01:19
1
939
spidermarn
75,537,788
5,235,665
Pandas groupby is removing columns unexpectedly
<p>New to Pandas and I'm trying to figure something out here. I have the following code:</p> <pre><code>logger.info(f&quot;There are {mydf.shape[0]} rows in the subset dataframe&quot;) logger.info(f&quot;before groupby mydf is: {mydf.head(25)}&quot;) mydf = mydf.groupby([Customer_ID, Customer_Name]).agg(&quot;sum&quot;...
<python><pandas><dataframe>
2023-02-22 20:22:20
1
845
hotmeatballsoup
75,537,775
1,511,294
Unable to create GridSpace Object in SynapseML
<p>I am trying to create a GridSpace object in SynapseML , like this</p> <pre><code>paramGrid = HyperparamBuilder().addHyperparam(gbt,gbt.maxBin, DiscreteHyperParam([200, 255,300])) searchSpace= paramGrid.build() print(searchSpace) type(searchSpace) GridSpace(searchSpace) </code></pre> <p>This gives me the following er...
<python><azure><machine-learning><azure-synapse>
2023-02-22 20:20:54
1
1,665
Ayan Biswas
75,537,615
15,215,859
GCP composer read MySql table and push into GCS and then into BigQuery
<p>We are using GCP Cloud composer 2 (Airflow managed) as orchestral tools and BigQuery as DB. I need to push all the records from MySQL table into GCS cloud bucket and BigQuery table but the method should be upsert. So I wrote below DAG but it fails saying &quot;airflow.exceptions.AirflowException: Invalid arguments w...
<python><python-3.x><google-bigquery><airflow>
2023-02-22 20:00:10
1
317
Tushaar
75,537,296
1,344,369
Enumerating list of simple observables subscribing to wrong object in Python
<p>I am experiencing some weird bug in a code using observables in list comprehensions. I built here the simplest <a href="https://colab.research.google.com/drive/1lRkhaAnlwj3zYXXx7DTPRWc4rsrKuAts?usp=sharing" rel="nofollow noreferrer">MWE</a> I could think of:</p> <pre class="lang-py prettyprint-override"><code>class...
<python><observable><list-comprehension>
2023-02-22 19:22:51
0
1,667
Fred Guth
75,537,277
2,540,669
How many websocket clients can flask-socketio handle when in Gunicorn with gevent?
<p>I am considering the following setup:</p> <ul> <li>A &quot;normal&quot; flask app</li> <li>A <a href="https://python-socketio.readthedocs.io/en/latest/" rel="nofollow noreferrer">socketio</a> app</li> <li><a href="https://flask-socketio.readthedocs.io/en/latest/" rel="nofollow noreferrer">Flask SocketIO</a></li> <li...
<python><gunicorn><gevent><flask-socketio><gevent-socketio>
2023-02-22 19:21:27
1
3,181
augray
75,537,234
20,898,396
Why is accessing elements of an array slower in the GPU than the CPU with Numba?
<p>Since we can't call print inside <code>@cuda.jit</code> and trying to print <code>cuda.to_device(A)</code> results in <code>&lt;numba.cuda.cudadrv.devicearray.DeviceNDArray at 0x7f2c5c0605e0&gt;</code>, I didn't think we could print anything from the GPU. However, we can print a single element.</p> <pre><code>import...
<python><cuda><numba>
2023-02-22 19:17:05
1
927
BPDev
75,537,204
4,764,604
How are df2 values placed to the right of df1 columns when there is a match in a common column?
<p>I want that for each row of <code>df_transformed</code> where there is a match with a row of the <code>Name</code> column with <code>df</code> we add the values of the <code>df_transformed</code> row to <code>df</code>.</p> <p>I have an example dataframe <code>df</code> (actually there are other columns):</p> <pre><...
<python><python-3.x><pandas><merge>
2023-02-22 19:14:04
0
3,396
Revolucion for Monica
75,537,113
3,045,351
How to zip keys within a list of dicts
<p>I have this object:</p> <pre><code>dvalues = [{'column': 'Environment', 'parse_type': 'iter', 'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']}, {'column': 'Frame Type', 'parse_type': 'list', 'values': ['All']}] </code></pre> <p>I want a zipped output like this:</p> <pre><code>('AirportEnclosed', 'All'...
<python><python-3.x><python-zip>
2023-02-22 19:03:16
1
4,190
gdogg371
75,536,995
1,806,392
Apply function accross multiple columns within group_by in Polars
<p>Given this dataframe:</p> <pre><code>import polars as pl polars_df = pl.DataFrame({ &quot;name&quot;: [&quot;A&quot;,&quot;B&quot;,&quot;C&quot;], &quot;group&quot;: [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;], &quot;val1&quot;: [1, None, 3], &quot;val2&quot;: [1, 5, None], &quot;val3&quot;: [No...
<python><dataframe><python-polars>
2023-02-22 18:50:48
5
2,314
nik
75,536,896
12,470,058
How to fix the syntax of a function which is in string format?
<p>I have a text file containing python functions in string format. My code reads each function from the text file, feeds it with the appropriate inputs and then runs it. To run a function string (for example <code>fun_str</code>) from the text file, I use the following snippet in my code:</p> <pre><code>dict = {} exec...
<python><python-3.x>
2023-02-22 18:41:00
1
368
Bsh
75,536,670
14,900,600
Python percentage calculator does not call exit()
<p>I am trying to write a percentage calculator that asks for the number of subjects, marks in the specified number of subjects and computes the percentage. It works well, but does not exit on calling exit() after the user presses &quot;n&quot;:</p> <pre class="lang-py prettyprint-override"><code>value = input(&quot;Do...
<python>
2023-02-22 18:17:19
4
541
SK-the-Learner
75,536,658
3,056,036
Merge Select Columns Dataframe Columns Into a Multi-Index
<p>I have N dataframes, in this case lets use 2 dfs as an example:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame([['a', 2], ['b', 4]], columns=['foo', 'bar']) df2 = pd.DataFrame([['a', 3], ['b', 5]], columns=['foo', 'bar']) </code></pre> <p>Which produce:</p> <pre><code> foo bar 0 a 2 1 ...
<python><pandas><multi-index>
2023-02-22 18:16:43
1
309
ateymour
75,536,405
3,399,638
Pythonic way of taking mean of values from Dictionary with Keys
<p>Given a Python Dictionary, I'm attempting to take the mean over a series where the key values don't match. The following is an example of the dictionary, where there are N numbers of winner_num keys and the mean is taken from each index of 'value_held_graph.'</p> <pre><code>nested_dict = {'winner_num_0': {'cash_held...
<python><dictionary><mean>
2023-02-22 17:49:21
3
323
billv1179
75,536,380
7,788,098
How to return outer function if any of the inner functions returns
<p>See the following example:</p> <pre><code>def a(test): if test &gt; 1: raise Exception(&quot;error in 'a'&quot;) print(&quot;nothing happened&quot;) def b(test): if test &gt; 1: raise Exception(&quot;error in 'b'&quot;) print(&quot;nothing happened&quot;) def c(test): if test &g...
<python><python-3.x>
2023-02-22 17:46:36
2
439
Matias Eiletz
75,536,284
1,497,139
How do i fix "default prefix is not defined" errors in LinkML?
<p>As contributor to <a href="https://github.com/WolfgangFahl/pyMetaModel" rel="nofollow noreferrer">https://github.com/WolfgangFahl/pyMetaModel</a> i am running into a problem when trying out the generated linkML yaml files with different LinkML generators</p> <p>While the linkML and mermaid generators seem to run fin...
<python><linkml>
2023-02-22 17:35:14
2
15,707
Wolfgang Fahl
75,536,279
7,984,318
Where to find all the third party packages or modules installed in a Flask project
<p>I'm new to flask ,but in Django I can find all the installed third party packages in settings.py:</p> <pre><code>INSTALLED_APPS=[ 'third_party_app,' ] </code></pre> <p>Is there any module or any way in flask ,I can easily find all the installed third party packages ?</p>
<python><flask>
2023-02-22 17:34:52
1
4,094
William
75,535,994
10,682,289
How to import function from module that uses ArgParser without passing args
<p>Let's say I have two modules:</p> <ul> <li><p>a.py:</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument(&quot;arg&quot;, help=&quot;Some argument&quot;) args = parser.parse_args() def func(): print('Hello world!') </code></pre> </li> <li><p>b.py:</p> <pre><code>from a import...
<python><argparse>
2023-02-22 17:06:23
1
4,891
JaSON
75,535,965
13,142,245
Optimal shape for Multiprocessing Pool.map in Python
<p>Say you have a matrix of MxN elems (nested list.) And you want to parallelize operations; so your choices are parallelize by row or parallelize by column. Suppose that data/operations are independent and require only the value of matrix[i][j].</p> <p>Depending on size of M &amp; N, what is the best way to distribute...
<python><multiprocessing>
2023-02-22 17:04:26
1
1,238
jbuddy_13
75,535,917
1,084,684
How to add a table to my SQLAlchemy query's FROM's?
<p>I'm attempting to convert a working, large, complex SQL query to SQLAlchemy's ORM.</p> <p>Here's a small example program that demonstrates the problem I'm seeing:</p> <pre><code>#!/usr/bin/env python3 &quot;&quot;&quot; An SSCCE. Environment variables: DBU Your database user DBP Your database password ...
<python><mysql><sqlalchemy>
2023-02-22 17:00:54
1
7,243
dstromberg
75,535,868
5,574,107
Title on graphs
<p>I am making plots in a loop:</p> <pre><code>plotData.sort_values(by=['segment']) for date in plotData.month_of_default.unique(): plt.figure() temp =plotData[plotData.month_of_default==date][['New_Amount_2','ID','segment','total','payment','month']] denom = temp.drop_duplicates(subset=['ID']).groupby('seg...
<python><pandas><matplotlib>
2023-02-22 16:57:11
1
453
user13948
75,535,764
10,094,736
How do I transform my dataframe in python so that it's a different shape?
<p><strong>I have a dataframe in python which is of the format:</strong></p> <p><a href="https://i.sstatic.net/7Kpmk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7Kpmk.png" alt="enter image description here" /></a></p> <p><strong>I would like to transform my dataframe so that it looks like the image b...
<python><dataframe><transform><transformation>
2023-02-22 16:45:41
1
405
Jed
75,535,679
1,503,669
Implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW
<p>How to fix this deprecated AdamW model?</p> <p>I tried to use the BERT model to perform a sentiment analysis on the hotel reviews, when I run this piece of code, it prompts the following warning. I am still studying the transformers and I don't want the code to be deprecated very soon. I searched on the web and I ca...
<python><pytorch><huggingface-transformers><sentiment-analysis>
2023-02-22 16:37:58
1
513
Panco
75,535,529
12,981,397
How to split a column with json string into their own columns
<p>I have a dataframe like (with one example row):</p> <pre><code>raw_data = [{'id': 1, 'name': 'FRANK', 'attributes': '{&quot;deleted&quot;: false, &quot;rejected&quot;: true, &quot;handled&quot;: true, &quot;order&quot;: &quot;37&quot;}'}] raw_df = pd.DataFrame(raw_data) </code></pre> <p>I would like to break the jso...
<python><json><pandas><json-normalize>
2023-02-22 16:24:30
1
333
Angie
75,535,513
10,739,252
Multiprocessing.Queue hangs process when it is large enough
<p>Today, I've stumbled on some frustrating behavior of <code>multiprocessing.Queue</code>s.</p> <p>This is my code:</p> <pre><code>import multiprocessing def make_queue(size): ret = multiprocessing.Queue() for i in range(size): ret.put(i) return ret test_queue = make_queue(3575) print(test_queu...
<python><multiprocessing><queue>
2023-02-22 16:23:22
1
2,942
Captain Trojan
75,535,305
1,216,584
How do I connect to a minio pod using the python API?
<p>I set up a microk8s deployment with the Minio service activated. I can connect to the Minio dashboard with a browser but cannot find a way to connect to the service via the API.</p> <p>Here is the output to the <code>microk8s kubectl get all --all-namespaces</code> command</p> <pre><code>NAMESPACE NAME ...
<python><kubernetes><minio>
2023-02-22 16:05:34
1
401
Mark C
75,535,291
6,223,328
pandas interpolate on new time base
<p>I'm looking for an easy way to put two dataframe with a physical seconds index on a new timebase using interpolation, e.g. with the example data</p> <pre class="lang-py prettyprint-override"><code>data1 = pd.DataFrame({'time': np.arange(2, 300, 0.2), 'data': np.random.randint(0, 2, len(np.arang...
<python><pandas><interpolation>
2023-02-22 16:04:24
0
357
Max
75,535,092
1,187,968
Python patch/mock under __name__ == "__main___"
<p>I have the following file named <code>w.py</code>, and under <code>__name__ == &quot;__main__&quot;</code>, I want to patch <code>MyAPI</code>, running <code>python w.py</code> shows the patching is not working at all. Is <code>patch('common.apis.MyAPI', mock_api)</code> being used correctly?</p> <pre><code>from com...
<python><mocking><patch>
2023-02-22 15:47:05
1
8,146
user1187968
75,535,023
395,258
Load Pillow image as texture in pyglet
<h1>Problem</h1> <p>I am trying to load a Pillow image as a Pyglet texture using the following code:</p> <pre><code>pixels = pillow_image.convert(&quot;L&quot;).tobytes() width, height = pillow_image.size image = pyglet.image.ImageData(width, height, &quot;L&quot;, pixels, pitch=width) image = image.get_texture().get_...
<python><python-imaging-library><pyglet>
2023-02-22 15:41:02
1
10,673
C. E.
75,535,002
11,462,274
Keep original page opening without upgrading to local version
<p>Every morning I open this site to see the games of the day, but I like to see it in the international version (<code>https://int.</code>) because I don't like the brazilian version (<code>https://br.</code>).</p> <p>But whenever I open it through <code>WebDriver</code> as it doesn't know that I prefer it that way (i...
<python><selenium-webdriver>
2023-02-22 15:39:55
1
2,222
Digital Farmer
75,534,779
4,379,365
Pandas, how to compute the mean of a third column grouped by two columns and set result to a fourth new column?
<p>In a dataframe, how to create a new column called z_mean, which is the mean of column z when grouping x and y?</p> <pre><code>data = [ {'x':0.0, 'y':0.0, 'z':0.8}, {'x':0.0, 'y':0.0, 'z':1.0}, {'x':0.0, 'y':0.0, 'z':1.2}, {'x':1.0, 'y':1.0, 'z':1.6}, {'x':1.0, 'y':1.0, 'z':2.0}, {'x':1.0, 'y'...
<python><pandas><group-by>
2023-02-22 15:20:13
1
559
Xavier M
75,534,750
10,545,426
Split string value in a MultIndex level to create a new level
<p>I want to split a level (of str values) in a MultiIndex using a delim to create a new level in the MultiIndex.</p> <p>My original DataFrame</p> <pre class="lang-py prettyprint-override"><code>pd.DataFrame( np.ones((5, 4)), columns=pd.MultiIndex.from_tuples( zip( list(reduce(lambda x, y: f...
<python><pandas>
2023-02-22 15:17:36
1
399
Stalin Thomas
75,534,737
690,255
Jupyter Notebook - underscore.js doesn't seem to be accessible anymore
<p>I'm using a custom widget in Jupyter. After upgrading to a new machine it stopped functioning. Checking the javascript console in the browser window running the notebook I see the error <code>ReferenceError: _ is not defined</code>. Indeed, running the following in a Jupyter cell:</p> <pre><code>%%js alert(_) </code...
<javascript><python><jupyter-notebook><underscore.js><jupyter-widget>
2023-02-22 15:16:30
1
883
John
75,534,617
5,684,405
Poetry unable to install hydra
<p>Poetry can not install hydra with the below error. How to install Hydra with poetry:</p> <pre><code>$ poetry add hydra Using version ^2.5 for hydra Updating dependencies Resolving dependencies... (6.3s) Writi...
<python><python-poetry><hydra>
2023-02-22 15:07:14
1
2,969
mCs
75,534,590
21,221,244
How to smooth adjacent polygons in Python?
<p>I'm looking for a way to smooth polygons such that adjacent/touching polygons remain touching. Individual polygons can be smoothed easily, e.g., with PAEK or Bezier interpolation (<a href="https://pro.arcgis.com/en/pro-app/latest/tool-reference/cartography/smooth-polygon.htm" rel="nofollow noreferrer">https://pro.ar...
<python><gis><polygon><geopandas><shapely>
2023-02-22 15:04:48
3
495
Thijs
75,534,549
5,240,684
mock_open with variable read_data
<p>I tried looking through the similar questions, but couldn't find an answer that answers my question.</p> <p>I have a function like so:</p> <pre><code>from smart_open import open import pandas as pd def foo(): with open('file1.txt', 'r') as f: df1 = pd.read_csv(f) value1 = do_something(df1) with open('file...
<python><python-3.x><pandas><unit-testing><smart-open>
2023-02-22 15:01:35
1
1,057
Lukas Hestermeyer
75,534,410
2,300,049
Force a python package that uses requests to go through a proxy
<p>I am currently using the python package <a href="https://dev.meteostat.net/" rel="nofollow noreferrer">meteostat</a>. It makes use of the requests package to download data off the meteostat servers. I am running this package through work a machine that needs to use an http proxy.</p> <p>When running their example co...
<python><python-requests><proxy><meteostat>
2023-02-22 14:50:39
0
321
entropy
75,534,368
1,889,750
Grouping and Reordering data in pandas dataframe
<p>I have some dataframe with a structure</p> <pre><code>Candidate z0, 0deg z0, 30deg z0, 60deg z0, 90deg z0, 120deg z0, 150deg z0, 180deg z0, 210deg z0, 240deg 10006A 0.30 0.05 0.05 0.05 0.05 0.30 0.05 0.05 0.05 10008A 0.30 0.30 0.30 0.30 0.30 0.30 0.30 0...
<python><pandas><dataframe>
2023-02-22 14:47:15
1
1,355
TomGeo
75,534,277
3,866,549
FastAPI grant_type refresh token
<p>I'm new to OAth2 and using FastApi, working great until now stumped on how to detect grant_type refresh. Here from the form, i'm getting grant_type as &quot;password&quot; or &quot;refresh_token&quot;. The problem is that when I pass grant_type &quot;refresh_token&quot; the code doesn't even get to the condidtiona...
<python><oauth-2.0><fastapi>
2023-02-22 14:40:31
1
2,507
jKraut
75,534,266
18,432,809
test an endpoint, where login is required with PYTEST
<p>I am trying to test my flask-api, but im not being able to do this, because the endpoints require login.</p> <p>I have a simple code:</p> <pre><code>import os import requests from dotenv import load_dotenv load_dotenv() ENDPOINT = os.getenv(&quot;ENDPOINT&quot;) ### - TESTING SALES ENDPOINT - ### def test_get_all...
<python><flask><pytest>
2023-02-22 14:38:52
1
389
vitxr
75,534,231
8,622,976
How can I connect to remote database using psycopg3
<p>I'm using Psycopg3 (not 2!) and I can't figure out how can I connect to a remote Postgres server</p> <pre class="lang-py prettyprint-override"><code>psycopg.connect(connection_string) </code></pre> <p><a href="https://www.psycopg.org/psycopg3/docs/" rel="nofollow noreferrer">https://www.psycopg.org/psycopg3/docs/</a...
<python><postgresql><psycopg2><psycopg3>
2023-02-22 14:36:16
2
2,103
Alon Barad
75,534,150
4,016,385
Is there a way to calculate average buy/sell price for stock share without cycles?
<p><a href="https://i.sstatic.net/O6nLYm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/O6nLYm.png" alt="orderbook" /></a></p> <p>I'm looking a way to calculate average sell\buy price of stock share without cycling through each element (using pandas\numpy functions).</p> <p>Let's assume I want to sell 1...
<python><pandas><dataframe><numpy>
2023-02-22 14:29:57
1
397
Alexander Zar
75,534,125
5,036,928
Numpy Value Error: Elementwise Operations on Meshgrid
<p>Given my code below:</p> <pre><code>import numpy as np nx, ny, nz = (50, 50, 50) x = np.linspace(1, 2, nx) y = np.linspace(2, 3, ny) z = np.linspace(0, 1, nz) xg, yg, zg = np.meshgrid(x, y, z) def fun(x, y, z, a, b, c): r = np.array([x, y, z]) r0 = np.array([a, b, c]) R = ((x-a)**2 + (y-b)**2 + ...
<python><numpy><mesh><elementwise-operations>
2023-02-22 14:28:00
1
1,195
Sterling Butters
75,533,936
6,529,926
Most efficient way of performing creation of new rows in a DataFrame
<p>I'm implementing a data augmentation script that takes as input a pandas DataFrame and a list of strings (e.g. <code>variations</code>). The script should generate new rows for the DataFrame, where each row concatenates an element of <code>variations</code>.</p> <p>For instance, having a DataFrame:</p> <pre><code>Co...
<python><pandas><numpy><performance>
2023-02-22 14:13:49
4
729
heresthebuzz
75,533,901
8,165,879
How to use sagemaker pipeline parameters in a processing step?
<p>I would like to pass a parameter to my sagemaker pipeline and use it in my processing step. I am defining my step as follows:</p> <pre><code>from sagemaker.processing import Processor my_processor = Processor(role=role, image_uri='xxxx', instance_type=&quot;ml.m...
<python><amazon-web-services><pipeline><amazon-sagemaker>
2023-02-22 14:10:55
1
530
Yash
75,533,892
962,891
How to plot multiple markers in mplfinance scatter plot
<p>I am using pandas v 1.5.3 and Python 3.10.</p> <p>I have timeseries data along with flag columns like this:</p> <pre><code> Open High Low Close Adj Close Volume Flag Date ...
<python><pandas><matplotlib><mplfinance>
2023-02-22 14:10:00
2
68,926
Homunculus Reticulli
75,533,830
11,391,711
Applying multiple filters on files names using glob in Python
<p>I would like to apply multiple filters on files names using <code>glob</code> library in <code>python</code>. I went trough some online sources and can see that using <code>*</code> opearation, it's possible to do so. However, my filters are not properly working since I'm trying to apply multiple them together. It i...
<python><regex><file><directory><glob>
2023-02-22 14:03:52
1
488
whitepanda
75,533,822
5,868,293
How to add text at specific points at x-axis, at a cumulative histogram in plotly python
<p>I produce the following cumulative histogram using plotly-express:</p> <pre><code>import pandas as pd import plotly.express as px px.histogram(pd.DataFrame({'N':[1,1,1,1,2,3,3,4,5,6,7,7,7,7,7]}), x='N', cumulative=True, nbins=7) </code></pre> <p><a href="https://i.sstatic.net/ZwLJs.png" rel="nofollow n...
<python><plotly>
2023-02-22 14:02:58
2
4,512
quant
75,533,746
5,806,297
Custom component in Streamlit is having trouble loading
<p>I'm testing out a custom <a href="https://github.com/mstaal/msal_streamlit_authentication" rel="nofollow noreferrer">authentication component</a> for my Streamlit app. However, when using the component in production, it fails to render for some reason. <a href="https://i.sstatic.net/HhkAK.png" rel="nofollow noreferr...
<python><typescript><streamlit>
2023-02-22 13:57:03
2
853
Artem
75,533,709
13,212,499
Weighted average on a GroupBy DataFrame with Multiple Columns and a Fractional Weight Column
<p>My question is similar to <a href="https://stackoverflow.com/questions/31521027/groupby-weighted-average-and-sum-in-pandas-dataframe">this</a> and <a href="https://stackoverflow.com/questions/57778649/return-groupby-weighted-average-for-multiple-pandas-dataframe-columns-as-a-dataf">that</a> but neither answer works ...
<python><pandas><dataframe>
2023-02-22 13:54:43
2
349
Ilya Voytov
75,533,620
11,167,163
What Is the new pandas update on groupby ? (FutureWarning)
<pre><code>DF.groupby([&quot;Criteria&quot;], as_index=False).apply(fn).groupby('Criteria').agg(d_agg1).round(2) </code></pre> <p>In the future, the group keys will be included in the index, regardless of whether the applied function returns a like-indexed object. To preserve the previous behavior, use</p> <pre><code> ...
<python><pandas>
2023-02-22 13:48:33
1
4,464
TourEiffel
75,533,619
2,505,799
Using Python to Iterate over a dataset rows part simultaneously
<p>I am looking for directions to iterate over 100K+ rows and two columns of a dataset (CSV or Google sheet) partly simultaneously, but with a delay.</p> <p>The task is to perform an API request using each row data, with a returned API response ID saved in a third column (iterating over 100K+ rows is expected to take a...
<python><python-3.x><pandas>
2023-02-22 13:48:24
1
1,019
MikG
75,533,582
218,768
maximum recursion depth when searching python object - requests
<p>This code works well when running from a python terminal. However, when running inside a DCC called Nuke - ( compositing software in vfx ), this gives recursion error. Totally blank on why this occurs.</p> <pre><code>import requests url = 'xxxxxxxx.com/my_work' data = {'field_to_query_01': 4444, 'field_to_query_02':...
<python><python-requests>
2023-02-22 13:44:42
0
1,078
nish
75,532,988
2,281,274
Patch module before importing in Python
<p>I need to patch a global constant in a module before importing it (before executing code from it).</p> <p>It's imported as <code>from app.foo.bar import Bar</code>.</p> <p>In the bar (<code>app/foo/bar.py</code>) there is a constant I want <code>mock.patch</code>, and that constant is checked at load time (code is i...
<python><monkeypatching>
2023-02-22 12:56:40
1
8,055
George Shuklin
75,532,908
762,688
VS Code Python launch.json config to set cwd to specific module directory
<p>Searching through <a href="https://stackoverflow.com/questions/38623138/vscode-how-to-set-working-directory-for-debugging-a-python-program">this question</a>, I was not able to find the information I need.</p> <p>My dir structure in VS Code:</p> <pre><code>ProjectXYZ | -module1 </code></pre> <p>My launch.json:</p> <...
<python><json><visual-studio-code><vscode-debugger><launch>
2023-02-22 12:49:36
1
759
sean.net
75,532,805
13,394,817
How to specify spacings among words of several sentences to force nth word in each sentence start from exact the same coordinate on plot in python
<p>I am trying to write some grouped texts, each sentence in each group contain 4 parts: <code>value + unit + symbol + value</code> e.g., <code>0.1 (psi) -&gt; 0.0223</code>, on a plot. Each group will begin from a specified coordinate, but I couldn't force the second parts (<em>units</em>) to begin from an exact the s...
<python><string><string-length>
2023-02-22 12:39:57
1
2,836
Ali_Sh
75,532,801
12,169,382
How to get bivariate normal probability distribution with specified standard deviation and angle in python
<p>I want to get a bivariate normal probability distribution(hereafter referred to as BNPD) from ellipse parameters. As shown in the illustraion below, the length of the major axis of the ellipse will be taken as 3 times the standard deviation of BNPD, the same to the minor axis, and the rotation angle of ellipse is ta...
<python><numpy><normal-distribution><ellipse><probability-distribution>
2023-02-22 12:39:43
1
700
Wade Wang
75,532,764
1,549,736
`conda-build` failing to populate working source directory?
<p>After updating the <em>Anaconda</em> installation on my Windows 11 Home Dell XPS-15 7590 laptop, my previously working <code>conda build</code> recipes are failing, all in the same manner:</p> <pre><code>(base) capnf@DESKTOP-G84ND7C MINGW64 ~/Documents/GitHub/PyBERT (master) $ conda build --python=3.9 --numpy=1.23 -...
<python><anaconda><conda><conda-build>
2023-02-22 12:35:58
0
2,018
David Banas
75,532,739
2,170,269
Incompatible `__iadd__` and `__add__` in mypy
<p>I'm writing some code for vectors and matrices where I want to type-check dimensions. I ran into a problem with type-checking <code>__add__</code> and <code>__iadd__</code>, though. With the simplified example below, <code>mypy</code> tells me that <code> Signatures of &quot;__iadd__&quot; and &quot;__add__&quot; ar...
<python><python-typing><mypy>
2023-02-22 12:33:46
1
1,844
Thomas Mailund
75,532,661
3,909,896
FastAPI- customize the 404 error on missing parameter in url
<p>I have an API endpoint at <code>/devices/{id}</code>. When I call the API without an <code>id</code>, I get <strong>404 errors</strong> with the vague message <code>&quot;Not found&quot;</code> in the body.</p> <p>Is there any way to customize the content / message of the 404 error in FastAPI when a parameter (in my...
<python><fastapi>
2023-02-22 12:26:04
2
3,013
Cribber
75,532,498
3,224,522
Running multiple snakemake pipelines one after the other with one single script
<p>I was wondering if it was possible to run multiple snakemake pipelines one after another in a row. I have 3 snakemake pipelines, I would like the 1st one to finish, then the 2nd one starts in automatic, then the 3rd one will start as soon as the 2nd one finishes in conda environment. The inputs and outputs might not...
<python><snakemake>
2023-02-22 12:07:57
1
1,151
user3224522
75,532,436
17,530,552
How to interpolate the first and the last values using pandas.DataFrame.interpolate?
<p>I know that this question has been asked before, but the suggested solutions that I found to not work for me. Maybe I am trying to do something that is simply not possible, but let me explain.</p> <p>I have a time-series <code>data</code> that has some values of <code>0</code>. I would like to interpolate the zeros ...
<python><pandas><dataframe><interpolation>
2023-02-22 12:02:36
1
415
Philipp
75,532,382
9,403,794
Pandas df.apply seems not working correctly. Is df apply vectorized?
<p>As @jpp answare in <a href="https://stackoverflow.com/a/52674448/9403794">Performance of Pandas apply vs np.vectorize to create new column from existing columns</a>:</p> <blockquote> </blockquote> <p>I will start by saying that the power of Pandas and NumPy arrays is derived from high-performance vectorised calculat...
<python><pandas>
2023-02-22 11:57:02
0
309
luki
75,532,295
4,764,419
Snakemake expand zip some wildcards and expand full the other
<p>I have three lists</p> <pre><code>BASES = [A,B,C] CONTRASTS = [1,2,3] ALLOUTPUTS = [outs1,outs2] </code></pre> <p>I want to zip together bases and contrasts, but expand fully all options from output dir</p> <p>Desired output would be something like</p> <pre><code>outs1/A-1_comparison.bed outs1/B-2_comparison.bed out...
<python><snakemake>
2023-02-22 11:48:00
1
463
Al Bro
75,532,164
14,269,252
get a list of values from user in streamlit app
<p>I want to get a list of values from user, but I have no idea how to perform. I tried with code as follows but this is not the correct way.</p> <pre><code>import streamlit as st collect_numbers = lambda x : [str(x)] numbers = st.text_input(&quot;PLease enter numbers&quot;) st.write(collect_numbers(numbers)) </code...
<python><streamlit>
2023-02-22 11:34:22
3
450
user14269252
75,532,043
15,906,357
How to get the correct info while extracting some particular key value from nested JSON
<p>I want to extract the task name and config corresponding to each task into new variable.</p> <p>The code that I have shared is not giving me the desired output. Although it is extracting some info but it is not able to extract all the required details.</p> <p>Here is the json:</p> <pre><code>old = { &quot;ta...
<python><json><python-3.x><nested-json>
2023-02-22 11:23:26
2
377
XGB
75,531,834
1,738,522
Flask trying to return a single item from a list returns an error
<p>I'm have a flask app which lists out my items:</p> <pre><code>@bp.route('/explore') def explore(): posts = Post.query.order_by(Post.timestamp.desc())) return render_template('explore.html', title='Explore', posts=posts.items) </code></pre> <p>What I am trying to do is be able to put the post ID in the URL so...
<python><sqlalchemy><flask-sqlalchemy>
2023-02-22 11:03:49
0
12,563
Jimmy
75,531,642
2,057,969
When is it necessary to define __getattr__() and __setattr()__ methods for a class?
<p>The official Python Programming FAQ advises the programmer to define the methods <a href="https://docs.python.org/3/reference/datamodel.html#object.__getattr__" rel="nofollow noreferrer"><code>object.__getattr__(self, name)</code></a> and <a href="https://docs.python.org/3/reference/datamodel.html#object.__setattr__...
<python><python-3.x>
2023-02-22 10:48:39
1
1,878
Lover of Structure
75,531,538
9,644,712
Calculating time difference with different base years in pandas
<p>Let's assumme I have the following data:</p> <pre><code>d = {'origin': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'], 'destination': ['b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c'], 'year': [2000, 2001, 2002, 2003, 2004, 2005, 2000, 2001, 2002, 2003, 2004, 2005], 'value': [10, 17, 22, 7, ...
<python><pandas>
2023-02-22 10:41:00
2
453
Avto Abashishvili
75,531,441
740,521
How to get hashlib to work on both Python2 and Python3
<p>This code works fine when using Python2, however when using Python3 it gives me this error:</p> <blockquote> <p>Checksum error: bob.tgz, Unicode-objects must be encoded before hashing</p> </blockquote> <p>I then made some changes to use byte like objects in the sha256 object but then I started getting:</p> <blockquo...
<python><python-3.x><hashlib>
2023-02-22 10:33:57
0
1,206
user740521
75,531,381
13,076,839
EINVAL when connect to a unix domain socket in K8s container
<p>I want to connect to a container create by K8s using unix domain socket, here is my logic in container:</p> <pre><code>def main(): file_sock = tornado.netutil.bind_unix_socket(&quot;/test/f.sock&quot;) client, address = file_sock.accept() ... </code></pre> <p>this container will start by K8s with configu...
<python><c><kubernetes><unix-socket>
2023-02-22 10:28:43
0
354
MrZ
75,531,326
3,102,638
vscode changing python interpreter leads to no module named debugpy
<p>Since I changed the python interpreter from the default one in my system, I am no longer able to debug python code. When I hit F5, I see a loading bar in the &quot;RUN and DEBUG&quot; window, it loads for a few seconds then disappears and nothing more.</p> <p>My vscode</p> <blockquote> <p>Version: 1.75.1 (user setup...
<python><python-3.x><visual-studio-code><debugging><vscode-extensions>
2023-02-22 10:24:29
1
400
a_bet
75,531,194
9,879,534
how to slice numpy array with an n*2 numpy index pythonicly?
<p>I don't know how to describe my question, if there already exists answer please redirect this question. My question is, like code below:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np idx = np.array([[1,3],[5,7], [9,11]], dtype=np.int64) data = np.arange(30).reshape(2, 15) need_list = [] for...
<python><numpy>
2023-02-22 10:13:49
3
365
Chuang Men
75,531,172
1,367,705
How to get all users in organization in GitHub using PyGithub? I'm getting github.GithubException.UnknownObjectException
<p>I would like to print all users in my organization in GitHub using PyGitHub.</p> <p>The below snippet works, however it returns a <code>PaginatedList</code>:</p> <pre><code>python3 -c 'import os; from github import Github;g = Github(os.environ[&quot;TOKEN&quot;]); repo = g.get_repo(&quot;ORG/REPO&quot;); organizat...
<python><python-3.x><github><pygithub>
2023-02-22 10:11:03
0
2,620
mazix
75,531,156
6,552,836
Scipy / Mystic taking too long to simplify expression
<p>I'm trying to use mystic to create a simplified expression of my constraints. I have an array of 200 elements. I'm first testing for 1 constraint, which is limiting the sum of all the variables between min and max limits like this:</p> <p><code>0 &lt;= x0 + x1 + x2 + ....... x198 + x199 &lt;= 20000</code></p> <p>Th...
<python><scipy><scipy-optimize><mystic>
2023-02-22 10:09:32
1
439
star_it8293
75,531,132
14,720,380
How can I implement a default factory for a generic type in a Pydantic BaseClass?
<p>I want to create a generic base model, that the field that defaults to the default factory for that type:</p> <pre><code>from pydantic import BaseModel, Field from pydantic.generics import GenericModel, Generic from typing import TypeVar, Generic, Optional T = TypeVar(&quot;T&quot;) class Material(GenericModel, G...
<python><generics><pydantic>
2023-02-22 10:07:11
0
6,623
Tom McLean
75,531,062
19,570,235
How to resolve attribute reference for inherited objects in Python?
<p>I would like to have a proper Python typing for the setup I have created.</p> <p>The issue I have is connected with class B, in which my IDE (pyCharm) reports unresolved attribute reference.<br>However, this setup is working fine.</p> <pre class="lang-py prettyprint-override"><code>class ConfigA: def __init__(se...
<python><python-typing>
2023-02-22 10:01:04
1
417
mlokos
75,531,014
6,281,366
enum like structure that represents a tree
<p>i want to represent a constant tree of strings, not a dynamic one.</p> <p>for example:</p> <p>structure -&gt; house,tower</p> <p>house -&gt; green_house, yellow_house</p> <p>tower -&gt; small_tower, big_tower</p> <p>where each of them is a string (house='house')</p> <p>the goal is to be able to access the tree in su...
<python><pydantic>
2023-02-22 09:57:27
1
827
tamirg
75,530,980
5,775,358
Polars subtract numpy 1xn array from n columns
<p>I am struggling with polars. I have a dataframe and an numpy array. I would like to subtract them.</p> <pre><code>import polars as pl import pandas as pd df = pl.DataFrame(np.random.randn(6, 4), schema=['#', 'x', 'y', 'z']) arr = np.array([-10, -20, -30]) df.select( pl.col(r'^(x|y|z)$') # ^[xyz]$ ).map_rows(...
<python><dataframe><numpy><python-polars>
2023-02-22 09:54:57
5
2,406
3dSpatialUser