QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
76,059,509
1,231,940
How to get an element index in a list column, if element is specified in a different column
<p>I have a dataframe, where one column <code>a</code> is a list, and another column <code>b</code> contains a value that's in <code>a</code>. I need to create the column <code>c</code> which contains index of the element in <code>b</code> in list <code>a</code></p> <pre><code>df = pl.DataFrame({'a': [[1, 2, 3], [4, 5,...
<python><dataframe><python-polars>
2023-04-19 23:26:27
3
437
Kaster
76,059,444
6,724,526
Python: Importing pandas into main and modules?
<p>I have a python script with a structure that looks like the following:</p> <pre><code>/ __init__.py main.py /modules fbm.py </code></pre> <p>I am attempting to split some functions out from main.py into fbm.py and then import fbm.py as a module using.</p> <pre><code>sys.path.extend([f'{item[0]}' for item ...
<python><python-3.x><pandas>
2023-04-19 23:07:57
1
1,258
anakaine
76,059,429
2,893,712
APScheduler Set misfire_grace_time globally
<p>I am trying to apply <code>misfire_grace_time</code> globally for all of my jobs. According to the <a href="https://apscheduler.readthedocs.io/en/3.x/userguide.html#missed-job-executions-and-coalescing" rel="nofollow noreferrer">Doc Page</a> it says:</p> <blockquote> <p>The scheduler will then check each missed exec...
<python><apscheduler>
2023-04-19 23:05:39
1
8,806
Bijan
76,059,423
1,546,990
Django REST framework: passing additional contextual data from view to serializer
<p>I have a Django REST framework view (<code>generics.GenericAPIView</code>). In it, I want to pass contextual data (the original request received by the view) to a serializer.</p> <p>As per <a href="https://stackoverflow.com/questions/52188500/serializer-including-extra-context-in-django-rest-framework-3-not-working"...
<python><django><django-rest-framework>
2023-04-19 23:03:55
1
2,069
GarlicBread
76,059,401
15,378,398
How to achieve desired well-log visualization in Power BI using Python visuals
<p>I'm using python visuals in Power BI for plotting 2 columns (DEPTH and GR) of a Well-Log <a href="https://github.com/santiagortiiz/Well-Logs-and-Petrophysics/blob/main/Data/15-9-19_SR_COMP.LAS" rel="nofollow noreferrer">dataset</a> in a &quot;vertical line chart&quot;.</p> <p>The target chart looks like this: <a hre...
<python><matplotlib><plot><powerbi><powerbi-python-visual>
2023-04-19 23:01:50
0
336
Santiago Ortiz Ceballos
76,059,371
6,440,589
"python: can't open file" error when running docker-compose up
<p>I wrote a simple Python script called <strong>myscript.py</strong>, calling a custom module in <strong>mycustommodules</strong>. Below is my folder structure:</p> <pre><code>-docker-compose.yml -Dockerfile -mycustommodules | -config.py -__init__.py -mysubfolder | -acquisition | -m...
<python><docker><docker-compose><import>
2023-04-19 22:53:04
0
4,770
Sheldon
76,059,187
497,934
How do I indicate that the .value of an enum is an unstable implementation detail?
<p>The official Enum HOWTO has <a href="https://docs.python.org/3.11/howto/enum.html#planet" rel="nofollow noreferrer">this example</a>:</p> <pre class="lang-py prettyprint-override"><code>class Planet(Enum): MERCURY = (3.303e+23, 2.4397e6) VENUS = (4.869e+24, 6.0518e6) EARTH = (5.976e+24, 6.37814e6) ...
<python><enums>
2023-04-19 22:14:33
2
26,053
Maxpm
76,059,134
6,539,635
fix_final works for x_f=[0,0,0,0,0,0] but for absolutely no other final state - 'Solution Not Found'
<p>'x_f' is defined in a separate file but here's the code for the GEKKO implementation:</p> <pre><code>m = GEKKO(remote = solverParams[&quot;remote&quot;]) m.time = timeSeq x = [m.Var(value = x_0[i], fixed_initial = True) for i in range(len(x_0))] u = [m.Var(value = u_0[i], fixed_initial = False) for i in range(len(u...
<python><optimization><gekko>
2023-04-19 22:03:35
1
349
Aaron John Sabu
76,059,118
7,091,646
conditionally append value to list of lists in pandas
<p>I'm trying to conditionally append a list of lists in pandas:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'A': [1, 2, 3]}) df['B'] = [[[1],[1],[1]]] * df.shape[0] df A B 0 1 [[1], [1], [1]] 1 2 [[1], [1], [1]] 2 3 [[1], [1], [1]] # attempting to append 1st li...
<python><pandas>
2023-04-19 22:00:51
4
1,399
Eric
76,059,076
2,079,306
Update image using flask and Ajax
<p>Running a webpage and when I click a button, I want an existing image to be replaced without reloading the page, after a servers function is finished creating the new image server side. I am getting a 400 error though, so something is wrong before I can even print the data in routes.py to see what it's passing, mean...
<javascript><python><html><ajax><flask>
2023-04-19 21:52:22
0
1,123
john stamos
76,059,063
2,386,605
How to compile ML model for AWS Inferentia with flexible input size?
<p>I have an ML model from Huggingface, which essentially looks as follows:</p> <pre><code>import torch from transformers import BloomTokenizerFast, BloomForCausalLM device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') device tokenizer = BloomTokenizerFast.from_pretrained(&quot;bigscience/bloom-560m&...
<python><amazon-web-services><tensorflow><pytorch><amazon-sagemaker>
2023-04-19 21:50:41
0
879
tobias
76,059,038
19,130,803
Postgres update query: only last letter from entire string get inserted
<p>I am working on python web app using docker. At startup I need to create and initialize the tables with some default value, for that I have created <code>queries.sql</code> script.</p> <pre><code># queries.sql CREATE TABLE IF NOT EXISTS person ( id serial primary key, address varchar(2000) ); IN...
<python><postgresql>
2023-04-19 21:46:02
0
962
winter
76,059,001
19,157,137
Viewing all the File Handling Methods and all the types of Errors in Python
<p>How would I be able to write a code that I can use to see all of the File Methods like <code>close(), detach(), readline(), readlines() ... </code> in python 3. I also want to have another code that shows all the possible <code>errors</code> like <code>ArithmeticError, AssertionError, MemoryError ...</code>. I am tr...
<python><python-3.x><file><methods><error-handling>
2023-04-19 21:39:32
1
363
Bosser445
76,058,975
7,160,815
Can we do the distance transform from one boundary to another?
<p>I have ring-like binary images with varying thicknesses. I want to calculate its thickness by calculating the distance between the inner and outer boundaries.</p> <p><a href="https://i.sstatic.net/7DRYq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7DRYq.png" alt="enter image description here" /></a...
<python><image-processing><euclidean-distance><thickness>
2023-04-19 21:34:55
0
344
Savindi
76,058,957
5,082,048
How can I share large numpy arrays between python processes, e.g. jupyter notebooks, without duplicating them in memory?
<p>I have large numpy arrays that I want to share with other python processes on the same machine without holding copies in memory. Specifically, my usecase is to share the array between jupyter notebooks on linux. How can I do this?</p>
<python><multiprocessing><shared-memory>
2023-04-19 21:31:03
1
3,950
Arco Bast
76,058,926
4,572,274
Azure ML experiment run failing with 'HttpLoggingPolicy' has no attribute 'DEFAULT_HEADERS_ALLOWLIST'
<p>This is related to the azure experiment run in the Microsoft Azure Machine Learning Studio. The experiment run fails with this stack trace:</p> <pre><code>Warning: Failed to setup Azure Machine Learning system code due to `type object 'HttpLoggingPolicy' has no attribute 'DEFAULT_HEADERS_ALLOWLIST'`. Your job will p...
<python><azure><azure-machine-learning-service><azuremlsdk>
2023-04-19 21:26:06
1
4,632
yardstick17
76,058,816
8,229,534
How to build docker image with Facebook prophet library
<p>I am trying to build a docker image with Prophet 1.0.1</p> <p>Here is my requirements.txt file</p> <pre><code>google-cloud-bigquery google-cloud-storage numpy==1.21.0 pandas==1.2.0 db-dtypes plotly==5.10.0 hampel==0.0.5 prophet==1.0.1 click joblib scikit-learn </code></pre> <p>and here is my docker file -</p> <pre><...
<python><docker><facebook-prophet>
2023-04-19 21:08:06
1
1,973
Regressor
76,058,782
17,041,240
Unable to automate the individual key actions after providing 'path' as user input
<p>Initially my code worked fine when the path/to/file was assigned to a variable directly and this variable was passed as an argument to a function. My working code:</p> <pre><code>def read_installation_package(filePath): ... ... dlg = app.window(class_name=&quot;#32770&quot;) dlg.Edit.type_keys(filePa...
<python><automation><pywinauto>
2023-04-19 21:01:28
1
349
Pramesh
76,058,513
5,036,928
Regex (Python): Matching Integers not Preceded by Character
<p>Based on some string of numbers:</p> <pre><code>(30123:424302) 123 #4324:#34123 </code></pre> <p>How can I obtain only the numbers that are NOT immediately preceded by &quot;#&quot;? I have found how to get those numbers preceded by &quot;#&quot; (<code>\#+\d+</code>) but I need the opposite. Can I group all <code>\...
<python><regex><regex-negation>
2023-04-19 20:19:53
2
1,195
Sterling Butters
76,058,487
11,331,843
regex code to find email address within HTML script webscraping
<p>I am trying to extract phone, address and email from couple of corporate websites through webscraping</p> <p>My code for that is as follows</p> <pre><code>l = 'https://www.zimmermanfinancialgroup.com/about' address_t = [] phone_num_t = [] # make a request to the link response = requests.get(l) soup = Beautiful...
<python><regex><web-scraping><beautifulsoup>
2023-04-19 20:15:36
1
631
anonymous13
76,058,384
9,940,188
Why doesn't this custom logger use the root formatter?
<p>The way I understand the logging documentation is that all calls to loggers that don't have handlers configured on them will eventually &quot;fall through&quot; to the root logger (and implicitly also use its formatter).</p> <p>In the example below, neither &quot;log&quot; nor &quot;mylog&quot; are the root logger. ...
<python>
2023-04-19 19:59:18
2
679
musbur
76,058,371
504,717
Pythonic way to map enum to api values
<p>I have a proto generated code which has 3 values (values i am interested in)</p> <pre class="lang-py prettyprint-override"><code>proto_type.VALUE1 proto_type.VALUE2 proto_type.VALUE3 </code></pre> <p>I have created an enum in my python project.</p> <pre class="lang-py prettyprint-override"><code>class MyEnum(Enum): ...
<python><python-3.x><enums><python-3.7>
2023-04-19 19:58:16
2
8,834
Em Ae
76,058,342
8,512,262
What does socket.setdefaulttimeout have to do with Windows services written in Python?
<p>I'm familiarizing myself with creating Windows services in Python, and all of the examples I've found here or elsewhere call <code>socket.setdefaulttimeout(60.0)</code> (or something similar). But none of these examples explain <em>why</em> this is being done...and I can't find any info regarding whether or not this...
<python><windows><sockets><service>
2023-04-19 19:53:49
1
7,190
JRiggles
76,058,279
12,144,502
The Travelling Salesman Problem Using Genetic Algorithm
<p>I was looking to learn about AI and found the traveling salesman problem very interesting. I also wanted to learn about genetic algorithms, so it was a fantastic combo. The task is to find the shortest distance traveling from <code>id 1</code> to each location from the list once and returning to the starting locatio...
<python><python-3.x><performance><genetic-algorithm><traveling-salesman>
2023-04-19 19:45:50
1
400
zellez11
76,058,225
4,025,583
Numpy's `meshgrid` is discontinuously slow
<p>Over repeated calls to <code>meshgrid</code> I realized it can become slow at some sample sizes for no seemingly apparent reason. For example, in this snippet:</p> <pre class="lang-py prettyprint-override"><code>from time import time import numpy as np np.random.seed(1729) maxn = 760 times = np.empty(maxn+1) times...
<python><numpy><performance>
2023-04-19 19:36:36
0
454
Mauricio
76,058,004
2,725,742
Efficiently Parsing XSD with xmlschema, without XML Available
<pre><code>import xmlschema data_schema = xmlschema.XMLSchema(&quot;myXSD.xsd&quot;) data = data_schema.to_dict(&quot;myXSD.xsd&quot;) </code></pre> <p>I am not sure what the normal use case for this is, but I only have a ton of XSD files to parse, so I ended up passing the XSD file into both of these calls to get a di...
<python><xsd>
2023-04-19 19:00:52
0
448
fm_user8
76,057,621
13,055,818
Any fancy way to unwind Enum classes in python?
<p>I am currently coding a package that contains several <code>Enum</code> classes and would like to use the symbolic names directly from the package name, not from the classes themselves, as OpenCV does. Is there anyway to define the classes but still accessing their symbolic names directly from the package or shall I...
<python><enums>
2023-04-19 18:08:09
4
519
Maxime Debarbat
76,057,616
6,529,926
Can't load properties from .ini into custom logger
<p>I have a class called <code>CustomLogger</code> that is a subclass of <code>BaseLogger</code>, which is a subclass of <code>logging.Logger</code>. <code>BaseLogger</code> loads properties from a <code>logger.ini</code> file. So, <code>CustomLogger</code> is just a facade for <code>BaseLogger</code>.</p> <p>Here is m...
<python><oop><debugging><inheritance><logging>
2023-04-19 18:07:34
1
729
heresthebuzz
76,057,604
6,546,694
Method not picking up default argument values and the local argument values persist between separate calls to the method
<p>What should the following code print?</p> <pre><code>class C: def b(self,d = {'k':0}): print(d) d['k'] += 1 def a(self): self.b() c1 = C() for i in range(3): c1.a() </code></pre> <p>I could have sworn it should be</p> <pre><code>{'k': 0} {'k': 0} {'k': 0} </code></pre> <p>since I ...
<python><python-3.x>
2023-04-19 18:05:46
0
5,871
figs_and_nuts
76,057,485
15,412,256
Pandas 2.0 pyarrow backend datetime operation
<p>I have the following pandas dataframe object using the pyarrow back end:</p> <pre class="lang-py prettyprint-override"><code>crsp_m.info(verbose = True) out: &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 4921811 entries, 0 to 4921810 Data columns (total 87 columns): # Column Dtype ...
<python><pandas><jupyter-notebook><pyarrow>
2023-04-19 17:50:46
1
649
Kevin Li
76,057,458
15,706,665
Reproduce color palette from an image containing that color palette (IVIS machine)
<p>I would like to know if that is possible to reproduce a color palette from an image.</p> <p>Here is an <a href="https://resources.perkinelmer.com/lab-solutions/resources/docs/tch_010887_01_subject_rois.pdf" rel="nofollow noreferrer">example</a>. Pages 1 and 3 show a rainbow palette in the figure legend.</p> <p>The s...
<python><r><colors><palette>
2023-04-19 17:47:16
2
485
William Wong
76,057,410
12,300,981
How to have approx_fprime return an array (multiple values) instead of scalar?
<p>I'm trying to figure out how I can get approx_fprime to return multiple values, instead of just a scalar.</p> <p>Let's say your doing error propagation through a system of equations:</p> <pre><code>from scipy.optimize import fsolve, approx_fprime def pipeline2(inp): sol1,sol1A,sol1B,sol1AB=inp def equations(...
<python><scipy>
2023-04-19 17:41:00
1
623
samman
76,057,350
63,898
Python 3.8 Flask log doesn't print to console, only to file
<p>I have this simple code running in Flask. I want to make it print to console and to file. Currently I can only print to file.</p> <p>The code:</p> <pre><code>import logging from flask import Flask, make_response from flask_cors import CORS from Handlers import Handlers app = Flask(__name__) # logging.basicConfig(...
<python><python-3.x><flask><logging><console>
2023-04-19 17:34:16
0
31,153
user63898
76,057,335
16,578,438
add character at character count in pyspark
<p>I'm looking for a way to insert special character at a specific character count in a string in <code>pyspark</code> :</p> <pre><code>&quot;M202876QC0581AADMM01&quot; to &quot;M-202876-QC0581-AA-DMM01&quot; (1-6-6-2-) insertion after 1char then after 6char then after 6char then after 2char </code></pre> <p>Tried som...
<python><dataframe><apache-spark><pyspark><apache-spark-sql>
2023-04-19 17:32:30
1
428
NNM
76,057,312
20,646,427
Why python interpreter not using venv
<p>I set up virtual env in my pycharm and i have interpreter of python in that venv and my console shows me that im using that but for some reason i still have packages of my main interpreter</p> <p>How can i solve that?</p> <p>This is my venv interpreter and im using it <a href="https://i.sstatic.net/nlQnJ.png" rel="n...
<python><windows><pycharm>
2023-04-19 17:29:51
1
524
Zesshi
76,057,301
13,762,083
Fit a shape enclosing data points
<p>I have some data points as shown in the image: <a href="https://i.sstatic.net/ErpML.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ErpML.png" alt="enter image description here" /></a></p> <p>I want to fit a curve that encloses all these data points, e.g. an ellipse or a circle. How do I do this?</p>
<python><matplotlib><curve-fitting>
2023-04-19 17:28:04
1
409
ranky123
76,057,261
21,346,793
Why does React to Flask call fail with CORS despite flask_cors being included
<p>I need to read data from flask into react. React:</p> <pre><code>const data = { name: 'John', email: 'john@example.com' }; axios.post('http://127.0.0.1:5000/api/data', data) .then(response =&gt; { console.log(response); }) .catch(error =&gt; { ...
<python><reactjs><flask>
2023-04-19 17:22:28
1
400
Ubuty_programmist_7
76,057,129
3,286,861
Use seaborn object interface to plot overlapping density plots, added inside a for loop, each having its own color/label shown in a legend
<p>Using seaborn python library, I am trying to make several density plots overlapping each other in the same figure and I want to color/label each of the lines. Using seaborn objects interface I am able to make the density plots within a for loop. But I cannot add color/label to each density plot.</p> <p>I understand ...
<python><seaborn><kdeplot><seaborn-objects>
2023-04-19 17:05:39
1
508
rkmalaiya
76,057,076
4,222,261
How to stream Agent's response in Langchain?
<p>I am using Langchain with Gradio interface in Python. I have made a conversational agent and am trying to stream its responses to the Gradio chatbot interface. I have had a look at the Langchain docs and could not find an example that implements streaming with Agents. Here are some parts of my code:</p> <pre><code>#...
<python><chatgpt-api><gradio><langchain>
2023-04-19 16:58:22
4
485
MRF
76,057,051
7,339,624
How to create a leptokurtic/platykurtic distribution in scipy having four moments?
<p>As <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html" rel="nofollow noreferrer">scipy documentation</a> says, we can easily calculate the first four moments of a normal distribution by this:</p> <pre><code>mean, var, skew, kurt = norm.stats(moments='mvsk') </code></pre> <p>But I can...
<python><scipy><statistics><normal-distribution>
2023-04-19 16:54:35
1
4,337
Peyman
76,057,034
2,961,927
Python Matplotlib produces larger and blurrier PDF than R
<p>Consider the following:</p> <ol> <li><p>Plot a histogram using R and save it in PDF:</p> <pre><code> set.seed(42) x = c(rnorm(1000, 1, 1), rnorm(1000, 8, 3)) pdf(&quot;Rplot.pdf&quot;, width = 10, height = 3.33) par(mar = c(4, 5, 0, 0), family = &quot;serif&quot;) hist(x, breaks = 100, border = NA, col = &quot;g...
<python><r><matplotlib><pdf><graphics>
2023-04-19 16:51:48
0
1,790
user2961927
76,057,033
181,783
Getting version of uninstalled Python module
<p>I have just joined a project that defined the version string in <code>src/__init__.py</code> like so</p> <pre><code>#src/__init__.py version = '0.0.7' </code></pre> <p>and the application in the same directory</p> <pre><code>#src/acme.py ... # get version here </code></pre> <p>I'd like to get the version string in t...
<python><python-3.x><version>
2023-04-19 16:51:17
0
5,905
Olumide
76,057,015
15,226,448
Python visualization in Power BI with slicers
<p>I am trying to create a Python visualization in Power BI from the data in my df and the plot pizza comparison code from mplsoccer: <a href="https://mplsoccer.readthedocs.io/en/latest/gallery/pizza_plots/plot_pizza_comparison.html" rel="nofollow noreferrer">https://mplsoccer.readthedocs.io/en/latest/gallery/pizza_plo...
<python><powerbi>
2023-04-19 16:48:39
1
353
nokvk
76,056,940
5,343,362
HTTP call working with python but not with Android okhhtp
<p>I am facing a strange issue with Android.</p> <p>I want to do a http call to <a href="https://api.moffi.io/api/orders/add" rel="nofollow noreferrer">https://api.moffi.io/api/orders/add</a>.</p> <p>I am using retrofit and defined this method:</p> <pre><code>@Headers(&quot;Content-Type: application/json&quot;) @POST(&...
<python><android><http><okhttp>
2023-04-19 16:39:49
0
301
Quentin M
76,056,936
1,422,096
MySQL "data" folder keeps growing, even after DROP TABLE
<p>I'm using MySQL (8.0.33-winx64, for Windows) with Python 3 and <code>mysql.connector</code> package.</p> <p>Initially my <code>mysql-8.0.33-winx64\data</code> folder was rather small: &lt; 100 MB.</p> <p>Then after a few tests of <code>CREATE TABLE...</code>, <code>INSERT...</code> and <code>DROP TABLE...</code>, I ...
<python><mysql><windows>
2023-04-19 16:39:24
2
47,388
Basj
76,056,867
12,319,746
CFFI Backend not found Azure functions
<p>Trying to deploy an azure python function from an Azure DevOps pipeline. The function gives the error</p> <blockquote> <p>ModuleNotFoundError: No module named _cffi_backend</p> </blockquote> <p>The interpreter is correct. This is my <code>requirements.txt</code></p> <pre><code>azure-functions requests==2.26.0 cffi==...
<python><azure-functions>
2023-04-19 16:30:50
1
2,247
Abhishek Rai
76,056,810
12,175,820
Making a class with empty name using type
<p>According to Python's documentation for the built-in function <a href="https://docs.python.org/3/library/functions.html#type" rel="nofollow noreferrer"><code>type</code></a>:</p> <blockquote> <p><code>class type(name, bases, dict, **kwds)</code></p> <p>[...]</p> <p>With three arguments, return a new type object. Thi...
<python>
2023-04-19 16:22:14
1
712
Gabriele Buondonno
76,056,789
16,243,418
Dict in Django TemplateView throws Server Error 500, Suggested to use ListView that helps for DetailView
<p>I'm attempting to utilise the dictionary <strong>prices</strong> to retrieve the stock prices from yahoo finance. And the Django database is where I get my stock tickers. In HTML, I am unable to utilise dict. Please review the code samples I've included below.</p> <p>If the datatype for the variable &quot;prices&quo...
<python><django><dictionary><django-views><django-templates>
2023-04-19 16:20:04
1
352
Akshay Saambram
76,056,447
10,311,377
BrokenPipeError inside gevent library when it is used with Celery. How to overcome the issue?
<p>We use <code>Celery</code> with <code>gevent</code> worker in our application. Workers are run as separated docker containers.</p> <p>How we run Celery: <code>celery -A app.worker worker --pool=gevent --loglevel=info --concurrency=50 -E -n woker-1 -Q some_q</code></p> <p>Once (sometimes more often) per day we get th...
<python><docker><rabbitmq><celery><gevent>
2023-04-19 15:43:12
0
3,906
Artiom Kozyrev
76,056,354
4,817,370
Python : access to a variable from an other module is only given as a reference
<p>I am working on writing the tests for a project that has a massive technical debt and am running into limitations of my understanding as to how python references variables</p> <p>Here is the very simplified example :</p> <pre><code>main.py src/ __init__.py foo.py variables.py tests/ __init__.py unit_test.p...
<python><reference><pytest>
2023-04-19 15:32:24
1
2,559
Matthieu Raynaud de Fitte
76,056,223
2,071,807
Type hint a SQLAlchemy 2 declarative model
<p>I create my SQLAlchemy models in <a href="https://docs.sqlalchemy.org/en/20/orm/quickstart.html" rel="nofollow noreferrer">the 2.0 way</a>:</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column class ...
<python><sqlalchemy>
2023-04-19 15:19:51
3
79,775
LondonRob
76,056,179
16,223,413
tuple false indexing function that takes into consideration old false indices
<p>Imagine a list of booleans, which are all True:</p> <pre><code>bools = [True] * 100 </code></pre> <p>I then have a tuple that correspond to the index of the bool that i want to set to False:</p> <pre><code>false_index = (0,2,4) for element in false_index: bools[element] = False </code></pre> <p>The next time i ...
<python>
2023-04-19 15:16:13
1
631
DHJ
76,056,098
1,028,270
How do I programmatically check if a secondary ip service range is in use by a GKE cluster?
<p>I pre-create secondary ranges for my GKE clusters to use.</p> <p>How do I programmatically check if a secondary range is currently in use by a cluster or is free?</p> <p>I use the python API.</p> <p>I can't even see how to list secondary ranges in a VPC. Looking at the docs the only thing I see remotely related to V...
<python><google-cloud-platform><google-kubernetes-engine><google-vpc>
2023-04-19 15:07:29
1
32,280
red888
76,056,089
7,087,604
Python code patterns: elegant way of trying different methods until one suceeds?
<p>I'm trying to extract informations from an HTML page, like its last modification date, in a context where there are more than one way of declaring it, and those ways use non-uniform data (meaning a simple loop over fetched data is not possible).</p> <p>The ugly task is as follow:</p> <pre class="lang-py prettyprint-...
<python><design-patterns>
2023-04-19 15:06:47
2
713
AurΓ©lien Pierre
76,055,967
9,314,961
How to resolve 'TypeError: waveshow() takes 1 positional argument but 2 were given' error?
<p>I tried the below code in pycharm. Then it gave the error, 'AttributeError: module 'librosa.display' has no attribute 'waveplot'. Did you mean: 'waveshow'?'. Then I used, 'waveshow', instead of the waveplot method. But now I am getting the error, '<strong>TypeError: waveshow() takes 1 positional argument but 2 were ...
<python><deep-learning><librosa>
2023-04-19 14:55:12
1
311
RMD
76,055,891
2,134,072
fastAPI background task takes up to 100 times longer to execute than calling function directly
<p>I have simple fastAPI endpoint deployed on Google Cloud Run. I wrote the <code>Workflow</code> class myself. When the <code>Workflow</code> instance is executed, some steps happen, e.g., the files are processed and the result are put in a vectorstore database.</p> <p>Usually, this takes a few seconds per file like <...
<python><performance><google-cloud-platform><fastapi>
2023-04-19 14:47:08
1
389
Clang
76,055,832
1,919,581
OpenSSL internal error, assertion failed: FATAL FIPS SELFTEST FAILURE
<p>I had an application written in Python3.9 packaged as executable file using PyInstaller in a CentOs7 docker image. Able to install the app successfully in linux machines where FIPS is disabled.</p> <p>If I try install it in FIPS enabled RHEL8.7 machine it gives the below error</p> <pre><code>fips.c(145): OpenSSL int...
<python><linux><openssl><fips>
2023-04-19 14:41:54
0
511
user1919581
76,055,828
3,487,001
Python Generic[T] - typehint inherited nested classes
<p>After a few rewrites due to cluttered code, I now have a setup that involves a set of BaseClasses and multiple inherited classes thereof such that</p> <pre class="lang-py prettyprint-override"><code>class Base: class Nested: ... class Nested2: ... ... class NestedN: ... class A(Base): class Nested(Base.Ne...
<python><generics><inheritance><python-typing>
2023-04-19 14:41:27
0
551
Schorsch
76,055,800
16,363,897
Change dataframe values based on other dataframes
<p>Let's say we have the following &quot;df1&quot; dataframe with cities as column names:</p> <pre><code> NY LA Rome London Milan date 2023-01-01 1 81 26 55 95 2023-01-02 92 42 96 98 7 2023-01-03 14 4 60 88 73 </code></pre> <...
<python><pandas><dataframe>
2023-04-19 14:39:11
1
842
younggotti
76,055,764
7,614,968
Running random forest for production
<p>I am trying to productionize a random forest model using AWS Lambda Layers. I have used sklearn random forest to create a model. Following are the dependencies:</p> <pre><code>joblib==1.1.0 numpy==1.23.1 pandas==1.4.2 python-dateutil==2.8.2 pytz==2022.1 scikit-learn==1.1.1 scipy==1.9.0 six==1.16.0 threadpoolctl==3.1...
<python><amazon-web-services><aws-lambda><random-forest><aws-lambda-layers>
2023-04-19 14:35:23
1
635
palash
76,055,688
12,967,353
Generate aligned requirements.txt and dev-requirements.txt with pip-compile
<p>I have a Python project that depends on two packages <code>moduleA</code> and <code>moduleB</code>. I have the following <code>pyproject.toml</code>:</p> <pre><code>[project] name = &quot;meta-motor&quot; version = &quot;3.1.0.dev&quot; dependencies = [ &quot;moduleA==1.0.0&quot; ] [project.optional-dependencie...
<python><requirements.txt><pyproject.toml><pip-tools><pip-compile>
2023-04-19 14:26:28
1
809
Kins
76,055,331
7,987,455
How to scrape data that appear when click on button?
<p>I am trying to scrape phone numbers from website, but the numbers will appear only if I click on the first number. In other words, the phone will be hidden in the HTML code, and when I click it will appear. can you help please? I used the following code:</p> <pre><code>import requests from bs4 import BeautifulSoup ...
<python><web-scraping><beautifulsoup><python-requests>
2023-04-19 13:50:00
1
315
Ahmad Abdelbaset
76,055,244
194,305
swig python derived and base in different modules
<p>I am trying to reproduce a python example from the swig 4.0 documentation <a href="https://www.swig.org/Doc4.0/Modules.html#Modules_nn1" rel="nofollow noreferrer">Modules Basics</a>. I got properly generated _base_module.so and _derived_module.so . However when I try to use derived module from my test program</p> <p...
<python><inheritance><swig>
2023-04-19 13:40:24
1
891
uuu777
76,055,206
3,323,526
CJK full-width characters as Python names: how does Python deal with it and is it common in other programming languages?
<p>Not only ASCII, but also other Unicode characters can be used as names in Python. For example:</p> <pre><code>my_variable = 'var 1' # Normal ASCII characters as name ζˆ‘ηš„ε˜ι‡ = 'var 2' # Chinese characters as name print(my_variable) print(ζˆ‘ηš„ε˜ι‡) </code></pre> <p>The code above generates output normally:</p> <pre><code>...
<python><unicode><cjk>
2023-04-19 13:35:53
0
3,990
Vespene Gas
76,055,198
10,906,063
Using Request mixed Forms and Files with Annotation and optional fields
<p>I'd like to post mixed form fields and upload files to a FastAPI endpoint. The FastAPI documentation <a href="https://fastapi.tiangolo.com/tutorial/request-forms-and-files/#__tabbed_2_2" rel="nofollow noreferrer">here</a> states that you can mix params using <code>Annotated</code> and the <code>python-multipart</cod...
<python><fastapi><python-typing>
2023-04-19 13:34:57
2
579
Chris
76,055,072
20,220,485
How do you sort a dataframe with the integer in a column with strings and integers on every row?
<p>How would you sort the following dataframe:</p> <pre><code>df = pd.DataFrame({'a':['abc_1.2.6','abc_1.2.60','abc_1.2.7','abc_1.2.9','abc_1.3.0','abc_1.3.10','abc_1.3.100','abc_1.3.11'], 'b':[1,2,3,4,5,6,7,8]}) &gt;&gt;&gt; a b 0 abc_1.2.6 1 1 abc_1.2.60 2 2 abc_1.2.7 3 3 abc_1.2.9 4 4 ...
<python><pandas><string><sorting><integer>
2023-04-19 13:24:27
3
344
doine
76,055,001
386,861
Using pandas to read HTML
<p>This should be easy but I've got errors that I can't work out. I've got some air pollution stats for the UK that I want to parse.</p> <p><a href="https://uk-air.defra.gov.uk/data/DAQI-regional-data?regionIds%5B%5D=999&amp;aggRegionId%5B%5D=999&amp;datePreset=6&amp;startDay=01&amp;startMonth=01&amp;startYear=2022&amp...
<python><pandas>
2023-04-19 13:18:01
3
7,882
elksie5000
76,054,972
8,618,380
Groupby and get value in N-days in Pandas
<p>I have the following dataframe, representing daily stock values:</p> <pre><code>print(df) date ticker price 19/04/22 AAPL 10 19/04/22 TSLA 15 20/04/22 TSLA 15 20/04/22 AAPL 10 (...) </code></pre> <p>For each date and ticker, I would like to retrieve the (future) <...
<python><pandas>
2023-04-19 13:15:03
1
1,975
Alessandro Ceccarelli
76,054,903
5,834,316
Is there a way to add columns to the data outputted to a headless Locust session?
<p>I would like to add a column with a custom metric to the headless output of Locust. Is this possible? I am struggling to see anything in the documentation that points to modifying the output.</p> <p>Just to be specific, I want to modify this output:</p> <pre><code>Type Name ...
<python><output><load-testing><locust>
2023-04-19 13:08:08
1
1,177
David Ross
76,054,890
2,708,714
A python script does not work from command line in contrast to running it from ipython
<p>The following code reports an error when executed from the command line, whereas it executes fine from ipython (line by line). The script uses a locally-stored HuggingFace model, reads a scientific paper from a pdf file and answers questions about the paper.</p> <pre><code>import os os.environ[&quot;HUGGINGFACEHUB_A...
<python><ipython><langchain>
2023-04-19 13:06:57
0
2,630
Igor Popov
76,054,847
1,432,980
exclude class names from breadcrumbs and leave only package names
<p>I am trying to imitate the behaviour that is shown in this documentation</p> <p><a href="https://faker.readthedocs.io/en/master/providers/baseprovider.html" rel="nofollow noreferrer">https://faker.readthedocs.io/en/master/providers/baseprovider.html</a></p> <p>I have installed ReadTheDocs theme for Sphinx and also u...
<python><python-sphinx><faker><autodoc>
2023-04-19 13:00:57
1
13,485
lapots
76,054,718
12,040,751
Type hint for class with __dict__ method
<p>I have a class that can be instantiated from a dataclass.</p> <pre><code>class Asd: @classmethod def from_dataclass(cls, dataclass): return cls(**dataclass.__dict__) def __init__(self, **kwargs): ... </code></pre> <p>In principle I could pass to <code>from_dataclass</code> any class with ...
<python><type-hinting>
2023-04-19 12:48:17
1
1,569
edd313
76,054,671
1,630,244
Is it Pythonic to import an external symbol imported into another module?
<p>Please guide me on the pythonic way for a minor code-standards question. Searching SO re imports gets me many discussions comparing <code>import foo</code> vs <code>from foo import bar</code> which is not my concern here. Still I apologize if I am creating a dupe Q.</p> <p>My team sometimes puts up code for review w...
<python><code-standards>
2023-04-19 12:43:44
0
4,482
chrisinmtown
76,054,571
7,056,765
How can I visualize the epsilon-delta criterion in Python?
<p>I'm a math student and I'm trying to understand the epsilon-delta criterion for limits. I know that the criterion says that for every epsilon &gt; 0, there exists a delta &gt; 0 such that if 0 &lt; |x - c| &lt; delta, then |f(x) - L| &lt; epsilon, where L is the limit of f(x) as x approaches c.</p> <p>I want to visu...
<python><function><math><visualization><limit>
2023-04-19 12:33:14
1
1,065
Createdd
76,054,552
15,095,104
Selecting a database to use per specific APIView in the Django application
<p>Recently I added a second database to my Django application. I have prepared API a long time ago with the use of djangorestframework and now I would like to be able to choose which view should use which database.</p> <p>I tried using <a href="https://docs.djangoproject.com/en/4.2/topics/db/multi-db/#database-routers...
<python><django><django-rest-framework>
2023-04-19 12:31:11
0
954
TymoteuszLao
76,054,532
1,021,888
Update Time Series date range in Colab
<p>As you can see in the last cell when you change the date slider and click on Update everything works but I duplicate the Figure everytime underneath the panel. I am new to Python and Colab so I am stuck I need some help thanks :) <a href="https://colab.research.google.com/drive/11SWIbkbOVonXWtEQnA6C_ns1Ij0RZh43?usp=...
<python><google-colaboratory><panel>
2023-04-19 12:28:43
1
1,781
Brett
76,054,444
16,733,101
Is there an option in Pycaret to stop looking for best model if the current models achieve a desired performance
<p>I have a data frame with 860k rows, and I am using GPU but still very slow. I decided to stop the training, and I am satisfied with the performance of the last model.</p> <p>Is there an option in Pycaret to stop looking for the best model if the current models achieve the desired performance?</p>
<python><classification><pycaret>
2023-04-19 12:21:09
1
9,984
Hamzah Al-Qadasi
76,054,373
6,477,678
Multiple p-values calculator for Multiple Chi-Squared Values
<p>This is not a theory question, just one of efficiency. Let's say I have a list (long list) of chi-squared random variables and I want to calculate a p-value for each. For ease let's say they all have the same degrees of freedom. Something like:</p> <pre><code>Chi Square [44,2.3, 33.4,........] -&gt; p_value [.11,.95...
<python><numpy><statistics><p-value>
2023-04-19 12:13:54
1
687
Canuck
76,054,304
6,583,606
How does `KSComp` behave when using the options `lower_flag`, `ref`, `ref0` and `units` and `upper` at the same time?
<p>Reading the <a href="https://openmdao.org/newdocs/versions/latest/features/core_features/adding_desvars_cons_objs/adding_constraint.html" rel="nofollow noreferrer">Adding Constraints</a> page, I have understood that the scaling of the a constraint value happens in the following order:</p> <ul> <li>the constraint val...
<python><constraints><openmdao>
2023-04-19 12:06:16
1
319
fma
76,054,207
276,052
Exploding a large json-file using ijson
<p>I have a large json-file (too large to fit in memory) with the following structure:</p> <pre><code>{ &quot;commonVal&quot;: &quot;foo&quot;, &quot;entries&quot;: [ { &quot;bar&quot;: &quot;baz1&quot; }, { &quot;bar&quot;: &quot;baz2&quot; }, ..., ] } </code></pre> <p>I would like ...
<python><json><ijson>
2023-04-19 11:55:03
1
422,550
aioobe
76,054,162
6,758,862
How to use TypeVar with dictionaries
<p>Following is a minimal example of a class dictionary defined with keys tuples of classes, and values callables accepting instances of those classes:</p> <pre class="lang-py prettyprint-override"><code>from typing import Callable, Dict, Tuple, TypeVar from typing import Type T = TypeVar(&quot;T&quot;) A: Dict[ ...
<python><mypy><python-typing>
2023-04-19 11:49:27
0
723
Vasilis Lemonidis
76,054,004
1,389,394
set edges colour based on node colour in networkx graph
<p>For a directed networkx graph the data is read from a csv file; The nodes' colours are set by degree of nodes. I want to set each edge line colour to take the node's colour. There has to be an efficient way to access the indices of nodes and respective edges of each node.</p> <p>Any ideas to achieve this?</p> <p>cur...
<python><import><colors><networkx><edges>
2023-04-19 11:32:56
0
14,411
bonCodigo
76,053,926
5,574,107
Python more efficient method than .apply()
<p>I have a large dataframe with projected data 60 months into the future, and I need to drop the projections for months that haven't happened yet. I have a functioning way to do this but it's throwing memory errors for a 16 million row dataframe (I have removed all unnecessary columns):</p> <pre><code>from dateutil.re...
<python><pandas><apply>
2023-04-19 11:25:40
1
453
user13948
76,053,688
1,096,660
How about `__name__ != "__main__"` in Python?
<p>I'm writing a Python script that is supposed to be imported. It has some plumbing to do and uses a function from itself. If I put this at the top of the script I have to put the function definition first and it gets ugly.</p> <p>Is <code>__name__ != &quot;__main__&quot;</code> a proper solution to execute code on im...
<python><python-import><python-importlib>
2023-04-19 10:57:45
1
2,629
JasonTS
76,053,620
3,490,424
How to stop the learning process with PPO in stablelines?
<p>So, I created a custom environment based on gymnasium and I want to train it with PPO from <code>stable_baselines3</code>. I'm using version 2.0.0a5 of the latter, in order to use gymnasium. I have the following code:</p> <pre class="lang-py prettyprint-override"><code>env = MyEnv() model = PPO(&quot;MlpPolicy&quot;...
<python><openai-gym><stable-baselines>
2023-04-19 10:47:52
1
1,288
Benares
76,053,605
8,219,760
Subclassing `Process` to set process level constant
<p>I am trying to subclass <code>mp.Process</code> to create process level constant to decide between GPUs on my desktop. To achieve this, I'd like to have a device id inside each process object and later pass it to a function in <code>run</code> method. The example code here does not actually yet use <code>self._gpu_i...
<python><multiprocessing>
2023-04-19 10:45:36
2
673
vahvero
76,053,482
11,963,167
pd.Timestamp is assimilated to dtype('O')?
<p>I developed a simple function which returns an empty dataframe with correct column names and dtypes from a dictionary:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def return_empty_dataframe(schema: dict[str, np.dtype]): return pd.DataFrame(columns=schema.keys()).astype(schema) </cod...
<python><pandas><numpy><timestamp>
2023-04-19 10:33:36
1
496
Clej
76,053,434
2,954,256
Python mutiprocessing within the same AWS Glue 4.0 job hangs
<p>I am trying to use Python Multiprocessing to process data in parallel within the same AWS Glue 4.0 job. I know that I could use Glue Workflows with multiple jobs to achieve parallel data processing, but for reasons that are irrelevant here, it is something that I don't want to do.</p> <p>This is my Python code:</p> ...
<python><multiprocessing><aws-glue>
2023-04-19 10:28:40
1
412
Roberto A.
76,053,313
13,078,279
Avoiding ZeroDivisionError for Runge-Kutta 4(5) solver
<p>I am trying to create a Runge-Kutta 4(5) solver to solve the differential equation <code>y' = 2t</code> with the initial condition <code>y(0) = 0.5</code>. This is what I have so far:</p> <pre class="lang-py prettyprint-override"><code>def rk45(f, u0, t0, tf=100000, epsilon=0.00001, debug=False): h = 0.002 u...
<python><differential-equations><runge-kutta>
2023-04-19 10:15:22
2
416
JS4137
76,053,220
5,930,047
How to check GET-query-parameters with requests-mock?
<p>I have a function which makes a GET-request with a dict of params. In my unit-tests I want to make sure that the parameters are set correctly. However when I try to use <code>requests-mock</code> to mock the request, I can only check for the URL without the parameters. It seems like the params are not picked up by r...
<python><unit-testing><python-requests><requests-mock>
2023-04-19 10:04:10
1
367
Philip Koch
76,053,201
5,539,674
Building a new pd.dataframe with statistics from own functions
<p>I am trying to creat some summary statistics for text data that I am working with, namely the average length of text columns in my dataFrame.</p> <p>I am working with two columns: <code>short</code> and <code>long</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = { 'short': [...
<python><pandas><dataframe>
2023-04-19 10:01:55
2
315
O RenΓ©
76,053,164
572,575
How to delete oldest data in table if more than 5 row using django?
<p>If data in table more than 5 row I want to delete oldest row such as.</p> <pre><code>id value 1 a1 &lt;= delete 2 a2 3 a3 4 a4 5 a5 6 a6 </code></pre> <p>I want to keep new 5 rows which is id 2-6 and delete oldest row which is id 1. I use this code.</p> <pre><code> objects_to_keep = Data.obje...
<python><django>
2023-04-19 09:58:14
2
1,049
user572575
76,053,085
4,751,700
How to use csv.reader in an async context?
<p>I query multiple services with asynchronously using <code>httpx</code>. These services return csv data that could be very large so I'm using <a href="https://www.python-httpx.org/async/#streaming-responses" rel="nofollow noreferrer">streams</a>.</p> <p>So far so good.</p> <p>The problem I'm having is that the Python...
<python><csv><python-asyncio><httpx>
2023-04-19 09:49:39
0
391
fanta fles
76,053,007
13,868,186
Use of widget.pack() does not recover forgotten pack widget in Tkinter
<pre><code>import tkinter top = tkinter.Tk() top.geometry(&quot;800x800&quot;) top.title(&quot;Text Editor&quot;) edit = False name = tkinter.Entry(top) def editTrue(): edit = True name.pack_forget() def editFalse(): edit = False name.pack() menubar = tkinter.Menu(top) filemenu = tkinter.Menu(menu...
<python><python-3.x><tkinter><python-3.8><tkinter-entry>
2023-04-19 09:41:41
2
926
Daniel Tam
76,052,993
3,259,222
How to split DataFrame/Array given a set of masks and perform calculations for each split
<p>You have 2 DataFrames/Arrays:</p> <ul> <li><code>mat</code>: size (N,T), type bool or float, nullable</li> <li><code>masks</code>: size (N,T), type bool, non-nullable <ul> <li>can be split to T masks, each of size N</li> </ul> </li> </ul> <p>The goal is to split <code>mat</code> to T slices by applying each mask, pe...
<python><arrays><pandas><dataframe><numpy>
2023-04-19 09:39:53
1
431
Konstantin
76,052,775
6,632,138
Customize "return by value" in IntEnum
<p>I have a class that extends <code>IntEnum</code> class that defines positions in a bit-encoded variable:</p> <pre><code>from enum import IntEnum class Bits(IntEnum): @classmethod def data(cls, value: int): return [ e for e in cls if (1 &lt;&lt; e) &amp; value ] class Status(Bits): READY = 0 ...
<python><enums><integer><overriding>
2023-04-19 09:17:59
2
577
Marko Gulin
76,052,758
246,754
How to only show related objects in Django Admin screens
<p>I have an app where I want administrators to be able to create events via the admin view. I have members, who will have multiple cars and attend multiple meets. I want to record which vehicle they used at a meet.</p> <p>In the django admin view for a member, I can manage their cars successfully and only cars belongi...
<python><django><django-admin>
2023-04-19 09:15:59
1
526
Anonymouslemming
76,052,704
3,935,797
brokenaxes AttributeError: 'SubplotSpec' object has no attribute 'is_last_row'
<p>I am trying to use the python brokenaxes to break both x and y axis. I run the code suggested here <a href="https://www.codespeedy.com/create-a-plot-with-broken-axis-in-python-using-matplotlib/" rel="nofollow noreferrer">https://www.codespeedy.com/create-a-plot-with-broken-axis-in-python-using-matplotlib/</a></p> <p...
<python><matplotlib><axis>
2023-04-19 09:09:36
1
1,028
RM-
76,052,646
1,096,660
How to implement logging in reusable packages?
<p>I'm more and more offloading frequently used tasks in small little libraries of mine. However I haven't figured out what the best practice for logging is. There are lots of resources explaining something like:</p> <pre><code>import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s ...
<python><python-logging>
2023-04-19 09:03:46
1
2,629
JasonTS
76,052,527
13,438,859
Can't retreive environment variable in python
<h3>Problem</h3> <p>After I do</p> <pre><code>export key=value </code></pre> <p>or</p> <pre><code>echo &quot;export key=value&quot; &gt;&gt; ~/.zshrc &amp;&amp; source ~/.zshrc </code></pre> <p>I can retrieve it in terminal using <code>echo $key</code></p> <p>But when I'm try to retrieve <code>key</code> in Python usin...
<python><environment-variables>
2023-04-19 08:52:27
0
325
Ian Hsiao