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,806,634
2,626,865
twilio sms webhook api
<p>I'm would like to programmatically change the webhook for a given number (and possibly enumerate available numbers) or messaging service, but I can't find the API documentation. From <a href="https://www.twilio.com/docs/messaging/guides/webhook-request" rel="nofollow noreferrer">Our Request to your Webhook URL</a>:</p> <blockquote> <p>You can configure the URLs and HTTP Methods Twilio uses to make its requests via your account portal in the Twilio Console or using the <a href="https://www.twilio.com/docs/sms/api" rel="nofollow noreferrer">REST API</a>.</p> </blockquote>
<python><rest><twilio><twilio-api>
2023-03-21 21:50:03
1
2,131
user19087
75,806,623
8,068,825
Parallelize operation on Pandas DataFrame
<p>So I have this Python class below. It's job is to take a Pandas Dataframe and create classes based on the contents of the Dataframe. This creation operation can take a while so I want to parallelize it. Below I have the code that I have parallelized it. I take number of cores and split the Dataframe then pass it to workers. For whatever reason the code below (not exactly the code below <code>operation</code> function was long so I shortened it as it's not really as relevant) hangs and does not finish. If I take out the multiprocessing code in <code>task</code> it works albeit it takes a long time. How do I parallelize this?</p> <pre><code>import numpy as np import multiprocessing as mp class DFOperator: def __init__(self, df, num_cores): self.num_cores = num_cores self.df = df def operation(self, df, param1): # Does some operation on df and returns a dictionary # with values as a class def task(self): splits = np.array_split(self.df, self.num_cores) with mp.Pool(self.num_cores) as p: async_results = [p.apply_async(operation, args=(2)) for split in splits] results = [ar.get() for ar in async_results] </code></pre>
<python><pandas>
2023-03-21 21:48:47
1
733
Gooby
75,806,560
14,173,197
Capping outliers of a dataframe
<p>I have a dataframe with a 'tot_dl_vol' column. I want to cap the values of that column that have higher than 80% Year over Year or lower than 10% Year over Year percentage. How do I achieve this? I have written this code so far.</p> <pre><code>df['YoY_dl'] = (df['tot_dl_vol'].pct_change(12)) * 100 upper = 80 lower = 10 df.loc[df['YoY_dl'] &gt; upper, 'tot_dl_vol'] = df['tot_dl_vol'].shift(12) * (1 + upper/100) df.loc[df['YoY_dl'] &lt; lower, 'tot_dl_vol'] = df['tot_dl_vol'].shift(12) * (1 - lower/100) </code></pre> <p>Here is a sample dataframe:</p> <p>here is a sample:</p> <pre><code>import pandas as pd from pandas import Timestamp data = {'key': ['A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1'], 'volume': [1714.11, 1907.1, 2927.58, 2656.2, 2364.18, 2372.41, 2363.76, 1956.16, 4146.98, 1971.72, 2588.72, 1853.93, 2050.91, 2267.84, 2634.94, 2750.46, 3072.91, 3363.62, 2717.2, 2273.96, 2228.8, 1886.77, 1864.19], 'ds': [Timestamp('2021-04-01 00:00:00'), Timestamp('2021-05-01 00:00:00'), Timestamp('2021-06-01 00:00:00'), Timestamp('2021-07-01 00:00:00'), Timestamp('2021-08-01 00:00:00'), Timestamp('2021-09-01 00:00:00'), Timestamp('2021-10-01 00:00:00'), Timestamp('2021-11-01 00:00:00'), Timestamp('2021-12-01 00:00:00'), Timestamp('2022-01-01 00:00:00'), Timestamp('2022-02-01 00:00:00'), Timestamp('2022-03-01 00:00:00'), Timestamp('2022-04-01 00:00:00'), Timestamp('2022-05-01 00:00:00'), Timestamp('2022-06-01 00:00:00'), Timestamp('2022-07-01 00:00:00'), Timestamp('2022-08-01 00:00:00'), Timestamp('2022-09-01 00:00:00'), Timestamp('2022-10-01 00:00:00'), Timestamp('2022-11-01 00:00:00'), Timestamp('2022-12-01 00:00:00'), Timestamp('2023-01-01 00:00:00'), Timestamp('2023-02-01 00:00:00')]} df = pd.DataFrame(data) key volume ds A1 1714.11 2021-04-01 A1 1907.10 2021-05-01 A1 2927.58 2021-06-01 A1 2656.20 2021-07-01 A1 2364.18 2021-08-01 A1 2372.41 2021-09-01 A1 2363.76 2021-10-01 A1 1956.16 2021-11-01 A1 4146.98 2021-12-01 A1 1971.72 2022-01-01 A1 2588.72 2022-02-01 A1 1853.93 2022-03-01 A1 2050.91 2022-04-01 A1 2267.84 2022-05-01 A1 2634.94 2022-06-01 A1 2750.46 2022-07-01 A1 3072.91 2022-08-01 A1 3363.62 2022-09-01 A1 2717.20 2022-10-01 A1 2273.96 2022-11-01 A1 2228.80 2022-12-01 A1 1886.77 2023-01-01 A1 1864.19 2023-02-01 </code></pre>
<python><pandas><dataframe><outliers>
2023-03-21 21:40:33
1
323
sherin_a27
75,806,509
444,561
Pandas truncates strings in numpy list
<p>Consider the following minimal example:</p> <pre class="lang-py prettyprint-override"><code>@dataclass class ExportEngine: def __post_init__(self): self.list = pandas.DataFrame(columns=list(MyObject.CSVHeaders())) def export(self): self.prepare() self.list.to_csv(&quot;~/Desktop/test.csv&quot;) def prepare(self): values = numpy.concatenate( ( numpy.array([&quot;Col1Value&quot;, &quot;Col2Value&quot;, &quot; Col3Value&quot;, &quot;Col4Value&quot;]), numpy.repeat(&quot;&quot;, 24), ) ) for x in range(8): #not the best way, but done due to other constraints start = 3 + (x * 3) - 2 end = start + 3 values[start:end] = [ &quot;123&quot;, &quot;some_random_value_that_gets_truncated&quot;, &quot;456&quot;, ] self.list.loc[len(self.list)] = values </code></pre> <p>When <code>export()</code> is called, <code>some_random_value_that_gets_truncated</code> is truncated to <code>some_rando</code>:</p> <pre class="lang-py prettyprint-override"><code>['Col1Value', '123', 'some_rando', '456', '123', 'some_rando', '456', '123', 'some_rando', '456', '123', 'some_rando', '456', '123', ...] </code></pre> <p>I've tried setting the following:</p> <p><code>pandas.set_option(&quot;display.max_colwidth&quot;, 10000)</code>, but this doesn't change anything...</p> <p>Why does this happen, and how can I prevent the truncation?</p>
<python><pandas><list><numpy><truncation>
2023-03-21 21:31:30
2
1,114
GarethPrice
75,806,497
967,621
Select and read a file from user's filesystem
<p>I need to:</p> <ul> <li>Enable the user to select a plain text file from the user's filesystem.</li> <li>Make it available to Pyodide.</li> <li>Read its contents line-by-line in Pyodide (in the Python code).</li> </ul> <p>The code to read currently replaced by dummy code: <code>inp_str = 'ACGTACGT'</code>. The actual use case involves complicated processing of the text file, but the minimal working example simply converts the input to lowercase.</p> <pre class="lang-js prettyprint-override"><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; Analyze input &lt;br&gt; &lt;script type=&quot;text/javascript&quot;&gt; async function main(){ let pyodide = await loadPyodide(); let txt = pyodide.runPython(` # Need to replace the line below with code for the user to select # the file from the user's filesystem and read # its contents line-by-line: inp_str = 'ACGTACGT' out_str = inp_str.lower() with open('/out.txt', 'w') as fh: print(out_str, file=fh) with open('/out.txt', 'rt') as fh: out = fh.read() out `); const blob = new Blob([txt], {type : 'application/text'}); let url = window.URL.createObjectURL(blob); var downloadLink = document.createElement(&quot;a&quot;); downloadLink.href = url; downloadLink.text = &quot;Download output&quot;; downloadLink.download = &quot;out.txt&quot;; document.body.appendChild(downloadLink); } main(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr /> <p>We have external users that may not be advanced computer users. We can specify they need to use Google Chrome browser, but not specific releases like Chrome Canary. We cannot ask them to manually enable the File System API.</p> <hr /> <p>Based on the suggestion by TachyonicBytes, I tried the code below. Now I got the error below. I also cannot see something like <kbd>select file</kbd> button, or any obvious code for it:</p> <pre><code>Uncaught (in promise) DOMException: Failed to execute 'showDirectoryPicker' on 'Window': Must be handling a user gesture to show a file picker. at main (file:///Users/foo/bar/upload_nativefs.html:10:35) at file:///Users/foo/bar/upload_nativefs.html:26:7 </code></pre> <p>This is line 10 referred to in the error message:</p> <pre class="lang-js prettyprint-override"><code>const dirHandle = await showDirectoryPicker(); </code></pre> <p>And the full page is pasted below:</p> <pre class="lang-js prettyprint-override"><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; Analyze input &lt;br&gt; &lt;script type=&quot;text/javascript&quot;&gt; async function main(){ const dirHandle = await showDirectoryPicker(); if ((await dirHandle.queryPermission({ mode: &quot;readwrite&quot; })) !== &quot;granted&quot;) { if ( (await dirHandle.requestPermission({ mode: &quot;readwrite&quot; })) !== &quot;granted&quot; ) { throw Error(&quot;Unable to read and write directory&quot;); } } let pyodide = await loadPyodide(); const nativefs = await pyodide.mountNativeFS(&quot;/mount_dir&quot;, dirHandle); pyodide.runPython(` import os print(os.listdir('/mount_dir')) `); } main(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<javascript><python><webassembly><pyodide>
2023-03-21 21:29:30
3
12,712
Timur Shtatland
75,806,484
11,141,816
Sympy package could not inport the number obtained from the calculation
<p>I wrote a function to optimize the number from sympy package.</p> <pre><code>Optimize_function() </code></pre> <p>It optimize a list of values</p> <pre><code> Optimize_function(list_1) </code></pre> <p>where in jupyter notebook, I typed</p> <pre><code>list_1 </code></pre> <p>and obtained the following output (they were sympy's float object)</p> <pre><code>[1, -988311972974935601., -335500850087402876., 1.32380518039078953e+18, -152434983182794179., 5.01315110369571637e+30, 3.61720312745301514e+33, -4309097254489294.70, 2.92407586668978579e+30, -1.17625737323022613e+34, -6276449726684414.55, -1.11152085817592009e+18, -2.71731566816187054e+29, 8.23318771547418636e+33, -1.53357167323722711e+26, 495654166482945.700, -3.30342982583157026e+30, -123643162644077806., -3.86735929106876011e+30, -568654588842030.100, 2.84640254508985288e+30, -4.51320218189050107e+31, 2812838629251394.05, -3.34119272054976907e+30, 388482304818.400000, 1.17639569262675174e+26, -5308554527899933.75, 2468145414450498.30, 31883120268830274.4, 1.30178514781976186e+18, 64680837588749954.5] </code></pre> <p>However, once I opened up the jupyter notebook again and tried to import the number to continue run the calculation</p> <pre><code> list_1=[1, -988311972974935601., -335500850087402876., 1.32380518039078953e+18, -152434983182794179., 5.01315110369571637e+30, 3.61720312745301514e+33, -4309097254489294.70, 2.92407586668978579e+30, -1.17625737323022613e+34, -6276449726684414.55, -1.11152085817592009e+18, -2.71731566816187054e+29, 8.23318771547418636e+33, -1.53357167323722711e+26, 495654166482945.700, -3.30342982583157026e+30, -123643162644077806., -3.86735929106876011e+30, -568654588842030.100, 2.84640254508985288e+30, -4.51320218189050107e+31, 2812838629251394.05, -3.34119272054976907e+30, 388482304818.400000, 1.17639569262675174e+26, -5308554527899933.75, 2468145414450498.30, 31883120268830274.4, 1.30178514781976186e+18, 64680837588749954.5] </code></pre> <p>The Optimize_function() would not run, despite showing that list_1 was correctly imported. I tried to convert the number back to the sympy float object</p> <pre><code>list_1=[ sp.Float(sp.N(value,50)) for value in list_1] </code></pre> <p>Instead of converting the number to be the original object, it showed multiple infinity.</p> <p>How to convert the result back to list_1 so that it could be used for sympy calculation?</p>
<python><sympy>
2023-03-21 21:27:06
0
593
ShoutOutAndCalculate
75,806,473
5,212,614
How can we pick out features form a JSON string and structure everything in rows and columns?
<p>I have a small python script that iterates through a bunch of JSON strings and appends everything into a list, liek this.</p> <pre><code>my_list.append(response) </code></pre> <p>Now, I am trying to normalize the list, liek this</p> <pre><code>df_vehicles = json_normalize(my_list) </code></pre> <p>Then, I normalize the results.</p> <pre><code>df_vehicles = pd.json_normalize(df_vehicles['data']) </code></pre> <p>So, ultimately I end up with this.</p> <pre><code>[{'id': '21201', 'name': 'SRW Utility, 4x4', 'latitude': 35.31068751, 'longitude': -80.66177891, 'headingDegrees': 161.2, 'speedMilesPerHour': 0}] </code></pre> <p>I think it's a dataframe of dictionaries. If I run this: <code>print(type(df_vehicles))</code> I get this: <code>&lt;class 'pandas.core.frame.DataFrame'&gt;</code></p> <p>What's the easiest way to normalize this? I'd like to get features arranged as columns, like this:</p> <pre><code>'id' 'name' 'latitude' 'longitude' etc., etc, </code></pre> <p>I thought it would be something like: <code>df_vehicles.explode('id')</code> When I run that, I get this error: <code>KeyError: 'id'</code></p> <p>Ultimately, I want to arrange the details under these feature named (columns).</p> <p>This is 'my_list':</p> <pre><code>{'id': '21201', 'name': 'SRW Utility, 4x4', 'externalIds': {'serial': 'X2ND985', 'gps': [{'time': '2023-01-01T23:57:36.485Z', 'latitude': 28.82809801, 'longitude': -81.70075479, 'headingDegrees': 0, 'speedMilesPerHour': 0, 'reverseGeo': {'formattedLocation': '2726 David Walker Drive, Mount Homer, FL, 32726'} ...some more things down here... </code></pre>
<python><json><python-3.x>
2023-03-21 21:25:32
0
20,492
ASH
75,806,451
9,727,763
Evaluating huggingface transformer with trainer gives different results
<p>I am using a pre-trained Transformer for sequence classification which I fine-tuned on my dataset with the Trainer class. When I evaluate the model using the Trainer class I get an accuracy of 94%</p> <pre class="lang-py prettyprint-override"><code>trainer = Trainer(model=model) preds = trainer.predict(validation_dataset) predictions = np.argmax(preds.predictions, axis=-1) metric = evaluate.load(&quot;accuracy&quot;) metric.compute(predictions=predictions, references=preds.label_ids) # prints: {'accuracy': 0.9435554514341591} </code></pre> <p>However, when I tried to get the predictions directly from the model, the accuracy was only around 86%:</p> <pre class="lang-py prettyprint-override"><code>predictions = [] model.eval() for row in validation_dataset: text_ids = row['input_ids'].unsqueeze(0) predicted = torch.argmax(model(text_ids)[0]) predictions += [predicted.item()] metric.compute(predictions, labels) # prints {'accuracy': 0.8639942552151239} </code></pre> <p>I wonder why are the predictions from the trainer and the model different. And additionally, why is the accuracy of the predictions from the trainer so much better? Am I missing something or is it an indication of bad implementation?</p>
<python><machine-learning><huggingface-transformers>
2023-03-21 21:20:55
0
345
Jan Koci
75,806,404
5,116,032
Scipy Chi2 Probability Density Function Exploding
<p>I am trying to plot a chi squared probability density function trained on some experimental data at different conditions in python. My code is shown below.</p> <pre><code> import numpy as np import matplotlib.pyplot as plt import scipy.stats as ss data= [] #read from CSV file. chi_linespace = np.linspace(4, 1500, len(data)) x,y,z = ss.chi2.fit(data) pdf_chi2 = ss.chi2.pdf(linespace, x,y,z) plt.hist(data, bins=100, density=True, alpha=0.3) plt.plot(linespace, pdf_chi2, label='Chi2') plt.legend() plt.show() </code></pre> <p>I have roughly 1500 observations per example, and when I run the code below most of the time I get a nice fit distribution. <a href="https://i.sstatic.net/1YuXk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1YuXk.png" alt="good fit distribution" /></a></p> <p>I am finding sometimes when I run the same code on a different dataset the probability density function <em>explodes</em> at ~0 and does not appear to be fit from the dataset at all. <a href="https://i.sstatic.net/cL79I.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cL79I.png" alt="bad fit distribution" /></a></p> <p>Has someone experienced this before, and how did they go about resolving this?</p>
<python><scipy><statistics><chi-squared><scipy.stats>
2023-03-21 21:13:26
0
434
iato
75,806,292
4,966,886
pyqt5 central widget with QTableWidgets in a MainWindow not correctly resized
<p>I use as the central widget in a QMainWindow a QDialog with a bunch of QTableWidget in it.</p> <pre><code>import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # the central widget scrollArea = QScrollArea() scrollArea.setWidgetResizable(True) self.centerWidget = QDialog() self.centerWidgetLayout = QVBoxLayout() self.centerWidget.setLayout(self.centerWidgetLayout) scrollArea.setWidget(self.centerWidget) self.setCentralWidget(scrollArea) self.populateLayout() def defineTable(self, ncols): tableWidget = QTableWidget() tableWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) tableWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) tableWidget.verticalHeader().hide() tableWidget.horizontalHeader().hide() tableWidget.setMinimumHeight(10) tableWidget.horizontalHeader().setDefaultSectionSize(50) tableWidget.horizontalHeader().setHighlightSections(False) tableWidget.horizontalHeader().setSortIndicatorShown(False) tableWidget.horizontalHeader().setStretchLastSection(False) tableWidget.setColumnCount(ncols ) tableWidget.setRowCount(1) for col in range(ncols): tableWidget.setItem( 0, col, QTableWidgetItem(&quot;lalala&quot;)) return tableWidget def populateLayout(self): for i in range(6): self.centerWidgetLayout.addWidget( self.defineTable(i+1) ) if __name__ == '__main__': app = QApplication(sys.argv) ex = MainWindow() ex.show() sys.exit(app.exec_()) </code></pre> <p>Curiously, the scroll bar is not effective.</p> <p>Here is a picture illustrating the result when the size of the widget is large:</p> <p><a href="https://i.sstatic.net/q7N9A.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/q7N9A.png" alt="enter image description here" /></a></p> <p>Everything is fine.</p> <p>Now, I squeeze the widget and get:</p> <p><a href="https://i.sstatic.net/wHocm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wHocm.png" alt="enter image description here" /></a></p> <p>This is not what I expect, and the widget is useless.</p> <p>If I make it small enough, the scrollbar appears:</p> <p><a href="https://i.sstatic.net/utk9Y.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/utk9Y.png" alt="enter image description here" /></a></p> <p>but it is still useless.</p> <p>Any hint on how to solve this issue? Thanks.</p> <p>Edit 1: As suggested by musicamante, the issue is triggered by</p> <pre><code>tableWidget.setMinimumHeight(10) </code></pre> <p>but if I remove this line, I get a blank space between the row and the scroll bar. Any idea how to remove this space?</p> <p><a href="https://i.sstatic.net/TZnkG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TZnkG.png" alt="enter image description here" /></a></p> <p>Edit 2: The white space can be removed using</p> <pre><code>tableWidget.verticalHeader().setStretchLastSection(True) </code></pre> <p>However, the rows are now too large:</p> <p><a href="https://i.sstatic.net/ljt4g.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ljt4g.png" alt="enter image description here" /></a></p> <p>and my attempts to reduce the height of the rows were not successful. Any idea ?</p>
<python><qt><pyqt5>
2023-03-21 21:01:15
1
306
user11634
75,806,255
3,965,828
Functions Framework giving "Provided code is not a loadable module. Could not load the function, shutting down."
<p>I have a Google Cloud Function I've developed. The main.py and requirements.txt file are both in a folder called &quot;hello&quot;. Here's the entirety of my main.py file:</p> <pre><code>import functions_framework import logging logging.basicConfig(level=logging.INFO) @functions_framework.http def hello(request): logging.info('Hello request received') return &quot;ok&quot; </code></pre> <p>When I open a terminal at the hello folder and use the command</p> <pre><code>functions-framework --target=hello </code></pre> <p>I receive</p> <blockquote> <p>Provided code is not a loadable module. Could not load the function, shutting down.</p> </blockquote> <p>as output. I've reinstalled functions framework, restarted my console, and cannot understand why I'm getting this error since hello is definitely a function name.</p>
<python><google-cloud-functions><functions-framework>
2023-03-21 20:55:14
0
2,631
Jeffrey Van Laethem
75,806,091
6,197,439
How to display required amount of leading zeroes with Python3 f-string?
<p>I just want to format a number as hex, with four characters in all - so up to three leading zeroes. I'm trying this:</p> <pre class="lang-none prettyprint-override"><code>$ python3 --version Python 3.10.10 $ python3 -c 'TVAR=0x000a; print(f&quot;{TVAR:#04x}&quot;)' 0x0a </code></pre> <p>So, I thought that with <code>04x</code> I had specified string of total 4 characters to the f-string, padded left with zeroes if need be - but I only get a two-character hex formatted string.</p> <p>Can I somehow modify this kind of f-string specification, so I get a 4-digit, left-zero padded, hex numeric string (in this case, 0x000a) - and if so, how?</p>
<python><python-3.x><hex><string-formatting><f-string>
2023-03-21 20:32:44
1
5,938
sdbbs
75,805,981
5,255,581
How to find most connected nodes after spectral clustering on networkx?
<p>I've done spectral clustering on G and created a partition matrix to form subgraphs for each cluster:</p> <pre><code>clusters = SpectralClustering(affinity = 'precomputed', assign_labels=&quot;discretize&quot;,random_state=0,n_clusters=n_clusters).fit_predict(adj_matrix) partMatrix = [[] for x in range(n_clusters)] for (node, cidx) in zip(nodes_list, clusters): partMatrix[cidx].append(node) H = G.subgraph(partMatrix[0]) I = G.subgraph(partMatrix[1]) J = G.subgraph(partMatrix[2]) K = G.subgraph(partMatrix[3]) L = G.subgraph(partMatrix[4]) </code></pre> <p>But now I want to run max flow min cost on these subgraphs but be able to set the source and targets to nodes that have the highest weighted edges to the other subgraphs. I am unsure how to even start to go about finding this.</p> <p>Any suggestions welcome.</p>
<python><graph><networkx>
2023-03-21 20:16:17
0
865
mleafer
75,805,947
12,760,550
Create column that orders ID by first Start Date
<p>Imagine I have the following dataframe:</p> <pre><code>ID Start Date 1 1990-01-01 1 1990-01-01 1 1991-01-01 2 1991-01-01 2 1990-01-01 3 2002-01-01 3 2000-01-01 4 1991-01-01 </code></pre> <p>What would be the best way to create a column named Order that, for each unique ID in the ID column, starting with 1 with the earliest Start Date and adds 1 to the subsequential earliest Start Dates (and if same value, doens't matter the order) resulting on the following dataframe:</p> <pre><code>ID Start Date Order 1 1990-01-01 2 1 1990-01-01 3 1 1989-01-01 1 2 1991-01-01 2 2 1990-01-01 1 3 2002-01-01 2 3 2000-01-01 1 4 1991-01-01 1 </code></pre>
<python><pandas><list><filter><sequence>
2023-03-21 20:11:33
1
619
Paulo Cortez
75,805,772
11,279,970
Call OpenAI API async with Python, asyncio and aiohttp
<p>I am trying to make asynchronous calls to openai API completions using aiohttp and asyncio. See below where I create a dataframe of elements (Door, Window, etc.) I want information from regarding the given context (description of a room)</p> <pre><code>#imports import pandas as pd # Make a dataframe import aiohttp # for making API calls concurrently import asyncio # for running API calls concurrently COMPLETIONS_MODEL = &quot;text-davinci-003&quot; request_url = &quot;https://api.openai.com/v1/completions&quot; request_header = {&quot;Authorization&quot;: f&quot;Bearer {api_key}&quot;} #data prompt_list = ['Door', 'Window', 'Table'] init_context = &quot; height if the room contains a door which is 8ft in height, a table 2ft in height and a window 6ft in height&quot; #dataframe of list of questions q_dataframe = pd.DataFrame({&quot;type&quot;: prompt_list}) async def process_question(question: str, context: str): query = &quot;What is the &quot; + question + context data = {'model': 'text-davinci-003', 'prompt': f'{query}'} try: async with aiohttp.ClientSession() as session: async with session.post(url=request_url, headers=request_header, json=data) as response: resp = await response.json() except Exception as e: print(f&quot;Request failed {e}&quot;) async def process_questions(idf): results = await asyncio.gather(*[process_question(question, init_context) for question in idf['type']]) asyncio.create_task(process_questions(q_dataframe)) </code></pre> <p>However I receive the following error for each request</p> <pre><code>Request failed Cannot connect to host api.openai.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')] </code></pre> <p>I tried using asyncio.sleep which didnt work. Am I using <strong>asyncio.gather</strong> incorrectly alongside <strong>asyncio.create_task</strong>?</p> <p>I am able to run openai.completion.create on each dataframe row so my connection is fine</p>
<python><pandas><python-asyncio><aiohttp><openai-api>
2023-03-21 19:49:29
2
508
Simon Palmer
75,805,468
12,458,212
Filter nested numpy array
<p>Hi I'm trying to filter the following numpy array but running into issues. I'd like to filter for all arrays equal to [('a','b','c'),1]. The problem is I can't figure out how to either combine the elements in each array so instead of [('a','b','c'),1], I would have [('a','b','c',1)], OR simply filter given the original structure. I tried a combination of np.concatenate() and np.ravel() but result wasn't expected.</p> <pre><code>a = np.array([[('a','b','c'), 1], [('b','c','a'), 1], [('a','b','c'), 2], [('a','b','c'), 1]]) Method: Filter if 1st element = 'a', 2nd element = 'b', 3rd element ='c' and 4th element = 1 Desired Output: output = np.array([[('a','b','c'), 1], [('a','b','c'), 1]]) </code></pre> <p>EDIT: I was able to get this to work with a pandas solution, but only by converting it to a dataframe, which is too expensive thus why I'm trying to acheive a more optimized solution with numpy</p>
<python><numpy>
2023-03-21 19:11:21
2
695
chicagobeast12
75,805,411
2,209,313
What are the `y` and `x` params to the python curses `window.getch()` method?
<p>I may be missing something very obvious, but I am confused by the optional <code>[y, x]</code> parameters to the <code>window.getch( [y, x] )</code> method <a href="https://docs.python.org/3/library/curses.html#curses.window.getch" rel="nofollow noreferrer">described in the Python documentation</a>. What are these optional params for, and what do they do if I include them in my call?</p> <p>As far as I can tell the documentation doesn't mention what these parameters are for. It just says:</p> <blockquote> <p>Get a character. Note that the integer returned does not have to be in ASCII range: function keys, keypad keys and so on are represented by numbers higher than 255. In no-delay mode, return -1 if there is no input, otherwise wait until a key is pressed.</p> </blockquote> <p>The <code>window.get_wch( [y, x] )</code> and <code>window.getkey( [y, x] )</code> methods seem to have similarly undescribed optional <code>[y, x]</code> params.</p>
<python><coordinates><curses><coordinate-systems><python-curses>
2023-03-21 19:03:40
3
3,423
Wandering Logic
75,805,235
1,451,531
How to pass bash argument array to single-quoted python call
<p>I have a script that looks something like this:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash /usr/local/bin/myproc --tags='env:dev' 'python myscript.py --my-argument VAL1 --my-argument VAL2 &gt; /some/redirect' </code></pre> <p>Now I need to add additional logic that conditionally changes the arguments passed to my python script. So I've tried pulling the script call into a bash function and passing the arguments from bash to python like this:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash callMyScript () { /usr/local/bin/myproc --tags='env:dev' 'python myscript.py &quot;$@&quot; &gt; /some/redirect' } if [ $1 = &quot;foo&quot; ] then callMyScript --myargument VAL1 --myargument VAL2 else callMyScript --myargument VAL3 --myargument VAL4 --my-argument VAL5 fi </code></pre> <p>Unfortunately my arguments aren't making it to my python script at all. I've tried several different approaches to string interpolation, array expansion, and quote wrapping but I'm coming up empty handed. The arguments are either missing, sent as one arg instead of separate args, or something even weirder.</p> <p>This is a simplified version of the real thing, of course, but the root of my troubles seems to be that my python call is wrapped in single quotes and that's not something I can find a way around.</p> <p>Any help would be much appreciated.</p>
<python><bash>
2023-03-21 18:42:20
1
1,416
Splendor
75,805,054
814,438
Python Process.join is Released in Linux but Not Windows
<p>I have observed different behavior in how Windows 10 and Ubuntu 18.04 handle the <code>Process.join()</code> function. What accounts for the difference in behavior?</p> <p>I am running Python 3.6.</p> <p>In this code, the main process starts a subprocess and then calls <code>join</code>. The subprocess runs a thread and does not terminate it. In Windows, the join continues to block, and the main process runs forever. In Linux, the subprocess ends and the main process ends.</p> <p>The <code>print(thread)</code> line shows that the thread is not daemonic on either Windows or Linux. I do not specify whether the child process is created with <code>fork</code> or <code>spawn</code>.</p> <pre class="lang-py prettyprint-override"><code>import threading import time from multiprocessing import Process def thread_f(): print(&quot;Thread function&quot;) while True: time.sleep(1) def subprocess_f(): print(&quot;TOP of Subprocess function&quot;) thread = threading.Thread(target=thread_f) thread.start() threads = ', '.join(map(str, [(thread.name, thread.ident, &quot;isDaemon {}&quot;.format(thread.isDaemon())) for thread in threading.enumerate()])) print(threads) print(&quot;BOTTOM of Subprocess function&quot;) def main(): print(&quot;TOP of main&quot;) process = Process(target=subprocess_f) process.start() process.join() print(&quot;BOTTOM of main&quot;) # In Windows 10, main process continues to run. # In Ubuntu Linux 18.04, main process ends. if __name__ == '__main__': main() </code></pre> <p>Output In Windows:</p> <pre><code>TOP of main TOP of Subprocess function Thread function ('MainThread', 14952, 'isDaemon False'), ('Thread-1', 10992, 'isDaemon False') BOTTOM of Subprocess function </code></pre> <p>Output In Linux:</p> <pre><code>TOP of main TOP of Subprocess function Thread function ('MainThread', 140283868624704, 'isDaemon False'), ('Thread-1', 140283844200192, 'isDaemon False') BOTTOM of Subprocess function BOTTOM of main </code></pre>
<python><linux><windows><multithreading><multiprocessing>
2023-03-21 18:24:54
1
1,199
Jacob Quisenberry
75,804,965
17,896,651
Peewee value returns to its default after few seconds (BUG?)
<p>This used to be my model:</p> <pre><code>db = SqliteDatabase(Settings.stats_conf_database_location) class ActivityTracker(Model): date = DateField(unique=True) activity_time_curr = IntegerField(default=0) # active seconds today activity_time_max = IntegerField() # max active seconds today class Meta: database = db </code></pre> <p>I added:</p> <pre><code>blocked = BooleanField(default=False) </code></pre> <p>as a 4th parameter</p> <p>and migrate code:</p> <pre><code>db.create_tables([ActivityTracker], safe=True) # migration table_name = ActivityTracker._meta.name db_columns_dict = db.get_columns(table_name) db_columns_name_list = [column.name for column in db_columns_dict] updated_column = ActivityTracker.blocked updated_column_name = ActivityTracker.blocked.name if updated_column_name not in db_columns_name_list: migrator = SqliteMigrator(db) migrate( migrator.add_column(table_name, updated_column_name, updated_column) ) </code></pre> <p>So far so good. I started to something strange once I update the blocked value:</p> <pre><code>ActivityTracker.update(blocked=True).where(ActivityTracker.date == datetime.today()).execute() </code></pre> <p><a href="https://i.sstatic.net/dAyYi.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dAyYi.png" alt="enter image description here" /></a></p> <p>The value gets updated: <a href="https://i.sstatic.net/IfNsZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IfNsZ.png" alt="enter image description here" /></a></p> <p><strong>ISSUE: After 10 - 30 seconds the value gets set back to 0</strong></p> <p><a href="https://i.sstatic.net/xK0Hc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xK0Hc.png" alt="enter image description here" /></a></p> <p>Not a single line of code is executed. This happens over all my 600+ processes across 4 different Windows PCs.</p> <p>I know also see the activity time current changed back to some old version.</p> <p><strong>ISSUE BREADCRUMBS:</strong></p> <pre><code> activity_tracker_obj, created = ActivityTracker.get_or_create(date=_datetime.date.today(), defaults={'activity_time_curr': 0, 'activity_time_max': max_working_seconds_today, 'blocked': False}) InstaPyLimits.activity_tracker_obj = activity_tracker_obj # store today pointer in db def update_daily_activity(time): #print(f'adding today time {time}') activity_tracker = InstaPyLimits.activity_tracker_obj new_time = activity_tracker.activity_time_curr + time activity_tracker.activity_time_curr = new_time activity_tracker.save() </code></pre> <p><strong>The activity_tracker.save() in async thread is reseting it to 0, why ?</strong> Why is it taken old value ? should I refetch it from database ?</p>
<python><peewee>
2023-03-21 18:13:55
1
356
Si si
75,804,936
6,321,559
Pytest Caplog for Testing Logging Formatter
<p>I'm using a logging formatter to redact passwords. I want to write a test to confirm that the logging redactor is effective. In this example I simplified the code to redact &quot;foo&quot;.</p> <p>With this redactor code in the my <code>my_logger.py</code> module (simplified redaction of a specific word):</p> <pre><code>class RedactFoo: def __init__(self, base_formatter): self.base_formatter = base_formatter def format(self, record): msg = self.base_formatter.format(record) return msg.replace(&quot;foo&quot;, &quot;&lt;&lt;REDACTED&gt;&gt;&quot;) def __getattr__(self, attr): return getattr(self.orig_formatter, attr) </code></pre> <p>Then I configure my logger and wrap the formatter for each handler:</p> <pre><code>logging.config.dictConfig(logging_config) # Set the formatter on all handlers for h in logging.root.handlers: h.setFormatter(RedactFoo(h.formatter)) def get_logger(name): return logging.getLogger(name) </code></pre> <p>If I run:</p> <pre><code>logger = my_logger.get_logger(&quot;Test&quot;) logger.error(f&quot;This message has foo.&quot;) </code></pre> <p>the logger redacts the message.</p> <p>However, in Pytest <code>test_my_logger.py</code>:</p> <pre><code>import my_logger def test_logging_redactor(caplog): logger = my_logger.get_logger(&quot;test&quot;) logger.error(f&quot;This message has foo.&quot;) assert &quot;&quot;This message has &lt;&lt;REDACTED&gt;&gt;.&quot; in caplog.text </code></pre> <p>This test does not pass because the Pytest logging configuration overwrites my custom config. How can I use Pytest and the <code>caplog</code> fixture to perform this test?</p> <p>I have seen the <code>unittest</code> solution here: <a href="https://stackoverflow.com/questions/73825305/how-to-test-specific-logging-formatting-in-python-using-pytest-and-unittest">How to test specific logging formatting in Python (using `pytest` and `unittest`)</a>, but I'm interested in doing this with Pytest.</p>
<python><pytest>
2023-03-21 18:11:37
1
2,046
it's-yer-boy-chet
75,804,905
19,980,284
Specify NaN encoding in np.where() logic
<p>I have data that looks like this:</p> <pre><code> id case2_q6 0 300 3.0 1 304 4.0 2 306 3.0 3 309 1.0 4 311 3.0 5 312 4.0 6 314 NaN 7 315 2.0 8 316 3.0 9 317 3.0 </code></pre> <p>And using this <code>np.where()</code> function call to generate new variables:</p> <pre><code>df['fluid_2'] = np.where((df['case2_q6'] == 1) | (df['case2_q6'] == 2), 1, 0) </code></pre> <p>Now <code>df</code> has the column <code>fluid_2</code> as below:</p> <pre><code> id case2_q6 fluid_2 0 300 3.0 0 1 304 4.0 0 2 306 3.0 0 3 309 1.0 1 4 311 3.0 0 5 312 4.0 0 6 314 NaN 0 7 315 2.0 1 8 316 3.0 0 9 317 3.0 0 </code></pre> <p>As you can see, the <code>NaN</code> value at index <code>6</code> was converted to a 0. Is there a way to set up the <code>np.where()</code> so as to leave those as NaN values in <code>fluid_2</code>?</p> <p>The desired output would be:</p> <pre><code> id case2_q6 fluid_2 0 300 3.0 0 1 304 4.0 0 2 306 3.0 0 3 309 1.0 1 4 311 3.0 0 5 312 4.0 0 6 314 NaN NaN 7 315 2.0 1 8 316 3.0 0 9 317 3.0 0 </code></pre> <p>Where the <code>NaN</code> is preserved.</p>
<python><pandas><dataframe><numpy><conditional-statements>
2023-03-21 18:07:49
2
671
hulio_entredas
75,804,827
18,108,767
The z-axis label is not showing in a 3D plot
<p>I have an issue with a 3d plot, at the moment of visualizing it. It appears without the z-axis label,</p> <p><a href="https://i.sstatic.net/N1Xp0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/N1Xp0.png" alt="enter image description here" /></a></p> <p>but when I set a longer title, it appears:</p> <p><a href="https://i.sstatic.net/p9TRy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/p9TRy.png" alt="enter image description here" /></a></p> <p>Is there any way to be able to &quot;see&quot; the z-axis label without modifying the title or another kind of solution to this issue?</p> <p>This is my code:</p> <p>mask1, mask2, mask3 shapes are <code>(100,100)</code> with values of 20, 32, 49 respectively</p> <pre><code>fig = plt.figure(figsize=(12, 4)) ax = fig.add_subplot(projection='3d') x, y = np.meshgrid(np.arange(100)*20, np.arange(100)*20) s1 = ax.plot_surface(x, y, mask1*20, linewidth=0, label='Reflector 1') s1._facecolors2d = s1._facecolor3d s1._edgecolors2d = s1._edgecolor3d s2 = ax.plot_surface(x, y, mask2*20, linewidth=0, label='Reflector 2') s2._facecolors2d = s2._facecolor3d s2._edgecolors2d = s2._edgecolor3d s3 = ax.plot_surface(x, y, mask3*20, linewidth=0, label='Reflector 3') s3._facecolors2d = s3._facecolor3d s3._edgecolors2d = s3._edgecolor3d ax.set(xlim=[0, 2000], ylim=([0, 2000]), zlim=([1000, 0]), xlabel=(r' $x [m]$'), ylabel=(r'$y [m]$'), zlabel=(r'$z [m]$')) ax.legend() ax.set_title('a short title', fontsize=18) plt.show() </code></pre>
<python><matplotlib><matplotlib-3d>
2023-03-21 17:58:36
1
351
John
75,804,781
1,440,349
How to create pyspark dataframes from pandas dataframes with pandas 2.0.0?
<p>I normally use <code>spark.createDataFrame()</code> which used to throw me deprecated warnings about iteritems() call in earlier version of Pandas. With pandas 2.0.0 it doesn't work at all, resulting in an error below:</p> <pre><code>AttributeError Traceback (most recent call last) File &lt;command-2209449931455530&gt;:64 61 df_train_test_p.loc[df_train_test_p.is_train=='N','preds']=preds_test 63 # save the original table and predictions into spark dataframe ---&gt; 64 df_test = spark.createDataFrame(df_train_test_p.loc[df_train_test_p.is_train=='N']) 65 df_results = df_results.union(df_test) 67 # saving all relevant data File /databricks/spark/python/pyspark/instrumentation_utils.py:48, in _wrap_function.&lt;locals&gt;.wrapper(*args, **kwargs) 46 start = time.perf_counter() 47 try: ---&gt; 48 res = func(*args, **kwargs) 49 logger.log_success( 50 module_name, class_name, function_name, time.perf_counter() - start, signature 51 ) 52 return res File /databricks/spark/python/pyspark/sql/session.py:1211, in SparkSession.createDataFrame(self, data, schema, samplingRatio, verifySchema) 1207 data = pd.DataFrame(data, columns=column_names) 1209 if has_pandas and isinstance(data, pd.DataFrame): 1210 # Create a DataFrame from pandas DataFrame. -&gt; 1211 return super(SparkSession, self).createDataFrame( # type: ignore[call-overload] 1212 data, schema, samplingRatio, verifySchema 1213 ) 1214 return self._create_dataframe( 1215 data, schema, samplingRatio, verifySchema # type: ignore[arg-type] 1216 ) File /databricks/spark/python/pyspark/sql/pandas/conversion.py:478, in SparkConversionMixin.createDataFrame(self, data, schema, samplingRatio, verifySchema) 476 warn(msg) 477 raise --&gt; 478 converted_data = self._convert_from_pandas(data, schema, timezone) 479 return self._create_dataframe(converted_data, schema, samplingRatio, verifySchema) File /databricks/spark/python/pyspark/sql/pandas/conversion.py:516, in SparkConversionMixin._convert_from_pandas(self, pdf, schema, timezone) 514 else: 515 should_localize = not is_timestamp_ntz_preferred() --&gt; 516 for column, series in pdf.iteritems(): 517 s = series 518 if should_localize and is_datetime64tz_dtype(s.dtype) and s.dt.tz is not None: File /local_disk0/.ephemeral_nfs/envs/pythonEnv-fefe10af-04b7-4277-b395-2f16b77bd90b/lib/python3.9/site-packages/pandas/core/generic.py:5981, in NDFrame.__getattr__(self, name) 5974 if ( 5975 name not in self._internal_names_set 5976 and name not in self._metadata 5977 and name not in self._accessors 5978 and self._info_axis._can_hold_identifiers_and_holds_name(name) 5979 ): 5980 return self[name] -&gt; 5981 return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'iteritems' </code></pre> <p>How can I solve this? I use Spark 3.3.2. I did find seemingly updated code with problematic call replaced here: <a href="https://github.com/apache/spark/blob/master/python/pyspark/sql/pandas/conversion.py" rel="nofollow noreferrer">https://github.com/apache/spark/blob/master/python/pyspark/sql/pandas/conversion.py</a> but not sure which version it is and whether it is available.</p> <p>EDIT: sample code which reproduces the problem below:</p> <pre><code>import pandas as pd from pyspark.sql import SparkSession # create a sample pandas dataframe data = {'name': ['John', 'Mike', 'Sara', 'Adam'], 'age': [25, 30, 18, 40]} df_pandas = pd.DataFrame(data) # convert pandas dataframe to PySpark dataframe spark = SparkSession.builder.appName('pandasToSpark').getOrCreate() df_spark = spark.createDataFrame(df_pandas) # show the PySpark dataframe df_spark.show() </code></pre>
<python><pandas><dataframe><apache-spark><pyspark>
2023-03-21 17:53:25
3
465
shiftyscales
75,804,599
4,505,301
OpenAI API: How do I count tokens before(!) I send an API request?
<p>OpenAI's text models have a context length, e.g.: Curie has a context length of 2049 tokens.</p> <p>They provide <code>max_tokens</code> and <code>stop</code> parameters to control the length of the generated sequence. Therefore the generation stops either when stop token is obtained, or <code>max_tokens</code> is reached.</p> <p>The issue is: when generating a text, I don't know how many tokens my prompt contains. Since I do not know that, I cannot set <code>max_tokens = 2049 - number_tokens_in_prompt</code>.</p> <p>This prevents me from generating text dynamically for a wide range of text in terms of their length. What I need is to continue generating until the stop token.</p> <p>My questions are:</p> <ul> <li>How can I count the number of tokens in Python API so that I will set <code>max_tokens</code> parameter accordingly?</li> <li>Is there a way to set <code>max_tokens</code> to the max cap so that I won't need to count the number of prompt tokens?</li> </ul>
<python><openai-api><chatgpt-api><gpt-3><gpt-4>
2023-03-21 17:35:10
4
1,562
meliksahturker
75,804,409
21,420,742
How to check for Previous managers in Employee History (Python)
<p>I have a dataset with all employees records and need to find the most recent(which I have) and the previous manager before. I wanted to use the shift function but unfortunately not all employees have the same history layout. Here is a small example:</p> <pre><code> ID Job_Title Mananger 1 Sales John Doe 1 Sales Kobe Bryant 1 Sales Phil Knight 2 Tech Michael Jordan 2 Tech Michael Jordan 2 Tech Larry Bird 3 Sales Magic Johnson 3 Sales Magic Johnson 3 Sales Magic Johnson </code></pre> <p>And this is what I need:</p> <pre><code>ID Job_Title Manager Previous Manager 1 Sales John Doe Kobe Bryant 1 Sales Kobe Bryant Kobe Bryant 1 Sales Phil Knight Kobe Bryant 2 Tech Michael Jordan Michael Jordan 2 Tech Michael Jordan Michael Jordan 2 Tech Larry Bird Michael Jordan 3 Sales Magic Johnson Magic Johnson 3 Sales Magic Johnson Magic Johnson 3 Sales Magic Johnson Magic Johnson </code></pre> <p>I tried using the shift function but that only works on seeing the change, I want to be able to map the previous manager.</p>
<python>
2023-03-21 17:15:46
1
473
Coding_Nubie
75,804,367
7,657,180
Delete list of files in python
<p>I am trying to clean USB drive and I have specified most of the unnecessary folders and files. the following code is very good</p> <pre><code>import os import shutil import hashlib def delete_files_and_folders_on_usb_drive(usb_drive_path, filenames_to_delete, folder_prefixes, target_hash): for root, dirs, files in os.walk(usb_drive_path, topdown=False): for name in files + dirs: if (name in filenames_to_delete) or any(name.startswith(prefix) for prefix in folder_prefixes) or (name == '534') or (name.endswith('.exe')): path = os.path.join(root, name) try: if os.path.isdir(path): if name.endswith('.exe') and os.path.basename(os.path.dirname(path)) == os.path.splitext(name)[0]: with open(path, 'rb') as f: file_hash = hashlib.sha256(f.read()).hexdigest() if file_hash == target_hash: os.remove(path) else: if name.startswith('very important'): for dirpath, dirnames, filenames in os.walk(path): for dirname in dirnames: os.chmod(os.path.join(dirpath, dirname), 0o777) for filename in filenames: os.chmod(os.path.join(dirpath, filename), 0o777) if os.path.exists(path) and name in filenames_to_delete: os.remove(path) else: shutil.rmtree(path, ignore_errors=True) else: with open(path, 'rb') as f: file_hash = hashlib.sha256(f.read()).hexdigest() if file_hash == target_hash: print(path) os.remove(path) except Exception as e: print(f'Failure {path}: {e}') filenames_to_delete = ['Files.bat', 'MyText.txt'] folder_prefixes = ['new folder', 'very important', 'hackfolder'] target_hash = '9b57e6a137882be5a6e8c085cfa23f26294c2ac9427a99d0e54e9d26fc46c087' delete_files_and_folders_on_usb_drive('I:/', filenames_to_delete, folder_prefixes, target_hash) </code></pre> <p>The only problem with the code is that it doesn't deal with the list of the files in this list <code>filenames_to_delete = ['Files.bat', 'MyText.txt']</code> but the folders are deleted successfully.</p>
<python><shutil>
2023-03-21 17:12:13
1
9,608
YasserKhalil
75,804,346
3,087,409
Opposite of Pandas "to_flat_index()"
<p>I have a pandas dataframe with MultiIndex columns, which I'm writing to an SQL database. To write to the database nicely I have to flatten the MultiIndex (see <a href="https://stackoverflow.com/a/60406162/3087409">this answer</a>), but this means when I read from the database I want to reconstruct the MultiIndex.</p> <p><code>df.columns</code> before flattening:</p> <pre><code>MultiIndex([( 'foo', 'bar'), ('part 2', 'spam')] ) </code></pre> <p>Dataframe after <code>df.columns = df.columns.to_flat_index()</code>:</p> <pre><code>Index([ ('foo', 'bar'), ('part 2', 'spam')], dtype='object') </code></pre> <p><code>df.columns</code> as read from the database (<code>df = pd.read_sql_table('df', connection)</code>)</p> <pre><code>Index(['('foo', 'bar')', '('part 2', 'spam')'], dytpe='object') </code></pre> <p>Is there a way to reconstruct the original MultiIndex from the latest version of the dataframe?</p>
<python><pandas><dataframe>
2023-03-21 17:10:42
1
2,811
thosphor
75,804,182
13,686,796
ValueError: object has no field when using monkeypatch.setattr on a pydantic.BaseModel's method
<p>I usually can patch methods of normal objects using pytest monkeypatch. However when I try with a <code>pydantic.BaseModel</code> it fails.</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class Person(BaseModel): name: str age: int def intro(self) -&gt; str: return f&quot;I am {self.name}, {self.age} years old.&quot; def test_person_intro(monkeypatch): p = Person(name='Joe', age=20) monkeypatch.setattr(p, 'intro', lambda: 'patched intro') assert p.intro() == 'patched intro' </code></pre> <p>Raises:</p> <pre class="lang-py prettyprint-override"><code>monkeypatch = &lt;_pytest.monkeypatch.MonkeyPatch object at 0x10f0d3040&gt; def test_intro(monkeypatch): p = Person(name='Joe', age=20) &gt; monkeypatch.setattr(p, 'intro', lambda: 'patched intro') - - - - - - - - - - - - - - - - - - - - - &gt; ??? E ValueError: &quot;Person&quot; object has no field &quot;intro&quot; pydantic/main.py:422: ValueError </code></pre>
<python><pytest><pydantic><monkeypatching>
2023-03-21 16:56:07
2
491
valcapp
75,804,180
1,609,428
how to do a qcut by group in polars?
<p>Consider the following example</p> <pre><code>zz = pl.DataFrame({'group' : ['a','a','a','a','b','b','b'], 'col' : [1,2,3,4,1,3,2]}) zz Out[16]: shape: (7, 2) ┌───────┬─────┐ │ group ┆ col │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═════╡ │ a ┆ 1 │ │ a ┆ 2 │ │ a ┆ 3 │ │ a ┆ 4 │ │ b ┆ 1 │ │ b ┆ 3 │ │ b ┆ 2 │ └───────┴─────┘ </code></pre> <p>I am trying to create a binned variable by group, essentially replicating a pandas <code>qcut</code> by group. This is easy in Pandas, as shown here:</p> <pre><code>xx = pl.DataFrame({'group' : ['a','a','a','a','b','b','b'], 'col' : [1,2,3,4,1,3,2]}).to_pandas() xx.groupby('group').col.transform(lambda x: pd.qcut(x, q = 2, labels = False)) Out[18]: 0 0 1 0 2 1 3 1 4 0 5 1 6 0 Name: col, dtype: int64 </code></pre> <p>But how to do this in Polars? Thanks!</p>
<python><pandas><python-polars>
2023-03-21 16:55:42
1
19,485
ℕʘʘḆḽḘ
75,804,160
3,764,619
Installing environment for https://github.com/igorshubovych/markdownlint-cli fails with AttributeError: 'bytes' object has no attribute 'tell' #328
<p>I am using</p> <pre><code>- repo: https://github.com/igorshubovych/markdownlint-cli rev: v0.32.2 hooks: - id: markdownlint </code></pre> <p>Sometimes, pre-commit fails with the following error.</p> <pre><code>[INFO] Installing environment for https://github.com/igorshubovych/markdownlint-cli. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: CalledProcessError: command: ('/usr/local/bin/python', '-mnodeenv', '--prebuilt', '--clean-src', '/root/.cache/pre-commit/repoki3l4r17/node_env-default') return code: 1 stdout: (none) stderr: * Install prebuilt node (19.8.1) .Incomplete read while readingfrom https://nodejs.org/download/release/v19.8.1/node-v19.8.1-linux-x64.tar.gz . Traceback (most recent call last): File &quot;/usr/local/lib/python3.10/runpy.py&quot;, line 196, in _run_module_as_main return _run_code(code, main_globals, None, File &quot;/usr/local/lib/python3.10/runpy.py&quot;, line 86, in _run_code exec(code, run_globals) File &quot;/usr/local/lib/python3.10/site-packages/nodeenv.py&quot;, line 1519, in &lt;module&gt; main() File &quot;/usr/local/lib/python3.10/site-packages/nodeenv.py&quot;, line 1104, in main create_environment(env_dir, args) File &quot;/usr/local/lib/python3.10/site-packages/nodeenv.py&quot;, line 980, in create_environment install_node(env_dir, src_dir, args) File &quot;/usr/local/lib/python3.10/site-packages/nodeenv.py&quot;, line 739, in install_node install_node_wrapped(env_dir, src_dir, args) File &quot;/usr/local/lib/python3.10/site-packages/nodeenv.py&quot;, line 762, in install_node_wrapped download_node_src(node_url, src_dir, args) File &quot;/usr/local/lib/python3.10/site-packages/nodeenv.py&quot;, line 602, in download_node_src with ctx as archive: File &quot;/usr/local/lib/python3.10/contextlib.py&quot;, line 135, in __enter__ return next(self.gen) File &quot;/usr/local/lib/python3.10/site-packages/nodeenv.py&quot;, line 573, in tarfile_open tf = tarfile.open(*args, **kwargs) File &quot;/usr/local/lib/python3.10/tarfile.py&quot;, line 1630, in open saved_pos = fileobj.tell() AttributeError: 'bytes' object has no attribute 'tell' </code></pre> <p>It looks like nodeenv-1.7.0 is used.</p> <p>It happens randomly every third time or so. Has anyone else encountered this?</p>
<python><pre-commit-hook><pre-commit><pre-commit.com><nodeenv>
2023-03-21 16:53:43
0
680
Casper Lindberg
75,803,969
3,215,940
QFileDialog not closing after file selection
<p>I have a simple function that opens a file dialog using pyqt6 to select a file. The function works, but the dialog hangs after being called and I'm not sure why it's not getting automatically closed when the file is selected.</p> <pre><code>def ui_find_file(title=None, initialdir=None, file_type=None): import os from PyQt6.QtWidgets import QApplication, QFileDialog app = QApplication([]) file_dialog = QFileDialog() file_dialog.setFileMode(QFileDialog.FileMode.ExistingFile) if file_type: filter = f&quot;{file_type} files (*.{file_type})&quot; file_dialog.setNameFilter(filter) else: file_dialog.setNameFilter(&quot;All files (*);;&quot;) if initialdir is None: initialdir = os.getcwd() elif initialdir == '~': initialdir = os.path.expanduser('~') file_dialog.setDirectory(initialdir) if title: file_dialog.setWindowTitle(title) if file_dialog.exec(): file_path = file_dialog.selectedFiles()[0] print(f&quot;Selected {file_path}&quot;) file_dialog.deleteLater() # Clean up the file dialog window app.quit() # Exit the event loop return file_path else: print(&quot;No file selected&quot;) file_dialog.deleteLater() # Clean up the file dialog window app.quit() # Exit the event loop return None </code></pre> <p>When I try the first lines in the command line</p> <pre><code>from PyQt6.QtWidgets import QApplication, QFileDialog app = QApplication([]) file_dialog = QFileDialog() file_dialog.setFileMode(QFileDialog.FileMode.ExistingFile) </code></pre> <p>and I use either <code>file_dialog.open()</code> or <code>file_dialog.exec()</code>, I can select a file and the dialog closes without freezing the python instance. I don't even have to call <code>file_dialog.deleteLater()</code> for it to close itself.</p> <p>When I try to use this from another script, for example doing:</p> <pre><code>from utils import ui_find_file ui_find_file() </code></pre> <p>It produces the freezing behavior.</p> <h3>Updates on things I have tried but didn't work</h3> <p>I am running this in python 3.10, Ubuntu 20.04, from a terminal.</p> <ul> <li>I have tried using <code>destroy()</code> instead of <code>destroyLater()</code>.</li> <li>I have tried using <code>app.processEvents()</code> below <code>destroy()</code> with <code>del(app)</code></li> </ul> <p>The reason I am creating <code>app = QApplication([])</code> was because when I didn't, I got <code>QWidget: Must construct a QApplication before a QWidget</code> (which I can reproduce by commenting out the line)</p> <pre><code>Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; from utils import ui_find_file &gt;&gt;&gt; ui_find_file() QWidget: Must construct a QApplication before a QWidget Aborted (core dumped) </code></pre>
<python><pyqt6>
2023-03-21 16:37:55
2
4,270
Matias Andina
75,803,710
5,858,752
How to prepend a string to the name of many columns in a dataframe?
<p>I have a dataframe with numerous columns, and I need to prepend the same string to the name of each of these columns.</p> <p>Rather than doing</p> <pre><code>df.rename({&quot;col1&quot;: &quot;prepended_str_col1&quot;, ....., }) </code></pre> <p>I was wondering if there is an easier way to do this?</p>
<python><pandas><dataframe>
2023-03-21 16:13:30
3
699
h8n2
75,803,534
11,267,783
Include live figures Matplotlib on PDF
<p>I wanted to know if it is possible to include interactive figures in PDF.</p> <p>For example, I wanted to generate figures with Matplotlib, create a PDF with Latex and be able to zoom or pan inside the figures on the PDF. (The same behavior that we have for example when we plot with Matplotlib)</p> <p>Maybe there is a format that can handle this feature ?</p>
<python><matplotlib><pdf><latex>
2023-03-21 15:58:48
1
322
Mo0nKizz
75,803,379
3,834,415
How does one export classmethods to a module as module methods in a dynamic fashion in python?
<p>Assuming <code>python3.10</code>, suppose I have a class in some file:</p> <pre><code>class Foo(metaclass=ABCMeta): @classmethod @abstractmethod def do_fn(cls, yada, yada_): pass @classmethod @abstractmethod def that_fn(cls, this, that): pass SpecializedFoo(Foo): @classmethod def do_fn(cls, yada, yada_): logger.info(&quot;doing it&quot;) @classmethod def that_fn(cls, this, that): logger.info(&quot;this or that&quot;) </code></pre> <p>And a system interface module that expects <code>do_fn</code> and <code>that_fn</code>:</p> <pre><code># interface.py from functools import partial from specialized_foo import SpecializedFoo ##### A Foo Interface ##### # Optionally leverage the system integration # Read the docs: https://yankee.doodle.etc/callbacks do_fn = partial(SpecializedFoo.do_fn) that_fn = partial(SpecializedFoo.that_fn) ### Done: Foo Interface </code></pre> <p>Is there a clean or at least automatic and <strong>stable</strong> way I can define a method in <code>SpecializedFoo</code> or abstract parent class <code>Foo</code> such that the system interface <code>interface.py</code> can simply call:</p> <pre><code>SpecializedFoo.export_interface() </code></pre> <p>And the method functions will be exported to the module's list of available module methods as if they were defined in the exact same fashion, e.g.:</p> <pre><code>do_fn = partial(SpecializedFoo.do_fn) that_fn = partial(SpecializedFoo.that_fn) </code></pre>
<python><oop><functional-programming>
2023-03-21 15:43:08
1
31,690
Chris
75,803,374
1,317,323
How to use miniconda as a linux system user
<p>I'd like to run a Django app on a linux machine using miniconda as a tool for managing packages and virtual environment.</p> <p>Systemctl will launch gunicorn as a dedicated system user, say my_app_user. Sources will be on /opt/my_app with permission only for my_app_user.</p> <p>What is the correct / secured way to install miniconda for such use case ?</p>
<python><django><miniconda>
2023-03-21 15:42:32
1
1,002
Yvain
75,803,316
5,575,597
How can I make a bar chart in Bokeh were positive/negative values have different colours?
<p>In the below simple example code I have a bar chart with pos/neg values, how can I ammend the code to show green/red for pos/neg value bars?</p> <pre><code>from bokeh.io import show from bokeh.plotting import figure fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] counts = [-5, 3, 4, -2, -4, 6] p = figure(x_range=fruits, plot_height=250, title=&quot;Fruit Counts&quot;, toolbar_location=None, tools=&quot;&quot;) p.vbar(x=fruits, top=counts, width=0.9) p.xgrid.grid_line_color = None show(p) </code></pre> <p>Any help much appreciated!</p>
<python><bokeh>
2023-03-21 15:37:47
1
863
cJc
75,803,123
7,656,767
How to pass double quoted parameter to Python requests.get()
<p>An API I'm using requires one of the parameters to be passed in in double quotes like so: <code>https://example.com/api?country=&quot;US&quot;</code>. It seems no matter how I try to pass this in, I get a 500 response using Python's <code>requests</code> library. I've tried the following:</p> <ul> <li>`params = {&quot;country&quot;: '&quot;US&quot;'}</li> <li>`params = {&quot;country&quot;: &quot;&quot;US&quot;&quot;} <ul> <li>these lead to the URL not picking up the argument in quotation marks.</li> </ul> </li> <li><code>params = urlencode({&quot;country&quot;: '&quot;US&quot;'})</code> which gives the string <code>country=%22US%22</code>. <ul> <li>If I paste the URL with that string into my browser I get the correct result, but running <code>requests.get(url, headers=headers, params=params)</code> using the urlencoded params, I still get a 500 error.</li> </ul> </li> </ul> <p>I know the API is working as I can test it in my browser, the problem lies in sending over a correctly formatted URL.</p> <p>Is there something I'm missing here regarding how to pass in this double quoted argument?</p>
<python><string><https><python-requests><urlencode>
2023-03-21 15:22:28
1
710
Eric Hasegawa
75,803,086
2,516,789
Countdown clock not updating in a multi-frame tkinter app
<p>I'm in the progress of writing a python app to show a countdown clock in one window, and a video in another (haven't started integrating the video part yet).</p> <p>However, the countdown clock I have written doesn't update, and only shows the initial countdown time when the app was launched. I need it to update around every 500ms.</p> <p>This is the area of interest in my code <code>PageOne</code> &amp; <code>show_clock</code>. PageOne is the display frame which should update to show a live clock countdown.</p> <p>EDIT: Code has been updated since original post. Now I don't get the clock label updating at all. I'm experiencing the following errors:</p> <pre><code>Line 73 : Statement seems to have no effect It looks like the statement doesnt have (or at least seems to) any effect. Line 108 : Name 'show_time' is not defined </code></pre> <pre><code>class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller fnt = font.Font(family='Quicksand Medium', size=30) self.txt = tk.StringVar() self.show_time lbl = tk.Label(self, textvariable=self.txt, font=fnt, foreground=&quot;black&quot;, background=&quot;#FFFFDD&quot;) lbl.pack() button = tk.Button(self, text=&quot;Go to the start page&quot;, command=lambda: controller.show_frame(&quot;StartPage&quot;)) button.pack() def show_time(self): endTime = datetime.datetime(2029, 7, 20, 16, 0, 0) # Get the time remaining until the event remainder = endTime - datetime.datetime.now() # remove the microseconds part remainder = remainder - datetime.timedelta(microseconds=remainder.microseconds) yrs = remainder.days // 365 yrsTxt = ' years, ' if yrs == 1: yrsTxt = ' year, ' days = remainder.days % 365 daysTxt = ' days,' if days == 1: daysTxt = ' day,' timeTxt = str(remainder).split(',')[1] # Show the time left global myClock myClock = str(yrs) + yrsTxt + str(days) + daysTxt + timeTxt # Show the time left self.txt.set(f&quot;{yrs} {yrsTxt}, {days} {daysTxt}, {timeTxt}&quot;) self.after(1000, show_time) </code></pre>
<python><python-3.x><tkinter><raspberry-pi>
2023-03-21 15:18:13
1
1,190
Newbie
75,803,030
710,955
Loguru - how to change the logs 'filename'
<p>With the python log library 'loguru', is there a way to change the log file name after declaring it?</p> <p>Thanks!</p> <pre><code>from loguru import logger logger.add('dummy.log', format=&quot;{time:YYYY-MM-DD HH:mm:ss} {level} {message}&quot;) ..... # How to change log filename? logger.debug('my message') </code></pre>
<python><loguru>
2023-03-21 15:14:00
1
5,809
LeMoussel
75,802,977
12,436,050
Adding a string to a dataframe column and create a new column in Python 3.7
<p>I have following pandas dataframe</p> <pre><code> col1 col2 0 ORG-1 LOC-100052061, LOC-100032442, LOC-100042003 1 ORG-2 LOC-100005615, LOC-100000912, LOC-100043831 </code></pre> <p>I would like to explode col2 and add a url to each value.</p> <p>The expected output is:</p> <pre><code> col1 col2 col3 0 ORG-1 LOC-100052061 https://europa.eu/v1/locations/LOC-100052061 0 ORG-1 LOC-100032442 https://europa.eu/v1/locations/LOC-100032442 0 ORG-1 LOC-100042003 https://europa.eu/v1/locations/LOC-100042003 1 ORG-2 LOC-100005615 https://europa.eu/v1/locations/LOC-100005615 1 ORG-2 LOC-100000912 https://europa.eu/v1/locations/LOC-100000912 1 ORG-2 LOC-100043831 https://europa.eu/v1/locations/LOC-100043831 </code></pre> <p>I am trying following lines of code.</p> <pre><code>df_exploded = df.assign(col2=df['col2'].str.split(',')).explode('col2') url_loc = &quot;https://europa.eu/v1/locations/&quot; df_exploded['col3'] = 'https://europa.eu/v1/locations/' + df_exploded['col2'].astype(str) </code></pre> <p>But this gives me strange output (only concatenated col3 column is shown).</p> <pre><code> col3 0 https://europa.eu/v1/locations/LOC-10... 0 https://europa.eu/v1/locations/LOC-1 ... 0 https://europa.eu/v1/locations/LOC-1 ... 1 https://europa.eu/v1/locations/LOC-10... 1 https://europa.eu/v1/locations/LOC-1 ... </code></pre> <p>Any help is highly appreciated.</p>
<python><pandas>
2023-03-21 15:09:34
2
1,495
rshar
75,802,971
8,613,945
How to use python and telnetlib3 to send commands and provide an interactive session
<p>I would like to use python to connect to a telnet server and do the following steps:</p> <ul> <li>send some commands to get the server in an initial state</li> <li>start an interactive session with stdin and stdout so a user can interact with the server's cli</li> <li>potentially send some commands after the user finishes the interactive session.</li> </ul> <p>I've tried to do this in bash with telnet and netcat but it makes for a very flakey solution.</p> <p>It looks like telnetlib3 is the right answer for doing this in python but there are almost no examples of how to use the classes in the library.</p>
<python><telnet>
2023-03-21 15:09:01
1
605
Giles Knap
75,802,870
12,769,783
Type hint that indicates that class contains method with signature
<p>Is it possible to write a type hint which checks if a passed type defines a function with a specific name and signature, if the name of the function and its signature are derived from another argument?</p> <p>In the following scenario I try to show what I intend to do: I want to write a type hint for the function <code>override</code>, which ideally should generate a warning if <code>override</code> is used as an annotation for a function that does not override a corresponding function in the <code>superclass</code> (passed explicitly, as argument).</p> <pre class="lang-py prettyprint-override"><code>import inspect from typing import Callable, Protocol # I would like to type hint the superclass, which should define a function with same signature as `method` def override(superclass: type): def overrider(method: Callable) -&gt; Callable: print('checking method ', method) if method.__name__ not in vars(superclass) or inspect.signature(method) != inspect.signature(getattr(superclass, method.__name__)): raise Exception(f'{method.__name__} does not override a function from {superclass.__name__}') return method return overrider class Parent: def func(self) -&gt; None: print('parent!') class Child(Parent): @override(Parent) def func(self) -&gt; None: print('child!') ce = Child() ce.func() </code></pre> <p>In the code above, I only check at runtime if the <code>override</code> is valid, by raising an exception whenever no function in the supposed super class exists with the same signature. Additionally, I would like to receive warnings whenever the child implementation does not match the parent implementation (anymore).</p> <p>I know that <code>Protocol</code> exists for a similar purpose, but I don't think that is applicable in this scenario, because the name of the function (in this case <code>func</code>) is supposed to be variable. Otherwise I could define a protocol with a function with the same ParamSpec and return type and utilize matching type hints for the <code>method</code> aswell.</p> <p>As chepner <a href="https://stackoverflow.com/questions/75802870/python-type-hint-that-indicates-that-class-contains-method-with-signature#comment133715197_75802870">suggested</a>, it might make more sense to pass the function directly to the decorator, because it solves the problem of the variable name of the function. I tried to do that <a href="https://mypy-play.net/?mypy=latest&amp;python=3.12&amp;gist=f028f92b54e36b53a9bb0b978cae67a5" rel="nofollow noreferrer">here</a>. However, this leads to the necessity to annotate <code>self</code> in a <code>Child</code> member function as <code>Parent</code>, which leads to type hinting problems later on, when attempting to access attributes of the <code>Child</code>.</p>
<python><python-typing>
2023-03-21 15:01:56
1
1,596
mutableVoid
75,802,832
8,849,755
Rename specific index level in multiindex data frame
<p>What I want to do can perfectly be done in this way:</p> <pre class="lang-py prettyprint-override"><code>df.reset_index('level_x', inplace=True, drop=False) df.rename(columns={'level_x': 'level_y', inplace=True) df.set_index('level_y', append=True) </code></pre> <p>but I am very sure there is a one liner (and better) approach. Something like</p> <pre class="lang-py prettyprint-override"><code>df.rename(level={'level_x': 'level_y'}, inplace=True) </code></pre> <p>which of course does not work (I tried several others as well such as <code>.rename(index=...)</code>, <code>.rename(...)</code>, etc.). Surprisingly neither Google nor ChatGPT are telling me how to do this trivial operation...</p> <p>Consider for example <code>df = pandas.DataFrame({'level_x':[1,2,3], 'asd':[2,3,4], 'a column':[3,4,5]}).set_index(['level_x','asd'])</code>.</p>
<python><pandas><rename><multi-index>
2023-03-21 14:58:12
1
3,245
user171780
75,802,773
5,881,882
Python: Object not callable - runs in Notebook but not in PyCharm
<p>EDIT: I could solve it (hopefully it does what I want). But I don't understand why it works now. I put my workaround at the bottom. Would be great, if somebody could enlighten me, why it works (or why notebook worked without it).</p> <hr /> <p>I use the code from this tutorial:</p> <p><a href="https://amaarora.github.io/posts/2020-09-13-unet.html#understanding-input-and-output-shapes-in-u-net" rel="nofollow noreferrer">https://amaarora.github.io/posts/2020-09-13-unet.html#understanding-input-and-output-shapes-in-u-net</a></p> <p>and it runs in my Notebook code.</p> <p>Now I try to adapt this code for my model. Thus, I copy it in my model.py which has an only class AENet and adapt it accordingly. But PyCharm already raises the warning that</p> <blockquote> <p>object 'Encoder' is not callable object 'Decoder' is not callable</p> </blockquote> <p>And the program breaks when I call it from the terminal.</p> <p>Before:</p> <pre><code>class AENet(nn.Module): def __init__(self,input_dim, block_size): super(AENet,self).__init__() self.input_dim = input_dim self.cov_source = nn.Parameter(torch.zeros(block_size, block_size), requires_grad=False) self.cov_target = nn.Parameter(torch.zeros(block_size, block_size), requires_grad=False) self.encoder = nn.Sequential( nn.Linear(self.input_dim,128), nn.BatchNorm1d(128,momentum=0.01, eps=1e-03), nn.ReLU(), nn.Linear(128,8), nn.BatchNorm1d(8,momentum=0.01, eps=1e-03), nn.ReLU(), ) self.decoder = nn.Sequential( nn.Linear(8,128), nn.BatchNorm1d(128,momentum=0.01, eps=1e-03), nn.ReLU(), nn.Linear(128,self.input_dim) ) def forward(self, x): z = self.encoder(x.view(-1,self.input_dim)) return self.decoder(z), z </code></pre> <p>and after my copy+paste and adaptation of the AENet class it looks like this</p> <pre><code> class Block(nn.Module): def __init__(self, in_ch, out_ch): super().__init__() self.conv1 = nn.Conv2d(in_ch, out_ch, 3) self.relu = nn.ReLU() self.conv2 = nn.Conv2d(out_ch, out_ch, 3) def forward(self, x): return self.conv2(self.relu(self.conv1(x))) class Encoder(nn.Module): def __init__(self, chs=(1, 64, 128, 256, 512, 1024)): super().__init__() self.enc_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)]) self.pool = nn.MaxPool2d(2) def forward(self, x): ftrs = [] for block in self.enc_blocks: x = block(x) ftrs.append(x) x = self.pool(x) return ftrs class Decoder(nn.Module): def __init__(self, chs=(1024, 512, 256, 128, 64)): super().__init__() self.chs = chs self.upconvs = nn.ModuleList([nn.ConvTranspose2d(chs[i], chs[i + 1], 2, 2) for i in range(len(chs) - 1)]) self.dec_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)]) def forward(self, x, encoder_features): for i in range(len(self.chs) - 1): x = self.upconvs[i](x) enc_ftrs = self.crop(encoder_features[i], x) x = torch.cat([x, enc_ftrs], dim=1) x = self.dec_blocks[i](x) return x def crop(self, enc_ftrs, x): _, _, H, W = x.shape enc_ftrs = torchvision.transforms.CenterCrop([H, W])(enc_ftrs) return enc_ftrs class AENet(nn.Module): def __init__(self, input_dim, block_size, enc_chs=(1, 64, 128, 256, 512, 1024), dec_chs=(1024, 512, 256, 128, 64), num_class=1, retain_dim=True, out_sz=(256, 640)): super(AENet,self).__init__() self.input_dim = input_dim self.cov_source = nn.Parameter(torch.zeros(block_size, block_size), requires_grad=False) self.cov_target = nn.Parameter(torch.zeros(block_size, block_size), requires_grad=False) self.encoder = Encoder(enc_chs) self.decoder = Decoder(dec_chs) self.head = nn.Conv2d(dec_chs[-1], num_class, 1) self.retain_dim = retain_dim self.out_sz = out_sz def forward(self, x): print(f'FOR X: we have the dimensions {x.shape}') z = self.encoder(x[None, None, :]) print(f'FOR Z: we have the dimensions {z.shape}') out = self.decoder(z[::-1][0], z[::-1][1:]) out = self.head(out) if self.retain_dim: out = F.interpolate(out, self.out_sz) print(f'FOR O: we have the dimensions {out.shape}') return out, z </code></pre> <p>My workaround:</p> <pre><code>z = self.encoder.forward(x[None, None, :]) out = self.decoder.forward(z[::-1][0], z[::-1][1:]) </code></pre> <p>Why do I need to call the class' method directly, while it works straight as above in jupyter notebook?</p>
<python><pytorch><callable>
2023-03-21 14:53:20
1
388
Alex
75,802,689
10,251,146
polars - Fill null over Groups
<p>I am trying to fill null timestamps over groups, my dataframe looks like this</p> <pre class="lang-py prettyprint-override"><code>df = pl.from_repr(&quot;&quot;&quot; ┌───────────────────────────────────┬──────────────────────────────────┬───────┐ │ start ┆ stop ┆ group │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞═══════════════════════════════════╪══════════════════════════════════╪═══════╡ │ 2021-12-08 06:40:53.734941+01:00 ┆ 2022-05-16 10:16:18.717146+02:00 ┆ 1 │ │ 2021-12-08 06:40:55.191598+01:00 ┆ null ┆ 1 │ │ 2021-12-08 10:39:12.421402+01:00 ┆ 2022-05-16 10:16:19.816922+02:00 ┆ 2 │ │ 2021-12-08 10:39:12.634873+01:00 ┆ 2022-05-16 10:16:19.817304+02:00 ┆ 1 │ │ 2021-12-08 10:49:47.392815+01:00 ┆ 2022-05-16 10:16:20.178050+02:00 ┆ 5 │ └───────────────────────────────────┴──────────────────────────────────┴───────┘ &quot;&quot;&quot;) </code></pre> <p>The stop timestamps should be imputed from the next start.</p> <p>My current implantation is:</p> <pre class="lang-py prettyprint-override"><code>df = df.sort(&quot;start&quot;).with_columns( pl.col(&quot;start&quot;).fill_null(strategy=&quot;backward&quot;).over(&quot;group&quot;) ) df = df.group_by(&quot;group&quot;).map_groups( lambda df: df.with_columns( pl.col(&quot;stop&quot;).fill_null( pl.col(&quot;start&quot;).shift(-1) ) ) ) </code></pre> <p>This current implementation is slow. Is there a faster way to solve this?</p> <p>Thanks in advance</p>
<python><dataframe><python-polars>
2023-03-21 14:46:26
1
459
linus heinz
75,802,643
271,388
Is double close in strace necessarily bad?
<p>I am training a neural network. Somewhere in my code base, I have a code snippet like the following:</p> <pre class="lang-py prettyprint-override"><code>def foo(): d = {} with PIL.Image.open(img_path) as img: d[&quot;img&quot;] = torchvision.transforms.functional.to_tensor(img) return d </code></pre> <p>This code doesn't cause any problems. However, when I run my program under <code>strace</code>, I see that there is a double call of the <code>close</code> syscall (below, I omit everything except relevant strace lines):</p> <pre><code>openat(AT_FDCWD, &quot;example.tif&quot;, O_RDONLY|O_CLOEXEC) = 3&lt;/tmp/example.tif&gt; fstat(3&lt;/tmp/example.tif&gt;, {st_mode=S_IFREG|0644, st_size=9274, ...}) = 0 lseek(3&lt;/tmp/example.tif&gt;, 0, SEEK_CUR) = 0 lseek(3&lt;/tmp/example.tif&gt;, 0, SEEK_SET) = 0 read(3&lt;/tmp/example.tif&gt;, &quot;II*\0\250#\0\0\200\0 P8$\26\r\7\204BaP\270d6\35\17\210DbQ8\244&quot;..., 4096) = 4096 # here some more lseeks and reads are omitted mmap(NULL, 1765376, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7feb10bbd000 fcntl(3&lt;/tmp/example.tif&gt;, F_DUPFD_CLOEXEC, 0) = 4&lt;/tmp/example.tif&gt; lseek(4&lt;/tmp/example.tif&gt;, 0, SEEK_SET) = 0 read(4&lt;/tmp/example.tif&gt;, &quot;II*\0\250#\0\0&quot;, 8) = 8 fstat(4&lt;/tmp/example.tif&gt;, {st_mode=S_IFREG|0644, st_size=9274, ...}) = 0 mmap(NULL, 9274, PROT_READ, MAP_SHARED, 4&lt;/tmp/example.tif&gt;, 0) = 0x7feb9e7a4000 munmap(0x7feb9e7a4000, 9274) = 0 close(4&lt;/tmp/example.tif&gt;) = 0 close(4) = -1 EBADF (Bad file descriptor) close(3&lt;/tmp/example.tif&gt;) = 0 </code></pre> <p>I am worried about <code>close(4) = -1 EBADF (Bad file descriptor)</code>. We can see that there is a duplicate call to the <code>close</code> syscall for some reason. The code works fine though. But still, does this necessarily mean that I have a bug in my code?</p> <hr /> <p>Upd: if anyone is interested, I have compiled a minimal self-contained example and reported the bug at <a href="https://github.com/python-pillow/Pillow/issues/7042" rel="nofollow noreferrer">https://github.com/python-pillow/Pillow/issues/7042</a></p>
<python><python-imaging-library><system-calls>
2023-03-21 14:43:33
1
1,808
CrabMan
75,802,629
6,137,103
Deny overriding specific fields of a Pydantic model
<p>What is the proper way to restrict child classes to override parent's fields?</p> <p><strong>Example</strong>. I want this to fail:</p> <pre class="lang-py prettyprint-override"><code>class TechData(BaseModel): id: Optional[int] = Field(default=None, alias='_id') class Child(TechData): id: Optional[int] # fail </code></pre> <p>I thought of creating:</p> <pre class="lang-py prettyprint-override"><code>class TechData(BaseModel): _id: Optional[int] = Field(default=None, alias='_id') @final @property def id(self) -&gt; int: return self._id </code></pre> <p>But it seems to be possible only on dataclasses.</p> <p><code>BaseModel</code> checker fails with:</p> <p><code>Field name &quot;id&quot; shadows a BaseModel attribute; use a different field name with &quot;alias='id'&quot;</code></p> <p>Is there a way to keep <code>BaseModel</code> validation and serialization features and forbid overrides of a certain fields?</p>
<python><python-3.x><pydantic>
2023-03-21 14:42:38
2
508
kupihleba
75,802,509
10,714,156
Python: Best way to define and re-use an object for subsequent tests using `pytest`
<p>I have some tests running on my Python package using <code>pytest</code>. However, I am noticing that I am re-writing a lot of times an object that is necessary for the function I am testing.</p> <p>For the sake of the example, consider the following function <code>foo()</code>.</p> <pre><code>def foo(dictionary:dict, key:str): &quot;&quot;&quot; Get the value of a key from a dictionary ---------- Parameters: dictionary: dictionary key: the key to get the value from ---------- Returns: value of the key &quot;&quot;&quot; return dictionary[key] </code></pre> <p>Now, I have another Python script where I have written the following three tests for the <code>foo()</code> function.</p> <pre><code>from mypackage.module_where_foo_is_located import foo def test_foo_one(): dict_used_by_many_tests = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'} actual = foo(dict_used_by_many_tests, &quot;name&quot;) expected = &quot;Dionysia&quot; assert actual == expected def test_foo_two(): dict_used_by_many_tests = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'} actual = foo(dict_used_by_many_tests, &quot;age&quot;) expected = 28 assert actual == expected def test_foo_three(): dict_used_by_many_tests = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'} actual = foo(dict_used_by_many_tests, &quot;location&quot;) expected = &quot;Athens&quot; assert actual == expected </code></pre> <p>Here is my question: what strikes me immediately as <em>&quot;bad form&quot;</em> is the fact that I have the dictionary <code>dict_used_by_many_tests</code> repeated three times... so, <strong>what's the best way to define and re-use it for the three tests?</strong></p> <p>I think one way to do it is simply to define <code>dict_used_by_many_tests = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}</code> once before defining the tests functions, but, it seems very unsafe in situations in which tests might change the content of <code>dict_used_by_many_tests</code> as part of the testing, so subsequent tests will not start with a fresh copy of this shared object. Thank you.</p>
<python><unit-testing><testing><automated-tests><pytest>
2023-03-21 14:29:31
2
1,966
Álvaro A. Gutiérrez-Vargas
75,802,506
2,826,011
Populate pandas dataframe after index values
<p>I have a DataFrame that looks like the one on the left below and I need to re-arrange so it looks like the one on the right:</p> <pre><code> XYZ year month values A B C D 0 A 2006 8 35601 2005-01 NaN NaN NaN NaN 1 A 2005 3 13164 2005-02 36889 NaN NaN NaN 2 A 2006 5 45830 2005-03 13164 NaN NaN NaN 3 A 2005 5 47495 2005-04 NaN NaN NaN NaN 4 A 2005 2 36889 -&gt; . 5 B 2006 1 33694 2006-01 NaN 33694 NaN NaN 6 C 2006 2 7400 2006-02 NaN NaN 7400 NaN 7 C 2006 6 5698 . 8 D 2006 6 14049 . 9 A 2005 9 22650 2006-08 35601 NaN NaN NaN </code></pre> <p>I have created the values that will be used as columns in the new DF, something like:</p> <pre><code>df1 = pd.DataFrame(..., columns=df.XYZ.unique().tolist()) </code></pre> <p>and I have created the values that will be used as index in the new DF, something like:</p> <pre><code>df1 = pd.DataFrame(..., index=pd.date_range('2005-01-01', periods=24,freq='M').to_period('m')) </code></pre> <p>I need help to understand how to iterate through df so that I can use the matching value for each column, based that the new index is mapped correctly to legacy DF values for <code>['year','month']</code></p> <p>Any help is appreciated, thanks!</p>
<python><pandas><dataframe>
2023-03-21 14:29:17
1
2,560
Thanos
75,802,453
1,656,343
Generate SQLAlchemy models from Pydantic models
<p>So I have this large JSON dataset with a huge number of properties (as well as nested objects). I have used <code>datamodel-code-generator</code> to build pydantic models. The JSON data has been imported into pydantic models (with nested models).</p> <p>Now I need to push them into the database.</p> <p>How can I automatically generate SQLAlchemy/SQLModel (or any other ORM) model definition classes from pydantic models?</p> <p>Note: SQLModel and Pydantic seem to have similar syntax for model definition, so I guess I could copy-paste the pydantic models and edit as necessary. But I'm not that familiar with SQLModel yet. I was wondering if there was an automated way to do this.</p>
<python><json><sqlalchemy><pydantic><sqlmodel>
2023-03-21 14:23:54
1
10,192
masroore
75,802,370
10,535,123
Is pandas groupby() function always produce a DataFrame with the same order respect to the column we group by?
<p>Given <code>pd.DataFrame</code> <code>X</code> with column <code>id</code>, is the call to <code>groupby()</code> always return a DataFrame with the same order with respect to the column <code>id</code>?</p> <p><code>X.groupby('id')[col_name].first()</code></p>
<python><pandas>
2023-03-21 14:16:28
1
829
nirkov
75,802,259
231,670
How to keep linters from complaining about type hints that don't match on a technicality?
<p>Considering the toy example:</p> <pre class="lang-py prettyprint-override"><code>def get_dimensions(the_string: str) -&gt; tuple[int, int]: return tuple([int(_) for _ in the_string.split(&quot;x&quot;)]) </code></pre> <p>I <em>know</em> that <code>the_string</code> will only ever contain on <code>x</code> (it's just the output of an <code>ffprobe</code> command), so I'm not concerned that this could return a tuple with more or less than 2 integers, but the reality is that linters like PyCharm are going to rightfully complain about the above as the type hint <code>tuple[int, int]</code> doesn't agree with the possible output of <code>tuple[int,...]</code>.</p> <p>What's the right thing to do here? I can adjust the last line there to use <code>maxsplit=1</code>, but that feels redundant, but I don't know of a way to indicate that <code>the_string</code> should only contain one <code>x</code> either. Is there a &quot;right&quot; way to do this? Should I just change the type hint? Is setting <code>maxsplit=1</code> the preferred albeit pointlessly verbose style? Is there some way to tell the linter not to worry about this?</p>
<python><type-hinting>
2023-03-21 14:06:43
1
6,468
Daniel Quinn
75,802,200
7,822,387
Best way to create 3d matrix of variables in PULP
<p>I want to create a list of variables in PULP that will follow the following structure. There can be any number of types, and each type can have any number of subcat, however each type/subcat must have exactly 2 numbers.</p> <pre><code>type subcat number 1 A 1 1 A 2 1 B 1 1 B 2 2 A 1 2 A 2 </code></pre> <p>I want to create one matrix of LpVariables that look like this, where each item in the list represets each type and is a matrix of subcat X number dimensions.</p> <pre><code>vars = [[&quot;1A1&quot;, &quot;1A2&quot; &quot;1B1&quot;, &quot;1B2&quot;], [&quot;2A1&quot;, &quot;2A2&quot;]] </code></pre> <p>I tried just looping through and creating individual LpVariables using the code below, but then it will create a bunch of individual variables right? So it would be difficult if I wanted to do a sum based on type or subcat.</p> <pre><code>for type in typeList: for subcat in subcatList: for num in range(2): varName = type + ':' + subcat + &quot;:&quot; + num LpVariable(varName, cat='Binary') </code></pre> <p>What would be the best way for me to do this? Thanks in advance</p>
<python><pulp>
2023-03-21 14:00:57
1
311
J. Doe
75,802,162
8,721,169
Set a custom requirements.txt for a Cloud Function
<p>I have several functions in <strong>the same <code>main.py</code> of a unique repo</strong>, each of them being deployed on GCP Cloud Function like that:</p> <ul> <li><code>gcloud functions deploy func1 --entry-point=my_function_1</code></li> <li><code>gcloud functions deploy func2 --entry-point=my_function_2</code></li> <li>...</li> </ul> <p>I have a common <code>requirements.txt</code>. Everything works fine, except <strong>one of my functions needs a specific dependency which is extremely slow to install</strong> (a huge AI-related module). It make all the deployments very slow, since they all share the same <code>requirements.txt</code>.</p> <p><strong>Is it possible to specify a requirement file for just one Cloud Function inside a repo?</strong> Or do you know any workaround (like a way to specify a list of modules to install) that could allow me to custom the requirements of this specific function without affecting the others?</p> <p>I tried to look at the <a href="https://cloud.google.com/functions/docs/writing/specifying-dependencies-python" rel="nofollow noreferrer">doc for specifying dependencies</a>, but it looks like each solution they give is at the repo scale, and not at the function scale.</p> <p>It would be very painful to have a different repo just for solving this. Thanks a lot for any help!</p>
<python><google-cloud-functions>
2023-03-21 13:58:12
1
447
XGeffrier
75,802,128
50,065
Adding --find-links URLs to dependencies in pyproject.toml
<p>You can install the python package <a href="https://github.com/google/jax/blob/main/setup.py" rel="noreferrer">Jax</a> with some extra packages depending on your environment.</p> <p>For GPU:</p> <pre><code>pip install jax[cuda] --find-links https://storage.googleapis.com/jax-releases/jax_cuda_releases.html </code></pre> <p>For TPU:</p> <pre><code>pip install jax[tpu] --find-links https://storage.googleapis.com/jax-releases/libtpu_releases.html </code></pre> <p>How do I add those <code>--find-links</code> URLs to the following <code>pyproject.toml</code>?</p> <pre class="lang-ini prettyprint-override"><code>[build-system] requires = [&quot;setuptools&gt;=67.6.0&quot;] build-backend = &quot;setuptools.build_meta&quot; [project] name = &quot;minimal_example&quot; version = '0.0.1' requires-python = &quot;&gt;=3.9&quot; dependencies = [ &quot;seqio-nightly[gcp,cache-tasks]&quot;, &quot;t5[gcp]&quot;, &quot;t5x @ git+https://github.com/google-research/t5x.git&quot; ] [project.optional-dependencies] cpu = [&quot;jax[cpu]&quot;] gpu = [&quot;jax[cuda]&quot; , &quot;t5x[gpu] @ git+https://github.com/google-research/t5x.git&quot;] tpu = [&quot;jax[tpu]&quot;, &quot;t5x[tpu] @ git+https://github.com/google-research/t5x.git&quot;] dev = [&quot;pytest&quot;, &quot;mkdocs&quot;] </code></pre> <p>If I do <code>pip install -e .</code> then I get a working install. But doing a <code>pip install -e &quot;.[gpu]</code> gives me a <code>ResolutionImpossible</code> error. And doing <code>pip install -e &quot;.[tpu]</code> gives me:</p> <pre><code>Packages installed from PyPI cannot depend on packages which are not also hosted on PyPI. jax depends on libtpu-nightly@ https://storage.googleapis.com/cloud-tpu-tpuvm-artifacts/wheels/libtpu-nightly/libtpu_nightly-0.1.dev20210615-py3-none-any.whl </code></pre>
<python><dependency-management><jax><pyproject.toml>
2023-03-21 13:54:55
0
23,037
BioGeek
75,802,111
1,314,503
groupby and count of values in dataframe
<p>I am having following values in excel/dataframe.</p> <p><a href="https://i.sstatic.net/t9Fpx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/t9Fpx.png" alt="enter image description here" /></a></p> <p>here I need to group by the values by 'Date' column and respectively need to put count of the other 2 field's values. like below,</p> <p><a href="https://i.sstatic.net/blWlu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/blWlu.png" alt="enter image description here" /></a></p> <p>I tried following code, but it's giving only count the dates.</p> <pre><code>df['Date'] = pd.to_datetime(df['Date'], dayfirst=True) df1 = df['Date'].dt.date.value_counts().sort_index().reset_index() df1.columns = ['DATE','Count'] </code></pre> <p>note: having <strong>million</strong> of rows</p>
<python><python-3.x><pandas><dataframe>
2023-03-21 13:53:39
4
5,746
KarSho
75,802,099
6,151,828
Change which axis is used as radial/angular position with matplotlib polar=True (Creating circular phylogenetic tree with Bio.Phylo)
<p>If I create a phylogenetic tree using Biopython Phylo module, it is oriented from left to right, e.g.:</p> <pre><code>import matplotlib.pyplot as plt from Bio import Phylo from io import StringIO handle = StringIO(&quot;(((A,B),(C,D)),(E,F,G));&quot;) tree = Phylo.read(handle, &quot;newick&quot;) fig, ax = plt.subplots(1, 1, figsize=(6, 6)) Phylo.draw(tree, axes=ax, do_show=False) plt.savefig(&quot;./tree_rect.png&quot;) plt.close(fig) </code></pre> <p>produces <a href="https://i.sstatic.net/nQUPi.png?s=256" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nQUPi.png?s=256" alt="enter image description here" /></a></p> <p>If I now try to convert it to a circular tree using the built-in polar transformation of matplotlib, I obtain:</p> <pre><code>fig, ax = plt.subplots(subplot_kw=dict(polar=True), figsize=(6, 6)) Phylo.draw(tree, axes=ax, do_show=False) plt.savefig(&quot;./tree_circ.png&quot;) plt.close(fig) </code></pre> <p>I obtain<br /> <a href="https://i.sstatic.net/TU7tB.png?s=256" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TU7tB.png?s=256" alt="enter image description here" /></a><br /> that is matplotlib takes y-axis as the radial axis and x-axis as the angle. This is the opposite of what I need for obtaining a correct layout, which I can do, e.g., using ete3:</p> <pre><code>from ete3 import Tree, TreeStyle t = Tree(&quot;(((A,B),(C,D)),(E,F,G));&quot;) circular_style = TreeStyle() circular_style.mode = &quot;c&quot; circular_style.scale = 20 t.render(&quot;tree_ete3.png&quot;, w=183, units=&quot;mm&quot;, tree_style=circular_style) </code></pre> <p><a href="https://i.sstatic.net/k5bQg.png?s=256" rel="nofollow noreferrer"><img src="https://i.sstatic.net/k5bQg.png?s=256" alt="enter image description here" /></a></p> <p>(How) could this be done using Bio.Phylo? I suppose the possibilities are</p> <ul> <li>Changing the layout in <code>Phylo.draw</code>, so that the tree is directed upwards</li> <li>telling matplotlib polar transformation to use x-axis as the radial vector and y-axis as the angle</li> </ul> <p>but I don't know how to do either (and whether it can be done.)</p> <p>Related question: <a href="https://stackoverflow.com/q/67686849/6151828">Python: How to convert a phylogenetic tree into a circular format?</a></p>
<python><matplotlib><bioinformatics><biopython><phylogeny>
2023-03-21 13:52:14
1
803
Roger V.
75,802,082
7,012,917
Minor ticks not evenly spaced/aligned with major ticks when setting xlim
<p>I am plotting some timeseries data. I noticed that when plotting the whole timeseries the minor ticks (for the x-axis) are perfectly evenly spaced. But when I set the x-axis limits (<code>xlim</code>), suddenly the minor ticks start getting more and more off-sync.</p> <p>As you can see the minor ticks are perfectly evenly spaced between 2017-01 to 2017-04, but at 2017-07 it is slightly off, then it gets worse at 2017-10 and onwards.</p> <p>Code and figure:</p> <pre><code>plt.figure(figsize=(10,6)) plt.xlim(datetime(2017, 1, 1), datetime(2019, 1, 1)) plt.minorticks_on() plt.plot(df['Date'], df['Price']) </code></pre> <p><a href="https://i.sstatic.net/Bz6eG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Bz6eG.png" alt="pyplot of timeseries with focus on x-axis minor ticks being off" /></a></p> <p>Is there any way to get the minor ticks perfectly spaced? The number of ticks is not that important, just that they are evenly spaced. I don't care about the y-axis for now.</p>
<python><matplotlib>
2023-03-21 13:50:45
3
1,080
Nermin
75,801,932
1,675,615
How to recursively enrich json object with custom field using python jsons
<p>I'm using <a href="https://jsons.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">jsons</a> library and would like to add a custom serializer that for a given type adds a certain field.</p> <p>Naive example:</p> <pre><code>def adjust(obj): if isinstance(obj, MyFoo): json = jsons.dump(obj) json['foo'] = &quot;bar&quot; return json jsons.set_serializer(lambda obj, **_: adjust(obj), MyFoo) json = jsons.dump(data, ensure_ascii=True) </code></pre> <p>This doesn't work because it goes into infinite recursion. I tried playing with forks but couldn't make it work.</p> <p>What is important, <code>MyFoo</code> might appear inside other <code>MyFoo</code>s and so the serializer must work on all levels.</p>
<python><python-jsons>
2023-03-21 13:35:37
1
1,467
Krever
75,801,738
9,769,953
importlib.metadata doesn't appear to handle the authors field from a pyproject.toml file correctly
<p>I'm having a problem retrieving the author metadata information of a package through <a href="https://docs.python.org/3.11/library/importlib.metadata.html" rel="nofollow noreferrer"><code>importlib.metadata</code></a>.</p> <p>My package setup is as follows:</p> <p>I'm using Python's <code>setuptools</code> with a minimal <code>setup.py</code> and some project metadata in <code>pyproject.toml</code>.</p> <p><code>setup.py</code>:</p> <pre><code>from setuptools import setup setup() </code></pre> <p><code>pyproject.toml</code>:</p> <pre><code>[project] name = &quot;myproj&quot; version = &quot;0.1.0&quot; description = &quot;Some description&quot; authors = [ {name = &quot;Some One&quot;, email = &quot;some.one@example.com&quot;}, {name = &quot;Another Person&quot;, email = &quot;another.person@example.com&quot;} ] readme = &quot;README.md&quot; requires-python = &quot;&gt;=3.11&quot; license = {text = &quot;BSD-3-Clause&quot;} [build-system] requires = [&quot;setuptools&quot;] build-backend = &quot;setuptools.build_meta&quot; </code></pre> <p>(I think <code>setup.py</code> is not even necessary for this, but for completeness.)</p> <p>The <code>pyproject.toml</code> follows keywords described in <a href="https://packaging.python.org/en/latest/specifications/declaring-project-metadata/" rel="nofollow noreferrer">the Python packaging user guide - Declaring project metadata</a>.</p> <p>The project itself is very simple: it's structure is</p> <pre><code>myproj/ __init__.py </code></pre> <p>and in <code>myproj/__init__.py</code>, I'm using <code>importlib.metadata</code> to get some metadata information about the package.:</p> <pre><code>from importlib.metadata import metadata meta = metadata(__package__ or __name__) print(meta['Name']) print(meta['Version']) print(meta['Author-email']) print(meta['Author']) </code></pre> <p>I install the package in a virtualenv using <code>pip</code>.</p> <p>Outside of the project directory, but with the virtualenv activated, I run Python and import the package:</p> <pre><code>python -c &quot;import myproj&quot; </code></pre> <p>This prints the various metadata fields:</p> <pre><code>myproj 0.1.0 Some One &lt;some.one@example.com&gt;, Another Person &lt;another.person@example.com&gt; None </code></pre> <p>This is where the problem is: the &quot;Author-email&quot; field yields the full <code>[project.authors]</code> entry, as a single string, while the &quot;Author&quot; field yields <code>None</code>.</p> <p>Is there a way to get the individual authors (without their email) out of the metadata from within the package?</p> <p>Or is <code>importlib.metadata</code> not up to date with the packaging metadata? (I did a quick search on bugs.python.org, but couldn't find anything related.)</p> <p>(Of course, I can parse the &quot;Author-email&quot; field manually and separate it into appropriate parts, but it would be nice if that can be avoided.)</p>
<python><setuptools><packaging><python-importlib>
2023-03-21 13:17:08
1
12,459
9769953
75,801,619
10,192,593
Slicing numpy arrays in a for loop
<p>I have a multidimentional numpy array of elasticities with one of the dimensions being &quot;age-groups&quot; (0-92 years) and the other &quot;income-groups&quot; (low/high income).</p> <p>I would like to create a table with the mean elasticities for each combination of subgroups using a for loop.</p> <p>My code is as follows:</p> <pre><code>import numpy as np elasticity = np.random.rand(2,92) print(elasticity.shape) income = ['i0','i1'] age_gr= [':18','18:'] table = {} for i in range(len(age_gr)): for j in range(len(income)): key = age_gr[i]+&quot;_&quot;+income[j] table[key] = np.mean(elasticity[age_gr[i],j]) print(table) </code></pre> <p>My problem is that &quot;age_gr[i]&quot; gives me an error &quot;IndexError: only integers, slices (<code>:</code>), ellipsis (<code>...</code>), numpy.newaxis (<code>None</code>) and integer or boolean arrays are valid indices &quot;. In reality I have many more age-groups, so I can't do this manually.</p> <p>I would like to have something like this as a result:</p> <p><a href="https://i.sstatic.net/DjyaF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DjyaF.png" alt="enter image description here" /></a></p> <p>with ... representing the mean of elasticities for the sub-group.</p> <p>EDIT: Age dimension runs from 0-92 years NOT (below/above 18 years) as stated before.</p>
<python><numpy><numpy-slicing>
2023-03-21 13:05:48
1
564
Stata_user
75,801,560
7,596,102
Use BytesIO instead of NamedTemporaryFile with openpyxl
<p>I understand that with <code>openpyxl&gt;=3.1</code> function <code>save_virtual_workbook</code> is gone and preferred solution is using <code>NamedTemporaryFile</code>.</p> <p>I want it to be done without writing to filesystem, only in memory, just like <code>BytesIO</code> did.</p> <p>Before update I had:</p> <pre><code>wb = Workbook() populate_workbook(wb) return BytesIO(save_virtual_workbook(wb)) </code></pre> <p>Now I need:</p> <pre><code>wb = Workbook() populate_workbook(wb) tmpfile = NamedTemporaryFile() wb.save(tmpfile.name) return tmpfile </code></pre> <p>As in <a href="https://openpyxl.readthedocs.io/en/3.1/tutorial.html?highlight=save#saving-as-a-stream" rel="nofollow noreferrer">https://openpyxl.readthedocs.io/en/3.1/tutorial.html?highlight=save#saving-as-a-stream</a></p> <p>As I'm using django probably I could use <code>InMemoryUploadedFile</code> but I don't want to.</p> <p>How can I use <code>BytesIO</code> or something similar in elegant fashion ie. without hacks and additional packages?</p>
<python><django><openpyxl>
2023-03-21 12:58:20
2
405
qocu
75,801,556
19,155,645
how to access folder in 'shared with me' drive from colab notebook
<p>I have a Jupyter notebook that needs access to a .csv data file. I intend to make these accessible for other people in my group, and I want it to work directly for them too, without the need to change the directory, or manually import data, or even 'save shortcut in drive'.</p> <p>At the moment both files (.ipynb and .csv) are in the same folder on my drive, but when I share the folder, the data file is not accessible to the other people (the <code>pwd</code> is set to <code>/content</code>, and even with mounting the drive, I dont get access to the 'shared with me folder'.</p> <p>Is there a workaround to allow for direct usage of the .csv file? idealy I just have a cell that copies the csv from the drive to the content folder, but I dont know how to access it:</p> <pre><code>!cp $where_is_the_folder? data.csv /content </code></pre> <p>It is very important that the other people don't need to do anything in order to run the notebook.</p> <p>I also tried the suggestion <a href="https://stackoverflow.com/questions/54351852/accessing-shared-with-me-with-colab">to use PyDrive and auth as here</a> but it does not seem to work.</p> <p>At the moment this is the full code, but obviously it only works on my drive, not on others i share it with:</p> <pre><code>import pandas as pd from google.colab import drive drive.mount('/content/drive') !cp /content/drive/MyDrive/project_folder/data.csv /content dataFrame = pd.read_csv('/content/data.csv') </code></pre> <p>note that the notebook and the data.csv are in the same directory (<code>/content/drive/MyDrive/project_folder</code>)</p>
<python><jupyter-notebook><google-drive-api><google-colaboratory>
2023-03-21 12:57:55
1
512
ArieAI
75,801,520
2,016,632
I'm unable to build CPython from scratch on Linux because of inability to find encodings Module. What am I missing?
<p>I have an old Centos 7 system. It has one user [plus root] and has python2.7 and python3.6.8 installed. The latter has binary <code>/bin/python3</code> Neither PYTHONHOME nor PYTHONPATH are defined. Python3 runs fine, for example, <code>print(encodings.__file__) </code> gives <code>usr/lib64/python3.6/encodings/__init__.py</code> but I need to upgrade it. There do not appear to be modern repositories for Centos 7 now, so I'll build by scratch. No problem....</p> <p>So I <code>git clone Python.3.11.2</code> (also tried 3.11.0a4) and <code>tar xvf</code> to create a directory and cd to that directory. The following fails</p> <pre><code>./configure make </code></pre> <p>with an error</p> <pre><code>Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' </code></pre> <p>The error is hit when trying to run <code>_bootstrap_python</code>. I've tried solving this a bunch of different ways. For example, trying a prefix gives this printout:</p> <pre><code>./_bootstrap_python ./Programs/_freeze_module.py abc ./Lib/abc.py Python/frozen_modules/abc.h Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = './_bootstrap_python' isolated = 0 environment = 0 user site = 0 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = '/usr/local/lib/python3.11' sys._base_executable = '/bin/python3' sys.base_prefix = '/usr/local' sys.base_exec_prefix = '/usr/local' sys.platlibdir = 'lib' sys.executable = '/home/xuser/analysis/Python-3.11.2/_bootstrap_python' sys.prefix = '/usr/local' sys.exec_prefix = '/usr/local' sys.path = [ '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload', ] </code></pre> <p>I've tried running the configure inside a virtualenv. I've run it as xuser. I've run it as root.... It keeps stumbling on the same point. The download of 3.11 has perfectly fine encodings sitting inside the its <code>Lib</code> directory, but I think they are not getting copied over to the destination where makefile expects them.</p> <p>Doubtless a dumb mistake of mine, but damned if I can find it. I did see some old discussions on stackoverflow to change the contents of <code>.ini</code> file (I dont have an <code>.ini</code> file) and/or to edit PYTHONPATH to something else. [No matter what I set that path to, it still shows up as &quot;not set&quot; in the configuration listed by bootstrap, so I dont think that is the solution.] My guess is a definition needs to be passed to .configure. But what?</p> <p>Looking at that print out, I see that <code>sys._base_executable</code> is pointing at 3.6.8, which is suspicious (why does it care about old python?)</p>
<python><centos7>
2023-03-21 12:54:59
2
619
Tunneller
75,801,389
4,436,572
Polars replace_time_zone and convert_time_zone show different string representation for same timezone conversion
<p>Test Data:</p> <pre><code>import polars as pl import pandas as pd from datetime import date, time, datetime # polars df for Jan to 12th, March 2022 before DST transition. tdf = pl.DataFrame( pl.date_range( low=date(2022, 1, 3), high=date(2022, 3, 12), interval=&quot;5m&quot;, time_unit=&quot;ns&quot;, time_zone=&quot;UTC&quot;, ).alias(&quot;UTC&quot;) ) </code></pre> <p>My use case is to convert UTC data (or timezone-unaware) to EST/EDT data (or timezone-aware), then filter the data on a time range (9:30 to 16:00).</p> <pre><code>tz_replaced_filtered = tdf.with_columns( pl.col(&quot;UTC&quot;).dt.replace_time_zone(time_zone=&quot;US/Eastern&quot;).alias(&quot;NY&quot;) ).filter( pl.col(&quot;NY&quot;).cast(pl.Time).is_between(time(9), time(16), closed=&quot;both&quot;) ) # output shape: (5780, 2) ┌─────────────────────────┬──────────────────────────┐ │ UTC ┆ NY │ │ --- ┆ --- │ │ datetime[ns, UTC] ┆ datetime[ns, US/Eastern] │ ╞═════════════════════════╪══════════════════════════╡ │ 2022-01-03 04:00:00 UTC ┆ 2022-01-03 04:00:00 EST │ │ 2022-01-03 04:05:00 UTC ┆ 2022-01-03 04:05:00 EST │ │ 2022-01-03 04:10:00 UTC ┆ 2022-01-03 04:10:00 EST │ │ 2022-01-03 04:15:00 UTC ┆ 2022-01-03 04:15:00 EST │ │ … ┆ … │ │ 2022-03-11 10:45:00 UTC ┆ 2022-03-11 10:45:00 EST │ │ 2022-03-11 10:50:00 UTC ┆ 2022-03-11 10:50:00 EST │ │ 2022-03-11 10:55:00 UTC ┆ 2022-03-11 10:55:00 EST │ │ 2022-03-11 11:00:00 UTC ┆ 2022-03-11 11:00:00 EST │ └─────────────────────────┴──────────────────────────┘ </code></pre> <p>Apparently there's no obvious 9 to 16 time range in this resulted <code>df</code>.</p> <p>I probed further:</p> <pre><code>tz_replaced_filtered.with_columns( pl.col(&quot;NY&quot;).cast(pl.Time).alias(&quot;NY_TIME&quot;), pl.col(&quot;UTC&quot;).cast(pl.Time).alias(&quot;UTC_TIME&quot;) ) # output shape: (5780, 4) ┌─────────────────────────┬──────────────────────────┬──────────┬──────────┐ │ UTC ┆ NY ┆ NY_TIME ┆ UTC_TIME │ │ --- ┆ --- ┆ --- ┆ --- │ │ datetime[ns, UTC] ┆ datetime[ns, US/Eastern] ┆ time ┆ time │ ╞═════════════════════════╪══════════════════════════╪══════════╪══════════╡ │ 2022-01-03 04:00:00 UTC ┆ 2022-01-03 04:00:00 EST ┆ 09:00:00 ┆ 04:00:00 │ │ 2022-01-03 04:05:00 UTC ┆ 2022-01-03 04:05:00 EST ┆ 09:05:00 ┆ 04:05:00 │ │ 2022-01-03 04:10:00 UTC ┆ 2022-01-03 04:10:00 EST ┆ 09:10:00 ┆ 04:10:00 │ │ 2022-01-03 04:15:00 UTC ┆ 2022-01-03 04:15:00 EST ┆ 09:15:00 ┆ 04:15:00 │ │ … ┆ … ┆ … ┆ … │ │ 2022-03-11 10:45:00 UTC ┆ 2022-03-11 10:45:00 EST ┆ 15:45:00 ┆ 10:45:00 │ │ 2022-03-11 10:50:00 UTC ┆ 2022-03-11 10:50:00 EST ┆ 15:50:00 ┆ 10:50:00 │ │ 2022-03-11 10:55:00 UTC ┆ 2022-03-11 10:55:00 EST ┆ 15:55:00 ┆ 10:55:00 │ │ 2022-03-11 11:00:00 UTC ┆ 2022-03-11 11:00:00 EST ┆ 16:00:00 ┆ 11:00:00 │ └─────────────────────────┴──────────────────────────┴──────────┴──────────┘ </code></pre> <p>The underlying timestamps does seem to show that I succeed in filtering on time range 9 to 16; and it is only the string representation which isn't in sync.</p> <pre><code> tdf.with_columns( pl.col(&quot;UTC&quot;).dt.replace_time_zone(time_zone=&quot;US/Eastern&quot;).alias(&quot;NY_REPLACED&quot;), pl.col(&quot;UTC&quot;).dt.convert_time_zone(time_zone=&quot;US/Eastern&quot;).alias(&quot;NY_CONVERTED&quot;) ) # output shape: (19585, 3) ┌─────────────────────────┬──────────────────────────┬──────────────────────────┐ │ UTC ┆ NY_REPLACED ┆ NY_CONVERTED │ │ --- ┆ --- ┆ --- │ │ datetime[ns, UTC] ┆ datetime[ns, US/Eastern] ┆ datetime[ns, US/Eastern] │ ╞═════════════════════════╪══════════════════════════╪══════════════════════════╡ │ 2022-01-03 00:00:00 UTC ┆ 2022-01-03 00:00:00 EST ┆ 2022-01-02 19:00:00 EST │ │ 2022-01-03 00:05:00 UTC ┆ 2022-01-03 00:05:00 EST ┆ 2022-01-02 19:05:00 EST │ │ 2022-01-03 00:10:00 UTC ┆ 2022-01-03 00:10:00 EST ┆ 2022-01-02 19:10:00 EST │ │ 2022-01-03 00:15:00 UTC ┆ 2022-01-03 00:15:00 EST ┆ 2022-01-02 19:15:00 EST │ │ … ┆ … ┆ … │ │ 2022-03-11 23:45:00 UTC ┆ 2022-03-11 23:45:00 EST ┆ 2022-03-11 18:45:00 EST │ │ 2022-03-11 23:50:00 UTC ┆ 2022-03-11 23:50:00 EST ┆ 2022-03-11 18:50:00 EST │ │ 2022-03-11 23:55:00 UTC ┆ 2022-03-11 23:55:00 EST ┆ 2022-03-11 18:55:00 EST │ │ 2022-03-12 00:00:00 UTC ┆ 2022-03-12 00:00:00 EST ┆ 2022-03-11 19:00:00 EST │ └─────────────────────────┴──────────────────────────┴──────────────────────────┘ </code></pre> <p>This final step concludes that <code>replaced_time_zone</code> and <code>convert_time_zone</code> does not generate the same string representation for an identical time zone conversion operation.</p> <p>More specifically, <code>replaced_time_zone</code> does replace the underlying timestamps however it does not &quot;replace&quot; the string representation; what <code>replaced_time_zone</code> does on the surface for UTC (or simply timezone-unaware timestamps) is like <code>with_time_zone</code>, i.e., simply attaching time zone info to existing time stamps.</p> <p>I'd appreciate if someone could clarify above.</p> <p><strong>Question Background</strong></p> <p>This is for polars users and devs such that all questions related to timezone conversion raised by me for <code>polars</code> can be easily referenced.</p> <p>I firstly raised <a href="https://stackoverflow.com/questions/74165901/polars-add-substract-utc-offset-from-datetime-object">this</a> to see how we could filter based on converted timestamps (utc offset accounted for), then as <code>polars</code> provided <code>replace_time_zone</code> a <a href="https://stackoverflow.com/questions/75793219/polars-replace-time-zone-function-throws-error-of-no-such-local-time">question</a> for it is also raised.</p> <p>A related question metioned by @FObersteiner is <a href="https://stackoverflow.com/questions/75268283/how-to-truncate-a-datetime-to-just-the-day">here</a>.</p> <p>For the time being my understanding is that <code>replace_time_zone</code> should provide the same string representation as <code>convert_time_zone</code>, because essentially what they are doing it the same. And this would make filtering on date/time range in <code>polars</code> WYSIWYG (What You See Is What You Get).</p> <p><strong>Background Information</strong></p> <p><code>Polars</code> provides <code>replace_time_zone</code> and <code>convert_time_zone</code> to handle scenarios like this.</p> <p><code>convert_time_zone</code> changes only the string representation presented to the user, not the underlying timestamps. Therefore <code>cast</code> is not going to work with &quot;converted&quot; timestamps in my use case (filtering would still be on the orignal underlying timestamps).</p> <p>Regarding <code>replace_time_zone</code>, DST transitions is causing <a href="https://stackoverflow.com/questions/75793219/polars-replace-time-zone-function-throws-error-of-no-such-local-time">problem</a> when user tries to <code>replace_time_zone</code> and this issue seems to be universal given that particular timestamp just doesn't exist because of DST transition:</p> <pre><code># demo polars df tpl = pl.DataFrame( pl.date_range( low=date(2022, 3, 13), high=date(2022, 3, 15), interval=&quot;5m&quot;, time_unit=&quot;ns&quot;, time_zone=&quot;UTC&quot;, ).alias(&quot;UTC&quot;) ) tpl.select( pl.col(&quot;UTC&quot;).dt.replace_time_zone(time_zone=&quot;America/New_York&quot;).alias(&quot;NY&quot;) ) # Panic Exception: no such local time # demo pandas pf tpn = pd.DataFrame( pd.date_range(start=&quot;2022-03-13&quot;, end=&quot;2022-03-15&quot;, freq=&quot;5T&quot;, # 5 minute interval tz=None, # default to UTC inclusive=&quot;both&quot;), columns=[&quot;UTC&quot;] ) tpn.UTC.dt.tz_localize(&quot;America/New_York&quot;) # NonExistentTimeError: 2022-03-13 02:00:00 </code></pre>
<python><date><datetime><time><python-polars>
2023-03-21 12:43:42
1
1,288
stucash
75,801,279
11,143,347
The passed model is not callable and cannot be analyzed directly with the given masker! Model: Pipeline()
<p>I have trained a model then have saved its pickle, I want to perform a shap analysis on the validation set &quot;X_val&quot;, I've set the code as follows:</p> <pre><code>import joblib import shap from lightgbm import LGBMClassifier # Load the model from the pickle file model = joblib.load(&quot;model.pkl&quot;) # Create an explainer object for the model explainer = shap.Explainer(model) # Compute SHAP values for the validation data shap_values = explainer(X_val) # Plot the SHAP values shap.plots.waterfall(shap_values[0]) # Replace 0 with the index of the instance you want to visualize </code></pre> <p>but I got this error :</p> <pre><code>Exception: The passed model is not callable and cannot be analyzed directly with the given masker! Model: Pipeline(steps=[('column_selector', --------------------------------------------------------------------------- Exception Traceback (most recent call last) &lt;command-1911364825105189&gt; in &lt;module&gt; 5 6 # Create an explainer object for the model ----&gt; 7 explainer = shap.Explainer(model) 8 9 # Compute SHAP values for the validation data /databricks/python/lib/python3.8/site-packages/shap/explainers/_explainer.py in __init__(self, model, masker, link, algorithm, output_names, feature_names, linearize_link, **kwargs) 166 # if we get here then we don't know how to handle what was given to us 167 else: --&gt; 168 raise Exception(&quot;The passed model is not callable and cannot be analyzed directly with the given masker! Model: &quot; + str(model)) 169 170 # build the right subclass Exception: The passed model is not callable and cannot be analyzed directly with the given masker! Model: Pipeline(steps=[('column_selector', ColumnSelector(cols=['A', 'b', 'c']), ('standardizer', StandardScaler()), ('classifier', LGBMClassifier(colsample_bytree=0.53, lambda_l1=0.6423636335585889, learning_rate=0.013, max_bin=173, max_depth=9, n_estimators=1758, subsample=0.68))]) </code></pre> <p>I would like some help, please.</p> <p>Thank you,</p> <p>regards.</p>
<python><pandas><machine-learning><lightgbm><shap>
2023-03-21 12:33:46
0
452
Sara
75,801,123
239,923
How do I assign a new column to polars dataframe?
<p>In polars, I am trying to create a new column I already know the values of the columns and I just want to add a column with those values. Below is the code</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({&quot;a&quot;: [1, 2], &quot;b&quot;: [4, 5]}) english_titles = [&quot;ok&quot;, &quot;meh&quot;] df.with_columns(pl.lit(english_titles).alias(&quot;english_title&quot;)) </code></pre> <pre><code>┌─────┬─────┬───────────────┐ │ a ┆ b ┆ english_title │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ list[str] │ ╞═════╪═════╪═══════════════╡ │ 1 ┆ 4 ┆ [&quot;ok&quot;, &quot;meh&quot;] │ │ 2 ┆ 5 ┆ [&quot;ok&quot;, &quot;meh&quot;] │ └─────┴─────┴───────────────┘ </code></pre> <p>But the above doesn't work and I think it's because I am using <code>pl.lit</code> wrongly.</p> <p>I want a <code>str</code> column instead of <code>list[str]</code></p> <pre><code>┌─────┬─────┬───────────────┐ │ a ┆ b ┆ english_title │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞═════╪═════╪═══════════════╡ │ 1 ┆ 4 ┆ ok │ │ 2 ┆ 5 ┆ meh │ └─────┴─────┴───────────────┘ </code></pre>
<python><dataframe><python-polars>
2023-03-21 12:19:20
1
16,264
xiaodai
75,801,049
8,279,555
Use CSV data downloaded from ftp with csv.reader
<p>I'm working on a little script that downloads a csv file from a ftp server, and when downloaded i want to do some calulations on each row before i write it to a new file.</p> <p>i have the ftp part working, but i cant figure out how to use the BytesIO data as csv data.</p> <p>Im using the code below but that prints 0 rows.</p> <p>Any help or push in the right direction would be very appreciated.</p> <pre><code>from ftplib import FTP import io ftp = FTP(FTP_SERVER) ftp.login(FTP_USER, FTP_PASSWORD) csv_data = io.BytesIO() ftp.retrbinary('RETR ' + FTP_FILE, csv_data.write) csv_reader = csv.reader(csv_data, delimiter=&quot;,&quot;) for row in csv_reader: print(row) </code></pre>
<python><csv><ftp>
2023-03-21 12:11:47
1
484
VA79
75,801,017
3,832,272
Glue in JupyterNotebook
<p>A while ago I was successfully able to insert variables/strings from a code into the markdown of JupyterNotebook. I followed these steps:</p> <pre><code>from myst_nb import glue a = 5*5 glue(&quot;results&quot;, a) </code></pre> <p>And then I inserted the variable in the markdown section:</p> <p><code> My calculation of the 5x5 gave the result of {{results}}.</code></p> <p>Obviously the <code>a= 25</code>.</p> <p>Currently, the curly brackets do not show 25 in the markdown and I don't understand why.</p> <p>Could someone point me to what have changed?</p> <p>Many thanks in advance</p>
<python><jupyter-notebook><module><markdown>
2023-03-21 12:08:10
1
315
Jo-Achna
75,800,972
1,581,090
How to use subprocess.run with correct path on windows?
<p>On windows 10 using python 3.10.10 I am trying to run a windows executable, but there is some issue with the path to the folder of the executable. I am trying to run the following code</p> <pre><code>path = r&quot;C:/Program Files (x86)/STMicroelectronics/STM32Cube/STM32CubeProgrammer/bin&quot; result = subprocess.run(command, cwd=path) </code></pre> <p>but I get the error</p> <pre><code>FileNotFoundError: [WinError 2] The system cannot find the file specified </code></pre> <p>(with and without the <code>r</code>). I guess I have to &quot;convert&quot; the path somehow? But how exactly?</p> <p>Also, the path DOES exist, and I am using similar path expressions (with the slash (<code>/</code>)) for other windows paths in the same python application running on windows.</p>
<python><windows>
2023-03-21 12:04:16
1
45,023
Alex
75,800,935
7,603,109
urllib: TypeError: expected string or bytes-like object
<p>I am trying to make an API call where I pass a file in the header</p> <pre><code>import urllib.request headers = {'files[]': open('File.sql','rb')} datagen ={} request = urllib.request.Request('https://www.rebasedata.com/api/v1/convert', datagen, headers) response1 = urllib.request.urlopen(request) # Error : TypeError: expected string or bytes-like object response2 = urllib.request.urlopen('https://www.rebasedata.com/api/v1/convert', datagen, headers) #Error: 'dict' object cannot be interpreted as an integer </code></pre> <p>The error I am retrieving is:</p> <blockquote> <p>TypeError: expected string or bytes-like object</p> </blockquote> <p>Any help will be appreciated</p>
<python><urllib><urllib3>
2023-03-21 12:02:08
1
22,283
Adrita Sharma
75,800,926
55,934
How can I improve the accuracy of OpenCV checkerboard detection in this case?
<p>I would like to track the location of checkerboard corners in this stereo fisheye camera, using OpenCV in Python.</p> <p><a href="https://i.sstatic.net/2STMl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2STMl.png" alt="Stereo fisheye checkerboard" /></a></p> <p>To help the algorithm, I am only running the checkerboard detection on the parts of the image where I know the checkerboard is. Here is the code I use for one side of the image. Similar code is used for the other checkerboard on the right.</p> <pre class="lang-py prettyprint-override"><code> # Extract the left checkerboard img_L = img[box_L[0][1]:box_L[1][1], box_L[0][0]:box_L[1][0]] # Detect corners ret_L, corners_L = cv2.findChessboardCorners(img_L, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE) if ret_L: # Improve accuracy corners_L = cv2.cornerSubPix(img_L, corners_L, (5,5),(-1,-1), criteria) # Draw the vertices img_L = cv2.drawChessboardCorners(img_L, CHECKERBOARD, corners_L, ret_L) # And draw it back into the main image InsertImage(img, img_L, box_L[0]) </code></pre> <p><a href="https://i.sstatic.net/eCEdv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eCEdv.png" alt="Stereo fisheye checkerboard with detection markers" /></a></p> <p>As you can see, the quality of the image isn't great, and the detector has some difficulty making a good detection. The checkerboards won't move very far, but I do need to know their location and shape accurately for calibration.</p> <p>About a third of the time, the left half doesn't detect a checkerboard at all (as you can see in this image), and the vertices jitter about quite a bit.</p> <p>There's not a lot I can do to improve the image quality due to the physical nature of my setup and these cameras.</p> <p><strong>Questions:</strong></p> <ol> <li>What can I do to improve the checkerboard detection?</li> <li>Is there a better checkerboard detector available in OpenCV?</li> </ol> <p>As far as I understand, the checkerboard detector is only detecting the corners using a saddle detector. Perhaps there's some kind of algorithm which can use the intersections of the long straight edges to help improve accuracy? For example, is there a function to help fit Bézier curves to the lines of the checkerboard, then I can do intersections to get the vertices? Here is an illustration I made using a paint program:</p> <p><a href="https://i.sstatic.net/kJ7fD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kJ7fD.png" alt="Checkerboard intersections" /></a></p>
<python><algorithm><opencv>
2023-03-21 12:01:16
1
5,950
Rocketmagnet
75,800,905
2,300,369
Implement order definition by multiple attributes
<p>I'd like to know how to efficiently sort by object's multiple attributes. For instance, given</p> <pre><code>class A: def __init__(self, a, b): self.a = a self.b = b def __lt__(self, other): if self.a == other.a: return self.b &lt; other.b return self.a &lt; other.a def __str__(self): return f'{self.__class__.__name__}({self.a}, {self.b})' A1 = A(1, 5) A2 = A(2, 5) A3 = A(1, 6) A4 = A(4, 0) A5 = A(-3, -3) A6 = A(0, 7) l = [A1, A2, A3, A4, A5, A6] </code></pre> <p>The expected order of class A instances after sorting is <code>A5, A6, A1, A3, A2, A4</code>, i.e.</p> <pre><code>A(-3, -3) A(0, 7) A(1, 5) A(1, 6) A(2, 5) A(4, 0) </code></pre> <p>because I want to order by both attributes <code>a</code> and <code>b</code> values. However, with the increasing number of attributes the logic relying on embedded conditional statements, e.g.</p> <pre><code>class A: def __init__(self, a, b, c=1): self.a = a self.b = b self.c = c def __lt__(self, other): if self.a == other.a: if self.b == other.b: return self.c &lt; other.c return self.b &lt; other.b return self.a &lt; other.a </code></pre> <p>seems to be cumbersome.</p> <p>Do you have a better idea to implement such a sorting for a custom object? I was expecting the short circuit to do the trick:</p> <pre><code> def __lt__(self, other): return self.a &lt; other.a or self.b &lt; other.b </code></pre> <p>but it generated following order:</p> <pre><code>A(-3, -3) A(0, 7) A(4, 0) A(1, 5) A(1, 6) A(2, 5) </code></pre> <p>which is not what I want.</p>
<python><sorting><oop>
2023-03-21 11:58:53
3
308
user2300369
75,800,672
8,506,921
Accessing model when creating new python package
<p>I'm making a python package where the main functionality is using a model that I've trained. I want it to be as easy as possible to access the model for end users so they can just use the main functions without needing to actively go find and download the model separately.</p> <p>I initially thought I would just include the model file in the package but it is on the large side (~95MB) and Github warns me about it so my feeling is I should try find an alternative way.</p> <p>I've tried compressing the model by zipping it but that doesn't make much of a dent in the file size. The model itself is fixed so I can't reduce the size by training an alternative version with different hyperparameters.</p> <p>My solution at the moment is to not include the model and instead download it from s3 when the relevant class is used (this is an internal package, so everybody using it would hypothetically have access to the s3 bucket). However, I don't really like this solution because it requires users to have things set up to access AWS with a specific role, and even if I include examples / documentation / hints in error messaging, I can imagine the experience not being ideal. They also have the option of passing a file path if they have the model saved somewhere, but again that requires some initial setup.</p> <p>I've tried researching ways to access / package models but haven't come up with much.</p> <p>So my questions are:</p> <ul> <li>Is there a way to include this model in the package?</li> <li>Are there other ways to access the model that I haven't thought about?</li> </ul>
<python><python-packaging>
2023-03-21 11:35:55
1
1,874
Jaccar
75,800,636
9,418,052
Google Ads API "RefreshError: ('unauthorized_client: Unauthorized', {'error': 'unauthorized_client', 'error_description': 'Unauthorized'})"
<p>I am trying to make a call to Google Ads API to access campaign data in python. I have completed the following steps:</p> <ol> <li>Created a web app and enabled Google-Ads API</li> <li>Saved JSON file that contains client id and secret information</li> <li>Generated refresh token</li> <li>Updated google-ads yaml file based on the client id, client secret, refresh token, developer token and customer id</li> </ol> <p>However when I try this:</p> <pre><code>from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient.load_from_storage(&quot;google-ads.yaml&quot;) </code></pre> <p>I get the error:</p> <blockquote> <p>RefreshError: ('unauthorized_client')</p> </blockquote> <p>I have rechecked for any typos or white-spaces. I have the &quot;Standard Access&quot; on my email id: on Google-Ads account under the Access and Security section. Any help would be really great.</p>
<python><google-ads-api>
2023-03-21 11:32:06
3
404
Ankit Tripathi
75,800,596
17,194,313
How to you write polars data frames to Azure blob storage?
<p>Given a parquet file in Azure blob storage, this can be read into a polars dataframe using</p> <pre class="lang-py prettyprint-override"><code>pl.read_parquet('az://{container-name}/{filename}', storage_options={'account_name': ..., 'account_key': ...}) </code></pre> <p>(the above works via the optional dependency on <code>adlfs</code>)</p> <p>Is there anything equivalent to <code>write_parquet</code>?</p>
<python><azure-blob-storage><python-polars>
2023-03-21 11:28:10
2
3,075
MYK
75,800,587
1,747,029
Use SI units in sympy rather than Hartree units
<p>I am trying to use <code>sympy</code> to calculate wave functions for the hydrogen atom, and would like to use SI units rather than Hartree units. The documentation gives lots of examples, but all using Hartree units. Is there a way of switching to SI units?</p>
<python><sympy><physics>
2023-03-21 11:27:02
1
594
Graham G
75,800,558
860,202
Find all possible sums of the combinations of integers from a set, efficiently
<p>Given an integer n, and an array a of x random positive integers, I would like to find all possible sums of the combinations with replacement (n out of x) that can be drawn from this array.</p> <p>For example:</p> <pre><code>n = 2, a = [2, 3, 4, 6] all combinations = [2+2, 2+3, 2+4, 2+6, 3+3, 3+4, 3+6, 4+4, 4+6, 6+6] all unique sums of these combination = {4, 5, 6, 7, 8, 9, 10, 12} </code></pre> <p>This can of course easily be solved by enumerating and summing all possible combinations, for example in Python:</p> <pre><code>from itertools import combinations_with_replacement n = 2 a = [2,3,4,6] {sum(comb) for comb in combinations_with_replacement(a, n)} </code></pre> <p>Is there a more efficient way to do this? I have to do this for n up to 4 and a up to a 1000 values, which gives 4e10 combinations, while the number of unique sums will be several orders of magnitude less for arrays with integers whose values aren't too far apart, so I would guess there must be a more efficient way.</p> <p>For example when n=3 and a is the set of the first 1000 even numbers, there will be only 2998 unique sums out of 1.6E8 possible combinations.</p> <p>** Original question was updated to state that integers are only positive</p>
<python><algorithm><math><optimization>
2023-03-21 11:24:07
1
684
jonas87
75,800,493
14,786,813
Official Flax Example "Imagenet" is Bugged
<p>I have tried to use run the official <a href="https://colab.research.google.com/github/google/flax/blob/main/examples/imagenet/imagenet.ipynb" rel="nofollow noreferrer">Flax/ImageNet</a> code. Due to the difference in jax version, I have tried two methods. The <a href="https://colab.research.google.com/gist/rwbfd/404df0d4df59da59d4e066fd12262c92/imagenet_error1.ipynb" rel="nofollow noreferrer">first example</a> I downgrade jax and jaxlib 0.3.25, and in the second example I change jax and jaxlib to 0.4.4. Then I setup TPU as</p> <pre><code>import jax.tools.colab_tpu jax.tools.colab_tpu.setup_tpu() import jax jax.local_devices() </code></pre> <p>which also shows that the TPU are properly set up.</p> <p>However, as I continue run the code, both version gives this error.</p> <pre><code>/usr/local/lib/python3.9/dist-packages/flax/__init__.py in &lt;module&gt; 20 ) 21 ---&gt; 22 from . import core 23 from . import jax_utils 24 from . import linen /usr/local/lib/python3.9/dist-packages/flax/core/__init__.py in &lt;module&gt; 14 15 from .axes_scan import broadcast as broadcast ---&gt; 16 from .frozen_dict import ( 17 FrozenDict as FrozenDict, 18 freeze as freeze, /usr/local/lib/python3.9/dist-packages/flax/core/frozen_dict.py in &lt;module&gt; 48 49 ---&gt; 50 @jax.tree_util.register_pytree_with_keys_class 51 class FrozenDict(Mapping[K, V]): 52 &quot;&quot;&quot;An immutable variant of the Python dict.&quot;&quot;&quot; AttributeError: module 'jax.tree_util' has no attribute 'register_pytree_with_keys_class' </code></pre> <p>I am really not sure where this comes from, and how I can make this work.</p>
<python><jax>
2023-03-21 11:17:58
1
320
RanWang
75,800,304
3,370,495
Can't open web browser with webbrowser module
<p>I'm trying to open an url using python <code>webbrowser</code> module. When the code below runs nothing happens.</p> <pre><code>import webbrowser webbrowser.open_new('http://www.python.org') </code></pre> <p>But when a <code>sleep</code> time is given, the browser opens and closes after the sleep time is over.</p> <pre><code>import time time.sleep(4) </code></pre> <p>I observed that this happens with Chrome and Firefox. But Edge stays open.</p> <p>Here Why first part of the code didn't open any browser and the second part causes automatic closing of the windows?</p> <p>OS: Windows 10, Python: 3.10.5</p>
<python><url><window><python-webbrowser>
2023-03-21 10:57:24
0
509
Shyam3089
75,800,290
13,180,235
Django admin integer field with '+' '-' on either side to increment/decrement value
<p>Im stuck in a client's requirement. He wants to have a field in django admin panel like the screenshot I have attached <a href="https://i.sstatic.net/kDpRs.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kDpRs.png" alt="screenshot" /></a></p> <p>I have a field in my model landing_page_btn_text_size = models.CharField(verbose_name=_(&quot;Button Text Size&quot;), max_length=255, default=&quot;20px&quot;)</p> <p>Now he want if i click '-' it subtracts 1 from the value and if '+' it adds 1 to the value.</p> <p>Any help would be appreciated, thanks.</p>
<python><django><django-models><django-admin>
2023-03-21 10:55:59
1
335
Fahad Hussain
75,800,252
10,687,907
Get next row after groupby
<p>My question is similar to this one : <a href="https://stackoverflow.com/questions/68479601/get-next-row-besides-the-previous-row-after-groupby">Get next row besides the previous row after groupby</a> but not quite the same. I'd like to get the first row appearing after a group concatenated to each row of the group.</p> <p>So if I have:</p> <pre><code>ID value counts date 1 1 3 1/2/2020 1 2 10 10/2/2020 1 3 5 15/2/2020 2 1 6 3/4/2020 2 2 2 10/4/2020 </code></pre> <p>I'd like to have:</p> <pre><code>ID value counts date NextID NextValue NextCounts NextDate 1 1 3 1/2/2020 2 1 6 3/4/2020 1 2 10 10/2/2020 2 1 6 3/4/2020 1 3 5 15/2/2020 2 1 6 3/4/2020 2 1 6 3/4/2020 3 4 1 11/12/2020 2 2 2 10/4/2020 3 4 1 11/12/2020 3 4 1 11/12/2020 nan nan nan nan </code></pre>
<python><pandas>
2023-03-21 10:51:54
1
807
Achille G
75,800,240
9,021,547
How to add intervals to a date in numpy
<p>I need to subtract x months from a specific date in python and tried several ways, but get the following errors:</p> <pre><code> dates = np.array(['2023-02-28T00:00:00.000000000','2022-12-31T00:00:00.000000000','2019-01-01T00:00:00.000000000'], dtype=np.datetime64) dates + np.timedelta64(-5,'M') numpy.core._exceptions._UFuncInputCastingError: Cannot cast ufunc 'add' input 1 from dtype('&lt;m8[M]') to dtype('&lt;m8[ns]') with casting rule 'same_kind' dates + relativedelta(months=-5) numpy.core._exceptions._UFuncBinaryResolutionError: ufunc 'add' cannot use operands with types dtype('&lt;M8[ns]') and dtype('O') datetime.fromtimestamp(dates.astype(datetime) / 1e9) + relativedelta(months=-5) TypeError: only integer scalar arrays can be converted to a scalar index </code></pre> <p>What is the problem here?</p>
<python><numpy><datetime>
2023-03-21 10:50:48
1
421
Serge Kashlik
75,799,998
10,391,157
App doesn't comply with Google OAuth policy
<p>I want basic user authentication using Google OAuth2 sign in. I open a browser in my app to <code>https://accounts.google.com/o/oauth2/v2/auth</code>, and receive the authentication token at my python server. But if I try to exchange this with an access token, google complains about not complying with the policy, without going into more detail.</p> <blockquote> <p>You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure.</p> <p>You can let the app developer know that this app doesn't comply with one or more Google validation rules.</p> </blockquote> <p>I tried it using a simple http request, as well as using their python module with the same result. The later would complain if https is not available.</p> <p>This issue sounds related, but the OP had success once while I constantly failed so far. The answers do not help in my case: <a href="https://stackoverflow.com/questions/70638732/error-message-you-cant-sign-in-to-this-app-because-it-doesnt-comply-with-goog">Error message &quot;You can&#39;t sign in to this app because it doesn&#39;t comply with Google&#39;s OAuth 2.0 policy for keeping apps secure&quot;</a></p> <p>My guess is the redirect URI is incorrect, because not escaping it (using colons) result in an uri_mismatch, while sending an escaped, but invalid URI results in the generic error from above.</p> <p><a href="https://stackoverflow.com/questions/74111525/get-refresh-token-request-throws-app-doesnt-comply-with-googles-oauth-2-0-pol">There might also be an issue with using this subdomain</a> (provided by my vps), but then I do not understand why I received the authentication token just fine, or how I can properly verify that domain. The app is still in testing and therefore not authorized.</p> <p>I added all redirects in the authorized redirects list.</p> <p>I'm following this page: <a href="https://developers.google.com/identity/protocols/oauth2/web-server" rel="nofollow noreferrer">https://developers.google.com/identity/protocols/oauth2/web-server</a></p> <pre><code>https%3A//my-subdomain.zap-srv.com%3A8000/login </code></pre> <p>Java client to open the browser:</p> <pre class="lang-java prettyprint-override"><code> // Construct the authorization URL String authUrl = &quot;https://accounts.google.com/o/oauth2/v2/auth?&quot; + &quot;client_id=&quot; + clientId + &quot;&amp;redirect_uri=&quot; + redirectUri + &quot;&amp;state=&quot; + &quot;125&quot; + &quot;&amp;response_type=code&quot; + &quot;&amp;nonce=&quot; + nonce + &quot;&amp;scope=openid&quot;; // Open the authorization URL in the user's default web browser Desktop.getDesktop().browse(new URI(authUrl)); </code></pre> <p>Python using their module:</p> <pre class="lang-py prettyprint-override"><code> redirect_uri = &quot;https%3A//my-subdomain.zap-srv.com%3A8000/login&quot; flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( &quot;client_secret.json&quot;, scopes=[&quot;openid&quot;], state=state ) flow.redirect_uri = redirect_uri flow.fetch_token(code=code, include_client_id=True) </code></pre> <p>Alternative Python using http request with the same result:</p> <pre class="lang-py prettyprint-override"><code> redirect_uri = &quot;https%3A//my-subdomain.zap-srv.com%3A8000/login&quot; # Set up the request parameters url = &quot;https://oauth2.googleapis.com/token&quot; data = { &quot;code&quot;: code, &quot;client_id&quot;: client_id, &quot;client_secret&quot;: client_secret, &quot;redirect_uri&quot;: redirect_uri, &quot;grant_type&quot;: &quot;authorization_code&quot;, } # Send the request and retrieve the access token response = requests.post(url, data=data) </code></pre>
<python><google-oauth>
2023-03-21 10:28:42
0
1,538
Luke100000
75,799,966
12,967,353
Using default tool values for reusable noxfile
<p>I am implementing a reusable noxfile, my goal is that the different Python components of my project can have the same workflow for testing, linting, etc.</p> <p>To do this, I created a <code>nox_plugin</code> module containing this generic <code>noxfile.py</code> (this is a sample):</p> <pre><code>import nox @nox.session(reuse_venv=True) def tests(session: nox.Session) -&gt; None: &quot;&quot;&quot; Run unit tests with required coverage. &quot;&quot;&quot; session.install(&quot;-r&quot;, &quot;dev-requirements.txt&quot;) session.run(&quot;coverage&quot;, &quot;run&quot;, &quot;-m&quot;, &quot;pytest&quot;, &quot;src&quot;) session.run(&quot;coverage&quot;, &quot;json&quot;) session.run(&quot;coverage&quot;, &quot;report&quot;) session.run(&quot;coverage-threshold&quot;) </code></pre> <p>I can package this module into a wheel that I can reuse by simply using the following <code>noxfile.py</code> in other projects:</p> <pre><code>from nox_plugin import tests </code></pre> <p>and executing the <code>nox</code> command.</p> <p>However, I have to redefine the <code>pyproject.toml</code> sections for the coverage and coverage-threshold tools in all the modules using the nox_plugin package:</p> <pre><code># Coverage configuration [tool.coverage.run] branch = true omit = [&quot;*__init__.py&quot;] include = [&quot;src/main/*&quot;] [tool.coverage.report] precision = 2 # Coverage-threshold configuration [tool.coverage-threshold] line_coverage_min = 90 file_line_coverage_min = 90 branch_coverage_min = 80 file_branch_coverage_min = 80 </code></pre> <p>I would like to define default values for those sections in my nox_plugin module. This way, I can have a default configuration followed by all repos (for example, the same linting threshold for all code, or the same coverage thresholds).</p>
<python><continuous-integration><coverage.py><pyproject.toml><nox>
2023-03-21 10:25:26
0
809
Kins
75,799,955
13,123,667
How to do inference with YOLOv5 and ONNX
<p>I've trained a YOLOv5 model and it works well on new images with yolo detect.py</p> <p>I've exported the model to ONNX and now <strong>i'm trying to load the ONNX model and do inference</strong> on a new image. My code works but I don't get the correct bounding boxes.</p> <p>I need to get the area of the bounding boxes etc. so <strong>I can't just use detect.py</strong></p> <p>Also I used Yolo's non_max_suppression to prune the list of bbox but I don't if it's a good solution.</p> <p>What I did yet:</p> <p><strong># Load image and preprocessing</strong></p> <pre><code>import cv2 import numpy as np img = cv2.imread(&quot;image.jpg&quot;, cv2.IMREAD_UNCHANGED) resized = cv2.resize(img, (640,640), interpolation = cv2.INTER_AREA).astype(np.float32) resized = resized.transpose((2, 0, 1)) resized = np.expand_dims(resized, axis=0) # Add batch dimension </code></pre> <p><strong># run session on ONNX</strong></p> <pre><code>import onnxruntime as ort ort_session = ort.InferenceSession(&quot;yolov5.onnx&quot;, providers=[&quot;CUDAExecutionProvider&quot;]) # compute ONNX Runtime output prediction ort_inputs = {ort_session.get_inputs()[0].name: resized} ort_outs = ort_session.run(None, ort_inputs) </code></pre> <h3>HERE I HAVE TENSOR WITH ALL THE BOUNDING BOXES</h3> <p><strong># Keep only interesting bounding boxes</strong></p> <pre><code>import torch from yolov5.utils.general import non_max_suppression, xyxy2xywh output= torch.from_numpy(np.asarray(ort_outs)) out = non_max_suppression(output, conf_thres=0.2, iou_thres=0.5)[0] # convert xyxy to xywh xyxy = out[:,:4] xywh = xyxy2xywh(xyxy) out[:, :4] = xywh </code></pre> <p><strong># Show bbox</strong></p> <pre><code>from PIL import Image, ImageDraw, ImageFont tmp_image = Image.fromarray(img) draw = ImageDraw.Draw(tmp_image) for i,(x,y,w,h,score,class_id) in enumerate(out): real_x = x * w_ratio # resize from model size to image size real_y = y * h_ratio shape = (real_x, real_y, (x + w) * w_ratio, (y + h) * h_ratio) # shape of the bounding box to draw class_id = round(float(class_id)) class_string = list(class_list.keys())[list(class_list.values()).index(class_id)] color = CLASS_RECTANGLE_COLORS[class_string] draw.rectangle(shape, outline=color, width=4) fnt = ImageFont.load_default() draw.multiline_text((real_x + 8, real_y + 8), f&quot;{class_string} {score*100:.2f}%&quot;, font=fnt, fill=color) tmp_image.show() </code></pre> <p>Image with my algorithm vs detect.py : <a href="https://i.sstatic.net/ZxNLJ.jpg" rel="nofollow noreferrer">https://i.sstatic.net/ZxNLJ.jpg</a></p> <p>Can anyone help ?</p>
<python><yolo><onnx><yolov5><onnxruntime>
2023-03-21 10:24:21
3
896
Timothee W
75,799,800
6,621,137
How to implement same customized log through differents files via logging module
<p>I believe from other questions I have read that logging has a singleton pattern but I did not succeed to implement it right.</p> <p>I have a <code>logger.py</code> file like this :</p> <pre><code>import logging import os from concurrent_log_handler import ConcurrentRotatingFileHandler def create_file_handler(path, filename=None): if filename is None: filename = f&quot;app_{os.getlogin()}&quot; formatter = logging.Formatter('%(asctime)s | %(name)s | %(funcName)s | %(levelname)s | %(message)s') file_handler = ConcurrentRotatingFileHandler(fr'{path}\{filename}.log', mode='a', maxBytes=1024*1024*10, # 10 Mo per file backupCount=10) file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) return file_handler </code></pre> <p>Let's say to simplify that I have two other files, <code>file_one.py</code> (the file I will call first) which uses functions from <code>file_two.py</code>.</p> <p>I would like a custom log file from <code>file_one.py</code>, so I have created log like this in it :</p> <pre><code>import logging from logger import create_file_handler file_handler = create_file_handler(r'C:\custom\path', filename=&quot;custom_filename&quot;) le_log = logging.getLogger(__name__) le_log.setLevel(logging.INFO) le_log.addHandler(file_handler) </code></pre> <p>The problem is that in <code>file_two.py</code> I can't put the custom path neither the custom_file_name in argument of <code>create_file_handler</code> because I don't know in advance which file (there is not only <code>file_one.py</code>) will call the functions in <code>file_two.py</code>. So how do I use the customized <code>le_log</code> from <code>file_one.py</code> when using functions from <code>file_two.py</code> ?</p> <p>Currently I do a default logger creation in <code>file_two.py</code> because I need a <code>le_log</code> variable in the file.</p>
<python><python-3.x><logging><singleton><python-logging>
2023-03-21 10:09:27
1
452
TmSmth
75,799,722
10,003,538
How to deal with stack expects each tensor to be equal size eror while fine tuning GPT-2 model?
<p>I tried to fine tune a model with my personal information. So I can create a chat box where people can learn about me via chat gpt.</p> <p>However, I got the error of</p> <blockquote> <p>RuntimeError: stack expects each tensor to be equal size, but got [47] at entry 0 and [36] at entry 1</p> </blockquote> <p>Because I have different length of input</p> <p>Here are 2 of my sample input</p> <blockquote> <p>What is the webisite of ABC company ? -&gt; <a href="https://abcdef.org/" rel="nofollow noreferrer">https://abcdef.org/</a></p> </blockquote> <blockquote> <p>Do you know the website of ABC company ? -&gt; It is <a href="https://abcdef.org/" rel="nofollow noreferrer">https://abcdef.org/</a></p> </blockquote> <p>Here is what I have tried so far</p> <pre><code>import torch from transformers import GPT2Tokenizer, GPT2LMHeadModel from torch.utils.data import Dataset, DataLoader class QADataset(Dataset): def __init__(self, questions, answers, tokenizer, max_length): self.questions = questions self.answers = answers self.tokenizer = tokenizer self.max_length = max_length # Add a padding token to the tokenizer self.tokenizer.add_special_tokens({'pad_token': '[PAD]'}) def __len__(self): return len(self.questions) def __getitem__(self, index): question = self.questions[index] answer = self.answers[index] input_text = f&quot;Q: {question} A: {answer}&quot; input_ids = self.tokenizer.encode(input_text, add_special_tokens=True, max_length=self.max_length, padding=True, truncation=True) if input_ids is None: return None input_ids = torch.tensor(input_ids, dtype=torch.long) print(f&quot;Input ids size: {input_ids.size()}&quot;) return input_ids # Set up the tokenizer and model tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model = GPT2LMHeadModel.from_pretrained('gpt2') # Load the question and answer data questions = [&quot;What is the webisite of ABC company ?&quot;, &quot;Do you know the website of ABC company ?&quot;] answers = [&quot;https://abcdef.org/&quot;, &quot;It is https://abcdef.org/&quot;] # Create the dataset and data loader max_length = 64 dataset = QADataset(questions, answers, tokenizer, max_length=max_length) data_loader = DataLoader(dataset, batch_size=8, shuffle=True) # Fine-tune the model on the QA dataset device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) optimizer = torch.optim.Adam(model.parameters(), lr=1e-5) criterion = torch.nn.CrossEntropyLoss() for epoch in range(3): running_loss = 0.0 for batch in data_loader: batch = batch.to(device) outputs = model(batch, labels=batch) loss, _ = outputs[:2] optimizer.zero_grad() loss.backward() optimizer.step() running_loss += loss.item() print(f&quot;Epoch {epoch + 1} loss: {running_loss / len(data_loader)}&quot;) # Save the fine-tuned model model.save_pretrained(&quot;qa_finetuned_gpt2&quot;) </code></pre> <p>I dont have a solid background of AI, it is more like reading references and try to implement it.</p>
<python><tensorflow><artificial-intelligence><huggingface-transformers><gpt-2>
2023-03-21 10:01:28
2
1,225
Chau Loi
75,799,294
16,971,617
Generate random 2D polygons
<p>I would like to generate some random shapes that are regular polygons with right angled (Like a floor plan) only.</p> <p>I'm not sure how to approach this problem. One approach is to train a GAN model to do it but is there a algorithm to do that? I was thinking to generate as follows</p> <p><a href="https://i.sstatic.net/vFl0A.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vFl0A.png" alt="enter image description here" /></a></p> <p>Any help is appreciated.</p>
<python><random><computer-vision><computational-geometry>
2023-03-21 09:20:48
2
539
user16971617
75,799,074
13,158,157
pyspark export parquet not in snappy compression
<p>Reading documentation for <a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrameWriter.parquet.html" rel="nofollow noreferrer">spark.write.parquet</a> does not show me options to change compression for the exported parquet. To go around the default exported parquet format I am able to convert pyspark dataframe into a pandas dataframe and export to parquet from that.</p> <p>This work but is highly inefficient are there option to change exported parquet compression (default is snappy) without having to convert dataframe to pandas ?</p>
<python><pandas><apache-spark><pyspark><databricks>
2023-03-21 08:58:13
1
525
euh
75,798,705
14,912,118
Getting Data must be padded to 16 byte boundary in CBC mode when decrypting the file
<p>I am trying to decrypt the file which I have encrypted using following link(python encryption code) <a href="https://stackoverflow.com/questions/75665392/getting-bad-magic-number-while-decrypting-the-file/">Getting Bad Magic Number while Decrypting the file</a></p> <p>But when i am trying to decrypt the code getting following error: <code>ValueError: Data must be padded to 16 byte boundary in CBC mode</code> Decryption Code:</p> <pre><code>def decrypt_file(input_file_path, output_file_path, key): &quot;&quot;&quot; Decrypt the given input file with the given key using AES and save the result to the given output file. &quot;&quot;&quot; with open(input_file_path, &quot;rb&quot;) as input_file: with open(output_file_path, &quot;wb&quot;) as output_file: iv = input_file.read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) while True: chunk = input_file.read(1024 * AES.block_size) if len(chunk) == 0: break output_file.write(cipher.decrypt(chunk)) </code></pre> <p>Note: Decryption using open ssl is working fine using following command <code>openssl aes-256-cbc -d -in sample.csv -out output_test.csv -K 30313233343536373839616263646566303132333435363453839616263646566 -iv 310401d79e639349639088859d7f433</code></p> <p>Now i want to decrypt using python before decryption we are splitting the encrypted file into 4 chunk and trying to decrypt the each chunk separately using above code, but i am getting above error, please help me to solve this issue.</p>
<python><encryption><openssl><aes>
2023-03-21 08:15:04
1
427
Sharma
75,798,605
6,761,328
Show non-numerical variables / columns in hover text
<p>I have this code to create a plot and this dataframe</p> <pre><code>df2.dtypes Out[464]: Device category time datetime64[ns] Path category variable object value float64 path category dtype: object df3 = df2.query('variable==@signals').groupby('path').first() fig_general = px.scatter(df3 , x = &quot;time&quot; , y = 'value' , custom_data = ['Path'] , color = 'Device' , symbol = 'variable' , hover_name = &quot;Path&quot; , opacity = 0.6 , template = 'plotly_dark' , marginal_y = &quot;rug&quot; ) fig_general.update_layout( transition_duration = 500 , autosize = True , height = 700 , hovermode = 'closest' ) fig_general.update_traces(marker = dict( size = 14 ) , hovertemplate=&quot;&lt;br&gt;&quot;.join([ &quot;Device: %{Device}&quot; , &quot;variable': {symbol}&quot; , &quot;time: %{x}&quot; , &quot;value': %{y}&quot; ]) ) </code></pre> <p>And I would like to show <code>variable</code> and <code>Device</code> in the hover text but it is only shown as text itself. <code>time</code> and <code>value</code> is working properly. How do I do that?</p>
<python><plotly><plotly-dash>
2023-03-21 08:03:48
1
1,562
Ben
75,798,212
4,792,660
Get vertex list and face list in maya
<p>I am new to maya scripting. I have a .fbx being loaded and for each shape node I need to convert such shape into a .obj file.</p> <p>Now I've found a way to exctract the vertex coordinates by doing something like</p> <pre><code>node_name = &quot;testnodeshape&quot; vtxIndexList = cmds.getAttr(node_name +&quot;.vrts&quot;, multiIndices=True) vtxWorldPosition = [] for i in vtxIndexList: curPointPosition = cmds.xform( node_name +&quot;.pnts[&quot;+str(i)+&quot;]&quot;, query=True, translation=True, worldSpace=True) vtxWorldPosition.append( curPointPosition ) for entry in vtxWorldPosition: print('v ' + (' '.join([str(x) for x in entry]))) </code></pre> <p>However I cannot find a way to extract the face list. I've tried to print all the attribute of a shape node to find such a list, there's something called 'edge' and 'face' but when I print it I only see consecutive numbers.</p> <p>I am also not an expert in navigating the maya documentation and it doesn't seem to help. There's also OpenMaya but I struggle a bit to understand how to use it.</p> <p>Can you suggest what to do (I need to extract the triplets of vertex index per face).</p> <p>If there's a quicker way also to do this conversion that's also fine.</p> <p><strong>Update</strong>: I've also found this link <a href="https://forums.cgsociety.org/t/how-maya-vertex-indexes-indcies-work/1519043/6" rel="nofollow noreferrer">https://forums.cgsociety.org/t/how-maya-vertex-indexes-indcies-work/1519043/6</a></p> <p>But it doesn't cover how to get the triangles. From maya the documentation there's a <code>getTriangles()</code> method but it doesn't seem leading me to get an equivalent of an obj yet.</p> <p>Along this line is what I've:</p> <pre><code>import maya.OpenMaya as om import maya.cmds as c meshIt = om.MItDag ( om.MItDag.kBreadthFirst , om.MFn.kMesh) while not meshIt.isDone (): obj = meshIt.currentItem() mesh = om.MFnMesh(obj) floatArray = om.MFloatPointArray() intArrayVc = om.MIntArray() intArrayVl = om.MIntArray() mesh.getVertices(intArrayVc,intArrayVl) mesh.getPoints(floatArray) for vl in intArrayVl: print &quot;v {} {} {}&quot;.format(floatArray[vl].x,floatArray[vl].y,floatArray[vl].z) intArrayFc = om.MIntArray( ) intArrayFl = om.MIntArray( ) mesh.getTriangles (intArrayFc, intArrayFl) numberOfIndices = len(intArrayFl) for fl in range(0,numberOfIndices,3): print &quot;f {} {} {}&quot;.format(intArrayFl[fl],intArrayFl[fl+1],intArrayFl[fl+2]) break meshIt.next() </code></pre> <p><strong>Update 2</strong> I've found the following lines of script that given a selected shape node can do the export to .obj</p> <pre><code>import maya.cmds as cmds cmds.file(&quot;D:/TestMesh/tmp/something.obj&quot;,pr=1,typ=&quot;OBJexport&quot;,es=1, op=&quot;groups=0; ptgroups=0; materials=0; smoothing=0; normals=0&quot;) </code></pre> <p>However what this doesn't do is to convert quads to triangles... Is there a way to do that?</p>
<python><maya><wavefront>
2023-03-21 07:11:04
0
2,948
user8469759
75,798,012
6,760,948
Modify flag status if a condition is met
<p>Below is a JSON output from an API microservice.</p> <pre><code>{ &quot;case&quot;: &quot;2nmi&quot;, &quot;id&quot;: &quot;6.00c&quot;, &quot;key&quot;: &quot;subN&quot;, &quot;Brand&quot;:[ { &quot;state&quot;: &quot;Active&quot;, &quot;name&quot;: &quot;Apple&quot;, &quot;date&quot;: &quot;2021-01-20T08:35:33.382532&quot;, &quot;Loc&quot;: &quot;GA&quot;, }, { &quot;state&quot;: &quot;Disabled&quot;, &quot;name&quot;: &quot;HP&quot;, &quot;date&quot;: &quot;2018-01-09T08:25:90.382&quot;, &quot;Loc&quot;: &quot;TX&quot;, }, { &quot;state&quot;: &quot;Active&quot;, &quot;name&quot;: &quot;Acer&quot;, &quot;date&quot;: &quot;2022-01-2T8:35:03.5432&quot;, &quot;Loc&quot;: &quot;IO&quot; }, { &quot;state&quot;: &quot;Booted&quot;, &quot;name&quot;: &quot;Toshiba&quot;, &quot;date&quot;: &quot;2023-09-29T9:5:03.3298&quot;, &quot;Loc&quot;: &quot;TX&quot; } ], &quot;DHL_ID&quot;:&quot;a3288ec45c82&quot; } </code></pre> <p>#List holding the Laptop Brands</p> <pre><code>my_list = [&quot;apple&quot;, &quot;hp&quot;] </code></pre> <p>I'm trying to come up with a script, to check, if items in the <code>my_list</code> list, is/are available as part of an API microservice's streaming output(JSON), if so, validate whether, those item(<code>apple</code>/<code>hp</code>) is/are in <code>Active</code> state within a timeout of 10 minutes. If a single item (either <code>apple</code> or <code>hp</code>) is not of <code>Active</code> state within 10 minutes, fail the script.</p> <p>The state (<code>Sales['state']</code>) can vary like Active, Booted, Disabled and Purged and also, <code>my_list</code> can have any number of entries.</p> <p>Unsure of logic, whether I should use multiple flags to check status of individual item in the list or manipulate the single flag accordingly.</p> <pre><code>def validate_status(): all_brand_status = False # flag to check if all the Brand's state are Active. Sales = func_streaming_logs_json(args) # JSON output is captured from the microservice using this function. for sale in Sales['Brand']: if sale['name'].lower() in my_list and sale['state'] == &quot;Active&quot;: all_brand_status = True else: print(f&quot;{sale['name']} status: {sale['state']}&quot;) return all_brand_status # Timeout Function def timeOut(T): start_time = datetime.now() stop_time = start_time + timedelta(minutes=T) while True: success = validate_status() if success: print(&quot;say script is successful blah blah&quot;) break start_time = datetime.now() if start_time &gt; stop_time: print(&quot;Timeout&quot;) sys.exit(1) if __name__ == '__main__': timeOut(10) </code></pre>
<python><python-3.x>
2023-03-21 06:42:52
2
563
voltas
75,797,700
6,505,146
How to make kdeplot robust to negative/zero values
<p>I have two real/float variables stored in native python lists:</p> <pre><code>x = [2.232, 2.331, 2.112...] y = [-3.431, 2.213, -1.232...] </code></pre> <p>Notice that there are negative values. This seems to be giving the <code>kde</code> call some problems. I have gotten this error:</p> <blockquote> <p>ZeroDivisionError: 0.0 cannot be raised to a negative power.</p> </blockquote> <p>For my purposes, the plot doesn't need to be insanely accurate, so I attempted to add in a small amount ad hoc to both <code>x</code> and <code>y</code>:</p> <pre><code>x = [] for i in range(len(raw_data)): x.append(float(raw_data[i][1])+.000000001) </code></pre> <p>To my surprise, the error persisted. I even added a much larger amount (.1) but no progress was made with that either.</p> <h2>Question</h2> <p>Is there a more fool-proof way to ensure the <code>kde</code> call is implemented robust to non-zero entries? The fact that altering my data ad hoc didn't work suggests that something else may be wrong here.</p> <p><strong>Call</strong></p> <pre><code>seaborn.kdeplot(x,y) </code></pre> <p><strong>Error text</strong></p> <pre><code>~\Anaconda3\lib\site-packages\statsmodels\nonparametric\bandwidths.py in bw_scott(x, kernel) 53 A = _select_sigma(x) 54 n = len(x) ---&gt; 55 return 1.059 * A * n ** (-0.2) 56 57 def bw_silverman(x, kernel=None): </code></pre>
<python><seaborn><kdeplot>
2023-03-21 05:51:42
0
2,627
Arash Howaida
75,797,640
1,645,131
How to specify column types with Polars read_csv
<p>While reading a csv file in pandas, we have option of dtype in read_csv(). Do we have similar option in polars?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import polars as pl data_pd = pd.read_csv('file.csv',dtype={'col1':str, 'col2':str}) data_pl = pl.read_csv('file.csv',dtype={'col1':str, 'col2':str}) </code></pre> <p>I get the following Polars error:</p> <pre><code>TypeError: read_csv() got an unexpected keyword argument 'dtype' </code></pre>
<python><dataframe><csv><python-polars>
2023-03-21 05:38:07
1
1,032
Kuber
75,797,591
4,107,349
Adding column to a Pandas df checking whether date range ever falls on a given month in any year
<p>We have a dataframe of entries where we want to know which entries have ever existed within a given month of any year. Simplified eg:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import datetime as dt df = pd.DataFrame( { &quot;start&quot;: [dt.datetime(2020,1,1), dt.datetime(2020,8,1), dt.datetime(2020,8,1)], &quot;finish&quot;: [dt.datetime(2021,12,1), dt.datetime(2021,6,1), dt.datetime(2022,6,1)], }) </code></pre> <p>How can we add a column determining which entries ever existed on any July of any year? We can add this if we're only concerned for July 2020: <code>df['existed_in_july_2020'] = (df['start'] &lt; dt.datetime(2020,7,1)) &amp; (df['finish'] &gt;= dt.datetime(2020,8,1))</code>, but this doesn't have other years, and the third entry existed in July 2021.</p> <p>In this eg df that column <code>existed_in_july</code> would be:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( { &quot;start&quot;: [dt.datetime(2020,1,1), dt.datetime(2020,8,1), dt.datetime(2020,8,1)], &quot;finish&quot;: [dt.datetime(2021,12,1), dt.datetime(2021,6,1), dt.datetime(2022,6,1)], &quot;existed_in_july&quot;: [True, False, True] }) </code></pre> <p>How can we create this column?</p>
<python><pandas><dataframe>
2023-03-21 05:27:31
2
1,148
Chris Dixon
75,797,278
610,569
Playing a video with captions in Jupyter notebook
<h1>How to play a video with captions in Jupyter notebook?</h1> <p>With code snippets from these post, I've tried to play a video inside jupyter notebook:</p> <ul> <li><a href="https://stackoverflow.com/questions/18019477/how-can-i-play-a-local-video-in-my-ipython-notebook">How can I play a local video in my IPython notebook?</a></li> <li><a href="https://stackoverflow.com/questions/57377185/how-play-mp4-video-in-google-colab">how play mp4 video in google colab</a></li> </ul> <pre><code>from IPython.display import HTML # Show video compressed_path = 'team-rocket.video-compressed.mp4' mp4 = open(compressed_path,'rb').read() data_url = &quot;data:video/mp4;base64,&quot; + b64encode(mp4).decode() HTML(&quot;&quot;&quot; &lt;video width=400 controls&gt; &lt;source src=&quot;%s&quot; type=&quot;video/mp4&quot;&gt; &lt;/video&gt; &quot;&quot;&quot; % data_url) </code></pre> <p>[out]:</p> <p><a href="https://i.sstatic.net/c4nCBl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c4nCBl.png" alt="enter image description here" /></a></p> <h3>When I tried to add a <code>.vtt</code> file as caption, the option appears</h3> <pre><code>from IPython.display import HTML # Show video compressed_path = 'team-rocket.video-compressed.mp4' mp4 = open(compressed_path,'rb').read() data_url = &quot;data:video/mp4;base64,&quot; + b64encode(mp4).decode() HTML(&quot;&quot;&quot; &lt;video width=400 controls&gt; &lt;source src=&quot;%s&quot; type=&quot;video/mp4&quot;&gt; &lt;track src=&quot;team-rocket.vtt&quot; label=&quot;English&quot; kind=&quot;captions&quot; srclang=&quot;en&quot; default &gt; &lt;/video&gt; &quot;&quot;&quot; % data_url) </code></pre> <p>[out]:</p> <p><a href="https://i.sstatic.net/sUTmRm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sUTmRm.png" alt="enter image description here" /></a></p> <h3>But the subtitles/captions are not present when playing the video. How to play a video with captions in Jupyter notebook?</h3> <p>The files used in the examples above are on:</p> <ul> <li><a href="https://pastebin.com/raw/Fam4a0Ec" rel="nofollow noreferrer"><code>team-rocket.vtt</code></a></li> <li><code>team-rocket.video-compressed.mp4</code> file can be found on <a href="https://colab.research.google.com/drive/1IHgo9HWRc8tGqjmwWGunzxXDVhPaGay_?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1IHgo9HWRc8tGqjmwWGunzxXDVhPaGay_?usp=sharing</a></li> </ul>
<python><video><jupyter-notebook><html5-video><webvtt>
2023-03-21 04:15:50
2
123,325
alvas
75,797,194
5,029,589
Combine two rows in data frame in python
<p>I have a data frame which has two columns and one column has a duplicate values .I want to combine the rows into one . But I dont want to run any aggregation function . My data frame is</p> <p>My data frame df</p> <pre><code> CP CL 0 45538 [757, 1] 1 5548 [712515, 1] 2 7908 [251, 3] 3 7908 [7885, 1] </code></pre> <p>The result I want is as below</p> <pre><code> CP CL 0 45538 [757, 1] 1 5548 [712515, 1] 2 7908 [[251, 3],[7885, 1]] </code></pre> <p>I tried with below code but aggregation doesn't work</p> <pre><code>agg_functions = {'CL': 'list'} df_new = df.groupby(df['CP']).aggregate(agg_functions) </code></pre> <p>The above code doesn't work and gives error ,I am not sure how I can combine it using data frame functions.</p>
<python><pandas><dataframe>
2023-03-21 03:57:19
1
2,174
arpit joshi