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,398,642
7,175,213
Maximum number of elements on list whose value sum up to at most K in O(log n)
<p>I have this exercise to do:</p> <p>Let M be a positive integer, and V = ⟨v1, . . . , vn⟩ an ordered vector <strong>where the value of item vi is 5Γ—i.</strong></p> <p>Present an O(log(n)) algorithm that returns the maximum number of items from V that can be selected given that the sum of the selected items is less th...
<python><algorithm>
2024-04-28 15:12:06
4
1,148
Catarina Nogueira
78,398,590
3,067,485
How to expose serial interface to the docker host?
<p>I have a python dockerized service that creates a TTY interface using PSL <code>pty</code>.</p> <pre><code>import os, pty server, device = pty.openpty() tty_name = os.ttyname(device) </code></pre> <p>I can see this interface created within the container <code>/dev/pts/0</code>:</p> <pre><code>ls -l /dev/pts total 0...
<python><docker><tty><volumes>
2024-04-28 14:56:50
0
11,564
jlandercy
78,398,573
243,031
Not able to access resource from another stack in AWS CDK
<p>I am using AWS CDK with python, and my directory structure is as below.</p> <pre><code>β”œβ”€β”€ README.md β”œβ”€β”€ app.py β”œβ”€β”€ bootstrap_scripts β”‚Β Β  └── install_httpd.sh β”œβ”€β”€ cdk.context.json β”œβ”€β”€ cdk.json └── resource_stacks Β Β  β”œβ”€β”€ __init__.py Β Β  β”œβ”€β”€ custom_vpc.py Β Β  └── web_server_stack.py </code></pre> <p>The files as as b...
<python><amazon-web-services><aws-cdk>
2024-04-28 14:52:31
1
21,411
NPatel
78,398,311
10,710,625
AttributeError: module 'collections' has no attribute 'Sized' when trying to load a pickled model
<p>I am trying to load a pretrained model but I'm hitting an error when I do. AttributeError: module 'collections' has no attribute 'Sized'</p> <pre><code>from fastai import * from fastai.vision import * from matplotlib.pyplot import imshow import numpy as np import matplotlib.pyplot as plt from skimage.transform impor...
<python><pytorch><fast-ai>
2024-04-28 13:24:35
1
739
the phoenix
78,398,307
547,231
Convert a sequence of exr files to mp4 using moviepy
<p>I have a sequence of <code>exr</code> files which I want to convert into a video using <code>moviepy</code>. When Since the colors in the <code>exr</code>s need be converted (otherwise the video appears almost black) I need to specify a color transfer characteristic. When I run <code>ffmpeg</code> directly using</p>...
<python><ffmpeg><moviepy>
2024-04-28 13:22:28
0
18,343
0xbadf00d
78,398,227
2,971,574
How to show all columns on a table with lots of columns?
<p>I've got an Ibis table (duckdb backend) t and I'm in interactive mode (<code>ibis.options.interactive=True</code>). When I try to see the first couple of rows (<code>t.head()</code>) ibis only shows the first three columns: <a href="https://i.sstatic.net/D11hEe4E.png" rel="nofollow noreferrer"><img src="https://i.ss...
<python><ibis>
2024-04-28 12:55:12
1
555
the_economist
78,397,889
17,915,481
Can not create shortcut of file using google drive api
<p>Here is sample code that i am trying to run.</p> <pre class="lang-py prettyprint-override"><code>import requests api_endpoint = 'https://www.googleapis.com/upload/drive/v3/files?supportsAllDrives=true' headers = { 'Authorization': f'Bearer {access_token}' } json={&quot;name&quot;: &quot;a.jpg&quot;, &quot;mim...
<python><google-drive-api>
2024-04-28 10:45:25
1
512
jak bin
78,397,757
3,142,695
Iterate over folder name list to copy folder if existing
<p>This is how I copy the folder <code>src</code> from source to workspace destination - replacing the content if already existing:</p> <pre><code>def copy_and_replace(directory): target = os.path.join('workspace', directory, 'src') source = os.path.join('..', 'source', directory, 'src') try: if os....
<python>
2024-04-28 09:54:14
2
17,484
user3142695
78,397,575
15,018,688
Proper way to handle data from a generator using PySpark and writing it to parquet?
<p>I have a data generator that returns an iterable. It fetches data from a specified date range. The total data it will fetch is close to a billion objects. My goal is to fetch all of this data, write it to a folder (local filesystem) and (already set up and working) use pyspark readstream to read these files and writ...
<python><apache-spark><pyspark>
2024-04-28 08:46:28
1
556
Furkan Γ–ztΓΌrk
78,397,447
1,497,418
Sending PDF to gemini-1.5-pro-latest fail with 500 error
<p>Below is a snippet that sends a prompt and a pdf file to gemini.</p> <pre><code>def runGemini(prompt, model, document=None): model = genai.GenerativeModel(model) content = prompt if document: content = [ document, &quot;What is this document?&quot;, ] respons...
<python><google-api-python-client><google-gemini>
2024-04-28 07:50:17
2
2,578
Walucas
78,397,357
16,277,807
How to use mediaquery or responsiveness in python reflex?
<p>The <a href="https://reflex.dev" rel="nofollow noreferrer">official documentation</a> isn’t talking anything at all about CSS mediaquery. particularly when I would like to place 2 divs and 1 image in single row (rx.hstack) in larger screen and want to place as single column (rx.vstack) in smaller screen, how can I c...
<python><python-reflex>
2024-04-28 07:11:26
0
514
Mahmudur Rahman Shovon
78,397,222
13,942,929
Cython: How can I import multiple class object from a single file?
<p>So this is how I currently structure my files.</p> <pre class="lang-none prettyprint-override"><code>CPP Folder Cython Folder β”œβ”€β”€ setup.py └── Geometry β”œβ”€β”€ Circle β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ Circle.pyx β”‚ β”œβ”€β”€ Circle.pyi β”‚ └── Circle.pxd └── Point β”œβ”€β”€ __init__.py β”œβ”€β”€ Point.p...
<python><c++><cython><cythonize>
2024-04-28 06:00:32
1
3,779
Punreach Rany
78,396,795
420,867
Python `audioop.ulaw2lin` with width 2 via PyVoip creates distorted sped up audio
<p>I'm trying to convert u-law audio into 16 bit 8khz raw audio in python using <code>audioop.ulaw2lin(ulaw_audio_bytes, 2)</code>.</p> <p>The resulting bytes object has the right size, however if I write it to a wave file as 16 bit 8khz raw audio, the result is double speed with medium to low frequency noise and quite...
<python><audio><mu-law>
2024-04-28 01:02:54
1
15,330
drevicko
78,396,733
2,444,008
ModuleNotFoundError: No module named 'django.db.backends.postgresql' on Ubuntu 24.04
<p>Yesterday I switched to Ubuntu 24.04 LTS from windows and having an issue with my django project and tried every suggestion on the web but no luck. I'm getting below issue:</p> <pre><code>django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend or couldn't be i...
<python><django><postgresql><ubuntu-24.04>
2024-04-28 00:18:01
2
1,093
ftdeveloper
78,396,693
16,852,890
Pyspark - How to handle error in for list
<p>I've written something to read the location of some lake files dynamically provided by a list called <code>partition_paths</code>:</p> <pre><code>dfs = [spark.read.parquet(f'{l}') for l in partition_paths] </code></pre> <p>I will then combine all these dfs into one in the next line:</p> <pre><code>df = reduce(DataFr...
<python><pyspark>
2024-04-27 23:52:14
1
316
tommyhmt
78,396,677
827,371
Most efficient way of running correlation of a small sequence against another larger sequence to try to find matching index
<p>In Python, I want to take a smaller sequence of numbers, and find the area along a very large sequence of numbers that has the highest correlation to this smaller sequence of numbers.</p> <p>Is there an efficient way to do this besides brute force ie. taking a subset of the larger sequence of the same length as the ...
<python><algorithm><numpy><correlation>
2024-04-27 23:46:10
1
1,860
steve8918
78,396,664
2,593,878
Python - using parent's method from child's super() call
<p>I imagine there are lots of similar questions, but I'm not sure how to search for this situation. Suppose I have the following code structure:</p> <pre><code>class Parent(): def method(self): self.helper() print('Parent method') def helper(self): print('Parent helper') class Child(P...
<python><inheritance><parent-child><method-resolution-order>
2024-04-27 23:32:18
1
7,392
dkv
78,396,642
10,262,805
module 'openai' has no attribute 'OpenAI'
<p>I installed the latest <code>openai</code> version:</p> <pre><code>pip install openai==1.23.6 </code></pre> <p>then</p> <pre><code>from openai import OpenAI </code></pre> <p>I get error</p> <blockquote> <p>cannot import name 'OpenAI' from 'openai'</p> </blockquote> <p>From <a href="https://pypi.org/project/openai/" ...
<python><openai-api>
2024-04-27 23:18:48
3
50,924
Yilmaz
78,396,549
6,727,976
How to run LangChains getting-started examples and getting output?
<p>I'm going to learn LangChain and stumble upon their Getting Started section. Because it doesn't work and I'm curious if I am the only person where LangChain examples don't work.</p> <p>This is their tutorial I am talking about. <a href="https://python.langchain.com/docs/get_started/quickstart/" rel="nofollow norefer...
<python><langchain><py-langchain>
2024-04-27 22:23:10
2
1,153
MrsBookik
78,396,467
13,952,135
OpenGL pygame cannot get buffers working reliably with vertextPointer and colorPointer
<p>So I'm pretty sure I'm just doing something wrong here with how I'm calling the OpenGL. I've provided an example below where about 30% of the time it shows the semi transparent vertex colored squares on top of a red background. The other 70% of the time it only shows the red background. I tried commenting out variou...
<python><opengl><pygame><pyopengl><vertex-buffer>
2024-04-27 21:33:41
1
615
Peter
78,396,068
13,393,940
How to plot SHAP summary plots for all classes in multiclass classification
<p>I am using XGBoost with SHAP to analyze feature importance in a multiclass classification problem and need help plotting the SHAP summary plots for all classes at once. Currently, I can only generate plots one class at a time.</p> <pre class="lang-py prettyprint-override"><code>SHAP version: 0.45.0 Python version: 3...
<python><machine-learning><classification><shap><xgbclassifier>
2024-04-27 19:02:16
1
873
cconsta1
78,396,014
7,846,884
Row bind multiple data frames in dictionary using dict.keys() as column 1 of output pd.df
<p>i found a way to concatenate my pandas data frames in a dictionary. Que; how can i use the dictionary keys as first column in the final dataframe? i tried but thar didn't work</p> <pre><code>pd.concat(test_list.values(), ignore_index=False, keys= test_list.keys()) </code></pre> <p>data</p> <pre><code>test_list = {'E...
<python><pandas><dictionary>
2024-04-27 18:40:39
1
473
sahuno
78,395,916
1,073,493
Regex with optional final capture group
<p>How do I construct a regex pattern that matches the following examples with three capture groups like so:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>example</th> <th>grp1</th> <th>grp2</th> <th>grp3</th> </tr> </thead> <tbody> <tr> <td>foo:bar-alpha</td> <td>foo</td> <td>bar</td> <td...
<python><regex>
2024-04-27 18:04:33
1
477
Lobert
78,395,683
596,922
Regular expresssion to extract the headers between two lines
<p>I'm trying to extract a headers between the two dotted line</p> <pre class="lang-none prettyprint-override"><code> ------------------------------------------------------------------------------------------ PortNo Descr Status Speed Mode Pause FlowCtrl ...
<python><regex><regex-group>
2024-04-27 16:34:31
1
1,865
Vijay
78,395,272
9,582,542
Issue with Vscode and interactive window
<p>Currently running VScode 1.88.0 which is very new.</p> <p>Here is the Scenario</p> <p>Session #1: I have Vscode open on a folder C:\user\Alastname\Datascience when I open code in this folder and make a selection hit Shift+Enter I get an interactive window and my code get processed successfully by the python interpre...
<python><visual-studio-code>
2024-04-27 14:11:18
1
690
Leo Torres
78,395,038
8,020,900
Pandas: bin column by frequency with unique bin intervals
<p>Let's say we have this DataFrame:</p> <p><code>df = pd.DataFrame(columns=[&quot;value&quot;], data=[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 5, 7, 10])</code></p> <p>I want to split up the values into 5 bins based on their frequency, with the condition that <strong>no value is in more than one bin.</strong> You mig...
<python><pandas><dataframe><quantile><qcut>
2024-04-27 12:50:54
1
3,539
Free Palestine
78,394,806
1,082,349
Only take color cycle from a style
<p>I hate everything about the style ggplot, but I do like the colors.</p> <pre><code>import matplotlib.pyplot as plt plt.style.use('ggplot') </code></pre> <p>This sets the colors from that style, and everything as well. How can I import only the color cycle from that style (for all lines, dots, ...), but import nothin...
<python><matplotlib>
2024-04-27 11:26:35
1
16,698
FooBar
78,394,714
9,877,065
How to force Designer to keep QScrollAreas in QGridLayout of same size during resize in PyQt5?
<p>Code main.py:</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt5.QtWidgets import QApplication, QScrollArea, QWidget, QGridLayout, QVBoxLayout from PyQt5 import QtGui , uic from PyQt5.QtGui import QDrag class MainWidget(QWidget): def __init__(self, *args, **kwargs): ...
<python><pyqt><pyqt5><qt-designer>
2024-04-27 10:50:00
0
3,346
pippo1980
78,394,687
3,103,957
Even loop creation in Asyncio of Python
<p>In asyncio library of Python, which method(s) create the event loop? Is it asyncio.run() / asyncio.get_event_loop() ? Also which method(s) start running the event loop? I tried searching; but it seems there are not very clear answers.</p>
<python><python-asyncio><event-loop>
2024-04-27 10:36:32
1
878
user3103957
78,394,663
3,156,085
Why does attempting to do a `Callable` alias (`Alias=Callable`) cause a "Bad number of arguments" when using it as a generic?
<p>I've encountered the following (error in 2nd snippet) while experimenting with type hinting:</p> <h3>First, without any alias, everything passes the type checking:</h3> <pre><code>from typing import Callable T = TypeVar(&quot;T&quot;) # Invariant by default P = ParamSpec(&quot;P&quot;) def some_decorator(f: Calla...
<python><python-typing><type-alias>
2024-04-27 10:28:15
1
15,848
vmonteco
78,394,542
4,060,904
SQLAlchemy - include rows where func.count() called on many-many relationship results in 0
<p>I am querying a table <code>Team</code> to get a list of all the teams. This query object is fed to a pagination function that makes use of sqlalchemy's <code>paginate()</code>.</p> <p>The function takes inputs for <code>order</code> and <code>order_by</code> which determine the column and order of the resulting que...
<python><sqlalchemy><flask-sqlalchemy>
2024-04-27 09:43:09
1
492
Locke Donohoe
78,394,306
14,159,253
Failed to execute cell. Could not send execute message to runtime: Error: await connected: disconnected
<p>While executing a cell in Google Colab, my aim was to display a selection of random rows from a DataFrame containing columns labeled <code>Id</code>, <code>condensed_summary</code>, and <code>generated_image</code>. Initially, I attempted to exhibit the entire dataset comprising 200 rows, only to encounter display i...
<python><jupyter-notebook><google-colaboratory><ipython>
2024-04-27 08:17:23
1
1,725
Behdad Abdollahi Moghadam
78,394,289
21,395,742
Running ollama on kaggle
<p>I downloaded ollama on a kaggle notebook (linux). I want to interact with it using a python script. On following the instructions on the github repo and running: <code>ollama run llama3</code> I got the output: <code>Error: could not connect to ollama app, is it running?</code>.</p> <p>It appears that I need to run ...
<python><llama><ollama>
2024-04-27 08:11:53
1
845
hehe
78,393,875
4,268,976
ValueError: time data does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
<p>While running the following code I'm getting following error</p> <p><code>ValueError: time data '2024-04-27T04:50:23.3480072Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'</code></p> <p>Here is my python code</p> <pre><code>from datetime import datetime time_string = '2024-04-27T04:50:23.3480072Z' format_string = ...
<python><datetime>
2024-04-27 05:11:30
3
4,122
NIKHIL RANE
78,393,822
2,256,085
animate 1D data with LineConnection
<p>The example code below creates 2 plots that attempt to convey what the desired animation is seeking to do. Note that the plot on the right is similar to the plot on the left, but represents the position of a wave after the passage of time <code>t</code>. The goal is to animate the downward movement of waves, with th...
<python><matplotlib><matplotlib-animation>
2024-04-27 04:42:37
1
469
user2256085
78,393,728
10,138,470
Merging Pandas dataframe and SQL table values
<p>I have dataframe and want to update it or create a new dataframe based on some input from an SQL table. The dataframe A has two columns (ID and Added_Date).</p> <p>On the other hand, the SQL table has a few more columns including ID, Transaction_Date, Year, Month and Day. My idea is to merge contents of d...
<python><pandas><dataframe><sqlite>
2024-04-27 03:33:08
1
445
Hummer
78,393,687
8,124,392
Where to set the scheduler and sampler?
<p>If I'm trying to build an inferencer using Python and the huggingface library, where do I set the scheduler and sampler? What function do I call? For context, this is what my code looks like:</p> <pre><code>import torch, PIL, random from typing import List, Optional, Union from diffusers import StableDiffusionInpai...
<python><deep-learning><huggingface><stable-diffusion>
2024-04-27 03:03:14
0
3,203
mchd
78,393,675
8,849,071
How to make a custom type inheriting from UUID work as a pydantic model
<p>in our codebase we are using a custom UUID class. This is a simplified version of it:</p> <pre class="lang-py prettyprint-override"><code>class ID(uuid.UUID): def __init__(self, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) </code></pre> <p>We cannot inherit from <code>BaseModel</code> an...
<python><uuid><pydantic>
2024-04-27 02:56:23
1
2,163
Antonio Gamiz Delgado
78,393,575
361,530
Why does iPython choose an earlier version of Python?
<p>I'm trying to upgrade from Python 3.11 to 3.12 and running into some problems, illustrated by iPython's unwillingness to go with me. I'm doing all this on an Arm Macbook Air with Python installed by Homebrew, in case that matters. Here's a copy of my Terminal activity, followed by my understanding of what's happen...
<python><ipython><version>
2024-04-27 01:51:55
0
389
RadlyEel
78,393,570
1,678,160
Inverted hierarchy of nested dicts/lists
<p>Considering the following dictionary:</p> <pre><code>{ &quot;a&quot;: { &quot;b1&quot;: { &quot;c&quot;: { &quot;value&quot;: &quot;c_value&quot;, &quot;children&quot;: { &quot;d&quot;: &quot;d_value&quot; } } }, &quot;b2&quot;: [ &quot;b2_1&quot;, ...
<python><python-3.x>
2024-04-27 01:45:24
1
522
kairos
78,393,551
1,601,580
How does one use vllm with pytorch 2.2.2 and python 3.11?
<h1>Title: How does one use vllm with pytorch 2.2.2 and python 3.11?</h1> <p>I'm trying to use the vllm library with pytorch 2.2.2 and python 3.11. Based on the GitHub issues, it seems vllm 0.4.1 supports python 3.11.</p> <p>However, I'm running into issues with incompatible pytorch versions when installing vllm. The g...
<python><pytorch><nlp><huggingface-transformers><vllm>
2024-04-27 01:34:19
1
6,126
Charlie Parker
78,393,417
19,626,271
Optimizing a function with linear constraints containing a singular matrix, in Python
<p>I'm working with traffic data to try the reconstruct the origin-destination matrix of a region, based on the article <a href="https://web.archive.org/web/20240426215022/https://sci-hub.se/10.1287/trsc.17.2.198" rel="nofollow noreferrer">Bell1983</a>.</p> <p>Basically, for each pair of locations, we need to get how m...
<python><optimization><scipy><mathematical-optimization><scipy-optimize>
2024-04-27 00:16:06
0
395
me9hanics
78,393,346
5,431,734
comparing two lists of tuples, np.isin
<p>I have two lists of tuples and I want to find which elements from the first are in the second one. For example:</p> <pre><code>elements = [ (903, 468), (913, 468), (926, 468), (833, 470), (903, 470), (917, 470), (833, 833), (903, 833), (913, 833), (917, 833), ] ...
<python><numpy>
2024-04-26 23:36:19
3
3,725
Aenaon
78,393,278
2,487,330
Filter by unique counts within groups
<p>I'm trying to filter by the count of unique items within groups.</p> <p>For example, suppose I have the following data set:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ 'data': [1,1,1,1,1,2,2], 'group': [1,1,1,2,2,1,1], 'id': [1,2,3,4,5,1,2], 'x': [1,1,...
<python><dataframe><python-polars>
2024-04-26 23:00:33
1
645
Brian
78,393,211
10,902,944
Default n_workers when creating a Dask cluster?
<p>Simple question. If I create a Dask cluster using the following code:</p> <pre><code>from dask.distributed import Client client = Client() </code></pre> <p>How many workers will it create? I ran this code on one machine, and it created 4 workers. I ran this same code on a server, and it created 8 workers. Does it j...
<python><dask><cpu-usage><dask-distributed>
2024-04-26 22:32:26
1
397
Adriano Matos
78,393,150
1,275,942
Python: Alias a module (in other libraries)
<p>Suppose I have two python installs. Let's say my global python3.7, and a python3.10 venv.</p> <p>Between 3.7 and 3.10, a module changed its name from <code>foo</code> to <code>foobar</code>. So in 3.7, we would do <code>import foo</code>, and in python 3.10, we'd do <code>import foobar</code>.</p> <p>Suppose my code...
<python><python-import><python-packaging>
2024-04-26 22:06:42
0
899
Kaia
78,393,072
480,118
pandas: dataframe with multilevel columns shift up the date index to to flatten out
<p>I have data that arrives to me that looks like this:</p> <pre><code>import pandas as pd, numpy as np data = [['', 'CCC', 'CCC', 'AAA', 'BBB' ], ['date', 'field1', 'file2', 'field1','field1'], ['01/01/2024', 100, 102, 103, 104 ], ['01/02/2024', 20...
<python><pandas>
2024-04-26 21:38:24
1
6,184
mike01010
78,393,066
9,877,065
Can't have Designer to resize Qwidget inside QGridLayout in pyqt5?
<p>I can run this code:</p> <pre><code>import sys from PyQt5.QtWidgets import QApplication, QScrollArea, QWidget, QGridLayout, QVBoxLayout, QLabel from PyQt5 import QtGui, QtCore from PyQt5.QtGui import QDrag class MainWidget(QWidget): def __init__(self, *args, **kwargs): super().__init...
<python><qt><pyqt><pyqt5><qt-designer>
2024-04-26 21:37:17
1
3,346
pippo1980
78,393,035
3,103,957
Unexpected behaviour in Python event loop
<p>I have the following piece of Async code in Python.</p> <pre><code>import asyncio async def get_some_values_from_io(): print(&quot;Getsome value Executing...&quot;) await asyncio.sleep(3) return [100,200] vals = [] async def fetcher(): while True: print(&quot;Fetcher Executing...&quot;) ...
<python><python-asyncio><event-loop>
2024-04-26 21:26:05
3
878
user3103957
78,392,900
4,880,003
How can I have multiple heatmaps share axes in holoviews?
<p>I'm creating two heatmaps which have different ranges of data. I'd like to plot them together with the same extents, with empty cells added as needed to make them the same size. Here's code for two sample heatmaps:</p> <pre class="lang-py prettyprint-override"><code>import random import holoviews as hv hv.extension(...
<python><visualization><holoviews>
2024-04-26 20:44:43
1
10,466
Nathan
78,392,534
16,770,846
Why doesn’t the ASGI specification allow handshake rejection with custom reason?
<p>A client initially opens a connection to an ASGI compliant server. The server forwards a <a href="https://asgi.readthedocs.io/en/latest/specs/www.html#connect-receive-event" rel="nofollow noreferrer"><code>Connect event</code> <sup>[asgi-spec]</sup></a> to the application. This event must be responded to with either...
<python><websocket><asgi>
2024-04-26 18:57:28
2
4,252
Chukwujiobi Canon
78,392,238
10,219,156
python dict is giving key error even if initialized with some values
<pre><code>data={} vega={} for coin in ['BTC']: vega[coin] = {} data[coin] = {} data[coin]['columns']=['27-Apr-24', '28-Apr-24', '29-Apr-24', '03-May-24', '10-May-24', '17-May-24', '31-May-24'] for expiry in data[coin]['columns']: vega[coin][expiry] = data[coin].get('Vega', {}).get('Total', {})....
<python><pandas><list><dictionary>
2024-04-26 17:53:21
2
326
Madan Raj
78,392,032
17,524,128
Cannot able to redirect even if user password and user name are correct
<p>Here is my <code>app.py</code> file and when I am running with flask but when i am running this with my flask and try to login then it is showing this error <a href="https://i.sstatic.net/2f86JXrM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2f86JXrM.png" alt="enter image description here" /></a></...
<python><python-3.x><flask>
2024-04-26 17:08:53
1
301
vatsal mangukiya
78,391,980
132,785
What is this Python list containing all tokens from my code?
<p>If I run this code in Python 3.10:</p> <pre><code>import gc def main(): a = 23764723 ref = gc.get_referrers(a)[0] print(ref) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>I get the following output:</p> <pre><code>['gc', 'main', 'a', 23764723, 'ref', 'gc', 'get_referrers', 'a', 0,...
<python><list>
2024-04-26 16:55:07
4
1,988
Neil
78,391,689
159,361
Cascaded optional dependencies in Python
<p>A python library has two packages &quot;package1&quot; and &quot;package2&quot;. Both packages support optional extras &quot;extras&quot;. Package1 has a setup.cfg as follows:</p> <pre><code>[options] install_requires = package2 [options.extras_require] extras = package2[extras] </code></pre> <p>and package2 has s...
<python><setuptools><python-packaging>
2024-04-26 15:59:06
1
7,755
Ricibob
78,391,600
1,045,755
multiprocessing doesn't clear cache
<p>I am trying to use <code>multiprocessing</code> to optimize some calculations. The code to start it looks something like this:</p> <pre><code>if __name__ == &quot;__main__&quot;: params = list(itertools.product(cutoff_hours, cutoff_minutes, chunk_sizes, buffer_sizes, products, optimize_ons)) params_dilled =...
<python><python-multiprocessing>
2024-04-26 15:42:18
0
2,615
Denver Dang
78,391,553
11,431,477
Basic save_pretrained / from_pretrained not retrieving the same model that was saved - Transformers
<p>I created my model with:</p> <pre><code>#Load of the model model_checkpoint = 'microsoft/deberta-v3-large' # model_checkpoint = 'roberta-base' # you can alternatively use roberta-base but this model is bigger thus training will take longer # Define label maps specific to your task id2label = {0: &quot;Human&quot;, ...
<python><huggingface-transformers>
2024-04-26 15:34:56
1
535
miguelik
78,391,485
802,678
Use `pip freeze > requirements.txt` to create a file with environment markers?
<p>There are <a href="https://peps.python.org/pep-0508/#environment-markers" rel="nofollow noreferrer">Environment Markers</a> or <a href="https://pip.pypa.io/en/stable/reference/requirement-specifiers/#requirement-specifiers" rel="nofollow noreferrer">Requirement Specifiers</a> we can use in <code>requirements.txt</co...
<python><pip><requirements.txt>
2024-04-26 15:24:35
1
582
Betty
78,391,438
6,674,599
Python Classes: NameError: name 'foo' is not defined
<p>Why does accessing the class attribute <code>foo</code> fail when building a tuple with non-zero length only?</p> <pre class="lang-py prettyprint-override"><code>class Foo: foo = 42 bar_ok1 = (foo for _ in range(10)) bar_ok2 = tuple(foo for _ in []) bar_fail1 = tuple(foo for _ in range(10))...
<python><class><static><iterator><nameerror>
2024-04-26 15:18:13
2
2,035
Semnodime
78,391,417
2,080,848
Transform value in same format as output from read(AES.block_size)
<p>I am working on some encrypt task using python. I am using Crypto.Cipher and Crypto from <code>python</code>. The code I used is next:</p> <pre><code>from Crypto.Cipher import AES from Crypto import Random iv = Random.new().read(AES.block_size) iv </code></pre> <p>The output of <code>iv</code> is next:</p> <pre><co...
<python><encryption><cryptography><aes>
2024-04-26 15:15:37
1
39,643
Duck
78,391,292
7,564,952
pyspark code on databricks never completes execution and hang in between
<p>I have two data frames: df_selected and df_filtered_mins_60</p> <p><code>df_filtered_mins_60.columns()</code><br/></p> <blockquote> <p>Output:[&quot;CSku&quot;, &quot;start_timestamp&quot;, &quot;end_timestamp&quot;]<br/></p> </blockquote> <p><code>df_selected.columns() </code><br/></p> <blockquote> <p>Output:[&quot...
<python><apache-spark><join><pyspark><databricks>
2024-04-26 14:53:10
1
455
irum zahra
78,391,260
2,817,520
Conditionally defining a class variable
<p>Is the following code considered Pythonic?</p> <pre><code>class A(): if True: x = 10 print(A.x) # prints 10 </code></pre> <p>This came to my mind when working on a plugin based application.</p>
<python>
2024-04-26 14:46:14
1
860
Dante
78,391,203
732,570
How to use LifespanManager to test a reverse proxy in FastAPI (async testing)
<p>According to <a href="https://fastapi.tiangolo.com/advanced/async-tests/" rel="nofollow noreferrer">FastAPI documentation</a> I may need to use a LifespanManager. Can someone show me an example of how to use the LifespanManager in an async test? Like, with this lifespan:</p> <pre class="lang-py prettyprint-override"...
<python><pytest><fastapi>
2024-04-26 14:35:53
1
4,737
roberto tomΓ‘s
78,391,190
8,507,034
Plotly ScatterGeo Text color
<p>I'm using plotly to make a choropleth map.</p> <p>I would like to add text labels to the map using fig.add_scattergeo, but it's borrowing the colormapping from the plot and it doesn't look good. The text doesn't contrast with the background color and it is difficult to read.</p> <p>I would like to know if and how I ...
<python><plotly><choropleth>
2024-04-26 14:34:12
1
315
Jred
78,391,084
19,392,385
Generate invite from other servers (discord.py)
<p>I'm doing a little experiment trying to see if I can generate invite from server my bot has been added to. I encounter a problem in the definition of something called <em>InviteTarget</em> that I am not even using (?)</p> <p>The code is the following:</p> <pre class="lang-py prettyprint-override"><code> @commands...
<python><discord><discord.py>
2024-04-26 14:16:08
0
359
Chris Ze Third
78,390,934
736,662
Python and parameter in Locust request
<p>Given a SequantialTask in a locust script I want to replace 73808 with the list all_pp_ids. How can I construct the data= parameter of my post request to instead take in the list as parameter? Now it is hardcoded to 73808 but I want alle values in all_pp_ids instead.</p> <pre><code> @task(2) def generate_bids...
<python><locust>
2024-04-26 13:52:12
1
1,003
Magnus Jensen
78,390,766
1,928,054
Access files within python package with python 3.12 and importlib
<p>I'm trying to figure out what the best practice is when it comes to reading data from within a package.</p> <p>I understood that in python 3.12 I should use importlib.resources, see e.g. <a href="https://stackoverflow.com/questions/6028000/how-to-read-a-static-file-from-inside-a-python-package">How to read a (static...
<python><python-importlib>
2024-04-26 13:25:14
0
503
BdB
78,390,753
5,224,881
How to correctly schedule and wait for result in asyncio code from synchronous context in Jupyter notebook?
<p>I have a small utility for calling synchronous code using <code>asyncio</code> in parallel.</p> <pre class="lang-py prettyprint-override"><code>import asyncio from concurrent.futures import ThreadPoolExecutor from asyncio import AbstractEventLoop, BaseEventLoop async def call_many_async(fun, many_kwargs): retur...
<python><jupyter-notebook><python-asyncio>
2024-04-26 13:22:50
1
1,814
MatΔ›j RačinskΓ½
78,390,578
2,817,520
How to add a relationship to an existing mapping class from another module
<p>I have two modules. The first one is:</p> <pre><code># module_1.py from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column class Base(DeclarativeBase): pass class User(Base): id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] </code></pre> <p>and the second one is:</p> <pre><...
<python><python-3.x><sqlalchemy>
2024-04-26 12:49:53
1
860
Dante
78,390,366
4,013,571
Construct a new tuple type from existing tuples
<p>I have a <code>list</code> structure as a flattened input to a API</p> <pre class="lang-json prettyprint-override"><code>(point_x, point_y, thing_a, thing_b, thing_c) </code></pre> <p><em>This real structure is a very long list of a many flattened objects. This example is a much simplified case.</em></p> <p>I would ...
<python><python-typing><mypy>
2024-04-26 12:13:19
1
11,353
Alexander McFarlane
78,389,639
3,400,076
How to create a download files button in ckan?
<p>Hi I am currently using Ckan2.10 and would like to create a Download button in the ckan webpage. After clicked on the Download button, it will call the plugin.py to generate an excel file, but how can I pass the excel file back to the html page so that user is able to download the excel file?</p> <p>I am trying to u...
<python><ckan>
2024-04-26 09:55:51
0
519
xxestter
78,389,600
9,542,989
Host and Port for snowflake-connector-python
<p>I am attempting to establish a connection to Snowflake using the <code>snowflake-connector-python</code> package. I am able to connect to it using the following:</p> <pre><code>connection = connector.connect( user='&lt;my-username&gt;', password='&lt;my-password&gt;', account='&lt;my-account&gt;' ) </cod...
<python><snowflake-cloud-data-platform>
2024-04-26 09:49:11
1
2,115
Minura Punchihewa
78,389,427
17,123,424
How to generate Multiple Responses for single prompt with Google Gemini API?
<h2>Context</h2> <p>I am using google gemini-api. <br /> Using their <a href="https://ai.google.dev/gemini-api/docs/get-started/python" rel="nofollow noreferrer">Python SDK</a></p> <h2>Goal</h2> <p>I am trying to generate multiple possible responses for a single prompt according to the <a href="https://ai.google.dev/ge...
<python><large-language-model><google-gemini>
2024-04-26 09:16:21
1
1,549
Curious Learner
78,389,262
5,790,653
Microsoft OneDrive download files
<p>I'm googling different ways regarding how to download files from my personal OneDrive accounts.</p> <p>I have these problems:</p> <p>The following code requires <code>code</code> parameter, I googled a lot but didn't find anything what's the <code>code</code> and how to find or get it:</p> <pre><code>import requests...
<python><onedrive>
2024-04-26 08:46:10
0
4,175
Saeed
78,389,254
9,059,634
Ingesting HLS into Mediapackage
<p>I have the following setup for a streaming app. EMX -&gt; EML -&gt; S3 -&gt; LAMBDA -&gt; EMP. When I try to make a <strong>put</strong> request to mediapackage hls ingest endpoint, I get a 201.</p> <pre class="lang-py prettyprint-override"><code>def postStreamToMediaPackage(envVariables, fileName, content, contentT...
<python><amazon-web-services><webdav><aws-media-live><aws-mediapackage>
2024-04-26 08:44:35
1
536
sakib11
78,388,929
23,461,455
Configure Sweetviz to analyze object-type column without forced type conversion?
<p>Consider the following short dataframe example:</p> <pre><code>df = pd.DataFrame({'column1': [2, 4, 8, 0], 'column2': [2, 0, 0, 0], 'column3': [&quot;test&quot;, 2, 1, 8]}) </code></pre> <p>df.dtypes shows that the datatypes of the columns are:</p> <pre><code>column1 int64 ...
<python><pandas><dataframe><visualization>
2024-04-26 07:39:43
1
1,284
Bending Rodriguez
78,388,928
2,707,342
How do I update status to either expired or active depending on date and time?
<p>I have an application built in Django. The application allows businesses to manage their day-to-day operations and has features like; HR Management, Sales, Point of Sale, Accounting, etc.</p> <p>For businesses to be able to attach discounts on their products, I have created a <code>Discount</code> model:</p> <pre><c...
<python><django><django-models><optimization>
2024-04-26 07:39:37
1
571
Harith
78,388,899
2,596,475
Encrypt Decrypt file using GNUPG
<p>I created PGP keys using <a href="https://pgpkeygen.com/" rel="nofollow noreferrer">this key generator website</a> (Algo - RSA, Key Size - 4096 bits). I am using Databricks to write its encrypt and decrypt function and store public and private keys generated through pgpkeygen.com. I tried multiple ways to achieve th...
<python><azure-databricks><public-key-encryption><gnupg><pgp>
2024-04-26 07:33:17
1
795
Ajay
78,388,889
11,267,783
Matplotlib issue with colorbar using subplot_mosaic and make_axes_locatable
<p>I want to create a figure using subplot_mosaic which is very useful to organize plots. However with my code, when I plot the figure, I don't see the colorbar value and title. This is probably due to <code>make_axes_locatable</code> and <code>constrained_layout=True</code>, but in my case I don't have the choice to u...
<python><matplotlib>
2024-04-26 07:31:40
1
322
Mo0nKizz
78,388,852
20,240,835
How to run Snakemake on an undetermined set of samples?
<p>I am planning to create a Snakemake script that will run on a large scale data set. The script will:</p> <ol> <li>preprocess the samples,</li> <li>filter the samples based on the results of the preprocessing (note: all preprocessing samples are required for filtering)</li> <li>proceed to the next step for samples th...
<python><workflow><snakemake>
2024-04-26 07:25:37
1
689
zhang
78,388,761
724,403
Manim axes alignment problem: How to align ParametricFunction and Points with Axes?
<p>How do I align my ParametricFunction and Points with Axes?</p> <p>I felt inspired to build parametric animations in manim. I have played around with the package, gotten a variety of 2D and parametric curves rendering, and am generally enjoying it. However, I cannot seem to get the axes aligned with my parametric equ...
<python><math><graph-visualization><manim><algorithm-animation>
2024-04-26 07:06:22
1
359
David
78,388,607
2,604,247
Jupyter Notebook not Starting in Virtual Environment
<h5>Environment</h5> <ul> <li>Ubuntu 20.04</li> <li>Python 3.8.10</li> <li>Pip 20.0.2</li> </ul> <p>Using pip venv to create a virtual environment in my project directory. These are the commands I am running.</p> <pre class="lang-bash prettyprint-override"><code>python3 -m pip venv .venv # Create the virtual environmen...
<python><jupyter-notebook><jupyter><virtualenv><python-venv>
2024-04-26 06:26:04
2
1,720
Della
78,388,444
8,890,613
Counting Instances of an element with selenium and python
<p>so I am working on a online class that requires me to use selenium to navigate to * Navigate to The Internet website (<a href="https://the-internet.herokuapp.com" rel="nofollow noreferrer">https://the-internet.herokuapp.com</a>) - then to a specific child page (add/remove elements)then add some elements and count th...
<python><selenium-webdriver>
2024-04-26 05:43:13
1
441
Jason Harder
78,388,365
209,942
Python Error: Unable to create process using python Access is denied
<p><strong>Environment</strong></p> <p>I had python 3.11.x and 3.12.x installed. But I found that 3.11.x is more compatible with things in general, and 3.12.x isn't mainstream yet. Sorry if that badly described, but I think it's roughly correct.</p> <p><strong>Problem</strong></p> <p>In vscode, my code runs. I use a vi...
<python><visual-studio-code>
2024-04-26 05:16:38
1
2,270
johny why
78,388,333
2,779,280
Nested quotes in f-string with Python 3.12 vs older versions
<p>With Python 3.12 I can do the following without error:</p> <pre><code>a = &quot;abc&quot; s = f&quot;{a.replace(&quot;b&quot;, &quot;x&quot;)}&quot; </code></pre> <p>Note the nested <code>&quot;</code> characters.</p> <p>With Python 3.6 the same will throw a SyntaxError because closing <code>)</code> and <code>}</co...
<python><python-3.x><f-string>
2024-04-26 05:03:52
2
660
pktl2k
78,388,171
4,931,657
client connecting to server works with python, but not with kotlin ktor
<p>I am connecting to a web server that returns binary data to me. Using the below python code, I am able to output the results:</p> <pre><code>from struct import unpack_from import socket HOST = &quot;127.0.0.1&quot; PORT = 12345 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, P...
<python><kotlin><binary><ktor>
2024-04-26 04:04:36
1
5,238
jake wong
78,388,150
10,964,685
Pattern matching callback for plotly dash - python
<p>I've got a dropdown that allows me to filter a categorical plotly graph. A separate callback allows the user to alter this graph from a bar chart to a pie chart. This part works as expected.</p> <p>I've got separate slider components that adjust the settings for both the bar chart or the pie chart. The problem is t...
<javascript><python><callback><plotly><pattern-matching>
2024-04-26 03:57:15
1
392
jonboy
78,387,926
4,732,111
Polars read_parquet method converts the original date value to a different value if the date is invalid
<p>I'm reading a parquet file from S3 bucket using polars and below is the code that i use:</p> <pre><code>df = pl.read_parquet(parquet_file_name, storage_options=storage_options, hive_partitioning=False) </code></pre> <p>In the S3 bucket, the value (which is invalid as the year is 0200) of the date column is stored as...
<python><pandas><python-polars>
2024-04-26 02:19:46
2
363
Balaji Venkatachalam
78,387,925
11,124,121
How to swap the columns according to the data type?
<p>The sample data is as below (The data is fake, not real data):</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>Key</th> <th>Death indicator</th> <th>Date Death</th> <th>Exact date of death</th> <th>Death Cause</th> </tr> </thead> <tbody> <tr> <td>00</td> <td>Alive</td> <td></td> <td></td>...
<python><r><pandas><dataframe><dplyr>
2024-04-26 02:18:49
2
853
doraemon
78,387,917
12,454,639
Django models cannot be queried due to missing id field?
<p>I currently am working on a django project for a discord bot. the issue that I am trying to resolve is that I cannot seem to query the data for one of my models.</p> <p>A piece of information that has been unclear to me that I am sure caused this issue was a series of migration issues I had trying to update my Chara...
<python><django><migration>
2024-04-26 02:15:23
1
314
Syllogism
78,387,721
1,100,248
How to scope autogen tool to working dir?
<p>I am playing with <code>AutoGen</code> and I've added tools to read and write text files (mainly because don't want to waste resource)</p> <p>My agent has working dir</p> <pre class="lang-py prettyprint-override"><code>executor = autogen.UserProxyAgent( name=&quot;executor&quot;, system_message=&quot;Executo...
<python><artificial-intelligence><ms-autogen>
2024-04-26 00:31:41
1
19,544
Vova Bilyachat
78,387,662
7,499,546
Cannot import name 'setuptools' from setuptools
<p>When installing a package I get the error:</p> <p><code>ImportError: cannot import name 'setuptools' from setuptools</code></p> <p>I am on the latest setuptools version <code>69.5.1</code> at the time of writing.</p>
<python><python-3.x><setuptools>
2024-04-25 23:57:22
1
703
Joshua Patterson
78,387,495
11,338,984
Query Firebase for "not-in document_id" in Python
<p>I have an array with some document ids to avoid on my search. I am trying to run the query by using the <code>FieldPath.document_id()</code> but I am getting the <code>__key__ filter value must be a Key</code>. Is there any way to solve it?</p> <p>Here's a snippet:</p> <pre class="lang-py prettyprint-override"><code...
<python><python-3.x><firebase><google-cloud-firestore>
2024-04-25 22:32:46
0
1,783
Ertan Hasani
78,387,304
2,437,514
possible to create custom type hint creation functions?
<p>I am playing around with creating a tool that can detect the addition and subtraction of incompatible dimensions (of unit-bearing values) at type checking time. It would need to know how to combine dimensions correctly when they are multiplied and divided.</p> <p>As a part of that effort, I'm trying to get this code...
<python><pycharm><mypy><python-typing>
2024-04-25 21:21:25
0
45,611
Rick
78,387,303
10,638,608
structlog with Celery
<p>I have a working celery app. I want to add structured logging to it.</p> <p>A complete working example would be hard to provide, so let me demostrate:</p> <pre class="lang-py prettyprint-override"><code>import structlog import logging logging.config.dictConfig(...) structlog.configure(...) app = Celery() </code></...
<python><celery><structlog>
2024-04-25 21:21:05
2
1,997
dabljues
78,387,280
947,012
How to locate CA bundle used by pip?
<p>Pip <a href="https://pip.pypa.io/en/stable/topics/https-certificates/" rel="nofollow noreferrer">documentation</a> says:</p> <blockquote> <p>By default, pip will perform SSL certificate verification for network connections it makes over HTTPS. These serve to prevent man-in-the-middle attacks against package download...
<python><pip><ssl-certificate>
2024-04-25 21:13:34
1
3,234
greatvovan
78,387,204
1,209,675
Pybind11 can't figure out how to access tuple elements
<p>I'm an experienced Python programmer trying to learn C++ to speed up some projects. Passing a py::tuple to a function, how do I access the elements?</p> <p>Here's the constructor for a class I'm making to hold images from a video.</p> <pre><code>Buffer::Buffer(int size, py::tuple hw_args_) { unsigned int frame_hei...
<python><c++><c++11><pybind11>
2024-04-25 20:53:24
1
335
user1209675
78,387,122
480,118
Pandas merge complaining about non unique labels when key is a composite and unique
<p>I am trying to merge two dataframes such that i end up with one with same number of columns but but an increased row count.</p> <pre><code>import pandas as pd, numpy as np data1 = [['date' , 'symbol', 'value'], ['1999-01-10', 'AAA', 101], ['1999-01-11', 'AAA', 201]] I am trying to me...
<python><pandas>
2024-04-25 20:31:13
2
6,184
mike01010
78,387,100
305,883
Setting window length and frame length in STFT for clustering audio
<p>I am looking to understand better the consequences of setting the window and the fft length in the short time fourier transform (STFT). My goal is increasing clustering of brief vocalisations (utterances) and I am trying to increase resolution of frequencies and squash the temporal component.</p> <p>What are the ef...
<python><tensorflow><signal-processing><fft><librosa>
2024-04-25 20:26:03
1
1,739
user305883
78,387,063
3,731,622
numpy aliases np.float_ and np.float64 treated differently by mypy
<p>From <a href="https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.double" rel="nofollow noreferrer">numpy documentation for np.double</a> it says <code>np.float</code> and <code>np.float64</code> are aliases for <code>np.double</code>. (Noting the docs say <code>Alias on this platform</code> for <code>...
<python><numpy><mypy><python-typing>
2024-04-25 20:15:11
0
5,161
user3731622