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
78,276,558
3,246,693
pandas.DataFrame.fillna with booleans?
<p>I have 2 dataframes, one that contains data and one that contains exlusions that need to be merged onto the data and marked as included(True or False). I have been doing this as follows for a couple of years by simply adding a new column to the exclusions data frame and setting everything to True, then merging that...
<python><pandas><dataframe><fillna>
2024-04-04 20:52:46
2
803
user3246693
78,276,476
274,610
How can I use Python to get a stock's Earnings date and time from the TraderWorkstation Api
<p>I’m trying to get Earnings Date/Time info for AAPL using the Trader Workstation Api for Python.</p> <p>I have subscribed to Wall Street Horizon data.</p> <p>Using the following Python script:</p> <pre><code>from ibapi.client import * from ibapi.wrapper import * import os port = 7496 class TestApp(EClient, EWrapper)...
<python><tws>
2024-04-04 20:34:52
1
529
user274610
78,276,391
5,844,134
Attach a debugger to a flask process started by tasks.json in vscode
<p>I have the following tasks.json in my workspace:</p> <pre><code>{ &quot;version&quot;: &quot;2.0.0&quot;, &quot;tasks&quot;: [ { &quot;label&quot;: &quot;Run Locally&quot;, &quot;dependsOn&quot;: [&quot;Run Backend&quot;, &quot;Run Frontend&quot;], &quot;dependsOrd...
<python><visual-studio-code><flask><vscode-debugger><vscode-tasks>
2024-04-04 20:14:15
1
754
Yuri Waki
78,276,306
5,676,198
ModuleNotFoundError: No module named 'psycopg2._psycopg' in AWS GLUE - Python 3.9
<p>I am trying to use the library <code>psycopg2</code> in AWS Glue.</p> <p>I followed <a href="https://stackoverflow.com/a/58305654/5676198">this question</a>:</p> <p>&quot;What I did was install psycopg2-binary into a directory and zip up the contents of that directory:</p> <pre><code>mkdir psycopg2-binary cd psycopg...
<python><amazon-web-services><psycopg2><aws-glue>
2024-04-04 19:55:20
1
1,061
Guilherme Parreira
78,276,261
5,089,311
Python CSV reader: need ignore quoted comma as delimiter
<p>I need parse text file by comma, but not by quoted comma.<br /> It looks like trivial task, but can't make Python do it right. Mainly because of an unquoted string prepending the quoted string, which makes it probably not well-formatted CSV, but I need it exactly this way.</p> <p>Example input:</p> <pre><code>cmd,pr...
<python><csv><regex-lookarounds>
2024-04-04 19:45:17
2
408
Noob
78,276,231
3,795,219
Ensuring Order of Package Installation with Conda to Enable CUDA with PyTorch
<p>I am attempting to streamline the setup of a Python environment that leverages both CUDA and PyTorch through Conda. My goal is to craft a unified environment.yml file that concurrently installs CUDA and a CUDA-capable version of PyTorch. However, I've encountered an issue where the installation order by Conda leads ...
<python><pytorch><anaconda><conda>
2024-04-04 19:36:00
0
8,645
Austin
78,276,161
13,354,617
Auto resize Canvas to fit tkinter window
<p>so I want to make the canvas fit all the window but currently it's like this: <a href="https://i.sstatic.net/SQBaW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SQBaW.png" alt="ss" /></a></p> <p>I want to do it without hard coding the width and height when initiating the canvas.</p> <p>here's the co...
<python><tkinter><tkinter-canvas>
2024-04-04 19:16:15
1
369
Mhmd Admn
78,276,136
9,357,484
PyTorch 1.7.1 unable to detect CUDA version 11.0
<p>PyTorch unable to locate the CUDA version in my GPU enabled machine. However the CUDA 11.0 is installed in my machine. The graphic card is GeForce RTX 2070 SUPER provided by NVIDIA. The GPU and CUDA configuration can be found in the following picture</p> <p><a href="https://i.sstatic.net/Ckjs1.png" rel="nofollow no...
<python><jupyter-notebook><pytorch>
2024-04-04 19:10:24
0
3,446
Encipher
78,275,952
1,445,015
Tkinter scrollbar on treeview table disappears when resized
<p>I wrote a table class using <code>Treeview</code>:</p> <pre><code>class SimpleDataTable(tk.Frame): def __init__(self, parent, colHeadings, colWidths, height): tk.Frame.__init__(self, parent) self.parent = parent self.colHeadings = colHeadings self.colWidths = colWidths sel...
<python><tkinter><treeview><scrollbar>
2024-04-04 18:36:14
1
1,741
Nasif Imtiaz Ohi
78,275,777
11,748,924
Why generator loss using BinaryCrossEntropy with from_logits enabled?
<p>From a simple vanilla GAN code I look from <a href="https://github.com/shinyflight/Simple-GAN-TensorFlow-2.0/blob/master/GAN.py" rel="nofollow noreferrer">GitHub</a></p> <p>I saw this generator model with activation <code>sigmoid</code>:</p> <pre><code># Generator G = tf.keras.models.Sequential([ tf.keras.layers.D...
<python><tensorflow><machine-learning><keras><loss-function>
2024-04-04 18:03:32
2
1,252
Muhammad Ikhwan Perwira
78,275,627
13,354,617
Drawing a rectangle on a tkinter canvas isn't working
<p>I'm trying to draw a simple rectangle on an image placed inside a canvas in tkinter, but it's not drawing. There's no errors.</p> <p>is it because I'm placing the image not with <code>canvas.create_image</code>? because I'm drawing the image inside a frame and I'm placing the frame inside the canvas. It's the only w...
<python><tkinter><python-imaging-library><tkinter-canvas>
2024-04-04 17:32:18
1
369
Mhmd Admn
78,275,550
5,980,655
Setting specific package version in Google Colab
<p>It's a long post but I'll try to make it more clear as possible.</p> <p>For reproducibility reason, I would like to set up conda environment in Google Colab to use a specific version of some packages.</p> <p>Based on many similar questions on this forum I followed the following steps:</p> <p>I install <code>condacol...
<python><conda><google-colaboratory><environment>
2024-04-04 17:21:49
0
1,035
Ale
78,275,401
616,460
Python 3.7 equivalent of `importlib.resources.files`
<p>I have an application that unfortunately does not support Python past 3.7. I have some code I'm trying to port (from Python 3.12) back to Python 3.7 that uses <code>importlib.resources.files</code> to get the path to some non-Python resources that are included in the package:</p> <pre><code>def _get_file (filename: ...
<python><python-3.7><python-importlib>
2024-04-04 16:52:34
1
40,602
Jason C
78,275,320
5,256,563
Use packages which require different python versions
<p>I'm developing a script for a pipeline that uses various packages. Unfortunately, these packages require different versions of Python. Here is a mock example of the situation:</p> <pre><code>Main script runs on Python 3.11, and it needs package 1 &amp; 2 Package 1 runs only on Python 3.8 Package 2 runs only on Pytho...
<python><python-3.x>
2024-04-04 16:36:39
0
5,967
FiReTiTi
78,275,265
10,200,497
Is there a ONE-LINER way to give each row of a dataframe a unique id consisting of an integer and string?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': [4, 3, 2, 2, 6] } ) </code></pre> <p>And this is the expected output: I want to create column <code>id</code>:</p> <pre><code> a id 0 4 x_0 1 3 x_1 2 2 x_2 3 2 x_3 4 6 x_4 </code></pre> <p>I can create <c...
<python><pandas><dataframe>
2024-04-04 16:26:00
2
2,679
AmirX
78,275,253
1,436,222
best way to create serializable data model
<p>somewhat inexperienced in python. I am coming from C# world, and I am trying to figure out what is the best practice to create a data structure in python that:</p> <ol> <li>can have empty fields (None)</li> <li>can have default values assigned to some fields</li> <li>can have aliases assigned to fields that would b...
<python><python-dataclasses><python-datamodel>
2024-04-04 16:23:32
1
459
concentriq
78,275,164
19,299,757
Selenium Pytest ValueError: setup did not yield a value
<p>I have this test suite (using selenium python pytest) named &quot;test_invoice.py&quot; which has several tests inside it. Similarly I have other test suites in other python files named &quot;test_admin.py&quot;, &quot;test_cash.py&quot; etc with same setup. I run all these suites from a docker image like this:</p> ...
<python><selenium-webdriver><pytest>
2024-04-04 16:07:45
1
433
Ram
78,274,979
9,342,193
Put two plots into the same figure as subplots in Python
<p>I am trying to add two plots into the same plot as subplots.</p> <p>So far I tried :</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import seaborn as sns penguins = sns.load_dataset(&quot;penguins&quot;) print(penguins['species']) fig = plt.gcf() gs = fig.add_gridspec(ncols=2, nrows=1, width_ra...
<python><matplotlib><scatter-plot>
2024-04-04 15:40:21
1
597
Grendel
78,274,904
632,813
ML ColumnTransformer OneHotEncoder
<p>When converting categorical data in first column of my dataframe I am getting strange behavior of ColumnTransformer with OneHotEncoder. the behavior occurs when I add one row to my csv file.</p> <p>the initial data is:</p> <pre><code>title,dailygross,theaters,DayInYear ACatinParis,307,5,257 ALettertoMomo,307,5,257 A...
<python><machine-learning><one-hot-encoding>
2024-04-04 15:25:57
1
435
Tech Wizard
78,274,571
14,954,327
Typing a function param to be any JSON serializable object
<p>what would be the best type for this function?<br /> I want basically any input type that <code>json.dumps</code> can process (with or without <code>JSONEncoder</code>)</p> <p>For now i'm using <code>Union[List[Any], Dict[Any, Any]]</code> but it's not exhaustive and mypy complains <code>Explicit &quot;Any&quot; is ...
<python><python-typing>
2024-04-04 14:31:20
1
960
codekoriko
78,274,561
3,785,719
Pandas display() nice table in AWS Glue Jupyter Notebook
<p>In <strong>AWS Glue Jupyter Notebook</strong>, I wanted to <code>display()</code> the dataframe in Pandas nice table (HTML) but it only shows the raw text.</p> <p>Example: In AWS Glue Jupyter Notebook, it only shows the raw text: <a href="https://i.sstatic.net/GsbKZ.png" rel="noreferrer"><img src="https://i.sstatic....
<python><pandas><amazon-web-services><jupyter-notebook><aws-glue>
2024-04-04 14:30:02
0
696
Chong Onn Keat
78,274,136
13,158,157
Convert to float, pandas string column with mixed thousand and decimal separators
<p>I have a pandas DataFrame with a column containing strings representing numbers. These strings have mixed formats. Some times numbers use comma as a decimal separator and sometimes a dot. When a dot is used as a decimal separator, that number can contain comma as a thousand separator.</p> <p>For example:</p> <pre><c...
<python><pandas><dataframe>
2024-04-04 13:18:36
2
525
euh
78,274,117
5,022,847
Pytest mock ring.redis decorator
<p>Below is my class implementation:</p> <pre><code>class Person: def __init__(self, n): self.n = n self.foo = self.fun() @ring.redis(redis.RedisClient, coder=&quot;json&quot;) def fun(self): another_thirparty_class() # somebusiness logic here def bar(self): a = self.foo[&quot;a&qu...
<python><redis><mocking><pytest><ring>
2024-04-04 13:14:37
0
1,430
TechSavy
78,274,097
108,390
Group/Cluster Polars Dataframe by substring in string or string in substring
<p>Given this Polars DataFrame:</p> <pre><code>df = pl.DataFrame( { &quot;id&quot;: [1, 2, 3, 4, 5], &quot;values&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;A--B&quot;, &quot;C--A&quot;, &quot;D&quot;], } ) </code></pre> <p>1, How can I group/cluster it so that 1,2 and 3 ends up in t...
<python><python-polars>
2024-04-04 13:11:00
1
1,393
Fontanka16
78,273,851
547,231
How can I create a new tensor with shape ( k, x.shape), where x is another tensor?
<p>Having tensor <code>x</code>, I want to create a tensor <code>y</code> of the shape <code>(k, x.shape)</code>. However, <code>y = torch.empty((k, x.shape))</code> does not work, since <code>(k, x.shape)</code> is a tuple of type <code>(int, torch.Size)</code>. Is there no possibility of achieving this?</p> <p>Natura...
<python><pytorch>
2024-04-04 12:28:00
1
18,343
0xbadf00d
78,273,782
7,692,855
Python 3: TypeError: Can't instantiate abstract class BaseConnection with abstract method create_connection
<p>I am upgrading some very old Python code from Python 2 to Python 3. There is a simple method to check rabbitmq connection using Pika.</p> <pre><code> from contextlib import closing from pika import URLParameters, BaseConnection def check_rabbitmq(self): conn_params = URLParameters(self.config.rab...
<python><pika>
2024-04-04 12:14:29
2
1,472
user7692855
78,273,399
357,313
Format float in N chars max with best precision
<p>For concise display in chart titles, I would like to format arbitrary floating point values as a fixed size string, in Python. Either decimal (0.0123) or in scientific notation (1.2e-2) but with the highest precision possible (choosing decimal here). The result is allowed to be <em>smaller</em> than the fixed size, ...
<python><floating-point><formatting>
2024-04-04 11:03:43
0
8,135
Michel de Ruiter
78,273,388
11,049,863
How to display the uuid field of my serializer as a string in a get request with django restframework
<p>Here is my serializer</p> <pre><code>class AgenceSerializer(serializers.Serializer): uuid = serializers.UUIDField(format='hex',allow_null=True,required=False) &lt;------- p1 = serializers.CharField(max_length=50,required=True) p2 = serializers.CharField(max_length=50,required=True) </code></pre> <p>views...
<python><django><django-rest-framework>
2024-04-04 11:00:56
2
385
leauradmin
78,273,384
534,238
Type hints and overloading for type parameter
<p>I have a case where, based upon the <code>type</code> provided as a parameter, I want to return a matching type. I am trying to ingest environment variables from outside of the program, which will always be ingested as strings, but which I want to push into whatever type. The function works perfectly fine, but I wan...
<python><python-typing>
2024-04-04 11:00:12
0
3,558
Mike Williamson
78,273,251
688,080
Autoscaling a figure with heatmap + scatter introduces extra padding
<p>The code below</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import plotly.graph_objects as go def make_blob(n: int) -&gt; np.ndarray: xx, yy = np.meshgrid(np.arange(n), np.arange(n)) return np.exp(-((xx - n // 2) ** 2 + (yy - n // 2) ** 2) / (2 * (n // 2) ** 2)) if __name__ == &...
<python><plotly><visualization><toolbar>
2024-04-04 10:37:00
1
4,600
Ziyuan
78,272,872
13,088,678
Optimze API invocations in parallel
<p>We have a below python code. This has 2 APIs</p> <ul> <li>a) to get all customers - get_all_customers ()</li> <li>b) to get specific customer detail - get_specifc_customer_details()</li> </ul> <p>currently (b) get_specifc_customer_details run sequentially. Is there anyway we can use spark parallelism, so that we can...
<python><apache-spark><pyspark>
2024-04-04 09:23:35
3
407
Matthew
78,272,867
726,730
pyqtSignal emit multi type
<p>I have a signal to be: <code>auto_dj_start = pyqtSignal(dict,str,dict,str)</code></p> <p>Sometimes when the player list is empty i want to emit <code>None</code> to all parameters instead of dicts and string.</p> <p>But this error happens:</p> <pre class="lang-py prettyprint-override"><code>Traceback (most recent ca...
<python><pyqt5><qthread>
2024-04-04 09:22:43
1
2,427
Chris P
78,272,860
9,548,319
Alembic - Inverted workflow upgrade/downgrade
<p>I have this issue with Alembic + FastAPI + PostgreSQL</p> <p>SQL Alchemy Alembic generates migrations in reverse, downgrade creates the table and upgrade drops it, while the database is empty.</p> <p>For example:</p> <pre><code>alembic revision --autogenerate -m &quot;Testing 2&quot; INFO [alembic.runtime.migration...
<python><postgresql><fastapi><alembic>
2024-04-04 09:21:10
1
417
sincorchetes
78,272,705
2,329,968
Weird margins when using curvilinear axis
<p>This example comes from Matplotlib's <a href="https://matplotlib.org/stable/gallery/axisartist/demo_curvelinear_grid.html#sphx-glr-gallery-axisartist-demo-curvelinear-grid-py" rel="nofollow noreferrer">documentation</a>. I'm running it inside Jupyter Lab. Here I attach the output figure:</p> <pre class="lang-py pret...
<python><matplotlib><jupyter-notebook><jupyter><axis>
2024-04-04 08:47:20
1
13,725
Davide_sd
78,272,691
5,346,843
3D interpolation in Python revisited
<p>I have a piece-wise linear path in 3D space, comprising an array of (x, y, z) values, and an array of values giving the distance along the path. I want to find the distance along the path of other (x, y, z) points which all lie &quot;on&quot; the path (ie the distance to one of the path segments is less than some t...
<python><scipy>
2024-04-04 08:44:47
1
545
PetGriffin
78,272,653
315,427
How to avoid interpolation in button_press_event of plot?
<p>For horizontal axis of my plot I have <code>int64</code> type numpy array. Then I've linked button press event to the plot:</p> <pre><code>plt.connect(&quot;button_press_event&quot;, on_click) </code></pre> <p>This is the handler</p> <pre><code>def on_click(event): cursor_x = event.xdata ... </code></pre> <p...
<python><numpy><matplotlib>
2024-04-04 08:36:55
1
29,709
Pablo
78,272,633
10,798,503
Nodriver click captcha box
<p>I'm trying to click the Captcha box witihin <a href="https://github.com/ultrafunkamsterdam/nodriver" rel="nofollow noreferrer">nodriver</a> in Python, At the moment nodriver is unable to locate the chekbox anchor element, but is able to locate the iframe, which makes me think, maybe I need to switch window to it?</p...
<python><recaptcha><captcha><undetected-chromedriver>
2024-04-04 08:32:17
0
1,142
yarin Cohen
78,272,574
10,200,497
What is the best way to slice a dataframe up to the first instance of a mask?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70], 'b': [1, 1, 1, -1, -1, -2, -1, 2, 2, -2, -2, 1, -2], } ) </code></pre> <p>The mask is:</p> <pre><code>mask = ( (df.b == -2) &amp; (df.b.shift(1) &gt...
<python><pandas><dataframe>
2024-04-04 08:20:48
1
2,679
AmirX
78,272,521
6,221,742
Hugging Face Prompt Injection Identifier
<p>packages versions</p> <ul> <li>langchain==0.1.14</li> <li>langchain-community==0.0.31</li> <li>langchain-core==0.1.38</li> <li>langchain-experimental==0.0.56</li> <li>pydantic==1.10.14</li> </ul> <p>I am attempting to utilize prompt injection identification following the guidelines outlined in the tutorial linked <a...
<python><prompt><langchain><large-language-model>
2024-04-04 08:08:53
2
339
AndCh
78,272,508
739,809
where to find my Google project's path for Google DLP
<p>probably very stupid question but in the following code I can't find what is my project path in Google DLP. Where can I find this path in Google console (or any other way)?</p> <pre><code>dlp = google.cloud.dlp_v2.DlpServiceClient() parent = dlp.project_path('WHERE CAN I FIND WHAT GOES HERE???') </code></pre>
<python><google-developers-console><google-cloud-dlp>
2024-04-04 08:06:13
1
2,537
dsb
78,272,340
6,013,016
--pyi_out: protoc-gen-pyi: Plugin failed with status code 1
<p>I'm trying to run this command in docker:</p> <pre><code>RUN python -m grpc_tools.protoc -I ./ --python_out=. --pyi_out=. --grpc_python_out=. my.proto </code></pre> <p>and seeing this error:</p> <pre><code>0.423 protoc-gen-pyi: program not found or is not executable 0.423 Please specify a program using absolute path...
<python><docker><grpc><protoc>
2024-04-04 07:23:28
1
5,926
Scott
78,272,294
14,930,256
MacOS: AttributeError: module 'socket' has no attribute 'AF_BLUETOOTH'
<p>I kept getting this error:</p> <pre><code>AttributeError: module 'socket' has no attribute 'AF_BLUETOOTH' </code></pre> <p>I tried to follow solutions from t<a href="https://stackoverflow.com/questions/52811888/attributeerror-module-socket-has-no-attribute-af-inet">his stackoverflow question</a>, however still getti...
<python><bluetooth><pyenv><python-sockets><bluetooth-socket>
2024-04-04 07:13:45
0
480
Ryan Wang
78,272,225
2,875,230
Use f-string instead of format call
<p>The server I'm posting ym data to doesn't seem to support <code>format</code> call so I get the folowing error.</p> <p>Use f-string instead of 'format' call for the functions below.</p> <pre><code>def write_xlsx_response(self, queryset): response = HttpResponse( content_type=&quot;application/vnd...
<python><f-string>
2024-04-04 07:00:06
1
337
user2875230
78,271,970
5,707,137
Polars read_database does not respect iter_batches = True when using sqlalchemy/oracledb
<p>This query using polars and sqlalchemy does not fetch chunked.</p> <pre><code>d = pl.read_database(sql_text(sql), e, iter_batches=True, batch_size=1000000) </code></pre> <p>The connection is a sqlalchemy create_engine(&quot;oracle+oracledb://@xxx&quot;) on top of oracledb.</p> <p>It fetches every 2 billion rows, or ...
<python><python-polars>
2024-04-04 06:03:23
0
458
Niels Jespersen
78,271,655
2,537,486
Line plot of multiple data sets with different x axis coordinates
<p>I have data organized like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl df = pd.DataFrame({(1,'x'):[0,1,2],(1,'y'):[10,11,12], (2,'x'):[1,2,3],(2,'y'):[11.5,11.8,13.2]}) df 1 2 x y x ...
<python><pandas><matplotlib><plot>
2024-04-04 04:20:57
2
1,749
germ
78,271,534
8,860,759
First Migration with alembic not created table in fastApi
<p>When run command for create my first migration with one table, do not create table, the script that created is empty in functions upgrade and downgrade and only create table alembic_version</p> <p>I understand that it should contain something like:</p> <pre><code>op.create_table( 'task', sa.Column('id', sa.Inte...
<python><sqlalchemy><fastapi><alembic>
2024-04-04 03:34:38
0
435
Lana YC.
78,271,379
3,962,849
Series Variable Convert Pinescript to Python Code
<p>I want to transfer my code to Python and use it more effectively. I have succeeded in most parts, but I need to translate the part that starts with the <code>zoneDecider</code> variable into Python. How can I do it?</p> <p>Python Code</p> <pre class="lang-py prettyprint-override"><code>df=data zone_length = 10 ...
<python><pine-script><pine-script-v5>
2024-04-04 02:42:18
1
5,244
abaci
78,271,277
6,546,694
Understanding sorted in the presense of NaN - Python
<p>Can you help me understand the following:</p> <pre><code>import numpy as np sorted([3,2,np.nan, -1]) output: [-1, 2, 3, nan] </code></pre> <pre><code>import numpy as np sorted([1,2,np.nan, -1]) output: [1, 2, nan, -1] </code></pre> <p>It is almost as if I need a sorting triggered pre-NaN otherwise it returns the sam...
<python><numpy><sorting><nan>
2024-04-04 01:57:20
1
5,871
figs_and_nuts
78,271,184
877,314
Python Triple Quoted comments choke on too many backslashes
<p>Python displays <code>SyntaxWarning: invalid escape sequence '\ '</code> when I am drawing a tree structure in a triple quoted comment string:</p> <pre><code> A / \ B C / \ \ D E F </code></pre>
<python>
2024-04-04 01:19:43
2
1,511
Stefan Musarra
78,271,162
21,321,616
Federated Averaging somehow always gives identical accuracy on test set
<p>I am implementing federated averaging on the <a href="https://www.stratosphereips.org/datasets-iot23" rel="nofollow noreferrer">IoT-23 dataset(lighter version)</a></p> <p>Omitting the preprocessing I am saving the data into a test set and 9 train sets as below:</p> <pre><code>X_train, X_test, Y_train, Y_test = train...
<python><tensorflow><machine-learning><keras><federated-learning>
2024-04-04 01:04:42
0
415
AdityaDN
78,271,087
20,386,110
Using get_tree to create a timer but it's not activating
<p>I'm working on creating Pong and I have two <code>RayCast2Ds</code> on the left and right side of the arena. I have it so whenever one of the RayCast gets hit, the ball resets back to the middle of the arena and the opposite player gets a point. I'm trying to make it so after the ball hits the RayCast, it resets bac...
<python><game-development><godot><gdscript>
2024-04-04 00:27:09
1
369
Dagger
78,271,085
449,347
python requirements.txt - requirement specifier for Linux docker on real Apple hardware?
<p>I am trying to create a <code>requirements.txt</code> to behave on</p> <ol> <li>Linux</li> <li>MacOS</li> <li>Linux container running on MacOS (M1 laptop) in Docker. I THINK this needs to behave like in (2)</li> </ol> <p>My scenario is similar to <a href="https://stackoverflow.com/questions/72720235/requirements-txt...
<python><docker><requirements.txt>
2024-04-04 00:26:33
0
5,028
k1eran
78,270,801
14,385,099
Glob pattern to read in a specific string in Python
<p>I have a folder with a list of files I want to read in as a list of full file paths.</p> <p>The files that I want to read in have this structure: <code>[0-9]_beta_[Y].nii.gz</code>, where:</p> <ul> <li>[0-9] is a 3 digit sequence of numbers (e.g. 123)</li> <li>[Y] is a character string of any length (e.g. 'faces', '...
<python><glob>
2024-04-03 22:29:50
1
753
jo_
78,270,745
15,452,168
How to Predict New Data Topics with BERTopic Model Loaded from Hugging Face in Python? (Automated solution)
<p>I've developed a BERTopic model for analyzing mobile app reviews and have successfully pushed it to Hugging Face. I'm able to load the model in my Python script but am facing challenges in predicting topics for new incoming feedback.</p> <p>My goal is to automatically assign a topic to new app feedback using the tra...
<python><nlp><huggingface>
2024-04-03 22:11:01
0
570
sdave
78,270,713
10,985,257
Connect jpype to existing JVM
<p>I try to access an API of an java Application from python. The Application is a simulation tool. It has more sophisticated functions but the simplest functions are <code>start</code>, <code>pause</code> and <code>reset</code> the simulation.</p> <p>I launch the java application like the following:</p> <pre class="la...
<python><java><jpype>
2024-04-03 22:04:23
0
1,066
MaKaNu
78,270,495
1,925,652
Why does breakpoint() not work in jupyter lab?
<p>Title says it all, I'm running jupyterlab with what should be default settings &amp; the python builtin breakpoint() does nothing... It works fine in ipython/python though. Am I missing something?</p>
<python><jupyter><pdb>
2024-04-03 21:02:14
0
521
profPlum
78,270,468
23,260,297
Combine data from different scripts into a dataframe
<p>I have multiple python scripts that read different csv/excel files that are received every day. The scripts export multiple dataframes to the same excel file, but on different sheets. I need to take it a step further and take specific data from each dataframe, combine them into a new, separate dataframe on another s...
<python><pandas><excel>
2024-04-03 20:57:21
1
2,185
iBeMeltin
78,270,182
3,517,025
connecting to postgres database from azure function - fails with local build/GH actions, succeeds from cli remote build
<p>This question is about the right way to set up/build an azure function such that it'll connect to a postgres database leveraging github actions CI/CD.</p> <p><strong>How things work</strong></p> <pre class="lang-py prettyprint-override"><code>import os import azure.functions as func import logging import psycopg2 ...
<python><postgresql><azure><azure-functions><github-actions>
2024-04-03 19:53:16
1
5,409
Joey Baruch
78,270,044
339,144
How to get insight in the relations between tracebacks of exceptions in an exception-chain
<p>This question is best introduced example-first:</p> <p>Consider the following trivial program:</p> <pre><code>class OriginalException(Exception): pass class AnotherException(Exception): pass def raise_another_exception(): raise AnotherException() def show_something(): try: raise Origina...
<python>
2024-04-03 19:24:22
0
2,577
Klaas van Schelven
78,270,032
1,987,319
AttributeError: '_UnixSelectorEventLoop' object has no attribute '_signal_handlers' while running pytest
<p>This is my error:</p> <pre><code>Connected to pydev debugger (build 233.15026.15) Exception ignored in: &lt;function BaseEventLoop.__del__ at 0x12809be50&gt; Traceback (most recent call last): File &quot;/usr/local/Cellar/python@3.9/3.9.19/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events....
<python>
2024-04-03 19:21:44
0
3,947
prabodhprakash
78,269,841
6,141,238
When saving and loading Keras or TensorFlow models: How do I disable/hide the warnings that appear when using the .h5 extension?
<p>I am trying to save and load Keras and/or TensorFlow models, and approaching the problem by following the <a href="https://keras.io/api/models/model_saving_apis/model_saving_and_loading/" rel="nofollow noreferrer">Keras documentation</a> and a <a href="https://www.tensorflow.org/tutorials/keras/save_and_load#hdf5_fo...
<python><tensorflow><keras><deep-learning><save>
2024-04-03 18:42:47
0
427
SapereAude
78,269,721
395,857
How can I automatically cancel slow downloads and automatically rerun them with the Internet Archive Python library?
<p>I use the Python library <a href="https://pypi.org/project/internetarchive/" rel="nofollow noreferrer">internetarchive</a> to download files from archive.org, e.g. to download <a href="https://archive.org/details/meetingbank-alameda" rel="nofollow noreferrer">https://archive.org/details/meetingbank-alameda</a> I run...
<python><download>
2024-04-03 18:16:44
0
84,585
Franck Dernoncourt
78,269,514
6,599,648
Snowflake Pandas Error: AttributeError: 'Engine' object has no attribute 'cursor'
<p>I'm trying to read data from a Snowflake table using Python (pandas). When I execute the following code:</p> <pre class="lang-py prettyprint-override"><code>from snowflake.sqlalchemy import URL from sqlalchemy import create_engine import pandas as pd url = URL( user=&quot;MY_SERVICE_ACCOUNT&quot;, password=&...
<python><pandas><snowflake-cloud-data-platform>
2024-04-03 17:40:06
1
613
Muriel
78,269,422
4,399,016
Python Logical Operations as conditions in Pandas
<p>I have a dataframe with columns:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'A': [False, True, False, False, False, False, True, True, False, True], 'B': [True, False, False, False, True, True, False, False, False, False ] }) df A B 0 False True 1 True Fal...
<python><pandas><logical-operators>
2024-04-03 17:23:18
1
680
prashanth manohar
78,269,415
2,776,012
Jinja not displaying the values in HTML
<p>I am very new to Python and Jinja and facing an issue in accessing the values of the list in HTML. It is showing blank on the page. Given below is the code snippet, any help would be highly appreciated. The <strong>emplList</strong> is retrieving the values in the manner <strong>[0,&quot;John&quot;] [1,&quot;Sunny&q...
<python><html><list><jinja2>
2024-04-03 17:21:09
2
837
Shivayan Mukherjee
78,269,403
10,516,773
How do I access iCloud mail programmatically using Python?
<p>I am working on a Python application where I need to access and retrieve emails from iCloud mail. From some searching there doesn't seem to be any official API provided by iCloud. Is there some other way to do this programmatically?</p> <p>One possible task for the application could be to list all messages in a mail...
<python><email><icloud>
2024-04-03 17:18:48
1
1,120
pl-jay
78,269,252
1,137,483
Concatenating pandas dataframe with multi index in different order
<p>I have two data frames, which should be concatenated. Both are multi index data frames with identical indexes, but in a different order.</p> <p>So, the index of the first data frame (df) looks like:</p> <pre><code>MultiIndex([(11, 1, 1), (11, 1, 2), (11, 1, 3), ... ...
<python><pandas>
2024-04-03 16:51:34
1
1,458
Tobias Lorenz
78,269,202
818,754
matplotlib's pyplot.show works from Python's Docker image but doesn't work with a custom Docker image built from the same Python image
<h3>Context</h3> <p>I'm looking to set up a development environment for a Python project that uses <a href="https://pypi.org/project/matplotlib/" rel="nofollow noreferrer">matplotlib</a>. Things work fine and I am able to see the plot when I run the default Docker image from Dockerhub as:</p> <p><code>docker run -v ./:...
<python><python-3.x><docker><matplotlib>
2024-04-03 16:43:11
0
1,868
rhetonik
78,269,134
16,717,009
Logging with adapter losing __name__ information
<p>When I use logger in the standard way I am able to capture the module name and it appears correctly in my logs. But if I implement an adapter (again, in the standard way) it seems like the module name keeps getting overwritten at initialization and my logs only ever show the same, last module initialized.</p> <p>To ...
<python><python-logging>
2024-04-03 16:30:25
1
343
MikeP
78,269,103
2,883,209
In Pydantic, how do I set env_ignore_empty to True
<p>I'm currently trying to use Pydantic to check if JSON received is in the right format, and it's one of those where we have 30, 40 fields coming in the JSON, and they have decided that if an amount (for example) is empty, they will provide a null string. Of course, when I check for a float, even if it is Optional, th...
<python><pydantic>
2024-04-03 16:24:31
2
1,244
vrghost
78,269,030
12,352,239
Create array of structs pyspark with named fields
<p>I would like to pass a list of strings - which are column names - into a transform function which results in a new column containing an array of structs with two fields - &quot;key&quot; and &quot;value&quot;. Where key is the column name and value is the corresponding column value</p> <pre><code>data = [ Row(na...
<python><pyspark>
2024-04-03 16:12:07
1
480
219CID
78,268,849
447,426
how override FastApi app.dependency_overrides with a function/ fixture that has an argument?
<p>I have setup tests with a fixture for my deb connection (SQLAlchemy based). The main feature here is that it is rolling back transactions (the tests are not changing the db):</p> <pre><code>@pytest.fixture(scope=&quot;session&quot;) def connection(): SQLALCHEMY_DATABASE_URL = &quot;postgresql://{0}:{1}@{2}:{3}/{...
<python><pytest><fastapi>
2024-04-03 15:42:36
1
13,125
dermoritz
78,268,799
1,563,422
How to replace the body contents (but not the body tag) in BeautifulSoup?
<p>If we have the following document:</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; &lt;body class=&quot;some classes here&quot; id=&quot;test&quot;&gt; &lt;div id=&quot;something&quot;&gt;This text and the div it is inside are the content&lt;/div&gt; &lt;div id=&quot;another&qu...
<python><beautifulsoup>
2024-04-03 15:33:29
0
21,027
Danny Beckett
78,268,766
8,506,921
Fastest way to extract relevant rows - pandas
<p>I've got a very large pandas df that has the fields <code>group</code>, <code>id_a</code>, <code>id_b</code> and <code>score</code>, ordered by <code>score</code> so the highest is at the top. There is a row for every possible combination of <code>id_a</code> and <code>id_b</code>. I want to extract rows so that the...
<python><pandas>
2024-04-03 15:27:11
2
1,874
Jaccar
78,268,740
1,126,944
Import ... From ... Confusion
<p>I read the Python3 references for the Import statement <a href="https://docs.python.org/3/reference/simple_stmts.html#import" rel="nofollow noreferrer">here</a>, in which it said:</p> <blockquote> <p>The from form uses a slightly more complex process: find the module specified in the from clause, loading and initial...
<python><python-3.x>
2024-04-03 15:24:00
2
1,330
IcyBrk
78,268,547
5,330,527
Autocomplete dropdown for related-field filtering in Django admin
<p>I'd like to have a nice autocomplete dropdown in my Django admin backend for filtering out results in the <code>project</code> model according to the <code>subject</code> attached to a <code>person</code>. this is my <code>models.py</code>:</p> <pre><code>class Subject(models.Model): name = models.CharField(max_...
<python><django>
2024-04-03 14:54:08
1
786
HBMCS
78,268,161
182,737
Indicate to mypy that an attribute cannot be none in a subclass
<p>Given the following code</p> <pre><code>@dataclass class MaybeTextContainer: text: list[str] | None class CertainlyText(MaybeTextContainer): def __init__(self) -&gt; None: super().__init__(text=[]) self.say_hi() def say_hi(self) -&gt; None: self.text.append(&quot;Hi&quot;) </c...
<python><mypy><python-dataclasses>
2024-04-03 13:53:00
1
1,229
Frank Meulenaar
78,268,053
9,381,746
How to obtain UTF-8 binary representation of an emoji character?
<p>I am trying to print bits of of UTf-8 character. In that case an emoji. According to the the following video: <a href="https://www.youtube.com/watch?v=ut74oHojxqo" rel="nofollow noreferrer">https://www.youtube.com/watch?v=ut74oHojxqo</a> the following code <code>script.py</code> (both from the script edited with vim...
<python><string><utf-8><byte><bit>
2024-04-03 13:33:32
1
5,557
ecjb
78,267,967
9,758,352
Ways to intercept error responses in Django and DRF
<p>The problem:</p> <ul> <li>Django errors are values to <code>details</code> keys.</li> <li>Django Rest Framework (DRF) errors are values to <code>detail</code> keys.</li> </ul> <p>Therefore, having an application that raises both Django and DRF exceptions is inconsistent by default. I want a way to change the respons...
<python><django><django-rest-framework>
2024-04-03 13:18:37
0
457
BillTheKid
78,267,668
22,371,917
How to make a terminal emulator in flask
<p>I want to make a flask app that allows me to run commands in cmd in the path D:<br /> I tried using subprocess and it worked for commands that didn't need to stay open but running something like a file with another flask app or something it would error because it needed it to stay alive or something i also tried os ...
<python><windows><flask><cmd>
2024-04-03 12:32:28
1
347
Caiden
78,267,650
827,927
How to generate a random binary invertible matrix?
<p>I need to generate a random n-by-n matrix A with the following properties:</p> <ol> <li>Every element in A is either 0 or 1;</li> <li>A is invertible;</li> <li>In the inverse of A, the sum of values in each row is at least 0.</li> </ol> <p>I can generate random binary matrices using numpy:</p> <pre><code>A = np.rand...
<python><matrix><linear-algebra>
2024-04-03 12:29:32
0
37,410
Erel Segal-Halevi
78,267,585
7,331,538
Scrapy force close at timeout limit when TCP connection freezes
<p>In my scpraper I have a specific url which goes down periodically. The finish stats show</p> <pre><code> 'downloader/exception_count': 2, 'downloader/exception_type_count/twisted.internet.error.TCPTimedOutError': 2, 'elapsed_time_seconds': 150.027039, 'finish_reason': 'closespider_timeout', </code></pre> <p>I add...
<python><tcp><scrapy><web-crawler><twisted.internet>
2024-04-03 12:17:41
2
2,377
bcsta
78,267,511
4,847,250
How to use curve_fit of scipy with constrain where the fitted curve is always under the observations?
<p>I'm trying to fit a signal with an exponential decay curve. I would like to constrain the fitted curve to be always under the signal. How can I add such a constraint? I tried something with a residual function with a penalization but the fit is not good</p> <p>Here a minimal example</p> <pre><code>import matplotlib....
<python><curve-fitting>
2024-04-03 12:03:26
1
5,207
ymmx
78,267,481
9,251,158
How to set video language when uploading to YouTube with Python API client
<p>I am uploading videos to YouTube programmatically following <a href="https://developers.google.com/youtube/v3/guides/uploading_a_video" rel="nofollow noreferrer">the official guide</a>:</p> <pre class="lang-py prettyprint-override"><code> body=dict( snippet=dict( title=title, description=description...
<python><python-3.x><youtube><youtube-api><youtube-data-api>
2024-04-03 11:59:36
1
4,642
ginjaemocoes
78,267,455
3,840,551
How can I indicate to static type checkers that specific methods of a library's baseclass MUST be re-implemented in our subclasses?
<p>I use a protocol to enforce that our subclasses should implement extra methods and define extra attributes. But I would like to also enforce that specific methods of the base class <em>MUST</em> be re-implemented in our subclass. Is this possible?</p> <pre class="lang-py prettyprint-override"><code>### From some lib...
<python><python-typing>
2024-04-03 11:56:01
1
1,529
Gloomy
78,267,418
536,262
fastapi returns HTML on HTTPException
<p>I'm trying to return a HTML response on HTTPException for a display board, so it can reload on connection errors:</p> <pre class="lang-py prettyprint-override"><code>from fastapi import HTTPException from fastapi.responses import HTMLResponse, JSONResponse class ReloadException(HTTPException): &quot;&quot;&quot; ...
<python><fastapi>
2024-04-03 11:47:49
0
3,731
MortenB
78,266,811
2,058,355
Unable to generate sentence embedding via multiprocessing
<p>I am trying to generate sentence embeddings for say 300 sentences using a huggingface model and my code is just keeps getting stuck, execution just doesn't proceed.</p> <p>I have put debug statements at different parts of the snippet but nothing conclusive. On the contrary when i try to embed sentences sequentially,...
<python><multiprocessing>
2024-04-03 09:52:29
1
1,755
prashantgpt91
78,266,786
4,673,585
Azure function app in python not trigger when blob is uploaded
<p>I have a consumption based function app in python which will be triggered when a blob with extension .db is created/uploaded in a folder in a container of a storage account.</p> <p>function.json:</p> <pre><code>{ &quot;scriptFile&quot;: &quot;__init__.py&quot;, &quot;bindings&quot;: [ { &quot;name&quot;...
<python><azure-functions><azure-blob-trigger>
2024-04-03 09:48:53
1
337
Rahul Sharma
78,266,772
567,059
How to stream Python sub-process output when using 'stdin'
<p>When using <code>stdin=PIPE</code> with <code>subprocess.Popen()</code>, is there a way to read <code>stdout</code> and <code>stderr</code> as they are streamed?</p> <p>When not using <code>stdin=PIPE</code> I have been successfully using reading the output from <code>stdout</code> and <code>stderr</code>, as descri...
<python><subprocess>
2024-04-03 09:46:49
1
12,277
David Gard
78,266,757
833,362
How to iterate a dict within a template that contains a key named items?
<p>I have some fairly simple django template and part of it is iterating through some dict ( that originates from some parsed json files ) like:</p> <pre><code>{% for k, v in d.items %} </code></pre> <p>However my dict now contains an item called <code>items</code>, which because for the syntax of <code>a.b</code> djan...
<python><django><django-templates>
2024-04-03 09:44:08
2
16,146
PlasmaHH
78,266,625
4,399,016
Identifying Peaks (Local Maxima) and Troughs (Local Minima) in Data and Labeling them
<p>I have data that resembles this:</p> <pre><code>import pandas as pd import random random.seed(901) rand_list = [] for i in range(20): x = random.randint(480, 600) rand_list.append(x/10) df = pd.DataFrame({'INDEX':rand_list}) df['INDEX_DIFF'] = df.INDEX.diff() df </code></pre> <p>Output:</p> <pre class="lan...
<python><pandas><data-wrangling>
2024-04-03 09:23:09
2
680
prashanth manohar
78,266,597
188,331
TypeError: forward() got an unexpected keyword argument 'token_type_ids'
<p>Using the HuggingFace Transformers framework, I encountered a problem when I used a custom <code>forward()</code> function in a custom class to fine-tune a pre-trained model to match my custom Tokenizer, but a strange error occurred:</p> <blockquote> <p>TypeError: forward() got an unexpected keyword argument 'token_...
<python><huggingface-transformers><huggingface-tokenizers>
2024-04-03 09:18:54
0
54,395
Raptor
78,266,465
2,875,230
How to remove json elements and reformat it
<p>I have the follow JSON as an output of an enumerate function.</p> <pre><code>{'question': (0, 'Who invented the light bulb?'), 'answers': [{'answer': 'Thomas Edison', 'score': '2.0'}, {'answer': 'Nikola Tesla', 'score': '2.0'}, {'answer': 'Albert Einstein', 'score': '0.0'}], 'error': &quot;We didn't quite get that&q...
<python><json><string>
2024-04-03 08:55:27
3
337
user2875230
78,266,452
22,326,950
Range slider for plotly waterfall in python
<p>I would like to implement a <a href="https://plotly.com/python/range-slider/" rel="nofollow noreferrer">range slider</a> for <code>plotly.graph_objects.Waterfall</code> chart. Unfortunately its layout has no property <code>rangeslider</code> so passing <code>rangeslider=dict(visible=True)</code> in <code>fig.update_...
<python><jupyter-notebook><plotly>
2024-04-03 08:53:31
1
884
Jan_B
78,266,416
1,422,096
Reed-Solomon correction with a stream of bits
<p>This works with the <a href="https://github.com/tomerfiliba-org/reedsolomon" rel="nofollow noreferrer"><code>reedsolo</code></a> package:</p> <pre><code>from reedsolo import RSCodec, ReedSolomonError rsc = RSCodec(10) # 10 ecc symbols rsc.encode(b'hello world') # b'hello world\xed%T\xc4\xfd\xfd\x89\xf3\xa8\xaa' rs...
<python><bit><error-correction><reed-solomon>
2024-04-03 08:46:55
1
47,388
Basj
78,266,223
13,903,839
Replace the row with a norm of 0 in the tensor with the corresponding row in another tensor
<p>I now have a pytorch tensor A of dimensions (2000, 1, 360, 3). I'm trying to find all indexes with norms of 0 in the last dimension of this tensor. And replace these positions with the values of the corresponding positions in another tensor B (the same dimension as A).</p> <p>Example (A, B: (2, 1, 3, 3))</p> <pre><c...
<python><pytorch><tensor>
2024-04-03 08:10:55
1
301
ojipadeson
78,266,175
354,051
scipy.signal.resample vs Ramer Douglas Peucker
<p><a href="https://i.sstatic.net/pqEZO.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pqEZO.jpg" alt="enter image description here" /></a></p> <p>The graph data is loaded from a wave file and only 1600 samples are used. For resampling, I have used</p> <pre class="lang-py prettyprint-override"><code>res...
<python><scipy><sampling>
2024-04-03 08:04:21
0
947
Prashant
78,266,102
23,461,455
OpenCV throws Error: (-215:Assertion failed)
<p>Hi I am trying to read in and display a picture with cv2 for further analysis with the following code:</p> <p>Edit: I added the path with my username being clear to prove it doesn't contain wacky characters. I also tried with multiple .jpg files. I am using opencv-python version 4.9.0.80</p> <pre><code>import cv2 ...
<python><file><path><anaconda><conda>
2024-04-03 07:51:40
2
1,284
Bending Rodriguez
78,265,963
15,313,661
Error when connecting to Azure SQL DataBase with PYODBC and ODBC Connection using DSN
<p>I'm using python in a project, in which I query data from an Azure SQL Database, and then write back the results to that same database.</p> <p>I use the following code to create the SQLAlchemy engine:</p> <pre class="lang-py prettyprint-override"><code>connection_string = 'mssql+pyodbc://user:pwd@dsn' engine = sqla...
<python><sqlalchemy><azure-sql-database><odbc>
2024-04-03 07:30:06
2
536
James
78,265,889
11,258,263
sys.path not always/reliably set by sitecustomize -- how can it be reliably overridden?
<p>I have an application using embedded Python, which includes <code>python.exe</code>. I have added a <code>sitecustomize.py</code> to set <code>sys.path</code>, something like:</p> <pre class="lang-py prettyprint-override"><code>import sys sys.path = ['.','.\\python310.zip','.\\Lib','.\\Lib\\site-packages'] </code></...
<python><pythonpath><python-embedding>
2024-04-03 07:17:19
1
470
DLT