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,111,464
1,942,868
Celery and Redis, Cannot connect to redis://redis:6379/0
<p>I am installing celery according to this <code>[article][1]</code>.</p> <pre><code> pip install &quot;celery[redis]&quot; </code></pre> <p>Then made tasks.py</p> <pre><code>from celery import Celery app = Celery('tasks', broker='redis://redis:6379/0') app.conf.result_backend = 'redis://localhost:6379/0' @app.task ...
<python><redis><celery>
2023-04-26 13:39:37
1
12,599
whitebear
76,111,121
9,690,041
When is xarrays `xr.apply_ufunc(...dask='parallelized')` fast?
<p>I open data from the ERA5 Google Cloud Zarr archive. I do some refactoring (change time resolution, select Northern Hemisphere only, etc.), where the operations are applied on dask data.</p> <p>This is how the xarray DataArray looks like:</p> <p><a href="https://i.sstatic.net/SaJn3.png" rel="nofollow noreferrer"><im...
<python><numpy><dask><python-xarray><large-data>
2023-04-26 13:07:33
1
335
jspaeth
76,110,977
716,237
Long-running jupyter notebook can't connect. Don't want to lose all my work
<p>I've had a jupyter notebook running for a week training a ML model. Usually I can tap the dropdown &quot;Reconnect&quot; when I need to check in on it. Now jupyter just started giving an error saying it can't connect. I don't want to restart it and lose all my progress, then likely have the same thing happen again!<...
<python><amazon-web-services><machine-learning><jupyter-notebook>
2023-04-26 12:52:53
1
6,891
Tyler
76,110,964
3,521,180
how to write a update method to update each cell of a table
<p><a href="https://i.sstatic.net/GG7Hy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GG7Hy.png" alt="enter image description here" /></a>I have scratched every single hair on my head, but able to come to any conclusion about writing an &quot;UPDATE&quot; query for a given scenario. I have a request bo...
<python><sql><python-3.x><flask>
2023-04-26 12:51:36
0
1,150
user3521180
76,110,928
7,559,397
Import could not be resolved, the module is user built, but the code runs
<p>I have a directory and the structure of two files is below</p> <pre><code>python/solver-tic-tac-toe.py python/players.py </code></pre> <p>I have this for my import statement in <code>solver-tic-tac-toe.py</code></p> <pre><code>import players </code></pre> <p>But I get from VSCode</p> <pre><code>Import &quot;players&...
<python><visual-studio-code><python-import>
2023-04-26 12:47:52
1
1,335
Jinzu
76,110,842
801,618
How am I misunderstanding Django's get_or_create function?
<p>We have a Django project that has a bunch of experiments, and each experiment can have zero or more text tags. The tags are stored in a table, and there is a many-to-many relationship between experiments and tags:</p> <pre class="lang-python prettyprint-override"><code>class Tag(models.Model): text = models.Text...
<python><django>
2023-04-26 12:39:16
1
436
MerseyViking
76,110,833
2,825,570
Python Selenium - How to select a tab in a page
<p>The following image is the code of tabs present in a web page: <a href="https://i.sstatic.net/M54VH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/M54VH.png" alt="enter image description here" /></a> The tab names are <code>Overview</code>, <code>Information</code>, and <code>Audit</code> (Kindly ref...
<javascript><python><html><jquery><selenium-webdriver>
2023-04-26 12:38:37
1
8,621
Jeril
76,110,677
10,721,627
How to get the operating system information from python docker container?
<p>Docker images can inherit from other images. Therefore, using the official Python docker image allows running Python applications and tools.</p> <pre><code>docker run --rm -it python bash </code></pre> <p>After creating and running an interactive container from the <a href="https://hub.docker.com/_/python" rel="nofo...
<python><docker><dockerfile>
2023-04-26 12:23:04
1
2,482
Péter Szilvási
76,110,402
1,900,520
How to do ewm_mean in rust polars?
<p>In python we can do:</p> <pre><code>df.with_columns([ pl.col(&quot;myCol&quot;).ewm_mean(50) ]) </code></pre> <p>But how do we do the same in rust? The following doesn't work:</p> <pre><code>df.with_columns([ col(&quot;myCol&quot;).ewm_mean(50) ]) </code></pre> <p>It fails with <code>No method named ewm_mean...
<python><rust><python-polars><rust-polars>
2023-04-26 11:51:25
1
8,089
Corvus
76,110,394
20,646,427
A lot of similar queries bcs of for loop Django
<p>I have for loop in my <code>get_queryset</code> function and i'm parsing info from request into my django template but for some reason bcs i try to filter by GUID i got 21 similiar sql queries</p> <p>I was trying to get CleanSections before my for loop but that didnt help</p> <p>Any tips how can i solve that?</p> <p...
<python><sql><django>
2023-04-26 11:50:09
1
524
Zesshi
76,110,329
2,838,281
Iterating over LLM models does not work in LangChain
<p>I am trying to instantiate LangChain LLM models and then iterate over them to see what they respond for same prompts.</p> <pre><code>from langchain.llms import OpenAI, HuggingFaceHub from langchain import PromptTemplate from langchain import LLMChain import pandas as pd bool_score = False total_score = 0 count = 0 ...
<python><openai-api><huggingface><langchain>
2023-04-26 11:43:51
2
505
Yogesh Haribhau Kulkarni
76,110,282
9,681,081
SQLAlchemy: get Index object for a given column with index=True
<p>How can I get an SQLAlchemy <code>Index</code> object corresponding to a column that has <code>index=True</code>?</p> <p>For example, in the code below, I'd like to have the <code>Index</code> associated to <code>MyTable.name</code>.</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy.orm import Decl...
<python><indexing><sqlalchemy>
2023-04-26 11:39:33
1
2,273
Roméo Després
76,110,267
11,837,399
Firestore warning on filtering with positional arguments. How to use 'filter' kwarg in Firestore queries?
<p>Firestore started showing</p> <pre><code>UserWarning: Detected filter using positional arguments. Prefer using the 'filter' keyword argument instead. </code></pre> <p>when using <code>query.where(field_path, op_string, value)</code> while it's the the method from the official docs <a href="https://cloud.google.com/f...
<python><google-cloud-firestore>
2023-04-26 11:37:49
5
795
syldman
76,110,009
3,596,355
__getitem__ only gets called if __iter__ is defined
<p>I am subclassing a dict and would love some help understanding the behavior below (please) [Python version: 3.11.3]:</p> <pre><code>class Xdict(dict): def __init__(self, d): super().__init__(d) self._x = {k: f&quot;x{v}&quot; for k, v in d.items()} def __getitem__(self, key): print(&...
<python><dictionary><subclass>
2023-04-26 11:05:51
1
319
pauleohare
76,109,951
10,323,453
Panda create csv with dictionary column
<p>I am try to create csv file with dictionary column but when I read it, that column is string not dictionary data type.</p> <pre><code>splittrain.to_csv(&quot;SQuAD_tain.csv&quot;,index=False) </code></pre> <p>splittrain is DataFrame. answers column have a dictionary data. when check type by using <code>type(splittra...
<python><pandas><csv><dictionary>
2023-04-26 10:59:39
1
395
Ind
76,109,899
2,281,274
Tracing (step-by-step) some other function call in pdb
<p>I'm in the middle of tracing in PDB, at some line. I want to call other function (<code>foo</code>) to see result. I can do it by just typing <code>foo()</code>.</p> <p>But I want to 'step' into <code>foo</code>. How can I do it?</p> <p>(To clarify, current line does not contain <code>foo</code> calls).</p>
<python><pdb>
2023-04-26 10:52:08
1
8,055
George Shuklin
76,109,710
14,535,309
Why adding index to django model slowed the exectuion time?
<p>I've added the index to my django model in order to make the queries on it a little bit faster but the execution time actually went up:</p> <pre><code>from autoslug import AutoSlugField from django.db import models class City(models.Model): name = models.CharField(max_lenght=30) population = models.Integer...
<python><django><database><django-models><optimization>
2023-04-26 10:25:54
1
2,202
SLDem
76,109,641
9,182,743
Python: get data into dataframe by clicking on plot
<p>I have a dataframe with:</p> <ul> <li><strong>time</strong>: unix time with freq = 4Hz</li> <li><strong>signal</strong>: a signal here simulated with n number of square waves (real signal more noisy/complex)</li> <li><strong>derr_1</strong>: signal derivative used to better classify signal types.</li> </ul> <h1>Obje...
<python><pandas><numpy>
2023-04-26 10:19:26
1
1,168
Leo
76,109,578
2,587,422
Searching a large DataFrame with a MultiIndex slow
<p>I have a large Pandas DataFrame (~800M rows), which I have indexed on a <code>MultiIndex</code> with two indices, an int and a date. I want to retrieve a subset of the DataFrame's rows based on a list of ints (about 10k) that I have. The ints match the first index of the multi-index. The multi-index is unique.</p> <...
<python><pandas><dataframe><multi-index>
2023-04-26 10:12:26
2
315
Luigi D.
76,109,550
12,349,101
Tkinter - Binding Keyboard keys to elements / items on Canvas
<p>I already know you can bind keys to widgets, or bind Mouse click to elements on a Canvas (eg: rectangle, line, etc), example for the latter:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk class App: def __init__(self, master): self.master = master self.canvas = tk.Canv...
<python><python-3.x><tkinter>
2023-04-26 10:08:20
1
553
secemp9
76,109,469
468,921
python find the largest number in a glob of filenames
<p>in a glob of filenames, I need to find the largest number.</p> <p><em>model_dir.glob('weights_epoch_*.tf.index')</em> returns a generator, but then what?</p> <pre><code>/home/rac/amf9-horizon/weights_epoch_1.tf.index /home/rac/amf9-horizon/weights_epoch_10.tf.index /home/rac/amf9-horizon/weights_epoch_15.tf.index /h...
<python><tensorflow><pathlib>
2023-04-26 10:00:06
2
1,553
Antti Rytsölä
76,109,079
20,240,835
snakemake threads wildcards not found
<p>I have a snakemake rule like:</p> <pre><code>rule get_coverage: input: cram=lambda wildcards: expand(config['input']['cram'][wildcards.reference_genome], #access_id = access_id[wildcards.sample_name], sample_name='{sample_name}'), bai=lambda wildcards: e...
<python><bioinformatics><snakemake>
2023-04-26 09:18:10
1
689
zhang
76,108,876
9,018,649
Which packages are required to put in requirements.txt when publishing a python azure function by remote build?
<p>This explains that you dont need some azure packages: <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python?pivots=python-mode-configuration&amp;tabs=asgi%2Capplication-level#azure-functions-python-worker-dependencies" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/...
<python><azure><deployment><package><azure-functions>
2023-04-26 08:50:53
1
411
otk
76,108,849
11,945,144
How to recommend recurring action
<p>I have a dataset that contains the following columns: <code>id_customer</code> (customer identifier), <code>id_receiver</code> (identifier of the person who receives the money), <code>money</code> (money sent), and the <code>date</code> the money was sent. I need to know which customers recurrently send money to the...
<python><dataframe><time-series><recommendation-engine><recurrent>
2023-04-26 08:47:27
1
343
Maite89
76,108,829
843,075
os.getenv() returns None after setting environment variables
<p>I am following simple tutorial which requires setting up of environment variables. I have set a few in the following way:</p> <pre><code>C:\Users\fsdam&gt;set GITHUB_USERNAME=damaf C:\Users\fsdam&gt;set GITHUB_USERNAME GITHUB_USERNAME=damaf </code></pre> <p>When I check this setting in Python, <code>None</code> is...
<python><windows><environment-variables>
2023-04-26 08:45:05
1
304
fdama
76,108,710
8,849,755
Python.h fails importing package
<p>I am using <code>Python.h</code> in C++ to run some Python code. Since I have no access to the <code>main</code> function, I am doing everything in my own function which gets called at some point. I am experiencing a weird failure when importing a package which unfortunately cannot reproduce in an external MWE. My c...
<python><c++>
2023-04-26 08:31:04
0
3,245
user171780
76,108,627
5,334,903
Defining classes in ontology, instanciating individuals in namespace
<p>Using Owlready2, how to define classes attached to the ontology (on this base iri: <a href="http://example.com/ontology/item/1.1#" rel="nofollow noreferrer">http://example.com/ontology/item/1.1#</a>) and when an individual is created, it would be defined on other iri (like: <a href="http://example.com/profile/item/r...
<python><owl><ontology><owlready>
2023-04-26 08:21:58
1
955
Bloodbee
76,108,471
15,560,990
Can you pass Airflow templated variables with their actual type into Operators?
<p>I know that you can pass templated variables as string into operators, but I'd like to pass them around as their actual type. For example, if I have (trivial function just to illustrate my point)</p> <pre><code>def get_day(datetime_object): return datetime_object.day </code></pre> <p>And a DAG with task</p> <pre...
<python><airflow><jinja2>
2023-04-26 08:04:57
2
460
Dasph
76,108,457
3,238,679
Scatter plot toy examples to benchmark a correlation coefficient
<p>I am interested in benchmarking a coefficient and would like to see some toy examples. I came across <a href="https://en.wikipedia.org/wiki/Pearson_correlation_coefficient" rel="nofollow noreferrer">this</a> link which includes the following image. Would anyone happen to know of a Python toolkit or be able to provid...
<python><matplotlib><pearson-correlation>
2023-04-26 08:02:46
1
1,041
Thoth
76,108,417
283,538
python plotly to javascript plotly
<p>I would like to stay away from JavaScript and focus on analytics. Can I develop plotly graphs in Python (e.g. in Jupyter notebooks) and simply use the <a href="https://plotly.github.io/plotly.py-docs/generated/plotly.io.write_html.html" rel="nofollow noreferrer">write_html</a> function for developers to integrate in...
<javascript><python><plotly>
2023-04-26 07:58:38
1
17,568
cs0815
76,108,348
20,612,566
Custom OrderingFilter Django REST + Vue
<p>I'm working on backend part of project (Django REST). I have a task - to do sorting for the front (Vue). The frontend sends a key for sorting and a parameter for sorting.</p> <p>Example:</p> <pre><code>GET /api/v1/stocks/?sort_key=FBS&amp;sort_type=ascending GET /api/v1/stocks/?sort_key=FBS&amp;sort_type=descending ...
<python><django><django-rest-framework><django-filters>
2023-04-26 07:50:27
2
391
Iren E
76,108,341
2,324,298
Is it possible to get feature importance in CatBoost for a prediction
<p>I want to know the feature importance for a particular prediction made by the CatBoost model. I know we can get feature importance at the data set level but I want to see if we can do so at each prediction level.</p>
<python><catboost>
2023-04-26 07:49:17
1
8,005
Clock Slave
76,108,321
210,559
Pyspark Aggregation of an array of structs
<p>I have the following schema in pyspark:</p> <pre><code>root |-- id: string (nullable = true) |-- data: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- id: string (nullable = true) | | |-- name: string (nullable = true) | | |-- seconds: decimal(38,18) (nullable =...
<python><apache-spark><pyspark><apache-spark-sql><aggregate-functions>
2023-04-26 07:46:16
1
9,488
Scott
76,108,305
17,896,651
TK to run django server on windows
<p>I have windows server running Django as a CMD process.</p> <p>Some PC USERS mistakenly closing it.</p> <p>I want to switch to TK running the Django server and put output on screen.</p> <p>How safe is that ?</p> <p>How do I close the django properly ?</p> <pre><code>class TextRedirector(object): def __init__(self...
<python><django><tkinter><tk-toolkit>
2023-04-26 07:45:20
0
356
Si si
76,108,250
14,485,257
How to only remove rows with NaN that are not at the beginning or end of the pandas Dataframe column?
<p>I have a pandas dataframe. It has a particular column which may or may not contain a continuous set of values as NaN's in its starting and ending. Also, it may or may not contain NaN's intermittently in between as well.</p> <p>My objective is to eliminate only all those rows where NaN's may intermittently be present...
<python><pandas><dataframe><numpy><nan>
2023-04-26 07:38:13
1
315
EnigmAI
76,108,240
10,829,044
Pandas column replace multiple special characters and insert new characters
<p>I have a pandas dataframe like as below</p> <pre><code>Country_list {'INDIA': '98.31%', 'ASEAN': '1.69%'} {'KOREA': '100.0%'} {'INDIA': '95.00%', 'ASEAN': '2.50%','ANZ': '2.50%'} {'INDIA': '95.00%', 'ASEAN': '2.50%','ANZ': '1.25%','KOREA': '1.25%'} </code></pre> <p>I would like to do the below</p> <p>a) Replace al...
<python><pandas><dataframe><replace><series>
2023-04-26 07:36:07
3
7,793
The Great
76,108,171
8,921,867
Why does SQLAlchemy recommend using built-in `id` as column name?
<p>Using reserved keywords or built-in functions as variable/attribute names is commonly seen as <a href="https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python">bad practice</a>. However, the SQLALchemy <a href="https://docs.sqlalchemy.org/en/20/orm/quickstart.html" rel="noreferrer">tutorial</a>...
<python><sqlalchemy>
2023-04-26 07:27:26
1
2,172
emilaz
76,108,133
8,996,032
Python script to read csv-file from `inst` folder within custom R package
<p>I am building a R package that uses a Python script which in turn loads internal data. Both the py-script (<code>load_csv.py</code>) as well as the data (<code>data.csv</code>) are located in the <code>inst/</code> folder of the package directory.</p> <pre><code>import pandas as pd my_df = pd.read_csv(&quot;inst/dat...
<python><r><reticulate>
2023-04-26 07:21:56
1
1,163
Ben Nutzer
76,107,909
5,338,465
When should I use asyncio.create_task?
<p>I am using Python 3.10 and I am a bit confused about <code>asyncio.create_task</code>.</p> <p>In the following example code, the functions are executed in coroutines whether or not I use <code>asyncio.create_task</code>. It seems that there is no difference.</p> <p>How can I determine when to use <code>asyncio.creat...
<python><python-3.x><task><python-asyncio><coroutine>
2023-04-26 06:51:40
1
1,050
Vic
76,107,844
10,753,968
SqlAlchemy StaleDataError on simple update statement
<p>I'm trying to update a user in the database but keep running into a <code>StaleDataError</code>.</p> <pre><code>user = session.query(User).get(1) user.first_name # John user.first_name = 'Sally' session.commit() # &gt; sqlalchemy.orm.exc.StaleDataError: UPDATE statement on table 'user' expected to update 1 row(s); ...
<python><sqlalchemy><orm>
2023-04-26 06:38:51
1
2,112
half of a glazier
76,107,800
5,501,591
UnicodeDecodeError: while trying to print dictionary
<p>I get a UnicodeDecodeError trying to execute the below code in python 3.6.12</p> <pre><code>import csv fh = open('./testLog.log', 'r') d = csv.DictReader(fh, delimiter=&quot; &quot;) for row in d: print(row) fh.close() </code></pre> <blockquote> <p>File &quot;/opt/rh/rh-python36/root/usr/lib64/python3.6/encodi...
<python>
2023-04-26 06:31:34
1
303
Ahtesham Akhtar
76,107,677
676,192
Combine two images with a mask in python/cv2
<p>I have three images:</p> <p>warp.png</p> <p><a href="https://i.sstatic.net/BnSWJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BnSWJ.png" alt="enter image description here" /></a></p> <p>weft.png</p> <p><a href="https://i.sstatic.net/cibb7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.n...
<python><opencv><image-processing>
2023-04-26 06:11:23
2
5,252
simone
76,107,595
4,451,521
title and labels in seaborn are on the border
<p>I am doing a simple displot with seaborn</p> <p>However when I do</p> <pre><code>ax2=sns.displot(outlist) ax2.set(xlabel='Rate(Hz)', title='Distribution of publication rates') </code></pre> <p>I got</p> <p><a href="https://i.sstatic.net/8tdMO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8tdMO.png" ...
<python><seaborn>
2023-04-26 05:57:27
1
10,576
KansaiRobot
76,107,579
1,999,585
How do I correctly use the lower and upper bound in a linear programming problem, in Python?
<p>I have the following Python code:</p> <pre><code>from scipy.optimize import linprog f = [612.03, 619, 617.13, 923] A = [[-94, -96, -94.3, -118.6], [-83.7, -83, -87.6, -89.7], [1.02, 0.51, 0, 0], [203.9, 214.5, 27.88, 78.2], [53.6, 70.7, 71.5, 5.95], [14.9, 0, 0, 0], [35.1, 73.7, 0, 0],...
<python><scipy><linear-programming><scipy-optimize>
2023-04-26 05:54:42
1
2,424
Bogdan Doicin
76,107,570
122,536
pyautogui sometimes doesn't switch windows in the following code
<p>I'm using this function to switch windows, to simulate Alt + Tab:</p> <pre><code>import time import pyautogui def switch_windows(): pyautogui.keyDown('alt') pyautogui.press('tab') pyautogui.keyUp('alt') </code></pre> <p>It works most of the time. But sometimes I get stuck in the terminal and a <code>^[<...
<python><pyautogui>
2023-04-26 05:53:49
1
55,665
wyc
76,107,515
1,595,350
How to get Blocks and Child Blocks for a Page in Notion?
<p>I have a page <code>https://www.notion.so/Wiki-Page-For-a-Business-Case-8ec70cd1894711a862acc61a47fdb74d</code>.</p> <p>I would like to access this page through Python an extract its blocks. I have added successfully the Connection, received the API Key but i cannot access a site by its url or anything else through ...
<python><notion-api><notion>
2023-04-26 05:44:33
1
4,326
STORM
76,107,458
2,802,576
Pandas Convert a complex datastructure to Dataframe
<p>I am querying an API and got the response like below</p> <pre><code> { &quot;data&quot;: { &quot;items&quot;: [ { &quot;outername&quot;: &quot;OuterNameValue1&quot;, &quot;value&quot;: { &quot;columns&quot;: [ { &quot;innername&quot;: &quot;innernameval...
<python><pandas><dataframe>
2023-04-26 05:30:03
2
801
arpymastro
76,107,450
5,091,720
Flask AttributeError: module 'flask.json' has no attribute 'JSONEncoder'
<p>My flask app was working prior to upgrades. I was having trouble with sending email when there was a forgot-reset-password. To try and fix this I recently upgraded some modules for my flask app. The modules that I upgraded with current versions are:</p> <ul> <li>email-validator==2.0.0.post2</li> <li>Flask==2.3.1</li...
<python><flask>
2023-04-26 05:29:05
8
2,363
Shane S
76,107,382
11,148,296
Default values in class inheritance
<p>I came across this code from Azure Python SDK</p> <pre class="lang-py prettyprint-override"><code>class BlobConverter(meta.InConverter, meta.OutConverter, binding='blob', trigger='blobTrigger'): @classmethod def check_input_type_annotation(cls, pyty...
<python>
2023-04-26 05:18:29
1
1,660
Olsgaard
76,107,371
7,250,111
How to set different point sizes in VisPy?
<p>This is an example that I referred to : <a href="https://github.com/vispy/vispy/blob/d7763448dd398e5dab91cc21db7378c1aa707c63/vispy/visuals/line/line.py#L273" rel="nofollow noreferrer">https://github.com/vispy/vispy/blob/d7763448dd398e5dab91cc21db7378c1aa707c63/vispy/visuals/line/line.py#L273</a></p> <pre><code>clas...
<python><vispy>
2023-04-26 05:15:55
0
2,056
maynull
76,107,270
6,810,602
Wrong tuple size for returned value. Expected 23, got 13 in SNOWFLAKE Python UDTF function?
<p>I have registered a Python udtf. This udtf performs data processing using the <code>pandas</code> library - groupby and pivot operations for feature engineering process. At the end it returns 23 columns.</p> <p>When I call this udtf using the select statement and partition over by () command, it gives me the followi...
<python><snowflake-cloud-data-platform>
2023-04-26 04:52:05
1
371
Dhvani Shah
76,107,265
4,417,586
Write uploaded file by chunks in an async context
<p>I have a Python async function receiving a <a href="https://docs.djangoproject.com/en/4.2/ref/files/uploads/" rel="nofollow noreferrer"><code>django.core.files.uploadedfile.TemporaryUploadedFile</code></a> from an Django API endpoint, as well as from a Django form.</p> <p>Once this function/coroutine is launched, it...
<python><django><asynchronous><python-asyncio>
2023-04-26 04:51:25
0
1,152
bolino
76,107,214
14,109,040
Group by and diffrence timestamps in consecutive rows
<p>I have the following data frame with a list of periods and timestamps. I want to group by period and sort by timestamp (to make sure the observations are in chronological order within the periods), then difference the corresponding timestamps - to calculate the difference between the current observation and the next...
<python><pandas>
2023-04-26 04:38:58
1
712
z star
76,107,177
16,971,617
os walk with specific extension
<p>I want to loop through files with extension ends with CR2, CR3, cr2, cr3 (contain cr in the extensions) only. Currently, I am using os.walk() but people recommend to use pathlib which I can do something like <code>path.glob('*.jpg')</code> but still I cannot specify the desired condition. Is there a better way to do...
<python><pathlib>
2023-04-26 04:30:05
3
539
user16971617
76,107,092
6,653,602
Django using prefetch_related to reduce queries
<p>I am trying to understand how I can improve the following query:</p> <pre><code>class PDFUploadRequestViewSet(viewsets.ModelViewSet): def get_queryset(self): project_id = self.request.META.get('HTTP_PROJECT_ID', None) if project_id: return PDFUploadRequest.objects.filter(project_id=p...
<python><django><django-rest-framework>
2023-04-26 04:05:06
1
3,918
Alex T
76,106,963
6,539,586
Calling Different Function Based on Config
<p>I'm trying to build a framework that takes in a file with data and depending on the name of the file calls a different function to transform that data. I can handle all the mapping parts, so far I just have a yaml config that maps file patterns to a schema string that represents the file that contains the function (...
<python><function><import>
2023-04-26 03:26:26
0
730
zachvac
76,106,619
11,098,908
How to define a class that has a relationship with other classes
<p>I tried to define the class <code>Interaction</code> that had a relationship with other classes (<code>Teacher</code> and <code>Student</code>) as follows</p> <pre><code>class Teacher(Person): def __init__(self, age: int, subjects: list[Subject] | None = None) -&gt; None: super().__init__(age) if...
<python><class><oop>
2023-04-26 01:55:36
1
1,306
Nemo
76,106,554
15,542,245
Why a numpy array appears to have no shape?
<p>I understand the following:</p> <pre><code>import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) print(arr.shape) </code></pre> <p>Output:</p> <pre><code>(2, 4) </code></pre> <p>So I was wondering why I get the following:</p> <pre><code>import numpy import pytesseract import logging # Raw call does not...
<python><arrays><numpy><python-tesseract>
2023-04-26 01:35:53
2
903
Dave
76,106,550
3,398,324
Fill Missing value in Pandas Dataframe combined with Merge
<p>My dataframe has misaligned observations, that is the dates do not match because the columns are pairs of dates and values that were generated invidiually via API, like so:</p> <pre><code>data = {'Date.0': ['1/1/2022','1/2/2022', '1/3/2022','1/4/2022'], 'ABC Return': [11, 21, 31, 41], 'Date.1': ['1/1/2022','1/2/2022...
<python><pandas><dataframe>
2023-04-26 01:34:37
2
1,051
Tartaglia
76,106,372
2,192,824
What is the simplest way to count the occurrences of different numbers in a sorted array?
<p>For example there is a sorted array <code>[1,1,1,2,2,3,3,4,5,5]</code>, without using map/hashtable, just using index, how to check whether all different numbers have the same count? This example should return <code>False</code>, while <code>[1,1,3,3,6,6]</code> should return <code>True</code>. What would be the cod...
<python><arrays><algorithm>
2023-04-26 00:37:16
3
417
Ames ISU
76,106,273
1,444,564
Delphi, Python4Delphi, Anaconda, Oct2Py, and Octave on Windows
<p>I have a Delphi Win32 program that needs to run some scripts on Octave. I've taken the approach of going through Python4Delphi to get to a Python &quot;environment&quot;, where I can write and run scripts that access Octave via Oct2Py. In order to get Oct2Py to install, I gave up doing so with my Windows Python inst...
<python><delphi><octave><oct2py><python4delphi>
2023-04-26 00:06:39
1
723
Bob
76,106,117
2,476,219
Python resolve ForwardRef
<p>I have a typing.ForwardRef object as a remnant from earlier generic programming shenanigans. At this point I know the class represented by the ForwardRef exists, but how can I retrieve this type?</p> <p>A fairly minimal example of what I am doing. Convoluted solution for this example, but for the actual use case it ...
<python><generics>
2023-04-25 23:23:44
1
3,688
Aart Stuurman
76,106,109
219,153
Using "match" as a method name in Python class
<p>I have a Python class <code>Shape</code>, which can perform matching. I called the corresponding method <code>match</code>:</p> <pre><code>class Shape: ... def match(self, image): </code></pre> <p>and it is working, as far as I can tell. Is there a reason to avoid using <code>match</code> keyword as a method nam...
<python><naming-conventions><keyword>
2023-04-25 23:22:02
0
8,585
Paul Jurczak
76,106,024
7,175,945
Is there a way to get weights for interaction terms using `vowpalwabbit.Workspace.get_weight_from_name`?
<p>Consider the following workspace:</p> <pre class="lang-py prettyprint-override"><code>import vowpalwabbit # define our workspace, a contextual epsilon-greedy bandit with interaction terms model = vowpalwabbit.Workspace(&quot;--cb_explore_adf -b 20 -q UA --quiet --epsilon 0.20&quot;) # we learn on two examples mode...
<python><vowpalwabbit>
2023-04-25 23:00:25
0
1,071
Dascienz
76,106,015
13,763,436
Error when importing SciPy within an application
<p>I have a python application running on the latest Raspberry Pi OS (Debian version 11 (bullseye)) and I am getting an error when importing SciPy. The specific error is:</p> <pre><code>from scipy.linalg import _fblas ImportError: libf77blas.so.3: cannot open shared object file: No such file or directory </code></pre> ...
<python><scipy><raspberry-pi>
2023-04-25 22:59:13
1
403
stackoverflowing321
76,105,995
7,212,809
Two levels of sampling
<p>I have a bunch of <code>Thing</code>s.</p> <p>A <code>Thing</code> is a struct with a field, <code>source</code>, typed as a string.</p> <p>Currently I get a deterministic sampled selection of <code>Things</code> by simply hashing the Thing.</p> <pre><code>def is_thing_sampled(t: Thing): hashed_thing = my_determ...
<python><random><sampling>
2023-04-25 22:55:49
1
7,771
nz_21
76,105,951
3,285,014
Search and print result along with earlier information
<p>I have total 30 test result files, each having 12 iterations in it. The structure of the file is as below:</p> <p><strong>File1_loc/result.txt</strong></p> <pre><code># starting information # User information # Time stamps # Random infomration # Thousnads of lines in between # ----------------- Iteration 1 ---------...
<python><awk><sed>
2023-04-25 22:44:26
2
319
user3285014
76,105,937
2,903,532
Serve and request in the same python script
<p>I am trying to briefly spin up an HTTP server, so that I can call a subprocess that needs to access local files over HTTP, but running the server using the following code blocks further code from executing:</p> <pre class="lang-py prettyprint-override"><code>import http.server import socketserver PORT = 8000 Handl...
<python><http><concurrency><subprocess><kill>
2023-04-25 22:41:05
2
1,285
reynoldsnlp
76,105,921
2,016,632
How ephemeral is the storage of Docker Cloud Run - Can multiple browsers see the same data? Multiple threads?
<p>I have a large BigQuery where the data is a Json dictionary at each time stamp. When a user clicks upload data on a browser, an Ajax command is initiated to tell python to download from Bigquery, crack the Json, apply various user-determined FFT's, etc and then present data back to the user for display. This is all ...
<python><docker><google-cloud-platform><caching><bigdata>
2023-04-25 22:38:04
1
619
Tunneller
76,105,902
1,045,755
Returning Pandas DataFrame in FastAPI response model
<p>I am trying to return a Pandas DataFrame using FastAPI.</p> <p>My response model looks something like:</p> <pre><code>class Response(BaseModel): df: Dict date: str </code></pre> <p>I then have my function run, which creates a Pandas data frame, and a date, which I am currently trying to return via:</p> <pre>...
<python><pandas><dataframe><fastapi>
2023-04-25 22:34:57
1
2,615
Denver Dang
76,105,875
120,457
gitlab ci/cd piple shell script is not working out of python script
<p>The following script in gitlab ci/cd - but it works locally on runner machine. but when i try in gitlab it shows empty addres list - how tried array and everything its not working</p> <pre><code>script: - &gt; #!/bin/bash cd address; echo 'STARTING generate address'; address_list=$(python3...
<python><gitlab><git-bash><gitlab-ci-runner>
2023-04-25 22:31:04
0
35,235
joe
76,105,821
19,675,781
How to filter pandas dataframe by a feature value ending with Case sensitive letter
<p>I have a data frame like this: df:</p> <pre><code>C1 C2 Ford 11 ram 13 SUV 19 SEDAN 14 </code></pre> <p>I want to filter the data frame column C1 where the C1 values end with a upper case character. So the expected output looks like this:</p> <pre><code>C1 C2 SUV 19 SEDAN 14 </code></pre> <p>I tried dif...
<python><pandas><regex><dataframe>
2023-04-25 22:19:14
1
357
Yash
76,105,818
6,606,057
Observation Specific Confidence for Random Forests in R and Python
<p>I have a classification task for which I have a binary outcome -- however, I need to know the level of confidence in classifying each row (the row could be a observation, participant, subject, etc.).</p> <p>Confidence could be a residual for the row, specificity, sensitivity/Recall, or f-score for the decision node ...
<python><r><classification><binary-tree><random-forest>
2023-04-25 22:18:35
1
485
Englishman Bob
76,105,792
2,128,799
Using a pivot table to create a tree-like structure and how to create efficient queries?
<p>In our codebase we have a set of models that represent AI models and their training data. When people train new models they are usually trained off an existing AI model in the database, and we wanted to track a sort of &quot;versioning&quot; of these models, so that people can use prior versions, and create branchin...
<python><django><postgresql><django-rest-framework>
2023-04-25 22:12:11
1
1,294
Dash Winterson
76,105,751
4,431,535
Why does the python installed by conda's defaults report the wrong mac platform?
<p>I use <code>miniconda</code> on <code>macOS</code> Ventura (13.3). When doing an experiment recently, I found that <code>platform.platform()</code> called from <code>python</code> installed from the <code>defaults</code> channel reports a different (and incorrect) version of macOS compared to both the system python ...
<python><macos><conda>
2023-04-25 22:03:07
0
514
pml
76,105,738
231,670
How to mock a function imported from inside another function or method?
<p>I don't make a habit of this, but sometimes, in an effort to work around a circular import, I'll import a function from inside another function or method like this:</p> <pre class="lang-py prettyprint-override"><code>class MyClass: def my_method(self): from somewhere import the_thing x = the_thin...
<python><mocking><python-unittest>
2023-04-25 22:01:02
1
6,468
Daniel Quinn
76,105,697
5,049,813
Efficiently remove a maximum amount of binary elements while keeping row and column sums above a certain level
<p>I have the following problem and I'm having difficulty writing an optimized program for it.</p> <p>I'm given a 2D binary numpy array (all elements are either 0 or 1, and its shape is (n, m)), and I need to remove the maximum number of elements from the array, while maintaining the property that the sum of each row i...
<python><optimization>
2023-04-25 21:51:06
1
5,220
Pro Q
76,105,680
11,462,274
How transport the values of a specific column of a dataframe only to the first match of each combination?
<p><code>df_1</code> has the columns <code>team1</code> and <code>team2</code>, and <code>df_2</code> has the columns <code>runner_home</code> and <code>runner_away</code>.</p> <p>I would like that when the values of these columns are the same in any of the rows of both dataframes, then the value of the <code>odds</cod...
<python><pandas><dataframe>
2023-04-25 21:48:27
1
2,222
Digital Farmer
76,105,627
7,988,497
SQLModel many-many relationships not working
<p>I've been struggling with this for weeks now. Here's the relevant code:</p> <pre><code>Base = declarative_base() class Band_Genre(SQLModel, table=True): genre_id: Optional[int] = Field(default=None, foreign_key=&quot;FK_Band_Genre_Genre&quot;, primary_key=True) band_id: Optional[int] = Field(default=None, ...
<python><sqlalchemy><sqlmodel>
2023-04-25 21:39:46
1
1,336
MichaelD
76,105,551
688,080
For type hinting purposes, what are the advantages of np.typing.NDArrray over np.ndarray?
<p>If we check the source of numpy, we will find in <a href="https://github.com/numpy/numpy/blob/main/numpy/__init__.pyi#L1477" rel="nofollow noreferrer">numpy/__init__.py</a> that <code>ndarray</code> is declared as</p> <pre><code>class ndarray(_ArrayOrScalarCommon, Generic[_ShapeType, _DType_co]) </code></pre> <p>and...
<python><numpy><python-typing>
2023-04-25 21:26:49
1
4,600
Ziyuan
76,105,512
3,398,324
Convert daily returns to 2 day or 5 day returns
<p>This question was asked for prices but not for returns to my knowledge (not in Python at least). I would like to convert my given daily returns to other frequencies, like 2 day or 5 day returns.</p> <p>This is what I have:</p> <pre><code>data = {'date': ['1/1/2022','1/1/2022', '1/2/2022','1/2/2022'], 'ticker': ['A',...
<python><pandas><quantitative-finance>
2023-04-25 21:21:24
2
1,051
Tartaglia
76,105,430
10,504,481
Jupyter Iframe and Flask
<p>I wrote a Flask app that uses three.js and wanted to make it possible to view it from inside a Jupyter Notebook. The app is designed to run locally.</p> <p>What I'm currently doing is:</p> <pre class="lang-py prettyprint-override"><code>import dataclasses import socket import threading import webbrowser from zndraw...
<python><flask><jupyter-notebook><three.js>
2023-04-25 21:07:48
0
506
PythonF
76,105,385
8,807,152
Problem in usage of Apache AGE python driver after installation
<p>I am getting start with Apache AGE python driver and learning about it, at the current time I am exploring the samples that was provided on GitHub so I have decided to go on with an online jupyter platform to test on [google-colab] is the selected one, I have followed the installation guide so that at the beginning ...
<python><python-3.x><apache-age>
2023-04-25 20:58:54
3
1,263
rrrokhtar
76,105,355
881,224
Mypy Incompatible types in assignment when relying on dynamic access, expression has type "object"
<p>I would like to know why this isn't correct. Here is a small example that highlights the error:</p> <pre class="lang-py prettyprint-override"><code>import typing kwargs: dict = {} region, city, state = kwargs.get('region'), kwargs.get('city'), kwargs.get('state') ordered_params = [city, state, region] last = None ...
<python><python-typing><mypy>
2023-04-25 20:52:33
1
7,169
yurisich
76,105,340
2,729,922
PyFlink KafkaSink throws AttributeError: 'NoneType' object has no attribute 'startswith'
<p>I am trying to read a kafka topic and write the same in another kafka topic using KafkaSource/KafkaSink in pyflink (flink version 1.16). Reading from kafka topic works and I am able to print the result but when trying to send to kafka using KafkaSink I get the following exception:</p> <pre><code>NOTE: Picked up JDK_...
<python><apache-kafka><apache-flink><flink-streaming><pyflink>
2023-04-25 20:50:50
0
342
Monika X
76,105,330
12,368,238
Monitoring Lambda ephemeral storage use without Insights
<p>I'd like to monitor the usage of our Lambdas' ephemeral storage, but I don't want to use the UI tools like Lambda Insights. We currently have a log-scanning python script set up that reads the logs to attain runtime, memory use/limit, etc., but also to find specific things in the logs like code warnings, errors, and...
<python><amazon-web-services><aws-lambda><amazon-cloudwatchlogs><ephemeral-storage>
2023-04-25 20:48:32
1
514
autonopy
76,105,321
16,305,340
cv2.findContours() can't find the contours perfectly
<p>so I am trying to refill black holes in the image using contours, here is the original image:</p> <p><a href="https://i.sstatic.net/K2qBM.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/K2qBM.jpg" alt="enter image description here" /></a></p> <p>I then tried to use this code to fill this only small bl...
<python><opencv>
2023-04-25 20:47:57
1
1,893
abdo Salm
76,105,225
2,112,406
How to let python know where a certain library is?
<p>I compiled and installed LLVM from source to an arbitrary path: <code>/arbitrary/path/llvm</code>. I then compiled and installed a package that has a python module, and needs the LLVM libraries. When I try to import the module:</p> <pre><code>&gt;&gt;&gt; import module_name </code></pre> <p>I'm getting the error:</p...
<python><llvm>
2023-04-25 20:33:41
0
3,203
sodiumnitrate
76,105,218
523,612
Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library?
<p>I have seen many different things go wrong when trying to use the Tkinter standard library package, or its related functionality (turtle graphics using <code>turtle</code> and the built-in IDLE IDE), or with third-party libraries that have this as a dependency (e.g. displaying graphical windows with Matplotlib).</p>...
<python><tkinter><installation><modulenotfounderror>
2023-04-25 20:32:47
6
61,352
Karl Knechtel
76,105,056
1,006,183
Best way to exclude unset fields from nested FastAPI model response
<p>Assuming I have Pydantic-based FastAPI models similar to:</p> <pre class="lang-py prettyprint-override"><code>class Filter(BaseModel, extra=Extra.forbid): expression: str | None kind: str | None ... class Configuration(BaseModel): filter: Filter | None = {} .... </code></pre> <p>By default a mo...
<python><fastapi><pydantic>
2023-04-25 20:08:40
1
11,485
Matt Sanders
76,104,929
2,184,517
Python import cannot find module
<p>Brand new to python and can't manage to get my import resolved when I debug my test within vscode.</p> <p>Project structure:</p> <pre><code>a/b/c/d/service/functions/s3_proxy.py a/b/c/d/service/functions/__init__.py a/b/c/d/service/tests/test_s3_proxy.py a/b/c/d/service/tests/__init__.py </code></pre> <p><strong>te...
<python>
2023-04-25 19:54:02
3
1,840
AfterWorkGuinness
76,104,901
19,325,656
DRF return errors from model validation
<p>I have models and serializers. Errors that are returned from the serializer are helpful because I can send them as a response to API and user can correct invalid data.</p> <p>However, errors that are from models are useless for me. They return 500 error and they don't have a body that I can send back to the user.</p...
<python><django><django-models><django-rest-framework><django-serializer>
2023-04-25 19:49:39
1
471
rafaelHTML
76,104,852
4,772,836
Attribute error __aenter__ Airflow deferrable sensor
<p>So, basically I am trying to create a deferrable sensor in airflow by following the guide <a href="https://airflow.apache.org/docs/apache-airflow/stable/authoring-and-scheduling/deferring.html#writing-deferrable-operators" rel="nofollow noreferrer">here</a>.</p> <p>So, basically, my trigger's async run method has be...
<python><airflow><python-asyncio>
2023-04-25 19:43:14
0
1,060
Saugat Mukherjee
76,104,818
8,182,118
Why would you install your package in editable mode in order to test it?
<p>Some of the packaging / testing guides like <a href="https://simonwillison.net/2021/Nov/4/publish-open-source-python-library/" rel="nofollow noreferrer">Simon Willison's</a> use editable install to test, locally which is understandable (kind-of) but also on CI which it seems a lot less so?</p> <p>What are the advant...
<python><testing><continuous-integration>
2023-04-25 19:37:45
1
43,706
Masklinn
76,104,775
19,834,019
Separating coroutine generation and execution, ensuring proper closing
<p>I feel as if the answer to this should be simple, but I'm having trouble. First, I'll clarify that my understanding is that I want to deal with coroutines and not tasks as, to create a task is to automatically schedule something on the event loop. I just want to pass around coroutines that I can properly order to ac...
<python><python-3.x><async-await>
2023-04-25 19:31:03
1
303
Ambiguous Illumination
76,104,761
4,943,329
Strange behavior in Head pose estimation algorithm when face is moved away from center of image
<p>I am trying to perform head pose estimation (determine the yaw, pitch, and roll of a face image). I first do face and landmark detection to obtain the 2D face landmark coordinates. Using these coordinates, along with 3D reference face landmark coordinates, I use OpenCVs PnP algorithm, Rodrigues algorithm, and then d...
<python><opencv><computer-vision><euler-angles><opencv-solvepnp>
2023-04-25 19:29:23
1
1,311
cyrusbehr
76,104,708
11,331,843
Multi Thread execution for webscrapping with Selenium throwing errors - Python
<p>I have around 30k license numbers that I want to search from a website and extract all the relevant information from it When I tried the extracting the information from the function below by looping through multiple license_nums the code works fine and gives me what I am looking for</p> <pre><code># create a UserAge...
<python><python-3.x><multithreading><selenium-webdriver><web-scraping>
2023-04-25 19:21:00
1
631
anonymous13
76,104,702
1,914,781
append spliter row after rows which contains 'REL' in action column
<p>I would like to add a split row after row which continas &quot;REL&quot; keyword.</p> <pre><code>import pandas as pd data = [ [1,'ACQ','A'], [2,'REL','A'], [3,'ACQ','B'], [4,'REL','B'], [5,'ACQ','C'], [6,'REL','C'], [7,'ACQ','A'], [8,'REL','A'] ] df = pd.DataFrame(data,columns=['x...
<python><pandas>
2023-04-25 19:20:04
3
9,011
lucky1928
76,104,557
16,305,340
how to convert a single RBG color to YCbCr color space using opencv?
<p>so I am trying to convert a single RGB colour whose values is (232, 190, 172) to YCbCr color space using <a href="https://docs.opencv.org/3.4/d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab" rel="nofollow noreferrer">cv2.cvtColor()</a> but I get an error stating:</p> <pre><code>erro...
<python><opencv>
2023-04-25 18:58:51
1
1,893
abdo Salm
76,104,472
19,533,532
Python str.lower() causes memory leak
<p>Initially I've noticed this problem when I worked with a huge DataFrame, tried to apply to str.lower() to string-features and it cost me 10 GB of memory.</p> <p>I decided to investigate this problem on simplified example and that's what I've found:</p> <p>At first check how much memory a process takes:</p> <pre><cod...
<python><python-3.x><string><memory-leaks>
2023-04-25 18:46:41
1
528
mz2300