QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,255,983
19,336,534
Weird behaviour in tensorflow metric
<p>I have created a tensorflow metric as seen below:</p> <pre><code>def AttackAcc(y_true, y_pred): r = tf.random.uniform(shape=(), minval=0, maxval=11, dtype=tf.int32) if tf.math.greater(r,tf.constant(5) ): return tf.math.equal( tf.constant(0.6) , tf.constant(0.2) ) else: return tf.math.equal( ...
<python><python-3.x><tensorflow><tensorflow2.0>
2023-01-27 09:08:29
1
551
Los
75,255,653
940,208
Discriminated union in Python
<p>Imagine I have a base class and two derived classes. I also have a factory method, that returns an object of one of the classes. The problem is, mypy or IntelliJ can't figure out which type the object is. They know it can be both, but not which one exactly. Is there any way I can help mypy/IntelliJ to figure this ou...
<python><pycharm><python-typing><mypy><discriminated-union>
2023-01-27 08:32:58
2
17,398
mnowotka
75,255,520
17,788,573
WinError 10060- A connection attempt failed because the connected party did not properly respond after a period of time
<p>I'm trying a tutorial of spaCy(NLP) and when I try to pip install the requirements(as mentioned in the spacy website), I'm getting this error. Can anybody please tell me what I'm doing wrong? The same error showed up while installing NLTK as well(figured spaCy would work but the same error pops up again).</p> <p>I'v...
<python><machine-learning><nlp><nltk><spacy>
2023-01-27 08:18:25
0
311
Vaikruta
75,255,453
10,729,772
Convert the output of protoc --decode_raw into json
<p>I'm trying to convert the message of a protobuf blob into a json, without the corresponding schema. This is the code I'm using but it doesn't get nested objects. Maybe there is a way to convert blobs without the schema? I just need a json. The variable names don't matter to me.</p> <pre><code>message_dict = {} for l...
<python><protocol-buffers><grpc>
2023-01-27 08:10:43
2
468
Georg K.
75,255,445
12,940,363
Streams data from multiple while loops
<p>I am using psutil to analyze the open_files() at any given point of time. As soon as program creates a file with a specific extension of interest (could be .xlsx, .csv, .docx, .dat), I want to save the file in another directory before it is modified and then perform sequential operations on it.</p> <p>Right now I am...
<python><python-multiprocessing><psutil>
2023-01-27 08:09:52
1
327
RealRK
75,255,070
15,781,591
How to groupby multiple columns in dataframe, except one in python
<p>I have the following dataframe:</p> <pre><code> ID Code Color Value ----------------------------------- 0 111 AAA Blue 23 1 111 AAA Red 43 2 111 AAA Green 4 3 121 ABA Green 45 4 121 ABA Green 23 5 121 ABA R...
<python><pandas>
2023-01-27 07:18:24
1
641
LostinSpatialAnalysis
75,254,841
18,125,194
Define which neighbours a Ball tree should return
<p>I have a dataframe with several locations. I want to find each locations nearest neighbours.</p> <p>To do this, I am using a Ball tree. However, the output seems to be comparing all of the locations with each other, including the original location. For example, I have locations A,B,C..... the output will list A as a...
<python><pandas><scikit-learn><nearest-neighbor>
2023-01-27 06:48:39
1
395
Rebecca James
75,254,838
10,694,247
Dynamodb lambda function Error Missing required parameter in AttributeDefinitions[0]
<p>I am working with AWS Lambda Function and want to integrate them with Dynamo-db to keep the track of my cloudwatch data matrix into it in order to keep track of alerts for sending messages if alerts are sent or not to record in DB.</p> <p>The function is perfectly fine if I don't use Dynamo-DB, below is the code wit...
<python><aws-lambda><amazon-dynamodb>
2023-01-27 06:48:21
1
488
user2023
75,254,698
5,807,808
Pass dataframe column values as String in dbduck sql query using loop
<p>I am using dbduck to run sql query on the following dataframe <code>df</code>:</p> <p><a href="https://i.sstatic.net/iII8h.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iII8h.png" alt="enter image description here" /></a></p> <p>In this sql, I need to pass the values from dataframe col3 using a loop...
<python><pandas><dataframe>
2023-01-27 06:24:22
1
401
peter
75,254,643
6,212,530
Why are TypedDict types without field and with NotRequired field incompatible?
<p>I am trying to create a few functions which will return values of different TypedDict types. Most of fields in them will be same so I want to generate base dictionary with same function in all cases. However I am getting stumped by typing this correctly.</p> <p>My idea was to create base type <code>Parent</code> and...
<python><mypy><python-typing><python-3.10><pylance>
2023-01-27 06:14:13
1
1,028
Matija Sirk
75,254,591
317,797
Create Altair Chart of Value Counts of Multiple Columns
<p>Using Altair charting, how can I create a chart of value_counts() of multiple columns? This is easily done by matplotlib. How can the identical chart be created using Altair?</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({'Col1':[0,1,2,3], 'Col2':[0,1,2,2], ...
<python><bar-chart><altair>
2023-01-27 06:04:33
1
9,061
BSalita
75,254,524
3,713,236
Preserve original column name in pd.get_dummies()
<p>I have a list of columns whose values are all strings. I need to one hot encode them with <code>pd.get_dummies()</code>.</p> <p>I want to keep the original name of those columns along with the value. So lets say I have a column named <code>Street</code>, and its values are <code>Paved</code> and <code>Not Paved</cod...
<python><pandas><dataframe>
2023-01-27 05:53:28
1
9,075
Katsu
75,254,325
2,989,642
shutil.move() not working after reading object with pywin32
<p>I've got a script that is intended to sort my photo/video collection (Windows). The photos work fine as they are sortable by EXIF which is easily accessed.</p> <p>Videos are harder because I have to get the file's &quot;Media Creation Date&quot; which is readable by only pywin32, to my understanding. However, once...
<python><windows><pywin32><shutil>
2023-01-27 05:17:11
1
549
auslander
75,254,132
14,808,637
Why is numpy.where() returning 2 arrays?
<p>I am confused with <code>numpy</code> function <code>np.where()</code>. For example if we have:</p> <pre><code>b = np.array([[1, 2, 3, 4, 5,6], [1,0,3,0,9,6]]) f = np.where(b) </code></pre> <p><strong>output</strong></p> <pre><code>print(f) (array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]), array([0, 1, 2, 3, 4, 5, 0, 2, 4, 5]...
<python><arrays><numpy>
2023-01-27 04:38:36
2
774
Ahmad
75,254,131
2,397,119
Unable to Click to next page while crawling selenium
<p>I'm trying to scrap the list of services we have for us from <a href="https://www.tamm.abudhabi/en/life-events/individual/HousingProperties" rel="nofollow noreferrer">this site</a> but not able to click to the next page.<br /> This is what I've tried so far using selenium &amp; bs4,</p> <pre class="lang-py prettypri...
<python><selenium><selenium-webdriver><web-scraping><webdriverwait>
2023-01-27 04:38:21
1
1,241
Aman Singh
75,254,029
11,803,187
Create new dataframe fields from row calculations
<p>I'd like to create some new columns based on calculation from each row values</p> <p>For example, input</p> <pre><code>data = {&quot;c1&quot;: [10], &quot;c2&quot;: [20], &quot;c3&quot;:[30], &quot;c4&quot;:[40], &quot;c5&quot;:[50], &quot;c6&quot;:[10]} df = pd.DataFrame(data=data) </code></pre> <p>Let us say we ta...
<python><pandas><dataframe>
2023-01-27 04:14:39
1
547
tudou
75,254,024
11,998,382
Expression that returns mutated list
<p>I'm looking for a single expression, mutates an element and returns the modified list</p> <p>The following is a bit verbose</p> <pre><code># key=0; value=3; rng=[1,2] [(v if i != key else value) for i, v in enumerate(rng)] </code></pre> <hr /> <p><strong>Edit</strong>:</p> <p>I'm looking for a way to inline the foll...
<python><functional-programming><python-3.8><python-assignment-expression>
2023-01-27 04:13:48
3
3,685
Tom Huntington
75,253,943
12,574,341
Selenium wait for presence of nested element query
<p>In Selenium you can wait for a DOM element to load using <code>WebDriverWait</code> and <code>EC.presence_of_element()</code></p> <pre class="lang-py prettyprint-override"><code>WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.TAG_NAME, 'button'))) </code></pre> <p>However, this queries the ent...
<python><selenium>
2023-01-27 03:57:52
1
1,459
Michael Moreno
75,253,893
19,980,284
Find overlapping time intervals based on condition in another column pandas
<p>I have cleaned up a data set to get it into this format. The <code>assigned_pat_loc</code> represents a room number, so I am trying to identify when two different patients (<code>patient_id</code>) are in the same room at the same time; i.e., overlapping <code>start_time</code> and <code>end_time</code> between rows...
<python><pandas><dataframe><group-by><overlap>
2023-01-27 03:47:28
2
671
hulio_entredas
75,253,793
16,971,617
Is global variable static in python
<p>This is my utils.py</p> <pre><code>detector = cv2.mcc.CCheckerDetector_create() def process(): print(detector) </code></pre> <p>main.py</p> <pre><code>for i in range(100): process() </code></pre> <p>This question might sound stupid. As the variable detector in process() is initiated everytime I call process()...
<python><variables>
2023-01-27 03:22:25
1
539
user16971617
75,253,751
169,992
How to draw a line in the Poincaré disk using geoopt for Python?
<p>I am trying to learn the API to geoopt and Python at once, but have this example so far:</p> <pre><code>import geoopt import torch import matplotlib.pyplot as plt # Create the Poincare ball model poincare = geoopt.PoincareBall() # Define two points in the hyperbolic space point1 = torch.tensor([0.1, 0.2]) point2 =...
<python><hyperbolic-function>
2023-01-27 03:13:01
0
80,366
Lance Pollard
75,253,564
7,984,318
SQLAlchemy pass parameters with like '%STRING%' in raw sql
<p>I have a sql:</p> <pre><code>select * from my table where exists ( select from unnest(procedure) elem where elem like '%String%' ) </code></pre> <p>It works well when directly execute in database ide.</p> <p>My question is how can I set 'String' as a parameters ?</p> <p>I have tried:</p> <pre><...
<python><sql><database><sqlalchemy><flask-sqlalchemy>
2023-01-27 02:25:45
1
4,094
William
75,253,431
8,888,469
How to replace a part of column value with values from another two columns based on a condition in pandas
<p>I have a dataframe <code>df</code> as shown below. I want replace all the <code>temp_id</code>column values which are having <code>_</code>(underscore with another value which combination of numerical part of the temp_id + city+ country column values.</p> <p><strong>df</strong></p> <pre><code> temp_id c...
<python><python-3.x><pandas><regex><dataframe>
2023-01-27 01:57:30
2
933
aeapen
75,253,235
17,243,835
Scraping Dynamic Webpages w/ a date selector
<p>I am looking to use the requests module in python to scrape:</p> <pre><code>https://www.lines.com/betting/nba/odds </code></pre> <p>This site contains historical betting odds data.</p> <p>The main issues, is there is a date selector on this page, and i can not seem to find where the date value is stored. Ive tried l...
<python><http><web-scraping><request>
2023-01-27 01:15:40
1
355
drew wood
75,253,022
8,682,074
error while parsing JSON file, probally a hidden value on the JSON content
<p>I have this JSON file:</p> <p><a href="https://drive.google.com/file/d/1zh_fJJNWs9GaPnlLZ459twSubsYkzMi5/view?usp=share_link" rel="nofollow noreferrer">https://drive.google.com/file/d/1zh_fJJNWs9GaPnlLZ459twSubsYkzMi5/view?usp=share_link</a></p> <p>Looks normal at first, even using online <strong>json schema validat...
<python><node.js><json><go>
2023-01-27 00:31:37
1
2,916
John Balvin Arias
75,252,933
4,506,929
Merging several variables of an xarray.Dataset into one using a new dimension
<p>I have a Dataset with several variables that named something like <code>t1</code>, <code>t2</code>, <code>t3</code>, etc. I'm looking for a simple function to merge them all into one variable <code>t</code> through the use an extra dimension.</p> <p>Basically I want the output that I'm getting in the MWE below:</p> ...
<python><python-xarray>
2023-01-27 00:17:32
1
3,547
TomCho
75,252,878
17,724,172
string .join method confusion
<p>I tried to join a sample string in three ways, first entered by the code and then entered by user input. I got different results.</p> <p>#Why isn't the output the same for these (in python 3.10.6):</p> <pre><code>sampleString = 'Fred','you need a nap! (your mother)' ss1 = ' - '.join(sampleString) print(ss1), print(...
<python><string><join>
2023-01-27 00:06:34
2
418
gerald
75,252,853
2,706,344
Set column with different time zones as index
<p>I have a DataFrame with time values from different timezones. See here:</p> <p><a href="https://i.sstatic.net/gO3Dr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gO3Dr.png" alt="enter image description here" /></a></p> <p>The start of the data is the usual time and the second half is daylight saving...
<python><pandas>
2023-01-27 00:01:42
1
4,346
principal-ideal-domain
75,252,830
420,157
Python Swig interface for C function allocating a list of structures
<p>I'm trying to get the following C function to be exposed as a python interface.</p> <pre><code>void myfunc(struct MyStruct** list, int* size) { int n = 10; *size = n; *list = (struct MyStruct*) malloc(n * sizeof(struct MyStruct)); for (int i = 0; i &lt; n; i++) { (*list)[i].x = i; (*l...
<python><c><python-3.x><list><swig>
2023-01-26 23:57:15
2
777
Maverickgugu
75,252,747
2,339,664
Regular expression for YYYY-MM-DDTHH:MM:SS is not detecting the presence of .00Z
<p>I have the following regular expression to match the date time format:</p> <pre><code>start_time = &quot;1970-01-08T00:38:45&quot; regular_exp = '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}' import re if not re.match(regular_exp, start_time): print('error') </code></pre> <p>If I use the date/time: start_time = &quot...
<python><regex><python-re>
2023-01-26 23:38:33
0
4,917
Harry Boy
75,252,728
344,669
Python SQLAlchemy PostgreSQL find by primary key Deprecate message
<p>I use below code to find the object by primary key. Now I am getting this <code>Deprecated features detected</code> message.</p> <p>How can I re-write this query to fix the deprecated message.</p> <p><strong>Code:</strong></p> <pre><code> def find_by_id(self, obj_id): with self.session() as s: x = s.que...
<python><sqlalchemy><flask-sqlalchemy><sqlalchemy-utils>
2023-01-26 23:35:01
1
19,251
sfgroups
75,252,687
2,056,067
Avoid deeply nested function calls Pythonically
<p>I have a series of functions, where the result of one is fed into the next, plus other inputs:</p> <pre class="lang-py prettyprint-override"><code>result = function1( function2( function3( function4(x, y, z), a, b, c), d, e, f), g, h, i) </code></pre> <p>This is ugly a...
<python>
2023-01-26 23:28:08
3
8,495
A. Donda
75,252,652
344,669
Python SQLAlchemy PostgreSQL Deprecated API features
<p>I am using following code to create the function and trigger to update the <code>created_at</code> and <code>updated_at</code> fields. with upgrade of new module getting the deprecated API warning.</p> <p>How can I replace <code> engine.execute(sa.text(create_refresh_updated_at_func.format(schema=my_schema)))</code>...
<python><sqlalchemy><flask-sqlalchemy><sqlalchemy-utils>
2023-01-26 23:22:23
1
19,251
sfgroups
75,252,625
8,554,833
for loop through multiple items based on a dataframe
<p>So I have several dataframes of different widths.</p> <p>I want a for loop that will perform an operation on each dataframe's columns:</p> <p>Table 1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> </tr> </thead> <tbody> <tr> <td>Hi</td> <td>1</td> ...
<python><loops><xlsxwriter>
2023-01-26 23:16:33
2
728
David 54321
75,252,581
333,262
Flask-Babel shows translated text locally but not on production on GAE
<p>Once the app is deployed on Google AppEngine, pages show the msgid and not the translated text. I can't see any error either. But the locale seem to be ignored on GAE (see different output in debug messages below).</p> <p>Other similar questions on SO mention that sometimes is due to case sensitive folders names, or...
<python><flask><google-app-engine><flask-babel>
2023-01-26 23:11:32
1
658
Andrea
75,252,561
14,425,076
How to adapt this python script to apt installed matplotlib vs pip3 installed
<p>I have a script (MWE supplied)</p> <pre><code>import matplotlib.pyplot as plt import matplotlib s_xLocs = [864] s_yLocs = [357] s_score = [0.33915146615180547] sMax = 0.34704810474264386 for i in range(len(s_xLocs)): plt.scatter(s_xLocs[i], s_yLocs[i], c=s_score[i], s=(20*(s_score[i]+1.5)**4), cmap=&quot;plasm...
<python><python-3.x><matplotlib><plot>
2023-01-26 23:08:30
2
853
Douglas B
75,252,499
12,906,445
Proper way converting TorchScript Version to Core ML
<p>I'm trying to convert <code>PyTorch ml model</code> into <code>Core ML</code>. As shown in this <a href="https://developer.apple.com/videos/play/tech-talks/10154/" rel="nofollow noreferrer">WWDC video</a>, I first converted it to <code>TorchScript Version</code>.</p> <p>But the problem happens when converting <code>...
<python><machine-learning><pytorch><coreml><coremltools>
2023-01-26 22:57:35
0
1,002
Seungjun
75,252,374
8,354,766
Tensorflow gelu out of memory error, but not relu
<p>Gelu activation causes my model to return an OOM error when training, but when I switch to relu the problem goes away. Even if the model is doubled in size, the model with relu performs fine.</p> <pre><code>if activation==&quot;gelu&quot;: out = tfa.layers.GELU()(out) elif activation==&quot;relu&quot;: out =...
<python><tensorflow><out-of-memory><relu>
2023-01-26 22:40:52
0
488
Alberto MQ
75,252,125
1,318,266
How to create model's tables in MySQL?
<p>I'm trying to replicate a PHP/Symfony project in Python/Django as a python learning exercise. Platform = Windows 10. The expected result is that a <code>migrate</code> command will add tables related to all of the entries in <code>settings.py INSTALLED_APPS{...}</code>. Instead, the <code>migrate</code> command adds...
<python><mysql><django>
2023-01-26 22:03:21
1
4,728
geoB
75,252,015
13,231,896
How to represent SVG polygon in HTML using deffinition coming from POSTGIS ST_AsSVG function
<p>In my django app I have postgis database. I tried to get a polygon as a SVG, so I could represent that polygon in HTML using the SVG standard.</p> <p>I use the following query: SELECT ST_AsSVG(geom) from country_limit cl where cl.id=3;</p> <p>And It returned the following result:</p> <pre><code>M -85.941653 -12.2856...
<python><django><svg><postgis><geodjango>
2023-01-26 21:52:39
1
830
Ernesto Ruiz
75,251,981
6,367,971
Convert hours-minutes-seconds duration in dataframe to minutes
<p>I have a csv with a column that represents time durations of two discrete events.</p> <pre><code>Day,Duration Mon,&quot;S: 3h0s, P: 18m0s&quot; Tues,&quot;S: 3h0s, P: 18m0s&quot; Wed,&quot;S: 4h0s, P: 18m0s&quot; Thurs,&quot;S: 30h, P: 10m0s&quot; Fri,&quot;S: 15m, P: 3h0s&quot; </code></pre> <p>I want to split that...
<python><pandas><dataframe><timedelta>
2023-01-26 21:48:19
3
978
user53526356
75,251,927
539,490
Plot.ly move y_title from overlapping with subplot yaxis_title and yaxis2_title
<p>Is it possible to configure plot.ly to stop the y axis titles and subplot titles from overlapping?</p> <p><a href="https://i.sstatic.net/sTO0L.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sTO0L.png" alt="enter image description here" /></a></p> <pre class="lang-py prettyprint-override"><code>import...
<python><plotly>
2023-01-26 21:42:50
1
29,009
AJP
75,251,911
6,761,231
How to find the sklearn version of pickled model?
<p>I have a pickled sklearn model, which I need to get to run. This model, however, is trained in unknown version of sklearn.</p> <p>When I look up the model in debugger, I find that there is a bunch of strange tracebacks inside, instead of the keys you'd expect, for example:</p> <pre><code>decision_function -&gt; 'Ran...
<python><scikit-learn><pickle>
2023-01-26 21:40:59
2
303
Artur Pschybysz
75,251,874
19,916,174
Declaring and Looping over a variable in one line
<p>Just for fun, I am trying to compress a programming problem into one line. I know this is typically a bad practice, but it is a fun challenge that I am asking for your help on.</p> <p>I have a piece of code which declares the variables and in the second line which loops over a list created in the first line, until a...
<python><python-3.x><string><binary><ascii>
2023-01-26 21:36:25
1
344
Jason Grace
75,251,687
1,210,614
Python 3.9.12 build failed - generate-posix-vars failed
<p>New to python. Trying to install <code>3.9.12</code> via pyenv. Getting the following error:</p> <pre><code>pyenv install 3.9.12 python-build: use openssl@1.1 from homebrew python-build: use readline from homebrew Downloading Python-3.9.12.tar.xz... -&gt; https://www.python.org/ftp/python/3.9.12/Python-3.9.12.tar.xz...
<python><python-3.x><pyenv>
2023-01-26 21:12:33
1
10,962
jordan
75,251,635
4,414,359
'ZipExtFile' object has no attribute 'open'
<p>I have a file <code>f</code> that i pulled from a url response:</p> <p><code>&lt;zipfile.ZipExtFile name='some_data_here.csv' mode='r' compress_type=deflate&gt;</code></p> <p>But for some reason i can't do <code>f.open('some_data_here.csv')</code></p> <p>I get an error saying: <code>'ZipExtFile' object has no attrib...
<python><zip>
2023-01-26 21:07:37
1
1,727
Raksha
75,251,570
11,648,332
Can't unlock pgpy private key: NotImplementedError: <SymmetricKeyAlgorithm.Plaintext: 0>
<p>I am trying to load a pgpy private key and decrypt an encrypted text message.</p> <pre><code>Private_key_path = r&quot;/content/Private_KEY.sub&quot; privkey, _ = pgpy.PGPKey.from_file(Private_key_path) </code></pre> <p>The key and the encrypted message manage to load without problems:</p> <pre><code>file_path=r&quo...
<python><encryption><encryption-asymmetric>
2023-01-26 21:00:39
0
447
9879ypxkj
75,251,551
919,264
Several lines on the same diagram with Pandas plot() grouping
<p>I have a CSV with 3 data sets, each coresponding to a line to plot. I use Pandas <code>plot()</code> grouping to group the entries for the 3 lines. This generates 3 separate diagrams, but I would like to plot all 3 lines on the same diagram.</p> <p>The CSV:</p> <pre class="lang-none prettyprint-override"><code>sho...
<python><pandas><plot>
2023-01-26 20:58:02
3
2,327
Florent Georges
75,251,484
7,077,761
adding python binary distribution to path
<p>I am trying to get the python package <code>simms</code> to work on my computing cluster. Unfortunately there isn't much documentation. I have inside my conda env installed it via</p> <pre><code>pip install simms </code></pre> <p>I also git cloned <a href="https://github.com/ratt-ru/simms.git" rel="nofollow noreferr...
<python><installation><package>
2023-01-26 20:48:41
0
966
math_lover
75,251,349
4,876,561
Place ellipsis on seaborn catplot
<p>I have a <a href="https://seaborn.pydata.org/generated/seaborn.catplot.html" rel="nofollow noreferrer"><code>seaborn.catplot</code></a> that looks like this:</p> <p><a href="https://i.sstatic.net/vPtc6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vPtc6.png" alt="enter image description here" /></a>...
<python><matplotlib><seaborn><scatter-plot><catplot>
2023-01-26 20:31:51
1
7,351
artemis
75,251,348
11,280,068
Python selenium wait until element has text (when it didn't before)
<p>There is a div that is always present on the page but doesn't contain anything until a button is pressed.<br /> Is there a way to wait until the div contains text, when it didn't before, and then get the text?</p>
<python><selenium><xpath><webdriverwait><expected-condition>
2023-01-26 20:31:46
2
1,194
NFeruch - FreePalestine
75,251,221
20,959,773
Python interprets list as a tuple by mistake
<p>I have this piece of code:</p> <pre><code> for keys in self.keys: if has_classes := self.class_checker(keys[0]): print(type(keys[0])) -&gt; #just for demonstrating that it is actual list keys[0] = [x for x in keys[0] if 'class=&quot;' not in x] ...
<python><list><tuples>
2023-01-26 20:18:56
1
347
RifloSnake
75,251,110
1,628,353
How to check if Paramiko SFTP client is still open
<p>How do I check sftp client opened earlier via Paramiko is still active throughout</p> <pre><code>self.sftp = ssh.open_sftp() </code></pre> <p>My application logic at times keeps the SFTP connection idle from anywhere between 0.5 sec to 5 minutes.</p>
<python><python-2.7><ssh><sftp><paramiko>
2023-01-26 20:06:43
2
1,547
chirag7jain
75,250,954
7,255,965
Use `sympy.Order` with functions, instead of symbols
<p>I have a problem like this f(u(x,y), v(x,y)) = 0. For a simple example we could choose f=u^2*v. I want to perturb the state with u=u_0+du,v=v_0+dv. Just doing it in sympy like:</p> <pre><code>import sympy as sp x, y = sp.symbols(&quot;x, y&quot;) u0, v0 = sp.symbols(&quot;u_0, v_0&quot;) du = sp.Function(&quot;\\de...
<python><sympy>
2023-01-26 19:46:14
1
322
Yotam Ohad
75,250,814
3,130,926
How to make `concurrent.futures.ProcessPoolExecutor().map` work with kwonly args?
<p>How to make <code>concurrent.futures.ProcessPoolExecutor().map</code> work with kwonly args? Is this even possible?</p> <p>With positional args:</p> <pre class="lang-py prettyprint-override"><code> def worker_function(x): # Return the square of the passed argument: return x ** 2 # concurrent.futures exampl...
<python><python-multiprocessing><concurrent.futures>
2023-01-26 19:31:04
1
14,217
muon
75,250,803
8,383,726
Python how to create a dictionary using the values in multiple pandas dataframe columns as tuple keys and a single column as value
<p>I would like to create a dictionary using the values in the pandas' data frame multiple columns as tuple keys and single-column values as the value(s). And where there are no values for a particular tuple pair, I would like to assign a generic value of say 99999. This latter part is proving to be a challenge and I w...
<python><dataframe><data-science>
2023-01-26 19:29:00
1
335
Vondoe79
75,250,792
6,077,239
Keep nan in result when perform statsmodels OLS regression in python
<p>I want to perform OLS regression using python's statsmodels package. But my dataset has nans in it. Currently, I know I can use missing='drop' option when perform OLS regression but some of the results (fitted value or residuals) will have different lengths as the original y variable.</p> <p>I have the following cod...
<python><numpy><statsmodels>
2023-01-26 19:27:57
1
1,153
lebesgue
75,250,788
13,885,312
How to prevent python3.11 TaskGroup from canceling all the tasks
<p>I just discovered new features of Python 3.11 like ExceptionGroup and TaskGroup and I'm confused with the following TaskGroup behavior: if one or more tasks inside the group fails then all other normal tasks are cancelled and <strong>I have no chance to change that behavior</strong> Example:</p> <pre><code>async def...
<python><asynchronous><python-asyncio><python-3.11>
2023-01-26 19:27:11
4
415
Anton M.
75,250,578
17,835,656
how can i hash a specific tag from XML file in a correct way?
<p>we are working on e-invoicing and to send the invoice to the government.</p> <p>and they gave us what they want from us to do like signing some tags and hashing another.</p> <p>my problem now is in hashing, when i hash the specific tag after doing every thing right and after that send it i get errors about hashing o...
<python><xml><xml-parsing><invoice><ubl>
2023-01-26 19:04:00
2
721
Mohammed almalki
75,250,483
5,592,430
jupyter notebook display plots as separate output instead of updating existing one
<p>I'd like to draw interactive plot and dropdown winget. For this aim I use the following code in my jupyter notebook:</p> <pre><code>import ipywidgets as widgets import plotly.graph_objects as go import pandas as pd df = pd.DataFrame({'timestamp' : [1,2,3,4,5,6], 'close' : [11,22,33,44,55,66], 'open' : [111,222,333,...
<python><jupyter-notebook><plotly>
2023-01-26 18:55:18
0
981
Roman Kazmin
75,250,429
2,789,788
Pandas dataframe to dictionary where values are lists
<p>I have a dataframe with two columns:</p> <pre><code>key | value &quot;a&quot; | 1 &quot;a&quot; | 2 &quot;b&quot; | 4 </code></pre> <p>which I would like to map to a dictionary that would look like:</p> <pre><code>my_dict[&quot;a&quot;] = [1,2] my_dict[&quot;b&quot;] = [4] </code></pre> <p>My current implementation ...
<python><pandas>
2023-01-26 18:49:37
0
1,810
theQman
75,250,367
867,549
How do I write a proper test for this mocked context manager and ZipFile?
<p>How am I supposed to write this test? I've tried the various options listed but each returns the same failed test:</p> <pre><code>import zipfile from mock import Mock, patch def unzip_file(fp): with zipfile.ZipFile(fp, 'r') as z: z.extractall('dir') @patch('zipfile.ZipFile') def test_unzip...
<python><pytest>
2023-01-26 18:42:06
1
21,781
TravisVOX
75,250,360
3,510,043
pandas fillna removes timezone when used with value=dict
<p>I bumped into an unexpected-to-me behaviour in pandas. Here is the code, running python 3.10.8.</p> <pre class="lang-py prettyprint-override"><code>In [1]: from datetime import datetime, timezone In [2]: import pandas In [3]: pandas.__version__ Out[3]: '1.4.4' In [4]: df = pandas.DataFrame(data={&quot;end_date&qu...
<python><pandas><datetime><timezone>
2023-01-26 18:41:28
0
820
Flavien Lambert
75,250,358
1,223,946
Howto process email from google
<p>Im not sure if this is google or email in general, but I'm seeing a some encoding that im not sure how to handle. Here is a snip that is the Washington post mailer form my google acct.</p> <p>the subject</p> <pre><code> b'=?UTF-8?Q?The_Morning:_Peru=E2=80=99s_deadly_protests?=' </code></pre> <p>actually reads</p> <...
<python><email-parsing><imapclient>
2023-01-26 18:40:42
1
2,176
Peter Moore
75,250,345
9,105,621
best way to pickup different pandas column value if current column value is blank
<p>I'm trying to write a logic that will pickup a different column value if the current value is blank. Here is what I have so far:</p> <pre><code>df['column1'] = df.apply(lambda x: x[&quot;column2&quot;] if x[&quot;column1&quot;].astype(str)=='' else x[&quot;column1&quot;], axis=1) </code></pre> <p>Is there a more eff...
<python><pandas>
2023-01-26 18:39:36
1
556
Mike Mann
75,250,300
75,103
setup.py command to show install_requires?
<p>Is there any way to get the list of packages specified in the <code>install_requires</code> parameter to the setup command (in setup.py)?</p> <p>I'm looking for something similar to <code>pip show pkgname | grep -i requires</code>, but for local packages (and that reports version specifiers and filters).</p> <p>The ...
<python>
2023-01-26 18:34:14
1
27,572
thebjorn
75,250,226
2,532,408
disable pytest plugin terminalreporter via conftest?
<p>Is there a programmatic equivalent (i.e. conftest.py) to setting <code>-p no:terminal</code> in pytest?</p> <p>I know it's possible to add it to the <code>addopts</code> in pytest.ini. But ultimately I would like to be able to have one plugin disable or prevent another plugin from loading.</p> <p>In my case, my plu...
<python><pytest>
2023-01-26 18:27:08
1
4,628
Marcel Wilson
75,250,117
147,562
What is the second type argument to ForeignKey in the django stubs typehints?
<p>What should I put in the place of the <strong><code>_GT</code></strong> type variable in this snippet?</p> <pre class="lang-py prettyprint-override"><code>from django.db.models import ForeignKey, PROTECT order = ForeignKey[&quot;ExtensionOrder&quot;, _GT]( &quot;subscriptions.ExtensionOrder&quot;, null=Fals...
<python><django><python-typing><pylance>
2023-01-26 18:15:34
1
18,247
boatcoder
75,249,741
5,212,614
Sankey Plot not Showing in Jupyter Notebook
<p>I'm pretty sure my code is fine, btu I can't generate a plot of a simple Sankey Chart. Maybe something is off with the code, not sure. Here's what I have now. Can anyone see a problem with this?</p> <pre><code>import pandas as pd import holoviews as hv import plotly.graph_objects as go import plotly.express as pex h...
<python><plotly><sankey-diagram><holoviews>
2023-01-26 17:35:38
1
20,492
ASH
75,249,718
8,372,336
python: hex to bin with binascii.a2b_hex results in binascii.Error: Odd-length string
<p>i am trying to convert a hex string to bin using <code>binascii.a2b_hex</code> but i get <code>binascii.Error: Odd-length string</code> only with some strings, not everytime.</p> <p>for example this is the string throwing the error: <code>177B16283F6C72F52DB9F00DF2629EB6F925A67AEF85A93F5588C62DCDB0050</code></p> <p>...
<python><binary><hex><binascii>
2023-01-26 17:33:23
1
1,730
91DarioDev
75,249,518
1,987,599
Right way to publish authors on PyPi from setuptools
<p>I currently use <code>setuptools</code> to build my Python's package and I have declared the two authors that way in my <code>pyproject.toml</code> file:</p> <pre><code>authors = [ {name = &quot;X Y&quot;, email = &quot;x.y@tt.net&quot;}, {name = &quot;Z H&quot;, email = &quot;z.h@tt.net&quot;}, ] </code><...
<python><setuptools><pypi><python-packaging><pyproject.toml>
2023-01-26 17:12:02
1
609
Guuk
75,249,408
19,980,284
Convert object-type hours:minutes:seconds column to datetime type in Pandas
<p>I have a column called <code>Time</code> in a dataframe that looks like this:</p> <pre><code>599359 12:32:25 326816 17:55:22 326815 17:55:22 358789 12:48:25 361553 12:06:45 ... 814512 21:22:07 268266 18:57:31 659699 14:28:20 659698 14:28:20 268179 17:48:53 Name: Time, Len...
<python><pandas><datetime><object><dtype>
2023-01-26 17:03:45
1
671
hulio_entredas
75,249,095
4,391,249
Return a 3rd party pybind type
<p>My C++ library depends on a 3rd party C++ library with its own bindings.</p> <p>I bind a <code>struct</code> that uses <code>def_readwrite</code> to expose its members. One of its members is a type from the 3rd party library.</p> <p>Basically I have:</p> <pre class="lang-cpp prettyprint-override"><code>struct MyStru...
<python><c++><pybind11><drake>
2023-01-26 16:38:40
1
3,347
Alexander Soare
75,249,016
12,304,000
A DataFrame object does not have an attribute select
<p>In palantir foundry, I am trying to read all xml files from a dataset. Then, in a for loop, I parse the xml files.</p> <p>Until the second last line, the code runs fine without errors.</p> <pre><code>from transforms.api import transform, Input, Output from transforms.verbs.dataframes import sanitize_schema_for_parqu...
<python><pandas><pyspark><palantir-foundry><foundry-code-repositories>
2023-01-26 16:32:12
1
3,522
x89
75,248,993
825,924
With Selenium, I want to find elements by text like Ctrl-F “Find in Page” in Chrome does
<p>Working with Selenium I need to find an element. Contrary to what is recommended, I want to find that element based on what the user sees. I know that this is difficult to solve in the general case, but at least I want to be able to go for elements based on what text/label they carry.</p> <p>In my case I have an <co...
<python><selenium><selenium-webdriver><selenium-chromedriver><selenium-webdriver-python>
2023-01-26 16:30:25
0
35,122
Robert Siemer
75,248,819
17,945,841
Get the rows that are not shared between two data frames
<p>I have two data frames with the exact same column, but one of them have 1000 rows (<code>df1</code>), and one of them 500 (<code>df2</code>). The rows of <code>df2</code> are also found in the data frame <code>df1</code>, but I want the rows that are not.</p> <p>For example, lets say this is <code>df1</code>:</p> <p...
<python><pandas>
2023-01-26 16:16:34
3
1,352
Programming Noob
75,248,774
3,922,727
Python reshaping for the transpose is returning an error of different dimensions when dot product is used
<p>I need to calculate the weights of linear regression model using the expression below:</p> <p><a href="https://i.sstatic.net/nDoXD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nDoXD.png" alt="enter image description here" /></a></p> <p>We should use reshape in order to get the transpose of X having...
<python><numpy><reshape>
2023-01-26 16:12:57
0
5,012
alim1990
75,248,668
2,463,948
Why subprocess.run() freezes on certain application?
<p>Why subprocess.run() freezes on this application?</p> <pre><code>import subprocess subprocess.run('eumdac.exe') </code></pre> <p>The app is from official source: <a href="https://gitlab.eumetsat.int/eumetlab/data-services/eumdac/-/releases/1.2.0" rel="nofollow noreferrer">https://gitlab.eumetsat.int/eumetlab/data-se...
<python><python-3.x><windows>
2023-01-26 16:02:59
1
12,087
Flash Thunder
75,248,577
11,986,167
find pattern in a string without using regex
<p>I'm trying to find a pattern in a string. Example:</p> <p>trail = '<code>AABACCCACCACCACCACCACC</code>&quot; one can note the &quot;<code>ACC</code>&quot; repetition after a prefix of AAB; so the result should be AAB(ACC)</p> <p>Without using regex 'import re' how can I do this. What I did so far:</p> <pre><code> ...
<python><algorithm><pattern-matching>
2023-01-26 15:55:51
1
741
ProcolHarum
75,248,508
3,003,432
Celery, RabbitMQ removes worker from consumers list while it is performing tasks
<p>I have started my celery worker, which uses RabbitMQ as broker, like this:</p> <pre><code>celery -A my_app worker -l info -P gevent -c 100 --prefetch-multiplier=1 -Q my_app </code></pre> <p>Then I have task which looks quite like this:</p> <pre><code>@shared_task(queue='my_app', default_retry_delay=10, max_retries=1...
<python><django><rabbitmq><celery>
2023-01-26 15:48:45
1
7,963
Mr.D
75,248,450
1,860,089
custom python IDEA debugger type renderer that requires an import
<p>I am trying to add a <a href="https://www.jetbrains.com/help/idea/customizing-views.html#renderers" rel="nofollow noreferrer">custom type renderer</a> in the IDEA Python debugger. Specifically, I would like to render an <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Eleme...
<python><debugging><intellij-idea><pycharm>
2023-01-26 15:43:32
1
2,330
Amnon
75,248,321
4,784,683
PyQt - what if you do not call .show()
<pre><code>import sys from PySide6.QtWidgets import QApplication, QLabel app = QApplication(sys.argv) label = QLabel(&quot;&lt;font color=red size=40&gt;Hello World!&lt;/font&gt;&quot;) # label.show() app.exec() </code></pre> <p>What actually happens if you do not call <code>label.show()</code>?<br /> I see that the w...
<python><qt><pyqt>
2023-01-26 15:33:36
0
5,180
Bob
75,248,097
4,806,787
Delete rows with overlapping intervals efficiently
<p>Consider the following DataFrame</p> <pre><code>&gt;&gt;&gt; df Start End Tiebreak 0 1 6 0.376600 1 5 7 0.050042 2 15 20 0.628266 3 10 15 0.984022 4 11 12 0.909033 5 4 8 0.531054 </code></pre> <p>Whenever the <code>[Start, End]</code> intervals of two rows overlap...
<python><pandas><dataframe><for-loop><coding-efficiency>
2023-01-26 15:16:27
2
313
clueless
75,248,003
11,182,916
Derivatives of delta
<p>I want to calculate <code>E</code> by this equation. But I am not sure if I can obtain results with <code>numpy.diff</code> module. It exports 4 points only.</p> <p><a href="https://i.sstatic.net/HjCei.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HjCei.png" alt="enter image description here" /></a>...
<python><numpy>
2023-01-26 15:10:05
1
405
Binh Thien
75,247,606
4,876,561
Add hue to Seaborn Histogram annotation
<p>I have a snippet of code that produces 2 <code>seaborn.histogram</code> plots on the same axes, split by <code>hue</code>, and annotated:</p> <p><a href="https://i.sstatic.net/4KyVD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4KyVD.png" alt="enter image description here" /></a></p> <p>The two hist...
<python><matplotlib><annotations><seaborn><histogram>
2023-01-26 14:39:52
1
7,351
artemis
75,247,505
5,896,319
How to make filtering with SerializerMethodField()?
<p>I'm creating table that show objects of a model and I have a SerializerMethodField that shows a value from a different table with same transaction ID.</p> <p>The problem is I'm using the serializers for the filtering table and chargeback is not working in there. How Can I make it filterable?</p> <p>Simplifying the c...
<python><django><django-rest-framework>
2023-01-26 14:30:19
1
680
edche
75,247,456
456,396
Django Api-Key with unit test
<p>I am trying to implement unit tests to an existing project, the existing project uses Api-Key's to access and authenticate against the Api endpoints.</p> <p>if I do the following via postman or command line:</p> <pre><code>curl --location --request GET 'http://127.0.0.1:8000/api/user_db' \ --header 'Authorization: A...
<python><django><django-rest-framework>
2023-01-26 14:26:21
3
356
Psymon25
75,247,445
11,696,358
Error when making a dash DataTable filterable by columns values
<p>Only when I add the property <code>filter_action=&quot;native&quot;</code> in a <code>dash.DataTable</code> in order to make it possible for the user to filter rows by column values I get an error that varies with the browser I run the webapp on:</p> <ul> <li>Edge: <code>Cannot read properties of undefined (reading ...
<python><reactjs><plotly-dash>
2023-01-26 14:25:36
1
478
user11696358
75,247,232
1,441,720
Spark Dataframe column name change does not reflect
<p>I am trying to rename some special characters from my spark dataframe. For some weird reason, it shows the updated column name when I print the schema, but any attempt to access the data results in an error complaining about the old column name. Here is what I am trying:</p> <pre><code># Original Schema upsertDf.col...
<python><apache-spark>
2023-01-26 14:08:24
1
333
jawsnnn
75,247,085
7,624,196
Case when method in mixin depends on a method of the class that mixin-ed to
<p>I'd like to ask the design pattern when method in a mixin depends on a method of the class that mixin-ed to. The example below is in python, but the question will be also the case with other languages I believe.</p> <p>For example, say I have the following two mixins, and I'd like to inject into some class. As in th...
<python><multiple-inheritance><mixins>
2023-01-26 13:56:21
1
1,623
HiroIshida
75,247,082
14,667,788
find pixel that is closest to the corners
<p>I have a following problem. I would like to find non-empty pixels coordinares that are closest to the left down corner and upper right corder, respectivelly.</p> <p>This function returns upper left and down right coordinates and I cannot figure out why:</p> <pre class="lang-py prettyprint-override"><code>import cv2 ...
<python><numpy>
2023-01-26 13:56:06
1
1,265
vojtam
75,247,001
11,622,712
How to calculate the duration between rows with the same stage value and then get the cumulative duration of each stage?
<p>I have the following dataframe:</p> <pre><code>dt_datetime stage proc_val 2011-11-13 11:00 0 20 2011-11-13 11:10 0 21 2011-11-13 11:30 1 25 2011-11-13 11:40 2 22 2011-11-13 11:55 2 28 2011-11-13 12:00 2 29 </code></pre> <p>I need to add a new column cal...
<python><pandas>
2023-01-26 13:48:01
1
2,998
Fluxy
75,246,963
13,518,907
Streamlit: Display Text after text, not all at once
<p>I want to build a data annotation interface. I read in an excel file, where only a text column is relevant. So &quot;df&quot; could also be replaced by a list of texts. This is my code:</p> <pre><code>import streamlit as st import pandas as pd import numpy as np st.title('Text Annotation') df = pd.read_excel('min...
<python><annotations><streamlit>
2023-01-26 13:44:46
1
565
Maxl Gemeinderat
75,246,929
13,158,157
pandas groupby: selecting unique latest entries
<p>In the following pandas Data Frame:</p> <pre><code> Name v date_modified 0 A 0 2023-01-01 1 A 1 2023-01-02 2 A 2 2023-01-03 3 B 0 2023-01-30 4 B 1 2023-01-02 5 B 2 2023-01-03 6 C 0 2023-01-30 7 C 1 2023-01-03 8 C 2 2023-01-03 </code></pre> <p>How can I ge...
<python><pandas><group-by><unique>
2023-01-26 13:41:13
1
525
euh
75,246,927
15,724,084
python scrapy is slowing down by the time it is parsing
<p>I have a scraper bot, which works fine. But as time passes when it is scraping the speed gets down. I added <code>concurrent request</code>, <code>download_delay:0</code>,<code>'AUTOTHROTTLE_ENABLED':False</code> but result is same. It is starting with a fast pace but gets slower. I guess it is about caching, but do...
<python><caching><scrapy><slowdown>
2023-01-26 13:40:55
4
741
xlmaster
75,246,894
8,778,855
pandas group by time intervall with dynamic intervall start
<p>I have a dataframe defined as:</p> <pre><code>datas = [['A', 51, 'id1', '2020-05-27 05:50:43.346'], ['A', 51, 'id2', '2020-05-27 05:51:08.347'], ['B', 45, 'id3', '2020-05-24 17:24:05.142'],['B', 45, 'id4', '2020-05-24 17:23:30.141'], ['C', 34, 'id5', '2020-05-23 17:31:10.341']] df = pd.DataFrame(datas, columns = ['c...
<python><pandas><group-by>
2023-01-26 13:37:59
1
477
volfi
75,246,762
774,575
Function vectorization says there is a 0-dimensional argument while the argument is an array
<p>I'm implementing this equation and using it for the set of frequencies <code>nos</code>:</p> <img src="https://i.sstatic.net/EexME.png" width="230" /> <p>The non vectorized code works:</p> <pre><code>import numpy as np h = np.array([1,2,3]) nos = np.array([4, 5, 6, 7]) func = lambda h, no: np.sum([hk * np.exp(-1...
<python><numpy><vectorization>
2023-01-26 13:26:05
1
7,768
mins
75,246,672
2,469,182
Dash is ignoring url_base_pathname for requests
<p>I am trying to get Dash to add a prefix to the URLs it fetches data from, so instead of loading a resource like /dash-layout it requests /my/prefix/dash-layout.</p> <p>I understand that there is a parameter url_base_pathname (<a href="https://dash.plotly.com/reference" rel="nofollow noreferrer">https://dash.plotly.c...
<python><plotly-dash>
2023-01-26 13:18:02
0
462
wtf8_decode
75,246,622
6,768,126
Unwanted type conversion pandas apply (int64 --> float64)
<p>Why do pandas convert automatically <code>int64</code> to <code>float64</code>?<br /> I've checked out these questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/50300983/involuntary-conversion-of-int64-to-float64-in-pandas">Involuntary conversion of int64 to float64 in pandas</a></li> <li><a href="h...
<python><pandas><types><int64>
2023-01-26 13:14:25
1
422
Leonardo Maffei
75,246,549
10,722,752
how to sort within each group of a dataframe while retaining other column
<p>I am working with a large dataframe with millions of rows.</p> <p>Sample data:</p> <pre><code>import pandas as pd df = pd.DataFrame({'id' : ['c1','c2','c1','c3','c2','c1','c3'], 'it' : ['it1','it2','it1','it5','it3','it7','it'], 'score' : [.8,.5,1.1,.65,.89,1.2,.91]}) df id ...
<python><pandas>
2023-01-26 13:07:55
1
11,560
Karthik S