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,910,089
9,265,735
I can't get DRF-Spectactular to generate OpenApiParameter valuesin Swagger for functions, only classes
<p>Currently I'm working on a django project and I have an <code>api_views.py</code> file with the following view function:</p> <pre class="lang-py prettyprint-override"><code>@api_view([&quot;GET&quot;]) @extend_schema( parameters=[ OpenApiParameter( name=&quot;jurisdiction&quot;, description=&...
<python><django><django-rest-framework><drf-spectacular>
2024-01-31 00:00:08
0
612
glitchwizard
77,910,052
9,072,753
How to dynamically set type hinting for inherited classes constructor?
<p>With the following code:</p> <pre><code>import dataclasses @dataclasses.dataclass class A: a: int b: float A(&lt;cursor location&gt; </code></pre> <p>If I now let my LSP pyright driver give me suggestions at the cursor location it finds &quot;a&quot; and &quot;b&quot; arguments.</p> <p><a href="https://i.sst...
<python><python-typing>
2024-01-30 23:47:59
1
145,478
KamilCuk
77,910,049
8,834,335
How do I get a mean INLCUDING NaN values in Python?
<p>Apparently I have the opposite of everyone else's problem... I would like to take the mean of a pandas dataframe, and I would like to have the result return NaN if there are ANY NaNs in the frame. However, it seems like neither np.mean nor np.nanmean do this. Example code:</p> <pre><code>b = pd.DataFrame([[1,2],[mat...
<python><pandas><numpy>
2024-01-30 23:46:59
1
468
Sinnombre
77,909,960
697,660
Python Bitflow Framegrabber BfUtils.BFGTLDevice Claxon-CXP1 getNode DeviceTemperature
<p>I’m attempting to acquire the temperature value from a Claxon-CXP1 connected to a Basler VNIR hyperspectral camera .</p> <p>I’m following these documents and either not opening the board and or getting a null node result when I expect a value. <a href="https://www.bitflow.com/PythonHelp/_generate/BFModule.BFGTLUtils...
<python><python-3.x>
2024-01-30 23:19:57
0
882
TheDev6
77,909,551
8,223,979
How to merge two columns by the intersection of the elements in each col?
<p>Imagine I have a dataframe like this: With lists of elements in a single string.</p> <pre><code>data = {'Col1': [&quot;apple, banana, orange&quot;, &quot;dog, cat&quot;, &quot;python, java, c++&quot;], 'Col2': [&quot;banana, lemon, blueberry&quot;, &quot;bird, cat&quot;, &quot;R, fortran&quot;] } df =...
<python><pandas><dataframe><intersection>
2024-01-30 21:37:28
2
1,097
Caterina
77,909,516
11,330,134
Use list to map subset of dataframe columns to dictionary values
<p>Is there a way to pass a list of columns to map a dictionary's values in a single call?</p> <p>I can do it by stating each column but wondering if I can shorten up the syntax.</p> <p>Looked at <a href="https://stackoverflow.com/questions/43725799/map-multiple-columns-by-a-single-dictionary-in-pandas">this post</a> f...
<python><pandas>
2024-01-30 21:31:17
1
489
md2614
77,909,434
3,747,241
Depth and RGB rendered using blender not aligning properly with the object model in Open3D
<p>I am working on the ShapeNetCore dataset which consists of 3D models with texture and color information. Link to ShapeNetCore repository - <a href="https://shapenet.org/" rel="nofollow noreferrer">https://shapenet.org/</a></p> <p>I am trying to render the RGB and depth information of these .obj (3D) files using blen...
<python><rendering><blender><open3d><blender-2.76>
2024-01-30 21:12:23
1
1,135
Aditya
77,909,414
11,602,367
Create madlib in Plotly Dash
<p>How can I implement a madlib feature in a Dash app, allowing users to update specific text areas (and the entire prompt upon clicking a different button) similar to the provided image? The goal is to create a function that takes a sentence with bracketed words or phrases, turns them into textarea boxes, and outputs ...
<python><plotly-dash>
2024-01-30 21:07:11
1
551
acciolurker
77,909,058
11,402,025
How to flatten a list of objects in python
<p>I have a list of objects :</p> <pre><code>[ { &quot;person&quot;: &quot;abc&quot;, &quot;city&quot;: &quot;united states&quot;, &quot;facebooklink&quot;: &quot;link&quot;, &quot;address&quot;: &quot;united states&quot;, &quot;united states&quot;: [ { &quot;person&quot;: &quot;cdf&...
<python><json><recursion><iteration><flatten>
2024-01-30 19:49:29
1
1,712
Tanu
77,909,039
53,491
How do I use aiohttp with requests_aws4auth
<p>More recent version of this question with more details: <a href="https://stackoverflow.com/questions/78077509/using-aiohttp-with-requests-aws4auth">Using aiohttp with requests_aws4auth</a></p> <p>I have synchronous code that puts files in an AWS bucket that uses requests_aws4auth. I want to make it asynchronous usin...
<python><python-asyncio><aiohttp>
2024-01-30 19:46:13
1
12,317
Brian Postow
77,908,978
11,321,530
AttributeError: 'Series' object has no attribute 'append' with pandas_ta library
<p>I'm trying to apply technical finance indicators to data I fetch from Yahoo Finance. I found the <code>pandas_ta</code> library which seemed to fit my needs, however, applying a strategy gives me errors. Specifically, I want to use the <code>AllStrategy</code> (the default strategy), which applies all indicators to ...
<python><pandas><ta-lib><pandas-ta>
2024-01-30 19:34:37
2
333
bragi
77,908,977
23,260,297
Group data together and retain groupings in dataframe
<p>I have a dataframe:</p> <pre><code>ID Deal Party Commodity startdate enddate price quantity mtmvalue ---- ----- ----- --------- --------- ------- ------ -------- --------- J1 Sell J (stock1, stock2) 01Jan23 01Feb23 10.00 10 100.00 J4 Buy J (stock1, stock2) 0...
<python><pandas><dataframe>
2024-01-30 19:34:25
1
2,185
iBeMeltin
77,908,931
770,788
Using Beautiful Soup to find all doesn't seem to be giving me a list
<p>I trying to get all the book categories from this website: <a href="http://books.toscrape.com/" rel="nofollow noreferrer">http://books.toscrape.com/</a></p> <p>When I inspect the element I see that the categories are in a list towards the top of the html. They are in <code>&lt;div class=&quot;side_categories&quot;&g...
<python><web-scraping><beautifulsoup><python-requests>
2024-01-30 19:24:58
1
625
Funlamb
77,908,916
1,299,787
Any way to accomplish this in regex without negative lookbehind
<p>I would like to format a regex query so that it matches on all newline characters that are not preceded by a comma followed by any amount of whitespace.</p> <p>For example, in this scenario:</p> <pre><code>Line One, Line Two Line Three Line Four, &lt;-- whitespace before newline Line Five </code></pre> <p>I want...
<python><regex>
2024-01-30 19:21:48
3
473
Robert Lu
77,908,824
3,042,018
TypeError on Trinket Implementation of Turtle Graphics
<p>The code below works fine on Windows 10 with Python 3.10. When you click on the turtle, its color changes. However when I run the code in the browser-based Trinket environment, here: <a href="https://trinket.io/python/0da2ab1181" rel="nofollow noreferrer">https://trinket.io/python/0da2ab1181</a>, I get the following...
<python><turtle-graphics><python-turtle>
2024-01-30 19:05:01
1
3,842
Robin Andrews
77,908,801
75,386
Get EXPLAIN from Delta Lake MERGE in PySpark?
<p>Using Python 3.10, delta-spark 2.4.0, I need to see the execution plan of a MERGE statement in PySpark.</p> <p>For a dataframe operation, a <code>df.explain()</code> provides it, but I have not found a method for seeing the physical plan of a merge().</p> <p>Is there a method to see the equivalent of <code>explain(m...
<python><pyspark><delta-lake>
2024-01-30 18:59:57
1
1,712
kermatt
77,908,784
12,298,510
Read multiple CSVs from same file into separate dataframes
<p>I have a CSV file that really contains 2 separate CSVs split by a title line for each. The number of lines in the Polymerase Stats section can be anywhere between 1 and 8 and the number of lines in the CCS Stats section does not technically have a limit but will never exceed 50.</p> <p>My current solution is to enum...
<python><pandas>
2024-01-30 18:56:55
0
678
kevin41
77,908,606
1,753,640
Recursively build a path from a python dictionary
<p>I have the following python dictionary:</p> <pre><code>a = {'name': 'Kestral', 'children': [ {'name': 'Burtree Lane', 'children': [ {'name': 'ARCHIVE', 'children': []}, {'name': 'Development', 'children': [ {'name':...
<python>
2024-01-30 18:22:06
2
385
user1753640
77,908,576
880,874
How can I increment items in a list alphabetically?
<p>I have the following Python code that prints data based on a template.</p> <p>In the template, each selection is preceded by empty brackets, like this:</p> <pre><code>-[ ] selection one -[ ] selection two -[ ] selection three </code></pre> <p>Is there a way to change my script so that it increments with letters?</p>...
<python><python-3.x>
2024-01-30 18:15:31
1
7,206
SkyeBoniwell
77,908,525
955,273
bug in cross-process synchronisation using python's multiprocessing.Event from thread pool?
<p>In a distributed system we're building at work we are using <a href="https://redis.io/docs/manual/patterns/distributed-locks/" rel="nofollow noreferrer">redis's distributed locks</a> to synchronise multiple accesses to the results of a calculation. (We're using the <a href="https://redis-py.readthedocs.io/en/v5.0.1/...
<python><multiprocessing><distributed-computing>
2024-01-30 18:06:39
0
28,956
Steve Lorimer
77,908,432
16,912,844
Test (pytest) Being Skipped While Using Jenkins, But Not Run Directly
<p>I am using pytest for testing on a function, but it seem to be having an issue executing only when running on/with Jenkins. It runs fine if I directly execute the command on the Jenkins machine though.</p> <p>I have the below functions...</p> <p>This code runs fine on my local, and after running on Jenkins, if I cop...
<python><jenkins><pytest>
2024-01-30 17:50:21
1
317
YTKme
77,908,367
18,558,424
can't start smtp debug sever in windows cmd line
<p>I downloaded and installed Python. It is added to envoirment variable Path. And I can run it in cmd line:</p> <pre><code>Python 3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)] on win32 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more i...
<python>
2024-01-30 17:40:51
0
716
Abe
77,908,236
11,628,437
jaxlib.xla_extension.XlaRuntimeError: INTERNAL: Failed to execute XLA Runtime executable: run time error: custom call 'xla.gpu.custom_call' failed
<p>I am trying to run multiple sbx programs (that use JAX) concurrently using <code>joblib</code>. Here is my program -</p> <pre><code>''' For installation please do - pip install gym pip install sbx-rl pip install mujoco pip install shimmy ''' from joblib import Parallel, delayed import gym from sbx import SAC # fro...
<python><dynamic-memory-allocation><jax>
2024-01-30 17:15:26
1
1,851
desert_ranger
77,907,959
23,260,297
groupby multiple columns and broadcast results back to each row in dataframe
<p>I have posted this question before, but it keeps getting closed due to having similar questions asked, but those solutions have not helped me here.</p> <p>I have a dataframe that needs to be grouped by 3 different columns. From the resultant groupings, I need to perform calculations and then apply the result to each...
<python><pandas><dataframe>
2024-01-30 16:35:18
1
2,185
iBeMeltin
77,907,884
9,877,065
Python relation between object and type
<p>After sometimes spent on writing small Python scripts, I started to try to learn it more formally.</p> <p>I've this code :</p> <pre><code>class One(object): pass print(One, type(One)) class Two(type): pass print(Two, type(Two)) print(object , type(object)) print(type, type(type)) print(isins...
<python><class><types>
2024-01-30 16:24:12
0
3,346
pippo1980
77,907,843
1,471,980
How do u convert a string into data frame in pandas
<p>I'm performing an api request and I get this response back:</p> <pre><code>print(res) b'amp,dev, util\n192.168.101.1,server123,80%\n192.168.101.4,serverabc,75%\n192.68.101.5,serverusa1,50%\n' </code></pre> <p>I need convert this string to a data frame:</p> <pre><code>Amp. dev. util 192.168.101.1 serve...
<python><pandas><string><dataframe>
2024-01-30 16:19:30
2
10,714
user1471980
77,907,799
8,049,947
How to Ensure Execution of Finally Block in Airflow DAG Despite Exception in Python Code?
<p>I have the following code, and under normal circumstances, it won't fail in Airflow. To make the DAG fail in case of a certain situation, I added a ValueError. However, in the event of a failure, the finally block, which is crucial, doesn't get executed. How can I avoid this situation?</p> <pre class="lang-py pretty...
<python><sql-server><airflow>
2024-01-30 16:12:25
0
308
panther93
77,907,578
14,705,072
How to add a general title with a seaborn.objects.Plot.facet plot
<p>I am currently using the seaborn library in Python to create a facetted stacked barplot from a pandas dataframe named <code>averages</code> with columns <code>['Name', 'Period', 'Value', 'Solver']</code>.</p> <p>Here is the code I use to create the plot I want.</p> <pre><code>p = so.Plot(data = averages, x = 'Period...
<python><seaborn><seaborn-objects>
2024-01-30 15:41:40
1
319
Haeden
77,907,542
4,451,521
Applying a function for only some indices
<p>I have a function <code>computeLeft</code> which receives an index and returns four numbers. Something like this:</p> <pre><code>def computeLeft(i): return np.array([i*2, i*3, i*4, i*5]) # edited to correct it </code></pre> <p>Right now in my code I use it like this:</p> <pre><code>import numpy as np import ...
<python><pandas><numpy>
2024-01-30 15:34:47
2
10,576
KansaiRobot
77,907,507
10,380,409
Selenium Invalid ID session before quit with new chromedriver 121
<p>I updated the browser and the web driver for selenium to the last version 121.0.6167.85 (Official Build) (x86_64). And now after a bit 30min more or less all test fail with error:</p> <pre><code>HOOK-ERROR in after_scenario: InvalidSessionIdException: Message: invalid session id </code></pre> <p>NOTE:</p> <ol> <li>B...
<python><selenium-webdriver><selenium-chromedriver><automated-tests>
2024-01-30 15:28:48
1
826
Angelotti
77,907,430
1,737,830
Searching for objects within nested array: how to return only found objects and parent elements?
<p>Here's an excerpt from <code>pictures</code> MongoDB collection:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;_id&quot;: &quot;57582b6b&quot;, &quot;source&quot;: &quot;integration&quot;, &quot;url&quot;: &quot;https://example.com/images/51/landscapes-polar.xml&quot;, &quot;pictu...
<python><json><flask><pymongo>
2024-01-30 15:17:02
1
2,368
AbreQueVoy
77,907,417
13,615,436
Select all <table> elements without classes or ids with BeautifulSoup
<p>I am trying to select all <code>&lt;table&gt;</code> elements on some web pages with BeautifulSoup. The table elements do not have specific classes or ids.</p> <pre class="lang-py prettyprint-override"><code>import bs4 import requests def get_keycode_soup(url): res = requests.get(url) res.raise_for_status()...
<python><python-3.x><beautifulsoup><python-requests><html-parsing>
2024-01-30 15:14:47
1
1,294
will-hedges
77,907,234
4,564,080
Create a v1 model from a v2 model
<p>I have a project that is using Pydantic v2. The project is also using LangChain which, as of today, <a href="https://python.langchain.com/docs/guides/pydantic_compatibility" rel="nofollow noreferrer">only supports Pydantic v1</a>.</p> <p>Instead of converting my entire project to Pydantic v1, or else having a mix of...
<python><pydantic><langchain>
2024-01-30 14:50:27
0
4,635
KOB
77,907,190
5,955,479
Using moto with pandas read_parquet and to_parquet functions
<p>I am trying to write a unit test for a function which uses <code>pd.read_parquet()</code> function and I am struggling to make it work. I have the code below</p> <pre><code>from moto import mock_aws import pandas as pd import pytest import datetime as dt import boto3 from my_module import foo @pytest.fixture def mo...
<python><pandas><mocking><pytest><moto>
2024-01-30 14:43:10
1
355
user430953
77,907,131
534,238
Python match statement on types
<p>I normally do not use match statements, but I had an opportunity.</p> <p>I have a variable which can be of different data <em>types</em>, and I want to match on the type to do different things. This toy example captures the essence of what I want to do:</p> <pre class="lang-py prettyprint-override"><code>lang = &qu...
<python><match>
2024-01-30 14:32:10
1
3,558
Mike Williamson
77,906,985
10,590,609
access airflow task arguments in the on_failure_callback function
<p>I need a rollback operation to happen when a certain airflow task fails. To know what to rollback I need access to the task arguments inside the rollback function. The rollback function is passed to the <code>on_failure_callback</code> argument when defining the task.</p> <p>Take this as a simplified example:</p> <p...
<python><airflow><rollback>
2024-01-30 14:10:06
1
332
Izaak Cornelis
77,906,793
14,669,597
Celery worker does not start running when using the geventpool and starting from within Python
<p>I have a Celery system running, with 4 queues, using RabbitMQ as the broker. Currently this system is running using the gevent workerpool, and it is working fine when starting the worker from the command line like this: <code>celery -A app worker -Q celery -P gevent -c 100</code> Now I want to start this from python...
<python><python-3.x><celery><gevent>
2024-01-30 13:42:02
0
403
Alfred Rodenboog
77,906,747
22,221,987
Sync python threads, share their states and close all threads in one time
<p>My project is an API for some hardware mechanics. User can just send commands via socket and receive responses from hardware.<br /> For this purpose I use two sockets. One is for receiving responses (let's name it <code>RTD</code> and one for sending commands (<code>CMDS</code>).</p> <p>I have 3 classes. <code>Recei...
<python><python-3.x><multithreading><sockets><multiprocessing>
2024-01-30 13:35:54
1
309
Mika
77,906,670
8,040,369
Remove duplicates in DF and convert into a JSON obj in python
<p>I have a df something like below</p> <pre><code>Name Series ============================= A A1 B B1 A A2 A A1 B B2 </code></pre> <p>I need to convert the series to a list which should be assigned to each Name like a dict or json obj as something lik...
<python><pandas>
2024-01-30 13:22:39
2
787
SM079
77,906,586
5,013,084
Separate axis labels on two axis in altair
<p>I am trying to use this code as an example to separate the axis labels for the y axis on the left and on the right side together.</p> <pre class="lang-py prettyprint-override"><code>import altair as alt import pandas as pd df = pd.DataFrame( { &quot;unique_ID&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;...
<python><pandas><dataframe><altair>
2024-01-30 13:10:27
0
2,402
Revan
77,906,584
3,433,875
Set aspect ratio in matplotlib 3.8 3D plots
<p>I am trying to plot this: <a href="https://100.datavizproject.com/data-type/viz4/" rel="nofollow noreferrer">https://100.datavizproject.com/data-type/viz4/</a></p> <p><a href="https://i.sstatic.net/3vUfl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/3vUfl.png" alt="enter image description here" /></...
<python><matplotlib><matplotlib-3d>
2024-01-30 13:10:05
1
363
ruthpozuelo
77,906,562
2,662,302
Polars calculate percentile
<p>I have a polars dataframe that hava a column with dates and others with prices and I want to calculate the percentile of each one in a window of 252 x 3 observations.</p> <p>For that I'm doing this:</p> <pre class="lang-py prettyprint-override"><code> prices = prices.sort(by=[&quot;date&quot;]) rank_cols = list(set(...
<python><dataframe><python-polars>
2024-01-30 13:05:27
1
505
rlartiga
77,906,558
5,013,084
Sorting barplot in altair by multiple columns
<p>I am trying to sort a dataframe by multiple columns (more precisely, the first column is a string and should be sorted alphabetically and the second column is numeric and should be sorted from lowest to highest).</p> <pre class="lang-py prettyprint-override"><code>import altair as alt import pandas as pd df = pd.Da...
<python><altair>
2024-01-30 13:04:43
1
2,402
Revan
77,906,456
18,880,790
How to improve image quality before reading barcode
<p>I am using <a href="https://pypi.org/project/zxing-cpp/" rel="nofollow noreferrer">zxing-cpp</a> library for reading barcode from image.</p> <pre><code>import cv2 import zxingcpp img = cv2.imread('test.jpg') results = zxingcpp.read_barcodes(img) for result in results: print('Found barcode:' f'\n Valid: &...
<python><opencv><image-processing><barcode><zxing>
2024-01-30 12:45:45
1
477
Coder3000
77,906,356
1,065,145
How to reinstantiate OpenAI ChatCompletion object from string
<p>OpenAI python api call <code>client.chat.completions.create</code> now returns an object by default. How to reinstantiate that object after it was persisted to a database using <code>str(...)</code> method?</p> <pre><code>responseObj = client.chat.completions.create(...) # returns ChatCompletion(id=...) responseObj...
<python><openai-api>
2024-01-30 12:28:43
1
9,049
Denis Kulagin
77,906,193
3,700,524
The behavior of numpy.fromfunction()
<p>I was trying to create different arrays using Numpy's <code>fromfunction()</code>. It was working fine until I faced this issue. I tried to make an array of ones using <code>fromfunction()</code>(I know I can create it using <code>ones()</code> and <code>full()</code>) and here is the issue :</p> <pre><code>array = ...
<python><python-3.x><numpy><function>
2024-01-30 12:01:48
3
3,421
Mohsen_Fatemi
77,905,905
2,707,864
Setup in python a function of Bessel functions that can be both integrated and differentiated
<p>I need to setup a user defined function <code>ILTintegrand(u, t, r, b, a)</code> for <code>integrand = (j0(ur)*y0(ub) - y0(ur)*j0(ub)) / (j0(ub)*j0(ub) + y0(ub)*y0(ub)) * np.exp(-a*t*u**2) / u</code>, where j0 and y0 are the Bessel functions of the first and second kind, respectively.</p> <p>Then I need another user...
<python><numpy><scipy><sympy><bessel-functions>
2024-01-30 11:12:27
0
15,820
sancho.s ReinstateMonicaCellio
77,905,297
8,080,758
Extract key, value from C enumeration using regex
<p>I have several enum from C source code that look like this :</p> <pre class="lang-c prettyprint-override"><code>typedef enum { /** comment */ A = 1, /** comment */ B = 2, }foo_t; typedef enum { /** comment */ A = 1, /** comment */ B = 2, }bar_t; </code></pre> <p>I would like ...
<python><regex>
2024-01-30 09:41:02
1
1,276
Clément
77,904,880
10,443,817
Why mulitple plots are generated in the first tab?
<p>I have written a class that uses &quot;shap&quot; library to compute and plot shap feature importance. I have also written an added functionality to plot the graphs in the same window and different tabs. However, my first tab is plotting the same graph twice. The second plot is then also carried over to other tabs. ...
<python><jupyter-notebook><jupyter><ipywidgets>
2024-01-30 08:32:38
0
4,125
exan
77,904,784
6,510,273
Fix first line on jupyter notebook output
<p>I use this great code to show pyspark dataframes in jupyter in a nice format:</p> <pre><code>from IPython.display import display, HTML display(HTML(&quot;&lt;style&gt;pre { white-space: pre !important; }&lt;/style&gt;&quot;)) </code></pre> <p>Thanks to user <a href="https://stackoverflow.com/users/3857460/eric-le-fo...
<python><dataframe><pyspark><jupyter-notebook><html-table>
2024-01-30 08:16:23
0
2,177
Florida Man
77,904,769
4,509,609
Fail to import torchtext KeyError: 'SP_DIR'
<p>I failed to import torchtext with the following error. I tried it with a fresh conda env install (under a different python version) and still got the same issue.</p> <p>Originally I was able to use torchtext (I remember installed from pip) in an env of python 3.11, but then it raised error with the dataset module, s...
<python><pytorch><anaconda><conda><torchtext>
2024-01-30 08:14:36
1
835
Cecilia Lee
77,904,685
451,878
Transform python dictionary in parameters function, and evaluate in a loop
<p>I've a loop and I had a Pydantic model in a list. But, when I add a field in the table, I have changes this code. But it's not dynamic (the field names are the same that the keys):</p> <pre><code>for t_one in table1: for t_two in table2: my_list.append(PydanticModel(id=t_one.id, name=t_one.name, version=...
<python><pydantic>
2024-01-30 07:55:47
0
1,481
James
77,904,550
13,975,077
Python set working directory like Intellij in terminal
<p>I have a python which has the following folder/file structure.</p> <pre><code>Project/ -- generic_module -- directory ---- sub_directory ------ main.py (uses generic_module, &amp; other imports are relative to Project) </code></pre> <p>Now if I want to run main.py via Intellij IDE, I can just set the &quot;Working D...
<python><intellij-idea><python-import>
2024-01-30 07:29:16
1
800
Yogesh
77,904,074
748,493
Set new column on pandas dataframe with setitem
<p>I have a nested dictionary (let's call it <code>dic</code>) which has nodes of different depths and where final nodes contain pandas dataframe. I am looking to provide a uniform way for accessing and setting values at any node (where &quot;values&quot; can be further dictionaries, dataframes, or columns in dataframe...
<python><pandas>
2024-01-30 05:27:28
2
522
Confounded
77,903,782
7,371,707
Assigning values to 2d array with list of coordinates and time series without for-loop
<p>I have data with four attributes. Two are coordinates <code>xs</code> and <code>ys</code>; the other two are timestamps <code>ts</code> and polarity <code>ps</code>. I need to set the value of an image at each position <code>(x,y)</code> with the newest polarity. The xs and ys are not unique.</p> <p>I can do it with...
<python><numpy><numpy-ndarray>
2024-01-30 03:39:43
2
1,029
ToughMind
77,903,679
18,308,621
Why polars on intel cpu is faster than on amd cpu?
<p>I have two pc, one is Intel i7 13700KF with 64GB RAM and another is AMD 3970X with same RAM, both pc use ssd as storage and both pc has python 3.11 and polars 0.20.5. I run code below:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({ &quot;name&quot;: [&quot;a&quot;+str(i) for i in range(1...
<python><intel><python-polars><amd-processor>
2024-01-30 02:56:52
0
331
Hakase
77,903,352
5,709,240
How to export a list of list into a file?
<p>Given the following Panda DataFrame:</p> <pre><code>import pandas as pd data = {'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'], '2015': [43.3, 83.1, 86.4, 72.4], '2016': [85.8, 73.4, 65.2, 53.9], '2017': [93.7, 55.1, 82.5, 39.1]} df = pd.DataFrame(data) </code></...
<python><pandas>
2024-01-30 00:45:44
2
933
crocefisso
77,903,321
515,368
ImportError: cannot import name 'mock_s3' from 'moto'
<pre class="lang-py prettyprint-override"><code>import pytest from moto import mock_s3 @pytest.fixture(scope='module') def s3(): with mock_s3(): os.environ['AWS_ACCESS_KEY_ID'] = 'test' os.environ['AWS_SECRET_ACCESS_KEY'] = 'test' os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' s3 =...
<python><moto>
2024-01-30 00:33:21
1
3,162
supermitch
77,903,316
12,279,326
basic config to run a python docker image via AWS Lambda function
<p>I have five hours trying to get a Lambda function to successfully return a response, using a Docker image, and failing miserably.</p> <p>Dockerfile</p> <pre><code>FROM python:3.9.6-buster WORKDIR /app COPY . /app CMD [&quot;python&quot;, &quot;/app/lambda_handler.py&quot;] </code></pre> <p>Python files p.py</p> <pre...
<python><docker><aws-lambda>
2024-01-30 00:31:21
1
948
dimButTries
77,903,156
2,092,609
How Do I Calculate a "Call Level" Column on a DataFrame?
<p>I have a DataFrame that could be thought of as a call stack, differentiated by a column, <code>Entry</code>, whose value is True when we enter the function and False when we leave. The other columns are <code>ThreadID</code> and <code>Function</code>, so that the data might look like this:</p> <pre><code> ThreadID...
<python><pandas>
2024-01-29 23:28:22
2
4,192
mojo
77,903,136
3,224,196
Can you find an exact html tag with BeautifulSoup?
<p>I'm using BeautifulSoup to add an arbitrary attribute to some HTML code files. Let's call it... data-custom.</p> <p>Let's assume this fragment is the html that BeautifulSoup is going to load.</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;col-md-6&quot;&gt; &lt;label asp-for=&quot;Dril...
<python><beautifulsoup>
2024-01-29 23:18:44
1
380
Martin
77,902,990
3,490,622
Is this possible within optimization framework?
<p>I am new to operations research, so would really appreciate your help. I don't know if this is possible to do within the OR framework, but here's the problem. Suppose I have a set of SKUs, their regular prices, their price elasticities, their current demand in units/week and their inventory levels . If, after N w...
<python><operations-research>
2024-01-29 22:30:56
0
1,011
user3490622
77,902,984
14,222,845
Pyinstaller exe file gives 'plotly' has no attribute 'express' error
<p>I have some code in Python (Jupyter Notebooks in my Anaconda environment). The file is called <code>myFile.py</code>:</p> <pre><code>import math import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import plotly DF = pd.read_csv('My CSV data file path') myCol = DF['Temp'].value_counts(nor...
<python><anaconda><pyinstaller><exe><command-prompt>
2024-01-29 22:29:24
2
330
Diamoniner12345
77,902,970
16,596,758
How can I display an interactive SVG image that utilizes javascript in a Jupyter notebook?
<p>I have an SVG image with embedded javascript that makes the image change based on <code>onclick</code> events:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot; ?&gt; &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; height=&quot;100&quot; width=&quot;100&quot;&...
<javascript><python><svg><jupyter-notebook><jupyter>
2024-01-29 22:26:41
1
998
Will Holtz
77,902,968
13,142,245
Python logging CloudWatch location?
<p>I have a Lambda function, which I've declared with CDK. Additionally, I've declared cloud watch logs and passed the resource to the Lambda function as an environment variable &quot;LOGS_DESTINATION&quot;.</p> <p>The location can be retrieved by <code>os.environ['LOGS_DESTINATION']</code> by Python Lambda.</p> <p>In ...
<python><logging><aws-lambda><amazon-cloudwatch>
2024-01-29 22:26:16
2
1,238
jbuddy_13
77,902,942
3,067,055
get ViewSet and http_method_names from drf url namespace
<p>I have this snippet to construct API URLs using <code>SimpeRouter()</code>. In the <code>urlpatterns</code> I have declared a namespace called <code>my_api</code>, is there a way to get all the associated ViewSets and their respective <code>http_method</code> properties?</p> <pre class="lang-py prettyprint-override"...
<python><django><django-rest-framework>
2024-01-29 22:20:20
1
1,261
hello
77,902,840
11,838,196
Why does Python Glue Job throw a KeyError for my Job parameter?
<p>I have defined a simple Glue Job of type Python Shell:</p> <pre class="lang-py prettyprint-override"><code>import sys from awsglue.utils import getResolvedOptions args = getResolvedOptions(sys.argv, [ 'test-parameter' ]) value = args[&quot;test-parameter&quot;] print(f'value = {value}') </code></pre> <p>I am try...
<python><aws-glue>
2024-01-29 21:57:17
1
1,971
srk
77,902,775
1,084,416
How to forward generic argument types to a callable in Python
<p>I want to annotate a generic function which takes as arguments another function and its parameters.</p> <pre><code>def forward(func, **kwargs): func(**kwargs) </code></pre> <p>So, if I have a function which takes two integers:</p> <pre><code>def sum_int(a: int, b: int): ... </code></pre> <p>in my editor I wa...
<python><python-typing>
2024-01-29 21:41:49
1
24,283
Open AI - Opting Out
77,902,760
5,790,653
python save function variable to use in another function parameter
<p>I have these two functions:</p> <pre class="lang-py prettyprint-override"><code>def func1(my_list, test1, test2): my_list = [ {'name': 'Saeed', 'id': 1}, {'name': 'David', 'id': 2} ] def func2(name): name[0]['id'] += 1 </code></pre> <p>The <code>name[0]</code> is in fact <code>my_list[0]</code>, but I'm no...
<python>
2024-01-29 21:37:36
1
4,175
Saeed
77,902,619
3,030,966
How to start aiogram bot and aiohttp webserver together?
<p>I have aiogram v3 bot that runs in polling mode, I need to add a handler to process requests from exteranl application, i use aiohttp server that listens for external requests, process it and send notification to bot users:</p> <pre class="lang-py prettyprint-override"><code>import asyncio from aiogram import Bot, D...
<python><telegram-bot><aiohttp><aiogram>
2024-01-29 21:04:54
1
722
swserg
77,902,593
1,480,131
Define the return type of a function depending on the real value of an argument
<p>I know that with <code>TypeVar</code> you can define the return type of a function depending on the type of one its arguments. However, I want the type based on the content of an argument.</p> <p>For example, the function <code>open</code> returns different types depending on the content of the <code>mode</code> arg...
<python><python-typing>
2024-01-29 20:58:52
1
13,662
Pablo
77,902,559
1,581,441
Python safe string compression without line breaks
<p>I am trying to save a large amount of JSON files, by appending the JSON string as a new line to a large text file. I have limited storage so I don't want to save the JSON string as is for so many files. Instead, I try to compress the JSON string using zlib library, and then append the compressed string as a new line...
<python><compression><zlib>
2024-01-29 20:49:31
3
1,512
hmghaly
77,902,475
13,142,245
Pydantic strict mode not enforceable
<pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel, ValidationError, Field class Student(BaseModel): id: int = Field(strict=True) s = Student(id=&quot;1&quot;) </code></pre> <p>Or alternatively</p> <pre><code>from pydantic import BaseModel, ValidationError, ConfigDict, Field clas...
<python><pydantic>
2024-01-29 20:34:00
0
1,238
jbuddy_13
77,902,407
12,348,406
How to alias an annotated type?
<p>I want to create a type that enables me to associate a type with a positive number.</p> <pre class="lang-py prettyprint-override"><code>type Array = # what I want to create class MyIp: ip: Array[float, 4] # Define a array of 4 elements </code></pre> <p>Under the hood, I was planning to use <code>Annotated</code...
<python><python-typing>
2024-01-29 20:19:14
1
814
gberth
77,902,376
5,842,705
How do I access array elements using int value going from IDL to python?
<p>I am working on code conversion from IDL to python and came across a hurdle. Some code I was given needs to be converted to python. In the IDL version, array element is accessed by int value rather than 3D index. Using the same technique, python gives an error. Any ideas how to resolve this?</p> <p>Here is a snippet...
<python><multidimensional-array><indexing><idl>
2024-01-29 20:12:21
1
407
Charanjit Pabla
77,902,366
967,621
Plotting weighted histograms with weighted KDE (kernel density estimate)
<p>I want to plot two distributions of data as weighted histograms with weighted kernel density estimate (KDE) plots, side by side.</p> <p>The data (<code>length</code> of DNA fragments, split by categorical variable <code>regions</code>) are integers in <code>(0, 1e8)</code> interval. I can plot the default, unweighte...
<python><matplotlib><seaborn><histogram><kernel-density>
2024-01-29 20:11:01
1
12,712
Timur Shtatland
77,902,326
531,358
AutoGen 2.0 Where are my workflows saved?
<p>I'm working in windows, with Microconda and Microsoft AutoGen 2.0. I got AutoGen up and running, and have started creating skills.</p> <p>I want to understand where my work (skills, agents, workflows) is stored, so that I can ensure it's backed up, etc. so I don't lose it.</p> <p>And along the same lines, can I con...
<python><artificial-intelligence><ms-autogen>
2024-01-29 20:02:56
1
708
Sandra
77,902,155
16,459,035
df.at updating multiple indexes on DataFrame pandas
<p>Consider the following code:</p> <pre><code>import pandas as pd import random data = {'col1': [random.randint(0, 100) for _ in range(5)], 'col2': [random.randint(0, 100) for _ in range(5)]} df = pd.DataFrame(data) lista = [] df['test'] = None for index, row in df.iterrows(): lista.append([random.rand...
<python><pandas>
2024-01-29 19:29:45
1
671
OdiumPura
77,902,118
1,428,653
How do you get cattrs to unstructure nested structures?
<p>In Python, with the libraries <code>attrs</code> and <code>cattrs</code>, I have a nested structure defined as follows:</p> <pre class="lang-py prettyprint-override"><code>@attrs.define class Score: added: datetime value: float @attrs.define class Entry: score: Score tags: List[str] added: Opti...
<python><python-attrs>
2024-01-29 19:21:21
1
10,652
Matt
77,902,067
15,781,591
Jupyter Notebook Unreadable because of error: Notebook does not appear to be JSON [Python]
<p>I was working in a Jupyter Notebook, I saved my work, rechecked it and everything looked fine. Three days later I try to open the same notebook and all I see is this error:</p> <pre><code>Unreadable Notebook: C:\Users\my_name\my_repos\my_folder\project_notebook.ipynb NotJSONError('Notebook does not appear to be JSON...
<python><jupyter-notebook>
2024-01-29 19:10:45
0
641
LostinSpatialAnalysis
77,901,884
11,357,695
os getcwd on command line vs editor
<p>I am calling a python 3.10 file from the Anaconda command line (windows, in a conda environment) and noticed that when <code>os.getcwd()</code> is called within a script via command line, it outputs the root directory (I think this is the correct terminology) rather than the directory of the file from which it is ca...
<python><command-line><operating-system><getcwd>
2024-01-29 18:30:51
1
756
Tim Kirkwood
77,901,811
4,200,859
Is there no way to adjust billing_cycle_anchor on Stripe's subscription_update_confirm deep link flow?
<p>Our service awards monthly credits, and therefore handles upgrades and downgrades differently - upgrades get processed straight away so users have access to their new credits. Billing cycle gets changed to 'now' and proration is 'none'. Downgrades do not prorate either, but billing cycle stays the same as it was and...
<python><stripe-payments>
2024-01-29 18:16:34
1
639
Max
77,901,692
9,855,588
python package versioning, using a higher version of a package than another dependency with a lower package version
<p>Consider Project A requirements.txt (project name being foo-bar-a)</p> <pre><code>pyspark==3.1.2 </code></pre> <p>Consider Project B requirements.txt</p> <pre><code>foo-bar-a pyspark==3.3.4 </code></pre> <p>There are a few projects that are using project repo a Python package, so we cant directly update the pyspark ...
<python><python-3.x>
2024-01-29 17:53:06
1
3,221
dataviews
77,901,682
3,780,372
pytest-xdist fails to collect tests after identifying workers
<p>I am unable to figure out why pytest=xdist is failing to collect tests from the <code>tests/sqlalchemy-dialect-compliance</code> folder after it finishes identifying workers. We have used the tests in that folder for years with no problem if we simply use <code>pytest</code>, but as soon as we add <code>pytest-xdist...
<python><python-3.x><sqlalchemy><pytest><pytest-xdist>
2024-01-29 17:51:27
0
4,296
E. Ducateme
77,901,605
12,064,319
Not able to load and predict on images using YOLO inside celery worker
<p>Here is my code</p> <pre><code>import sys from question_detection.inference_object_detection.check_model import verify_model from logger import logger from ultralytics import YOLO class ModelNotFoundError(Exception): pass def load_model(): try: success, model_path = verify_model() logger....
<python><machine-learning><celery><yolov8>
2024-01-29 17:35:56
0
720
Danish Bansal
77,901,487
10,889,650
Getting the Python exception object in a call
<p>Is it possible to get the exception object without relying on the namespace of the except block?</p> <pre><code>try: destined_to_fail() except Exception as e: other_function() def other_function(): # can I get e here, without passing it as an argument? </code></pre>
<python>
2024-01-29 17:14:28
1
1,176
Omroth
77,901,478
8,703,313
update vector field of pandas df
<p>I have a DataFrame with one column holding vector values:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({&quot;a&quot;: [1,2,3], &quot;b&quot;: [4,5,6]}, index=[&quot;one&quot;, &quot;two&quot;, &quot;three&quot;]) s = pd.Series([(i*10, i*11, i*12) for i in df[&quot;a&quot;]], index=df.index)...
<python><pandas><vector>
2024-01-29 17:12:18
2
310
Honza S.
77,901,392
3,197,792
Canonic way to use Namespaces / Bunchs in Python
<p>This is maybe rather a style-question. Often, I use <code>dict</code>s in Python for passing around bundles of variables (like keyword parameters in any function call).</p> <p>However, my interactive environment (<em>ipython</em> or the debugging console in my IDE) does not support <code>dict</code>-key autocomplete...
<python>
2024-01-29 16:57:45
3
727
Leolo
77,901,382
7,347,925
How to crop matplotlib image by circle?
<p>I have plotted some data using matplotlib and wanna crop it by circle from center.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np np.random.seed(100) Z = np.random.rand(10, 10) fig, ax = plt.subplots() ax.imshow(Z) </code></pre> <p>I have tried the idea of masking image:</p> <pre><code>import ma...
<python><numpy><matplotlib><python-imaging-library>
2024-01-29 16:56:11
3
1,039
zxdawn
77,901,290
55,934
pip install "scipy==1.10.1" - What does this error message even mean?
<p>I am trying to install a specific version of scipy using:</p> <pre><code>pip install &quot;scipy==1.10.1&quot; </code></pre> <p>But I'm getting an error I can't interpret:</p> <pre><code> Using cached scipy-1.10.1.tar.gz (42.4 MB) Installing build dependencies ... done Getting requirements to build wheel ... do...
<python><pip><scipy><windows-10>
2024-01-29 16:43:32
3
5,950
Rocketmagnet
77,901,003
7,920,004
Assert one from multiple entries in one CDK property
<p>I need to assert, as part of my TDD, that specific <code>Stage</code> in CodePipeline got created. Tried to use CDK's method but I can't get this code working to retreive only specific <code>Name</code> from all <code>Stages</code> array.</p> <p>Sample data:</p> <pre><code>&quot;Type&quot;: &quot;AWS::CodePipeline::...
<python><amazon-web-services><aws-cloudformation><aws-cdk>
2024-01-29 15:59:29
1
1,509
marcin2x4
77,900,971
9,640,238
pandas FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version
<p>In order to print dataframes nicely using <a href="https://github.com/astanin/python-tabulate" rel="noreferrer">tabulate</a>, so that <code>NaN</code> and <code>NaT</code> are printed as empty cells, I've been using this successfully:</p> <pre class="lang-py prettyprint-override"><code>print(tabulate(df.astype(objec...
<python><pandas><downcast>
2024-01-29 15:54:50
10
2,690
mrgou
77,900,883
2,233,500
Problem accessing Wikipedia page using Python API
<p>I want to extract image URLs from Wikipedia pages. I'm using the <a href="https://pypi.org/project/wikipedia/" rel="nofollow noreferrer">Wikipedia python API</a> for that. I'm having some problems accessing some pages and I cannot understand what is wrong.</p> <p>I'm using the <a href="https://en.wikipedia.org/wiki/...
<python><wikipedia>
2024-01-29 15:42:57
1
867
Vincent Garcia
77,900,818
1,422,096
Why does running a plot in a secondary thread works the first time (with warning), but fails the second time (with error)?
<p>For some quick tests (this code will evolve later anyway, so a temporary solution is ok), I need to use Matplotlib in a <code>thread</code>, and <strong>not</strong> the main thread.</p> <p>Usually we have this warning but it works anyway:</p> <blockquote> <p>UserWarning: Starting a Matplotlib GUI outside of the mai...
<python><multithreading><matplotlib>
2024-01-29 15:31:52
1
47,388
Basj
77,900,729
3,029,238
How to call rev_list with GitPython
<p>This program fails</p> <pre><code>import git repo = git.repo.Repo('..') res = repo.git.rev_list('--since=&quot;2024-01-01&quot; master').split('\n') </code></pre> <p>with the following error</p> <pre><code>git.exc.GitCommandError: Cmd('git') failed due to: exit code(129) cmdline: git rev-list --since=&quot;2024-01-...
<python><python-3.x><git><gitpython>
2024-01-29 15:16:35
1
1,649
Dmitry
77,900,681
1,422,096
Checkboxes to select plots in realtime live matplotlib (interactive) display
<p>Is there a <code>matplotlib</code> built-in way to display <strong>checkboxes</strong> along the legend, allowing the user to select/unselect some of the 3 curves in a realtime live plotting? (I currently refresh data with <code>set_ydata</code>, but I can change this if needed)</p> <pre><code>import numpy as np imp...
<python><matplotlib><visualization><interactive>
2024-01-29 15:07:58
0
47,388
Basj
77,900,469
5,330,527
Turn old Python web app into WSGI-ready and Apache
<p>I have an ancient web application written in Python. It's basically a bunch of .py files. For instance:</p> <p><code>display.py</code>:</p> <pre><code>import cgi import re import string import operator from urllib.parse import urlparse from errors import herigean from routines import * error = False query = cgiFie...
<python><python-3.x><apache><mod-wsgi><wsgi>
2024-01-29 14:37:31
1
786
HBMCS
77,900,299
7,662,164
JAX `grad` error for function with `jax.lax.switch` and compound boolean conditions
<p>I have encountered a scenario where applying <code>jax.grad</code> to a function with <code>jax.lax.switch</code> and compound boolean conditions yields <code>jax.errors.TracerBoolConversionError</code>. A minimal program to reproduce this behavior is the following:</p> <pre><code>from jax.lax import switch import j...
<python><boolean><gradient><jax>
2024-01-29 14:10:05
1
335
Jingyang Wang
77,900,125
9,318,323
Can I release dev and stable versions together
<p>Let's say I have a stable <code>0.8.4</code> version of my package. Let's also say I released a <code>1.0.0.dev1</code> version in a separate branch.</p> <p>Can I still release versions e.g. <code>0.8.5</code> or <code>0.9.0</code> while I am developing my <code>1.0.0</code> version?</p>
<python><pip><python-packaging>
2024-01-29 13:37:29
1
354
Vitamin C
77,899,986
3,833,612
Opencv videocapture ESP32CAM faliure
<p>I am using opencv videocapture to access live video stream from my ESP32CAM server. The video is streaming at url <code>http://172.20.10.10:81/stream</code>.<strong>If I put the url in the web browser, I could actually see the video from my ESP32CAM</strong>. However, I am not able to access this video in jupyter no...
<python><opencv><esp32>
2024-01-29 13:14:27
0
427
user3833612