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
79,199,153
31,317
Using IUnknown-derived interface in python / pywin32
<p>In short: I'm trying to call a method on in IUknown-based interface. I have some parts, but they don't connect.</p> <p>Situation:</p> <pre><code>o1 = win32com.client.Dispatch(&quot;SomeProgId&quot;) o2 = o1.SubObject </code></pre> <p>The subobject is not co-creatable, <code>o2._ole_obj_</code> is a &lt;PyIDispatch a...
<python><com><pywin32><win32com>
2024-11-18 08:10:24
0
41,346
peterchen
79,199,034
2,955,827
How to read a part of parquet dataset into pandas?
<p>I have a huge dataframe and want to split it into small files for better performance. Here is the example code to write. BUT I can not just read a small pieces from it without loading whole dataframe into memory.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import os # Create a sample Dat...
<python><pandas><parquet><pyarrow>
2024-11-18 07:24:44
1
3,295
PaleNeutron
79,198,966
4,190,657
ThreadPoolExecutor for Parallelism
<p>I have PySpark code which does few POST API call to an external system. For each row in the input dataframe, I need to trigger a POST API request (using Python code) to create an entry in an external system. Given that the dataset is large, this process was taking considerable time.</p> <p>To improve performance, p...
<python><python-3.x><apache-spark><pyspark>
2024-11-18 07:04:16
0
305
steve
79,198,926
9,632,470
How to Read a Text File and Make Pandas Data Frame
<p>Given a text file (data.txt) with the following contents:</p> <pre><code>John: 1 Jane: 5 Mark: 7 Dan: 2 </code></pre> <p>How can I use python to use the text file to create a data frame that would be logically equivalent to the one given by:</p> <pre><code># Initialize data data = {'Name': ['John', 'Jane', 'Mark'...
<python><pandas><dataframe>
2024-11-18 06:48:00
2
441
Prince M
79,198,686
6,468,467
diffPool implementation in PyTorch for unsipervised clustering of homogeneous graph
<p>I am trying to implement unsupervised multilayered clustering based on the <strong>difpool</strong> approach.</p> <pre><code>import torch import torch.nn.functional as F from torch_geometric.data import Data from torch_geometric.nn import GCNConv, DenseGCNConv, dense_diff_pool from torch_geometric.utils import to_de...
<python><tensorflow><graph-neural-network>
2024-11-18 04:26:24
0
841
HSJ
79,198,575
1,297,248
SQLAlchemy database session is not reset after each test
<p>I have this TestRunner base class mostly following their <a href="https://docs.sqlalchemy.org/en/14/orm/session_transaction.html#joining-a-session-into-an-external-transaction-such-as-for-test-suites" rel="nofollow noreferrer">example</a>:</p> <pre class="lang-py prettyprint-override"><code>import unittest from sql...
<python><sqlalchemy>
2024-11-18 02:55:30
2
6,409
Batman
79,198,485
9,873,381
Can we use Optuna to optimize YOLOv7's hyperparameters on a custom dataset?
<p>I would like to use Optuna to optimize YOLOv7's hyperparameters like the learning rate, momentum, weight_decay, iou_t, etc. Is this possible?</p> <p>I tried writing an objective function that would call the training script <a href="https://github.com/WongKinYiu/yolov7/blob/main/train_aux.py" rel="nofollow noreferrer...
<python><deep-learning><yolo><hyperparameters><optuna>
2024-11-18 01:26:56
0
672
Skywalker
79,198,413
492,015
Adding JSON key to field generated by usaddress python library
<p>Currently I'm using the usaadress python library to parse US addresses <a href="https://github.com/datamade/usaddress" rel="nofollow noreferrer">https://github.com/datamade/usaddress</a></p> <p>Example code</p> <pre><code>address = '456 Elm St, Someville, NY 54321' print( usaddress.tag(address)) </code></pre> <p>and...
<python>
2024-11-18 00:20:41
2
9,055
Arya
79,198,409
1,837,976
Azure Key vault creation and configuration using script
<p>I'm new to the Azure Key vault automation. I know its possible to create/automate the AKV creation using ARM template or Terraform or some other script. I have a requirement to create, configure and store the secrets in the Key vault.</p> <p>Step1: Create a Key vault in a particular subscription and resource group.<...
<python><azure><terraform><azure-resource-manager><azure-keyvault>
2024-11-18 00:14:25
1
2,625
AskMe
79,198,397
5,547,553
How to redraw figure on event in matplotlib?
<p>I'm trying to pre-generate and store matplotlib figures in python, and then display them on a keyboard event (left-right cursor keys).<br> It partially seems working, but fails after the first keypress.<br> Any idea, what am I doing wrong?</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot ...
<python><matplotlib>
2024-11-18 00:05:40
1
1,174
lmocsi
79,198,377
398,348
How to tell if a matrix is 1-D or 2-D or... how to know if len(lst) is the number of rows of a 2-D matrix or the number of cols of a 1-D matrix?
<p>I am learning python and puzzled by this error while trying to tell if a matrix is 1-D or 2-D. (they are all integers and rectangular since I am multiplying them. That is why I call them matrices)</p> <p>I am trying to find the dimensions of the matrices so that I can create a new matrix representing their product. ...
<python>
2024-11-17 23:43:43
2
3,795
likejudo
79,198,298
14,122
Improving safety when a SQLAlchemy relationship adds conditions that refer to tables that don't exist yet
<p>I have a situation where I want to set up relationships between tables, mapped with the SQLAlchemy ORM layer, where these relationships have an extra join key. As far as I know, setting this up by hand requires embedding strings that are <code>eval</code>'d; I'm trying to figure out to what extent that can be avoide...
<python><sqlalchemy>
2024-11-17 22:37:56
1
299,045
Charles Duffy
79,198,264
2,329,592
Connecting a Web Scraper to an Asset in Dagster without the Pipeline Module
<p>I want to scrape the content of a website in dagster with scrappy. Unfortunately, all the examples I have found use the pipeline module of dagster. The current version does not have this pipeline plugin.</p> <p>I have this scraper and its parse function which returns all headings of the document. These headings are ...
<python><scrapy><dagster>
2024-11-17 22:12:25
0
3,262
marcel
79,198,258
1,169,091
Why does pip say cmake is not installed?
<p>I have cmake:</p> <pre><code>PS C:\Users\nicholdw\AppData\Local\Programs\Python\Python312&gt; cmake --version cmake version 3.31.0 </code></pre> <p>I try to install dlib and it says I don't have cmake:</p> <pre><code>PS C:\Users\nicholdw\AppData\Local\Programs\Python\Python312&gt; pip install dlib Collecting dlib ...
<python><cmake><pip>
2024-11-17 22:10:21
0
4,741
nicomp
79,198,230
320,399
Django + Dask integration: usage and progress?
<h2>About performance &amp; best practice</h2> <blockquote> <p><em>Note, the entire code for the question below is public on Github. Feel free to check out the project! <a href="https://github.com/b-long/moose-dj-uv/pull/3" rel="nofollow noreferrer">https://github.com/b-long/moose-dj-uv/pull/3</a></em></p> </blockquote...
<python><django><concurrency><dask>
2024-11-17 21:54:06
1
2,713
blong
79,198,203
11,594,202
How to properly call asynchronous request in Python without aiohttp
<p>This may be a silly question, but I designed a small python script to synchronize two applications, designed to run in a HubSpot custom coded action. This environment runs for a maximum of 20 seconds with a maximum 128MB of memory.</p> <p>To optimize for speed, my code fetches records asynchronously using <code>asyn...
<python><asynchronous><python-requests><get>
2024-11-17 21:39:06
0
920
Jeroen Vermunt
79,198,199
3,486,684
How do I stop legends from being merged when vertically concatenating two plots?
<p>Consider the following small example (based off of this gallery example]):</p> <pre class="lang-py prettyprint-override"><code>import altair as alt from vega_datasets import data import polars as pl # add a column indicating the year associated with each date source = pl.from_pandas(data.stocks()).with_columns(year...
<python><vega-lite><altair>
2024-11-17 21:37:11
1
4,654
bzm3r
79,198,175
893,254
Fernet key must be 32 url-safe base64-encoded bytes - How to create a key for use with Fernet?
<h4>An example Fernet key</h4> <p>The following code produces an example Fernet key, and reports that the length is 44.</p> <pre><code>from cryptography.fernet import Fernet generated_key = Fernet.generate_key() print(f'Example generated key: {generated_key}') print(f'Length of example key: {len(generated_key)}') </co...
<python><cryptography><base64><fernet>
2024-11-17 21:17:38
1
18,579
user2138149
79,198,131
554,305
How can I enable Auto fitting of column widths in the python package openpyxl?
<p><em>This is a similar question to <a href="https://stackoverflow.com/questions/71139718/openpyxl-autosize-column-size">Openpyxl autosize column size</a> -and- <a href="https://stackoverflow.com/questions/65115775/python-openpyxl-worksheet-autosizing-column-dimensions-fail">python openpyxl worksheet autosizing column...
<python><excel><openpyxl>
2024-11-17 20:45:00
0
395
BeschBesch
79,197,994
893,254
What are the certchain.pem and private.key files used by Pythons ssl library, are they required, and how can I create them if they are?
<h1>Background</h1> <p>I am writing a Python utility which will allow synchronization of files and folders across a network between a client machine and a server. Synchronization will be unidirectional and initiated by a client push action.</p> <p>The initial &quot;version 1&quot; for this is quite simple. The server w...
<python><ssl><encryption><tls1.3>
2024-11-17 19:30:46
0
18,579
user2138149
79,197,810
12,357,035
auto formatting using yapf to put parameters on multiple lines in condensed format
<p>Related to <a href="https://stackoverflow.com/questions/65955455/auto-formatting-python-code-to-put-parameters-on-same-line">this</a>. But instead of putting all arguments on single line, I want to put them onto multiple lines in condensed form.</p> <p>Basically I want to transform:</p> <pre><code>def f(arg1: typ1, ...
<python><vscode-extensions><code-formatting><yapf>
2024-11-17 17:52:58
0
3,414
Sourav Kannantha B
79,197,656
1,492,229
How to reduce the size of Numpy data type
<p>I am using Python to do cosine similarity.</p> <pre><code>similarity_matrix = cosine_similarity(tfidf_matrix) </code></pre> <p>The problem is that I am getting this error</p> <pre><code>MemoryError: Unable to allocate 44.8 GiB for an array with shape (6011226750,) and data type float64 </code></pre> <p>I don't think...
<python><numpy><scikit-learn><cosine-similarity>
2024-11-17 16:41:49
0
8,150
asmgx
79,197,644
336,827
AKS Python Azure Function - console log without timestamp
<p>This is the output of an Azure Function running in a kubernetes pod.</p> <p>How can I enable the timestamp in my logs?<br /> Can I have one line of log for each message instead of two?</p> <pre><code>info: Function.name_of_the_function.User[0] this is the info message from the function... info: Function.name_o...
<python><azure><azure-functions>
2024-11-17 16:34:33
1
30,887
freedev
79,197,575
759,880
Python GIL, multi-threading and atomicity
<p>I have read that lists in python provide atomic operations. I have 2 threads that use a list: one iterates over the list to retrieve regex strings to apply to some objects, and one updates the list at regular intervals by adding and removing elements of it. If I want the list update to be atomic for the first thread...
<python><multithreading>
2024-11-17 15:59:05
3
4,483
ToBeOrNotToBe
79,197,289
4,061,339
sub chapters not shown in ebooklib in python
<h1>Objective</h1> <p>To programmatically create a epub file from text files</p> <h1>Problem</h1> <p>Some of the sub chapters are not shown</p> <h1>Minimal Reproducible Example</h1> <pre class="lang-py prettyprint-override"><code>from ebooklib import epub # Create a new EPUB book book = epub.EpubBook() # Set metadata...
<python><windows><visual-studio-code><epub><ebooklib>
2024-11-17 13:26:41
1
3,094
dixhom
79,197,024
19,270,168
Google Forms API raises google.auth.exceptions.RefreshError: 'No access token in response.'
<p>I want to create a grading bot for my community's applications through Google Forms and when I try to retrieve a form, I get a <code>RefreshError</code>.</p> <p>Minimal Reproducible Example:</p> <pre class="lang-py prettyprint-override"><code># Google Credentials from google.oauth2 import service_account SCOPES = ...
<python><google-cloud-platform><google-forms><google-forms-api>
2024-11-17 10:53:43
1
1,196
openwld
79,196,656
19,499,853
networkx graph get groups of linked/connected values with multiple values
<p>If I use such data</p> <pre><code>import networkx as nx G = nx.Graph() G.add_nodes_from([1, 2, 3, 4, 5, 6, 7]) G.add_edges_from([(1, 2), (1, 3), (2, 4), (5, 6)]) print(list(nx.connected_components(G))) </code></pre> <p>Everything works fine.</p> <p>But what if I need to get connected values from multiple tuple, su...
<python><graph><logic><networkx>
2024-11-17 07:07:50
1
309
Gerzzog
79,196,654
2,962,555
Replacing the placeholder in a hierarchical config.yaml file with the value in the .env file
<p>Right now, I have config.yaml like this</p> <pre><code>kafka: bootstrap_servers: &quot;${BOOTSTRAP_SERVERS}&quot; group: &quot;${GROUP_NAME_1}&quot; topics: - name: &quot;${TOPIC_1}&quot; consumers: &quot;${CONSUMER_NUMBER_FOR_TOPIC_1}&quot; </code></pre> <p>And I have Dynaconf working as below:</p>...
<python><configuration><environment-variables><.env><dynaconf>
2024-11-17 07:06:35
1
1,729
Laodao
79,196,626
2,929,914
Python Polars recursion
<p>I've used Polars for some time now but this is something that often makes me go from Polars DataFrames to native Python calculations. I've spent resonable time looking for solutions that (tries) to use <a href="https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.shift.html#polars.Expr.shift"...
<python><dataframe><python-polars>
2024-11-17 06:45:13
2
705
Danilo Setton
79,196,539
6,463,525
Exception has occurred: ValueError in langchain
<pre><code>def standardize_column_names(df, target_columns): &quot;&quot;&quot; Uses a language model to standardize column names dynamically based on semantic similarity. Args: df (pd.DataFrame): The DataFrame whose columns need standardization. target_columns (list): A list of target colum...
<python><langchain>
2024-11-17 05:16:26
0
1,203
kvk30
79,196,217
9,632,470
Using BeautifulSoup to extract Titles from Text Box
<p>I am attempting to write a code using beautiful soup that prints the text for the links in the left handed gray box on <a href="https://www.mountainproject.com/area/110928184/stuart-enchantments" rel="nofollow noreferrer">this</a> webpage. In this case the code should return</p> <pre><code>** Enchantments Bouldering...
<python><html><beautifulsoup>
2024-11-16 23:05:57
2
441
Prince M
79,196,138
1,700,890
How to import dbutils module in Python on Databricks
<p>In Databricks Python notebook I can easily use <code>dbutils</code> module. Now I also would like to use it within plain Python file which I import into Databricks notebook</p> <p>Here is an example.</p> <p>Here is content of some_python_module.py</p> <pre><code>secret_value = dbutils.secrets.get(&quot;some_location...
<python><azure><databricks><dbutils>
2024-11-16 22:07:33
2
7,802
user1700890
79,195,973
15,086,628
How to access unknown fields in python protobuf version 5.38.3 with upb backend
<p>I'm using Python protobuf package version <code>5.38.3</code> for deserializing some packets and I need to check if the messages I deserialize are conformant or not to a specific protobuf message structure. For some checks I want to obtain the list of unknown fields.</p> <p><a href="https://github.com/protocolbuffer...
<python><protocol-buffers>
2024-11-16 20:09:22
1
395
V.Lorz
79,195,896
405,017
Correlate columns in two pandas dataframes with varying data types
<p>I have two Excel worksheets, one of which (&quot;edit&quot;) is a slightly modified version of the other (&quot;base&quot;). I want to figure out if any columns have been added, deleted, or moved. I have loaded the worksheets into dataframes, and tried to correlated the two frames, but I get an unhelpful error, whic...
<python><pandas><dataframe><spreadsheet><correlation>
2024-11-16 19:22:23
2
304,256
Phrogz
79,195,851
662,967
How can I find the last occurance of a dot not preceding with a slash?
<p>I'm trying to create a regex to find the last dot in a string not preceded by a slash.</p> <pre><code>r = MyLine.Text.Swap\ Numbered\ and\ Unnumbered\ List.From\ -\ -\ -\ to\ Numbered\ list\ 1\.\ 2\.\ 3\.\ </code></pre> <p>What I want to find as match is &quot;<code>From\ -\ -\ -\ to\ Numbered\ list\ 1\.\ 2\.\ 3\.\...
<python><python-3.x><regex>
2024-11-16 18:50:24
1
8,199
Reman
79,195,840
6,843,153
Pylance failing to resolve import of libraries in a devcontainer in Linux
<p>I have a Python project in <strong>Ubuntu 24.04.1 LTS</strong> and I have a DevContainer in VSC with <strong>Debian GNU/Linux 11</strong>, the problem is that <strong>Pylance</strong> is flagging <code>import streamlit as st</code> with <code>Import &quot;streamlit&quot; could not be resolved</code>. If I run the ap...
<python><docker><ubuntu><containers><pylance>
2024-11-16 18:41:03
1
5,505
HuLu ViCa
79,195,787
8,190,068
How do I make an Accordion layout which allows more than one item to be expanded and also scrolls when the items are many?
<p>I currently have an Accordion layout which looks like this:</p> <p><a href="https://i.sstatic.net/WxTTp3Aw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WxTTp3Aw.png" alt="current accordion layout" /></a></p> <p><em>Note: the code for this can be seen here: <a href="https://stackoverflow.com/questi...
<python><accordion><kivy-language>
2024-11-16 18:10:08
0
424
Todd Hoatson
79,195,579
16,037,313
How to generate a matrix in Python with 0 and 1 alternatively sorted
<p>I want to create a matrix of 0 and 1, using Numpy package, alternating 0 and 1, of size 8*8</p> <p>This means:</p> <ul> <li>Along each row, the values alternate between 0 and 1.</li> <li>Along each column, the values also alternate between 0 and 1.</li> </ul> <p>I want something like this:</p> <pre><code>np.random.b...
<python><numpy>
2024-11-16 16:31:18
3
410
Javier Hernando
79,195,542
7,090,501
Selenium cannot retrieve url when running in Google Colab
<p>I built a small web scraper that has run successfully in a Google Colab over the last few months. It downloads a set of billing codes from the CMS website. Recently the driver started throwing timeout exceptions when retrieving some but not all urls. The reprex below downloads a file from two urls. It executes succe...
<python><selenium-webdriver><selenium-chromedriver><google-colaboratory><google-notebook>
2024-11-16 16:13:20
2
333
Marshall K
79,195,406
2,386,113
Scatter plot in python with x/y-ticks on a haircross?
<p>I want to create a scatter plot with a hair-cross (vertical and horizontal line) at the centre. The x-ticks and y-ticks also need to be shown on this hair-cross. How can I do that?</p> <p><strong>Sample Required Plot:</strong> <a href="https://i.sstatic.net/MkNkI2pBm.png" rel="nofollow noreferrer"><img src="https://...
<python><matplotlib><plot><figure>
2024-11-16 15:00:20
0
5,777
skm
79,195,340
3,885,446
Jupyter notebook not displaying properly
<p>This question is very similar to <a href="https://stackoverflow.com/questions/78173935/jupyter-notebook-not-displaying-correctly-after-reinstall">Jupyter Notebook not displaying correctly after reinstall</a> which does not have a satisfactory answer.</p> <p>A few months ago I was fiddling around with the preferences...
<python><css><jupyter-notebook>
2024-11-16 14:23:24
0
575
Alan Johnstone
79,195,338
2,685,402
How do I attach a python debugger to a Gradio UI running on IntelliJ Jupyter?
<p>I am running Gradio in an IntelliJ Jupyter plugin editor window. I have set a breakpoint in the <code>chat</code> function. I run the following code to start a Gradio interface in debug mode. The breakpoint I created is &quot;Suspend: All&quot;, not &quot;Suspend: Thread&quot;. The breakpoints are not being hit.</p>...
<python><intellij-idea><jupyter><gradio>
2024-11-16 14:22:33
0
1,550
Wojtek
79,195,042
5,866,580
Handling complex parentheses structures to get the expected data
<p>We have data from a REST API call stored in an output file that looks as follows:</p> <p><strong>Sample Input File:</strong></p> <pre><code>test test123 - test (bla bla1 (On chutti)) test test123 bla12 teeee (Rinku Singh) balle balle (testagain) (Rohit Sharma) test test123 test1111 test45345 (Surya) (Virat kohli (La...
<python><regex><awk>
2024-11-16 11:20:41
9
134,567
RavinderSingh13
79,194,909
5,563,616
How to share the standard input with a child process in Python?
<p>I need to do in Python what this C++ program does:</p> <pre class="lang-none prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;sys/wait.h&gt; #include &lt;stdio.h&gt; int main() { char buffer[256]; read(0, buffer, sizeof(buffer)); s...
<python>
2024-11-16 10:07:37
0
1,682
Jennifer M.
79,194,425
10,679,609
Sampling from joint probability mass function in python
<p>I have a non-negative normalized vector <code>p</code>. I would like to sample an index from the index set of the vector. The probability getting sample <code>k</code> is <code>p[k]</code>. Using <code>np.random.choice</code> function, I can write the following code.</p> <pre class="lang-py prettyprint-override"><co...
<python><probability><sampling>
2024-11-16 02:52:12
1
694
Sakurai.JJ
79,194,050
569,229
How can I stop resource files that are Python source from being compiled by pip?
<p>I have a Python project with a flat layout that has some resource files. My <code>pyproject.toml</code> has the following entries:</p> <pre class="lang-ini prettyprint-override"><code>[tool.setuptools] packages = [ &quot;linton&quot;, &quot;linton.subcommand&quot;, ] [tool.setuptools.package-data] linton = ...
<python><pip>
2024-11-15 21:49:13
0
756
Reuben Thomas
79,193,781
89,233
grpc_tools.protoc compiling grpc with edition = 2023 fails
<p>I'm using protoc version 28.3 on macos:</p> <pre><code>&gt; protoc --version libprotoc 28.3 </code></pre> <p>This version can generate gRPC for typescript and go and C++, with the appropriate plugins. It can also generate plain protobuf:</p> <pre><code>&gt; protoc --experimental_editions -I src/proto3 --python_out=....
<python><protocol-buffers><grpc>
2024-11-15 19:52:44
1
7,386
Jon Watte
79,193,735
11,594,202
Python - Generator not working with next method
<p>I created a generator to perform pagination on an api:</p> <pre><code>def page_helper(req, timeout=5, page=1, **kwargs): print(f&quot;Page {page}&quot;, end=&quot;\r&quot;) try: response = req(params={**kwargs, &quot;page&quot;: page}) response = response.json() except Exception as e: ...
<python><iterator><generator><yield>
2024-11-15 19:35:18
2
920
Jeroen Vermunt
79,193,687
2,662,743
python locust config file for multiple files/classes
<p>I'm using locust to do some load testing on our backend service and I have three classes defined in three different .py files</p> <p>then I'm trying to run locust using this command line</p> <p>==&gt; <code>locust -f locustfiles/locustfile.py --headless --config ../loadTestConfig.yml</code></p> <p><strong>locustfile...
<python><locust>
2024-11-15 19:12:29
0
1,767
eetawil
79,193,647
5,563,616
Can I prevent "^Z" from being printed when I handle SIGTSTP (Ctrl-Z) in my program?
<p>In Linux I need to print the terminal program status when the user presses some keyboard hotkey.</p> <p>Since <kbd>Ctrl</kbd>+<kbd>T</kbd> isn't available on Linux (it is only available on BSDs), I decided to use <kbd>Ctrl</kbd>+<kbd>Z</kbd> instead.</p> <p>I handle the SIGTSTP signal in my program, and it works fin...
<python><terminal>
2024-11-15 18:57:24
2
1,682
Jennifer M.
79,193,384
726,730
Open cv.VideoCapture(index) - ffmpeg list camera names - How to match?
<pre class="lang-py prettyprint-override"><code> def fetch_camera_input_settings(self): try: self.database_functions = database_functions self.camera_input_device_name = database_functions.read_setting(&quot;camera_input_device_name&quot;)[&quot;value&quot;] self.camera_i...
<python><opencv><ffmpeg><camera>
2024-11-15 17:22:12
0
2,427
Chris P
79,193,167
474,772
Subclassing typing.TypeDict
<p>I skimmed over <a href="https://peps.python.org/pep-0589/" rel="nofollow noreferrer">PEP-0589</a>, and I am wondering why <code>typing.TypedDict</code> works when subclassing it like this:</p> <pre><code>class A(TypedDict, total=False): x: int y: int </code></pre> <p>Specifically, <code>TypedDict</code> is a...
<python><metaclass><typeddict>
2024-11-15 16:15:41
1
5,954
Mariy
79,193,082
10,425,150
"Invalid_grant" error after using "change_current_realm()" in keycloak-python
<p>I have <code>401: b'{&quot;error&quot;:&quot;invalid_grant&quot;,&quot;error_description&quot;:&quot;Invalid user credentials&quot;}'</code> error after I switch realm with <code>change_current_realm()</code> function from &quot;master&quot; to &quot;new-sso&quot; realm.</p> <p>Here is the full code:</p> <pre><code>...
<python><realm><keycloak>
2024-11-15 15:47:55
2
1,051
Gооd_Mаn
79,192,832
10,003,652
Is there a difference in rendering Matplotlib image (heatmaps) in Jupyter notebook vs running in Python script (terminal)?
<p>I have an NxN symmetric matrix from a <code>csv</code> file that I want to visualize using a heatmap with colorbar. The values consist of 0 to 1, and possibly <code>NaNs</code> as well. I used the following line of code to create a heatmap &amp; save it as a <code>png</code> file with <code>dpi = 300</code>:</p> <pr...
<python><matplotlib><visual-studio-code><jupyter-notebook>
2024-11-15 14:42:54
0
416
n3lmnTrxx
79,192,792
10,722,752
How to assign scores to each value in pandas columns based on percentile range, getting `Truth value of a Series is ambiguous.` error
<p>I need to assign scores to each of the values in many columns of a pandas dataframe, depending on the percentile score range each value falls between.</p> <p>I have created a function:</p> <pre><code>import pandas as pd import numpy as np def get_percentiles(x, percentile_array): percentile_array = np.sort(np.a...
<python><pandas><apply>
2024-11-15 14:26:58
1
11,560
Karthik S
79,192,572
11,062,613
How can I abbreviate phrases using Polars built-in methods?
<p>I need to abbreviate a series or expression of phrases by extracting the capitalized words and then creating an abbreviation based on their proportional lengths. Here's what I'm trying to achieve:</p> <ul> <li>Extract capitalized words from each phrase.</li> <li>Calculate proportional lengths based on the total leng...
<python><string><dataframe><python-polars>
2024-11-15 13:26:07
2
423
Olibarer
79,192,562
6,197,439
Open file from QFileDialog in native file explorer via right-click in PyQt5?
<p>In Firefox, if I download a file, there is a folder icon &quot;Show in Folder&quot;:</p> <p><a href="https://i.sstatic.net/x6qr3viI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/x6qr3viI.png" alt="Firefox Show in Folder" /></a></p> <p>... which when clicked, opens the native OS file explorer in the ...
<python><pyqt5><qt5><file-manager><qfiledialog>
2024-11-15 13:22:40
2
5,938
sdbbs
79,192,545
9,984,846
Python looks for modules in current working directory on self-hosted azure agent
<p>I have a self-hosted azure windows agent with which I want to run python scripts in a few steps for which I need a couple of libraries. Therefore I added the following tasks to my pipeline.yml</p> <pre><code> - task: UsePythonVersion@0 inputs: versionSpec: '3.12' architecture: 'x64' </code><...
<python><azure-devops>
2024-11-15 13:17:52
1
1,571
Christian
79,192,393
12,775,432
Torch randn vector differs
<p>I am trying to generate a torch vector with a specific length. I want the vector to have the same beginning elements when increasing its length using the same seed.</p> <p>This works when the vector's length ranges from 1 to 15 for example:</p> <p>For length 14</p> <pre><code>torch.manual_seed(1) torch.randn(14) te...
<python><torch><random-seed>
2024-11-15 12:32:22
1
640
pyaj
79,192,391
19,499,853
networkx graph get groups of linked/connected values
<p>I've got such data</p> <pre><code>import networkx as nx G = nx.Graph() G.add_nodes_from([1, 2, 3, 4, 5, 6, 7]) G.add_edges_from([(1, 2), (1, 3), (2, 4), (5, 6), (7)]) </code></pre> <p>As you can see 1 is connected with 2 (edge 1, 2) and 1 is connected with 3. This means that 2 is connected with 3 via 2.</p> <p>So I...
<python><graph><logic><networkx>
2024-11-15 12:32:06
1
309
Gerzzog
79,192,313
1,461,380
CrewAI - KeyError: 'key_name' When Running the Crew
<p>I’m following the CrewAI Getting Started Guide and running into a <code>KeyError: 'key_name'</code> when executing the <code>crewai run</code> command in the root of my project directory.</p> <pre><code>(ai-crew) userk@mycelium:~/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_development$ crewai run Ru...
<python><ubuntu><artificial-intelligence><crewai>
2024-11-15 12:07:49
2
918
UserK
79,192,261
5,335,649
aiohttp behaviour when not reading body
<p>In my current development, I am sending a request to 50-100 different servers at the same time with <code>aiohttp</code>, and I am in no need to read the body (only need status_code and headers). I also cannot use <code>HEAD</code> request for the purpose of my application.</p> <p>My goals are:</p> <ul> <li>Be able ...
<python><aiohttp>
2024-11-15 11:52:34
1
4,540
Rockybilly
79,191,816
11,152,224
Automatic token refresh using Admin SDK Python
<p>I've made a simple REST service using FastAPI + Admin SDK (firebase_admin).</p> <pre><code>import os import firebase_admin from firebase_admin import credentials, messaging from fastapi import FastAPI, HTTPException from pydantic import BaseModel from dotenv import load_dotenv load_dotenv() cred = credentials.Cert...
<python><oauth-2.0><jwt><firebase-cloud-messaging>
2024-11-15 09:44:12
0
569
WideWood
79,191,769
956,424
how to resolve latency issue with django M2M and filter_horizontal in ModelAdmin panel?
<p>I have used django ModelAdmin with M2M relationship and formfield filtering code as follows: But for superuser or any other login where the number of mailboxes is more than 100k. I have sliced the available after filtering. But loading the m2m field takes time and times out for superuser login:</p> <pre><code>def fo...
<python><django>
2024-11-15 09:33:05
2
1,619
user956424
79,191,760
3,296,786
Python test passing in CMake but not with pytest
<pre><code> def test_cover_fail(self): self.url = self._api(&quot;cover&quot;) fo.dis.cover().AndRaise(http_server.RpcError(&quot;error&quot;)) self.mock.ReplayAll() try: json.load(self._make_request()) except (urllib.error.HTTPError, urllib.error.URLError) as e: self.assertTrue(&quo...
<python><pytest>
2024-11-15 09:29:48
0
1,156
aΨVaN
79,191,712
1,719,931
Is dunder an official designation for `__method__` in Python?
<p>In a Python class you can use methods whose name is preceded and followed by a double underscore, which are called by a &quot;special&quot; syntax which is not the usual <code>object.method()</code> syntax.</p> <p>For example:</p> <pre><code>class Item: def __init__(self, name): self.name = name i = Ite...
<python><oop><methods>
2024-11-15 09:15:14
1
5,202
robertspierre
79,191,599
11,159,734
FastAPI unit testing: AttributeError: 'NoneType' object has no attribute 'send'
<p>I try to test my FastAPI application. I use a real postgres test database so I actually want to read/write data from/to the database instead of mocking.</p> <p>The first test works fine. However the second test will always give me this error:</p> <pre><code>FAILED tests/users/test_signup.py::test_signup_successful2 ...
<python><asynchronous><pytest><fastapi>
2024-11-15 08:38:33
1
1,025
Daniel
79,191,561
7,479,675
How to Parse Complex SQL Values String into Columns Safely
<p>I'm working with a string that represents SQL parameter values and need to parse it into individual columns. Here's an example of such a string:</p> <pre><code>values = &quot;( 14587, '290\'960', 'This is, a, difficult,,, string that uses '' \&quot; and even '' \&quot; , '' '', ''. So it definitely needs to be check...
<python><string>
2024-11-15 08:24:06
1
392
Oleksandr Myronchuk
79,191,501
8,721,930
Polars rolling window on time series with custom filter based on the current row
<p>How do I use polars' native API to do a rolling window on a datetime column, but filter out rows in the window based on the value of a column of the &quot;current&quot; row?</p> <p>My polars dataframe of financial transactions has the following schema:</p> <p><a href="https://i.sstatic.net/IYN2CLUW.png" rel="nofollo...
<python><dataframe><window-functions><python-polars>
2024-11-15 07:59:34
2
1,001
lionbigcat
79,191,441
6,930,340
How to identify differences in polars dataframe when assert_series_equal / assert_frame_equal fails?
<p>I am using <code>pl.testing.assert_frame_equal</code> to compare two <code>pl.DataFrame</code>s. The assertion fails. The traceback indicates that there are <code>exact value mismatches</code> in a certain column.</p> <p>The column in question is of type <code>bool</code>. It also contains <code>null</code> values. ...
<python><pytest><python-polars>
2024-11-15 07:36:17
2
5,167
Andi
79,191,312
4,080,615
How to sort python pandas dataframe in repetitive order after groupby?
<p>I have a dataset which is sorted in this order:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>1</td> <td>r</td> </tr> <tr> <td>a</td> <td>1</td> <td>s</td> </tr> <tr> <td>a</td> <td>2</td> <td>t</td> </tr> ...
<python><pandas><dataframe>
2024-11-15 06:37:06
1
1,017
DarthSpeedious
79,191,259
1,070,833
how to generate model constraint in cpmpy from a list?
<p>I have a list of filters that I need to apply to my model as OR so they cannot be added separately to the model. I'm looking for syntax to do it. Is there a way to extend a constraint added to the model and add the OR options in a loop? or some other cpmpy magic that can do that? I'm trying to write a generator of t...
<python><cpmpy>
2024-11-15 06:14:27
1
1,109
pawel
79,191,157
508,236
What is the correct way to measure the performance of a Databrick notebook?
<p>Here is my code for converting one column field of a data frame to time data type:</p> <pre class="lang-none prettyprint-override"><code>col_value = df.select(df.columns[0]).first()[0] start_time = time.time() col_value = datetime.strftime(col_value, &quot;%Y-%m-%d %H:%M:%S&quot;) \ if isinstance(col_va...
<python><jupyter-notebook><databricks>
2024-11-15 05:06:54
0
15,698
hh54188
79,191,134
2,457,962
Need a smooth curve from lmfit at more datapoints
<p>I am fitting a Lorenztian to the following data. If I plot the best fit, it only plots the results at particular values of x where I had data. I tried to get a smooth curve that is a better representation but something seems off.</p> <p>data:</p> <pre><code>y_means = [2.32070822e-06, 1.90175015e-06, 2.09473380e-06, ...
<python><curve-fitting><model-fitting><lmfit>
2024-11-15 04:48:36
1
1,702
Abhinav Kumar
79,191,086
5,145,090
statsmodel glm and generalized linear model formula have inversed coefficient results
<p>I am new to using statsmodel in python (and a lot of more generalized statistics in general), but I have a question regarding the difference between how sm.GLM and smf.glm calculate their results. From my understanding, as long as you ensure the added coefficient to sm.GLM, they should yield the same results. Howeve...
<python><pandas><statistics><statsmodels>
2024-11-15 04:22:35
1
465
tinfangwarble
79,191,052
2,525,479
Does TensorFlow or XLA provide a python API to read and parse the dumped MHLO mlir module?
<p>I turned on XLA when running TensorFLow, and in order to further optimize the fused kernels, I added <code>export XLA_FLAGS=&quot;--xla_dump_to=/tmp/xla_dump&quot;</code>, and got the dumped IRs, including lmhlo.xxx.mlir and other llvm IRs. Now as I'm trying to further analyze those dumped mlir's, I want to read the...
<python><tensorflow><xla>
2024-11-15 03:57:07
1
541
StayFoolish
79,190,945
15,966,103
Django & Cloudinary - Admin Panel Image Upload Returns Error "This res.cloudinary.com page can’t be found"
<p>I have the following <code>Teacher</code> model:</p> <pre><code>class Teacher(models.Model): ... # Image Field image = models.ImageField(upload_to='teacher_images/', blank=False, null=False) # Metadata ... class Meta: verbose_name = &quot;Teacher&quot; verbose_name_plural = &q...
<python><django><django-models><django-admin><cloudinary>
2024-11-15 02:22:32
0
918
jahantaila
79,190,941
4,547,189
Regex in Python - Only capture exact match
<pre><code>import re fruit_list = ['apple banana', 'apple', 'pineapple', 'banana', 'banana apple', 'kiwi'] fruit = re.compile('|'.join(fruit_list)) fruit_re = [ re.compile(r'\b('+re.escape(fruit)+r')\b') for fruit in fruit_list] fruit_re.append(re.compile( r'([#@])(\w+)')) string = &quot;this is pooapple is banana ap...
<python><regex>
2024-11-15 02:20:01
1
648
tkansara
79,190,576
15,072,863
Canvas API - upload_to_submission succeeds, but there is nu submission
<p>I'm an instructor, and I created an assignment which requires file submission. I want to upload a submission file for a student using Canvas API.</p> <pre><code>from canvasapi import Canvas canvas = Canvas('https://canvas.[my university].edu', canvas_api_key) course = canvas.get_course(args.course_id) assignment = ...
<python>
2024-11-14 22:08:10
0
340
Dmitry
79,190,430
1,686,236
Python scipy.stats create new distribution function by adjusting a single argument
<p>I'm using the <code>distfit</code> package (<a href="https://erdogant.github.io/distfit/pages/html/Functions.html#module-distfit.distfit.distfit.fit_transform" rel="nofollow noreferrer">https://erdogant.github.io/distfit/pages/html/Functions.html#module-distfit.distfit.distfit.fit_transform</a>) to find the best-fit...
<python><scipy><scipy.stats>
2024-11-14 21:07:50
1
2,631
Dr. Andrew
79,190,354
482,819
TypeVar defined within if/else
<p>While this code works:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeAlias, TypeVar T = TypeVar(&quot;T&quot;, complex, float, str) z: TypeAlias = tuple[T, ...] | list[T] </code></pre> <p>defining <code>T</code> conditionally does not.</p> <pre class="lang-py prettyprint-override"><cod...
<python><python-typing><mypy>
2024-11-14 20:37:07
1
6,143
Hernan
79,190,189
2,761,174
Extract uncaptured raw text from regex
<p>I am given a regex expression that consists of raw text and capture groups. How can I extract all raw text snippets from it?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>pattern = r&quot;Date: (\d{4})-(\d{2})-(\d{2})&quot; assert extract(pattern) == [&quot;Date: &quot;, &quot;-&quot;, &quo...
<python><regex>
2024-11-14 19:32:37
2
409
Peter
79,190,162
420,996
PySpark issue with user defined function
<p>Why does my pyspark application fail with user defined function?</p> <pre><code> multiplier = udf(lambda x: float(x) * 100.0, FloatType()) df = df.select(multiplier(df['value']).alias('value_percent')) </code></pre> <p>The error thrown is</p> <blockquote> <p>Lost task 0.0 in stage 1.0 (TID 1) (127.0.0.1 execu...
<python><apache-spark><pyspark><apache-spark-sql>
2024-11-14 19:18:01
1
3,036
Kiran Mohan
79,190,025
1,420,553
Tensorflow Not Creating Model Correctly
<p>found a problem following some samples from the book <em>&quot;AI Model and Machine Learning for Coders&quot;</em> from Laurence Moroney and Andrew Ng.</p> <p>Summarizing the findings, the following code:</p> <pre><code>import tensorflow as tf from tensorflow import keras model = tf.keras.models.Sequential([ tf...
<python><tensorflow>
2024-11-14 18:29:16
1
369
gus
79,189,939
11,001,493
How to make bars more visible while using plotly?
<p>I am trying to plot some data using plotly graph_objects. X axis has dates as categories and Y axis has depth values. I realized my graph becomes less visible when there is a relevant quantity of data. It almost seems that it become transparent.</p> <p>I already tried to change the <code>opacity</code> to 1 or <code...
<python><plotly><plotly.graph-objects>
2024-11-14 17:59:10
1
702
user026
79,189,876
1,802,693
Error with Observer while exiting async function only when using uvloop as event loop
<p>I can't figure out, why I'm getting error while shutting down when using uvloop, and not getting the same error when going without it.</p> <p>The error:</p> <pre><code>ImportError: sys.meta_path is None, Python is likely shutting down </code></pre> <p>I need to use an Observer to watch config files and reconfigure t...
<python><python-3.x><python-asyncio><uvloop>
2024-11-14 17:39:23
0
1,729
elaspog
79,189,825
1,826,066
Use brush for transform_calculate in interactive altair char
<p>I have an interactive plot in <code>altair</code>/<code>vega</code> where I can select points and I see a pie chart with the ratio of the colors of the selected points.</p> <pre class="lang-py prettyprint-override"><code>import altair as alt import numpy as np import polars as pl selection = alt.selection_interval(...
<python><vega-lite><altair>
2024-11-14 17:21:51
1
1,351
Thomas
79,189,727
3,056,882
How to disable or ignore the SSL for the Yfinance package
<p>Because I'm behind a firewall at the office, I get an SSL error when running yFinance package and I would like to disable the SSL when he pulls data from yahoo.</p> <p>Code example:</p> <pre><code># Load packages import yfinance as yf # Get data df = yf.download('SPY', start='2000-01-01', end='2024-10-01') # print p...
<python><ssl><yfinance>
2024-11-14 16:50:49
2
741
H.L.
79,189,688
3,611,164
Plotly Python: How to properly add shapes to subplots
<p>How does plotly add shapes to figures with multiple subplots and what best practices are around that?</p> <p>Let's take the following example:</p> <pre class="lang-py prettyprint-override"><code>from plotly.subplots import make_subplots fig = make_subplots(rows=2, cols=1, shared_xaxes=True) fig.add_vrect(x0=1, x1=2,...
<python><plotly>
2024-11-14 16:39:03
1
366
Fabitosh
79,189,667
192,801
How to get counts on all queries running in BigQuery
<p>I am trying to get information on the number of queries running in BigQuery, and their states.</p> <p>I've tried this:</p> <pre class="lang-sql prettyprint-override"><code>select count(job_id) as job_count, state from `MY_PROJECT`.`region-MY_REGION`.INFORMATION_SCHEMA.JOBS where creation_time between TIMESTAMP_S...
<python><sql><google-bigquery><information-schema>
2024-11-14 16:32:03
2
27,696
FrustratedWithFormsDesigner
79,189,622
558,639
Lazy creation of an asyncio event loop creates duplicates?
<p>I have a number of modules that need to run under an <code>asyncio</code> event loop, though I don't know until runtime which modules will be loaded. So at initialization, I want to make sure that there is one (and only one) event loop in effect.</p> <p>I tried the following code. I expected that the 'A' code bloc...
<python><python-asyncio>
2024-11-14 16:19:55
0
35,607
fearless_fool
79,189,502
5,477,531
Logging subclass is not retrieved correctly
<p>I am using python's <code>logging</code> library and I need to create a custom logger that logs two attributes of my process: <code>instance_name</code> and <code>instance_id</code>. I have come to this solution that works successfully, though I'm not sure if it overlooks something/does something unnecessary:</p> <p...
<python><logging>
2024-11-14 15:48:51
1
627
mrbolichi
79,189,438
1,936,046
How do I add a Python script to the enterprise schedule ActiveBatch?
<p>According to the ActiveBatch website, they do support Python scripts:</p> <p><a href="https://www.advsyscon.com/en-us/activebatch/script-management" rel="nofollow noreferrer">https://www.advsyscon.com/en-us/activebatch/script-management</a></p> <p>But I do not see an option for Python from the script editor in Activ...
<python><activebatch>
2024-11-14 15:30:00
0
764
Duanne
79,189,436
10,004,903
How to display a GIF in Dearpygui
<p>Since importing and displaying GIF is not natively supported in dearpygui, how would one go about to render and animate a GIF in dpg using the existing tools?</p>
<python><animated-gif><dearpygui>
2024-11-14 15:29:43
1
548
grybouilli
79,189,423
16,389,095
How to display a pdf page into a Flet container
<p>I'm trying to develop a simple app for displaying each page of a Pdf file. I start by adding a container and a button. The Pdf file's full path(absolute path + file name) is given to the variable <code>fullname</code>. The file is converted into a list of PIL images using the <a href="https://pypi.org/project/pdf2im...
<python><flutter><pdf><flet>
2024-11-14 15:23:31
1
421
eljamba
79,189,217
2,127,543
Retrieve cell of a DataFrame Enum column as an Enum
<p>I have a DataFrame in which several columns are defined as Enums. When I retrieve a cell in an Enum column, the value is returned as a string. How do I retrieve the value as an Enum? Shown below is a small repro:</p> <pre><code>import polars as pl flags: pl.Enum = pl.Enum([&quot;foo&quot;, &quot;bar&quot;, &quot;b...
<python><python-polars>
2024-11-14 14:38:37
1
439
scorpio
79,189,097
11,022,199
Removing a combination from stacked parametrization in pytest
<p>For a lot of tests we use a stacked parametrizing for testing our functions like this:</p> <pre><code>@pytest.mark.parametrize(&quot;x&quot;, x.values()) #possible values 1,2,3,4 @pytest.mark.parametrize(&quot;y&quot;, y.values()) #possible values True, False def test_get_somehting(x): get_something(x, y) </code...
<python><pytest>
2024-11-14 14:07:40
1
794
borisvanax
79,189,080
3,584,765
install specific version of pytorch
<p>I am trying to install a specific version of <code>torch</code> (along with <code>torchvision</code> and <code>torchaudio</code>) for a project.</p> <p>The <a href="https://github.com/Traffic-X/ViT-CoMer/tree/main/segmentation" rel="nofollow noreferrer">instructions</a> from the project mentioned the command:</p> <p...
<python><pytorch><pip>
2024-11-14 14:00:49
0
5,743
Eypros
79,189,028
5,696,601
Matplotlib Stackplot Gradient
<p>Is it possible to fill the &quot;Odds&quot; area with a gradient from left (green) to right (transparent)? I would like to do this in a plot to indicate uncertainty.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y1 = [1, 1, 2, 3, 5] y2 = [0, 4, 2, 6, 8] y3 = [1, 3, 5, 7, 9] ...
<python><matplotlib>
2024-11-14 13:48:05
1
1,023
Stücke
79,188,746
17,487,457
Presenting complex table data in chart for a single slide
<p>Tables allow to summarise complex information. I have a table similar following one (this is produce for this question) in my latex document, like so:</p> <pre class="lang-latex prettyprint-override"><code>\documentclass{article} \usepackage{graphicx} % Required for inserting images \usepackage{tabularx} \usepackage...
<python><pandas><matplotlib><latex><visualization>
2024-11-14 12:30:26
2
305
Amina Umar