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
74,805,662
1,905,305
How to multiply pandas dataframe columns with dictionary value where dictionary key matches dataframe index
<p>Is there a better way than iterating over columns to multiply column values by dictionary values where the dictionary key matches a specific dataframe column? Give a dataframe of:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'category': [1,2,3,4,5], 'a': [5,4,3,3,4], 'b': [3,2,4,3,10], ...
<python><pandas><dataframe>
2022-12-15 00:31:42
2
779
mweber
74,805,446
16,287,416
How to hash a PyTorch Tensor
<p>Given a PyTorch Tensor of integers, for example, <code>torch.Size(N, C, H, W)</code>. Is there a way to efficiently hash each element of the tensor such that I get an output from <code>[-MAX_INT32 to +MAX_INT32]</code> or <code>[0 to MAX_INT32]</code> that fast runs on the GPU?</p> <p>Also in a way I can perform <co...
<python><hash><pytorch><tensor>
2022-12-14 23:54:49
3
307
Christian__
74,805,336
11,462,274
Among investment histories how to find the cumulative sum option that proves to be more reliable for the long term?
<p>In fact, not always the chart that reaches the highest peak of positive value when doing cumulative sum is the most reliable for long-term investments, because a single investment may have generated a very high profit but then it returns to the normal of being negative and if become an endless fall.</p> <p>Also rely...
<python><pandas><standard-deviation><cumsum>
2022-12-14 23:37:45
2
2,222
Digital Farmer
74,805,287
14,436,930
Why deque.append appears to be slower than list when performing extra calculations?
<p>As shown below, where I try to implement a memory with max length.</p> <p><code>a</code> uses a list that pops the first item when reaches the maximum length, <code>b</code> uses deque and relies on its built-in management of maxlen</p> <pre><code>import time import numpy as np import collections a = [np.ones((64, ...
<python><list><time><append><deque>
2022-12-14 23:30:19
0
671
seermer
74,805,267
143,684
How to use a custom console logger for the entire application in Python?
<p>After reading the logging documentation of Python and several examples of how to customise the log format and output, I came to the conclusion that formatting can only be set for a single logger instance. But since all libraries in other modules use their own logger instance (so that their source can be identified),...
<python><logging><python-logging>
2022-12-14 23:27:18
2
20,704
ygoe
74,805,228
6,017,833
Python how to detect a change in executed code
<p>I have a Python package with an entry point at <code>__main__</code>. I will be running a nightly Cron job, and I want the Cron job to execute the package if it detects a change in the execution of the package. I will be using git hashes to perform the comparison between files and commits.</p> <p>However, if I commi...
<python><git><cron><package>
2022-12-14 23:22:27
0
1,945
Harry Stuart
74,805,191
5,678,057
Pandas plot: How to add ```hue``` parameter to pandas plot
<p>I have the below graph obtained the following code:</p> <pre><code>x_var, y_var = 'category', 'instance' df.groupby(x_var)[y_var].nunique().plot.bar(stacked=False) </code></pre> <p>I want to add <code>hue</code> element using <code>Corr</code> column, on top of this so that I can see the distribution of the <code>Co...
<python><pandas><matplotlib>
2022-12-14 23:16:44
1
389
Salih
74,805,156
214,526
Pandas contains() returning an empty series while searching for text in a DataFrame column
<p>Dataset: <a href="http://github.com/mircealex/Movie_ratings_2016_17/raw/master/fandango_score_comparison.csv" rel="nofollow noreferrer"><code>fandango_score_comparison.csv</code></a></p> <p>I'm trying to access a row that matches a given movie name using the following code:</p> <pre class="lang-py prettyprint-overri...
<python><pandas><dataframe>
2022-12-14 23:12:09
1
911
soumeng78
74,805,132
5,227,892
Remove all elements in each list of a nested list, based on first nested list
<p>I have a following list:</p> <pre><code>a = [[0, 1, 0, 1, 1, 1], [23,22, 12, 45, 32, 33],[232, 332, 222, 342, 321, 232]] </code></pre> <p>I want to remove <code>0</code> in <code>a[0]</code> and corresponding values of <code>a[1]</code> and <code>[2]</code>, so the result list should be as follows:</p> <pre><code>d ...
<python><python-3.x>
2022-12-14 23:09:26
3
435
Sher
74,804,825
3,507,825
How to save created Python win32com msg file without displaying the email in the GUI?
<p>I am using Pywin32 and win32com to programmatically create and save Outlook MSG files. (These are emails that will only ever be saved and never be sent across smtp.) I am able to create and save the emails, but it only works when the display() method is used. This is problematic because it creates and opens the actu...
<python><outlook><save><win32com><msg>
2022-12-14 22:26:32
1
451
user3507825
74,804,756
2,088,886
Python Flask App Deployed to IIS Webserver 500's when using Subprocess nslookup
<p>I have a simple flask app that works locally but gets 500'd when testing in IIS.</p> <p>Edit: I was wrong, initially thought was pandas read issue but the issue is actually coming from subprocess that tries to get the user's IP address:</p> <pre><code>from flask import Flask, request import subprocess app = Flask(...
<python><flask><iis><subprocess><nslookup>
2022-12-14 22:18:56
1
2,161
David Yang
74,804,745
17,835,656
how can i show PDF file as Bytes using QWebEngineView in PyQt5?
<p>i need to import file from the database as Bytes and show it on the window using QWebEngineView in PyQt5.</p> <p>this is my code:</p> <pre class="lang-py prettyprint-override"><code> from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore from PyQt5 import QtWebEngineWidgets import sys applica...
<python><qt><pyqt><pyqt5>
2022-12-14 22:17:33
0
721
Mohammed almalki
74,804,702
12,574,341
Instantiating TypedDict easily with unpacked args
<p>When using <code>NamedTuple</code>, you can easily instantiate by unpacking an arbitrary number of arguments using <code>*</code></p> <pre class="lang-py prettyprint-override"><code>class DateTimeUTC(NamedTuple): year: int month: int day: int hour: int minute: int second: float dt = DateTime...
<python><python-typing>
2022-12-14 22:11:03
1
1,459
Michael Moreno
74,804,481
3,555,558
Django Signals not triggering when only using apps.py
<p>Here I want to create a Datalog when a new Customer create an account. I want to trigger the <code>Datalog</code> event and save the relevant information into the <code>Datalog</code> table.</p> <p>(I could write in signals.py but I prefer to write it into directly app.py)</p> <h3>apps.py</h3> <pre><code>from...
<python><django><django-signals>
2022-12-14 21:44:10
1
4,675
Alexander
74,804,404
2,989,642
How do I convert a Windows UNC path to a mapped drive letter path with Python?
<p>I've seen the reverse of this question asked a lot but can't find info on this one.</p> <p>A set of subprocesses I'm running in a script want Windows drive-letter paths (<code>M:\Some\Path\file.txt</code> instead of <code>\\my.subnet\someplace\Some\Path\file.txt</code>), but the UNC path is presented as an earlier i...
<python><pathlib>
2022-12-14 21:35:24
0
549
auslander
74,804,358
9,103,445
Combining large xml files efficiently with python
<p>I have about 200 xml files ranging from 5MB to 50MB, with 80% being &lt;10MB. These files contain multiple elements with both overlapping and unique data. My goal is to combine all this files, by performing a logical union over all the elements.</p> <p>The code seems to work but gets exponentially slower the more fi...
<python><lxml>
2022-12-14 21:28:10
1
1,267
Petru Tanas
74,804,336
3,423,825
How to return the user ID in HTTP response after a user log in with DRF token authentification?
<p>My application has a <code>/login</code> endpoint where users can enter their login information, and after a user has been authenticated I would like to display a DRF view based on it's user ID as a parameter in the URL. What is the best way to do that ? Shall I need to include the user ID into the HTTP response and...
<python><django><django-rest-framework>
2022-12-14 21:25:58
1
1,948
Florent
74,804,185
12,609,881
Update ObservableGauge in Open Telemetry Python
<p>I am using opentelemetry-api 1.14 and opentelemetry-sdk 1.14. I know how to create and use Counter and ObservableGauge instruments. However, I need to update and set the gauge throughout my application in a similar manner to how a counter can use its add method. I have working code below but in this working code the...
<python><open-telemetry>
2022-12-14 21:06:45
1
911
Matthew Thomas
74,804,068
3,826,115
How to add a equal-aspect inset axes in the corner of a parent axes
<p>I want to add an inset axis to the upper left corner of a parent axis. This can easily be done like so:</p> <pre><code>fig, ax = plt.subplots() iax = ax.inset_axes([0,.8, .2, .2]) </code></pre> <p><a href="https://i.sstatic.net/i6TJO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/i6TJO.png" alt="inse...
<python><matplotlib>
2022-12-14 20:54:23
1
1,533
hm8
74,804,010
9,422,346
Elasticsearch not showing running log in python
<p>I am new in Elasticsearch. I have a running Elasticsearch instance in cloud and accessing it via python, i want to see running logs which has a field - &quot;type&quot;- &quot;filebeat&quot;. I have following lines of code:</p> <pre><code>import elasticsearch from elasticsearch import Elasticsearch import elasticsea...
<python><elasticsearch>
2022-12-14 20:46:47
1
407
mrin9san
74,803,953
34,935
How to tell whether a python unittest subTest has failed as it's running?
<p>Python docs <a href="https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests" rel="nofollow noreferrer">say</a> give this example of using a subTest in unit testing:</p> <pre><code>import unittest class NumbersTest(unittest.TestCase): def test_even(self): &quot;&qu...
<python><python-unittest>
2022-12-14 20:39:51
1
21,683
dfrankow
74,803,912
10,576,322
Python package naming convention
<p>I want to create some python packages and deploy them in my company, not on PyPi.</p> <p>I stumbled over the problem that one package name already existed. So instead of mypackage from our repo I installed a PyPi package.</p> <p>The obvious solution is to change the name of the package. However, if I don't put the p...
<python><package>
2022-12-14 20:35:40
1
426
FordPrefect
74,803,726
1,100,913
Change tkinter menu radiobutton indicator
<p>Consider the menu below:</p> <pre><code>menu = tk.Menu(menubar, tearoff=0) menu.add_radiobutton(label='A', variable=flavour_value, value='a') menu.add_radiobutton(label='B', variable=flavour_value, value='b') </code></pre> <p>When radiobutton is selected, it shows V (checked) indicator from the left of a label.<br /...
<python><tkinter><menu><radio-button><indicator>
2022-12-14 20:14:10
2
953
Andrey
74,803,696
17,316,080
Get tar file buffer without write to file with Python
<p>I know how to tar file using Python</p> <pre><code>import os import tarfile with tarfile.open('res.tar.gz','w:xz' )as tar : tar.add('Pic.jpeg') </code></pre> <p>But I want to do that without create any tar.gz file, only get the results buffer.</p> <p>Hiw can I do that please?</p>
<python><python-3.x><tar><tarfile>
2022-12-14 20:10:52
1
363
Kokomelom
74,803,663
18,308,393
Replacing multiple columns with values in pandas
<p>I am replacing multiple columns values in pandas with the <code>pd.DataFrame.replace</code> method, however, this will not update any values inside my loop, and I cannot understand why it wont.</p> <p>For example:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': [0, 1, 2, 2, 2], 'B': [5...
<python><pandas>
2022-12-14 20:07:33
1
367
Dollar Tune-bill
74,803,526
827,927
Why don't I get faster run-times with ThreadPoolExecutor?
<p>In order to understand how threads work in Python, I wrote the following simple function:</p> <pre><code>def sum_list(thelist:list, start:int, end:int): s = 0 for i in range(start,end): s += thelist[i]**3//10 return s </code></pre> <p>Then I created a list and tested how much time it takes to co...
<python><multithreading><python-multithreading>
2022-12-14 19:52:31
2
37,410
Erel Segal-Halevi
74,803,430
5,500,634
Check graph equality using networkx isomorphic
<p>I have two graphs as follows</p> <pre><code>import networkx as nx G1, G2 = nx.DiGraph(), nx.DiGraph() G1.add_edges_from([(&quot;s1&quot;, &quot;s2&quot;), (&quot;s2&quot;, &quot;s3&quot;), (&quot;s3&quot;, &quot;s4&quot;)]) # G1: 1-&gt;2-&gt;3-&gt;4 G2.add_edges_from([(&quot;s1&quot;, &quot;s2&quot;), (&quot;s2&quo...
<python><graph><networkx><isomorphic>
2022-12-14 19:38:22
1
489
TripleH
74,803,382
1,811,073
Mock patch the return value of an inner function that's not returned from the outer function
<p>I'd like to capture the return value of an inner function without having to explicitly return that return value from the outer function.</p> <p>So I'd like to do something like this:</p> <pre><code># bar.py import foo def my_fn(): foo.fn() </code></pre> <pre><code># test.py from mock import patch import foo imp...
<python><mocking>
2022-12-14 19:32:18
2
876
aweeeezy
74,803,368
6,396,569
How can I run ripgrep using subprocess.Popen in Python3 with arguments?
<p>I use Python 3.10.7 and I am trying to get the Python interpreter to run this command:</p> <p><code>rg mysearchterm /home/user/stuff</code></p> <p>This command, when I run it in <code>bash</code> directly successfully runs <code>ripgrep</code> and searches the directory (recursively) <code>/home/user/stuff</code> fo...
<python><linux><bash><popen>
2022-12-14 19:31:14
1
2,567
the_endian
74,803,285
12,667,229
is these two dictonary statments are same while looping it in for loop?
<p>I read that my_dict.keys() returns the dynamic view to iterate over the dictionary. I usually iterate the dictionary without the keys() function.</p> <p>So my question is, are below two code blokes are same? if not, what performance differences do these two have (which one is more optimized)</p> <pre><code># without...
<python><python-3.x><optimization>
2022-12-14 19:23:04
2
330
Sahil Lohiya
74,803,278
5,025,216
python request and MSL is not working with azure protected URL
<p>i have some url where i need to do web crawling and it is protected by azure SAML protected. i have got the access token but still, request.get method return me to the redirected SAML login page content i use python masl library for azure SAML authentication.</p> <pre><code>import requests http_proxy = &quot;http://...
<python><python-3.x><python-requests><azure-active-directory><azure-ad-msal>
2022-12-14 19:22:22
1
310
om tripathi
74,803,239
5,942,100
Tricky Reverse Aggregate values to unique rows per category in Pandas
<p>I have a dataset where I would like to de aggregate the values into their own unique rows as well as perform a pivot and grouping by category.</p> <h2>Data</h2> <pre><code>Date start end area BB_stat AA_stat BB_test AA_test final 10/1/2022 11/1/2022 12/1/2022 NY 10 80 ...
<python><pandas><numpy>
2022-12-14 19:18:38
1
4,428
Lynn
74,803,109
7,134,235
What is the best way to validate a large json file before reading it into a pyspark dataframe?
<p>I have to read a large (roughly 1500 lines) json file into a pyspark data frame, and take into account incomplete json objects and unexpected line endings. The file has one json object per line, and looks like this:</p> <pre><code>{&quot;place&quot;:{&quot;place_name&quot;:&quot;Chicago&quot;,&quot;place_id&quot;: 2...
<python><json><pyspark>
2022-12-14 19:02:10
0
906
Boris
74,803,071
19,675,781
How to assign colors to values in a seaborn heatmap
<p>I have a data frame with 15 rows and 15 columns and the values are whole numbers in the range(0-5).</p> <p>I use this data frame to create multiple heatmaps by filtering the data.</p> <p>In the heatmap, I want to assign particular colors to every value so that even if the number of unique values in the data frame va...
<python><matplotlib><seaborn><legend><heatmap>
2022-12-14 18:59:13
1
357
Yash
74,802,764
7,617,510
plotly graph objects persistent data labels when clicking the graph
<p>I'm generating a graph:</p> <pre><code>import plotly.graph_objects as go </code></pre> <p><a href="https://i.sstatic.net/clHFX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/clHFX.png" alt="image1" /></a></p> <p>When I click on a data point I get the x,y data as shown, but as soon as I move the mouse...
<python><plotly><plot-annotations><grouped-bar-chart>
2022-12-14 18:29:11
0
1,289
magicsword
74,802,761
1,635,305
Get page content with "login with google" authentication using python
<p>I am wondering if it's generally possible. I have to get content of some page with specific URL utilizing python3.x. When I put URL into the browser, I have only one option: &quot;Continue with google&quot;. I give my google account credentials and then desired page appears. I need his content. Is it possible to do ...
<python><python-3.x><http><google-signin>
2022-12-14 18:28:53
2
1,595
Yuri Levinsky
74,802,735
11,614,319
easygui buttonbox crashes becase of default font from Tkinter
<p>I'm using easygui in a Python app and then generate an .exe with PyInstaller.</p> <p>Everything works fine in my computer, but my colleague get this weird error when they try to run the app :</p> <pre><code>Traceback (most recent call last): File &quot;easygui\boxes\button_box.py&quot;, line 95, in buttonbox File &q...
<python><tkinter><pyinstaller><easygui>
2022-12-14 18:25:32
1
362
gee3107
74,802,727
3,849,039
Converting PyTorch to CoreML gives a TypeError: 'dict' object is not callable
<p>I've been following Apple's <a href="https://coremltools.readme.io/docs/pytorch-conversion-examples" rel="nofollow noreferrer">coremltools docs</a> for converting PyTorch segmentation models to CoreML.</p> <p>While it works fine when we're loading a remote PyTorch model, I'm yet to figure out a working Python script...
<python><machine-learning><pytorch><coreml><coremltools>
2022-12-14 18:24:42
1
1,919
AnupamChugh
74,802,720
15,186,292
Change color of the node in Pyvis Network when it gets clicked on
<p>I'm creating a network visualization in python using Pyvis. I can create the graph as I want with no problem, but when I run my script and get the html file as output, I want the nodes to change colors when I click on them and I can't achieve that. I've tried a lot of things and nothing seems to work. The data I'm u...
<python><java><html><pyvis>
2022-12-14 18:23:57
0
301
TomasC8
74,802,692
275,002
MySQL deadlock error while updating within a loop
<p>I have the following piece of code updating records in a loop:</p> <pre><code> if connection is not None: with connection.cursor() as cursor: for instrument in instruments: instrument_name = instrument[0] price = instrument[2] price = instrument_...
<python><mysql><database-deadlocks>
2022-12-14 18:20:50
0
15,089
Volatil3
74,802,535
3,450,163
Implementing a complex custom function row by row using rolling and apply
<p>I have a dataframe as below:</p> <pre><code>my_dict = { 'id': [1, 2, 3, 4, 5], 'salary': [100, 200, 300, 400, 500], 'location_vector' : [[1, 2, 3], [2, 3, 4], [2, 3, 5], [4, 5, 4], [7, 5, 4]] } df = pd.DataFrame(my_dict) id salary location_vector 0 1 100 [1, 2, 3] 1 2 200 [2, 3, 4...
<python><pandas>
2022-12-14 18:04:35
1
3,097
GoGo
74,802,448
12,621,824
Client that communicates with multiple servers concurrently
<p>I am trying to learn multithreading programming with Python and specifically I am trying to build a programm that 1 Client sends data to multiple servers and get some messages back. In the first version of my programm I want my client to communicate back and forth with each server that I have spawned with each threa...
<python><multithreading><sockets><client-server><python-multithreading>
2022-12-14 17:56:40
0
529
C96
74,802,368
3,868,474
PySpark join DataFrames multiple columns dynamically ('or' operator)
<p>I have a scenario where I need to dynamically join two DataFrames. I am creating a helper function and passing DataFrames as input parameters like this.</p> <pre><code>def joinDataFrame(first_df, second_df, first_cols, second_cols,join_type) -&gt; DataFrame: return_df = first_df.join(second_df, (col(f) == col(s) ...
<python><dataframe><pyspark><dynamic><apache-spark-sql>
2022-12-14 17:49:31
1
555
Prakash
74,802,248
12,193,952
After changing column type to string, hours, minutes and seconds are missing from the date
<p>I am have a dataframe loaded from a file containing a time series and values</p> <pre class="lang-py prettyprint-override"><code> datetime value_a 0 2019-08-19 00:00:00 194.32000000 1 2019-08-20 00:00:00 202.24000000 2 2019-08-21 00:00:00 196.55000000 3 2019-08-22 00:00:00 1...
<python><pandas><dataframe><datetime>
2022-12-14 17:38:41
2
873
FN_
74,802,237
6,322,924
matplotlib quiver weird plot
<p>I am trying to make simple quiver plot, with 4 points in xy plane which roughly form square, and 4 shifted points which form smaller, inner square. But my arrows are weird. What am I doing wrong?</p> <pre><code>p_x = np.array([1,10,10,1]).reshape(-1,1) p_y = np.array([1,1,10,10]).reshape(-1,1) corr_x = np.array([2,9...
<python><matplotlib>
2022-12-14 17:37:34
1
607
Falco Peregrinus
74,802,223
4,551,325
Pandas resample().apply() with custom function very slow
<p>I have a pandas Series in business-day frequency, and I want to resample it to weekly frequency where I take the product of those 5 days in a week.</p> <p>Some dummy data:</p> <pre><code>dates = pd.bdate_range('2000-01-01', '2022-12-31') s = pd.Series(np.random.uniform(size=len(dates)), index=dates) # randomly assi...
<python><pandas><numpy><apply><resample>
2022-12-14 17:36:28
1
1,755
data-monkey
74,802,101
17,696,880
Set alphanumeric regex pattern not accepting certain specific symbols
<pre class="lang-py prettyprint-override"><code>import re #Examples: input_text = &quot;Recien el 2021-10-12 despues de 3 dias 2021-10-12&quot; #NOT PASS input_text = &quot;Recien el 2021-10-12 hsah555sahsdhj. Ya despues de 3 dias hjsdfhjdsfhjdsf 2021-10-12&quot; #NOT PASS input_text = &quot;Recien el 2021-10-12 hsah5...
<python><python-3.x><regex><string><regex-group>
2022-12-14 17:25:29
1
875
Matt095
74,802,041
3,826,115
How to plot two GeoDataFrames with one legend in Python
<p>I have the following code:</p> <pre><code>import geopandas as gpd import matplotlib.pyplot as plt states_gdf = gpd.read_file('https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_state_5m.zip') CO_gdf = states_gdf[states_gdf['STUSPS'] == 'CO'] fig, ax = plt.subplots() CO_gdf.plot(ax = ax, column = 'STUSPS') C...
<python><matplotlib><legend><geopandas>
2022-12-14 17:20:43
0
1,533
hm8
74,802,016
1,892,584
How do I stop pdb from hiding tracebacks at the shell?
<p>If you execute a statement that results in an exception in pdb you get the exception but the traceback for the exception is hidden.</p> <p>Is there a way of getting pdb to output the exception?</p> <p>Unfortunately neither <code>sys.exc_info()</code> or <code>!sys.exc_info</code> seems to contain the exception for ...
<python><pdb>
2022-12-14 17:18:36
0
1,947
Att Righ
74,801,747
558,639
Laminating two column arrays
<p>Assume I have two numpy (N, 1) column arrays. I know their length to be equal:</p> <pre><code>&gt;&gt;&gt; a array([[0.], [2.], [4.], [6.]]) &gt;&gt;&gt; b array([[0.], [1.], [2.], [3.]]) </code></pre> <p>and I'd like to &quot;laminate&quot; them side by side to form an (N,...
<python><numpy><numpy-ndarray>
2022-12-14 16:57:23
1
35,607
fearless_fool
74,801,490
11,894,831
Get Ublock Origin logger datas using Python and selenium
<p>I'd like to know the number of blocked trackers detected by Ublock Origin using Python (running on linux server, so no GUI) and Selenium (with firefox driver). I don't necessarly need to really block them but i need to know how much there are.</p> <p>Ublock Origin has a logger (<a href="https://github.com/gorhill/uB...
<python><selenium-webdriver><selenium-firefoxdriver><ublock-origin>
2022-12-14 16:37:35
1
475
8oris
74,801,447
12,979,993
How to pprint custom collection
<p>I am not able to simulate pprint on my custom collections.<br /> See the following behaviour:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt;from pprint import * &gt;&gt;&gt;pprint([&quot;x&quot;*80]*4) ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxx...
<python><abc><pprint>
2022-12-14 16:34:39
1
895
BorjaEst
74,801,365
10,309,712
Stacking ensemble of classifiers in a chain
<p>I have the following human activity recognition sample dataset:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( { 'mean_speed': [40.01, 3.1, 2.88, 20.89, 5.82, 40.01, 33.1, 40.88, 20.89, 5.82, 40.018, 23.1], 'max_speed': [70.11, 6.71, 7.08, 39.63, 6.68, 70.11, 65.71, 71.08, 39.63, 13...
<python><machine-learning><scikit-learn><classification><supervised-learning>
2022-12-14 16:28:56
1
4,093
arilwan
74,801,357
3,937,811
How to connect a Twilio number to a Twilio flow
<p>I am working on a project to connect a phone number to a Twilio flow project. I've created a flow and I've added a number the flow does not work.</p> <p><a href="https://i.sstatic.net/688fV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/688fV.png" alt="enter image description here" /></a></p> <p><a h...
<python><twilio>
2022-12-14 16:28:28
1
2,066
Evan Gertis
74,801,343
805,357
Python dateutils relativedelta incorrect result when starting with 30 day month
<p>I'm trying to create some date recurrence rules. Based on the issues with <code>dateutil</code> noted <a href="https://stackoverflow.com/questions/38328313/dateutils-rrule-returns-dates-that-2-months-apart">here</a> and <a href="https://github.com/dateutil/dateutil/issues/149" rel="nofollow noreferrer">here</a> I am...
<python><python-dateutil><relativedelta>
2022-12-14 16:27:30
1
2,085
deepak
74,801,333
166,723
Spyder not terminating tkinkter mainloop()
<p>I am starting with python and I'm using Spyder 3.9.13 with Python 3.9</p> <p>When beginning with the GUI design I have run in one problem: Spyder runs the script just once and jams in infinite loop.</p> <p>Code that fails:</p> <pre><code>import tkinter as TK ws=TK.Tk() print('Foo') ws.mainloop() print('Bar') </code>...
<python><tkinter><spyder>
2022-12-14 16:26:24
1
2,341
Crowley
74,801,291
2,321,195
How do I parse multi-line logs when I have some regex for individual lines?
<p>I have newline-delimited logs that look like this:</p> <pre><code>Unimportant unimportant Some THREAD-123 blah blah blah patternA blah blah blah Unimportant unimportant More THREAD-123 blah blah blah patternB blah blah blah Unimportant unimportant Unimportant unimportant Outbound XML distinctive doctype tag Unimport...
<python><powershell><sh><logparser>
2022-12-14 16:23:38
1
401
k..
74,801,254
9,274,940
pandas aggregate items as list and filter based on legth
<p>Let me show with an example, I have this dataframe:</p> <p><a href="https://i.sstatic.net/2Qz3E.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2Qz3E.png" alt="enter image description here" /></a></p> <p>I want to end up with to this dataframe: (so I group by &quot;column_1&quot; and &quot;last_column...
<python><pandas><dataframe><group-by>
2022-12-14 16:20:36
2
551
Tonino Fernandez
74,800,989
10,197,418
How to add a numeric seconds column (or duration) to a datetime in Polars?
<p>I want to add a duration in seconds to a date/time. My data looks like</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( { &quot;dt&quot;: [ &quot;2022-12-14T00:00:00&quot;, &quot;2022-12-14T00:00:00&quot;, &quot;2022-12-14T00:00:00&quot;, ], ...
<python><dataframe><datetime><python-polars><timedelta>
2022-12-14 16:00:48
1
26,076
FObersteiner
74,800,807
6,045,509
Why isn't boto3 (AWS) using ~/.aws/credentials?
<p>My issue is AWS boto3 package, authorization, python.</p> <p>Referencing to <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html" rel="nofollow noreferrer">https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html</a> section: &quot;Configuring credentials&quot...
<python><amazon-web-services><boto3>
2022-12-14 15:47:06
1
361
harry hartmann
74,800,793
2,836,172
Find the lowest value index in a numpy array per column plus value
<p>This is quite easy:</p> <pre><code>import numpy as np np.random.seed(2341) data = (np.random.rand(3,4) * 100).astype(int) </code></pre> <p>so I have</p> <pre><code>[[35 20 47 39] [ 6 17 77 85] [ 8 25 2 3]] </code></pre> <p>Great, now lets get the indices of the smallest values per row:</p> <pre><code>kmin = np.a...
<python><numpy>
2022-12-14 15:46:16
1
1,522
Standard
74,800,749
6,119,375
pass custom scaling operation in python
<p>i am following an example of the <a href="https://github.com/google/lightweight_mmm" rel="nofollow noreferrer">https://github.com/google/lightweight_mmm</a> but instead of using the default setting for scalars, which is mean:</p> <pre><code>media_scaler = preprocessing.CustomScaler(divide_operation=jnp.mean) </code>...
<python><function><lambda><mean>
2022-12-14 15:43:24
1
1,890
Nneka
74,800,656
5,137,645
pytorch weighted MSE loss
<p>I wanted to apply a weighted MSE to my pytorch model, but I ran into some spots where I do not know how to adapt it correctly. The original lines of code are:</p> <pre><code>self.mse_criterion = torch.nn.MSELoss(reduction='none') loss_mot_rec = self.mse_criterion(self.fake_noise, self.real_noise).mean(dim=-1) def t...
<python><pytorch>
2022-12-14 15:36:11
1
606
Nikita Belooussov
74,800,580
330,867
Celery pool parameter ignored in setup_defaults?
<p>I have a script that run the Celery Worker like this:</p> <pre><code>if __name__ == '__main__': worker = celery.Worker() worker.setup_defaults( loglevel=logging.INFO, pool='eventlet', concurrency=500 ) worker.start() </code></pre> <p>This launches C...
<python><celery><pool>
2022-12-14 15:30:43
1
40,087
Cyril N.
74,800,210
7,713,770
Comparing two lists with each other and color the difference with django
<p>I have a django application. And I try to mark the difference values in the lists red in the template.</p> <p>So I have some methods with lists inside. Because in the real situation. You can upload a pdf and excel file. But this is just for testing. So that I can use it in the real situation. But the idea is the sam...
<python><django>
2022-12-14 15:01:57
2
3,991
mightycode Newton
74,800,045
5,675,325
Extend social pipeline and prevent a specific function to run during tests
<p>I'm using <a href="https://python-social-auth.readthedocs.io/en/latest/configuration/django.html" rel="nofollow noreferrer">Python Django Social Auth</a> and extended the pipeline with the following three steps</p> <ol> <li>One before the user is created (<a href="https://python-social-auth.readthedocs.io/en/latest/...
<python><django><authentication><django-testing><python-social-auth>
2022-12-14 14:49:24
1
15,859
Tiago Peres
74,799,995
1,522,342
Flake8: how to select all lints
<p>According to: <a href="https://flake8.pycqa.org/en/6.0.0/user/options.html#cmdoption-flake8-select" rel="nofollow noreferrer">https://flake8.pycqa.org/en/6.0.0/user/options.html#cmdoption-flake8-select</a></p> <blockquote> <p>--select=&lt;errors&gt;</p> <p>Specify the list of error codes you wish Flake8 to report. S...
<python><lint><flake8>
2022-12-14 14:45:15
2
2,453
iuridiniz
74,799,751
5,917,999
How bind my predictions trained on a subset, back to the original DF?
<p>I am making predictions on a feature engineered training set, without any identification key. How can I merge my predictions back to the original df?</p> <p>Original_DF</p> <pre><code>ID. ColumnB. ColumnC. ColumnD. Target A 2 3 1 8 B 2 3 1 ...
<python><pandas><scikit-learn>
2022-12-14 14:26:12
1
1,346
R overflow
74,799,676
2,146,894
How to run a "hello world" python script with Google Cloud Run
<p>Forgive my ignorance..</p> <p>I'm trying to learn how to schedule python scripts with Google Cloud. After a bit of research, I've seen many people suggest Docker + <a href="https://cloud.google.com/run" rel="nofollow noreferrer">Google Cloud Run</a> + <a href="https://cloud.google.com/scheduler" rel="nofollow norefe...
<python><docker><google-cloud-run>
2022-12-14 14:20:56
2
21,881
Ben
74,799,672
5,535,747
SQLAlchemy Joining 2 CTE Results in Ambiguous ON Clause
<p>I'm attempting retrieve a max version for either a published version or, if a resource has no published versions, the highest version. I'm using 3 CTE to find these values, one to get the max version that is published, a second to get the max version overall, and lastly a third to do an outer join which produces the...
<python><postgresql><sqlalchemy>
2022-12-14 14:20:32
2
301
BusinessFawn
74,799,642
3,805,467
sqlalchemy filter on date + offset
<p>what I try to do is to create a query that finds all records where a date is greater than today - days_before_activation.</p> <p>For this I use a @hybrid_property that shows the correct start_day (today - days_before_activation).</p> <p>The issue is, that timedelta does not work in filter queries, at least with sqll...
<python><sqlalchemy>
2022-12-14 14:18:19
1
1,355
shalama
74,799,588
5,877,122
Insert a text transformation between open and json.load
<p>I actually do the following code:</p> <pre><code> with open(filename) as f: data = json.load(f) </code></pre> <p>I need to transform the content with some string replacements on the fly. So something like:</p> <pre><code> def repair(???): # The function to write with at least a call of string or byt...
<python>
2022-12-14 14:12:51
1
3,495
Benjamin
74,799,408
493,080
Why doesn't Pandas use the same memory block for reading into the same Dataframe?
<p>I read a big CSV file into a Dataframe in a Jupyter notebook with:</p> <pre><code>df = pd.read_csv(my_file) df.info() &gt; memory usage: 10.7+ GB </code></pre> <p>When I execute the same cell again, the total memory usage of my system increases. And after I repeat a few times, Jupyter kernel eventually dies.</p> <p...
<python><pandas><jupyter>
2022-12-14 13:59:32
1
3,915
mustafa
74,799,224
11,261,546
Import elements from multiple submodules
<p>I have a python project with a package, where the tree looks like this:</p> <pre><code>my_package ├── __init__.py ├── A.py └── B.py </code></pre> <p>I would like to call several objects from <code>A</code> and <code>B</code> at once (from different files in the same command), is something &quot;like&quot; this posib...
<python><module><package>
2022-12-14 13:45:24
0
1,551
Ivan
74,799,058
12,301,726
Bigquery import asks for pyparsing in shell run
<p>I get this error <strong>&quot;ImportError: The 'pyparsing' package is required&quot;</strong> after trying to run .py file with <code>from google.cloud import bigquery</code> line. Import was working before and is still working in the Jupyter Notebook or in Ipython.</p> <p>I looked at existing options here and tri...
<python><google-bigquery><setuptools><pyparsing>
2022-12-14 13:32:55
1
1,250
poloniki
74,798,991
11,809,811
Creating a responsive layout, avoid infinite Configure loop
<p>I am trying to create a responsive layout where the content of the app changes depending on the width of the window (basically like any website works). The code I have so far is this:</p> <pre><code>import tkinter as tk from tkinter import ttk class App(tk.Tk): def __init__(self, start_size, min_size): ...
<python><tkinter>
2022-12-14 13:26:32
1
830
Another_coder
74,798,878
8,761,554
Code a tensor view layer in nn.sequential
<p>I have a <code>sequential</code> container and inside I want to use the <code>Tensor.view</code> function. Thus my current solution looks like this:</p> <pre><code>class Reshape(nn.Module): def __init__(self, *args): super().__init__() self.my_shape = args def forward(self, x): retur...
<python><machine-learning><pytorch><autoencoder>
2022-12-14 13:17:03
1
341
Sam333
74,798,874
4,792,229
Nano Jetson Jetpack 4.6.1 can't install right h5py version?
<p>I have a Nano Jetson and flashed it with the latest available Jetpack version from here: <a href="https://developer.nvidia.com/embedded/learn/get-started-jetson-nano-devkit" rel="nofollow noreferrer">https://developer.nvidia.com/embedded/learn/get-started-jetson-nano-devkit</a> which is 4.6.1. Now when following thi...
<python><tensorflow><nvidia>
2022-12-14 13:16:55
1
3,002
Hakaishin
74,798,728
7,383,799
Python multi-processing cannot imported module
<p>I am testing toy code to parallelize a process using python's <code>multiprocess</code>. The code works on my home computer but when I migrated it to a remote server I am working on it returns an error.</p> <p>I first define functions in <code>defs.py</code></p> <pre><code>import numpy as np def g(n): A = np.ra...
<python><python-3.x><multiprocessing><python-multiprocessing>
2022-12-14 13:03:45
3
375
eigenvector
74,798,626
1,564,730
Why is log(inf + inf j) equal to (inf + 0.785398 j), In C++/Python/NumPy?
<p>I've been finding a strange behaviour of <code>log</code> functions in C++ and numpy about the behaviour of <code>log</code> function handling complex infinite numbers. Specifically, <code>log(inf + inf * 1j)</code> equals <code>(inf + 0.785398j)</code> when I expect it to be <code>(inf + nan * 1j)</code>.</p> <p>Wh...
<python><c++><numpy><complex-numbers><infinity>
2022-12-14 12:54:40
3
948
Firman
74,798,423
9,274,940
when grouping dataframe join the values that are different for a certain column
<p>I'm first going to show with an example what I mean:</p> <p>Let's suppose that I have this dataframe:</p> <p><a href="https://i.sstatic.net/kuB5S.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kuB5S.png" alt="enter image description here" /></a></p> <p>If I group the dataframe <strong>without</strong...
<python><pandas><dataframe><group-by>
2022-12-14 12:36:28
1
551
Tonino Fernandez
74,798,302
7,556,450
Using cattrs / attrs where attr name does not match keys to create an object
<p>I am looking at moving to cattrs / attrs from a completely manual process of typing out all my classes but need some help understanding how to achieve the following.</p> <p>This is a single example but the data returned will be varied and sometimes not with all the fields populated.</p> <pre><code>data = { &quot;d...
<python><python-3.x><python-attrs>
2022-12-14 12:28:12
1
1,019
SimonT
74,798,155
14,366,906
Drawing line through two points, instead of between (on a log scale, but still a straight line)
<p>I am currently working on a Python API responsible for plotting diagrams and tangents made in a Front-end application using Angular. In this application it is possible to move points to adjust the a line perpendicular to the curve.</p> <p>When the user thinks this is the way it is supposed to be the diagrams can be ...
<python><matplotlib>
2022-12-14 12:16:38
1
335
Wessel van Leeuwen
74,798,130
19,580,067
Remove characters other than alphanumeric from first 4 values of string Python
<p>I need to remove characters other than alphanumeric from first 4 characters of string. I figured out how to do it for the whole string but not sure how to process only the first 4 values.</p> <pre><code>Data : '1/5AN 4/41 45' Expected: '15AN 4/41 45' </code></pre> <p>Here is the code to remove the non-alphanumeric ...
<python><python-3.x><regex>
2022-12-14 12:14:40
3
359
Pravin
74,798,015
11,622,712
TypeError: StructType can not accept object '1/1/2021 1:00:00 AM' in type
<p>I want to create a simple dataframe in PySpark. This datframe should contain a timestamp string &quot;1/1/2021 1:00:00 AM&quot; that later I want to convert from string into timestamp.</p> <p>This is my current code. When I run it, I get the error &quot;TypeError: StructType can not accept object '1/1/2021 1:00:00 A...
<python><python-3.x><pyspark>
2022-12-14 12:03:32
1
2,998
Fluxy
74,798,004
13,498,838
How can I filter a Pandas DataFrame based on whether all aggregated values in a column are True?
<p>I have the following data</p> <pre><code>data = [ [1, True], [1, True], [1, True], [1, True], [2, True], [2, False], [2, True], [3, True], [3, True], [3, True], [3, True], [4, True], [4, True], [4, False], [5, True], [5, True], [5, True], [5...
<python><pandas><dataframe>
2022-12-14 12:02:44
2
1,454
jda5
74,797,963
219,976
Django + Celery task never done
<p>I'm trying to run the example app Django+Celery from official celery repository:<br /> <a href="https://github.com/celery/celery/tree/master/examples/django" rel="nofollow noreferrer">https://github.com/celery/celery/tree/master/examples/django</a><br /> I cloned the repo, ran RabbitMQ in my docker container:</p> <p...
<python><django><rabbitmq><celery><django-celery>
2022-12-14 11:59:27
1
6,657
StuffHappens
74,797,790
11,167,163
How to display labels,values and percentage on a pie chart
<p>I tri to display on a pie chart :</p> <ol> <li>labels</li> <li>Value</li> <li>Percentage</li> </ol> <p>I know how to do to display both the value and the percentage :</p> <pre><code>def autopct_format(values): def my_format(pct): total = sum(values) val = int(round(pct*total/100.0)/1000000) ...
<python><matplotlib>
2022-12-14 11:45:56
1
4,464
TourEiffel
74,797,737
3,521,180
what would be the simplest way to get the value based on some comparison in pyspark?
<p>I'm playing around with some acceptance criteria and one of the requests is quite simple where I need to return the sum value of a column when the value of another column equals: <code>xycvg</code>.</p> <p>I've written this bit of code and was just wondering: Is there a simpler way of doing this?</p> <pre><code>df.g...
<python><sql><pyspark>
2022-12-14 11:40:54
1
1,150
user3521180
74,797,716
5,586,359
How do I get FastAPI to do SSR for Vue 3?
<p>According to this documentation for <a href="https://vuejs.org/guide/scaling-up/ssr.html#basic-tutorial" rel="nofollow noreferrer">Vue's SSR</a>, it is possible to use node.js to render an app and return it using an express server. Is is possible to do the same with FastAPI?</p> <p>Or is using <a href="https://jinja...
<python><vue.js><jinja2><fastapi><server-side-rendering>
2022-12-14 11:38:49
1
954
Vivek Joshy
74,797,697
15,893,581
python - how to Interpolate NaN values
<p>Is there a way to interpolate Nan values of P &amp; C in final_df (where str is a range with equal step) ??</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df0 = pd.DataFrame({'str': [var for var in range(700,1260,5)]}) print(df0) df1 = pd.DataFrame({'str': [700,705,710,715,72...
<python><pandas><interpolation>
2022-12-14 11:36:33
1
645
JeeyCi
74,797,692
8,916,474
Tox and pre-commit hook "error: unrecognized arguments" or not running test envs
<p>Everything is inside a docker container. Tox works fine separately inside docker. What I'm trying to do is to add Tox to the pre-commit hook to run it for files with changes to be committed.</p> <p><strong>.pre-commit-config.yaml</strong></p> <pre><code>- repo: local hooks: - id: tox-project name...
<python><githooks><pre-commit-hook><tox><pre-commit.com>
2022-12-14 11:36:08
0
504
QbS
74,797,663
20,732,098
Convert timedelta to milliseconds python
<p>I have the following time:</p> <pre class="lang-py prettyprint-override"><code>time = datetime.timedelta(days=1, hours=4, minutes=5, seconds=33, milliseconds=623) </code></pre> <p>Is it possible, to convert the time in milliseconds? <br> Like this:</p> <pre class="lang-py prettyprint-override"><code>101133623.0 </co...
<python><timestamp><timedelta>
2022-12-14 11:34:37
3
336
ranqnova
74,797,581
12,493,545
Understanding OpenCV's drawing calls: Are those lines of code irrelevant?
<p>Source: <a href="https://docs.opencv.org/4.x/d1/dc5/tutorial_background_subtraction.html" rel="nofollow noreferrer">https://docs.opencv.org/4.x/d1/dc5/tutorial_background_subtraction.html</a></p> <p>In that tutorial the lines of code:</p> <pre><code>cv.rectangle(frame, (10, 2), (100,20), (255,255,255), -1) cv.putTex...
<python><opencv>
2022-12-14 11:28:30
1
1,133
Natan
74,797,565
1,150,683
XPath on lxml's iterparse matches elements outside its scope
<p>I have huge corpora that I am parsing with <code>lxml</code>, so I am using <code>iterparse</code> which makes it easy to read XML on-the-fly. By using <code>iterparse(fh, tag=&quot;your_tag&quot;)</code> we can efficiently iterate over nodes in large files.</p> <p>I wish to do some XPath matching for each major tag...
<python><xml><xpath><lxml><xpath-1.0>
2022-12-14 11:27:10
1
28,776
Bram Vanroy
74,797,238
7,713,770
How to print list vertical and not horizaontal with tabulate package?
<p>I try to print the results of a list vertical. But they are at the moment display horizontal.</p> <p>So I try it as code:</p> <pre><code>def extract_data_excel_combined(self): dict_fruit = {&quot;Watermeloen&quot;: 3588.20, &quot;Appel&quot;: 5018.75, &quot;Sinaasappel&quot;: 3488.16} fruit_list = li...
<python><tabulate>
2022-12-14 11:03:38
1
3,991
mightycode Newton
74,796,978
6,708,782
Webscraping all available repos from a topic search on github
<p>I'm trying to create a dataframe from a webscraping. Precisely: from a search of a topic on github, the objective is to retrieve the <strong>name</strong> of the owner of the repo, the <strong>link</strong> and the <strong>about</strong>.</p> <p>I have many problems.</p> <p><strong>1.</strong> The search shows that ...
<python><web-scraping><beautifulsoup><request>
2022-12-14 10:43:16
1
602
ladybug
74,796,947
9,749,124
How to extract RSS links from website with Python
<p>I am trying to extract all RSS feed links from some websites. Ofc if RSS exists. These are some website links that have RSS, and below is list of RSS links from those websites.</p> <pre><code>website_links = [&quot;https://www.diepresse.com/&quot;, &quot;https://www.sueddeutsche.de/&quot;, &quot;https://www.berlin...
<python><web-scraping><beautifulsoup><rss>
2022-12-14 10:40:31
2
3,923
taga
74,796,781
19,502,111
Python json to object from model
<p>I know this looks like Frequency Ask Question mainly this question: <a href="https://stackoverflow.com/questions/6578986/how-to-convert-json-data-into-a-python-object">How to convert JSON data into a Python object?</a></p> <p>I will mention most voted answer:</p> <pre><code>import json from types import SimpleNamesp...
<python><json><object><model>
2022-12-14 10:25:37
1
353
Citra Dewi
74,796,775
9,919,423
How to update an object's method in python
<p>Say I have a class and an object of it.</p> <p>In Python, you can update the behavior of an object's method by re-assigning the method to a new function. This is possible because methods in Python are just attributes of an object that happen to be functions. Here's an example of how you can do this:</p> <pre><code>c...
<python><object><methods><reassign>
2022-12-14 10:24:35
0
412
David H. J.