QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
76,355,619
5,197,034
Detect the format of a datetime string in Python
<p>I'm looking for a way to detect the <code>strftime</code>-style format of a datetime string in Python. All datetime libraries I've found have functionalities for parsing the string to create a datetime object, but I would like to detect the format or pattern that can be used with the <code>datetime.strptime</code> f...
<python><datetime><parsing><format><python-polars>
2023-05-29 08:03:22
4
2,603
pietz
76,355,510
7,657,219
Where can i find pip in linux to add it to my path? Python3.11.3
<p>I've installed Python 3.11.3 in my Linux machine, but every time I need to install an offline package or do something with pip I have to run it using:</p> <blockquote> <p>python3.11 -m pip install &quot;package&quot;</p> </blockquote> <p>But I can't use it just with the command pip (without python3.11) like:</p> <bl...
<python><pip>
2023-05-29 07:45:20
3
353
Varox
76,355,446
1,259,374
String to occurences and back algorithm
<p>So I have this string <code>aabcd</code> and I need to count the number of occurrences and back.</p> <p>This is the first method I have:</p> <pre class="lang-py prettyprint-override"><code>def string_to_occurances(s): dictionary = {} for i in range(int(len(s))): if s[i] in dictionary: diction...
<python>
2023-05-29 07:33:38
3
1,139
falukky
76,355,427
20,646,427
How to make django-filter depend on another django-filter
<p>I'm using package django-filter and i have some fields which i want to be depend on another field like i have field <code>name</code> and field <code>car</code> and if i choose name Michael in <code>name</code> filter, filter <code>car</code> will show me only cars that Michael has</p> <p>This looks like a big probl...
<python><django><django-filter>
2023-05-29 07:30:47
1
524
Zesshi
76,355,339
13,564,858
Bandit vulnerability on 'Drop View <View_Name>'
<p>I am not sure why bandit is notifying the below as 'Detected possible formatted SQL query. Use parameterized queries instead.':</p> <pre><code> conn.execute(f&quot;DROP VIEW {view_name};&quot;) </code></pre> <p>Is there a way to parameterize the view_name? or concatenation is the only way forward to remove bandit...
<python><sql-injection><parameterization><bandit-python>
2023-05-29 07:15:21
1
429
Lucky Ratnawat
76,355,115
11,197,301
read values in a file and convert them according to their type in python
<p>I have the following file:</p> <pre><code> 10 10 11 10530 18 100 0 Open ; 11 11 12 5280 14 100 0 Open ; 12 ...
<python><input><type-conversion>
2023-05-29 06:30:50
1
623
diedro
76,354,999
13,710,421
How to transfer dictionary to dataframe
<p>There is dictionary <code>dic_1</code> , i want transfer it to <code>dataframe</code> (the result just like the result of <code>val_1.append(val_2)</code>), but code <code>pd.DataFrame(dic_1)</code> failed .How to fixed it ?</p> <pre><code>import pandas as pd val_1 = pd.DataFrame({'category':['a','b'],'amount':[1,3...
<python><pandas><dictionary>
2023-05-29 06:05:05
2
2,547
anderwyang
76,354,983
2,598,184
List all folders from ClickUp space
<p>I'm trying to list all folders created under particular ClickUp space, but it's not giving me desired result. Below is the snippet,</p> <pre><code>import requests # Enter your ClickUp API token here api_token = 'pk_xxxxxxxxxxx' # Space ID for the desired space space_id = '1234567' # API endpoint for retrieving fo...
<python><clickup-api>
2023-05-29 06:01:16
1
418
Rahul
76,354,939
12,436,050
Load data to Oracle db through flat file
<p>Is there a way to load data from a flat file to an oracle table. I am using following python code but the file is too big and the script stops after sometime (due to lost db connection).</p> <pre><code>from tqdm import tqdm insert_sty = &quot;insert into MRSTY (CUI,TUI,STN,STY,ATUI,CVF) values (:0,:1,:2,:3,:4,:5)&q...
<python><oracle-database>
2023-05-29 05:50:34
1
1,495
rshar
76,354,598
13,710,421
In python/pandas, how to filter the dataframe whice condition stored in list
<p>in python/pandas, how to filter the dataframe the condition stored in list ? Below code <code>ori_data[ori_data['category'] in ['a','d','f']]</code> can't work</p> <pre><code>import pandas as pd ori_data = pd.DataFrame({'category':['a','a','b','c','d','f']}) filtered_data = ori_data[ori_data['category'] in ['a','d',...
<python><pandas>
2023-05-29 03:57:56
1
2,547
anderwyang
76,354,557
9,510,800
Hide whiskers and outliers in box plot plotly express and adjust color tone python
<p>Is it possible to remove the whiskers and outliers in plotly express box plot in python ? My code looks like below: Also, is there a way, I can give 2 sets of colors ? for example I have 3 labels and each label has 2 categories. I wanted to have same color for each label but the color tone alone, I wanted to reduce ...
<python><plotly>
2023-05-29 03:41:02
0
874
python_interest
76,354,467
6,458,245
RuntimeError: Expected all tensors to be on the same device?
<p>I am getting this runtime error here:</p> <pre><code>RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_CUDA_addmm) </code></pre> <p>However, all the tensors I've created here are on cuda. Does anyon...
<python><pytorch>
2023-05-29 03:09:05
1
2,356
JobHunter69
76,354,242
2,769,240
f string to pass file path issue
<p>I have a function which accepts a file path. It's as below:</p> <pre><code>def document_loader(doc_path: str) -&gt; Optional[Document]: &quot;&quot;&quot; This function takes in a document in a particular format and converts it into a Langchain Document Object Args: doc...
<python><streamlit>
2023-05-29 01:44:47
1
7,580
Baktaawar
76,354,204
7,766,024
Flask's order of rendering functions?
<p>I'm trying to set up a basic website to practice Flask and have the following in my <code>app.py</code> file:</p> <pre><code>from flask import Flask, render_template app = Flask(__name__) @app.route(&quot;/&quot;) def hello_world(): return &quot;Hello, world!&quot; @app.route('/') def home(): return re...
<python><flask>
2023-05-29 01:25:45
1
3,460
Sean
76,354,125
6,159,217
3d scatter plot is displaying a black window
<p>Here is an example of matplotlib displaying a black window on my local environment.</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np fig = plt.figure() ax = Axes3D(fig, elev=4, azim=-95) xs, ys, zs = np.linspace(-2, 2, 60), np.linspace(-2, 2, 60), np.linspace...
<python><matplotlib><mplot3d><matplotlib-3d><scatter3d>
2023-05-29 00:51:44
1
972
IntegrateThis
76,354,103
13,608,794
Rendering audio graph with correct volume level
<p>On the images below, the same audio file is represented. On the left side, there's a <strong>correct, original and NOT NORMALIZED audio preview</strong>.</p> <p>I want to fix the following problems of the matplotlib's graph:</p> <ul> <li><h2>Correct the audio level (amplitude)</h2> </li> <li>Stop truncating the heig...
<python><matplotlib><audio><waveform>
2023-05-29 00:42:18
0
303
kubinka0505
76,353,867
8,671,089
org.apache.kafka.common.KafkaException: Failed to construct kafka producer
<p>I have a docker-compose.yml file, running kafka server and creating kafka topic. running docker compose and tests from github workflow</p> <h2>docker-compose.yml</h2> <pre><code>version: &quot;3.8&quot; networks: kafka-network: driver: bridge services: kafka: container_name: kafka image: bitnami/kaf...
<python><pyspark><apache-kafka><github-actions>
2023-05-28 22:47:04
2
683
Panda
76,353,680
4,966,945
Read Parquet files without reading into memory (using Python) from URL
<p>I am trying to read NY data set which is stored &amp; publically available <a href="https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page" rel="nofollow noreferrer">here</a>, I extracted the underlying location of the parquet file for the 2022 as &quot;https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tr...
<python><download><stream><parquet><pyarrow>
2023-05-28 21:30:26
2
667
av abhishiek
76,353,462
14,852,106
Get value from rows not null XLSXWRITER (python)
<p>I want to merge column 2 (with &quot;description&quot;) same to column 1(with &quot;name&quot;) : same number of rows to merge , but when using merge_range I got null value in the column 2.</p> <p>Here is my code.</p> <pre><code> my_list = [ {'field1': [ {'name': 'value1', 'description': ...
<python><excel><xlsxwriter>
2023-05-28 20:23:19
1
633
K.ju
76,353,461
5,210,803
ANTLR4 python target not working with some special rule names
<p>For example, if my grammar contains a rule named <code>state</code>:</p> <pre><code>// Grammar.g4 grammar Grammar; program : state* EOF ; state: 'break;' | 'continue;' | 'return;' ; </code></pre> <p>The <code>GrammarParser.py</code> generated by <code>antlr4 -Dlanguage=Python3 Grammar.g4</code> will raise an except...
<python><antlr4>
2023-05-28 20:22:50
0
3,852
xmcp
76,353,403
12,436,050
Adding progress monitor while inserting data to a Oracle db using Python
<p>I would like to add a progress bar in my python script. I am running following lines of code. I am reading a file 'MRSTY.RRF' which is 0.195 MB. I would like to how much file has been processed.</p> <pre><code>insert_sty = &quot;insert into MRSTY (CUI,TUI,STN,STY,ATUI,CVF) values (:0,:1,:2,:3,:4,:5)&quot; records=[]...
<python><oracle-database>
2023-05-28 20:08:05
1
1,495
rshar
76,353,265
9,261,745
sqlalchemy call mysql procedure to read the multiple results
<p>I am trying to get the multiple results from procedure in mysql by using sqlalchemy in python.</p> <pre><code>async def create_user(db: AsyncSession, user: UserInfo): try: result_proxy = await db.execute( text(&quot;CALL create_user(:account)&quot;), { &quot;accou...
<python><mysql><stored-procedures><sqlalchemy>
2023-05-28 19:27:47
1
457
Youshikyou
76,353,116
2,131,907
Can I create a venv with already locally installed packages?
<p>I already have some locally installed Python packages in <code>~/.local</code>. Some of them are self-built packages. And now I want to create a new virtual environment, is there any way to create a virtual environment with those locally installed packages?</p> <p><code>pip -r requirement.txt</code> doesn't work for...
<python><python-venv>
2023-05-28 18:52:38
1
364
user2131907
76,352,883
5,822,440
How to use snowball (.sbl) file in Python
<p>I am a first-year Master's student currently learning NLP with Python. My professor has assigned me a mini project that involves implementing Porter Stemmer in Snowball Language. However, I am a bit confused and would appreciate some assistance from anyone experienced with Snowball (.sbl).</p> <p>Specifically, I wou...
<python><nltk><snowball>
2023-05-28 18:01:26
0
411
Fatihi Youssef
76,352,834
7,895,542
Polars: Pad list columns to specific size
<p>I think i ran into the XY problem...</p> <p>Here is what i actually want to do:</p> <p>To be exact i have a dataframe like:</p> <pre><code>shape: (3, 3) ┌───────────┬───────┬──────────────────────────┐ │ nrs ┆ stuff ┆ more_stuff │ │ --- ┆ --- ┆ --- │ │ list[i64] ┆ i64...
<python><python-polars>
2023-05-28 17:51:47
2
360
J.N.
76,352,655
325,809
Generate data from the results of .describe() in pandas
<p>I don't have access to the actual dataset, but I do have access to the results of the dataframes' <code>.describe()</code>. I need to construct some data that has similar statistics. Is there a way to generate random data that matches those statistics? ie I would ideally like a <code>data_generator(pd.DataFrame) -&g...
<python><pandas>
2023-05-28 17:13:18
1
6,926
fakedrake
76,352,457
5,623,899
How to convert a conda env yaml file to a list of requirements for a settings.ini file accounting for channels and conversions for pypi
<p><strong>NOTE</strong>: you can start at <a href="https://stackoverflow.com/questions/76352457/how-to-convert-a-conda-env-yaml-file-to-a-list-of-requirements-for-a-settings-in/76352458/#problem-formulation">Problem formulation</a>. The motivation section just explains how I found myself asking this.</p> <h1>Motivatio...
<python><pip><conda><nbdev>
2023-05-28 16:22:43
1
5,218
SumNeuron
76,352,445
7,895,542
Polars how to turn column of type list[list[...]] into numpy ndarray
<p>I know I can turn a normal polars series into a numpy array via <code>.to_numpy()</code>.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl s = pl.Series(&quot;a&quot;, [1,2,3]) s.to_numpy() # array([1, 2, 3]) </code></pre> <p>However that does not work with a list type. What would be they wa...
<python><numpy><python-polars>
2023-05-28 16:19:36
1
360
J.N.
76,352,280
13,709,317
Can a python function be both a generator and a "non-generator"?
<p>I have a function which I want to yield bytes from (generator behaviour) and also write to a file (non-generator behaviour) depending on whether the <code>save</code> boolean is set. Is that possible?</p> <pre class="lang-py prettyprint-override"><code>def encode_file(source, save=False, destination=None): # enc...
<python><generator>
2023-05-28 15:42:02
2
801
First User
76,352,244
3,610,891
How to create diff environments for different Python packages in production
<p>I am new to Python as well as Azure, so I might be missing some crucial information with my design. We have couple of libraries which are created to be used by user while working on their Azure ML workspace. Now, this questions remain same if we are creating libraries for user to be used in a simple Jupyter notebook...
<python><azure><virtualenv><azure-machine-learning-service><azuremlsdk>
2023-05-28 15:32:52
1
2,115
Onki
76,352,198
11,080,806
How to compare two Python ASTs, ignoring arguments?
<p>I want to elegantly compare two Python expressions ignoring any differences in the arguments. For example comparing <code>plt.show()</code> and <code>plt.show(*some-args)</code> should return <code>True</code>.</p> <p>I've tried parsing the expressions using <code>ast</code> as follows:</p> <pre class="lang-py prett...
<python><abstract-syntax-tree>
2023-05-28 15:23:10
1
568
Jonathan Biemond
76,352,175
18,018,869
Separate form fields to "parts"; render part with loop, render part with specific design, render part with loop again
<p>I want to render part of the form via a loop in template and a part with specific &quot;design&quot;.</p> <pre class="lang-py prettyprint-override"><code># forms.py class HappyIndexForm(forms.Form): pizza_eaten = forms.IntegerField(label=&quot;Pizzas eaten&quot;) # 5 more fields minutes_outside = forms.I...
<python><django><django-forms><django-templates>
2023-05-28 15:16:30
0
1,976
Tarquinius
76,352,024
6,357,916
Escaping % in django sql query gives list out of range
<p>I tried running following SQL query in pgadmin and it worked:</p> <pre><code> SELECT &lt;columns&gt; FROM &lt;tables&gt; WHERE date_visited &gt;= '2023-05-26 07:05:00'::timestamp AND date_visited &lt;= '2023-05-26 07:07:00'::timestamp AND url LIKE '%/mymodule/api/myurl/%'; </code></pre> <p>I wante...
<python><sql><django><django-rest-framework>
2023-05-28 14:40:39
2
3,029
MsA
76,351,958
2,715,498
Superclass property setting using super() and multiple inheritance
<p>In a real world program I have ran into the next problem: I have a diamond inheritance having SuperClass, MidClassA, MidClassB and SubClass. SuperClass has a property (a filename, actually) that is used by its successors, but different ways (with or without extension). At all levels I want to set this property by a ...
<python><properties><method-resolution-order>
2023-05-28 14:22:32
2
3,372
Gyula Sámuel Karli
76,351,947
7,895,542
Polars convert string of digits to list
<p>So i have a polars column/series that is strings of digits.</p> <pre><code>s = pl.Series(&quot;a&quot;, [&quot;111&quot;,&quot;123&quot;,&quot;101&quot;]) s shape: (3,) Series: 'a' [str] [ &quot;111&quot; &quot;123&quot; &quot;101&quot; ] </code></pre> <p>I would like to convert each string into a list o...
<python><python-polars>
2023-05-28 14:20:04
1
360
J.N.
76,351,894
11,584,730
jinja2 unpack unknown number of values
<p>I'm wondering how to unpack a tuple with an unknown number of variables in Jinja2. Specifically, I'm looking for an equivalent syntax or approach in Jinja2 that achieves the same effect as the following Python code:</p> <pre><code>a,*_ = d,f,g,e </code></pre> <p>In the Python code above, the *_ syntax allows me to d...
<python><flask><jinja2>
2023-05-28 14:08:08
1
620
Itay Lev
76,351,798
3,416,774
Variables and their values are stored externally in a YAML file. How to read them as if I declare them internally?
<p>Instead of having to declare the variables and their values in the script, I would like to have them declared externally in a separate YAML file called <code>settings.yml</code>:</p> <pre class="lang-yaml prettyprint-override"><code>setting1: cat setting2: dog </code></pre> <p>Is there a way to use the variables' na...
<python><yaml><pyyaml>
2023-05-28 13:45:48
2
3,394
Ooker
76,351,690
1,239,299
Pycharm does not support Blenders Bpy package
<p>I'm trying to use Blenders bpy package in Pycharm.</p> <p>I'm using the correct version of Python (3.10)</p> <p>And have used pip to install the bpy package</p> <p><a href="https://i.sstatic.net/y5OpR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/y5OpR.png" alt="enter image description here" /></a><...
<python><pycharm>
2023-05-28 13:15:24
0
817
user1239299
76,351,660
15,839,694
Endless trace messages when converting python kivy program to exe file with pyinstaller
<p>So i am trying to convert an example kivy program into an exe standalone file from this documentation page, just as a bleak example to investigate why my pyinstaller and kivy do not work: <a href="https://kivy.org/doc/stable/tutorials/firstwidget.html" rel="nofollow noreferrer">https://kivy.org/doc/stable/tutorials/...
<python><python-3.x><kivy><pyinstaller><trace>
2023-05-28 13:10:08
1
317
Coder Alpha
76,351,556
7,895,542
Polars Series.to_numpy() does not return ndarray
<p>I was trying to convert a series to a numpy array via <code>.to_numpy()</code> but unlike what the documentation shows i am not getting a ndarray out but a seriesview</p> <p>Running exactly the example in the documentation: <a href="https://pola-rs.github.io/polars/py-polars/html/reference/series/api/polars.Series....
<python><numpy><numpy-ndarray><python-polars>
2023-05-28 12:43:38
2
360
J.N.
76,351,518
4,451,521
tox skipped because could not find python interpreter
<p>I am having a problem using <em>tox</em>. I have to say first that I am not an expert on virtual environments, and I prefer to use <em>conda</em> environments, I find them much more easy to use and understand.</p> <p>So as the background of my system I have a Ubuntu 18 system, where Python is 3.6.9. I also have a <...
<python><tox>
2023-05-28 12:35:57
2
10,576
KansaiRobot
76,351,373
1,319,998
Test that a ZIP doesn't require zip64 support
<p>I'm looking to test some Python code makes zip files that dynamically chooses zip32 or zip64, and I would like to assert that in certain cases it really does create valid zip32 files by opening it in something that does not support zip64.</p> <p>How can I check that a file really is openable by something that doesn'...
<python><zip><deflate>
2023-05-28 11:58:34
2
27,302
Michal Charemza
76,351,319
3,247,006
How to set the current time to "TimeField()" as a default value in Django Models?
<p>The doc says below in <a href="https://docs.djangoproject.com/en/4.2/ref/models/fields/#django.db.models.DateField.auto_now_add" rel="nofollow noreferrer">DateField.auto_now_add</a>:</p> <blockquote> <p>Automatically set the field to now when the object is first created. ... If you want to be able to modify this fie...
<python><django><datetime><django-models><default>
2023-05-28 11:47:10
2
42,516
Super Kai - Kazuya Ito
76,351,097
2,302,262
"boolean" nunique in pandas object dataframes
<h2>The goal</h2> <p>I have a long narrow dataframe <code>df</code> (30k x 15), and want to see for each row, if <em>all</em> the values are unique or not.</p> <p>The values in the dataframe are not necessarily float or int values, but may also be objects. This questions is about the latter case, as it slows things dow...
<python><pandas><dataframe>
2023-05-28 10:49:36
1
2,294
ElRudi
76,350,376
7,149,485
Django : Edit main.html to reference static webpage
<p>I am learning Django and I am still very new to it so I don't yet understand how all the pieces fit together.</p> <p>I have successfully built the polls application on the tutorial website (<a href="https://docs.djangoproject.com/en/4.2/intro/tutorial01/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/4...
<python><django>
2023-05-28 07:18:34
1
1,169
brb
76,350,255
2,514,521
Is there a standard class that implements all the int-like magic methods by calling int(self)?
<p>Please note: I have made edits since some of these responses were given, due to my bad wording. Blame me. Thanks to everyone for putting up with me.</p> <p>I am writing a class that has int-like properties.</p> <p>It implements the <code>__int__</code> method.</p> <p>I'd like to implement all the magic methods that ...
<python>
2023-05-28 06:40:37
2
5,929
AMADANON Inc.
76,350,008
11,117,265
isinstance based custom validator in pydantic for custom classes from third party libraries
<p>In my custom package for work, I want to validate inputs using <code>pydantic</code>. However, most of my functions take inputs that are not of native types, but instances of classes from other libraries, e.g. <code>pandas.DataFrame</code> or <code>sqlalchemy.Engine</code>. Mentioning these as type hints and adding ...
<python><python-3.x><pydantic>
2023-05-28 05:05:57
1
1,676
yarnabrina
76,349,990
336,527
How to delete a python variable whose name is only known at runtime?
<p>I need to do the equivalent of the <code>del</code> statement when the variable name is only known dynamically.</p> <p>For the global namespace, I believe <code>del globals()[name]</code> works correctly.</p> <p>For the local namespace, <code>del locals()[name]</code> is incorrect since <code>locals()</code> is not ...
<python>
2023-05-28 04:55:58
1
52,663
max
76,349,868
11,482,269
Python mariadb-connector function returns empty cursor.fetchall() on 252nd iteration with different WHERE clauses
<p>Caveats: Linux Distribution prevents upgrade beyond connector 3.1.20 and thus python module 1.0.11</p> <p>Versions from /usr/bin/mariadb_config Copyright 2011-2020 MariaDB Corporation AB Get compiler flags for using the MariaDB Connector/C. Usage: mariadb_config [OPTIONS] Compiler: GNU 10.2.1</p> <p>--version ...
<python><python-3.x><mariadb-10.5><mariadb-connector>
2023-05-28 03:56:41
1
351
Joe Greene
76,349,851
19,504,610
Accessing variables in the local scope of a python decorator
<p>Consider:</p> <pre><code>def g(value): def f(): return value return f x = g(3) x() # prints 3 </code></pre> <p>Given <code>x</code> in the example, the returned closure from <code>g(3)</code>, is there any way to inspect that is the value of <code>value</code> without calling <code>x()</code>?</p>
<python><scope><closures><local>
2023-05-28 03:45:57
1
831
Jim
76,349,775
14,012,470
Removing Noise and Detecting Circle in Spotlight Using OpenCV
<p>I have been trying to detect circles in spotlight images using OpenCV and have a variety of pictures I am working with, generally looking something like these 4 images:</p> <p><a href="https://i.sstatic.net/6RQKh.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6RQKh.jpg" alt="enter image description h...
<python><opencv><image-processing>
2023-05-28 03:03:11
1
1,511
AS11
76,349,651
16,595,100
Python Curses: Check if cursor is hidden
<p>I am wanting to write a function to ask the user input using Python curses. The problem I am having is I want to have the cursor hidden in other parts of the program except in the text-box. I intend to use this function in many cases and if the cursor is hidden before the function call, it should be returned to that...
<python><ncurses><python-curses>
2023-05-28 01:42:23
1
673
Enderbyte09
76,349,589
1,105,249
How do I ensure the created uinput.Device instance is always the same?
<p>In Python3, instances for gamepad controllers can be created using <code>python-uinput</code> module. The code may look something like this:</p> <pre><code>device = uinput.Device(list_of_events, name=name, bustype=0x06, vendor=0x2357, product=0x1, version=mode) </code></pre> <p><em>While I forced some values, where ...
<python><uinput>
2023-05-28 01:06:08
0
12,383
Luis Masuelli
76,349,549
7,995,293
Python script called by Zsh function: why does printing the python output work, but returning the same output does not?
<p>I have a large nested file structure; navigating from one working folder to the next requires verbose commands like <code>cd ../../../../path/to/working/file</code>. Fortunately, the files are consistently named: <code>part01_Part01-04.fileName/src/main/</code> To make navigation easier, I've written a Python script...
<python><zsh><zshrc>
2023-05-28 00:38:05
0
399
skytwosea
76,349,404
427,083
Django rest_framework serializer dynamic depth
<p>I am using a ModelSerializer to serialize a model. How do I have <code>depth = 1</code> when retrieving a single instance, and <code>depth = 0</code> when retrieving a list.</p> <pre><code>from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User ...
<python><django><django-rest-framework><django-serializer>
2023-05-27 23:24:18
1
80,257
Mundi
76,349,378
17,987,266
How to log method calls from derivate classes in an asynchronous way?
<p>I'm implementing a logger of method calls from derivate classes as suggested by this <a href="https://stackoverflow.com/a/58656725/17987266">answer</a>:</p> <pre class="lang-py prettyprint-override"><code>class Logger: def _decorator(self, f): @functools.wraps(f) def wrapper(*args, **kwargs): ...
<python><multithreading><asynchronous><logging><async-await>
2023-05-27 23:11:54
1
369
sourcream
76,349,264
5,611,471
How to retain the data type datetime64 with the format ("%m/%d/%Y") in pandas?
<p>Please, wait before marking it as a duplicate.<br> These posts <br> <a href="https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas">How to change the datetime format in Pandas</a> <br> <a href="https://stackoverflow.com/questions/38333954/converting-object-to-datetime-format-in-pyt...
<python><pandas>
2023-05-27 22:18:22
0
529
007mrviper
76,349,202
8,869,570
Composed object needs access to parent class method
<p>I have a class <code>Round</code> that has a <code>Calc</code> composed class object. <code>Round</code> also inherits from several base classes, and inherits a method called <code>parameter</code> from one of its base classes.</p> <p><code>Calc</code> has a method, <code>compute</code>, that is called from a method...
<python><inheritance><composition>
2023-05-27 21:54:33
0
2,328
24n8
76,349,192
3,604,745
Rasa - ‘from_entity’ mapping for a non-existent entity
<p>This Rasa issue seems to not really be described by the “Warning” (and the “Warning” in this case is effectively an error). It has this message for every slot and entity:</p> <p><code>/rasa/shared/utils/io.py:99: UserWarning: Slot ‘name’ uses a ‘from_entity’ mapping for a non-existent entity ‘name’</code>. Skipping ...
<python><rasa><rasa-nlu><rasa-sdk>
2023-05-27 21:52:25
0
23,531
Hack-R
76,349,101
13,460,543
How to select rows until an element is encountered in a column?
<p>Let's suppose we have the following dataframe :</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame(index=['A', 'B', 'C', 'D'], data = [1,2,3,3]) </code></pre> <p>which gives us the following dataframe :</p> <pre><code>df 0 A 1 B 2 C 3 D 3 </code></pre> <p>I was looking ...
<python><pandas>
2023-05-27 21:22:59
2
2,303
Laurent B.
76,348,906
1,278,365
SQLAlchemy 2.x: Eagerly load joined collection query
<h2>Context</h2> <p>With SQLAlchemy 2.x, how to eagerly load a joined collection?</p> <p>Let's say we have the following models <code>Parent</code> and <code>Child</code>:</p> <pre class="lang-py prettyprint-override"><code>class Parent(Base): __tablename__ = &quot;parent&quot; id: Mapped[int] = mapped_column(p...
<python><sql><sqlalchemy>
2023-05-27 20:28:12
2
2,058
gmagno
76,348,824
7,453,065
Meaning of Python's @setter decorator
<p>In the website <a href="https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work-in-python">How does the @property decorator work in Python?</a> you can find many answers about the meaning of the @property decorator, but no answer about the corresponding @propertyname.setter decorator.</p> <...
<python><properties>
2023-05-27 20:05:55
2
744
Dietrich Baumgarten
76,348,589
9,620,095
How to display Break page by default with XLSXWRITER
<p>I added the configuration of break page .I want to know if is it possible to display page break view by default in xlsxwriter (python)?</p> <p>I tried with <code>sheet.set_page_break_view()</code> but I got error .</p>
<python><excel><xlsxwriter>
2023-05-27 19:08:56
2
631
Ing
76,348,551
982,049
Launching Python scripts on Kotlin server for Android app?
<p>Tldr; how to launch python scripts for multiple clients at the same time using Kotlin server side code for Android clients.</p> <p>I am developing an Android app using Kotlin for client side as well as server side code. However, I want to use some libraries for NLP using Python. This is required for text input by an...
<python><android><kotlin>
2023-05-27 19:00:50
1
5,113
Cool_Coder
76,348,441
2,029,836
Cant resolve Import exception in python using Visual Studio Code
<p>I am getting following exceptions when trying to execute a Python script in Visual Studio Code (VSC). I suspect this is a simple env config issue but am new to Python and can't see it.</p> <blockquote> <p>Import &quot;openai&quot; could not be resolved by Pylance Import &quot;gradio&quot; could not be resolved by Py...
<python><visual-studio-code><import><openai-api><gradio>
2023-05-27 18:34:12
1
2,281
dancingbush
76,348,350
18,092,798
Writing out sparse matrix as a compressed gzip file
<p>I have a sparse matrix <code>m</code> (scipy.sparse.coo_matrix) and a output path <code>p</code> (example <code>p=&quot;~/matrix.mtx.gz&quot;</code>). I'm using <code>scipy.io.mmwrite</code> to write out <code>m</code> (to the path <code>p</code>), but it doesn't appear to have any compression options. Is there a wa...
<python><scipy>
2023-05-27 18:08:32
1
581
yippingAppa
76,348,268
20,130,220
Clicking loading button with selenium doesnt work
<p>I try to load all comments from this site to scrape them but i cant figure out how to load them all.</p> <p>When i run my code i get error in console it says:</p> <blockquote> <p>WebDriverWait(driver, 20).until(EC.element_to_be_clickable( File &quot;C:\Users\Jakub\dev\rok_quests\rok_quests\Lib\site-packages\seleni...
<python><selenium-webdriver><web-scraping><beautifulsoup>
2023-05-27 17:49:03
1
346
IvonaK
76,348,264
1,927,108
How can I understand why Sphinx fails with code -4 within GitLab CI?
<p>I am trying to build the docs of my project with <em>Sphinx</em>, <em>tox</em>, and <em>GitLab CI</em>. Although it works fine locally I am getting this very unintuitive error without any proper error message on <em>GitLab CI</em>. Any ideas on what might be going on and how to fix it?</p> <p>Everything is pretty mu...
<python><gitlab-ci><python-sphinx><tox><pyscaffold>
2023-05-27 17:48:41
0
1,440
gkcn
76,348,254
11,720,193
Error in syntax of fields while exporting data from Botify
<p>I am trying to pull website crawl data from Botify by using Python leveraging the Botify Query Language. Now, to retrieve the crawled values from Botify, the following JSON needs to be sent to Botify using Python <code>requests.PUT()</code>.</p> <p>Below is a sample JSON string provided which works fine when sent to...
<python><python-requests><bots>
2023-05-27 17:45:44
0
895
marie20
76,348,088
6,290,211
How to simulate a starting queue before opening times in a Simulation process with Simpy?
<p>I am studying SimPy and I came across <a href="https://medium.com/swlh/simulating-a-parallel-queueing-system-with-simpy-6b7fcb6b1ca1" rel="nofollow noreferrer">this interesting tutorial</a> that allows to simulate a queue in a bank.</p> <p>I wanted to know if it is possible and how to create an initial queue.</p> <p...
<python><simulation><simpy><traffic-simulation><event-simulation>
2023-05-27 17:10:44
1
389
Andrea Ciufo
76,348,086
9,877,065
PyQt5 QThread.self.setTerminationEnabled(False) seems not to work
<p>borrowing from <a href="https://stackoverflow.com/questions/27961098/pyside-qthread-terminate-causing-fatal-python-error">PySide QThread.terminate() causing fatal python error</a> I tried this example:</p> <pre><code>from PyQt5 import QtCore, QtGui, QtWidgets class Looper(QtCore.QThread): &quot;&quot;&quot;QT...
<python><multithreading><pyqt><pyqt5><qthread>
2023-05-27 17:10:35
1
3,346
pippo1980
76,348,055
5,330,527
Check if an id is in another model's field, and get the connected values
<p>Given these two models:</p> <pre><code>class Event(models.Model): title = models.CharField(max_length=200) class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE,null=True, blank=True) event = models.ForeignKey('Event', on_delete=models.CASCADE) class Venue(models.Mode...
<python><django><django-models><django-views>
2023-05-27 17:03:42
1
786
HBMCS
76,347,562
3,821,009
Initialize polars dataframe from list of structs
<p>These two make sense:</p> <pre><code>df = polars.DataFrame(dict( j=1, )) print(df) print(df.schema) j 1 shape: (1, 1) {'j': Int64} df = polars.DataFrame(dict( j=range(2) )) print(df) print(df.schema) j 0 1 shape: (2, 1) {'j': Int64} </code></pre> <p>However:</p> <pre><code>cols = list('ab') df = p...
<python><python-polars>
2023-05-27 15:10:27
1
4,641
levant pied
76,347,524
1,481,314
AWS Lambda works but Lambda@Edge throws error
<p>I have written a python lambda to redirect unauthorized users to Cognito. The lambda works when I run a test event in the lambda console, but when I try to hit the CloudFront distribution, I get the following error:</p> <pre><code>[ERROR] Runtime.ImportModuleError: Unable to import module 'app': No module named 'py...
<python><amazon-web-services><aws-lambda-edge><pyjwt>
2023-05-27 15:01:18
1
1,718
Danny Ellis Jr.
76,347,173
5,166,312
How to use pyOCD, or open OCD from Python
<p>I want to use <code>pyOCD</code> (or open OCD) for some operation with <code>STLink</code> and <code>STM32</code> MCU. I found this list of commands <a href="https://pyocd.io/docs/command_reference.html#find" rel="nofollow noreferrer">https://pyocd.io/docs/command_reference.html#find</a> but I am not wise from that ...
<python><gdb><stm32><openocd>
2023-05-27 13:30:06
1
337
WITC
76,347,065
11,594,202
Custom Exception for missing fields in pydantic
<p>I want to catch the exception that validators raise of a Pydantic as such. I currently got a working set up like so:</p> <pre><code>class MissingPhoneNumber(ValueError): pass class SMS(Basemodel): id: str phone_number: Optional[str] = None @validator('phone_number', always=True) ...
<python><exception><pydantic>
2023-05-27 13:05:32
1
920
Jeroen Vermunt
76,346,946
5,431,734
size on disk of pickled objects
<p>I want to serialize an object (which contains other objects etc) and I would like to exclude (if possible) attributes that take up a lot space when the pickle file is saved on the disk. I plan to do this by deleting the attribute while manipulating <code>__getstate__(self)</code> of my (top level) class, for example...
<python><pickle>
2023-05-27 12:33:47
1
3,725
Aenaon
76,346,900
8,665,962
Finding a clever way to set a threshold given a list of loss values
<p>Assume I have a list of losses plotted in the following KDE plot:</p> <p><a href="https://i.sstatic.net/ioufT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ioufT.png" alt="enter image description here" /></a></p> <p>If the goal is to spot the outliers, the best threshold would be clearly around <cod...
<python><python-3.x><anomaly-detection>
2023-05-27 12:24:37
1
574
Dave
76,346,896
12,902,027
How can you find where a specified function is defined in a library?
<p>For example, I am investigating the implementation of <code>torch.nn.Embedding</code> class. I guessed this would be in some file in <code>nn</code> directory and found the class in <a href="https://github.com/pytorch/pytorch/blob/main/torch/nn/modules/sparse.py#L13" rel="nofollow noreferrer">torch/nn/module/sparse....
<python><pytorch><embedding>
2023-05-27 12:23:44
1
301
agongji
76,346,891
11,232,272
Should I deactivate current conda env before creating a new one?
<p>Does it make any difference in creating a new conda environment from which conda environment? I mean, should I create all of my environments from the <code>base</code> environment?</p>
<python><conda>
2023-05-27 12:22:48
1
741
Matin Zivdar
76,346,847
11,720,193
Create JSON dynamically reading file from S3
<p>I am working on AWS Glue and writing a a <code>requests</code> program to query Botify (with BQL). I need to have a json (requred for POST) which should be <strong>dynamically</strong> created with the queried fields. The fields that needs to be queried resides in a text file on S3. We should be able to read the S3 ...
<python><python-requests><python-jsons>
2023-05-27 12:10:07
2
895
marie20
76,346,786
1,935,655
Python OpenCV Mediapipe Overlay Triangle on landmark on face
<p>I am wanting to take a triangle from an image and overlay it at the same location on my face in video camera.</p> <p>I am using python mediapipe to get the landmarks and it seems I am able to get the correct triangle, but it doesn't overlay on the correct location properly.</p> <p>Mediapipe landmarks: <a href="https...
<python><opencv><mediapipe>
2023-05-27 11:54:20
0
1,214
LUser
76,346,764
2,889,716
Celery task queue is not registered
<p>In my code only task1-queue will be registered. Why? <code>pass-params.py</code></p> <pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI from celery import Celery, chain app = FastAPI() celery_app = Celery('tasks', broker='redis://localhost:6379/0', # broker URL ...
<python><celery>
2023-05-27 11:49:36
0
4,899
ehsan shirzadi
76,346,637
4,512,218
Can PyCharm suggest available methods?
<p>PyCharm Professional does not suggest methods while typing (for any library).</p> <p>For example, in the screenshot below, I would expect to see methods I can call on <code>service</code> in the autosuggest popover (like I would in WebStorm or PhPStorm). I only get &quot;not&quot;, &quot;par&quot; and &quot;main&quo...
<python><pycharm><jetbrains-ide>
2023-05-27 11:17:19
1
1,339
Cellydy
76,346,518
2,925,976
Odoo Python Function TypeError: EventBooth.check_app_installed() missing 1 required positional argument: 'self'
<p>What is necessary to make this peace of code working? I always get the error &quot;Function TypeError: EventBooth.check_app_installed() missing 1 required positional argument: 'self'&quot;. Meanwhile I tried a lot of different approaches, but nothing worked.</p> <pre><code>from odoo import models, fields, api class...
<python><function><odoo><self>
2023-05-27 10:47:01
1
628
Perino
76,346,318
12,751,927
Why my request works in python but not with curl
<p>Hi i try fetch from this <a href="https://dooood.com/d/h9rojbkqnpan" rel="nofollow noreferrer">url</a> with curl and i got 403 error but it perfectly work in python with request</p> <p>python code</p> <pre><code>import requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit...
<python><curl><python-requests><http-headers><http-status-code-403>
2023-05-27 09:50:25
1
335
linkkader
76,345,708
3,909,896
Passing kwargs via dict to a function and overwriting a single passed kwarg in an elegant way
<p>Thanks to <a href="https://stackoverflow.com/questions/50989404/how-do-i-pass-variable-keyword-arguments-to-a-function-in-python">this SO post</a> I now know how to pass a dictionary as kwargs to a function (and save some space if I repeatedly call a function).</p> <p>I was wondering whether it is still possible in ...
<python>
2023-05-27 06:56:44
1
3,013
Cribber
76,345,404
4,869,293
How to define Django model datefield
<p>I am new in python django, i am creating app model and wants to define a field(date of birth) to input date from user form but unable to understand how to define date field in model so that i can capture the date(date of birth) using form.</p> <p>Here is model</p> <pre><code> # Create your models here. class funder...
<python><django><django-models>
2023-05-27 05:09:26
2
465
Rahul Saxena
76,345,366
2,437,656
How can I extend every unique key constraint of all models with a common key across using Flask-SQLAlchemy and Flask-Migrate in Python?
<p>Want to extend every unique key constraint of all models with a common key across. Have tried multiple things but doesn't seem to working when I do</p> <pre><code>flask db init; flask db migrate -m &quot;init&quot;; flask db upgrade; </code></pre> <p>But it works and adds</p> <p><code>&quot;users_email_organization_...
<python><flask><flask-sqlalchemy><alembic><flask-migrate>
2023-05-27 04:55:36
1
306
Aakash Aggarwal
76,345,344
219,153
How to set channel value with PyDMXControl?
<p>I have a DMX512 decoder with LEDs at address 1. It is connected to the PC running Ubuntu 22.04.2 via USB/RS485 dongle using FT232R chip. It works fine with QLC+ app. I would like to control it from a Python script. I'm using PyDMXControl module and this script:</p> <pre><code>from PyDMXControl.controllers import Ope...
<python><dmx512>
2023-05-27 04:43:15
1
8,585
Paul Jurczak
76,345,286
743,531
Unable to resolve '_WorkbookChild" has no attribute "max_row" [attr-defined]' warning with openpyxl
<p>With the python file below I am unable to resolve mypy errors.</p> <pre><code>import openpyxl inputWorkbook = openpyxl.load_workbook(&quot;input.xlsx&quot;) activeSheet = inputWorkbook.active if activeSheet: print(activeSheet.max_row) </code></pre> <p>I keep getting this error <code>test.py:6: error: &quot;_Wor...
<python><python-3.x><openpyxl><mypy>
2023-05-27 04:13:24
2
301
jprince14
76,345,255
4,825,796
TensorFlowJS Mask RCNN - ERROR provided in model.execute(dict) must be int32, but was float32
<p>I have trained a object detection model using transferred learning from <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nofollow noreferrer">Mask R-CNN Inception ResNet V2 1024x1024</a> and after converting the model to js I get the error: <strong>...
<python><angular><typescript><tensorflow><tensorflow.js>
2023-05-27 03:58:09
0
1,762
Hozeis
76,345,189
5,212,614
How to get the bedroom square footage and prices from Zillow?
<p>I asked this question below to ChatGPT today</p> <blockquote> <p>User python mozlla headers scrape bedrooms square footage and price from zillow</p> </blockquote> <p>I got this.</p> <pre><code>import requests from bs4 import BeautifulSoup # Set the URL of the Zillow page you want to scrape url = &quot;https://www.z...
<python><python-3.x><web-scraping><beautifulsoup><mozilla>
2023-05-27 03:15:08
2
20,492
ASH
76,344,950
1,942,868
Stop automatic encoding by FileField
<p>I am using the <code>FileField</code> of django model.</p> <pre><code>class Drawing(models.Model): drawing = models.FileField(upload_to='uploads/') </code></pre> <p>For example I try uploading 2byte charactor filename such as <code>木.pdf</code>,</p> <p>then filename is encoded into , <code>%E6%9C%A8_sBMogAs.pdf<...
<python><django><django-rest-framework>
2023-05-27 01:00:31
0
12,599
whitebear
76,344,687
3,096,622
Pytest: ModuleNotFoundError. Problem with my import statements
<p>Initial development of my project had everything in the same directory and all of my Pytest tests worked fine. I changed directory structure for packaging and moved code into <code>src/project_name</code> directory, and all test files into <code>test/</code>. Now Pytest throws a ModuleNotFoundError. I am running ...
<python><import><pytest>
2023-05-26 23:23:43
1
603
JayCo741
76,344,360
12,904,608
Is this a fits header problem or something to do with astropy?
<p>I tried a simple example in astropy, like the one bellow:</p> <pre><code>from astropy import wcs from astropy.io import fits # Load the FITS hdulist using astropy.io.fits hdulist = fits.open('abell.fits') # Parse the WCS keywords in the primary HDU w = wcs.WCS(hdulist[0].header) # Print out the &quot;name&quot; o...
<python><astropy><fits>
2023-05-26 21:50:34
0
317
Adrian
76,344,334
11,001,493
os.makedirs is creating a new folder with file name
<p>I'm trying to copy all folders and files from one path to another if a file doesn't contain a substring called &quot;obsolete&quot;. Here is my code:</p> <pre><code>import os import shutil rootdir = &quot;C:/Old&quot; new_rootdir = &quot;C:/New/&quot; for root, dirs, files in os.walk(rootdir): for filenam...
<python><operating-system><shutil>
2023-05-26 21:44:08
1
702
user026
76,344,312
1,997,735
pyinstaller doesn't like sounddevice
<p>Our Python 3.7 project is using sounddevice and it runs just fine, but we recently updated pyinstaller to 5.10.1 and the new version of pyinstaller doesn't like sounddevice.</p> <p>BTW, updating pyinstaller to 5.11.0 doesn't help.</p> <p>What do we need to do, to create an installable Python EXE that uses sounddevic...
<python><pyinstaller><python-sounddevice>
2023-05-26 21:38:50
1
3,473
Betty Crokker
76,344,269
3,330,347
Call value from PyQt5 UI interface and carry out operation in another py file
<p>I am new to Python and still learning.</p> <p>I have a py file that I generated ftom Qt designer (ForEmail.py):</p> <pre><code>from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QSize, QTimer class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(&quot;Mai...
<python><pyqt5>
2023-05-26 21:27:22
0
405
Joe
76,344,214
5,252,492
numpy: Faster np.dot/ multiply(element-wise multiplication) when one array is the same
<p>I have to do dot product multiplications between two 1D arrays and then take the sum of the list as:</p> <pre><code>import numpy as np import numba import time import random a = np.array([1, 2, 3, 4, 5, 6],dtype=int8) # Same first array b = [np.array([random.randint(0,100) for y in range(6)],dtype=float) for x in ...
<python><numpy>
2023-05-26 21:14:46
1
6,145
azazelspeaks