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
⌀
77,087,173
3,650,983
tqdm print average information in the end of the loop
<p>During the run tqdm print current information of the unit (in my case batch) like accuracy and loss.</p> <p>Is there an elegant way that after last iteration tqdm print in the same line the average accuracy/loss of all the batches that run?</p> <p>Now I'm doing in &quot;manually&quot; by saving the accuracy/loss dat...
<python><machine-learning><pytorch><torch><tqdm>
2023-09-12 08:09:27
0
4,119
ChaosPredictor
77,087,153
894,827
Extracting data from PDF files using python
<p>New to python here, and I have a challenge which is to extract order information presented in a PDF file. I can log onto the website to convert the orders onto PDF, however what I require is to export it into excel in the form of a table.</p> <p>The columns required are order number, order date, code, items, quanti...
<python>
2023-09-12 08:07:33
0
1,099
learner
77,087,129
13,087,576
Converting characters like '³' to Integer in Python
<p>I have this character '³' in my dataset that I'm processing on top of.</p> <p>Generic Idea is to detect if a character is an integer, convert it into an integer and process on top of it.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; x = '³' &gt;&gt;&gt; x.isdigit() # Returns True True </code></pre...
<python>
2023-09-12 08:05:02
1
307
Sai Prashanth
77,087,115
1,668,622
How do I avoid pollution of a .venv folder with files owned by root when running a script with root privileges?
<p>In virtual environment (created with poetry) I'm running a Python script regularly as current user via</p> <pre class="lang-bash prettyprint-override"><code>poetry run ./script.py </code></pre> <p>or</p> <pre class="lang-bash prettyprint-override"><code>.venv/bin/python3 script.py </code></pre> <p>From within this s...
<python><linux><root><pyc><file-ownership>
2023-09-12 08:02:48
0
9,958
frans
77,087,110
3,302,016
Rewrite apply function in pandas using simpe Dataframe calculation
<p>I have this piece of code which calculates the values of a column based on values of some existing columns on a pandas dataframe.</p> <pre><code>def get_prj_yield(row): try: prj_yield = row['prj_rev'] / (row['ds'] + row['otb_demand']) if pandas.isnull(prj_yield): prj_yield = row['ot...
<python><pandas><dataframe><apply>
2023-09-12 08:01:38
1
4,859
Mohan
77,087,063
13,238,846
Langchain pinecone similarity search error : Invalid type for variable 'namespace'
<p>I'm trying to getting work similarity search with Pincone's existing index. But I'm getting following error when passing the query. This is only happening on local machine. everything working fine in colab.</p> <pre><code>pinecone.core.client.exceptions.ApiTypeError: Invalid type for variable 'namespace'. Required v...
<python><callback><langchain><pinecone>
2023-09-12 07:53:54
2
427
Axen_Rangs
77,087,044
12,888,866
Python recursive dictionary value finder returns None
<p>I am working with multiple dictionaries which all have different depths and I am looking for the key <code>&quot;values&quot;</code> in all of them. I am not very familiar with recursive functions, but for this problem I attempted to write one. According to my print statements, the function arrives at the key I'm lo...
<python><dictionary><recursion>
2023-09-12 07:51:29
1
377
Timo
77,086,913
12,880,432
how to get split months from two intervals?
<p>I've two dates in YYYYmm format</p> <pre><code>start : 202307 end : 202612 </code></pre> <p>want to split them in interval wise, based on provided interval</p> <p>for example split_months <code>('202307,'202405',5)</code>, will give me</p> <pre><code>((202307,202311), (202312,202404), (202405,202405)) </code></pre> ...
<python><python-3.x>
2023-09-12 07:31:34
3
610
Maria
77,086,896
311,660
Adjusting the values in an array to be at least minimum distance apart
<p>I have an array of floats in a specific order</p> <pre><code>[99.3, 100.0, 98.6] </code></pre> <p>I need to ensure that they are a minimum distance apart, for this example say they must be at least 3 units apart. The maximum value should not be adjusted.</p> <p>The other values can all be adjusted to pass the spaci...
<python><arrays><python-3.x>
2023-09-12 07:29:25
1
30,444
ocodo
77,086,743
8,961,082
Airflow dag hanging on running state when interacting with AWS S3 bucket
<p>Simple Airflow DAGs are working for me, however, when I try to interact with an S3 bucket, the DAG will just hang on a running state. I'm using airflow S3 hook. If I run the code it will work but as a DAG it hangs. The function interacts with an API and saves the json file to an S3 bucket. Add your own bucket name t...
<python><amazon-s3><airflow><directed-acyclic-graphs>
2023-09-12 07:04:18
1
377
d789w
77,086,529
20,732,098
HTML Error Message will be returned instead of the custom JSON error message
<p>I have an API_1 that I call with Postman. If there is an error in the calculation, an error message will be output in JSON format, as well as the status code. I use the following code for this:</p> <pre><code>@app.errorhandler(Exception) def handle_default_error(e): message = e.description return jsonify(err...
<python><flask><pycharm>
2023-09-12 06:23:52
1
336
ranqnova
77,086,484
1,145,666
How do I get the body of a PUT request in SimpleHTTPRequestHandler
<p>I have this super simple HTTP server to test some REST endpoints:</p> <pre><code>import http.server class MyHandler(http.server.SimpleHTTPRequestHandler): def do_PUT(self): self.send_response(200) self.end_headers() def do_POST(self): self.send_response(409) self.end_headers...
<python><http.server>
2023-09-12 06:13:53
1
33,757
Bart Friederichs
77,086,419
956,424
multilevel user admin in django
<p>Need to create multi level users with roles having same validation for the models as that specified in admin.py, only that each of these users will have different roles.eg. Customer can have different custom_users with diff. roles. A customer can create multiple such custom users with different roles. Each customer ...
<python><django>
2023-09-12 05:59:26
1
1,619
user956424
77,086,208
8,089,312
x axis tick labels are one position ahead of data points
<p>I have a seaborn lineplot that shows two categories' quarterly count changes. The issue is that the x-axis labels are one position ahead of the data points. I adjusted my code, but it didn't help.</p> <p>Create example data</p> <pre><code>import pandas as pd import random import matplotlib.pyplot as plt import seabo...
<python><matplotlib><datetime><seaborn><xticks>
2023-09-12 04:56:22
2
1,744
Osca
77,086,128
8,595,891
How to pass worker options/parameters in gunicorn
<p>I am running an app which needed <code>uvicorn</code>'s asycio loop, by default it uses auto and some time it randomly assign it to <code>uvloop</code> whihc breaks the behavior. So I use the following command</p> <pre><code>uvicorn myapp.server.api:app --loop asyncio --port 7474 </code></pre> <p>This forces uvicorn...
<python><python-asyncio><fastapi><gunicorn><uvicorn>
2023-09-12 04:31:15
1
1,362
Pranjal Doshi
77,086,012
432,509
Python multiprocessing: how to constrain the amount of memory used by a Pool?
<p>When working on a script, you may wish to use all available cores for best performance.</p> <p>There are cases however, when each sub-process uses a lot of memory, where it may be useful to set a memory threshold for the pool to prevent each task in the tool from running out of memory or cause the system to swap.</p...
<python><multiprocessing>
2023-09-12 03:56:25
1
49,183
ideasman42
77,085,952
2,626,865
Should probabilities be managed outside of Hypothesis?
<pre class="lang-py prettyprint-override"><code>from hypothesis import strategies as st import random import time import math </code></pre> <p>Imagine your code expects a list sampling four elements. Some elements are more likely than others. You don't know the list's length, so you've modeled the list as a series of B...
<python><probability><python-hypothesis>
2023-09-12 03:38:14
1
2,131
user19087
77,085,915
14,154,784
JavaScript on Site Prevents `requests.get` from Working
<p>I’m trying to write a simple web-scraper, practicing on <a href="https://weighttraining.guide/exercises/standing-dumbbell-overhead-triceps-extension/" rel="nofollow noreferrer">this site</a> which has dynamic content.</p> <p>My strategy is to use Selenium to get the page source so I have all the dynamic content, the...
<python><selenium-webdriver><web-scraping><beautifulsoup><python-requests>
2023-09-12 03:27:06
1
2,725
BLimitless
77,085,879
1,492,229
LIME gives this error "classifier models without probability scores" in python
<p>it is my first time to use LIME and i have never used any interpretation technique before.</p> <p>most likeley i am doing something wrong but i cannot figure out what is it.</p> <p>I tried googling and go through SOF question to find the way to resolve this but did not find anything that can help me.</p> <p>my datas...
<python><nlp><lime>
2023-09-12 03:14:13
1
8,150
asmgx
77,085,832
1,471,980
how do you force write pandas styles to excel file in Pandas
<p>I have a data frame like this:</p> <p>df</p> <pre><code>Server CPU_Usage Memory Usage Prod1 80 30 Prod2 70 10 Prod3 20 12 </code></pre> <p>I need to apply Pandas Style to show % sign next to the numbers like below:</p> <pre><code>Server CPU_Usage Memory_Usage Prod1 80% 30%...
<python><pandas><pandas-styles>
2023-09-12 02:57:22
2
10,714
user1471980
77,085,817
12,394,134
Map user-defined function on multiple polars columns
<p>I am doing a bit of data munging on a <code>polars.Dataframe</code> and I could write the same expression twice, but I would ideally like to cut down on that a bit. So I was thinking that I could just create a user-defined function that just plugs in the column names.</p> <p>But, I know that polars tends to be a bit...
<python><python-polars>
2023-09-12 02:53:22
2
326
Damon C. Roberts
77,085,415
4,002,633
Python, Pandas, Dataframes: Inexplicable characteristic difference that I cannot identify
<p>In a code base that has worked wonderfully for a long time, suddenly I have a crash. I have traced it nominally to a Pandas idiosyncrasy that has be confused. Essentially I have two CSV files, a reference and a result and I load each of these into a dataframe for a subsequent comparison.</p> <p>But out of the blue, ...
<python><pandas><csv>
2023-09-12 00:11:36
0
2,192
Bernd Wechner
77,084,988
9,757,174
"The merchandise variant referenced by this term condition could not be found" - Shopify API Error
<p>I am creating a custom app on shopify and trying to create a draft order. When I create the draft order, I get the following error.</p> <pre><code>{ &quot;errors&quot;: { &quot;base&quot;: [ &quot;The merchandise variant referenced by this term condition could not be found.&quot; ] } } </code></pre...
<python><shopify><fastapi><shopify-app><shopify-api>
2023-09-11 22:01:09
1
1,086
Prakhar Rathi
77,084,912
1,100,107
How to clip a PyVista mesh to a ball?
<p>I have this PyVista isosurface:</p> <pre class="lang-py prettyprint-override"><code>from math import pi, cos, sin import pyvista as pv import numpy as np def strange_surface(x, y, z, A, B): return ( z**4 * B**2 + 4 * x * y**2 * A * B**2 + x * z**2 * A * B**2 - 2 * z**4 * A ...
<python><3d><pyvista>
2023-09-11 21:38:17
1
85,219
Stéphane Laurent
77,084,784
11,277,108
Find string in text of script element
<p>I'm trying to scrape a page where I want to wait until a string has been detected in a <code>script</code> element before returning the page's HTML.</p> <p>Here's my MRE scraper:</p> <pre><code>from scrapy import Request, Spider from scrapy.crawler import CrawlerProcess from scrapy_playwright.page import PageMethod ...
<python><xpath><scrapy><scrapy-playwright>
2023-09-11 21:08:05
1
1,121
Jossy
77,084,774
12,436,050
Filter pandas dataframe if value is either 'True' or null
<p>I have following dataframe</p> <pre><code>A B C 1 ABC True 2 DEF False 3 GHI </code></pre> <p>I would like to filter this dataframe and select those rows where column C is either 'True' or blank.</p> <pre><code>A B C 1 ABC True 3 GHI </code></pre> <p>I tried many approaches a...
<python><pandas><dataframe>
2023-09-11 21:05:41
1
1,495
rshar
77,084,682
21,370,869
How to seperate my program output from the Path being displayed on terminal
<p>When I run a simple python programme, like the following:</p> <pre><code>print(&quot;Hello World&quot;) </code></pre> <p>The output on the terminal becomes:</p> <pre><code>c:; cd 'c:\Users\super\long\path\here'; &amp; 'c:\Users\super\long\path\here\MyPyENV\Scripts\python.exe' 'c:\Users\super\.vscode\extensions\ms-py...
<python><visual-studio-code>
2023-09-11 20:39:36
0
1,757
Ralf_Reddings
77,084,622
5,036,928
PyInstaller Hidden Imports Param for Local Imports
<p>(Open to suggestions for a more descriptive title)</p> <p>I am trying to package my script using Pyinstaller and get the following when trying to run the exe:</p> <pre><code> File &quot;PyInstaller\loader\pyimod02_importers.py&quot;, line 385, in exec_module File &quot;apryse_sdk\__init__.py&quot;, line 17, in &l...
<python><pyinstaller><python-import><python-module>
2023-09-11 20:29:24
1
1,195
Sterling Butters
77,084,573
3,781,009
Identifying location in list of runtimeWarning in python
<p>I have a script that loops through a list and at certain points generates a runtimeWarning. I want to flag these locations, but not kill the loop. I just want to identify the locations of the warnings.</p> <p>Here is an example.</p> <pre><code>import numpy as np #define NumPy arrays x = np.array([4, 5, 5, 7, 0,10]) ...
<python>
2023-09-11 20:19:41
2
1,269
user44796
77,084,500
1,802,225
<class 'psycopg2.errors.UndefinedColumn'>: column does not exist when JOIN
<ul> <li><strong>python</strong>: 3.9.17</li> <li><strong>psycopg2</strong>: 2.9.7</li> <li><strong>OS</strong>: Ubuntu 20.0</li> <li><strong>postgre</strong>: 12</li> </ul> <p>I did all I can and still this error:</p> <pre><code>2023-09-11 22:45:35,033 ERROR &lt;class 'psycopg2.errors.UndefinedColumn'&gt;: column u.id...
<python><postgresql><psycopg2><psql>
2023-09-11 20:04:09
1
1,770
sirjay
77,084,311
5,038,503
Optional, dynamic dependencies at Python runtime
<p>I'm building a complex Python application with a maximalist approach in terms of support for different libraries, some of which are machine learning libraries that use several gigabytes. I am now getting ready to make a release of the project, but I've realized the build size is enormous and 99% of it is not my code...
<python><pip><setuptools>
2023-09-11 19:25:11
4
2,024
Tessa Painter
77,084,041
13,584,963
Compare numpy 3D array with 2D array aisle by aisle
<p>I have large amount of m-by-n 2D arrays that need to be compared with one reference m-by-n 2D array (of course it's not all 1),</p> <pre><code>arrays = np.random.rand(m,n,k) array_ref = np.ones((m,n)) result = np.zeros_like(arrays, dtype=np.bool_) for k_id in range(k): result[:,:,k_id] = arrays[:,:,k_id]&gt; arr...
<python><numpy><multiprocessing><mask>
2023-09-11 18:32:28
0
311
Crear
77,083,986
8,521,346
imap-tools Access Raw Message Data
<p>How do you access the raw message data of an email when using imap-tools? Specifically so it can then be loaded into the email.message_from_bytes() function for forwarding?</p> <pre><code>from imap_tools import MailBox, AND with MailBox('imap.gmail.com').login('asdf@gmail.com', '123456', 'INBOX') as mailbox: # g...
<python><smtp><imap>
2023-09-11 18:21:08
2
2,198
Bigbob556677
77,083,861
595,305
Maintain responsiveness of PyQt5 and other threads during call to intensive non-Python module?
<p>This is the first time I've tried writing a Rust module (using PyO3) to be called from Python. OS is W10.</p> <p>Before, when just using Python, I spent quite a bit of time trying to understand how to maintain responsiveness of PyQt5's &quot;gui thread&quot; (aka &quot;main application thread&quot;) when running bac...
<python><multithreading><rust><pyqt5><pyo3>
2023-09-11 17:58:29
1
16,076
mike rodent
77,083,578
1,852,526
Filter List of T or list of some type in Python
<p>I am new to Python. I have a List of T i.e. List of PackageReference objects. The PackageReference object is defined as follows:</p> <pre><code>class PackageReference: def __init__(self, ecosystem, repository_root, repository_name, source, package_name, version): self.ecosystem = ecosystem self.r...
<python><list><filter>
2023-09-11 17:07:18
0
1,774
nikhil
77,083,408
3,851,085
Django create Polygon from list of lat/long coordinates
<p>I have a list of lat/long coordinates that make up a polygon. How do I instantiate a Polygon, to be used as a PolygonField?</p>
<python><django><django-models><geodjango>
2023-09-11 16:41:56
1
1,110
Software Dev
77,083,405
2,071,807
How to mock pathlib.Path.read_text for a particular file
<p>The unittest docs show you <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.mock_open" rel="nofollow noreferrer">how to use mock_open</a> to mock <em>direct</em> calls to <code>builtins.open</code>.</p> <p>But how about mocking <code>pathlib</code>'s <code>read_text</code> like this:</p> <...
<python><python-unittest>
2023-09-11 16:41:29
2
79,775
LondonRob
77,083,211
5,217,293
Gridspec spanning fractional column width
<p>I'd like a plot that has two subplots in the first row, each spanning 1.5 columns, and three plots in the second row, each a column wide. Is that possible with matplotlib and gridspec? From the <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html#examples-using-matplotlib-gridspec-gri...
<python><matplotlib><subplot><matplotlib-gridspec>
2023-09-11 16:11:04
2
1,023
K. Shores
77,083,199
130,208
In python doit how to run task only when some condition is met
<p>Something really simple I want to achieve with python doit module. I have task_entry and three other tasks: task_a, task_b, task_c. I want to control from task_entry which of the either tasks a, b, or c to get evaluated. Lets say there is a config file from which task entry finds out which among a, b, c to execute. ...
<python><doit>
2023-09-11 16:08:15
1
2,065
Kabira K
77,083,082
20,830,264
openai.error.InvalidRequestError: The specified base model does not support fine-tuning. when fine-tune Azure OpenAI model
<p>I'm running the following Python code for a fine-tune OpenAI task:</p> <pre class="lang-py prettyprint-override"><code>import openai from openai import cli import time import shutil import json openai.api_key = &quot;*********************&quot; openai.api_base = &quot;https://*********************&quot; openai.ap...
<python><azure><azure-openai>
2023-09-11 15:50:14
1
315
Gregory
77,082,810
3,247,006
What is & How to know the default screenshot's window size of browsers in Selenium?
<p>I ran the code below to take 3 screenshots of Django Admin on Google Chrome, Microsoft Edge and Firefox. *I use <a href="https://github.com/django/django" rel="nofollow noreferrer">Django</a>, <a href="https://github.com/pytest-dev/pytest-django" rel="nofollow noreferrer">pytest-django</a> and <a href="https://githu...
<python><django><selenium-webdriver><screenshot><pytest-django>
2023-09-11 15:07:37
1
42,516
Super Kai - Kazuya Ito
77,082,788
7,454,706
Pandas Multi-index on 2 Levels
<p>I have a json which is in the following format :</p> <pre><code>data = { 'Low': { '2023.07.01': {&quot;u&quot;: &quot;mo&quot;, 'N': 1, 'O': 2, &quot;PN&quot;: 22, &quot;PO&quot;: 34}, '2023.07.02': {&quot;u&quot;: &quot;no&quot;, 'N': 1, 'O': 2, &quot;PN&quot;: 22, &quot;PO&quot;: 34} }, ...
<python><pandas><multi-index>
2023-09-11 15:04:46
2
2,047
ASHu2
77,082,780
913,347
HTTPServer: can't listen on Wifi when wire is connected (Windows)
<p>I've encountered an unusual behavior with Python's HTTPServer. My computer has both Ethernet and WiFi connections active simultaneously. I intended for the server to exclusively respond to incoming requests from the WiFi interface, so I configured it accordingly as described below. However, I've encountered an issue...
<python><python-sockets><basehttpserver>
2023-09-11 15:03:10
1
6,845
ishahak
77,082,739
2,626,865
selecting conditional code paths in hypothesis
<p>Most conditional strategies seem to be data-driven. But what if I want to select a code path independently of any generated data?</p> <p>For example, let's convert the grammar <code>rule_a = rule_optional? rule_b</code> to a strategy:</p> <pre class="lang-py prettyprint-override"><code>@strategy.composite def rule_a...
<python><conditional-statements><python-hypothesis>
2023-09-11 14:56:55
1
2,131
user19087
77,082,653
13,023,224
Order nested lists inside column
<p>I have this dataset:</p> <pre><code>df = pd.DataFrame({'Name':['John', 'Rachel', 'Adam','Joe'], 'Age':[95, 102, 31,np.nan], 'Scores':[np.nan, [80, 82, 78], [25, 20, 30, 60, 21],np.nan] }) </code></pre> <p>I would like to sort values inside column 'scores'.</p> ...
<python><pandas><sorting><nested-lists>
2023-09-11 14:48:12
4
571
josepmaria
77,082,612
2,173,773
Pytest mock when using multiprocessing: How to wait until method is called?
<p>I would like to test the following code using pytest and <a href="https://pytest-mock.readthedocs.io/en/latest/usage.html" rel="nofollow noreferrer">pytest-mock</a> (this is a minimal example from a larger program):</p> <pre><code>import logging import multiprocessing import os def task(): logging.info('task st...
<python><pytest><python-multiprocessing><pytest-mock>
2023-09-11 14:42:31
2
40,918
Håkon Hægland
77,082,550
583,187
Search string at the beginnig of line is not returned by regex and lines with $ are not ignored
<p>From a text file I want to extract everything that starts with specific &quot;keyword&quot; including the keyword, until a &quot;end_word&quot; but not the end_word itself. New line characters must be returned as well. Every extracted string is stored in a dictionary. I have the following code in Python which works ...
<python><regex>
2023-09-11 14:32:13
3
2,841
Lumpi
77,082,545
2,725,810
Making sense of the log for the cold start of AWS Lambda
<p>My AWS Lambda measures the time (in milliseconds) of copying two ML models from <code>/var/task</code> to <code>/tmp</code> and initializing these models during the cold start. Here is the relevant code (i.e. the code that executes outside of any function):</p> <pre class="lang-py prettyprint-override"><code>import...
<python><shell><aws-lambda><aws-sam><aws-sam-cli>
2023-09-11 14:31:38
0
8,211
AlwaysLearning
77,082,541
20,831,707
how to install python3 in postgres
<p>I'm trying to work with plpython in postgresql So I run the command:</p> <pre><code>CREATE EXTENSION plpython3u </code></pre> <p>but I get the error:</p> <pre><code>Erro SQL [58P01]: ERROR: could not load library &quot;C:/Program Files/PostgreSQL/15/lib/plpython3.dll&quot;: unknown error 126 </code></pre> <p>I read ...
<python><postgresql><plpython>
2023-09-11 14:31:15
0
389
Guilherme Rodrigues
77,082,451
1,652,219
How to test if any date matches a specific year-month within each group in Polars?
<h3>Intro</h3> <p>In Polars I would like to do quite complex queries, and I would like to simplify the process by dividing the operations into methods. Before I can do that, I need to find out how to provide these function with multiple columns and variables.</p> <h3>Example Data</h3> <pre class="lang-py prettyprint-ov...
<python><dataframe><datetime><group-by><python-polars>
2023-09-11 14:20:36
1
3,944
Esben Eickhardt
77,082,304
5,769,814
Opposite of numpy.reduce
<p>So in <code>numpy</code> we have a <code>reduce</code> function with which we can reduce one dimension of an array by applying a function to the elements across that dimension. Is there also an inverse of this function that would take a single element and expand it to a whole new dimension?</p> <p>Let's say I have t...
<python><numpy><vectorization>
2023-09-11 14:00:45
1
1,324
Mate de Vita
77,081,953
6,440,589
How to test whether timezone exists in Python/pandas?
<p>I am working with pandas' <code>tz_localize</code> function to convert dates from local time to UTC:</p> <pre><code>time_zone = 'America/Santiago' pd.to_datetime(pd.to_datetime(df['mydate']).apply(lambda x: datetime.strftime(x, '%d-%m-%Y %H:%M:%S'))).dt.tz_localize(time_zone).dt.tz_convert('UTC').dt.tz_localize(...
<python><pandas><timezone><utc>
2023-09-11 13:11:59
1
4,770
Sheldon
77,081,785
394,957
Manipulating particular values of a previous tensorflow layer
<p>I'm trying to build a tensorflow model in which the final output is a decaying function of the original data and the classifier.</p> <p>Thus, I've got the following layer:</p> <pre><code>class HalfLifeLayer(tf.keras.layers.Layer): def __init__(self, **kwargs): super(HalfLifeLayer, self).__init__(**kwargs...
<python><tensorflow><keras>
2023-09-11 12:50:16
0
1,955
Mark C.
77,081,746
15,222,211
FastAPI - multiple examples for Body in Response
<p>I need to create multiple examples for the Response Body, to display it in API documentation <a href="http://127.0.0.1:8000/docs" rel="nofollow noreferrer">http://127.0.0.1:8000/docs</a>. I found an example for the Request Body in the <a href="https://fastapi.tiangolo.com/tutorial/schema-extra-example/#openapi-examp...
<python><fastapi><pydantic>
2023-09-11 12:44:21
2
814
pyjedy
77,081,709
21,365,399
not sure how to interpret and solve ImportError from lxml using py2exe
<p>I'm trying to build a standalone executable file from a python script using <a href="https://pypi.org/project/py2exe/" rel="nofollow noreferrer">py2exe</a></p> <p>The creation of the .exe file does not output any warning nor errors, but when i actually try to execute it from command prompt it outputs the following e...
<python><exe><lxml><py2exe>
2023-09-11 12:39:41
0
656
Ferro Luca
77,081,560
17,561,414
change feed data in databricks
<p>How can I pass the lateste version as startingVersion and evndingVersion while Im trying to read changeFeed data in databricks?</p> <p>Code I have</p> <pre><code>df1 = spark.read.format(&quot;delta&quot;) \ .option(&quot;readChangeFeed&quot;, &quot;true&quot;) \ .option(&quot;startingVersion&quot;, 45) \ .option(&qu...
<python><azure><databricks><azure-databricks>
2023-09-11 12:18:24
1
735
Greencolor
77,081,425
5,308,892
Match functions with more than two arguments with Regex
<p>I want to write a regular expression in Python that matches functions with more than two arguments, such that the following expressions match:</p> <pre><code>function(1, 2, 3) function(1, 2, 3, 4) function(1, function(1, 2), 3) function(function(function(1, 2), 2), 2, 3, 4) </code></pre> <p>but the following don't:<...
<python><regex><pcre><parentheses>
2023-09-11 11:59:12
2
2,146
cabralpinto
77,081,386
4,451,521
In which case to use action store_false in python argparse?
<p>This question is about the very useful argparse Python library.</p> <p>We know the basic usage:</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument(&quot;--useOptionA&quot;,help=&quot;activate the useOptionA option&quot;, action=&quot;store_true&quot;) args=parser.parse_args() prin...
<python><argparse>
2023-09-11 11:50:14
2
10,576
KansaiRobot
77,081,344
3,560,671
SQLAlchemy ORM add Session Sleeping and not Committing on SQL Server 2022
<p>I'm following <a href="https://docs.sqlalchemy.org/en/20/orm/quickstart.html" rel="nofollow noreferrer">SQLAlchemy ORM's Quick Start tutorial</a> and can't get the first code to work on our company's SQL Server 2022 database. I'm able to create tables (and commit them), but I'm unable to commit after adding the data...
<python><sql-server><sqlalchemy><orm><pyodbc>
2023-09-11 11:43:10
0
897
Thomas Vanhelden
77,081,311
17,561,414
how to create the watermark table in databricks
<p>I would like to have a watermark table created in databricks with one column (version) and its value 1. This will be starting point. eveytime the python script will finish running I want to update the value by 1.</p> <p>Goal is to use this value later before the python code runs.</p>
<python><azure-databricks><watermark>
2023-09-11 11:38:43
1
735
Greencolor
77,081,025
9,731,056
Record and Speak at the same time using Twilio
<p>I am currently developing a Python Flask application that utilizes Twilio, and I am encountering the following challenge:</p> <ul> <li><p>The application needs to <strong>maintain continuous listening</strong> capabilities to transcribe the user's speech into text.</p> </li> <li><p>Once the user finishes speaking, t...
<python><asynchronous><concurrency><twilio><voice>
2023-09-11 10:55:18
0
645
Tbertin
77,080,720
12,236,313
Celery signatures .s(): early or late binding?
<p>This <a href="https://adamj.eu/tech/2022/08/22/use-partial-with-djangos-transaction-on-commit/" rel="nofollow noreferrer">blog post</a> of Adam Johnson perfectly illustrates the difference between <em><strong>early binding</strong></em> and <em><strong>late binding</strong></em> closures in Python. This is also expl...
<python><django><celery><late-binding><early-binding>
2023-09-11 10:10:53
1
1,030
scūriolus
77,080,169
1,422,096
How to do a try / retry / except?
<p>Is there a way to avoid nested <code>try / except</code> when there are <strong>3 cases</strong> (a bit like <code>if</code> <code>elif</code> <code>else</code>)?</p> <pre><code>try: name = open(&quot;test.txt&quot;, &quot;r&quot;).read() # test in current folder except FileNotFoundError: try: ...
<python><exception><try-except>
2023-09-11 08:49:43
2
47,388
Basj
77,080,078
10,518,698
Video output is not showing in OpenPifPaf
<p>I am trying to detect pose from my Webcamera using OpenPifPaf Library (<a href="https://openpifpaf.github.io/tutorial_opencv.html" rel="nofollow noreferrer">https://openpifpaf.github.io/tutorial_opencv.html</a>). However I am always getting this error, <code>AttributeError: 'NoneType' object has no attribute '__arra...
<python><opencv><pose-estimation><openpifpaf>
2023-09-11 08:36:53
0
513
JSVJ
77,080,024
2,900,959
How to fetch DynamoDB records with FilterExpression=Attr.exists via boto3?
<p>I have the following code:</p> <pre><code>import boto3 from boto3.dynamodb.conditions import Attr resource = boto3.resource(&quot;dynamodb&quot;) table = resource.Table(MY_TABLE_NAME) records = [] pagination = {} while True: response = table.scan(FilterExpression=Attr(attr_name).exists(), **pagination) re...
<python><amazon-dynamodb><boto3>
2023-09-11 08:30:02
1
398
MartinSolie
77,079,893
12,983,543
JWE Invalid Invalid Initialization Vector length
<p>I need to encrypt using Python with the A256GCM algorithm, and getting back a JWT that I need to send to a Typescript backend, that then needs to decrypt it and consume its content.</p> <p>This is the code that in the backend is used to decrypt what is received:</p> <pre><code>import { jwtDecrypt } from 'jose' resul...
<python><encryption><aes>
2023-09-11 08:09:17
0
614
Matteo Possamai
77,079,773
5,567,893
python map function returns NaN value while key is existed in the dictionary
<p>I have trouble converting values using <code>map</code> and <code>dictionary</code></p> <p>Although I checked a similar situation here (<a href="https://stackoverflow.com/questions/61369944/dictionary-mapping-return-nan">Dictionary mapping return Nan</a>), I can't understand why it didn't work well.</p> <p>I have tw...
<python><pandas><dataframe><dictionary>
2023-09-11 07:47:07
0
466
Ssong
77,079,762
14,830,534
Can you reconstruct a neural network from the weights file (.h5) only?
<p>If you want to keep your Neural Network architecture secret and still want to use it in an application, would somebody to be able to reverse engineer the Neural Network from the weights file (.h5) only?</p> <p>The weights are an output of <code>model.save_weights()</code> and are loaded back into the model with <cod...
<python><tensorflow><deep-learning>
2023-09-11 07:45:18
1
1,106
Jan Willem
77,079,553
1,028,133
Filtering PyTables PerformanceWarning with warnings.filterwarnings() fails
<p>There are a number of answers on this website detailing how one can ignore specific warnings in python (either <a href="https://stackoverflow.com/questions/63979540/python-how-to-filter-specific-warning">by category</a> or by <a href="https://stackoverflow.com/questions/9134795/how-to-get-rid-of-specific-warning-mes...
<python><pandas><pytables>
2023-09-11 07:11:35
1
744
the.real.gruycho
77,079,524
5,359,846
How to expect count bigger or smaller than?
<p>Using <code>Playwright</code> and <code>Python</code>, how can I expect for count bigger or smaller than?</p> <p>For example, this code expect for count of 2.</p> <p>How do I achieve count &gt;= 2 <strong>(Only bigger)</strong></p> <pre><code>expect(self.page.locator('MyLocator')).to_have_count(2, timeout=20 * 1000)...
<python><playwright><playwright-python>
2023-09-11 07:06:08
4
1,838
Tal Angel
77,079,458
4,451,521
Copy a file to a different place with a new name with python
<p>I have a file in some location, and I want to copy that file to another location but with a different name. This operation will be repeated many times and in every case the basename of the file to copy is the same (only location varies) so that is why the renaming.</p> <p>Anyway, a way to do this is explained in <a ...
<python><file-copying><file-move>
2023-09-11 06:54:08
0
10,576
KansaiRobot
77,079,088
7,223,184
How to get a rounded corners color clip using MoviePy?
<p>I'm working on a small video project using Python and MoviePy, and I want to create a color clip with rounded corners to use as a background. However, I'm unsure how to achieve this effect. So far I have a rectangle background !!. Can anyone give me a small example on how to add rounded corners to a color clip in Mo...
<python><moviepy>
2023-09-11 05:23:19
1
680
Aness
77,079,060
972,647
Running many CLI processes from Python, avoid CPU overload
<p>I'm creating a python script to launch many processes via the CLI. Once process per file found in a certain directory. And then I just loop over the files and launch the process which works on that file.</p> <pre><code>for path in pathlist: # Prepare cli call p = subprocess.Popen(cmd...) processes.append...
<python><command-line-interface>
2023-09-11 05:16:54
2
7,652
beginner_
77,079,039
9,983,652
how to upgrade to pandas 2.0 in anaconda?
<p>I am using anaconda. currently I have pandas 1.3 installed. how do I upgrade pandas to 2.0? I checked below website and there is pandas 2.0.3 available in anaconda with following command</p> <pre><code>conda install -c anaconda pandas </code></pre> <p><a href="https://anaconda.org/anaconda/pandas" rel="nofollow nore...
<python><pandas><anaconda>
2023-09-11 05:09:27
1
4,338
roudan
77,078,795
271,351
Add Image to Excel file after pandas.to_excel()
<p>I am using <code>xlsxwriter</code> as the <code>engine</code> that I pass to <code>pandas.ExcelWriter</code>. I have a DataFrame and I call <code>to_excel()</code> on it passing the writer that I've previously acquired. I then try grabbing the worksheet using <code>get_worksheet_by_name()</code>, which seems to work...
<python><pandas><export-to-excel><xlsxwriter>
2023-09-11 03:42:12
1
4,573
cjbarth
77,078,680
11,262,633
Average of datetime.datetime.now() is overstated
<p>If I make a list of time deltas, the average is larger than if I average the microsecond values from these deltas. Why is that?</p> <pre><code>import time import numpy as np l = [] l_m = [] for _ in range(5): start = datetime.datetime.now() time.sleep(1) l.append((datetime.datetime.now() - start)) l...
<python>
2023-09-11 02:53:26
1
1,260
mherzog
77,078,298
10,138,470
What distance measure can I use that factors in order?
<p>I have a few lists that havethe same IDs that are strings. They are as follows:</p> <pre><code>list1 = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;] list2 = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;5&quot;, &quot;4&quot;] list3 = [&quot;1&quot;, &quot;5&quot;, &quot;4&quot;, ...
<python><distance><levenshtein-distance>
2023-09-11 00:04:09
2
445
Hummer
77,078,235
2,458,922
Pandas Find distance amoung the group
<p>Given data set contains,</p> <blockquote> <p>Brand | Sector|Year|Price|Sales.</p> </blockquote> <blockquote> <p>B1, S1, 2023, 45900, 400</p> </blockquote> <blockquote> <p>B1, S1, 2022, 45000, 500</p> </blockquote> <blockquote> <p>B2, S1, 2022, 45400, 520</p> </blockquote> <p>The Group may be defined as Same Brand an...
<python><pandas>
2023-09-10 23:29:05
1
1,731
user2458922
77,078,098
7,869,636
How to specify para mutual exclusive groups (sets) of arguments in argparse? Or make optional positional parameter with any number of args
<p>I want the following usege:</p> <p>Usage 1: <code>my_launch.py --list-installed</code><br /> Usage 2: <code>my_launch.py [-a | -b | -c &lt;arg_c&gt;] &lt;appname [args ...]&gt;</code></p> <p>Is that possible to combine with argparse?</p> <p>If the <code>--list-installed</code> is used, then there should not be any o...
<python><argparse>
2023-09-10 22:28:39
0
839
Ashark
77,078,086
2,068,311
Can not uploading content to WordPress folder /wp-content/uploads/woocommerce_uploads/
<p>Im trying to write a Python script that will upload images and pdf to WordPress. I would like the images to be uploaded to the folder '/wp-content/uploads/' and the pdf files to the folder '/wp-content/uploads/woocommerce_uploads/'.</p> <pre><code>import requests import os class UploadProductMedia: def __init__...
<python><wordpress><rest>
2023-09-10 22:24:35
1
654
Andrew Seaford
77,078,023
604,063
Progress bar when copying one large file in Python?
<p>I want to use <a href="https://tqdm.github.io/" rel="nofollow noreferrer">tqdm</a> to display a progress bar when copying a single large file from one filepath to another.</p> <p>This is not the same as <a href="https://stackoverflow.com/questions/62342365/display-progress-bar-in-console-while-copying-files-using-tq...
<python><file-copying><tqdm>
2023-09-10 21:56:13
1
8,125
David Foster
77,077,807
11,561,158
Django query: transform two for loops into a queryset
<p>I have 3 simple models:</p> <pre><code>from django_better_admin_arrayfield.models.fields import ArrayField class BuildItem(models.Model): base = models.ForeignKey(Item, on_delete=models.CASCADE) level = models.IntegerField(default=1) mandatory_skills = ArrayField(models.IntegerField(null=True, blank=Tru...
<python><django>
2023-09-10 20:42:17
1
863
Hippolyte BRINGER
77,077,694
12,236,313
Using Celery tasks in Django to update aggregated data
<p>In my Django project, I have a use case where I have some complex Python functions which are <strong>computationally expensive</strong>: they involve numerous calculations based on a recurrence relation. They are already well optimized but still take a few seconds to run in some cases.</p> <p>In this context, I'm th...
<python><django><celery>
2023-09-10 19:57:33
0
1,030
scūriolus
77,077,628
10,671,956
python3 TypeError: '<' not supported error when try to implement A* algo use python heapq
<p>I am trying to implement A* algorithm using pri_que by leveraging python library <em>heapq</em>. In general, all the state of will be stored as a <strong>Node</strong> instance</p> <pre><code>class Node: def __init__(self, state, parent, action, depth): self.path_cost = 0 self.state = state ...
<python><python-3.x><priority-queue><a-star>
2023-09-10 19:35:21
1
1,505
Rieder
77,077,603
3,476,463
run llama-2-70B-chat model on single gpu
<p>I'm running pytorch on an ubuntu server 18.04 LTS. I have an nvidia gpu with 8 GB or ram. I'd like to experiment with the new llma2-70B-chat model. I'm trying to use peft and bitsandbytes to reduce the hardware requirements as described in the link below:</p> <p><a href="https://www.youtube.com/watch?v=6iHVJyX2e5...
<python><pytorch><gpu><large-language-model><llama>
2023-09-10 19:27:06
3
4,615
user3476463
77,077,056
12,944,030
optimize insert operation in MySQL (InnoDB)
<p>I have this table:</p> <pre><code>create table tab3( id int not null auto_increment, phrase text, link_1 int, link_2 int, primary key (id), foreign key (link_1) references tab1 (id), foreign key (link_2) reference...
<python><mysql>
2023-09-10 16:43:03
1
349
moe_
77,077,029
15,303,234
os.scandir throws mysterious NotADirectory error
<p>while I was writing a function loop through a folder</p> <p>code here:</p> <pre><code>import os from pathlib import Path path = Path(r'D:\full') for i in os.scandir(path):#folders for j in os.scandir(i.path):#subdict for k in os.scandir(j.path):#files print(k.path) </code></pre> <p>it...
<python><filesystems><file-not-found>
2023-09-10 16:38:06
0
301
TheHappyBee
77,076,981
7,809,915
Pyinstaller throws AssertionError
<p>I'm trying to turn a Python app (with a PyQt dialog) into an exe using pyinstaller. Unfortunately this doesn't work and returns the following output to the console:</p> <p>There's only one (!) Python script, app.py. It contains some functions and a class for the gui. Nothing special.</p> <pre><code>C:\Users\m14\Desk...
<python><python-3.x><pyinstaller>
2023-09-10 16:26:36
1
490
M14
77,076,663
11,416,654
RNG Challenge Python
<p>I am trying to solve a CTF challenge in which the goal is to guess the generated number. Since the number is huge and you only have 10 attempts per number, I don't think you can apply binary search or any kind of algorithm to solve it, and that it has something to do with somehow getting the seed of the random funct...
<python><random><ctf>
2023-09-10 15:06:12
1
823
Shark44
77,076,597
837,451
Is it possible to get pydantic v2 to dump json with sorted keys?
<p>In the pydantic v1 there was an option to add kwargs which would get passed to <code>json.dumps</code> via <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeljson" rel="noreferrer"><code>**dumps_kwargs</code></a>. However, in pydantic v2 if you try to add extra kwargs to <code>BaseModel.json()</cod...
<python><json><pydantic>
2023-09-10 14:48:01
3
4,688
mmdanziger
77,076,413
893,254
How can I test some Python code which makes use of the requests package?
<p>I have a Python script which uses the <code>requests</code> package to make a <code>get</code> request to a url to download a (large) file.</p> <p>Becuase the file is large, I cannot use this in the current state for testing. (It takes about 20 minutes to download.)</p> <p>Is there a way I can use another Python pac...
<python><python-3.x>
2023-09-10 13:55:45
1
18,579
user2138149
77,076,399
11,748,924
using finally clause vs without using finally clause
<p>What is the difference between this code that uses a <code>finally</code> statement and the code without a <code>finally</code> statement?</p> <pre><code># code 1 a = 10 b = 0 try: c = a / b print(c) except ZeroDivisionError as error: print(error) finally: print('Finishing up.') </code></pre> <p>and...
<python><error-handling><try-catch-finally>
2023-09-10 13:53:25
0
1,252
Muhammad Ikhwan Perwira
77,076,359
16,222,937
Import could not be resolved for modules in same folder
<p>I have two .py files (modules). I'm trying to import one into the other:</p> <pre><code>from place import Place </code></pre> <p><code>place</code> is the name of the .py files and <code>Place</code> name of the class inside it. I am getting an error:</p> <blockquote> <p>Import &quot;place&quot; could not be resolve...
<python><pylance>
2023-09-10 13:41:58
1
443
CloakedArrow
77,076,185
5,859,885
SciPy - Warning when there are Contradictory constraints?
<p>I am using the SciPy package from Python in order to solve a minimization problem with many constraints.</p> <p>Let's say I have contradictory constraints on my solution. For purposes of this questions, let's just say I had these constraints:</p> <pre><code> def con1(x): return 0.9 * x[0] - x[1] def con2(...
<python><scipy><scipy-optimize><scipy-optimize-minimize>
2023-09-10 12:52:35
0
1,461
the man
77,076,144
1,045,800
Create a single object from chained comparison in Python
<p>I am toying around with chained comparison in Python, that is, something like <code>a &lt; b &lt; c</code>. According to the docs, it is evaluated as <code>(a &lt; b) and (b &lt; c)</code>, where <code>b</code> is evaluated only once.</p> <p>I do this to save inequalities of symbolic expressions to a list. For examp...
<python><highs>
2023-09-10 12:40:11
1
5,420
cxxl
77,076,122
1,473,517
scipy's direct fails (almost) immediately on this toy optimization problem
<p>Consider the following simple MWE:</p> <pre><code>import numpy as np from scipy.optimize import direct def score(x): parity_in_range = len([v for v in x if 4 &lt;= v &lt;= 6])%3 main_score = np.max(np.abs(np.diff(x))) return main_score + parity_in_range length = 20 bounds = [(0,10)] * length result = di...
<python><scipy><scipy-optimize>
2023-09-10 12:34:23
1
21,513
Simd
77,076,050
689,242
pyserial gets no response from the bootloader in embedded device
<p>I have an embedded device configured to boot in to the bootloader which expects to communicate with the user on the USART1 after reboot.</p> <p>This works if I open a serial terminal application <em>(cutecom)</em> and connect to the device <code>/dev/ttyUSB0</code> using:</p> <ul> <li>115200 baud rate,</li> <li>8 da...
<python><pyserial>
2023-09-10 12:16:10
1
1,505
71GA
77,076,045
20,285,843
MySQL Connector / CharacterSet / two connections
<p>I am facing a problem using python, mysql.connector (8.1.0) and trying to open 2 connections on 2 different servers:</p> <p>If I run :</p> <pre><code>from mysql.connector import MySQLConnection if __name__ in '__main__': # A try: c1 = MySQLConnection( host='host1', user=...
<python><mysql-connector><charset>
2023-09-10 12:13:51
3
529
yotheguitou
77,075,930
1,942,868
How can I make the queryset filter `or` conditions dynamically from the array?
<p>I have <code>array</code> and try to use this as filter key for database</p> <p>I want to make this dynamically from the <code>array = [AC&quot; ,&quot;BC&quot;]</code></p> <pre><code> queryset = queryset.filter(Q(username__icontains=&quot;AC&quot;)| Q(username__icontains=&quot;BC&quot;)) </code></pre> <p>For exampl...
<python><django><filter>
2023-09-10 11:35:06
2
12,599
whitebear
77,075,862
15,212,664
Interact with an exe file which is converted from py file
<p>I have the following python script. In my python script i run it to convert some pdfs to excel. When i run it i enter the filename which the folders with the pdfs exist and i press enter and my script proceed the pdf files and return me a structured excel file.</p> <p>I tried to convert the py file to an exe file us...
<python><pyinstaller><exe>
2023-09-10 11:13:16
1
327
Lefteris Kyprianou