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,022,019
17,724,172
Why am I getting error all arrays must be of the same length?
<p>I was hoping that this would print a six-bar broken bar chart with 5 colored categories from GUI entries, but I get an error:</p> <pre><code>Traceback (most recent call last): File &quot;/usr/lib/python3.10/idlelib/run.py&quot;, line 578, in runcode exec(code, self.locals) File &quot;/home/jerry/Python_Code/...
<python><pandas><matplotlib><tkinter>
2023-04-15 11:38:31
0
418
gerald
76,021,918
2,850,115
Python linter with variables in conditional code block
<p>Consider the following code:</p> <pre><code>testvar: bool = True if testvar: foo: str = '' # Statements that do not affect value of testvar if testvar: bar: str = foo </code></pre> <p>Any linter I've tried will complain that <code>foo</code> is possibly unbound, although it obviously must be bound. Is this...
<python><static-analysis>
2023-04-15 11:18:45
1
1,914
Nikša Baldun
76,021,914
3,324,491
how to commit a pandas dataframe to JSON/utf-8 back to gitlab so it's read as a CSV
<p>I can successfully read in a CSV like this using pandas and python-gitlab:</p> <pre><code> filename = &quot;file.csv&quot; f = project.files.get(file_path=filename, ref='master') data = pd.read_csv(StringIO(str(f.decode(),'utf-8')), sep=',', header=None, names=[&quot;direction&quot;, &quot;width&quot;, &q...
<python><json><dataframe><csv><gitlab>
2023-04-15 11:17:22
1
559
user3324491
76,021,857
9,251,158
403 error when scraping a URL that works on Firefox without cookies nor javascript
<p>I have a URL that works on Firefox set to block all cookies and with JavaScript turned off, and yet when I scrape it on Python with <code>urllib</code>, I get <code>HTTP Error 403: Forbidden</code>. I use the same user-agent as Firefox, and here is my code:</p> <pre class="lang-py prettyprint-override"><code>import ...
<javascript><python><web-scraping><cookies><user-agent>
2023-04-15 11:04:02
2
4,642
ginjaemocoes
76,021,692
268,127
How to ensure that Python type checking tools correctly recognize "type-conversion decorators"?
<p>Basically I am looking for a way to implement a Python decorator, which tries to automatically convert &quot;suitable&quot; argument to another type (from &quot;str&quot; to &quot;Palindrome&quot; in the example below). From the outside the function should look like it can be called with a &quot;suitable&quot; type,...
<python><type-conversion><python-decorators><python-typing>
2023-04-15 10:33:19
0
4,584
raisyn
76,021,421
1,754,221
Python Protocol for De-/Serialization with Shared Generic Types
<p>I am writing a protocol that requires conforming classes to provide serializing/deserializing methods <code>to_config</code> and <code>from_config</code>.</p> <p>This is my current approach. CV is the group of allowed types in the config. The idea is to keep the serialization generic but enforce that whatever type i...
<python><serialization><deserialization><protocols><python-typing>
2023-04-15 09:32:17
1
1,767
Leo
76,021,017
13,345,744
How to Normalise Column of Pandas DataFrame as Part of Preprocessing for Machine Learning?
<p><strong>Context</strong></p> <p>I am currently preprocessing my dataset for <code>Machine Learning</code> purposes. Now, I would like to <code>normalise</code> all numeric columns. I found a few solutions but none of them really mimics the behaviour I prefer.</p> <p>My goal is to have normalised a column in the foll...
<python><pandas>
2023-04-15 07:58:38
1
1,721
christophriepe
76,020,838
860,202
Find all possible sums of the combinations of sets of integers, efficiently
<p>I have an algorithm that finds the set of all unique sums of the combinations of k tuples drawn with replacement from of a list of tuples. Each tuple contains n positive integers, the order of these integers matters, and the sum of the tuples is defined as element-wise addition. e.g. (1, 2, 3) + (4, 5, 6) = (5, 7, 9...
<python><performance><math><optimization><combinations>
2023-04-15 07:08:41
1
684
jonas87
76,020,762
245,543
Pyparsing: how to match parentheses around comma_separated_list
<p>I cannot figure out how to combine expressions with the <a href="https://pyparsing-docs.readthedocs.io/en/latest/pyparsing.html#pyparsing.pyparsing_common.comma_separated_list" rel="nofollow noreferrer">comma_separated_list</a> in order to match a list in parentheses. The following does not work, because the csv exp...
<python><pyparsing>
2023-04-15 06:45:24
2
1,462
Ondrej Sotolar
76,020,709
15,326,565
Detecting paragraphs in a PDF
<p>How can I detect different &quot;blocks&quot; of text extracted from a PDF to split them into paragraphs? Could I try to use to use their position to do this?</p> <p>PyMuPDF only puts one newline character between the blocks, and also one newline after one of the lines, making it not possible to distinguish between ...
<python><pdf><pymupdf>
2023-04-15 06:29:20
0
857
Anm
76,020,620
713,200
How to get length of list from a json reponse from API request in python?
<p>I'm trying to get json response from API get method and get a length of a list names <code>items</code> in the response.</p> <p>This the API json reponse</p> <pre><code>{ &quot;identifier&quot;: &quot;id&quot;, &quot;items&quot;: [ { &quot;deployPending&quot;: &quot;NONE&quot;, ...
<python><json><python-3.x><list><dictionary>
2023-04-15 05:59:08
1
950
mac
76,020,588
992,644
Left align tkinter widgets using place
<p>I'm having some trouble understanding tkinter place coordinates.</p> <p>As demonstrated by the brilliant visual answer i found <a href="https://stackoverflow.com/a/64545215/992644">here</a>, anchors determine the corner/edge of the object that the coordinates apply to.</p> <p>Given this fact, then why are my check b...
<python><tkinter>
2023-04-15 05:49:41
1
695
hamsolo474 - Reinstate Monica
76,020,560
678,572
How to scrape fields on eBay using beautifulSoup4 in Python?
<p>I'm watching this <a href="https://www.youtube.com/watch?v=csj1RoLTMIA" rel="nofollow noreferrer">video</a> (which is dated) and adapting this <a href="https://github.com/jhnwr/ebay-prices" rel="nofollow noreferrer">code</a> (which is broken). Learning a lot about web scraping from this and I've been able to adapt ...
<python><web-scraping><beautifulsoup>
2023-04-15 05:41:41
1
30,977
O.rka
76,020,491
8,968,801
Django REST Framework - Weird Parameter Shape due to JSON Parser?
<p>Currently I'm contacting my APIViews through AJAX requests on my frontend.</p> <pre class="lang-js prettyprint-override"><code>config = { param1: 1, param2: 2, param3: 3 } $.ajax(APIEndpoints.renderConfig.url, { type: APIEndpoints.renderConfig.method, headers: { &quot;X-CSRFToken&quot;: csrfToke...
<python><json><django><parsing><django-rest-framework>
2023-04-15 05:21:47
1
823
Eddysanoli
76,020,167
11,462,274
How to access the Date & time in the Settings on Windows using pywinauto?
<pre><code>English: Settings &gt; Time &amp; language &gt; Date &amp; Time &gt; Set time automatically Portuguese: Configurações &gt; Hora e idioma &gt; Data e hora &gt; Definir horário automaticamente </code></pre> <p>My computer is not synchronizing the time when it restarts, so I want to automate this synchronizati...
<python><pywinauto><windows-11>
2023-04-15 03:10:51
0
2,222
Digital Farmer
76,020,123
13,981,285
Error parsing font string in matplotlib stylesheet
<p>I want to use a custom font in my matplotlib plots. I would like to use path of the .ttf file in the stylesheet, for example:</p> <pre><code>mathtext.it: &quot;/path/to/fontname-Italic-VariableFont_wght.ttf&quot; </code></pre> <p>But when using this stylesheet the python script gives the following warning:</p> <bloc...
<python><matplotlib><plot><visualization>
2023-04-15 02:52:56
1
402
darthV
76,019,929
913,098
pytorch transformer with different dimension of encoder output and decoder memory
<p>The <a href="https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html" rel="nofollow noreferrer">Pytorch Transformer</a> takes in a <code>d_model</code> argument</p> <p>They say <a href="https://discuss.pytorch.org/t/using-different-feature-size-between-source-and-target-nn-transformer/139525/2?u=noam_sal...
<python><machine-learning><deep-learning><pytorch><transformer-model>
2023-04-15 01:20:16
0
28,697
Gulzar
76,019,862
5,788,582
Iteratively replace every cell in a dataframe using values from the original dataframe
<p>Here's a sample dataframe:<br /> <a href="https://i.sstatic.net/u8luX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/u8luX.png" alt="example dataframe to update" /></a></p> <p>I need to be able to get &quot;2023-01-01&quot; <em>edit: (a string of random numbers, not a true Date object)</em> and &quot...
<python><pandas>
2023-04-15 00:51:21
3
1,905
Jay Jung
76,019,757
7,254,514
Unable to add rows to an inherited table with SQLAlchemy v1.4. I get a "NULL result in a non-nullable column" error
<p>For the sake of this example I have four tables:</p> <ol> <li>ModelType</li> <li>ModelTypeA</li> <li>ModelTypeB</li> <li>Model</li> </ol> <p>I am trying to model the following relationship among these tables: <a href="https://i.sstatic.net/yIgeJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yIgeJ.pn...
<python><sqlalchemy>
2023-04-15 00:21:18
1
1,178
Luca Guarro
76,019,731
10,853,071
Filtering + Grouping a DF on same sentence
<p>I am facing a really weird behavior when using Pandas.loc and pandas.groupy on a same sentence on a big data frame. I´ve noticed this behavior after updating from pandas 1.5x to 2.0x</p> <p>To illustrate.</p> <p>This is the small dataframe. This DF has 3 mm rows <a href="https://i.sstatic.net/WSajk.png" rel="nofollo...
<python><pandas>
2023-04-15 00:09:27
1
457
FábioRB
76,019,650
2,687,317
Aggregating based on a range of indexes or columns- Pandas
<p>I have a very large df:</p> <pre><code>CallType Broadcast C1 C2 Csk Data Netd2 Net3 OpenP1 OpenP2 OpenP8 SBD Voice LFrame 0 85.811985 0.820731 0.479020 0.550982 23.95 0.0 4.79 32.338503 23.573862 8.462412 6.696933 3.781450 22...
<python><pandas>
2023-04-14 23:44:56
1
533
earnric
76,019,591
1,293,193
Clearing unique cache using Faker within factory boy
<p>I am using Faker from inside factory boy and we are getting duplicate values that are making our tests fail. Faker has the ability to generate unique values, but it has a finite number of values for a given provider like first_name. We have 100s of tests and after a while all the unique values have been used and we ...
<python><pytest><faker><factory-boy>
2023-04-14 23:24:39
1
3,786
Larry Martell
76,019,290
4,783,029
How to import Python methods of existing classes selectively?
<p>Consider the following example that imports additional Pandas methods from the <code>pyjanitor</code> package.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import janitor df = pd.DataFrame({ 'Column One': [1, 2, 3], 'Column-Two': [4, 5, 6], 'Column@Three': [7, 8, 9], }) df_cl...
<python><pandas>
2023-04-14 22:10:23
2
5,750
GegznaV
76,019,214
14,350,333
How can determine to run a script using `python` or `python3` depending on the installed version of python?
<p>I have a script file <code>myfile.sh</code> and contains the following</p> <pre><code>#! /bin/bash set -e MYVAR=`cat $1 | python -c 'import os`' </code></pre> <p>The question is, how I can make a condition to use python3 if python3 is installed or in other word(python is &gt; 3) and use python if the installed ver...
<python><python-3.x><bash><shell>
2023-04-14 21:54:24
1
3,553
Yusuf
76,019,139
5,788,582
How to use bs4 to grab all text, sequentially, whether wrapped in element tag or not, regardless of hierarchical order
<p>Here's a sample of what I'm scraping:</p> <pre><code>&lt;p&gt;&lt;strong&gt;Title 1&lt;/strong&gt; &lt;br /&gt; lorem ipsum 1&lt;/p&gt; &lt;p&gt;lorem ipsum 2&lt;/p&gt; … &lt;p&gt;lorem ipsum n&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Title 2&lt;/strong&gt; &lt;br /&gt; blah blah &lt;/p&gt; </code></pre> <p>I would like al...
<python><python-3.x><beautifulsoup>
2023-04-14 21:40:36
1
1,905
Jay Jung
76,019,033
7,903,749
How to use assert in Python production source code?
<p>We are looking at self-developed libraries shared between multiple Django projects or components of the same project, not the published open-source libraries.</p> <p><strong>Question:</strong></p> <p>We wonder whether it is OK to use <code>assert</code> to validate the variable's values.</p> <p>If yes, how?</p> <p><...
<python><django><assert>
2023-04-14 21:22:43
1
2,243
James
76,019,012
9,837,010
Homography point estimation looks incorrect
<p>I'm attempting to map the locations of people's feet to a top down view of a game area. The top part of the image is the top down view and the bottom half is the camera view. I've used the center net to calculate the homography for the points on each person's feet, however, when they are projected on the top down v...
<python><opencv><homography>
2023-04-14 21:20:07
0
479
Austin Ulfers
76,018,972
12,639,940
Find items from a list starting with the letter a through m
<p>For example we have a list:</p> <pre class="lang-py prettyprint-override"><code>l = [&quot;aqi&quot;, &quot;cars&quot;, &quot;dosage&quot;, &quot;dummy&quot;, &quot;maze&quot;, &quot;quiz&quot;, &quot;sample&quot;, &quot;trips&quot;, &quot;users&quot;, &quot;zoo&quot;] </code></pre> <ul> <li>Assuming the list to be ...
<python><list><search>
2023-04-14 21:11:12
1
516
Kayvan Shah
76,018,926
2,328,273
Using ANSI color codes with multiple logging handlers in Python producing strange results
<p>I am working on logging for a program I have. I am setting up different formats for the log message depending on the level. This includes colors. I am have two handlers, one for the console and one for the file. I was working on the format because the ANSI codes leave characters behind in the log when I came across ...
<python><logging><ansi-escape>
2023-04-14 21:02:40
2
1,010
user2328273
76,018,681
9,611,950
How to deal with double header dataframe and pivot it in Python?
<p>I've a data frame as follows:</p> <pre><code>Country Year Stunting prevalence in children aged &lt; 5 years (%) Stunting prevalence in children aged &lt; 5 years (%) Stunting prevalence in children aged &lt; 5 years (%) Stunting prevalence in children aged &lt; 5 years (%) Stunting prevalence in children aged...
<python><pandas><dataframe>
2023-04-14 20:22:40
0
1,391
Vishal A.
76,018,612
2,194,718
Python - Check if an exact list item exists in a string
<p>I'm trying to match a string exactly in another string.</p> <pre><code>'-w' </code></pre> <p>And I have a few different string target formats below.</p> <pre><code>`string -w` `string -wy` `string -w string` `string -wy string` </code></pre> <p>I've tried the basic check but it matches all of the above four strings,...
<python><regex>
2023-04-14 20:11:28
0
2,503
llanato
76,018,415
3,261,292
XPath in Python: getting the html script that contains the extracted value of an Xpath
<p>I have two types of xpaths, the first looks like this:</p> <pre class="lang-xpath prettyprint-override"><code>//div[@class=&quot;location msM10&quot;]//div[@class='categories'] </code></pre> <p>and the second looks like this:</p> <pre class="lang-xpath prettyprint-override"><code>//a[contains(@class,'job-title')][1]...
<python><html><xpath>
2023-04-14 19:36:47
1
5,527
Minions
76,018,374
5,619,148
Find consecutive or repeating items in list
<p>I have the following python list</p> <p><code>data = [1, 2, 2, 2, 3, 4, 7, 8]</code></p> <p>Now I want to partition it so that the consecutive or repeating items are in the same group.</p> <p>So this should break into two lists as:</p> <p><code>[1, 2, 2, 2, 3, 4] and [7, 8]</code></p> <p>Tried itertools and group by...
<python>
2023-04-14 19:30:13
4
761
Pankaj Daga
76,018,339
15,763,991
getting the Premium tier of a User without redirect uri
<p>I want to check whether a user is subscribed to Discord Nitro. I found out that you can do that with the following line of code:</p> <pre><code>response = requests.get(f&quot;https://discord.com/api/v8/users/{message.author.id}&quot;, headers={ &quot;Authorization&quot;: f&quot;Bot TOKEN&quot; }) if response.sta...
<python><discord>
2023-04-14 19:25:10
1
418
EntchenEric
76,018,299
788,153
pandas rolling window parallelize problem while using numba engine
<p>I have huge dataframe and I need to calculate slope using rolling windows in pandas. The code below works fine but looks like numba is not able to parallelize it. Any other way to parallelize it or make it more efficient?</p> <pre><code>def slope(x): length = len(x) if length &lt; 2: return np.nan ...
<python><pandas><optimization><numba>
2023-04-14 19:17:31
1
2,762
learner
76,018,241
3,668,129
How to record to wav file using dash application
<p>I'm trying to build a simple <code>dash</code> application which:</p> <ul> <li>Have one button</li> <li>After clicking on the button the client talks for 5 seconds to the microphone and a new wav is created.</li> </ul> <p>It seems that running this app opens the microphone at the server and not at the client.</p> <p...
<python><plotly-dash>
2023-04-14 19:07:47
0
4,880
user3668129
76,018,208
1,214,800
Python typing equivalent of TypeScript's keyof
<p>In TypeScript, we have the ability to create a &quot;literal&quot; type based on the keys of an object:</p> <pre class="lang-js prettyprint-override"><code>const tastyFoods = { pizza: '🍕', burger: '🍔', iceCream: '🍦', fries: '🍟', taco: '🌮', sushi: '🍣', spaghetti: '🍝', donut: '🍩', cookie: '🍪...
<python><python-typing>
2023-04-14 19:03:29
2
73,674
brandonscript
76,018,174
5,679,985
Heroku dynos H12, all requests timing out
<p>Dynos completely fail (timeouts) every other day</p> <p>Hi all, I've been having this issue with Heroku for months now. I have a python/django app, using the 2X dynos (2 of them). I have 8 workers per dyno</p> <p>Every other day, there will be a huge spike in the response times and it will last for 30 mins to a few ...
<python><django><heroku>
2023-04-14 18:57:57
0
1,274
Human Cyborg Relations
76,018,125
1,667,868
django if value equals enum show field
<p>For my django project I try to show a button if a field is equal to an enum value. I loop over lights and based on the state I want to show a button.</p> <p>My enum:</p> <pre><code>class DeviceState(Enum): UNKNOWN = 1 STAND_BY = 2 ON = 3 OFF = 4 </code></pre> <p>My light:</p> <pre><code>class Light: ...
<python><django>
2023-04-14 18:49:24
1
12,444
Sven van den Boogaart
76,018,045
9,944,937
Scipy filter returning nan Values only
<p>I'm trying to filter an array that contains nan values in python using a scipy filter:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import scipy.signal as sp def apply_filter(x,fs,fc): l_filt = 2001 b = sp.firwin(l_filt, fc, window='blackmanharris', pass_zero='lowpass', fs=fs) ...
<python><numpy><scipy><signal-processing>
2023-04-14 18:36:42
1
1,101
Fabio Magarelli
76,017,771
419,116
Smooth evolving histogram in matplotlib?
<p>I'm porting some Mathematica <a href="https://www.wolframcloud.com/obj/yaroslavvb/nn-linear/mathoverflow-gaussian-convergence.nb" rel="nofollow noreferrer">code</a> and wondering if there's a way to do visualization like below in Python library like matplotlib or seaborne</p> <p><a href="https://i.sstatic.net/e2L9u....
<python><matplotlib><plot><seaborn>
2023-04-14 17:53:32
0
58,069
Yaroslav Bulatov
76,017,745
20,266,647
Valid parquet file, but error with parquet schema
<p>I had correct parquet file (I am 100% sure) and only one file in this directory <code>v3io://projects/risk/FeatureStore/ptp/parquet/sets/ptp/1681296898546_70/</code>. I got this generic error <code>AnalysisException: Unable to infer schema ...</code> during read operation, see full error detail:</p> <pre><code>-----...
<python><pyspark><parquet><mlrun>
2023-04-14 17:50:15
3
1,390
JIST
76,017,680
2,778,224
Remove duplicated rows of a `list[str]` type column in Polars
<p>I have a DataFrame with a column that contains lists of strings. I want to filter the DataFrame to drop rows with duplicated values of the list column.</p> <p>For example,</p> <pre class="lang-py prettyprint-override"><code>import polars as pl # Create a DataFrame with a list[str] type column data = pl.DataFrame({ ...
<python><dataframe><python-polars>
2023-04-14 17:40:32
3
479
Maturin
76,017,652
419,042
ModuleNotFoundError: No module named 'promise'
<p>I get this error about a module called promise with most pip installs.</p> <pre><code>pip install promise Defaulting to user installation because normal site-packages is not writeable Collecting promise Using cached promise-2.3.tar.gz (19 kB) Preparing metadata (setup.py) ... error error: subprocess-exite...
<python>
2023-04-14 17:34:03
0
805
galactikuh
76,017,589
4,158,016
Python pandas add new column in dataframe after group by, based on emp-manager relation
<pre><code>import pandas as pd import numpy as np testdf=pd.DataFrame({'id':[1,3,4,16,17,2,52,53,54,55],\ 'name':['Furniture','dining table','sofa','chairs','hammock','Electronics','smartphone','watch','laptop','earbuds'],\ 'parent_id':[np.nan,1,1,1,1,np.nan,2,2,2,2]}) #tes...
<python><pandas>
2023-04-14 17:20:35
1
450
itsavy
76,017,567
21,420,742
How to find Vacant roles in Python
<p>I asked this question before and got a response that at the time with test cases worked but now is creating incorrect results. The data I have looks at Employees history from job to who they report to. What I want to see is when a role is vacated and someone fills in. This can be identified by <strong>ManagerPosNum<...
<python><python-3.x><pandas><dataframe><numpy>
2023-04-14 17:18:13
1
473
Coding_Nubie
76,017,503
12,323,468
How do I write a Pyspark UDF to generate all possible combinations of column totals?
<p>I have the following code which creates a new column based on combinations of columns in my dataframe, minus duplicates:</p> <pre><code>import itertools as it import pandas as pd df = pd.DataFrame({ 'a': [3,4,5,6,3], 'b': [5,7,1,0,5], 'c': [3,4,2,1,3], 'd': [2,0,1,5,9] }) orig_cols = df.columns for r ...
<python><pyspark><user-defined-functions>
2023-04-14 17:10:45
2
329
jack homareau
76,017,106
11,855,904
How to set `filterset_fields` in Django-Filter and Django REST Framework?
<p>When I set the fiterset_fields like below,</p> <pre class="lang-py prettyprint-override"><code>class SubCategoryViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = [&quot;category_id&quot;] # single underscore </code></pre> <p>I get this response when a category...
<python><django><django-rest-framework><django-filter>
2023-04-14 16:17:47
2
392
cy23
76,017,076
1,693,057
Package with "typing" subpackage causing naming collision
<p>I'm having an issue with a Python package that has a <code>typing</code> subpackage. When I try to import a module from this package, it seems that the <code>typing</code> subpackage in the package is being assigned to the global namespace of <code>mypackage</code>, causing naming collisions with the built-in <code>...
<python><python-import><python-module><python-packaging>
2023-04-14 16:14:36
0
2,837
Lajos
76,016,928
135,807
How can I submit a pending order using ibapi that can be executed after hours as well?
<p>I use Python to access abiapi..</p> <pre><code> order = Order() order.action = &quot;BUY&quot; # or &quot;SELL&quot; order.action = &quot;SELL&quot; order.totalQuantity = quantity # the quantity of the asset to buy/sell order.orderType = &quot;LMT&quot; # the order type, such as &quot;LMT&q...
<python><ib-api>
2023-04-14 15:56:13
1
5,409
Aftershock
76,016,890
17,639,970
how to plot isochrone_map around a particular node?
<p>I'm working on the followimg map data:</p> <pre><code># Define the bounding box coordinates for the region of interest north, south, east, west = 40.8580, 40.7448, -73.9842, -74.2996 # Retrieve the street network for the region of interest G = ox.graph_from_bbox(north, south, east, west, network_type='drive') </cod...
<python><osmnx>
2023-04-14 15:51:30
0
301
Rainbow
76,016,774
4,913,254
Split and explode a column with several items
<p>I have a data frame like this</p> <pre><code> CHR START END INFO 2547 X 153595089 153595228 FLNA_NM_001110556.2_ex05,FLNA_NM_001456.4_ex05 2548 X 153595754 153595922 FLNA_NM_001110556.2_ex04,FLNA_NM_001456.4_ex04 2549 X 153595998 153596116 FLNA_NM_001110556.2_ex03,FLNA_NM_001456.4_e...
<python><pandas>
2023-04-14 15:38:24
1
1,393
Manolo Dominguez Becerra
76,016,640
6,727,914
Python equivalent of this matlab function
<p>I am looking for the Python equivalent of this Matlab code:</p> <pre><code>% create a set of 2D points points = [0 0; 1 0; 1 1; 0 1; 0.5 0.5]; % compute the Delaunay triangulation tri = delaunay(points); % plot the points and the triangles triplot(tri, points(:,1), points(:,2)); </code></pre> <p>The output is:</p>...
<python><matlab><scipy><physics><computational-geometry>
2023-04-14 15:20:03
0
21,427
TSR
76,016,620
386,279
Reliable way to detect new Int64 and Float64 dtypes and map to older ones
<p>I don't know what the new dtypes are called, but when I create a df like</p> <pre class="lang-py prettyprint-override"><code>xdf = pd.DataFrame( { &quot;a&quot;: pd.Series([1, 2, 3, 4], dtype=pd.Float64Dtype), &quot;b&quot;: [True, False, True, False], } ) </code></pre> <p>the dtype for <code...
<python><pandas>
2023-04-14 15:18:13
1
21,193
beardc
76,016,567
9,850,681
How to reuse variable in YAML file with Pydantic
<p>I would like to load a YAML file and create a Pydantic BaseModel object. I would like to know if it is possible to reuse a variable inside the YAML file, for example:</p> <p><code>YAML file</code></p> <pre class="lang-yaml prettyprint-override"><code>config: variables: root_level: DEBUG my_var: &quot;TEST&...
<python><yaml><pydantic>
2023-04-14 15:11:06
1
460
Plaoo
76,016,458
13,819,183
Set time to live in Azure Blob containers created using BlobServiceClient
<p>I'm currently using the following setup to create containers in an Azure Storage Account, and writing blobs to those containers:</p> <pre class="lang-py prettyprint-override"><code>from azure.storage.blob import BlobServiceClient connstr = &quot;...&quot; bsc = BlobServiceClient.from_connection_string(connstr) cont...
<python><python-3.x><azure><azure-blob-storage><azure-storage>
2023-04-14 14:59:36
2
1,405
Steinn Hauser Magnússon
76,016,453
2,391,712
FastAPI: Combine ORM and dataclass
<p>I am trying to use dataclass in combination with fastapi. I want to use the same dataclass for fastapi (json-serialisation) <em>and</em> orm-database model.</p> <p>my <code>model.py</code> looks like this:</p> <pre><code>from typing import Optional from pydantic.dataclasses import dataclass from sqlalchemy import S...
<python><sqlalchemy><orm><fastapi><python-dataclasses>
2023-04-14 14:59:14
1
2,515
5th
76,016,442
2,130,515
How to hide pages except one in streamlit
<p>here is my pages.toml config</p> <pre><code>[[pages]] path = &quot;src/features/home.py&quot; name = &quot;Home&quot; icon = &quot;🏠&quot; [[pages]] path = &quot;src/features/page0.py&quot; name = &quot;page0&quot; icon = &quot;🔍&quot; [[pages]] path = &quot;src/features/page1.py&quot; name = &quot;page1&quot; i...
<python><streamlit>
2023-04-14 14:57:24
1
1,790
LearnToGrow
76,016,429
2,201,603
DASH PLOTLY Callback error updating county_dropdown.value
<p>Receiving callback error in browser but not terminal or jupyter notebook. I am receiving the outcome I'd like, but I'm getting the error message. I've restarted my computer and ensured no other browsers were running on port 8050 (suggestion from another stack question).</p> <p><strong>Outcome I would like:</strong> ...
<python><pandas><plotly-dash>
2023-04-14 14:55:54
1
7,460
Dave
76,016,383
13,158,157
pyspark vs pandas filtering
<p>I am &quot;translating&quot; pandas code to pyspark. When selecting rows with <code>.loc</code> and <code>.filter</code> I get different count of rows. What is even more frustrating unlike pandas result, pyspark <code>.count()</code> result can change if I execute the same cell repeatedly with no upstream dataframe ...
<python><pandas><dataframe><pyspark>
2023-04-14 14:50:45
0
525
euh
76,016,355
417,896
Python exit asyncio/websockets process with Ctrl-C
<p>I have a problem stopping python processes using asyncio and websockets, not sure which one is the issue. If I run this code then sometimes Ctrl-C doesn't do anything and I need Ctrl-Z which seems to just send the process to background because it doesn't close the websocket server port in use.</p> <p>How do I allow...
<python><websocket><python-asyncio>
2023-04-14 14:47:58
0
17,480
BAR
76,016,271
7,886,653
Is there a way to perform multioutput regression in Scikit-Learn using a different base estimator for each output?
<p>Consider a typical multi-output regression problem in Scikit-Learn where we have some input vector X, and output variables y1, y2, and y3. In Scikit-Learn that can be accomplished with something like:</p> <pre class="lang-py prettyprint-override"><code>import sklearn.multioutput model = sklearn.multioutput.MultiOutp...
<python><machine-learning><scikit-learn>
2023-04-14 14:39:09
0
2,375
AmphotericLewisAcid
76,015,935
1,914,781
filter dataframe by rule from rows and columns
<p>I got a xlsx file, data distributed with some rule. I need collect data base on the rule. e.g. valid data begin row is &quot;y3&quot;, data row is the cell below that row.</p> <p>In below sample,</p> <pre><code>import pandas as pd data1 = [ [&quot;A&quot;,&quot;y3&quot;,&quot;y2&quot;,&quot;y3&quot;,&quot;y4&qu...
<python><pandas>
2023-04-14 14:04:03
1
9,011
lucky1928
76,015,932
2,966,421
Replacing multiple json fields with the same name in python
<p>I am trying to modify a json file with partial success.</p> <p>I have the same field names in different parts of this json file. For some reason my code only works on the second field. I don't know if there is a redundancy issue. My code is this:</p> <pre><code>with open(os.path.join(model_folder, 'config.json'), 'r...
<python><json>
2023-04-14 14:03:58
0
818
badner
76,015,746
1,506,850
upload a file to s3 after script end/crashes: cannot schedule new futures after interpreter shutdown
<p>I need to upload a file to s3 no matter how a script end/interrupts.</p> <p>I have done:</p> <pre><code>import atexit import signal atexit.register(exit_handler) signal.signal(signal.SIGINT, exit_handler) signal.signal(signal.SIGTERM, exit_handler) def exit_handler(): s3_client = boto3.client('s3') s3_client...
<python><amazon-web-services><amazon-s3><sigint><atexit>
2023-04-14 13:43:20
1
5,397
00__00__00
76,015,670
8,746,466
How to change all occurrences of a tag to a specific text using `lxml`?
<p>My home-made solution could be:</p> <pre class="lang-py prettyprint-override"><code>import lxml.etree as ET def tag2text(node, sar): &quot;&quot;&quot;Replace element in `sar.keys()` to text in `sar.values()`.&quot;&quot;&quot; for elem, text in sar.items(): for ph in node.xpath(f'.//{elem}'): ...
<python><lxml>
2023-04-14 13:35:24
2
581
Bálint Sass
76,015,650
5,852,506
See output of a python app running in the background in a docker image in Gitlab
<p>In my gitlab-ci.yml file I have a script which runs my python app in the background <code>python app.py &amp;</code> and then I do calls to it from other testing scripts.</p> <p>The problem is I don't see the output of the application in my Gitlab console.</p> <p>For example, this is the output I get from running my...
<python><gitlab><stdout><docker-image><gitlab-ci.yml>
2023-04-14 13:33:19
2
886
R13mus
76,015,647
8,188,120
Editing xml child node text by finding child nodes based on name
<p>I would like to alter the text of a child node for an xml file parsed using python. I know the name of the childnodes but I can't seem to find the right sytax to point to the childnode, or the fact that the childnode name has a colon in it is throwing things off (I can't tell which).</p> <p>For editing a childnode's...
<python><xml><nodes><lxml>
2023-04-14 13:33:03
0
925
user8188120
76,015,646
8,898,218
how to disable inline disable comments for pylint and flake8?
<p>we started using pylint and flake8. But, I see many just adding an inline comment to disable the pylint/flake8 error/warnings. Is there a way to ignore these inline comments and generate a complete report in pylint and flake8?</p>
<python><pylint><flake8>
2023-04-14 13:32:58
1
5,090
rawwar
76,015,643
2,591,194
ruamel.yaml: Trying to parse a GitHub Actions workflow file, do some modifications to it and then dump back to file. Formatting is off/unexpected
<p>I am using Python to migrate our GitHub Actions workflows.</p> <p>Chose ruamel.yaml over pyYaml because here I at least have the option to preserve quotes.</p> <p>Now, it looks like this though:</p> <pre class="lang-yaml prettyprint-override"><code> - {uses: actions/checkout@v3} </code></pre> <p>The original is this...
<python><yaml><ruamel.yaml>
2023-04-14 13:32:33
1
3,731
Moritz Schmitz v. Hülst
76,015,607
13,518,907
Python - Extract Informations from Docx-File into Pandas Df
<p>I have a Word-Document with the contents of an interview and want to store every question and answer in a Pandas dataframe. The word-document looks like this:</p> <p><a href="https://i.sstatic.net/4BFWb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4BFWb.png" alt="word doc" /></a></p> <p>So in the e...
<python><pandas><dataframe><docx><text-extraction>
2023-04-14 13:28:34
2
565
Maxl Gemeinderat
76,015,477
2,028,234
Graph Error or Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>)
<p>I have been trying to solve this issue for the last few weeks but is unable to figure it out. I am hoping someone out here could help out.</p> <p>I am following this github repository for generating a model for lip reading however everytime I try to train my own version of the model I get this error: Attempt to conv...
<python><tensorflow><conv-neural-network><jupyter><3d-convolution>
2023-04-14 13:12:28
1
532
Nique Joe
76,015,335
3,084,842
Python networkx optimal distances between nodes and labels
<p>I'm using Python's <a href="https://networkx.org/" rel="nofollow noreferrer">networkx</a> to plot a network diagram that shows roughly 30 connections between different items.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd import networkx as nx de = pd.DataFrame(data={'x1':['sp...
<python><matplotlib><graph><formatting><networkx>
2023-04-14 12:56:04
1
3,997
Medulla Oblongata
76,015,265
1,256,347
Why does pandas pipe change the dataframe in place when columns are added, but not when columns or rows are removed?
<p>Whenever a function used in <code>pipe</code> adds columns, the DataFrame is affected in place. However, when the function removes rows or columns, the original DataFrame is not affected.</p> <p>Is this how it is supposed to work? How can I ensure the DataFrame is always affected in place without having to re-assign...
<python><pandas><dataframe>
2023-04-14 12:47:30
1
2,595
Saaru Lindestøkke
76,014,845
21,420,742
How to map a column to another column in Python
<p>I have a dataset that is employee's history. What I want to do is map the managers ID to the job position being held by that manager.</p> <p>Here is a sample of what I have:</p> <pre><code> ID Name Job_Title ManagerID ManagerName 101 Adam Sales Rep 102 Ben 102 ...
<python><python-3.x><pandas><dataframe><numpy>
2023-04-14 11:57:42
0
473
Coding_Nubie
76,014,842
3,176,696
PySpark read Iceberg table, via hive metastore onto S3
<p>I'm trying to interact with Iceberg tables stored on S3 via a deployed hive metadata store service. The purpose is to be able to push-pull large amounts of data stored as an Iceberg datalake (on S3). Couple of days further, documentation, google, stack overflow... just not coming right.</p> <p>From <a href="https://...
<python><pyspark><hive><apache-iceberg>
2023-04-14 11:57:09
3
906
Paul
76,014,701
14,729,820
How to avoid adding double start of token in TrOCR finetune model
<p><strong>Describe the bug</strong> The model I am using (TrOCR Model):</p> <p>The problem arises when using:</p> <ul> <li>[x] the official example scripts: done by the nice tutorial <a href="https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TrOCR/Fine_tune_TrOCR_on_IAM_Handwriting_Database_using_Seq2S...
<python><deep-learning><pytorch><huggingface-transformers><huggingface>
2023-04-14 11:37:17
1
366
Mohammed
76,014,556
9,018,649
What replaces the old BlockBlobService.get_blob_to_bytes in the new BlobServiceClient?
<p>I have an old azure function which uses BlockBlobService -&gt;get_blob_to_bytes. As described here: <a href="https://github.com/uglide/azure-content/blob/master/articles/storage/storage-python-how-to-use-blob-storage.md#download-blobs" rel="nofollow noreferrer">https://github.com/uglide/azure-content/blob/master/art...
<python><azure><azure-blob-storage>
2023-04-14 11:17:31
1
411
otk
76,014,288
4,444,546
Python logger left align level with color + :
<p>I am using fastapi and uvicorn and I want my logger to look the same. I don't manage to do it.</p> <p>The logging is as follows:</p> <pre><code>INFO: Application startup complete. WARNING: StatReload detected changes in 'ethjsonrpc/main.py'. Reloading... INFO: Shutting down INFO: Waiting for application...
<python><logging>
2023-04-14 10:45:57
1
5,394
ClementWalter
76,014,122
12,193,952
TypeError: No matching signature found while using fillna(method='ffill')
<h2>Problem</h2> <p>I wanted to replace <code>NaN</code> values in my dataframe with values using <code>fillna(method='ffill')</code> (<em>fill missing values in a DataFrame or Series with the previous non-null value</em>), however the code example below resulted in error.</p> <pre class="lang-py prettyprint-override">...
<python><pandas><dataframe>
2023-04-14 10:27:42
1
873
FN_
76,014,099
17,174,267
Why does writing to %appdata% from the Windows Store version of Python not work?
<p>I was trying to write some data to <code>%appdata%</code>. Everything seemed to work as shown in the output of Script1. The new directories are being created and the file is saved and the data gets retrieved successfully as well. But when trying to look at the data in File Explorer, the folder wasn't there! CMD coul...
<python><python-3.x><windows-10><windows-store>
2023-04-14 10:25:19
2
431
pqzpkaot
76,014,087
9,827,719
Install yara-python gives "Cannot open include file: 'openssl/asn1.h'" on Windows 11
<p>When I try to install yara-python by issuing the following command:</p> <pre><code>C:\Users\admin\code\my-project\venv\Scripts\activate.bat pip install yara-python </code></pre> <p>I get the following error message:</p> <pre><code>&quot;C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14....
<python><yara>
2023-04-14 10:24:08
0
1,400
Europa
76,013,881
5,547,553
How to rewrite row_number() windowing sql function to python polars?
<p>I'd like to rewrite the following sql code to python polars:</p> <pre><code>row_number() over (partition by a,b order by c*d desc nulls last) as rn </code></pre> <p>Suppose we have a dataframe like:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;a&quot;: [&quot;a&quot;, &quot;b&quot;, &quo...
<python>
2023-04-14 10:01:50
1
1,174
lmocsi
76,013,851
9,581,273
How can I optimize this Django query to get faster result?
<pre><code>items = Items.objects.filter(active=True) price_list = [] for item in items: price = Price.objects.filter(item_id = item.id).last() price_list.append(price) </code></pre> <p>Price model can have multiple entry for single item, I have to pick last element. How can we optimize above query to avoid use o...
<python><mysql><sql><django><orm>
2023-04-14 09:59:04
2
1,787
Puneet Shekhawat
76,013,820
6,936,682
Configuring TALISMAN with superset helm
<p>So I'm in the process of configuring my superset deployment with helm. Everything works fine aside from the warning regarding Talisman, which I really want to configure to get rid of. i.e.:</p> <blockquote> <p>WARNING:superset.initialization:We haven't found any Content Security Policy (CSP) defined in the configura...
<python><kubernetes-helm><apache-superset>
2023-04-14 09:54:36
2
1,970
Jeppe Christensen
76,013,811
6,195,489
Replace value in dataframe with another value in the same row
<p>I have a pandas dataframe that looks something like this:</p> <pre><code>myid user start end a tom 2023-01-01T23:41:32 2023-01-02T23:41:32 b dick None 2023-01-05T20:41:32 c harry 2023-01-01T23:41:32 2023-01-03T21:41:32 d sally None ...
<python><pandas><dataframe>
2023-04-14 09:53:42
0
849
abinitio
76,013,780
350,685
Unable to use Python to connect to mysql
<p>I am attempting a basic MySQL connection program using Python. The code:</p> <pre><code>if __name__ == '__main__': print_hi('PyCharm') print(&quot;Connecting to database.&quot;) mysqldb = mysql.connector.connect( host=&quot;localhost&quot;, user=&quot;username&quot;, password=&qu...
<python><mysql>
2023-04-14 09:51:26
1
10,638
Sriram
76,013,753
5,468,372
Pass memory address to multiprocessing.Process outside of its memory context
<p>I'd like to achieve something that is most possibly not possible, potentially dangerous of very certainly despicable:</p> <p>I have a global complex data object. I'd like to pass its memory address, which is of course outside of the spawned process's memory so it can alter the same data that is on global scope.</p> ...
<python><memory><multiprocessing>
2023-04-14 09:48:17
1
401
Luggie
76,013,725
8,993,864
How to interpret the error message "Foo() takes no arguments" when specifying a class instance as base class?
<p>The following code:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; class Foo: pass &gt;&gt;&gt; class Spam(Foo()): pass </code></pre> <p>will of course raise an error message:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, ...
<python><inheritance><python-internals>
2023-04-14 09:45:11
1
405
yixuan
76,013,593
5,783,373
Importing variable from a function of one script into separate script in Python
<p>I am trying to import a variable which is created inside a function of one python script into another python script, but I am receiving an error.</p> <p>Here is what I have tried:</p> <pre><code># File1.py: ----------- from file2 import foo def myfunc(): print(foo.x) myfunc() #calling the function # File2.py:...
<python><import>
2023-04-14 09:32:30
1
345
Sri2110
76,013,575
3,170,559
How to setup serverless sql pool to use it with basic SQL Interfaces like pyodbc or RODBC?
<p>I'm trying to set up a serverless SQL pool in Azure Synapse Analytics, and I want to be able to use basic SQL interfaces like pyodbc or RODBC to interact with it. However, I'm not sure how to go about doing this.</p> <p>Basically, I want to be able to use standard commands like <code>create</code> or <code>insert</c...
<python><r><pyodbc><serverless><azure-synapse>
2023-04-14 09:30:41
1
717
stats_guy
76,013,485
4,095,771
Rasterizing a large image with Rasterio
<p>I am rasterizing polygons in a large raster using the following code:</p> <pre><code>import rasterio.features from shapely.geometry import Polygon p1 = Polygon([[0,0], [32000,0], [32000,32000], [0,0]]) out_shape = (32000, 32000) # The default transform is fine here r = rasterio.features.rasterize([p1], out_shape=ou...
<python><gdal><rasterio><rasterize>
2023-04-14 09:20:56
1
3,446
KarateKid
76,013,112
102,063
Kubernetes: How do I get a robust status of a pod using python?
<p>I use something like this to get the status of pods.</p> <pre><code>from kubernetes import client v1core = client.CoreV1Api() api_response =v1core.list_namespaced_pod(...) for pod in api_response.items: status = pod.status.phase </code></pre> <p>I have some extra code to find out that it is actually an error ex...
<python><kubernetes>
2023-04-14 08:38:19
0
567
HackerBaloo
76,013,013
5,560,529
How to fill rows of a PySpark Dataframe by summing values from the previous row and the current row?
<p>I have the following, simplified PySpark input Dataframe:</p> <pre><code>Category Time Stock-level Stock-change apple 1 4 null apple 2 null -2 apple 3 null 5 banana 1 12 null banana 2 null 4 oran...
<python><apache-spark><pyspark><apache-spark-sql>
2023-04-14 08:23:09
1
784
Peter
76,012,995
20,508,530
How to implement two factor authentication over simplejwt in django?
<p>I have implemented authentication using simple jwt and Now I want to implement 2 factor authentication. I am using react for frontend.</p> <p>2-fa will be introduced only when there is change in browser/device/ip address.</p> <p>I store this information I have thee field in my user model <code>last_login_location</c...
<python><django><django-rest-framework><django-rest-framework-simplejwt>
2023-04-14 08:20:48
1
325
Anonymous
76,012,878
1,127,683
Debugging Python File in monorepo in VS Code gives ModuleNotFoundError
<p>I'm using:</p> <ul> <li>VS Code v1.74.3</li> <li>ms-python.python v2022.20.2</li> <li>python v3.9.1 (installed globally with Pyenv)</li> </ul> <p><strong>My setup</strong></p> <pre class="lang-bash prettyprint-override"><code>workspace-root └── dir-1 └── dir-2 └── src └── event_producer_1 ├──...
<python><visual-studio-code>
2023-04-14 08:06:51
1
3,662
GreenyMcDuff
76,012,845
4,336,593
Tweaking Pandas dataframe to train a regression (advance prediction of events) model
<p>My dataframe has several prediction variable columns and a target (event) column. The events are either <code>1</code> (the event occurred) or <code>0</code> (no event). There could be consecutive events that make the target column <code>1</code> for the consecutive timestamp. I want to shift (backward) all rows in ...
<python><pandas><dataframe><regression>
2023-04-14 08:03:47
0
858
santobedi
76,012,772
10,413,428
setCursor(QCursor(Qt.ForbiddenCursor)) does not work on disabled QLineEdit
<p>I am trying to set the forbidden cursor to a dynamically enabled/disabled line edit. But it does not seem to work at all.</p> <pre class="lang-py prettyprint-override"><code>from PySide6.QtCore import Qt from PySide6.QtGui import QCursor def toggle_line_edit(self, switch_type: SwitchType): match switch_type: ...
<python><qt><pyside><pyside6>
2023-04-14 07:54:13
1
405
sebwr
76,012,755
14,269,252
how can I remove some unwanted characters in dictionary values
<p>I extracted some search keywords and their corresponding text and put them into a dictionary using python. A sample of dictionary looks as follows:</p> <pre><code>{'ID': 'ID', 'HE': 'Q1 - lth', 'LT': 'Q2 - La tor', 'HIP': 'Q3a - hh sure', 'MHBP': 'Q3.1.a - pressure ', 'DITE': 'Q3b - Dates'} </code></pre> <p>how can...
<python><nlp>
2023-04-14 07:52:27
1
450
user14269252
76,012,701
6,357,916
Unable to check if new youtube video is uploaded
<p>I want to know when someone upload a new video to his / her youtube channel 'https://www.youtube.com/@some-name-xyz'.</p> <pre><code>from googleapiclient.discovery import build from datetime import datetime, timedelta # Replace with your API key api_key = &quot;my-api-key&quot; # Replace with the Youtuber's userna...
<python><youtube><youtube-api><youtube-data-api><google-api-python-client>
2023-04-14 07:47:01
0
3,029
MsA