QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
77,309,471
3,433,875
Add a new row to an existing dataframe pandas error
<p>I need to append a new row that I specify to an existing dataframe:</p> <pre><code>import pandas as pd import random random.seed(42) data = {'group':['a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c' ], 'value' : [1, 2, 5, 3, 4, 5, 7, 4, 7, 9], 'year': ['2010', '2010', '2010', '2011', '2011', '2011'...
<python><pandas>
2023-10-17 13:35:06
4
363
ruthpozuelo
77,309,464
14,468,588
DCPError: Problem does not follow DCP rules - TV minimization using CVXPY library
<p>I want to solve a compressed sensing problem which I wish to minimize total variation(TV) of my object vector. Here is representation of my code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import os import numpy as np from scipy.optimize import minimize import scipy.io import pandas as pd impo...
<python><cvxpy><convex-optimization>
2023-10-17 13:33:10
1
352
mohammad rezza
77,309,413
21,295,456
How to make pynput.keyboard.listener thread keep running in the background even when main app is terminated
<p>I have a main GUI app made out of <em>Tkinter</em>, which includes a button called <em>&quot;start&quot;</em> , which when pressed initiates the <code>pynput.keyboard.listener</code> thread .</p> <p>Its listens to the keystrokes all right .</p> <p>But when I terminate the app (by clicking <em>'x'</em>) , the keystr...
<python><multithreading><tkinter><pynput>
2023-10-17 13:27:45
1
339
akashKP
77,309,270
7,667,649
Python numpy: don't understand the result of subtracting np.datetime64 dates
<p>If I do the following operation:</p> <pre><code>import numpy as np np.datetime64('20230901') - np.datetime64('20230831') </code></pre> <p>I get the result</p> <pre><code>numpy.timedelta64(70,'Y') </code></pre> <p>I get that the letter 'Y' in this case means Year, but what does the 70 mean?</p> <p>Furthermore, if I ...
<python><numpy><timedelta><datetime64>
2023-10-17 13:08:05
1
479
Mauro
77,309,155
14,631,246
Python `requests.Session()`: response headers not showing `Set-Cookie` headers
<p>I was following the tutorial over at <a href="https://requests.readthedocs.io/en/latest/user/advanced/" rel="nofollow noreferrer">https://requests.readthedocs.io/en/latest/user/advanced/</a> regarding the <code>requests.Session()</code>. I tried to access the response headers for the HTTP GET request that is expecte...
<python><python-requests>
2023-10-17 12:50:53
2
618
Jarrett GXZ
77,309,123
19,130,803
extend list for matching dictionary keys
<p>I am trying to combine multiple sub <code>dictionaries</code> and into single <code>dictionary</code> based on <code>keys</code>. The dictionary <code>keys</code> are fixed(same) and <code>items</code> are <code>list</code> that I am trying to combine.</p> <pre><code>fruits = ['apple', 'banana', 'cherry'] cars = ['...
<python>
2023-10-17 12:46:14
6
962
winter
77,309,029
10,416,012
asyncio.run not working at python azure function app
<p>I have a code that works in local perfectly:</p> <pre><code>... main.py from file import my_test ... test.py async test(): &quot;&quot;&quot;some async function&quot;&quot;&quot; await asyncio.sleep(1) return &quot;test&quot; import asyncio my_test = asyncio.run(test()) </code></pre> <p>Notice that te...
<python><azure><azure-functions><event-loop><aio>
2023-10-17 12:33:28
0
2,235
Ziur Olpa
77,308,976
14,498,998
Media files are not shown: open() "/home/shahriar/Amlak/real_estate/media/images/image1.jpg" failed (13: Permission denied) - Django Nginx
<p>I'm trying to see my media files in my website, but I can't. Static files are OK but Media files, despite all my efforts are not visible.</p> <p>Here is nginx error log:</p> <pre><code>2023/10/17 11:59:33 [error] 48068#48068: *7 open() &quot;/home/shahriar/Amlak/real_estate/media/images/ویلا-چمستان-1_uWh54BB.jpg&quo...
<python><django><linux><ubuntu><nginx>
2023-10-17 12:25:55
1
313
Alin
77,308,801
13,935,315
Nested Cross Validation with Optuna
<p>I want to perform nested cross validation using Optuna. I am wondering what your take is on my solution. Would one implement it like this or am I making some fundamental mistakes? In particular with the branching strategy and mixing <code>trial.suggest_categorical</code> and <code>OptunaSearchCV</code></p> <pre clas...
<python><scikit-learn>
2023-10-17 11:58:17
0
331
Jens
77,308,683
1,001,290
Guest checkout business logic for server/database with Stripe
<p>I am making an a simple app which allows users to post ads to the website for a fee, as in pay per post. No account is required, it is in essence a guest checkout by default.</p> <p>The issue I am dealing with is the order and best way to implement the business logic on the server side.</p> <p>My flow is as follows:...
<python><django><sqlite><stripe-payments><business-logic>
2023-10-17 11:41:46
1
412
Sjieke
77,308,674
14,282,714
Count number of groups with any certain value across rows pandas
<p>I would like to count the number of groups which have any <code>True</code> value across there rows in a column. Here I have some reproducible data:</p> <pre><code>import pandas as pd df = {'group': [1, 1, 1, 2, 2, 2, 3, 3], 'condition': [&quot;True&quot;, &quot;False&quot;, &quot;False&quot;, &quot;True&quot;, &quo...
<python><pandas>
2023-10-17 11:39:42
3
42,724
Quinten
77,308,472
13,916,049
Subset dataframe based on index substring that matches the index of another dataframe in unspecified order
<p>I want to subset <code>anno_GSE159115</code> based on the substring of its index that matches any value in <code>adata.obs.index</code>, regardless of order. My code does not return all the matches when I use <code>isin</code>.</p> <pre><code>anno_GSE159115[anno_GSE159115.index.str.rsplit(&quot;_&quot;, 1).str[-1].i...
<python><pandas>
2023-10-17 11:05:13
0
1,545
Anon
77,308,447
6,851,715
Dynamically create a fake dataset based on the subset of another (real) dataset
<p>I've got a few datasets and for each, I'd like to create a fake dataset that is kind of a representative of that dataset. I need to do it dynamically, only based on the type of data (numeric, obj)</p> <p>Here's an example</p> <pre><code>import pandas as pd import random # Create a dictionary with columns as lists d...
<python><pandas><random><dynamic><faker>
2023-10-17 11:02:05
2
1,430
Ankhnesmerira
77,308,411
3,445,378
Can I use the python library 'xmlschema' to create XML-Documents from scratch?
<p>There are some schema definition files (xsd). They can be read with the library <a href="https://xmlschema.readthedocs.io/en/latest/" rel="nofollow noreferrer">xmlschema</a>. I can use it to validate or convert some existing XML-Documents. That is fine.</p> <p>But I have to create entire new XML-Documents from scrat...
<python><xml><xsd>
2023-10-17 10:57:09
1
1,280
testo
77,308,321
1,227,057
How to install external Python dependencies for Spark workers in a PySpark cluster?
<p>I am running a Spark job with a PySpark user-defined function (UDF) that requires the <code>requests</code> package, which is not a standard built-in Python package. When executing the job, I encounter the error <code>ModuleNotFoundError: No module named 'requests'</code>. I understand that the dependencies are miss...
<python><apache-spark><pyspark>
2023-10-17 10:43:22
1
1,401
micmia
77,308,150
6,393,479
How to fetch data asynchronously from a multiprocessing spawn process in Python?
<p>I have a FastAPI app with a single endpoint <code>/generate</code>. This endpoint takes in requests and puts them into global <code>input_queue</code>. Now the background spawn process called <code>worker</code> gets the data from the <code>input_queue</code> and do some calculations on it real-time and stores the o...
<python><multiprocessing><python-asyncio><fastapi><python-multiprocessing>
2023-10-17 10:17:47
2
1,053
Uchiha Madara
77,308,083
9,530,017
How to change figure size and other size elements for a svg file
<p>I am currently working with figures that I save in <strong>SVG</strong> format, in order to include them into a HTML presentation. I'm looking for consistency in terms of fonts, line sizes etc .. across the presentation.</p> <p>Hence, I need to scale all my figures of a factor 2 in width compared to the default <cod...
<python><matplotlib><svg><svgutils>
2023-10-17 10:08:57
1
1,546
Liris
77,308,067
4,288,043
wrap one pandas column heading and another column contents simultaneously
<p>I've had two styling things clash in a pandas dataframe in jupyter notebook and cancel each other out.</p> <p>One column has a very long column heading, the other column has a small column heading but the cell contents are a lot of text.</p> <p>I wanted to wrap the heading of the one column but contents of the other...
<python><pandas><pandas-styles>
2023-10-17 10:06:15
1
7,511
cardamom
77,308,057
7,737,097
Conversion accuracy issues of E57 to LAS in Python using pye57 and laspy
<p>I am attempting to convert an .e57 pointcloud into a .las pointcloud but I am running into issues which seem to be caused by accuracy. The following images illustrate the original .e57 in CloudCompare, compared to the converted .las file also in CloudCompare. The point size is bumped up significantly to compare the ...
<python><python-3.x><data-conversion><floating-accuracy><point-clouds>
2023-10-17 10:05:06
1
609
Arjan
77,307,979
11,678,191
Installing IPOPT in Linux (to be used with Pyomo)
<p>I am trying to install ipopt in a Linux machine but without success...</p> <p>I have followed the steps in <a href="https://coin-or.github.io/Ipopt/INSTALL.html" rel="nofollow noreferrer">https://coin-or.github.io/Ipopt/INSTALL.html</a>.</p> <p>I am able to sucesfully compile it but in the end it seems that the bin ...
<python><optimization><pyomo><ipopt>
2023-10-17 09:58:01
2
319
rapha123
77,307,953
5,379,182
SQLAlchemy session is invalidated unexpectedly causing PendingRollbackError
<p>I am using SQLAlchemy (2.0.20) as an ORM library in my FastAPI project. Whenever a request is made to the API server, the route requires a db <code>sqlalchemy.orm.session.Session</code> object. This session object is either created anew by a <code>DbSession = sessionmaker(engine)</code> or taken from the cache</p> <...
<python><sqlalchemy><fastapi>
2023-10-17 09:55:04
0
3,003
tenticon
77,307,821
17,160,160
Dictionary creation from dataframe, replace values, remove nulls. Pandas
<p>Suppose the following dataframe in which one column (<code>df.VALUE</code>) contains only string values and several other columns which contain a combination of null and floats.</p> <pre><code>df = pd.DataFrame({ 'VALUE': ['A','B','C','D','E'], 'CAT1' : [np.nan,1,1,1,1], 'CAT2': [1,1,np.nan,np.nan,1]}) <...
<python><pandas>
2023-10-17 09:38:41
2
609
r0bt
77,307,788
16,405,935
Join data from two data frame
<p>I have two data frame that I want to join from <code>df2</code> to <code>df</code> by using values of <code>df2</code> rows. Something as below:</p> <pre><code>import pandas as pd import numpy as np #create DataFrame df = pd.DataFrame({'Definition': ['Loan', 'Deposit'], '20231015': [28, 17], ...
<python><pandas><join>
2023-10-17 09:34:34
1
1,793
hoa tran
77,307,787
3,241,486
Run localGPT via pipenv instead of conda
<h3>Goal</h3> <p>I would like to use <strong>pipenv</strong> instead of <strong>conda</strong> to run <a href="https://github.com/PromtEngineer/localGPT" rel="nofollow noreferrer"><strong>localGPT</strong></a> on a Ubuntu 22.04.03 machine.</p> <p><em>Reason: On the server where I would like to deploy <em>localGPT</em> ...
<python><conda><pipenv><pdfminer><privategpt>
2023-10-17 09:34:27
0
2,533
chamaoskurumi
77,307,743
16,545,894
Create a Polars Dataframe by appending multiple row at a time
<p><strong>How can I make DataFrame and then more rows one at a time?</strong></p> <pre><code>import polars as pl df_polars = pl.DataFrame({ 'abc': [], 'def': [], 'ghi': [] }) value_to_set = 10.0 df_polars = df_polars.extend([ pl.lit(None).alias('abc'), pl.lit(value_to_set).alias('def'), ...
<python><python-polars>
2023-10-17 09:27:13
2
1,118
Nayem Jaman Tusher
77,307,742
18,904,265
How should I pass a class as an attribute to another class with attrs?
<p>So, I just stumbled upon a hurdle concerning the use of <code>attrs</code>, which is quite new to me (I guess this also applies to dataclasses?). I have two classes, one I want to use as an attribute for another. This is how I would do this with regular classes:</p> <pre class="lang-py prettyprint-override"><code>cl...
<python><python-attrs>
2023-10-17 09:26:37
2
465
Jan
77,307,614
4,399,016
Applying function to Pandas Data frame and merging resulting data frames into a new data frame
<p>I have this code:</p> <pre><code>import pandas as pd import yfinance as yF import datetime from functools import reduce def get_returns_change_period(tic,com,OHLC_COL1,OHLC_COL2): df_Stock = yF.download(tickers = tic, period = &quot;38y&quot;, interval = &quot;1mo&quot;, prepost = False, repair = False) df...
<python><pandas><dataframe><merge>
2023-10-17 09:11:25
1
680
prashanth manohar
77,307,603
11,913,986
map columns of two dataframes based on array intersection of their individual columns and based on highest common element match Pyspark/Pandas
<p>I have a dataframe df1 like this:</p> <pre><code>A B AA [a,b,c,d] BB [a,f,g,c] CC [a,b,l,m] </code></pre> <p>And another one as df2 like:</p> <pre><code>C D XX [a,b,c,n] YY [a,m,r,s] UU [e,h,I,j] </code></pre> <p>I want to find out and map column C of df2 with column A of df1 based on the highest element m...
<python><arrays><pandas><dataframe><pyspark>
2023-10-17 09:10:03
1
739
Strayhorn
77,307,584
14,566,295
InterpolationWarning: KPSS test in Python with statsmodels
<p>When I run below code, I get specific warning</p> <pre><code>import numpy as np from statsmodels.tsa.stattools import kpss kpss(np.random.choice(range(-1000,1000),10000)) </code></pre> <p>Warning message</p> <pre><code>&lt;stdin&gt;:1: InterpolationWarning: The test statistic is outside of the range of p-values avai...
<python><python-3.x><statsmodels>
2023-10-17 09:07:18
1
1,679
Brian Smith
77,307,421
3,553,923
Robust import of Python package modules in nested git submodule structure
<p>This might be a duplicate, but I didn't really find questions with this problem (nor a helpful answer).</p> <p>The setup is as follows (simplified):</p> <p>I have three different git Python projects using each other as submodules (note: I use the name <code>submodule</code> here referring to the git submodules. In P...
<python><git><import><nested><git-submodules>
2023-10-17 08:45:03
1
323
clel
77,307,413
17,082,611
Best practice for loading test data in separate python files for model training and evaluation: should I train_test_split again or load test data?
<p>Let's suppose I have a <strong>train.py</strong> file containing the logic for training a model and then saving its parameters into a directory called <code>weights/</code>:</p> <pre><code>x_train, x_test, y_train, y_test = train_test_split(x, y) model = compile() model.fit(x_train, y_train) model.save_weights(&quot...
<python><tensorflow><machine-learning><train-test-split>
2023-10-17 08:43:50
1
481
tail
77,307,336
4,451,521
How can adjust the axis so that I don't have unused space in dash?
<p>I have the following dash script</p> <pre><code>import dash from dash import dcc, html from dash.dependencies import Input, Output import pandas as pd import plotly.graph_objects as go import random # Generate random data for demonstration random.seed(42) # For reproducibility data = pd.DataFrame({ 'fr': list(...
<python><plotly-dash>
2023-10-17 08:32:55
1
10,576
KansaiRobot
77,307,174
13,330,214
Does the python library 'webdriver-manager' always install the latest chrome driver?
<p>Even reading the github page, the role of this library is confusing.</p> <ol> <li>always install the latest chrome drivers</li> <li>checks the user's Chrome browser version and installs the appropriate Chrome driver.</li> </ol> <p>Which is it?</p>
<python><selenium-webdriver><webdriver-manager><webdrivermanager-python>
2023-10-17 08:08:02
1
705
newbieeyo
77,306,999
2,890,093
Flask restx Debug "Unauthorized" response
<p>I have a Flask (2.2.3) app with Flask-RESTX (1.1.0) used as an API (without frontend). I'm using flask-azure-oauth library to authenticate users using Azure AD. The setup is:</p> <pre class="lang-py prettyprint-override"><code>from flask import Flask, current_app from flask_azure_oauth import FlaskAzureOauth from fl...
<python><azure><flask><flask-restx><azure-oauth2>
2023-10-17 07:37:57
1
10,783
Kombajn zbożowy
77,306,963
22,046,817
Does Class Variable is common among objects in Python
<p>Suppose I want to implement common variable among objects using class variables (similar to static in java/c++).</p> <p>When I access class variable using object, it shows default value. Then I updaded class variable via object, its not updating class variable for other objects. It is showing old value in when class...
<python><class><static-variables>
2023-10-17 07:32:07
1
772
Vinay Vishwakarma
77,306,959
638,504
Expose statistics/logging remotely in Python
<p>I have Python scripts which run in the background (for a long time). Those scripts process data in some way and log output to the STDOUT - nothing fancy...</p> <p>Playing around with <a href="https://www.dask.org/" rel="nofollow noreferrer">Dask</a> and its status page (which shows the progress if you run something ...
<python><logging><jupyter-notebook><monitoring>
2023-10-17 07:31:09
0
2,193
ddofborg
77,306,748
1,801,060
How is QStyle.StandardPixmap defined in PyQt6
<p>How is the enumeration for QStyle.StandardPixmap defined in PyQt6? I've tried to replicate it as shown below:</p> <pre><code>from enum import Enum class bootlegPixmap(Enum): SP_TitleBarMenuButton = 0 SP_TitleBarMinButton = 1 SP_TitleBarMaxButton = 2 for y in bootlegPixmap: print(y) </code></pre> <p...
<python><enums><pyqt><pyqt6>
2023-10-17 06:55:46
1
2,821
user1801060
77,306,569
5,731,101
Django proxy-model returning wrong ContentType
<p>Let's say we have a model <code>Company</code> and subtype <code>Client</code> like so:</p> <pre class="lang-py prettyprint-override"><code>class Company(models.Model): name = models.CharField(max_length=100) related_companies = models.ManyToManyField('self', symmetrical=True) is_customer = models.Boolea...
<python><django><django-models>
2023-10-17 06:24:02
1
2,971
S.D.
77,306,397
1,609,428
wide to long in pandas while aligning columns
<p>Consider the following example:</p> <pre><code>pd.DataFrame({'time' : [1,2,3], 'X1-Price': [10,12,11], 'X1-Quantity' : [2,3,4], 'X2-Price': [3,4,2], 'X2-Quantity' : [1,1,1]}) Out[92]: time X1-Price X1-Quantity X2-Price X2-Quantity 0 1 10 ...
<python><pandas>
2023-10-17 05:42:58
3
19,485
ℕʘʘḆḽḘ
77,306,322
18,148,705
Getting Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ec2-ip/login
<p>I have a react frontend which is deployed on S3. Now I have mapped my domain with the S3 hosted url. So whenever someone tries to access s3 hosted url, they will get redirected to <a href="https://myproject.mycompany.com" rel="nofollow noreferrer">https://myproject.mycompany.com</a> . My backend is using Flask pytho...
<python><reactjs><nginx><flask><cors>
2023-10-17 05:19:01
1
335
user18148705
77,306,171
146,077
Can Boto3's DynamoDB "update_item" method handle native python objects?
<p>I'm currently using boto3 to get and put items into DynamoDB. I can get and put like this:</p> <pre><code>def get_item(key): # key is a dict like {&quot;partitionkey&quot;: &quot;abc&quot;, &quot;sortkey&quot;: &quot;123&quot;} table = boto3.resource(&quot;dynamodb&quot;).Table(DYNAMO_TABLE) response = t...
<python><amazon-dynamodb><boto3>
2023-10-17 04:21:04
1
28,876
Kirk Broadhurst
77,306,112
2,728,074
Write dynamically-defined python function to file
<p>Consider:</p> <pre><code>def func_create(default_val): def the_function(): print(&quot;The default value is: %s&quot; % default_val) return the_function new_f = func_create(1.0) new_f() </code></pre> <p>Which prints the line:</p> <pre><code>The default value is: 1.0 </code></pre> <p>Is there a way t...
<python><function><file><dynamic><export>
2023-10-17 04:03:44
2
469
Charlie
77,306,059
70,157
Interrogate Python package dependencies without using network
<p>How can I query Python's 'pip' to answer the question &quot;is this install specification already satisfied&quot;, without any network requests?</p> <p>To allow the build system to work offline, I want to interrogate the Python environment for <em>whether</em> anything would need to be installed to satisfy dependenc...
<python><pip>
2023-10-17 03:42:14
0
32,600
bignose
77,306,024
7,260,269
Problem sending email with template_id with Airflow and Sendgrid
<p>I am trying to send an email with Sendgrid and <a href="https://en.wikipedia.org/wiki/Apache_Airflow" rel="nofollow noreferrer">Airflow</a> (2.4.2). I am able to send the email, but when I try to pass a <em>template_id</em>, the email is sent without the template design. It looks like I am passing the template_id in...
<python><airflow><sendgrid><directed-acyclic-graphs>
2023-10-17 03:29:43
1
341
James Hameson
77,305,875
6,303,639
Python get the total execution time of a function
<p>Suppose that I have a function:</p> <pre class="lang-py prettyprint-override"><code>def func(x): time.sleep(x) return x </code></pre> <p>It will be called in every place when needed, for example, <code>func_a in class A</code>, <code>func_b in class B</code>... And all the modules start from a main function,...
<python><decorator><profiler>
2023-10-17 02:30:07
2
783
Whisht
77,305,865
1,620,040
Pandas Dataframe from a text file (table) python
<p>Considering my text file would have the following pattern:</p> <pre><code> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS ...
<python><pandas><dataframe>
2023-10-17 02:24:21
1
5,362
Lakshmi Narayanan
77,305,848
9,983,652
is there a command to clear all output when running the notebook?
<p>In jupyter notebook, typically I use the menu to clear all output. I am wondering if there is a command (majic command or lines of code) which I can place on the first cell and it will clear all output when running the notebook?</p> <p>Thanks</p>
<python><jupyter-notebook>
2023-10-17 02:18:58
1
4,338
roudan
77,305,778
2,030,532
How to vectorize <x(t-lag), y(t)> for two similar shaped numpy arrays?
<p>I have two numpy arrays of the same dimensions <code>x</code> and <code>y</code>. I would like to calculate the &lt;x(t-lag&gt;, y(t)&gt; as follows for different values of lag. The following code works by I am wondering if there is a vectorized implementation that could be faster.</p> <pre><code>def foo(x, y, lags)...
<python><numpy>
2023-10-17 01:48:37
1
3,874
motam79
77,305,726
156,458
In Python Regex, how can I express the following pattern of strings?
<p>In Python Regex, how can I express the following pattern of strings?</p> <p>Suppose I have two subpatterns p1 and p2. I would like the pattern for any of the following cases:</p> <ul> <li>p1p2 (p1 appears immediately before p2)</li> <li>p1 (no p2)</li> <li>p2 (no p1)</li> </ul> <p>It is not possible that the two pat...
<python><regex>
2023-10-17 01:26:08
0
100,686
Tim
77,305,722
4,451,521
A plotly plot with many points is very heavy and cannot unzoom
<p>I have made a plot with plotly. It has five plots in it, each with 25409 points.</p> <p>My problem is that the plot appears but it is very heavy when I try to zoom it and unzoom it is impossible.</p> <p>Is there a way that I can do this in a more practical way?</p> <p>Each plot is like this</p> <pre><code>hover_text...
<python><plotly>
2023-10-17 01:24:40
1
10,576
KansaiRobot
77,305,591
433,432
Can I create a normalied image rotation matrix and then use it on multiple different images?
<p>I'm trying to store an affine transformation matrix that is independent of image size (normalized if you will) and then apply that to an image but I'm having problems with the math. It certainly seems possible to me. Here is my python code.</p> <pre class="lang-py prettyprint-override"><code>import cv2 image = cv2....
<python><opencv>
2023-10-17 00:30:54
1
7,257
crowmagnumb
77,305,290
2,646,881
SQLite - create standalone sequence (get autoincrement integer without the need of having table)
<p>I am trying to fix an issue with InfluxDB, where it does not support sequences (unique, incremental Integer column). The workaround I have &quot;invented&quot; is, to create an unique Id outside of Influx, when transforming data into data Points.</p> <p>So my workflow is like: 1.) get set of data 2.) Extract one for...
<python><sqlite><influxdb>
2023-10-16 22:31:18
0
418
rRr
77,305,284
1,234,419
setup unable to find zope
<p>hello I am unable to install crossbar.io due to a zope error. here is the env details</p> <pre><code>ENV: Python 3.11.6 (main, Oct 16 2023, 14:39:12) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. uname -a...
<python><zope><crossbar>
2023-10-16 22:30:24
0
1,403
vector8188
77,305,166
1,644,561
Can you use a HMAC-SHA256 signature in authlib in python?
<p>The <a href="https://docs.authlib.org/en/latest/flask/1/customize.html" rel="nofollow noreferrer">authlib documentation</a> discusses how to process <code>HMAC-SHA256</code> signature methods server side, but there doesn't seem to be anything about how to sign requests with this kind of signature.</p> <p>The followi...
<python><oauth><oauth-1.0a><authlib>
2023-10-16 21:56:32
1
854
avyfain
77,305,151
353,407
Sympy diffgeom: Expressions won't simplify
<p>Here is the setup, defining a manifold and a local coordinate system (x,y,z).</p> <pre><code>from sympy.diffgeom import ( Manifold, Patch, CoordSystem, Differential, WedgeProduct, LieDerivative) from sympy import symbols, simplify R3 = Manifold('R_3', 3) U = Patch('U', R3) cartesian = CoordSystem('xyz', U...
<python><sympy>
2023-10-16 21:54:02
1
5,543
Mark
77,305,072
11,429,035
multiprocessing and write date to disk to reduce memory costs in python?
<p>I am using <code>multiprocessing</code> to do a bunch of parallel computing, and returning the results as a list. The may issue right now is the function often runs out of memory. My current code is like</p> <pre><code>def some_func(a) b = a**2 (some calculations here) return b with multiprocessing.Pool() as p:...
<python><multiprocessing><networkx>
2023-10-16 21:31:59
1
533
Xudong
77,305,054
7,397,195
dateparser search_dates returns impossible year
<p>I'm using dateparser's &quot;search_dates&quot; to parse text for dates and got a strange date in my result.</p> <pre><code>dateparser.__version__ '1.1.8' settings= { 'RELATIVE_BASE': datetime.datetime(2023, 7, 31, 0, 0), 'PREFER_DAY_OF_MONTH': 'first', 'PREFER_DATES_FROM': 'future', 'REQUIRE_PARTS': ['year', ...
<python><dateparser>
2023-10-16 21:27:53
1
454
leeprevost
77,305,001
3,582,701
How to separate the EXE header and the encrypted message of a PGP SDA using Python?
<p>I have both PGP Self Decrypting Archive EXE file and their password. It is my understanding that correspond to an EXE header and the encrypted message.</p> <p>How can I separate the encrypted message for further processing?</p> <p>I'm trying to use PEReader, but I have no idea how identify neither the content not th...
<python><exe><pgp>
2023-10-16 21:15:37
1
506
tristobal
77,304,809
14,546,482
Pydantic 2.0 multiple Basemodel classes - how to handle class dependencies
<p>How can I make my other classes optional in pydantic 2.0? When I have data I dont get an error, however, when I send a null value I get a ValidationError Field Required type=missing error.</p> <p>For Example, I could do <em><strong>profile: Optional[dict[str, str]] = None in User</strong></em> and that works but it ...
<python><python-typing><pydantic>
2023-10-16 20:33:57
1
343
aero8991
77,304,783
179,372
Dask from_delayed() causing high memory usage
<p>I'm following the instructions from (<a href="https://docs.dask.org/en/stable/delayed-collections.html" rel="nofollow noreferrer">https://docs.dask.org/en/stable/delayed-collections.html</a>) to create a custom data loader for a Dask DataFrame, which is basically this:</p> <pre class="lang-py prettyprint-override"><...
<python><pandas><dask><dask-distributed>
2023-10-16 20:28:08
1
20,050
Tarantula
77,304,751
8,205,554
How can I combine two dictionaries with the same keys and values, ignoring string values?
<p>I have a dataset as follows,</p> <pre class="lang-py prettyprint-override"><code>[ {'sets': 3, 'muscle': 'Chest', 'body_part': 'Upper'}, {'sets': 3, 'muscle': 'Chest', 'body_part': 'Upper'}, {'sets': 4, 'muscle': 'Chest', 'body_part': 'Upper'}, {'sets': 2, 'muscle': 'Abdominal', 'body_part': 'Abdominal'}, ...
<python><dictionary>
2023-10-16 20:21:45
2
2,633
E. Zeytinci
77,304,733
5,287,011
append() question - AttributeError: 'numpy.ndarray' object has no attribute 'append'
<pre><code>import numpy as np import pandas as pd from PIL import Image from glob import glob import cv2 import gc import os </code></pre> <p>It is an attempt to build a CNN to classify lung and colon cancer. Dataset: <a href="https://www.kaggle.com/datasets/andrewmvd/lung-and-colon-cancer-histopathological-images" r...
<python><memory-management><append><attributeerror>
2023-10-16 20:17:26
2
3,209
Toly
77,304,705
5,227,892
Load the python dictionary from csv file
<p>I saved the dictionary <code>dict</code> <code>dict_keys(['df1', 'df2'])</code> into a <code>csv</code> file. <code>cat data.csv</code> outputs something like this?</p> <pre><code>,,df1,df2 quantile_10,h0,0.03636844456195831,0.105098 quantile_10,h5,0.0654495671391487,0.108322 quantile_10,h10,0.10933497846126557,0.11...
<python>
2023-10-16 20:12:00
1
435
Sher
77,304,601
489,088
How to use a mask to limit broadcasted operations between two numpy arrays?
<p>I have an array like so:</p> <pre><code>data = np.array([ [[10, 10, 10], [10, 10, 10], [10, 10, 10]], [[20, 20, 20], [20, 20, 20], [20, 20, 20]], [[30, 30, 30], [30, 30, 30], [30, 30, 30]], ], dtype=np.float64) </code></pre> <p>and one to divide values by, like so:</p> <pr...
<python><arrays><numpy><numpy-ndarray><array-broadcasting>
2023-10-16 19:48:50
1
6,306
Edy Bourne
77,304,463
5,924,264
Round and floating point precision
<p>We're writing data to a sql database (sqlite3 to be specific). For a particular column, <code>quantity</code>, it is specified as a <code>REAL</code> (float) column because we store the <code>quantity</code> as multiples of 1000 (so the integer quantity is divided by <code>1000</code>). So the stored quantity is ac...
<python><sql><sqlite><floating-point><rounding>
2023-10-16 19:16:58
3
2,502
roulette01
77,304,386
5,924,264
Does a "round"'ed value guarantee equality?
<p>Suppose i have some floating point value <code>x</code>. Suppose we do <code>x = round(x, 3)</code>, i.e., we truncate after the 3rd decimal place.</p> <p>Then we if we check something like:</p> <pre><code>x == 0.222 </code></pre> <p>Does this guarantee there's no comparison after the 3rd decimal place?</p>
<python><floating-point>
2023-10-16 19:04:45
1
2,502
roulette01
77,304,366
1,386,584
Cannot download file with scrapy-playwright
<p>I was trying to download file via <a href="https://github.com/scrapy-plugins/scrapy-playwright" rel="nofollow noreferrer">scrapy-playwright</a>, but for some reason download of file fails. On URL there is pdf file that I want to download, and I can see from logs that download is started, but it is interrupted. I am ...
<python><scrapy><playwright-python><scrapy-playwright>
2023-10-16 19:00:29
0
5,728
Ivan Vasiljevic
77,304,354
5,431,734
chaining an I/O bound and a cpu bound operation in python multtprocessing
<p>Suppose I want to fetch/read data from the filesystem and then process them with some number crunching function. The former is an io bound hence I will benefit by running multiple threads on it (using <code>multiprocessing.dummy.pool</code> and <code>pool.map</code>) whereas the latter being cpu bound will benefit b...
<python><multithreading><multiprocessing><python-multiprocessing>
2023-10-16 18:57:49
1
3,725
Aenaon
77,304,248
5,131,139
NameError when running Apache Beam pipeline on Google Dataflow when using nested functions
<p>I am working on an Apache Beam pipeline in Python, and I'm encountering a NameError when running the pipeline on Google Dataflow. The error specifically mentions that 'json_encoder' is not defined. The pipeline works fine when running it locally.</p> <p>Here's the gist of the code:</p> <pre><code>import apache_beam ...
<python><google-cloud-dataflow><apache-beam>
2023-10-16 18:35:08
1
1,429
AnandShiva
77,304,230
11,330,134
Order dataframe by two values and assign category per n-size
<p>I have a dataframe with two columns:</p> <pre><code>data = [ (0, 'A'), (0, 'B'), (0, 'C'), (1, 'D'), (1, 'E'), (2, 'F'), (3, 'G'), (4, 'H'), (5, 'I'), ] schm = ['val', 'id'] df = spark.createDataFrame(data,schema=schm) df.show() +---+---+ |val| id| +---+---+ | 0| A| | 0| B| | 0|...
<python><pyspark>
2023-10-16 18:31:42
0
489
md2614
77,304,200
14,608,443
How to loop through a file and use the values in a bash or python script?
<p>I have a numbers.txt file which contains thousands of numbers in the following format</p> <pre><code>00001 00002 </code></pre> <p>I need to create a Python or Bash script which will take each number and replace xyz as seen below with each of the values in a new file. Below is the format:</p> <pre><code>echo '{&quot;...
<python><bash>
2023-10-16 18:25:30
3
373
IveGotCodeButImNotACoder
77,304,167
14,546,482
Using pydantic to change int to string
<p>I am sometimes getting data that is either a string or int for 2 of my values. Im trying to figure out the best solution for handling this and I am using pydantic v2. Ive been studying the @field_validtaors(pre=True) but haven't been successful.</p> <p>Here's my code:</p> <pre><code>class User(BaseModel): system...
<python><pydantic>
2023-10-16 18:18:34
4
343
aero8991
77,304,052
960,412
Transactional Operations with google.cloud.ndb
<p>I am using Google Cloud Datastore via the <a href="https://googleapis.dev/python/python-ndb/latest/" rel="nofollow noreferrer">python-ndb</a> library (Python 3). My goal is to <em>transactionally</em> create two entities at once. For example, when a user creates an <code>Account</code> entity, also create a <code>Pr...
<python><google-cloud-platform><google-app-engine><google-cloud-datastore>
2023-10-16 17:58:09
1
1,280
hyang123
77,304,020
20,947,319
How to filter an item in one queryset from appearing in another queryset in django
<p>I have a Django view where I am getting the first queryset of 'top_posts' by just fetching all the Posts from database and cutting it in the first four. Within the same view, I want to get &quot;politics_posts&quot; by filtering Posts whose category is &quot;politics&quot;. But I want a post appearing in 'top_posts'...
<python><django><django-views><django-queryset>
2023-10-16 17:52:38
1
446
victor
77,303,939
1,726,083
How to locally test FastAPI app using AWS JWT authorizer & API Gateway
<p>I'm struggling to implement testing on my FastAPI which runs under Mangum as a Lambda behind an AWS API Gateway with the <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html" rel="nofollow noreferrer">AWS JWT Authorizer</a>.</p> <blockquote> <p>After validating the JWT,...
<python><pytest><aws-api-gateway><fastapi><mangum>
2023-10-16 17:37:13
1
16,447
erik258
77,303,722
2,382,483
Optimizing divisions in numpy
<p>I have a situation where I need to divide several different large arrays by the same array:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.random.uniform(-1, 1, size=(1000000,)) b = np.random.uniform(-1, 1, size=(1000000,)) c = np.random.uniform(-1, 1, size=(1000000,)) d = np.random.u...
<python><numpy>
2023-10-16 16:56:18
1
3,557
Rob Allsopp
77,303,511
12,553,730
How do you calculate the area metric when comparing three images using python?
<p>I have three images: A, B, and C. I want to compare the difference in area between (A, B) and (C, B). Is there a more efficient and accurate way to do this using Python?</p> <p>Here's what I am currently doing, which I believe is quite inaccurate:</p> <pre><code>from PIL import Image from pycocotools import mask as ...
<python><python-3.x><image><image-processing><image-segmentation>
2023-10-16 16:18:16
1
309
nikhil int
77,303,499
16,591,513
TensorRT seems to lack common functionality
<p>I've recently encountered such an amazing tool called tensorRT, but because I don't have NVIDIA GPU on my laptop, I decided to use Google Collab instead to play around with this technology.</p> <p>I used simple pip command to install necessary libraries, including ones for CUDA management</p> <pre><code>pip install ...
<python><tensorrt>
2023-10-16 16:16:24
2
449
CraZyCoDer
77,303,405
1,852,526
Pandas dataframe remove square brackets from list string when writing to xlsx
<p>The location data is a list of strings that I am getting. When I use Pandas to write to xlsx, it always puts square brackets around this 1 column.</p> <p>This is what I have been trying:</p> <pre><code>def create_excel_with_format(headers,values,full_file_name_with_path): #Write to CSV in xlsx format with ind...
<python><pandas><dataframe><xlsx>
2023-10-16 15:57:38
1
1,774
nikhil
77,303,336
17,530,552
Sorting a deeply nested dictionary from lowest to highest values
<p>I created an empty dictionary labeled <code>dict_dif = {}</code> into which I loaded data via a for loop. The resulting dictionary has the following nested structure:</p> <pre><code>dict_dif[var][roi][subject][numeric_value] </code></pre> <p>This means that for each var, roi, and subject, there is a specific numeric...
<python><dictionary><sorting>
2023-10-16 15:48:00
0
415
Philipp
77,303,323
2,112,406
Can I overload init from C++ side in pybind11?
<p>If in C++ a class had an overloaded constructor:</p> <pre><code>class MyClass { std::string name; public: MyClass(){}; MyClass(std::string name_){ name = name_;} }; </code></pre> <p>how do I expose this to python? Can I use <code>py::overload_cast</code> and <code>py::init</code> together?</p> <p>Current...
<python><c++><pybind11><constructor-overloading>
2023-10-16 15:45:11
1
3,203
sodiumnitrate
77,303,295
160,245
count_documents gives error: AttributeError: 'dict' object has no attribute '_txn_read_preference'
<p>I wrote a function to check if a row exists, then insert if it is not there, or update if it is there. So I'm trying to use <code>count_documents</code>. I'm using a field called <code>filetype</code> as my unique key.</p> <p>A sample document looks like this:</p> <pre class="lang-json prettyprint-override"><code>{ ...
<python><mongodb><pymongo>
2023-10-16 15:41:01
1
18,467
NealWalters
77,303,260
15,405,732
How can I import a local module using Databricks asset bundles?
<p>I want to do something pretty simple here: import a module from the local filesystem using databricks asset bundles. These are the relevant files:</p> <p><strong>databricks.yml</strong></p> <pre class="lang-yaml prettyprint-override"><code>bundle: name: my_bundle workspace: host: XXX targets: dev: mode: ...
<python><pyspark><databricks><azure-databricks><databricks-asset-bundle>
2023-10-16 15:36:00
4
6,101
Koedlt
77,303,204
4,288,043
differences between a Pandas dataframe and Geopandas dataframe
<p>I have used Pandas a lot but recently completed a project with Geopandas for the first time. There was a dataframe of POIs which had various data columns including a Latitude and a Longitude column and that was converted into a Geopandas dataframe which now included a 'projection' applied to the whole dataframe and ...
<python><pandas><dataframe><geopandas>
2023-10-16 15:26:40
1
7,511
cardamom
77,303,203
13,438,431
How to make Telegram deep-linking work for messages?
<p>I'm developing a bot, which creates games in Telegram.</p> <p>When a user issues a <code>/start_game</code> command, the bot replies to user's command with a message, which includes a link to the created game.</p> <p>Now when the same user issues the <code>/start_game</code> command again, the bot responds with some...
<python><telegram><telegram-bot><python-telegram-bot><telethon>
2023-10-16 15:26:33
1
2,104
winwin
77,303,136
3,251,425
Python UrlLib3 - Can't download file due to SSL Error even when ssl verification is disabled
<p>I am unable to download a file using this piece of code:</p> <pre class="lang-py prettyprint-override"><code>import requests response = requests.get('https://download.inep.gov.br/informacoes_estatisticas/indicadores_educacionais/taxa_transicao/tx_transicao_municipios_2019_2020.zip', stream=True, verify=False) with ...
<python><python-requests><openssl><urllib3><certifi>
2023-10-16 15:15:29
2
1,312
Jackson Mourão
77,302,958
10,430,394
Updating height_ratios of gridspec multiplot after initial creation
<p>I am trying to change the height ratios of my stacked triple plot after it has been created using the <code>.set_height_ratios()</code> method of a <code>GridSpec</code> object. The reason I need this is that I have a method in my class, which multiplies data by a certain factor to make it &quot;more visible&quot; i...
<python><matplotlib><plot>
2023-10-16 14:46:28
0
534
J.Doe
77,302,772
192,801
Cannot access task instance to get xcom
<p>I am new to using xcoms in Airflow.</p> <p>Here's what my code looks like:</p> <pre class="lang-py prettyprint-override"><code>with DAG(default_args=default_args, max_active_runs=1, dag_id=&quot;my_dag&quot;, catchup=False, start_date=start_date, render_template_as_native...
<python><airflow><google-cloud-composer><airflow-xcom>
2023-10-16 14:21:55
4
27,696
FrustratedWithFormsDesigner
77,302,592
458,742
Django settings.py can't import my local module
<p>My Django tree looks like this</p> <pre><code>git/src ├── myproject │   ├── settings.py │   ├── mysharedlib.py │   └── urls.py └── www ├── myotherlib.py ├── urls.py └── views.py </code></pre> <p>It works except that in <code>settings.py</code> I have</p> <pre><code>import mysharedlib </code></pre> <p>But...
<python><django><python-import>
2023-10-16 13:57:30
2
33,709
spraff
77,302,486
17,530,552
Sort values in a nested dictionary from min. to max
<p>I created a dictionary, named <code>dict_dif</code> and loaded nested data into the same. The nested structure of this dictionary has the following structure:</p> <ol> <li>Variables (four different variables)</li> <li>Regions (eleven different regions for each of the four variables)</li> <li>Data points (60 data poi...
<python><dictionary><sorting>
2023-10-16 13:41:47
1
415
Philipp
77,302,438
13,866,965
Python function for plotting distributions works with one DataFrame but not another - no output or error
<p>I have the following python function to make graphs.</p> <pre><code> def plot_distributions(dataframe, title=None): # Set the style of seaborn sns.set(style=&quot;whitegrid&quot;) # Plotting distributions for each column plt.figure(figsize=(15, 8)) # Loop through each column and plot distributi...
<python><pandas><matplotlib><debugging><seaborn>
2023-10-16 13:35:33
1
451
arrabattapp man
77,302,270
1,627,466
Alternative to applying slicing of dataframe in pandas
<p>I am trying to rank authors using an intersection of two metrics (where averaging wouldn't make sense) for each observation.</p> <p>So far the only way I have done it was to apply a slice of the dataframe and take the unique number of authors but it's really slow.</p> <p>I was wondering if there was a faster solutio...
<python><pandas><dataframe><apply>
2023-10-16 13:12:08
3
423
user1627466
77,302,216
3,057,377
Bokeh sticky crosshair
<p>In <a href="http://bokeh.org/" rel="nofollow noreferrer">Bokeh</a>, is there a tool similar to <a href="https://plotly.com/python/hover-text-and-formatting/#spike-lines" rel="nofollow noreferrer">spike lines in plotly</a> ? The crosshair tool is close to that but is it possible to make it stick to a plot?</p>
<python><bokeh>
2023-10-16 13:04:19
1
1,380
nico
77,302,128
15,893,581
pulp: Schedule equipment replacement, maximizing Total Cost (considering devaluation)
<p>Given <code>init_age=3</code> years, <code>init_cost=4</code> of equipment, and <code>new_eq_cost=18</code>, schedule replacement time, given data for <code>cost= np.array([31, 30, 28, 28, 27, 26, 26, 25, 24, 24, 23 ])</code> &amp; <code>depreciation= np.array([ 8, 9, 9, 10, 10, 10, 11, 12, 14, 16, 18])</code> yearl...
<python><optimization><pulp>
2023-10-16 12:52:09
1
645
JeeyCi
77,302,112
6,221,742
plpython3u anaconda environment
<p>I am trying to use an anaconda environment inside my plpython3u function in postgres 15. Here is what I tried so far:</p> <pre><code>DROP FUNCTION use_anaconda_env(); CREATE OR REPLACE FUNCTION use_anaconda_env() RETURNS text LANGUAGE plpython3u AS $$ import os # Set the PYTHONHOME environment variable to point to...
<python><anaconda><system-paths><postgres-plpython>
2023-10-16 12:50:37
0
339
AndCh
77,302,092
4,451,521
Hovering message with plotly
<p>I have a script that does a plot with plotly</p> <pre><code>import plotly.graph_objects as go import pandas as pd # Create a DataFrame with X, Y, and f values df= pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y': [10, 12, 5, 8, 6], 'x2': [1, 3, 4, 5, 7],'y2':[2,5,3,1,8],'f':[1,2,3,4,5]}) hover_text1 = df.apply(lambda row: ...
<python><plotly>
2023-10-16 12:48:25
2
10,576
KansaiRobot
77,302,055
4,551,325
Parsing xml response to pandas dataframe and dictionary
<p>My response is a well-shaped .xml file with the following structure:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;Response&gt; &lt;Record key=&quot;XXXXX&quot; req_sym=&quot;AAPL-US&quot;&gt; &lt;Fields&gt; &lt;Field id=&quot;7000&quot; name=&quot;HEADLINE&quot; val...
<python><xml><dataframe>
2023-10-16 12:42:13
3
1,755
data-monkey
77,301,932
3,550,786
Efficient way to drop rows based on custom function
<p>I am processing a Pandas dataframe and I want to filter out the rows that don't meet a specific condition. The dataframe has a <code>content</code> column that contains examples of Javascript code. The goal is to parse each snippet, remove its comments and only keep it if its length is above a certain threshold (e.g...
<python><pandas>
2023-10-16 12:23:31
1
1,455
GRoutar
77,301,900
3,449,093
Why passing exception as e doesn't work, while explicitely does?
<p>I'm catching an exception and I want to pass it further. I've tried this the 2 following ways:</p> <pre><code>except exceptions.MyException as e: raise exceptions.MyException(message=e.message) </code></pre> <p>and:</p> <pre><code>except exceptions.MyException as e: raise e(message=e.message) </code></pre> <p>fu...
<python>
2023-10-16 12:17:44
3
1,399
Malvinka
77,301,650
10,353,865
Element of Dataframe column and its type relations to original array element
<p>In the code below I start with a numpy string-array (typecode:'U') and then create a pandas df from it. Afterwards I look at the type of an individual element and it is just an ordinary ptyhon str - hence it seems to &quot;forget&quot; the numpy-datatype (which should be &lt;class 'numpy.str_'&gt;). However, if I do...
<python><pandas>
2023-10-16 11:40:03
1
702
P.Jo