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,131,257
12,703,411
How to add file extension to tkinter textbox?
<p>I'm working on a project where I'm building my own Python IDe. At the moment, I have added a textbox where I can write or edit my script file. In the attached image below, due to the invalidity of a file extension, you can see that the text is plain and uninterpreted. Hence, I would like to know if it would possible...
<python><user-interface><tkinter><textbox><ide>
2023-04-28 15:49:19
2
345
Aatif Shaikh
76,131,147
8,420,175
Rar File issue with Extract
<p>raise RarCannotExec(&quot;Cannot find working tool&quot;)</p> <pre><code>import rarfile rarpath = '/home/server/test_rar/ABC.rar' def unrar(file): rf=rarfile.RarFile(file) rf.extractall() unrar(rarpath) </code></pre>
<python><python-3.6><rar>
2023-04-28 15:36:11
1
782
Harshit Trivedi
76,130,968
12,466,687
How to arrange categories on y axis based on values in descending order on x axis in Python plotly express?
<p>I am trying to <strong>arrange categories in descending order</strong> on <code>y axis</code> based on <code>Max</code> values from <code>x axis</code> in <code>plotly express</code> <strong>scatter</strong> plot and unable to do it.</p> <p>Data:</p> <pre><code>import pandas as pd import plotly.express as px df = p...
<python><plotly>
2023-04-28 15:17:07
1
2,357
ViSa
76,130,914
7,984,318
Flask wtforms validators=[validators.DataRequired()] allows empty string and skip
<p>I'm using Flask wtforms to build a note submit function, as long as there is empty string, thre validation will fail. How can I allow empty string to be inputted ,and if it is empty string just skip ,don't save it as a note ?</p> <p>code:</p> <pre><code>class VendorForm(FlaskForm): notes = fields.TextAreaField(&...
<python><flask><flask-wtforms><wtforms>
2023-04-28 15:10:16
1
4,094
William
76,130,808
4,397,312
How recursion calls are working in the call stacks
<p>Here is a code that works for generating all the well-form parenthesis combinations by getting an integer as the number of open/close parentheses using recursive calls.</p> <pre><code>class Solution: def generateParenthesis(self, n: int): res = [] def backtrack(open_count, close_count, c...
<python>
2023-04-28 14:56:14
0
717
Milad Sikaroudi
76,130,751
20,220,485
How do you create a list object from a dataframe based on a column value?
<p>For the following <code>df</code>, how could you create the desired output below? I'm specifically after a list of lists of tuples.</p> <pre><code>import pandas as pd df = pd.DataFrame({'x':['ab_c_1.0.0','ab_c_1.0.1','ab_c_1.0.2','ab_c_1.1.0','ab_c_1.1.1','ab_c_1.2.0','ab_c_1.3.0','ab_c_1.3.1'], '...
<python><pandas><dataframe>
2023-04-28 14:46:24
3
344
doine
76,130,589
802,678
What is the function of the `text_target` parameter in Huggingface's `AutoTokenizer`?
<p>I'm following the guide here: <a href="https://huggingface.co/docs/transformers/v4.28.1/tasks/summarization" rel="nofollow noreferrer">https://huggingface.co/docs/transformers/v4.28.1/tasks/summarization</a> There is one line in the guide like this:</p> <pre><code>labels = tokenizer(text_target=examples[&quot;summar...
<python><huggingface-transformers><huggingface>
2023-04-28 14:27:23
2
582
Betty
76,130,580
90,580
How can I filter out the internal Dynaconf settings?
<pre><code>from .config import settings for k,v in settings.items(): print(k,v) </code></pre> <p>this prints things like <code>RENAMED_VARS</code>, <code>SETTINGS_MODULE</code>, <code>PROJECT_ROOT</code>, <code>*_FOR_DYNACONF</code> in addition to the configuration parameter that I explicitly setup in my <code>settin...
<python><configuration>
2023-04-28 14:26:21
2
25,455
RubenLaguna
76,130,482
11,160,421
How to add a new column with key information in that column from dictionary of different length array without loosing any value in pandas in python
<p>Input</p> <pre><code>dict_table = {'Table1': [1, 2,], 'Table2': [3, 4, 5], 'Table3': [6, 7, 8, 9, 10, 11]} </code></pre> <p>Result</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Table_name</th> <th>Table_value</th> <th>New_Column</th> </tr> </thead> <tbody> <tr> <td>Table1</td> <td>1</t...
<python><pandas><dataframe><list><numpy>
2023-04-28 14:14:46
1
316
AXz
76,130,370
2,808,520
Why is python slower inside a docker container?
<p>The following small code snippet times how long adding a bunch of numbers takes.</p> <pre><code>import gc from time import process_time_ns gc.disable() # disable garbage collection for func in [ process_time_ns, ]: pre = func() s = 0 for a in range(100000): for b in range(100): ...
<python><docker>
2023-04-28 14:02:15
1
1,058
GitProphet
76,130,356
14,649,310
Which HTTP method to use when no data is transfered, just to execute code in an endpoint?
<p>I build an Flask API endpoint which when called will execute an action to process some data (the data are not send but come from the database). The result of the method(action) called is to update some fields in some database objects based on calculations performed on the objects themselves.</p> <p>Initially from w...
<python><flask><httprequest><openapi>
2023-04-28 14:01:09
4
4,999
KZiovas
76,130,275
12,870,628
How to increment a whole column's values by x amount in SQLAlchemy?
<p>I am looking to increase an entire column's values by a certain variable amount, and initially I used sqlite3, but in order to optimise my script I had to switch to SQLAlchemy, but I am unable to find similar utilities in SQLAlchemy. For example, for sqlite3 I did this:</p> <pre><code>amt = 3 #for example with sqli...
<python><sqlalchemy><sqlite3-python>
2023-04-28 13:52:43
1
495
Justin Chee
76,130,267
1,216,183
csv.writer can't handle QUOTE_NONE and empty escapechar since python 3.11
<p>Since Python 3.11, the <code>CsvWriter</code> with <code>quoting=csv.QUOTE_NONE</code> raises an error when trying to generate data containing <code>quotechar</code> (<code>&quot;</code>). It asks for an <code>escapechar</code> to be defined.</p> <p>The CSV I need to generate does not require quotes around the field...
<python><python-3.11>
2023-04-28 13:51:18
1
2,213
fabien-michel
76,130,226
8,048,800
Pandas simple way to split column header names on separator
<p>I need to rename columns name in pandas but need the string after pipe symbol <code>@</code>.</p> <p>Example : <code>Col1 @ my data1</code> to <code>my data1</code></p> <p>I am reading a csv and trying the be</p> <pre><code>df= pandas.read_csv('path'); df.rename(columns=lambda col: col.replace(col, '^[^@\r\n]+@\s*\K...
<python><pandas>
2023-04-28 13:46:30
3
387
Dot Net Dev 19
76,130,222
299,754
Exception in logging module itself is not sent to sentry
<p>Django app on python 2 (yeah I know). The sentry integration is working well otherwise, but looks like it doesn't record crashes in logging itself, for instance when passing insufficient arguments to logger.info().</p> <p>In this case the incriminating line was something like:</p> <pre><code>logger.info('some info a...
<python><django><logging><sentry>
2023-04-28 13:46:23
1
6,928
Jules OllΓ©on
76,130,069
8,512,262
How can I check for user activity/idle from a Windows service written in Python?
<p>I've written a Windows service in Python that needs to be able to detect user activity. Under normal circumstances I would call the Windows <code>GetLastInputInfo</code> method, but that method doesn't work when called by a service. Here's the relevant info from the documentation for this method:</p> <blockquote> <p...
<python><windows><service><user-input><user-inactivity>
2023-04-28 13:27:25
1
7,190
JRiggles
76,130,037
3,668,129
SSLError ( certificate verify failed)
<p>I'm trying to run simple gradio app with https:</p> <pre><code>import gradio as gr if __name__ == &quot;__main__&quot;: with gr.Blocks(theme=gr.themes.Glass()) as demo: testLabel = gr.Label(label=&quot;Just for test&quot;) demo.queue().launch(share=False, debug=False, ...
<python><gradio>
2023-04-28 13:22:18
1
4,880
user3668129
76,129,604
21,420,742
How to merge two datasets of different shapes with different column names in python
<p>I have a 2 datasets with two different shapes and column names and I need to merge them to fill the blanks in for all the NaNs. When I try and doesn't work and I am left with NaNs still.</p> <p>Here is a sample:</p> <p>DF1:</p> <pre><code> ID Mgr_name Reports EmpType mgr_pos_num 101 NaN 3 ...
<python><python-3.x><pandas><dataframe><merge>
2023-04-28 12:30:05
1
473
Coding_Nubie
76,129,550
11,065,874
How to make case insensitive choices using Python's enum and FastAPI?
<p>I have this application:</p> <pre class="lang-py prettyprint-override"><code>import enum from typing import Annotated, Literal import uvicorn from fastapi import FastAPI, Query, Depends from pydantic import BaseModel app = FastAPI() class MyEnum(enum.Enum): ab = &quot;ab&quot; cd = &quot;cd&quot; class...
<python><enums><fastapi><pydantic>
2023-04-28 12:24:37
4
2,555
Amin Ba
76,129,412
7,936,386
execute external sql script from lambda function using Python
<p>I'm trying to execute some external SQL scripts which are containing some CREATE TABLES syntaxes while the other ones are some pre-defined PL/pgSQL functions. I'm using the Python 3.10 and the aws-psycopg2 library to create a Lambda function in AWS which will connect to a PostgreSQL AWS database and run these script...
<python><amazon-web-services><aws-lambda><psycopg2>
2023-04-28 12:06:06
1
619
Andrei NiΘ›Δƒ
76,129,182
7,559,896
How can I force CMake to use Python executables and libs from a given folder?
<p>I have both Python 3.6 in &quot;C:\PYTHON_VERSIONS\STANDARD_3.6.8&quot; and 3.8 in &quot;C:\Python\3.8&quot; in my system. I want to compile pybind11 using 3.6 but CMake takes lib directories from 3.6 and the executable from 3.8! a very bad mix indeed.</p> <p>Here is output of CMake:</p> <pre><code>-- Found PythonIn...
<python><cmake><pybind11>
2023-04-28 11:35:20
1
933
DEKKER
76,129,150
11,065,874
fastapi bug with annotated default value
<p>I have this small FastAPI (fastapi==0.95.0 and uvicorn==0.20.0 in my requirements.txt) application that works as expected.</p> <pre><code>from typing import Annotated import uvicorn from fastapi import FastAPI, Depends, Query from pydantic import BaseModel app = FastAPI() class TestInput(BaseModel): q: Annot...
<python><fastapi><python-typing><pydantic>
2023-04-28 11:31:47
1
2,555
Amin Ba
76,129,121
494,739
How should we do order_by in Django ORM for self-referred sub objects?
<p>Have an issue with a somewhat problematic ordering/sorting in Django ORM. What I have is a Venue with a FK to <code>self</code>, thus the potential for sub-venues:</p> <pre class="lang-py prettyprint-override"><code># models.py class Venue(models.Model): parent = models.ForeignKey( to=&quot;self&quot;, r...
<python><django><django-models><django-rest-framework><django-orm>
2023-04-28 11:29:16
3
772
kunambi
76,129,060
13,219,123
Define pyspark table with column type as timestamp
<p>I need to create a PySpark dataframe for some unit testing. One of the columns in the dataframe needs to be of the type <code>TimestampType</code>. I have the following code to define the dataframe:</p> <pre><code>spark = (SparkSession .builder .master(&quot;local[*]&quot;) .appNa...
<python><pyspark>
2023-04-28 11:19:10
1
353
andKaae
76,129,049
8,510,149
Rank and exclude null values in Pyspark
<p>Using Pyspark and the ntile function, I'm look for a way to deal with null values when I rank. The code below will rank the null values as well, as 1. I dont want that, I would like them to have rank null. And ranking only to be done on non-null values.</p> <p>I can filter out null-values before the ranking, but the...
<python><pyspark>
2023-04-28 11:17:40
1
1,255
Henri
76,128,989
9,974,205
Problem looping the crossing of parents of a genetic algorithm in python
<p>I have the following function in python used to generate the children of a genetic algorithm</p> <pre><code>def cruce(padres): mitadHerencia = len(padres[0])//2 hijo1 = np.concatenate((padres[0][:mitadHerencia], padres[1][mitadHerencia:])) hijo2 = np.concatenate((padres[1][:mitadHerencia], padres[0][mit...
<python><function><loops><genetic-algorithm>
2023-04-28 11:11:04
1
503
slow_learner
76,128,932
2,749,397
meaning of "add mappable to an Axes"
<p>Recently I ran an old code and Matplotlib told me</p> <blockquote> <pre><code>MatplotlibDeprecationWarning: Unable to determine Axes to steal space for Colorbar. Using gca(), but will raise in the future. Either provide the *cax* argument to use as the Axes for the Colorbar, provide the *ax* argument to steal space ...
<python><matplotlib>
2023-04-28 11:04:03
1
25,436
gboffi
76,128,917
617,648
How can I modify this closed-connection regex to cover multi-line invalid user entries
<p>I need a regex string to give to denyhosts config for filtering invalid ssh login attempts to my remote server.</p> <p>Here is the regex that I am using currently:</p> <pre><code>USERDEF_FAILED_ENTRY_REGEX=.*sshd.* Connection closed by .* (?P&lt;host&gt;\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) port \d{1,5} \[preauth\] </...
<python><regex><ssh>
2023-04-28 11:01:34
2
1,752
obayhan
76,128,890
235,671
Assign a default callable value for a callable protocol
<p>I have the following callable <code>Protocol</code>:</p> <pre class="lang-py prettyprint-override"><code>class OnStarted(Protocol): def __call__(self, kwargs: Dict[str, Any]) -&gt; Optional[Dict[str, Any]]: ... </code></pre> <p>that I want to assign a default function, which I did like this:</p> <pre class="lang...
<python><mypy><python-typing>
2023-04-28 10:59:02
2
19,283
t3chb0t
76,128,753
4,045,275
Can ecdfplot show the concentration of a variable? E.g. the top 10 items account for 20% of the total, etc
<h1>The issue</h1> <p>I want to create a plot to show the concentration by a certain variable. Let's say I have a 1-dimensional array of prices.</p> <ul> <li><strong>I want a plot that shows me that the first 10 most expensive items account for 10% of the total price, the first 100 most expensive items for 40% of the t...
<python><matplotlib><seaborn><ecdf>
2023-04-28 10:38:29
1
9,100
Pythonista anonymous
76,128,714
9,626,922
Jupyter notebook kernel dies when running gym env.render()
<p>EDIT: When i remove <code>render_mode=&quot;rgb_array&quot;</code> it works fine. But this obviously is not a real solution.</p> <p>I am trying to run a render of a game in Jupyter notebook but each time i run it i get a pop up saying <code>Python 3.7 crashed</code> and the kernel has died.</p> <pre><code>%matplotli...
<python><machine-learning><jupyter-notebook><openai-gym>
2023-04-28 10:33:39
1
617
Jm3s
76,128,690
3,815,773
How do I know which "File Descriptor" stands for a TCP connection in Python?
<p>In Linux the <code>lsof</code> command is very helpful for listing open files, giving e.g. this output:</p> <pre><code>~$ sudo lsof -a -i -u root -c python ======= COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME python3 1504835 root 19u IPv4 57127166 0t0 TCP urkam.fritz.box:http-&gt;GMC-500-ol...
<python><tcp><file-descriptor><handle>
2023-04-28 10:30:09
0
505
ullix
76,128,663
11,466,416
Hugging Face load model --> RuntimeError: Cuda out of memory
<p>I found several threads that dealt with the same error message, but my case seems to be different. In the other threads I encountered, there was actually not enough memory to allocate. I want to load a pre-trained transformer onto a GPU, but even trying to load the model results into the following error message:</p>...
<python><huggingface-transformers>
2023-04-28 10:25:19
2
456
Blindschleiche
76,128,609
14,368,631
Create an event system using decorators that work for global functions and class functions
<p>So I have this following code:</p> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict _event_handlers = defaultdict(set) def add_event_handler(event_name=&quot;&quot;): def wrapper(func): _event_handlers[event_name if event_name else func.__name__].add(func) re...
<python><events><decorator>
2023-04-28 10:19:19
0
328
Aspect11
76,128,593
8,818,287
Deploy a general tree model in flask
<h2>Background</h2> <p>I have a class that holds a general tree data structure (called <strong>Factory</strong> class). This general tree is composed of nodes (called <strong>Item</strong> class) that can have multiple parents nodes and multiple child nodes. Also, parents and children can be shared. For those familiar ...
<python><flask><serialization><deployment>
2023-04-28 10:17:12
0
789
asa
76,128,437
15,358,800
Add percentage of repitative strings in bar graph using Pandas
<p>Let's say I've df like this</p> <p><strong>Reproducable:</strong></p> <pre><code>import pandas as pd import io TESTDATA=&quot;&quot;&quot;All_services All_services Rehosting applications to AWS Replacing flexible functionalities Unaltered replatforming of underlying code structure, functionalities, features Rebu...
<python><pandas><graph>
2023-04-28 10:02:35
1
4,891
Bhargav
76,128,423
5,881,882
Librosa specshow, what data processing is done under the hood compared to plt.imshow
<p>I am trying to understand, why a plot produced by <code>plt.imshow()</code> is way less detailed and more blurry, than a plot produced by <code>librosa.display.specshow</code>.</p> <p>As the plots, or better to say, the data behind the plots is my basis of further analysis, I would like to go for as much detail as p...
<python><pytorch><librosa><torchvision>
2023-04-28 10:00:40
1
388
Alex
76,128,396
13,391,350
Re-arranging pivot column and value using Pandas
<p>I would like to rearrange the pivot table in the way that base on this input data, the revenue_month will be treated as a column, keeping all other indexes, whereas the columns:revenue__net_eur and accrual__net_eur will be the values.</p> <pre><code>data = { 'cust_id': [1, 1, 1, 1], 'cust_name': ['Company A'...
<python><pandas>
2023-04-28 09:56:23
1
747
Luc
76,128,230
5,308,802
Django ORM: move filter after annotate subquery
<p>This Django ORM statement:</p> <pre class="lang-py prettyprint-override"><code>Model.objects.all() \ .annotate( ord=Window( expression=RowNumber(), partition_by=F('related_id'), order_by=[F(&quot;date_created&quot;).desc()] ) ) \ .filter(ord=1) \ .f...
<python><django><postgresql><orm>
2023-04-28 09:38:48
2
1,228
AivanF.
76,128,144
8,547,163
Issue with pipenev and pip after installation of the package : pkg_resources.DistributionNotFound
<p>I'm trying to install a package via <code>pip</code> and in an virtual environment using</p> <pre><code>python3 -m venv env source env/bin/activate </code></pre> <p>then I install the package via pip</p> <pre><code>pip install &lt;package name&gt; </code></pre> <p>I get no error while installing it, but when I try t...
<python><pip><python-venv>
2023-04-28 09:26:55
0
559
newstudent
76,127,887
11,024,270
How to average spatial points data over spatial grid boxes in Python
<p>I have a set of data points that have coordinates and one value associated with them. I would like to be able to place the data points into grid boxes and average all the points that fall into each grid box.</p> <p>Here is the code I managed to create that makes what I want. I wonder if there is a more elegant and m...
<python><arrays><numpy>
2023-04-28 08:54:58
1
432
TVG
76,127,761
10,981,411
how do I make my horizontal scroll bar to work in my codes that uses tkinter library
<p>below are my codes</p> <p>when you click the run script button it populates the frame with df of random numbers I can scroll down but not across. Any reason why? Can someone fix the code please? I dont want to change the position of the treeframe as I have other button and labels on the left what I have removed from...
<python><tkinter>
2023-04-28 08:38:42
0
495
TRex
76,127,738
1,920,368
regex lookbehind if matches exclude entire lane
<p>I am trying to match single character <code>]</code> only if <code>[!</code> is not ahead.</p> <h5>Regex:</h5> <pre><code>(?!(?:\[\!.*))\] </code></pre> <h5>Expected Result:</h5> <pre><code>_dynamic_text_[!_dynamic_text_]_dynamic_text_ _dynamic_text__dynamic_text_]_dynamic_text_ ↑ </code...
<python><regex><negative-lookbehind>
2023-04-28 08:35:39
1
4,570
Micah
76,127,700
13,393,940
Docker container keeps running after system was pruned
<p>Yesterday I discovered that a container was still running on my machine (macOS Monterey). I searched StackOverflow for answers to my issue but anything I tried didn't work.</p> <p>I did a <code>docker ps</code> and then a <code>docker stop &lt;container-ID&gt;</code> but the web app was still running in port <code>0...
<python><docker><plotly-dash><gunicorn>
2023-04-28 08:29:29
1
873
cconsta1
76,127,674
6,632,138
Wrapper around instance methods with default return value
<p>I have a dozen of (instance) methods that should evaluate only if a condition is satisfied, otherwise return default value which is different for each method:</p> <pre><code>def fun(self, *args, **kwargs): if not self.init(): return ... # &lt;- default value, different for each method # method logic ...
<python><decorator><return-value><wrapper><default>
2023-04-28 08:26:45
1
577
Marko Gulin
76,127,624
1,159,488
How to optimize the sorting of a big table with Python
<p>I have a table A with all values hidden.<br /> The goal is to find a trick to sort these values with the help of two functions :</p> <ol> <li>compare (x, y) checks in the table A whether x value &lt; y value or not</li> <li>If not : sort(x, y) sorts x compared to y with : <code>A[x], A[y] = A[y], A[x]</code></li> </...
<python><algorithm><loops><sorting>
2023-04-28 08:21:40
4
629
Julien
76,127,418
4,568,775
Data types when reading mysql with python library MySqldb
<p>I wish to extract data from a mysql table, and write it verbatim to a text file. The most simplified form of my code is below, of course it must be much refined later (both the SELECT statement and further conditions in the python code); but I already run into trouble here.</p> <pre><code>#!/usr/bin/python import My...
<python><mysql>
2023-04-28 07:56:17
0
305
Karel Adams
76,127,340
20,263,044
Annotate closest OSM vertex
<p>I'm trying to get the closest OSM vertex for each row of MyModel</p> <pre class="lang-py prettyprint-override"><code>class MyModel(models.Model): location = GeometryField() </code></pre> <p>I currently use RawSQL for this</p> <pre class="lang-py prettyprint-override"><code>def annotate_closest_vertex(queryset): ...
<python><django><django-orm>
2023-04-28 07:48:20
1
1,360
Alombaros
76,127,328
509,263
How to return DML statements results from Bigquery with python (Update, Delete)?
<p>I'm running DML commands with Python3 and bigquery (using google-cloud-bigquery package). Compared to results provided by running the command in the console, I can't get it with Python.</p> <p>Running the normal:</p> <pre class="lang-py prettyprint-override"><code>client = bigquery.Client() result = client.query(......
<python><google-bigquery>
2023-04-28 07:46:37
1
8,884
Alexandru R
76,127,269
2,583,670
extract and count lists from text file in python
<p>I have a large text file that includes so many lists. Each list includes random numbers as follows. Test file:</p> <pre><code>[-1460,-1460,-1460,-1460,-1460,0,-1460,0,-1460,-1460,-1460,45,-1460,-1460,-1460,-1460,-1460,-1460] [250,-1250,36,-1250,-1250,33,-1250,-1250,-1250,-1250,-1250,-1250,-1250,-490,-1243,-1250,-125...
<python><list><file><text>
2023-04-28 07:39:16
2
711
Mohsen Ali
76,127,268
19,694,624
pybit.exceptions.FailedRequestError: Http status code is not 200. (ErrCode: 404) (ErrTime: 07:32:08)
<p>I have an issue with Python's Pybit module. I'm trying to get my wallet balance but I get the following error:</p> <pre><code>pybit.exceptions.FailedRequestError: Http status code is not 200. (ErrCode: 404) (ErrTime: 07:32:08) </code></pre> <p>My code:</p> <pre><code>from pybit.unified_trading import HTTP # API cre...
<python><bybit><python-bybit><pybit>
2023-04-28 07:39:06
1
303
syrok
76,127,178
7,972,989
Pandas rank function with custom method OR limit number of decimals in mean calcultation
<p>EDIT : my question is not well asked nor enough detailed. I am redoing it better, please let me time to do it</p> <p>EDIT 2 : My question was not clear enough nor adapted to my problem, I solved my problem in a different way. I cannot delete the question, but please don't bother answering, I messed up the question.<...
<python><pandas><numpy>
2023-04-28 07:26:11
2
2,505
gdevaux
76,127,156
10,232,932
Visual Studio Code: OSError: Proxy URL had no scheme, should start with http:// or https://
<p>I am running the Visual Studio Code behind a Company proxy on windows with Python 3.9.0. And when I try to use the command:</p> <pre><code>pip install pandas </code></pre> <p>in the terminal, it leads to the following error (note that it could be every other pip install package):</p> <blockquote> <p>ERROR: Could not...
<python><visual-studio-code><proxy>
2023-04-28 07:22:33
1
6,338
PV8
76,126,892
14,808,001
Python 'cannot open shared object file: No such file or directory' on Raspbian
<p>I am trying to install <a href="https://pypi.org/project/pvrecorder/" rel="nofollow noreferrer">pvrecorder</a> on a Virtual Machine with Raspbian installed. I got some Python script that records the user's microphone, until <code>KeyboardInterrupt</code> is triggered (user presses <code>Ctrl</code> + <code>C</code>)...
<python><linux><debian><raspbian>
2023-04-28 06:41:46
1
1,283
Mario MateaΘ™
76,126,859
7,985,055
how to find id or name using selenium in a div container
<p>I am trying to automate the login to the website, however, I can't for the life of me figure out how to find the elements of the login page. (<a href="https://data-exchange.amadeus.com/sfiler/Login.action" rel="nofollow noreferrer">https://data-exchange.amadeus.com/sfiler/Login.action</a>)</p> <pre><code> &lt;form m...
<python><selenium-webdriver><web-scraping><selenium-chromedriver>
2023-04-28 06:37:02
2
525
Mr. E
76,126,422
6,455,731
Pass final positional argument in a curried function to the last parameter available
<p>Given a simple curried function</p> <pre><code>import toolz @toolz.curry def mklist(x, y, z): return [x, y, z] </code></pre> <p>obviously calling <code>mklist(x=1, y=2)(z=3)</code> works.</p> <p>What I would like to be able to do is to call the function like so: <code>mklist(x=1, y=2)(3)</code>, where z gets bo...
<python><functional-programming><currying>
2023-04-28 05:13:26
0
964
lupl
76,126,374
5,942,100
Tricky calculation transformation based on a row sum using Pandas
<p>I would like to round values in specific columns according to these rules:</p> <pre><code>if = or &gt; 0.6 round to nearest even number if &lt; 0.6 round to 0 if and only if the sum of the values does not exceed its total by row rounded to the nearest number. If the total is exceeded, subtract or add this delta to...
<python><pandas><numpy>
2023-04-28 04:58:40
1
4,428
Lynn
76,126,350
1,497,720
ValueError: If using all scalar values, you must pass an index with Transformer
<p>For code below</p> <pre><code>from sklearn.preprocessing import FunctionTransformer from functools import partial from types import FunctionType from statistics import mean import pandas as pd X_train = pd.DataFrame(columns=['domain']) # Add rows to the dataframe X_train.loc[36] = ['e1548bfed8d05713acacc4d33393b2...
<python><python-3.x><scikit-learn>
2023-04-28 04:51:09
0
18,765
william007
76,126,264
20,122,390
How can I filter by dates in a Firestore Realtime Database with pyhon?
<p>I have a firestore realtime database with the following structure:</p> <p><a href="https://i.sstatic.net/jKBR9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jKBR9.png" alt="enter image description here" /></a></p> <p>And I need to be able to apply a filter for the dates. The idea is that the user en...
<python><database><firebase><firebase-realtime-database><nosql>
2023-04-28 04:28:08
0
988
Diego L
76,126,095
1,355,120
Should all python dict types be type hinted to dict?
<p>Excuse my noob question as I haven't done too much python coding so am not as familiar with &quot;pythonic&quot; ways and untyped languages.</p> <p>In Python I see the <code>Dataframe.to_dict()</code> method has several ways it can return the dict. For example, <code>Dataframe.to_dict(&quot;records&quot;)</code> bas...
<python><pandas><type-hinting>
2023-04-28 03:34:09
1
3,389
Kevin
76,125,938
14,735,451
Is there a way to merge multiple json files without opening them?
<p>I have a large number of big <code>json</code> files and I cannot open all of them at the same time. I'm trying to merge them into one <code>json</code> file, but all the solutions I find on SO (e.g., <a href="https://stackoverflow.com/questions/57422734/how-to-merge-multiple-json-files-into-one-file-in-python">this...
<python><json><merge>
2023-04-28 02:49:37
0
2,641
Penguin
76,125,906
9,334,609
WARNING: autodoc: failed to import module when trying to generate python documentation with sphinx
<p>I have reviewed the sphinx documentation to generate the python documentation. When I generate the documentation in html format using the .rst files that do not reference any python source code, the documentation is generated correctly.</p> <p>In my configuration I work with the following files: conf.py, index.rst, ...
<python><python-3.x><python-sphinx><autodoc>
2023-04-28 02:40:38
0
461
Ramiro
76,125,807
5,942,100
Tricky organizing transformation that places values with their categories using Pandas
<p>I have a df where I would like to create a transformation that places values with their categories using Pandas.</p> <p><strong>Data</strong></p> <pre><code>year quarter Location Low_ stat_AA Low_range_AA Low_ stat_BB Low_range_BB Med_stat_AA Med_range_AA Med_stat_BB Med_range_BB Up_stat_AA Up_range_AA Upp_...
<python><pandas><numpy>
2023-04-28 02:11:06
3
4,428
Lynn
76,125,779
1,807,003
How can I install TLS/SSL for python to install Python 3.11 and pip on a raspberry pi?
<p>I've been fighting this for three days now, and I have no idea what I'm doing wrong. I've got a headless raspberry pi 4 and I understand there is no apt package available for python on the raspberry pi, so I need to compile it from source. I've tried following the instructions from three different places that all bo...
<python><ssl><pip>
2023-04-28 02:03:45
0
948
nickvans
76,125,772
6,676,101
In python, how do you get the escape sequence for any Unicode character?
<p>In python, what is the escape sequence for the left-double quote Unicode character <code>β€œ</code> (U+201C)?</p> <pre class="lang-python prettyprint-override"><code>left_double_quote = &quot;β€œ&quot; print(ord(left_double_quote)) # prints `8220` </code></pre> <p>Note that <code>201C</code> is hexadecimal notation for...
<python><string><unicode><unicode-string><unicode-escapes>
2023-04-28 02:01:25
1
4,700
Toothpick Anemone
76,125,653
14,908,558
A numpy function that lists all the possible "coordinates" in a nd-array
<p><strong>Is there a <code>numpy</code> function that lists all the possible &quot;coordinates&quot; in a <code>numpy.ndarray</code>?</strong></p> <p>It would do exactly what this function <code>all_possible_coordinates</code> does:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def all_possib...
<python><numpy>
2023-04-28 01:21:56
1
328
edmz
76,125,648
11,922,765
Pandas convert mutil-row-column dataframe to single-row multi-column dataframe
<p>My dataframe is given below:</p> <p>code:</p> <pre><code>df = Car measurements Before After amb_temp 30.268212 26.627491 engine_temp 41.812730 39.254255 engine_eff 15.963645 16.607557 avg_mile 0.700160 0...
<python><pandas><dataframe><pivot>
2023-04-28 01:19:26
1
4,702
Mainland
76,125,532
3,257,464
Python writes extra blank line to the file
<p>The following code adds an extra blank line (&quot;\r&quot;) to every write, whereas it is supposed to just write one (&quot;\r\n&quot;) at the end of every write. I have no idea why.</p> <pre><code>import os with open(&quot;output&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f: for i in range(10): ...
<python><windows><blank-line>
2023-04-28 00:47:29
2
598
Diamond
76,125,434
12,060,361
git tag 'malformed object name' β€” Github Action/Workflow Subprocess Error
<p>I have a Python script that utilizes Subprocess to execute a git command:</p> <pre class="lang-py prettyprint-override"><code>import subprocess fetch_cmd = ['git', 'fetch', '--tags'] //fetch tags subprocess.run(fetch_cmd, capture_output=True, text=True) test_tag = ['git', 'tag', '--points-at', 'origin/test~1'] ...
<python><git><github><subprocess><github-actions>
2023-04-28 00:14:27
1
1,105
mmarion
76,125,337
14,348,996
Is there a python equivalent to R's `with`?
<p>In R, the <code>with</code> function constructs an environment from some data - this allows you to refer to items in your data as if they are variables, so this:</p> <pre><code>with(list(&quot;a&quot; = 12, &quot;b&quot; = 13), { print(a) print(b) }) </code></pre> <p>prints this:</p> <pre><code>[1] 12 [1] 13 </c...
<python><r><scope>
2023-04-27 23:42:50
1
1,236
henryn
76,125,285
4,894,543
Recursion error while simplifying nested json to flat in python
<p>I am trying flatten the json object so that I can create plain csv file out of it. But it is throwing</p> <pre><code>RecursionError: maximum recursion depth exceeded while calling a Python object </code></pre> <p>Code which I have written in python, calling simplify_multy_nested_json_recur() :</p> <pre><code>def sim...
<python><recursion><nested-json>
2023-04-27 23:28:22
1
704
Kalpesh
76,125,257
6,401,403
Add column values in a dataframe to values in another dataframe with different length
<p>There is a dataframe <code>df</code>:</p> <pre><code> test_num el_num file_num value fail 429 4 1 0 3.36 False 430 4 1 1 3.29 False 431 4 1 2 3.29 False 432 4 1 3 3.26 False 433 4 1 4 3.28 ...
<python><pandas><dataframe>
2023-04-27 23:17:13
1
5,345
Michael
76,125,140
2,478,485
python3.6 pytest failing with "future feature annotations is not defined"
<p>Running pytests using the python3.6 tox. it started failing with following error.</p> <p>python3.6 tox failing with following error:</p> <pre class="lang-py prettyprint-override"><code> Error processing line 1 of /home/test/sample/.tox/py36/lib/python3.6/site-packages/_virtualenv.pth: Traceback (most r...
<python><pytest><tox>
2023-04-27 22:45:04
2
3,355
Lava Sangeetham
76,125,049
15,804,190
pywin32 - get cell Address in R1C1 format
<p>I am working with pywin32 and trying to get the R1C1 address of a specific cell. In VBA, you can use <code>Range.Address(ReferenceStyle:=xlR1C1)</code>.</p> <p>However, it appears that in pywin32, using <code>Range.Address</code> is not a method that allows for parameters, but instead is a property that just returns...
<python><excel><pywin32><win32com>
2023-04-27 22:22:28
1
3,163
scotscotmcc
76,124,928
7,648
"Missing key(s) in state_dict" error when loading model
<p>I am trying to load a model:</p> <pre><code>model = AlexNet3DDropoutRegression(9600) model_save_location = 'my_model.pt' model.load_state_dict(torch.load(model_save_location, map_location='cpu')) </code></pre> <p>Previously I saved it like this:</p> <pre><code> torch.save(self.mod...
<python><deep-learning><pytorch>
2023-04-27 21:56:04
2
7,944
Paul Reiners
76,124,916
3,720,435
windows 10 install python PIP does not work
<p>I am trying to get PIP working on my computer, but it keeps telling me the module isn't found.</p> <pre><code>C:\CODE\SCRIPTS\python&gt;where python C:\TOOLS\PYTHON\python.exe C:\Users\User\AppData\Local\Microsoft\WindowsApps\python.exe C:\CODE\SCRIPTS\python&gt;where py C:\Windows\py.exe C:\CODE\SCRIPTS\pytho...
<python><pip>
2023-04-27 21:53:43
0
1,476
user3720435
76,124,908
4,175,822
How can one type hint a __new__ method implementation using a Generic or Union?
<p>How can I type hint my <code>__new__</code> implementation using a generic input?</p> <p>So I have a class that can store <code>str</code> or <code>decimal.Decimal</code> instances, and it subclasses the input <code>str</code> or <code>decimal.Decimal</code> class.</p> <p>This code works in mypy and python:</p> <pre...
<python><python-3.x><operator-overloading><mypy><typing>
2023-04-27 21:51:19
0
2,821
spacether
76,124,814
6,242,883
How to take the cumulative maximum of a column based on another column
<p>I have a DataFrame like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ &quot;realization_id&quot;: np.repeat([0, 1], 6), &quot;sample_size&quot;: np.tile([0, 1, 2], 4), &quot;num_obs&quot;: np.tile(np.repeat([25, 100], 3), 2), &quot;accuracy&quot;: [0.8, 0.7, 0.8, 0....
<python><pandas><dataframe>
2023-04-27 21:32:32
4
1,176
Tendero
76,124,764
2,735,009
pool.map() doesn't like list of lists
<p>I have the following piece of code:</p> <pre><code>import sentence_transformers import multiprocessing from tqdm import tqdm from multiprocessing import Pool embedding_model = sentence_transformers.SentenceTransformer('sentence-transformers/all-mpnet-base-v2') data = [[100227, 7382501.0, 'view', 30065006, False, '...
<python><python-3.x><multiprocessing><mapreduce>
2023-04-27 21:21:56
1
4,797
Patthebug
76,124,622
6,632,138
Override __new__ of a class which extends Enum
<p>A class <code>Message</code> extends <code>Enum</code> to add some logic. The two important parameters are verbose level and message string, with other optional messages (<code>*args</code>). Another class <code>MessageError</code> is a special form of the <code>Message</code> class in which verbose level is always ...
<python><enums><overriding><typeerror><new-operator>
2023-04-27 21:00:15
1
577
Marko Gulin
76,124,313
16,003,919
How to get a dictionary of arguments passed to a python method?
<p>For simple functions we can use</p> <pre><code>def my_func(a, b): print(locals()) </code></pre> <p>...that will return <code>{a: 1, b: 2}</code> if function called with <code>my_func(a=1, b=2)</code>.</p> <p><strong>How can I get the same dictionary if <code>my_function</code> was a class method?</strong>*</p>
<python><dictionary><class><local-variables>
2023-04-27 20:15:29
1
577
Eduardo Gomes
76,124,064
19,989,634
Updating and refreshing front end variables with javascript
<p>I am wanting the item quantity my Cart page to refresh and update if quantity is changed with out having to refresh the page. The buttons are working regarding adding and removing items to the back end. But nothing is happening on the Cart page its self.</p> <p><strong>My view:</strong></p> <pre><code>def get_item_q...
<javascript><python><django>
2023-04-27 19:40:33
1
407
David Henson
76,123,911
8,079,611
Altair Python horizontal bar graph with two variables in the same frame
<p>Using Altair, how can I plot in the same horizontal bar plot two variables that are in the same data frame?</p> <p>I have a panda data frame that looks like this:</p> <pre><code># initialize list of lists data = [['AAA','71.15','FOUSA06C1Y'], ['AA','2.93','FOUSA06C1Y'], ['A','11.9','FOUSA06C1Y'], ['BBB','14.04','FOU...
<python><bar-chart><altair>
2023-04-27 19:14:59
1
592
FFLS
76,123,849
2,056,201
Is there a way to run Flask + React without building the React app
<p>I am following tutorial <a href="https://towardsdatascience.com/build-deploy-a-react-flask-app-47a89a5d17d9" rel="nofollow noreferrer">https://towardsdatascience.com/build-deploy-a-react-flask-app-47a89a5d17d9</a></p> <p>It works if I use the instructions and run <code>npm run build</code> in the <code>frontend</cod...
<javascript><python><reactjs><flask>
2023-04-27 19:06:33
0
3,706
Mich
76,123,535
267,391
Installing Python into user-accessible build folder during build process
<p>Trying to install python inside my build folder in CMake. At heart though it doesnt seem to work as documented for a few versions I have tried.</p> <pre><code>.\python-3.10.7-amd64.exe /quiet /log C:\Users\MyUser\Documents\python_install.log TargetDir=&quot;C:\Users\MyUser\Documents\PythonTest&quot; </code></pre> <...
<python><python-3.x><windows><build>
2023-04-27 18:21:40
1
3,194
Kalen
76,123,481
10,308,255
How can I melt a dataframe from wide to long twice on the same column?
<p>I have a dataframe:</p> <pre><code>data = [ [1, &quot;2022-04-29&quot;, 123, &quot;circle&quot;, 1, 3, 6, 7.3], [1, &quot;2022-02-10&quot;, 456, &quot;square&quot;, 4, np.nan, 3, 9], ] df = pd.DataFrame( data, columns=[ &quot;ID&quot;, &quot;date&quot;, &quot;code&quot;, ...
<python><pandas><dataframe><reshape>
2023-04-27 18:14:40
2
781
user
76,123,439
2,081,381
Use s3-pit-restore inside a lambda function
<p>I'm wondering if it's possible to import and use this tool in a lambda function written in Python and how to do it</p> <p><a href="https://github.com/angeloc/s3-pit-restore" rel="nofollow noreferrer">https://github.com/angeloc/s3-pit-restore</a></p>
<python><aws-lambda>
2023-04-27 18:08:20
0
388
juan
76,123,328
5,024,631
python: return element of array when a mask element is True, and return zero when a mask element is False
<p>Just say I have an numpy array like this:</p> <pre><code>a = np.array([1,2,3,4,5]) </code></pre> <p>and a mask like this:</p> <pre><code>mask = np.array([True, True, True, False, False]) </code></pre> <p>I would like to create an equal sized array with the elements from <code>a</code> included whenever that same pos...
<python><numpy>
2023-04-27 17:51:05
2
2,783
pd441
76,123,289
11,065,874
fastapi Annotated does not work with Field - How to fix it?
<p>I have installed fastapi version 0.95.0</p> <p>I have run.py working fine as below:</p> <pre><code>import uvicorn from fastapi import FastAPI from fastapi import Path app = FastAPI() @app.get(&quot;/test/{test_id}&quot;) def test(test_id: str = Path(..., title=&quot;a test title&quot;, description=&quot;a test de...
<python><fastapi><pydantic>
2023-04-27 17:46:08
0
2,555
Amin Ba
76,123,245
12,671,057
Why is set.remove so slow here?
<p>(Extracted from <a href="https://stackoverflow.com/q/76122610/12671057">another question</a>.) Removing this set's 200,000 elements one by one like this takes 30 seconds (<a href="https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3A4sVbBWKU0s0ihLz0lM1jAxAQFOTqzwjMydVodiKSwEI0vKLFCoUMvNgfBAo1itKzc0vS9Wo0ISLJRWlJmZD...
<python><performance><set><python-internals>
2023-04-27 17:41:08
1
27,959
Kelly Bundy
76,123,186
4,508,962
Python - Numba : How can I pass a @jitclass class to a property type in the specs of another @jitclass class?
<p>I have a class <code>OrderBook</code> that is <code>@jitclass</code>. I want to declare a class <code>Position</code> that contains a <code>last_ob</code> property, of type <code>OrderBook</code>. <code>Position</code> is a <code>@jitclass</code> as well.</p> <pre><code>@jitclass([ ('instrument', types.string), ...
<python><numba>
2023-04-27 17:32:41
1
1,207
Jerem Lachkar
76,123,155
1,860,222
Replacing all data in a pyqt table model
<p>I'm working on a game that involves moving 'gems' between a storage bank and a player. I'm using a QTableView to display the current gems of the player with a QAbstractTableModel as the model. When the app is initialized I set up the model like this:</p> <pre><code>def __init__(self, *args, obj=None, **kwargs): ...
<python><model-view-controller><pyqt><pyqt5><qtableview>
2023-04-27 17:27:34
2
1,797
pbuchheit
76,123,076
11,061,755
Read a compressed file with custom extension using Pyspark
<p>I have a set of gzip-compressed CSV files in S3. But they have the <em>.csv</em> extension, not <em>.csv.gz</em>. The issue is that when I try to read them using Pyspark, they do not read properly. I have tried many configurations, but with no luck.</p> <p><a href="https://i.sstatic.net/gFk7M.png" rel="nofollow nore...
<python><pyspark><compression>
2023-04-27 17:13:54
0
320
Shanga
76,122,859
2,651,073
How can I remove fields from WTF form by name
<p>I am trying to remove some fields from a wtf form:</p> <pre><code>form = super().edit_form(obj=obj) for f in form: if f.name not in self.form_details_columns: del f return form </code></pre> <p>This method doesn't work, however if I use something like</p> <pre><code> del form.questin </code></pre> <p>W...
<python><flask-wtforms><wtforms><flask-admin>
2023-04-27 16:46:47
2
9,816
Ahmad
76,122,713
6,719,772
How to define a function interface that allows any number of arguments and 1 required argument?
<p>How can I get rid of this mypy error?</p> <pre><code>class TestListener(Protocol): def __call__(self, command: str, *args: tuple[Any, ...],) -&gt; Any: ... def test(listener: TestListener): ... def listener1(command: str, test: int): ... def listener2(command: str): ... def listener3(co...
<python><mypy>
2023-04-27 16:27:45
0
401
danielmoessner
76,122,705
14,485,257
How to reduce the width of a plot display in Python Dash?
<p>This is my code for a callback function as a part of a bigger code using the Dash package.</p> <pre><code>@app.callback( Output(&quot;graph-container&quot;, &quot;children&quot;), Input(&quot;type-dropdown&quot;, &quot;value&quot;), ) def update_graph(serial_number): serial_data = pd.read_csv(&quot;...
<python><callback><plotly-dash><plotly>
2023-04-27 16:26:15
1
315
EnigmAI
76,122,690
543,913
Updating the location of a horizontal line based on a slider value in Bokeh
<p>I want to draw a plot that has both curves based on (x, y) data and horizontal lines. I want to update the curves and lines based on the state of a slider. How can I do this?</p> <p>I know how to update the curve based on the slider state, by using <code>ColumnDataSource</code>. I also know how to draw a horizontal ...
<python><bokeh>
2023-04-27 16:24:40
1
2,468
dshin
76,122,630
17,322,210
How to ignore environment directory when using python ruff linter in console
<p>I was trying ruff linter. I have a file structure like below</p> <pre><code>project_folder β”œβ”€β”€ env # Python enviroment [python -m venv env] β”‚ β”œβ”€β”€ Include β”‚ β”œβ”€β”€ Lib β”‚ β”œβ”€β”€ Scripts β”‚ β”œβ”€β”€ ... β”œβ”€β”€ __init__.py └── numbers.py </code></pre> <p>I am trying to use this <a href="https://beta.ruff.rs/docs/tutorial/" rel...
<python><linter><ruff>
2023-04-27 16:18:02
2
307
Shahobiddin Anor
76,122,572
1,362,485
Python yield function runs twice instead of once
<p>The objective of the python code below is to take a CSV file, partition it into N CSV files, and write these output files to disk.</p> <p>Note that each file has to contain complete records, you cannot split records between files.</p> <p>The <code>chunk_file.write()</code> function writes the files. Problem is that ...
<python><python-3.x>
2023-04-27 16:11:44
2
1,207
ps0604
76,122,528
14,735,451
How to cluster a massive amount of data that doesn't fit into memory?
<p>I have 30 files, each is a dictionary with about 1M keys that map to embeddings:</p> <pre><code>file_1 = {key_1: some_array, key_2: some_array ...} file_2 = {key_13: some_array, key_21: some_array ...} ... file_30 = {key_123: some_array, key_9: some_array ...} </code></pre> <p>Normally I would just use <a href="h...
<python><machine-learning><data-science><cluster-analysis><data-analysis>
2023-04-27 16:07:57
1
2,641
Penguin