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
76,085,684
678,491
Using matplotlib cmap function outside of matplotlib
<p>I'm trying to use the same mapping function as <strong>matplotlib</strong> <strong>cmap</strong> but outside of <strong>matplotlib</strong>. E.g.:</p> <p>Given:</p> <pre class="lang-py prettyprint-override"><code>plt.imshow(image, cmap=&quot;viridis&quot;) </code></pre> <p>Manually replicate same result such that ev...
<python><matplotlib>
2023-04-23 15:20:00
0
1,313
k1m190r
76,085,647
1,668,622
In Python is it technically possible to access a functions local variables after it has been executed?
<p>I guess, the answer is &quot;no&quot;, since <a href="https://stackoverflow.com/questions/35754307/how-do-i-access-a-local-variable-in-my-decorated-function-from-my-decorator">someone else asked something similar</a> a while ago, but a lot happens in 7 years..</p> <p>In some quite non-pythonic experiment I'd like to...
<python><python-3.x><python-decorators>
2023-04-23 15:11:55
0
9,958
frans
76,085,625
17,936,708
Insert error using SQL Alchemy to transfer data from SQL Server to MariaDB
<p>Using SQL Alchemy, I am trying to move data from a SQL Server table to a MariaDB table. The tables are almost the same, as you can see in this code:</p> <p>MariaDB table :</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE IF NOT EXISTS customers ( id INT PRIMARY KEY, first_name VA...
<python><sql-server><sqlalchemy><mariadb>
2023-04-23 15:07:32
1
390
Oleg Ivsv
76,085,260
599,912
Define constraints with or-tools for a carpooling problem
<p>I am having a real life situation where I am trying to solve a school carpooling problem. I thought it would be good to try and use or-tools and learn in the process.</p> <p>The school is divided into 2 locations, some children go to location 1 and some to location 2 (for the entire week)</p> <p>So far, I have defin...
<python><constraints><linear-programming><or-tools><cp-sat>
2023-04-23 13:55:17
3
22,977
Michael
76,085,253
3,900,373
Call AWS API Gateway from Flask server
<p>I am using <a href="https://mblackgeo.github.io/flask-cognito-lib/" rel="nofollow noreferrer">flask-cognito-lib</a> and AWS Cognito to authentical users. I am able to follow the example code to secure Flask endpoints.</p> <pre><code>from flask import Flask, jsonify, redirect, session, url_for from flask_cognito_lib...
<python><amazon-web-services><flask><aws-lambda><jwt>
2023-04-23 13:54:01
0
2,316
alagris
76,085,135
4,225,430
How to beautify jupyter output, especially with alignment?
<p>I'm learning python pandas programming with jupyter notebook. I see from video clips that the output of pandas series is neat, with column alignment, such as the one below:</p> <p><a href="https://i.sstatic.net/Irzcn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Irzcn.png" alt="enter image descripti...
<python><pandas><dataframe><jupyter>
2023-04-23 13:29:45
0
393
ronzenith
76,085,064
15,295,149
Langchain gpt-3.5-turbo models reads files - problem
<p>I am making really simple (and for fun) LangChain project.</p> <p>A model can read PDF file and I can then ask him questions about specific PDF file.</p> <p>Everything works fine (<strong>this is working example</strong>)</p> <pre><code>from PyPDF2 import PdfReader from langchain.embeddings.openai import OpenAIEmbed...
<python><openai-api><langchain>
2023-04-23 13:16:49
2
746
devZ
76,084,999
12,398,468
Getting Unknown opcode error even though Python/TF versions for train and test are the same
<p>I'm trying to create a Siamese network following this tutorial <a href="https://pyimagesearch.com/2020/11/30/siamese-networks-with-keras-tensorflow-and-deep-learning/" rel="nofollow noreferrer">https://pyimagesearch.com/2020/11/30/siamese-networks-with-keras-tensorflow-and-deep-learning/</a></p> <p>The only thing I'...
<python><tensorflow><machine-learning><keras><deep-learning>
2023-04-23 13:03:18
1
453
J Xkcd
76,084,995
16,363,897
Numpy Discrete Fourier Transform (fft) on multiple arrays
<p>This is a follow-up question to this <a href="https://stackoverflow.com/questions/76081149/polyfit-for-a-seasonality-model">other question</a></p> <p>I have several quite large pandas dataframes and I need to apply Numpy's fft function to denoise each row separately.</p> <p>What I'm doing right now is iter through t...
<python><pandas><numpy>
2023-04-23 13:01:51
1
842
younggotti
76,084,776
7,115,122
How to implement stripe subscription with three months initial upfront payment
<p>I'm building a checkout page where a user subscribes to a $10 /month product. However, when the user signs up, they are required to pay for the first three months upfront (that's $30). If they wish to auto renew their subscription thereafter, we'll fallback to them paying $10 each month.</p> <p>The frontend is a Sin...
<python><reactjs><stripe-payments>
2023-04-23 12:15:46
1
1,354
Cels
76,084,731
5,016,440
Returning function from compiled string in Python
<p>I am trying to create a function from a string and return it from another Python function. Example below</p> <pre><code>def compile_functions() -&gt; t.Callable: code = &quot;&quot;&quot;def f():\n\treturn 1&quot;&quot;&quot; compiled = compile(code, &quot;&lt;string&gt;&quot;, &quot;exec&quot;) exec(cod...
<python>
2023-04-23 12:06:10
1
455
nestor556
76,084,676
10,313,194
Django Cannot keep last 3 row of database
<p>I want to keep latest 3 row of each key and delete oldest row if data of each key more than 3 row. I have sample data like this.</p> <pre><code>id value key created 1 a1 001 2023-04-23 01:01:00 &lt;= delete oldest of key 001 2 a2 001 2023-04-23 01:02:00 3 a3 001 2023-04-23 01:03:00 4 a4 001...
<python><django><django-views>
2023-04-23 11:54:28
1
639
user58519
76,084,565
1,145,011
Unable to connect to Snowflake to Python
<p>H,</p> <p>I' unable to connect to SNowflake using Python. Via browser I'm able to connect using the same URL and Password. Python Version -- 3.11 Snowflake - 3.0.2</p> <p>I installed snowcd to investigate further and got below error. But not able to decode it.</p> <h1>**Check for 4 hosts failed, display as follow:</...
<python><snowflake-cloud-data-platform>
2023-04-23 11:30:20
1
1,551
user166013
76,084,523
3,668,129
How to downcast sample rate of ndarray (without saving it as wav file)
<p>I have a <code>ndarray</code> (which I got from microphone) with samples (sample rate = 48000).</p> <p>I want to create a new <code>ndarray</code> with lower sample rate (16000).</p> <p>One option is to save this <code>ndarray</code> as <code>wav</code> file and reload it with different sample rate (via <code>libros...
<python><python-3.x><librosa>
2023-04-23 11:18:55
1
4,880
user3668129
76,084,358
19,318,120
Django VideoField
<p>I'm want to make a custom FileField that only allows video uploads I'm trying to use pymediainfo to make sure the file uploaded is a video but I keep getting FileNotFoundError</p> <p>here's my code</p> <pre><code>from django.core.exceptions import ValidationError from django.db import models from pymediainfo import ...
<python><django>
2023-04-23 10:37:38
2
484
mohamed naser
76,084,214
8,445,442
What is the recommended number of threads for PyTorch relative to available CPU cores?
<p>First I want to say that I don't have much experience with pytorch, ML, NLP and other related topics, so I may confuse some concepts. Sorry.</p> <p>I downloaded few models from Hugging Face, organized them in one Python script and started to perform benchmark to get overview of performance. During benchmark I monito...
<python><pytorch><parallel-processing><huggingface-transformers><huggingface>
2023-04-23 10:02:53
1
1,043
Amaimersion
76,084,159
12,466,687
Unable to change default selection in streamlit multiselect()
<p>I am new to <code>streamlit</code> apps and facing an <strong>issue</strong> of <strong>not able to select any other <code>option</code></strong> other than <strong>default</strong> option when using <code>st.multiselect()</code>. I have also tried <code>st.selectbox</code> but faced an issue with that as well.</p> ...
<python><streamlit><python-polars>
2023-04-23 09:51:31
3
2,357
ViSa
76,084,157
6,223,328
Python inherit methods depending on condition in init
<p>lets say I have two classes:</p> <pre class="lang-py prettyprint-override"><code>class ImgClass(): &quot;&quot;&quot; A class based on an image &quot;&quot;&quot; def __init__(self): ... def i_am_an_img(self): ... class PdfClass(): &quot;&quot;&quot; A class based on a ...
<python><class><subclass>
2023-04-23 09:50:50
1
357
Max
76,084,128
11,246,056
How to update a single value in Polars dataframe?
<p>In Pandas, you can update a value with the <strong><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.at.html" rel="nofollow noreferrer">at</a></strong> property, like this:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({&quot;col1&quot;: [1, 2, 3], &q...
<python><dataframe><python-polars><setvalue>
2023-04-23 09:43:10
2
13,680
Laurent
76,084,095
7,331,538
Airflow with docker not finding local python scripts and directories (ModuleNotFoundError)
<p>I am using Airflow with the default <code>docker-compose.yaml</code> file. I have my own sorce directories which I want to run from <code>DAGs</code>. Structure is like so:</p> <pre><code>root_package ├── __init__.py ├── __pycache__ ├── foo1.py ├── dags │   ├── __init__.py │   ├── __pycache__ │   └── update.py ├── s...
<python><docker><airflow><python-module>
2023-04-23 09:35:24
1
2,377
bcsta
76,084,046
14,562,965
Terraform showing only default workspace in Jenkins pipeline
<p>I have a Jenkins pipeline I am using to perform terraform actions. The Jenkins pipeline runs python scripts to perform those actions (and some more). One of those actions is <code>terraform workspace select</code>, and the python function is this:</p> <pre><code>def terraform_plan(options): provider=get_cluster_...
<python><jenkins><terraform><pipeline>
2023-04-23 09:20:42
0
302
Tom Sebty
76,084,030
16,363,897
Get the (dynamic) nth column value for each row in pandas dataframe
<p>I have the following dataframe &quot;df1&quot;:</p> <pre><code> reference date 2023-01-01 1 2023-01-02 2 2023-01-03 3 2023-01-04 4 </code></pre> <p>I have another dataframe &quot;df2&quot;:</p> <pre><code> 1 2 3 4 date 20...
<python><pandas>
2023-04-23 09:16:07
2
842
younggotti
76,084,026
15,742,150
How to mock method in another class method?
<p>I got method in <code>notifier</code> file that i want to test:</p> <pre><code>def notify(): Class_A.another_class_method() Class A: @classmethod def prepare(): helper_method() def another_class_method(): prepare() </code></pre> <p>I need to mock helper_method. How can i do this ?</...
<python><unit-testing><python-unittest>
2023-04-23 09:15:10
1
539
akonovalov
76,084,000
5,319,180
Asyncio async_wrap to convert sync functions to async in python. How does it work?
<p>I huge chunk of legacy sync code ( a huge function which calls other sync functions, includes sync http API calls with <code>requests</code> library, and so on ). This function is run as a part of a Queue worker (picks up tasks from the queue and executes this function ) Facing performance issues and moving to asyn...
<python><multithreading><python-asyncio><python-anyio>
2023-04-23 09:08:52
1
429
D.B.K
76,083,975
4,780,574
SQLAlchemy declarative dataclass mapping: How to create non-required columns?
<p>I am trying to figure out how to use declarative mapping with dataclasses in SQLAlchemy.</p> <p>Setup:</p> <pre><code> from dotenv import load_dotenv import os from sqlalchemy.engine import URL #test abc load_dotenv() url_object = URL.create( &quot;postgresql+psycopg2&quot;, username=os.environ.get('DBUSE...
<python><sqlalchemy><orm><default-value><python-dataclasses>
2023-04-23 09:03:50
1
814
Stonecraft
76,083,927
4,405,160
FastAPI returns 404 'detail not found' when using multiple Optional path parameters
<p>Trying to create this FastAPI app using three optional path paarameters. I tried expanding the code into three optional inputs shown below, it now forces me to input all three; otherwise, a 404 'detail not found' error is raised.</p> <pre><code>import json from datetime import date from typing import Optional @app....
<python><fastapi><optional-parameters>
2023-04-23 08:51:01
0
574
beavis11111
76,083,905
19,325,656
AttributeError: 'ContactSerializer' object has no attribute 'get_status'
<p>Hi all I have this error when im trying to save my serializer</p> <pre><code>AttributeError: 'ContactSerializer' object has no attribute 'get_status' </code></pre> <p>I render my serializer as form so I've created custom template for forms just to add new classes</p> <pre><code>class ContactSerializer(serializers.Mo...
<python><django><django-rest-framework><django-serializer>
2023-04-23 08:47:20
1
471
rafaelHTML
76,083,492
7,133,942
Tensorflow does not detect GPU altough the GPU driver and Cuda are installed
<p>I have an Nvidia GPU (Geforce RTX 3090) and the driver is displayed in Nvidia Control Panel. I also have installed the latest version of Cuda. However, when using the following code in Python with TensorFlow:</p> <pre><code>gpus = tf.config.list_physical_devices('GPU') if not gpus: print(&quot;No GPUs detected&q...
<python><tensorflow><gpu>
2023-04-23 06:50:13
4
902
PeterBe
76,083,485
2,793,602
SHAP - instances that have more than one dimension
<p>I am very new to SHAP and I would like to give it a try, but I am having some difficulty.</p> <p>The model is already trained and seems to perform well. I then use the training data to test SHAP with. It looks like so:</p> <pre><code> var_Braeburn var_Cripps Pink var_Dazzle var_Fuji var_Granny Smith \ 0 ...
<python><machine-learning><shap>
2023-04-23 06:49:07
1
457
opperman.eric
76,083,450
691,197
Segmentation fault: 11 when loading Haystack DensePassageRetriever
<p>I am trying to run this Question Answering model using this doc <a href="https://haystack.deepset.ai/tutorials/12_lfqa" rel="nofollow noreferrer">https://haystack.deepset.ai/tutorials/12_lfqa</a>, but running into segmentation fault as below. I am using Python 3.9.17. May laptop has 64 GB RAM, and when I checked the...
<python><segmentation-fault><nlp-question-answering><haystack>
2023-04-23 06:35:24
0
1,009
user691197
76,083,428
11,482,269
ImportError: cannot import name 'json_normalize' from 'pandas.io.json'
<pre><code>python 3.9.2-3 pandas 2.0.0 pandas-io 0.0.1 </code></pre> <pre><code>Error: from pandas.io.json import json_normalize ImportError: cannot import name 'json_normalize' from 'pandas.io.json' (/home/casaos/.local/lib/python3.9/site-packages/pandas/io/json/__init__.py) </code></pre> <p>Apparently this...
<python><json><pandas><importerror><json-normalize>
2023-04-23 06:27:35
2
351
Joe Greene
76,083,413
13,330,700
Running an application via docker container on http://localhost:8000/ returns Bad Request, but http://127.0.0.1:8000/ works
<p>Disclaimer: I am a docker noob and I'm trying to learn. I am also running this on Windows 10</p> <p>Here's my <code>Dockerfile.yaml</code></p> <pre><code>FROM python:3.11 # setup env variables ENV PYTHONBUFFERED=1 ENV DockerHOME=/app/django-app # Expose port EXPOSE 8000 # create work dir RUN mkdir -p $DockerHOME # s...
<python><django><docker><containers><docker-desktop>
2023-04-23 06:20:43
1
499
mike_gundy123
76,083,347
2,454,357
hover not working correctly when using different kinds of subplots in plotly
<p>I am trying to generate a plotly-figure that contains one <a href="https://plotly.com/python-api-reference/generated/plotly.graph_objects.Scattermapbox.html" rel="nofollow noreferrer">Scattermapbox</a> and multiple other types of plots (in this case line plots generated with <a href="https://plotly.com/python-api-re...
<python><plotly>
2023-04-23 05:56:50
1
9,890
Thomas Kühn
76,083,008
15,599,248
How to install 'tensorflow_examples' in colab
<p>I run <a href="https://www.tensorflow.org/tutorials/images/segmentation" rel="nofollow noreferrer">Image segmentation in Tensorflow Core tutorial</a> in Google Colab. When running</p> <pre class="lang-bash prettyprint-override"><code>!pip install git+https://github.com/tensorflow/examples.git </code></pre> <p>get an...
<python><tensorflow><google-colaboratory>
2023-04-23 03:36:29
1
351
cc01cc
76,082,807
4,281,353
Why numpy array is not of Sequence type?
<p>Help understand why numpy array is not a Sequence type object.</p> <pre><code>from typing import Sequence import numpy as np x = np.array([1,2,3]) isinstance(x, Sequence) --- False </code></pre> <ul> <li><a href="https://docs.python.org/3/glossary.html#term-sequence" rel="noreferrer">sequence</a></li> </ul> <blockq...
<python><numpy><python-typing>
2023-04-23 02:11:14
1
22,964
mon
76,082,804
6,222,331
how to convert 'dask_cudf' column to datetime?
<p>How can we convert a <strong>dask_cudf</strong> column of string or nanoseconds to a datetime object? <code>to_datetime</code> is available in pandas and cudf. See sample data below</p> <pre><code>import pandas import cudf # with pandas df = pandas.DataFrame( {'city' : ['Dallas','Bogota','Chicago','Juarez'], ...
<python><dask><rapids><cudf>
2023-04-23 02:10:18
0
2,314
dleal
76,082,746
1,601,580
How to transform a quickdraw image to 84 by 84 in pytorch using the learn2learn library?
<p>I was trying to use learn2learn's QuickDraw but it seems like I'm getting errors when I attempt to apply transformations (resizing to 84x84, random crop) on it. The issue stems from when l2l's quickdraw library attempts to apply transformations onto a quickdraw image (that is apparently in the form of a np.memmap/.n...
<python><machine-learning><deep-learning><pytorch><learn2learn>
2023-04-23 01:45:24
4
6,126
Charlie Parker
76,082,734
4,281,353
How to check if an object can slice
<p>Is this the right way to check if a Python object can be sliced or are there better/correct ways?</p> <pre><code>import typing def can_slice(object) -&gt; bool: return &quot;__getitem__&quot; in dir(object) </code></pre> <p>I am looking for a way not using exception to test if an object can be sliced.</p> <h2>...
<python><slice>
2023-04-23 01:42:28
2
22,964
mon
76,082,697
6,676,101
How do we remove duplicates from an iterator and put it in sorted order?
<p>How do we remove duplicates from an iterator and put it in sorted order?</p> <p>Sample input:</p> <pre><code>it = iter([&quot;black&quot;, &quot;aqua&quot;, &quot;aqua&quot;, &quot;black&quot;, &quot;black&quot;, &quot;blue&quot;, &quot;aqua&quot;, &quot;blue&quot;, &quot;fuchsia&quot;, &quot;gray&quot;, &quot;gray&...
<python>
2023-04-23 01:27:03
1
4,700
Toothpick Anemone
76,082,693
1,330,719
VS Code: Connecting to a python interpreter in docker container without using remote containers
<p>I know it is generally possible to connect to a container's python interpreter with:</p> <ul> <li>remote containers</li> <li>remote ssh</li> </ul> <p>The problems I have with these solutions:</p> <ul> <li>it opens a new window where I need to install/specify all extensions again</li> <li>it opens a new window per co...
<python><docker><visual-studio-code>
2023-04-23 01:25:21
1
1,269
rbhalla
76,082,604
3,116,936
Python regular expression to capture phrases?
<p>I want to figure out a regex pattern capable of capturing the operation and the two registers or addresses it acts on for a given snippet of assembly code. This is what I have so far:</p> <pre><code>import re assembly_code = &quot;&quot;&quot; lea r8, [rcx + 8*rax] movsd xmm0, qword ptr [rcx + 8*rax] ...
<python><regex>
2023-04-23 00:50:25
1
506
user3116936
76,082,551
11,740,629
Scrape all Word Document files from a website using Python or R
<p>I'm trying to find a way to download all the docx files from the following URL, using Python or R:</p> <p><a href="https://www.microsoft.com/en-us/Investor/annual-reports.aspx" rel="nofollow noreferrer">https://www.microsoft.com/en-us/Investor/annual-reports.aspx</a></p> <p>I've looked into similar questions (<a hre...
<python><r><web-scraping>
2023-04-23 00:28:04
1
583
lovestacksflow
76,082,526
7,776,212
CrossEntropyLoss using weights gives RuntimeError: expected scalar type Float but found Long neural network
<p>I am using a Feedforward neural network for a classification task with 4 classes. The classes are imbalanced and hence, I want to use a weight with the CrossEntropyLoss as mentioned <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss" rel="nofollow noreferrer">...
<python><machine-learning><pytorch><neural-network><cross-entropy>
2023-04-23 00:14:54
1
779
diviquery
76,082,452
7,448,860
How to get the current stock price using fidelity's screener?
<p>I am trying to get the current stock price using fidelity's screener. For example, the current price of AAPL is <code>$165.02</code> on <a href="https://digital.fidelity.com/prgw/digital/research/quote/dashboard/summary?symbol=AAPL" rel="nofollow noreferrer">https://digital.fidelity.com/prgw/digital/research/quote/d...
<python><selenium-webdriver><web-scraping><beautifulsoup><python-requests>
2023-04-22 23:42:44
1
1,250
Beginner
76,082,425
6,339,279
Is it possible to create an attribute of an instance of a Python class outside of the __init__ method?
<p>All of the Python 3.x documentation that I can find implies that an instance attribute can be created <em>only</em> in the <code>__init__</code> method of a class. I have not been able to find documentation (or examples) suggesting that an instance attribute can be created in other instance methods of a class. I mus...
<python>
2023-04-22 23:31:24
1
651
Matthew Rips
76,082,398
6,439,229
How to make a QIcon switch appearance without resetting it on the widget?
<p>Now that dark mode has finally come to Windows with Qt 6.5, I noticed that a lot of my icons don't look too well on a dark background. So I'd like to use different icons for light and dark mode. And, to make things difficult, have the icons change (their appearance) when the user switches mode on his OS.</p> <p>In o...
<python><pyqt><qicon>
2023-04-22 23:22:25
1
1,016
mahkitah
76,082,137
1,934,510
Routes from new blueprint not found and getting 404
<p>I'm building a new blueprint for my flask app and for a new blueprint. Its routes are getting 404 errors.</p> <p>This is the new Blueprint (shopify) views.py file:</p> <pre><code>... shopify = Blueprint('shopify', __name__, template_folder='templates', url_prefix='/shopify') # @admin.before_req...
<python><flask>
2023-04-22 22:06:43
1
8,851
Filipe Ferminiano
76,082,017
18,949,720
Loading train/val/test datasets with images in separate folders using Pytorch
<p>For my first Pytorch project, I have to perform image classification using a dataset containing jpg image of clouds. Im am struggling with data importation, because the train/validation/test sets are not separated and the images are located in different folders according to their class. So, the folders structure loo...
<python><import><pytorch><classification>
2023-04-22 21:31:24
3
358
Droidux
76,081,685
764,195
Post list field In urllib3
<p>I'm creating a simple AWS lambda function to post some data to an API but the API expects a list however I can't get it to work. I've got the following code that I'm testing with</p> <pre class="lang-py prettyprint-override"><code>import urllib3 import json http = urllib3.PoolManager() file_path = 'file.png' with o...
<python><urllib3>
2023-04-22 20:00:07
1
4,448
PaReeOhNos
76,081,557
4,404,805
Getting duplicates after list comprehension
<p>I have two lists of dictionaries such as:</p> <pre><code>l1 = [{&quot;ticket_type&quot;: &quot;A1&quot;, &quot;ticket_count&quot;: 30, &quot;ticket_price&quot;: 1000.0}, {&quot;ticket_type&quot;: &quot;A2&quot;, &quot;ticket_count&quot;: 70, &quot;ticket_price&quot;: 500.0}, {&quot;ticket_type&quot;: &qu...
<python>
2023-04-22 19:31:55
2
1,207
Animeartist
76,081,104
5,034,651
Proper way to pass datetime from pyspark to pandas
<p>I'm trying to convert a spark dataframe to pandas but it is erroring out on new versions of pandas and warns the user on old versions of pandas.</p> <p>On python==3.9, pyspark==3.4.0, and pandas==1.5.3, the warning looks as follows:</p> <pre><code>/Users/[me]/miniconda3/envs/py39/lib/python3.9/site-packages/pyspark/...
<python><pandas><pyspark>
2023-04-22 17:51:01
1
616
Ken Myers
76,080,957
2,476,219
SQLAlchemy 2 generic mixin
<p>My goal is to create a generic mixin, which concept can best be explained by an example:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar, Generic from sqlalchemy.orm import Mapped, mapped_column, MappedAsDataclass, DeclarativeBase from sqlalchemy import create_engine T = TypeVar(&quot...
<python><generics><sqlalchemy>
2023-04-22 17:17:33
1
3,688
Aart Stuurman
76,080,822
348,183
wxPython: Automatically resize the frame to keep free space out
<p>I have a very simple wxPython app which consist of a <code>frame</code> containing:</p> <ol> <li><code>control1</code> that keeps its aspect ratio on resize.</li> <li><code>control2</code> that keeps its height constant and fills the entire width of the <code>frame</code>.</li> </ol> <p>I'm using a <code>BoxSizer</c...
<python><layout><wxpython><wxwidgets>
2023-04-22 16:51:50
1
12,646
Albus Dumbledore
76,080,764
480,118
Is there anyway to get the class instance given the member variable?
<p>While this might seem like a silly example, it's the simplest way i can think of to explain what im after...let's say i have:</p> <pre><code>class MyClass: def __init__(self) -&gt; None: self.table_df = pd.DataFrame() self.table_df2 = pd.DataFrame() </code></pre> <p>I can do something like this<...
<python>
2023-04-22 16:40:30
0
6,184
mike01010
76,080,711
15,098,472
Stack arrays on specified dimension with arbitrary dimension size
<p>Consider the following data:</p> <pre><code>data = np.array([[i for i in range(3)] for _ in range(9)]) print(data) print(f'data has shape {data.shape}') [[0 1 2] [0 1 2] [0 1 2] [0 1 2] [0 1 2] [0 1 2] [0 1 2] [0 1 2] [0 1 2]] data has shape (9, 3) </code></pre> <p>And some parameter, let's call it <code>hi...
<python><arrays><numpy>
2023-04-22 16:28:25
1
574
kklaw
76,080,692
12,411,536
Dash multipage "stored component" values
<p>I am trying to implement a multipage Dash webapp and I am having a hard time to &quot;store&quot; changes in components when switching back and forth across pages. Namely, each time I move to a new page, the layout is refreshed.</p> <p>Below there is a (minimal?) code example for reproducibility purpose, where in Pa...
<python><plotly-dash>
2023-04-22 16:24:20
2
6,614
FBruzzesi
76,080,627
8,267,332
Elasticsearch Docker Authentication Exception with Python client
<p>Elasticsearch Docker Version: 8.5.0 Python Version: 3.10 elastic-transport==8.4.0 elasticsearch==8.7.0</p> <p>Elastic Search Docker Run command: <code>docker run -d -p 9200:9200 -e &quot;discovery.type=single-node&quot; -e &quot;xpack.security.enabled=true&quot; -e &quot;ELASTIC_PASSWORD=my_pass&quot; docker.elastic...
<python><docker><elasticsearch>
2023-04-22 16:10:38
0
369
PssstZzz
76,080,581
11,246,056
How to sum durations in Polars dataframe?
<p>I have the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>import datetime import polars as pl df = pl.DataFrame( { &quot;idx&quot;: [259, 123], &quot;timestamp&quot;: [ [ datetime.datetime(2023, 4, 20, 1, 45), datetime.datet...
<python><dataframe><duration><python-polars>
2023-04-22 16:02:04
1
13,680
Laurent
76,080,418
19,130,803
MyPy: Incompactible arg-type for a property
<p>I am working on python web app. I have defined an <code>enum</code> as below:</p> <pre><code>class AccountTypes(StrEnum): A: str = &quot;aaa&quot; B: str = &quot;bbb&quot; </code></pre> <p>Then, I have a <code>class</code> as below:</p> <pre><code>class Account: _types: type[AccountTypes] = AccountTy...
<python>
2023-04-22 15:26:42
0
962
winter
76,080,358
13,099,604
Why conditioning on dataframe return NAN?
<p>I have some coordinate data, and it seems they are very dispersed. So, I want to keep all outliers that are 2 distance away from std. There are two problem:</p> <pre><code># Load the data import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np df = pd.read_csv(&quot;map.csv&quo...
<python><pandas><dataframe>
2023-04-22 15:14:52
1
325
Hemfri
76,080,237
5,168,463
Delete 80K images from google drive at once
<p>I accidentaly unzipped a folder with 80K images in my main google drive folder <strong>MyDrive</strong>. And now I am trying to delete these files. I found a solution at this <a href="https://stackoverflow.com/questions/62496307/remove-files-on-google-drive-using-google-colab">link</a> and I am using the following c...
<python><python-3.x><google-drive-api><google-colaboratory>
2023-04-22 14:47:12
2
515
DumbCoder
76,079,894
16,363,897
Expanding standard deviation of all columns
<p>I have the following dataframe:</p> <pre><code> a b c day 1 2 2 8 2 1 2 2 3 7 2 3 4 2 9 7 5 4 6 4 </code></pre> <p>I want to get a new column (&quot;std&quot;) with the expanding standard deviation of all column values. NaNs should be ignored. This is the expected output:</p> ...
<python><pandas><numpy>
2023-04-22 13:28:28
3
842
younggotti
76,079,841
3,204,942
run `python.exe` to run the python shell interactively
<p>I am trying to run a exec.Command <code>python.exe</code> to run the python shell interactively. How can I type into it?</p> <pre><code>package main import ( &quot;fmt&quot; &quot;os&quot; &quot;os/exec&quot; &quot;io&quot; &quot;log&quot; ) func main() { fmt.Println(&quot;Before Pytho...
<python><shell><go>
2023-04-22 13:18:22
1
2,349
Gary
76,079,813
3,323,526
Python paramiko SSH: why doesn't reading of stdout free some buffer space?
<p>I'm writing testing code to check how does the SSH buffer work, and how exactly many bytes of none-read output blocks the remote program from proceeding. Here is the code:</p> <p>Client side:</p> <pre><code>from paramiko import SSHClient, AutoAddPolicy from datetime import datetime def log(msg, *args, **kwargs): ...
<python><ssh><paramiko><openssh>
2023-04-22 13:12:21
0
3,990
Vespene Gas
76,079,804
15,528,750
Singularity: Python package not available even though it is in docker
<p>I built myself a docker image from this docker file:</p> <pre><code>FROM ubuntu:22.04 RUN apt-get update RUN apt-get upgrade -y # Install python: RUN apt-get install software-properties-common -y RUN add-apt-repository ppa:deadsnakes/ppa -y RUN apt-get update RUN DEBIAN_FRONTEND=noninteractive apt-get install py...
<python><docker><singularity-container>
2023-04-22 13:09:44
1
566
Imahn
76,079,787
904,992
Making moviepy concatenations faster
<p>I'm adding clips to a main clip:</p> <pre><code>final_clip = VideoFileClip('video.mp4') secondary_clip = VideoFileClip('video2.mp4') for tr in time_ranges: clip = secondary_clip.subclip(tr['start'], tr['end']).set_position((0, 0)) final_clip = concatenate_videoclips([final_clip.subclip( 0...
<python><moviepy>
2023-04-22 13:04:09
1
8,294
funerr
76,079,776
1,999,585
How can I compute the value of softmax function on only a couple of Dataframe rows?
<p>I have the following Dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>Plassering</th> <th>Average FGrating</th> </tr> </thead> <tbody> <tr> <td>22943</td> <td>1</td> <td>100.43</td> </tr> <tr> <td>22944</td> <td>2</td> <td>93.5</td> </tr> <tr> <td>22945</td> <td>...
<python><pandas><dataframe><loops>
2023-04-22 13:02:03
2
2,424
Bogdan Doicin
76,079,763
7,987,455
How do I scrape data from a div-container?
<p>I'm trying to scrape apps names (which exist at the bottom of the website) from [This Website] <a href="https://www.workato.com/integrations/salesforce" rel="nofollow noreferrer">1</a> using requests_html and CSS selectors, but it returns an empty list. Can you please provide an explanation? The code:</p> <pre><code...
<python><web-scraping><beautifulsoup><css-selectors><python-requests-html>
2023-04-22 12:58:50
1
315
Ahmad Abdelbaset
76,079,748
7,906,206
Cant import ydata_profiling import into my google colab environment
<p>I cant import ydata_profiling into my python environment. I do understand that pandas_profiling has been deprecated. Is there anything wrong with my code:</p> <p><a href="https://i.sstatic.net/tMQhf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tMQhf.png" alt="enter image description here" /></a></p...
<python>
2023-04-22 12:56:16
1
1,216
Immortal
76,079,700
9,524,424
ModuleNotFoundError: No module named 'tensorflow.compat' / Keras compability issue?
<p>I have Python 3.11.3 (Windows) installed and use tensorflow and keras (both version 2.12.0). I keep getting the error:</p> <blockquote> <p>ModuleNotFoundError: No module named 'tensorflow.compat'</p> </blockquote> <p>There is a lot of discussion about the error but I could not find a proper solution so far.</p> <p>T...
<python><tensorflow><keras>
2023-04-22 12:45:06
1
2,453
Peter
76,079,575
8,324,480
Move the pointer in a bytearray as seek does for a BinaryIO
<p>If I have a binary file, I can open it in mode <code>rb</code> and move the pointer with <code>.seek()</code>:</p> <pre><code>with open(fname, &quot;rb&quot;) as fid: fid.seek(101) </code></pre> <p>But this is not possible with a <code>bytearray</code>:<code>bytearray(10).seek(1)</code>.</p> <hr /> <p>Does a <co...
<python><python-3.x><byte><binaryfiles><bytebuffer>
2023-04-22 12:14:58
1
5,826
Mathieu
76,079,388
610,569
How to use cross-encoder with Huggingface transformers pipeline?
<p>There're a set of models on huggingface hubs that comes from the <code>sentence_transformers</code> library, e.g. <a href="https://huggingface.co/cross-encoder/mmarco-mMiniLMv2-L12-H384-v1" rel="nofollow noreferrer">https://huggingface.co/cross-encoder/mmarco-mMiniLMv2-L12-H384-v1</a></p> <p>The suggested usage exam...
<python><nlp><huggingface-transformers><sentence-transformers><large-language-model>
2023-04-22 11:23:03
1
123,325
alvas
76,079,353
1,112,097
Plotly choropleth not working as expected
<p>I am trying to understand why no data is showing up on a plotly choropleth map</p> <p>The full code is in <a href="https://www.kaggle.com/code/andrewstaroscik/plotly-express-choropleth-not-working-as-expected?scriptVersionId=126678658" rel="nofollow noreferrer">this kaggle notebook</a></p> <p>I am trying to graph so...
<python><plotly><choropleth>
2023-04-22 11:15:54
1
2,704
Andrew Staroscik
76,079,104
1,096,660
Can you have multiple python versions with Conda and Apache2?
<p>I'm trying to wrap my head around configuring Apache2 to run my Django project which runs by using conda. After switching recently from venv the goal is to run multiple projects with their own environments.</p> <p>So far so good and there are multiple tutorials how to set this up.</p> <p>What I do not understand is ...
<python><python-3.x><apache2><conda><mod-wsgi>
2023-04-22 10:15:32
1
2,629
JasonTS
76,078,821
3,886,898
pyinstaller: doesn't save the video from the webcam
<p>I have a python script which records the webcam and saves the video using cv2.VideoWriter. The code works with no issues when I run it directly. After creating an exe file on windows using pyinstaller, it opens the webcam and creates output.avi, but the file doesn't open. This is my sample.py script:</p> <pre><code>...
<python><opencv><ffmpeg><pyinstaller>
2023-04-22 09:00:51
0
1,108
Mohammad
76,078,707
2,998,077
Pandas to add new column to indicate if the row fits multiple condition
<p>A simple dataframe that I want to use the &quot;df.loc&quot; way to add a new column (green) to indicate if the row fits the condition, like:</p> <p><a href="https://i.sstatic.net/9QtxC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9QtxC.png" alt="enter image description here" /></a></p> <pre><code>...
<python><pandas><dataframe>
2023-04-22 08:31:34
1
9,496
Mark K
76,078,688
16,383,578
Python turn a list of numbers into a Counter of ranges
<p>Given a <code>list</code> of numbers (<code>int</code>s or <code>float</code>s, usually <code>float</code>s), and a number <code>step</code>, what is the best way to turn the <code>list</code> into a <code>Counter</code>, so that the keys are two-element <code>tuple</code>s, each a multiple of <code>step</code>, and...
<python><python-3.x><grouping>
2023-04-22 08:25:32
2
3,930
Ξένη Γήινος
76,078,448
3,541,631
Retry failed downloads (using multiple workers) and check the parent if multiple urls with the same parent fail
<p>I'm creating a download worker using queues.</p> <pre><code>class Item: url: str download_path: str is_downloaded: bool </code></pre> <p>The worker code:</p> <pre><code>SENTINEL = &quot;END&quot; def download_item(to_download: Queue, downloaded: Queue): item: Item = to_download.get() while ...
<python><multithreading><python-3.8>
2023-04-22 07:13:51
0
4,028
user3541631
76,078,303
18,349,319
async sqlalchemy 'NoneType' object has no attribute 'send'
<p>I have a problem with async sqlalchemy. I am trying to create a record in my table in the database but it is not being created.</p> <p>database connection</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import create_a...
<python><postgresql><sqlalchemy>
2023-04-22 06:26:02
1
345
TASK
76,078,240
3,517,025
is there a way to force a cluster to go on top of the diagram in diagrams
<p>I'm using diagrams and I'm trying to force a cluster to go on top.</p> <p>Aplogies for the long code example, I didn't manage to render anything with less complexity that conveyed the same issue.</p> <pre class="lang-py prettyprint-override"><code>import os from diagrams import Cluster, Diagram, Edge from diagrams.o...
<python><graphviz><diagram>
2023-04-22 06:01:26
2
5,409
Joey Baruch
76,078,003
252,060
Regex works on regextester, but not python
<p>I tried this</p> <pre><code> pattern_time = ( r&quot;\b\d{1,2}([: .]?)(\d{2})?(\s?)((P|p)?)(.?)((M|m)?)(.?)((next|this)?)(\s?)((tomorrow|today|day|evening|morning|(mid?)night|((after|before)?)(noon))?)\b&quot; ) test_string = &quot;The meeting is at 3pm today or 5 tomorrow or 7 this afternoon or 00:00 midnight....
<python><regex>
2023-04-22 04:17:52
1
921
Ursa Major
76,077,950
5,583,772
How do you copy a dataframe in polars?
<p>In polars, what is the way to make a copy of a dataframe? In pandas it would be:</p> <pre><code>df_copy = df.copy() </code></pre> <p>But what is the syntax for polars?</p>
<python><dataframe><python-polars>
2023-04-22 03:55:15
2
556
Paul Fleming
76,077,814
1,938,410
The simplest and most pythonic way to test if a variable is between two other variables?
<p>I have two variables <code>n1</code> and <code>n2</code>, without knowing which is bigger. I want to test if <code>n</code> is between <code>n1</code> and <code>n2</code>.</p> <p>While I can definitely test <code>if min(n1, n2) &lt; n &lt; max(n1, n2)</code>, I am just curious if there is any more pythonic way to do...
<python>
2023-04-22 03:03:56
3
507
SamTest
76,077,754
11,737,958
How to pack a button in custom area of window
<p>I am new to python. I am using python 3.10 version. I created a window with two buttons using tkinter. I need to place the buttons in custom area rather than any sides which tkinter choose. I dont want to use &quot;place&quot; method. How to place the buttons with specific coordinates using pack?</p> <p>Thanks in ad...
<python><tkinter>
2023-04-22 02:35:24
1
362
Kishan
76,077,714
10,173,383
install_python() raises Error in setwd(root) : cannot change working directory
<p>I was following the code at <a href="https://tensorflow.rstudio.com/install/" rel="nofollow noreferrer">https://tensorflow.rstudio.com/install/</a>. Then I encountered the following error that stopped me from continue.</p> <pre><code>&gt; library(reticulate) &gt; path_to_python &lt;- install_python() Error in setwd(...
<python><r><reticulate>
2023-04-22 02:19:46
0
435
J.Z.
76,077,605
754,136
Handling exceptions and CTRL+C in python multiprocessing and multithread
<p>My code does the following:</p> <ul> <li>Starts processes to collect data</li> <li>Starts processes to test model</li> <li>One thread takes care of aggregating the data to train the model</li> <li>One thread aggregates the test results</li> </ul> <p>I need to handle exceptions such that if the training thread fails ...
<python><multithreading><exception><multiprocessing>
2023-04-22 01:29:38
2
5,474
Simon
76,077,561
469,224
CPython: Understanding the difference between tp_dealloc and tp_finalize
<p>After reading the documentation for both <a href="https://docs.python.org/3.11/c-api/typeobj.html#c.PyTypeObject.tp_dealloc" rel="nofollow noreferrer">tp_dealloc</a> and <a href="https://docs.python.org/3.11/c-api/typeobj.html#c.PyTypeObject.tp_finalize" rel="nofollow noreferrer">tp_finalize</a>, and the finalizatio...
<python>
2023-04-22 01:09:09
1
373
iustin
76,077,346
8,954,291
Python semisort list of objects by attribute
<p>I've got a list of an object:</p> <pre class="lang-py prettyprint-override"><code>class packet(): def __init__(self, id, data): self.id, self.data = id, data my_list = [packet(1,&quot;blah&quot;),packet(2,&quot;blah&quot;),packet(1,&quot;blah&quot;),packet(3,&quot;blah&quot;),packet(4,&quot;blah&quot;)]...
<python><sorting><data-partitioning>
2023-04-21 23:41:11
1
1,351
Jakob Lovern
76,077,335
13,079,519
Gurobi variable creation giving different name than what I input
<p>I am trying to figure out why my gurobi variable name is different from what I input.</p> <p>Here is my code:</p> <pre><code>v_dc_mfc_wc = m.addVars(total_wc, name=v_dc_mfc_weightcube, vtype=GRB.BINARY) </code></pre> <p>where</p> <pre><code>v_dc_mfc_weightcube = ['v1_Pennsylvania_BKN-2'] total_wc = len(v_dc_mfc_weig...
<python><optimization><gurobi>
2023-04-21 23:38:32
0
323
DJ-coding
76,077,205
15,525,854
Join inner directories with parent directory
<p>Given this directory structure:</p> <pre><code>└── names ├── name1 │ └── subdir1 │ ├── subnames │ │ └── cool │ │ ├── another-subdir1 │ │ │ ├── file │ │ │ │ ├── file.txt │ │ │ ├── subnames │ │ │ │...
<python><file><filesystems>
2023-04-21 23:00:02
3
384
ayuuk ja'ay
76,077,166
6,296,626
Python Tkinter listbox color individual word
<p>From <a href="https://stackoverflow.com/questions/5348454">this answer</a> I know how to color individual items in a <code>listbox</code>. However, is it possible to color individual words/characters inside the item of a Tkinter <code>listbox</code>?</p> <p>If yes, how to achieve that?</p> <p>If no, is there a way t...
<python><tkinter><textbox><listbox><customtkinter>
2023-04-21 22:45:20
1
1,479
Programer Beginner
76,077,118
16,363,897
Fast way to implement a polynomial regression on each pandas dataframe row
<p>I have the following pandas dataframe:</p> <pre><code>df = pd.DataFrame({0: [11, 12, 31], 1: [6, 14, 27], 2: [11, 24, 21], 3: [1, 24, 20]}) 0 1 2 3 0 11 6 11 1 1 12 14 24 24 2 31 27 21 20 </code></pre> <p>For each row at the time, I want to implement a polynomial regression, where column nam...
<python><pandas><numpy>
2023-04-21 22:30:12
1
842
younggotti
76,077,047
8,340,881
looping through each row of snowpark/pyspark dataframe and concatenating list of dataframes
<p>I have a PySpark/Snowpark dataframe called df_meta. I want to loop through each row of <code>df_meta</code> dataframe and create a new dataframe based on the query and appending to an empty list called new_dfs. Once the looping is complete, I want to concatenate those list of dataframes. I have the below code which ...
<python><apache-spark><pyspark><snowflake-cloud-data-platform>
2023-04-21 22:15:28
1
1,255
Shanoo
76,076,846
13,448,665
How can I use the Python debugger (with breakpoints) while using the interactive mode in VS Code?
<p>Here is a simplified example to show the problem I have in VS Code:</p> <pre class="lang-py prettyprint-override"><code>#%% cell 1 import time def myfunc(): a = 5 # &lt;-- Put breakpoint here b = 0 return a/b #%% cell 2 t = time.time() print(&quot;started at&quot;, t) myfunc() </code></pre> <p>I put a...
<python><python-3.x><visual-studio-code><vscode-debugger>
2023-04-21 21:35:55
1
361
BinaryMonkey
76,076,783
651,174
Set operations for filter values
<p>Let's say I have a list column and I want to apply a filter to it. Here are the values in the column:</p> <pre><code>row People -------------------- 1 ['Veli'] 2 ['David'] 3 ['David', 'Veli'] 4 ['George'] 5 ['David', 'George'] </code></pre> <p>The user selects the values <code>Veli</code> and <code>David<...
<python><set>
2023-04-21 21:24:03
2
112,064
David542
76,076,695
6,218,849
Given events with start and end timex, how merge events closer than a threshold?
<p>I have a data frame <code>capsules</code> that hold events localized in time:</p> <pre><code> Start End 0 2022-01-05 04:35:00 2022-01-05 04:45:00 1 2022-02-04 21:05:00 2022-02-04 21:15:00 2 2022-03-09 04:35:00 2022-03-09 04:45:00 3 2022-03-09 04:35:00 2022-03-09 04:45:00 4 2022-0...
<python><pandas>
2023-04-21 21:04:52
1
710
Yoda
76,076,610
16,179,502
Elastic Beanstalk ModuleNotFoundError Flask App
<p>I am trying to deploy my flask app to EB. My current structure is as follows:</p> <pre><code>requirements.txt backend/ __init__.py application.py configurations/ __init__.py </code></pre> <p>With the core part of my <code>application.py</code> looking something like</p> <pre><code>from flask import Fl...
<python><flask><amazon-elastic-beanstalk>
2023-04-21 20:48:19
0
349
Malice
76,076,547
7,384,676
Glue Spark Converting string to datetime - Unable to create Parquet converter for data type "timestamp" whose Parquet type is optional binary
<p>I am trying to read in partitioned parquet files. And convert a parquet string in this format: <code>2023-12-10T11:00:00.826+0000</code> to a timestamp. I am using this command:</p> <pre><code>df = df.withColumn( &quot;etaTs&quot;, to_timestamp(col(&quot;etaTs&quot;), &quot;yyyy-MM-dd'T'HH:mm:ss.SSS...
<python><apache-spark><pyspark><apache-spark-sql><aws-glue>
2023-04-21 20:36:08
1
3,634
Ian Wesley
76,076,494
3,380,902
apply custom color scale to pydeck h3hexagon layer
<p>I am using pydeck to render a visualization using spatial data. I was hoping to use a custom color scale and apply the gradient to the hexagons based on counts.</p> <p>here's some <code>json</code> data:</p> <pre><code>[{&quot;count&quot;: &quot;12&quot;, &quot;hexIds&quot;: [&quot;82beeffffffffff&quot;]}, {&quot;co...
<python><geospatial><deck.gl><pydeck>
2023-04-21 20:21:46
1
2,022
kms
76,076,330
7,700,802
Cannot import Forecaster from greykite
<p>I try running this</p> <pre><code>from greykite.framework.templates.forecaster import Forecaster </code></pre> <p>and I get this error</p> <pre><code>ImportError: cannot import name 'Literal' from 'statsmodels.compat.python' (/home/user/anaconda3/lib/python3.8/site-packages/statsmodels/compat/python.py) </code></pre...
<python><time-series>
2023-04-21 19:50:03
0
480
Wolfy