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
75,933,074
14,546,482
Python nested dictionary - remove "" and data with extra spaces but keep None values
<p>I have a dictionary and would like to keep None values but remove values with &quot;&quot; and also values of any combination of &quot; &quot;'s</p> <p>I have the following dictionary:</p> <pre><code>{'UserName': '', 'Location': [{'City': '', 'Country': 'Japan', 'Address 1': ' ', 'Address 2': ' '}], 'P...
<python><json><dictionary>
2023-04-04 19:19:26
2
343
aero8991
75,933,037
11,092,636
flask and Jinja2 control structure doesn't work with render_template.format but works when passing the variable directly
<p>Here is a MRE.</p> <p><code>templates/index.html</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Flask App&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{test}} {% if test %}lol{% endif %} &lt;/body&gt; &lt;/html&gt; </code></pre>...
<python><flask>
2023-04-04 19:13:39
1
720
FluidMechanics Potential Flows
75,932,966
183,315
Why am I getting a MissingAuthenticationToken error when calling sns.publish from Python boto3?
<p>I'm working on a Python 3.10.3 application in a Docker container that sends messages using AWS SNS. I've written this code:</p> <pre class="lang-py prettyprint-override"><code>import boto3 from botocore.config import Config config = Config(signature_version=botocore.UNSIGNED) def send_sns_message(topic_arn: str, me...
<python><amazon-web-services><amazon-sns>
2023-04-04 19:03:19
1
1,935
writes_on
75,932,923
14,608,529
How to play 2 pieces of audio in parallel through different speakers? - python
<p>I have two pieces of audio: (1) 15 heartbeat clips and (2) 15 frequency noises. The frequency noises are only 1 second and shorter in duration than the heartbeat clips (generated on-the-fly, variable length).</p> <p>I'm able to successfully play both pieces through different speakers but only in series (one at a ti...
<python><multithreading><audio><python-multithreading><python-sounddevice>
2023-04-04 18:57:04
0
792
Ricardo Francois
75,932,695
935,376
reading a string with new line and comma into a list wit
<p>I have a string as shown below that correspond to date, agency, drivers license and car.</p> <pre><code>st = '2020-09-12, Budget, DF8576, Ford,\n 2020-04-22, Avis, D143266, Toyota, \n ..' </code></pre> <p><a href="https://i.sstatic.net/zGcnn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zGcnn.png" a...
<python><string>
2023-04-04 18:29:15
2
2,064
Zenvega
75,932,654
834,808
Unable to compile C extensions for clickhouse-connect python module
<p>Unexpectedly stuck on installation of python module <strong>clickhouse-connect</strong>, with this error:</p> <pre><code>Building wheels for collected packages: clickhouse-connect Running setup.py bdist_wheel for clickhouse-connect ... error Complete output from command /usr/bin/python3 -u -c &quot;import setupt...
<python><python-3.x><pip><module><clickhouse>
2023-04-04 18:23:55
1
468
Vasilij
75,932,642
1,715,544
How to test subclass of tornado.web.RequestHandler without using AsyncTestCase or AsyncHTTPTestCase (since they're deprecated)?
<p>I've got a subclass of <code>tornado.web.RequestHandler</code>, but the common test-cases are deprecated as of 6.2. Most resources I've found (including many questions on StackOverflow) use the deprecated classes, which I would like to avoid.</p> <p>Tornado's documentation says to use <code>unittest.IsolatedAsyncToT...
<python><unit-testing><tornado>
2023-04-04 18:22:47
1
1,410
AmagicalFishy
75,932,600
1,176,432
Distribute data from list into column in panda dataframe
<p>I have a list <code>users=['a','b','c','d']</code></p> <p>I have a dataframe X with 100 rows. I want to populate the <code>X['users']</code> with list users, such that</p> <ol> <li>distribution is even. In the above example there must be 25 entries of each element</li> <li>the distribution is done in a random way. I...
<python><pandas><dataframe>
2023-04-04 18:17:16
2
772
anotherCoder
75,932,557
1,964,489
Calculate overall balance with records including various add and sub operations
<p>I have a data frame <code>df</code> with columns <code>type</code>, <code>timestamp</code>, <code>value</code> and <code>team</code>. The type can be <code>add</code> (adding value) or <code>sub</code> (subtracting value). The records log the payments given or taken away for a particular team. I would like to calcul...
<python><pandas><dataframe>
2023-04-04 18:10:20
1
3,541
Ziva
75,932,505
3,394,510
How can I debug IPython display methods?
<p>I'm writing <code>_repr_latex_</code>, <code>_repr_html_</code>, <code>__repr__</code> methods.</p> <p>The problem that I'm facing is that I want to debug the call chain, because I bumped in to a situation like this.</p> <pre class="lang-py prettyprint-override"><code>class A: def _get_text(self): return...
<python><jupyter-notebook><ipython><jupyter-lab>
2023-04-04 18:02:12
1
840
ekiim
75,932,482
10,698,244
Generic way to check validity of file name in Python?
<p>Creating a file can fail in Python because of various file name related reasons:</p> <ol> <li><p>the file path is too long (see e.g.: <a href="https://askubuntu.com/questions/859945/what-is-the-maximum-length-of-a-file-path-in-ubuntu">what-is-the-maximum-length-of-a-file-path-in-ubuntu</a> )</p> </li> <li><p>the fil...
<python><filesystems>
2023-04-04 18:00:25
2
1,369
user7468395
75,932,278
12,131,472
how to "pivot" my dataframe without changing row and column orders
<p>I wish to be able to &quot;pivot&quot; an existing dataframe without changing the row and column order for existing category,</p> <p>I have this dataframe</p> <pre><code> shortCode period WS $/mt change 0 TC2 2023-04-03 279.17 NaN NaN 1 TC2 BALMO 228.49 39.30 -5.88 2 ...
<python><pandas><dataframe><pivot>
2023-04-04 17:33:37
1
447
neutralname
75,932,117
10,918,680
Pandas read_csv() converts integer columns to float if there are NaN. How does one keep them integers?
<p>I need to use <code>read_csv()</code> to make a dataframe from a csv file. Most columns in the csv file are integer type (such as number of products bought) or string type (such as store name), but sometimes there might be float type (such as the weight of product in lbs).</p> <p>I realize that Pandas convert the in...
<python><pandas><dataframe><numpy><csv>
2023-04-04 17:13:48
1
425
user173729
75,932,074
21,343,992
Python webbot library, example returns "session not created exception: Missing or invalid capabilities"
<p>I'm trying to run this simple Python webbot example on Ubuntu 22.04:</p> <pre><code>from webbot import Browser web = Browser() web.go_to('google.com') web.type('hello its me') # or web.press(web.Key.SHIFT + 'hello its me') web.press(web.Key.ENTER) web.go_back() web.click('Sign in') web.type('mymail@gmail.com' , in...
<python><python-3.x><selenium-webdriver><webbot>
2023-04-04 17:09:19
1
491
rare77
75,932,059
8,121,824
Selenium Attribute Error when selecting dropdown
<p>I had some code that was running fine but has recently ran into an error. When I run the following code to select the dropdown to iterate through pages, it returns this error:</p> <pre><code>File C:\Program Files\Spyder\pkgs\spyder_kernels\py3compat.py:356 in compat_exec exec(code, globals, locals) File c:\user...
<python><selenium-webdriver>
2023-04-04 17:08:02
1
904
Shawn Schreier
75,931,752
4,570,472
How to add an empty facet to a relplot or FacetGrid
<p>I have a <code>relplot</code> with columns split on one variable. I'd like to add one additional column <strong>with no subplot or subpanel</strong>. To give a clear example, suppose I have the following plot:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np impo...
<python><matplotlib><seaborn><facet-grid><relplot>
2023-04-04 16:30:39
1
2,835
Rylan Schaeffer
75,931,703
8,942,319
MongoDB/pymongo error: The DNS response does not contain an answer to the question ... IN SRV
<p>I have a python script running in K8s that's been working fine. Trying to run the code locally within it's docker container and I'm getting the following error when it attempts to connect to MongoDB</p> <p><code>pymongo.errors.ConfigurationError: The DNS response does not contain an answer to the question: _mongodb....
<python><mongodb><docker><dns>
2023-04-04 16:25:18
0
913
sam
75,931,697
6,515,755
Sentry traces_sampler(sampling_context) how to use with FastAPI
<p>In sentry docs there is example</p> <p><a href="https://docs.sentry.io/platforms/python/configuration/sampling/" rel="nofollow noreferrer">https://docs.sentry.io/platforms/python/configuration/sampling/</a></p> <pre><code>def traces_sampler(sampling_context): # Examine provided context data (including parent dec...
<python><fastapi><sentry>
2023-04-04 16:24:50
1
12,736
Ryabchenko Alexander
75,931,652
3,130,747
How to shade portions of a matplotlib axis face based on timeseries values
<p>Given data with timeseries and values associated with the timeseries, I'd like to shade the background of the axis plot depending on the value of the timeseries in order to highlight values which have particular meanings relating to the times (eg - could be a season, or opening hours etc).</p> <p>I don't really know...
<python><matplotlib>
2023-04-04 16:18:34
1
4,944
baxx
75,931,596
2,108,344
Why is my Python app slow connecting to Cassandra compared to C#?
<p>I have default configuration cassandra on default installation docker on windows 11. Table data contains 19 rows.</p> <p>The python driver is exceptionally slow and crashes in about 20% of cases. (Connection Timeout)</p> <p>I first expected this has something to do with docker or the container configuration, but I n...
<python><cassandra><datastax-python-driver>
2023-04-04 16:12:18
2
783
SalkinD
75,931,562
11,922,765
Remove the white gaps, or no data regions, from the histogram
<p>I want to plot Histogram plot. This is temperature. It will never be more than +- 150. But the real data has some bad values, may be inserted into the database by the datalogger when it fails to hear from the sensor in time. I want to plot histogram plot, so, I should know from it presence of any bad data and how mu...
<python><pandas><matplotlib><seaborn><histogram>
2023-04-04 16:09:06
0
4,702
Mainland
75,931,485
11,447,688
Vectorized calculation with condition in pandas
<p>I want to have vectorized calculation, since <code>apply or df.iterrows()</code> is slow. below code works fine, gives result as expected</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;a&quot;: [0, 12, 0, 5], &quot;b&quot;: [5, 89, 45, 6], &quot;c&quot;: [85, 23, 14, 10]}) def cal(data): val1 = da...
<python><pandas><numpy>
2023-04-04 16:01:12
2
1,511
young_minds1
75,931,467
11,668,258
json.decoder.JSONDecodeError: Invalid control character when we try to parse a JSON
<p>json.decoder.JSONDecodeError: Invalid control character error when i try to parse a JSON string.</p> <pre><code>import json import pprint json_data = None with open(&quot;C:\\Users\\75\\OneDrive\\PROJECT P1\\Work_1.0\\CBP\\server.txt&quot;, 'r') as f: data = f.read() json_data = json.loads(data) pprint.ppr...
<python><json>
2023-04-04 15:58:19
1
916
Tono Kuriakose
75,931,445
10,981,411
how do I change my dataframe shape in python
<p>below is my code</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Date' : [np.nan, '2035-12-31', np.nan, '2036-12-31',np.nan, '2037-12-31',np.nan, '2038-12-31'], 'Cftype': [&quot;Interest&quot;, &quot;Principal&quot;, &quot;Interest&quot;, &quot;Principal&quot;,&quot;Inte...
<python><dataframe>
2023-04-04 15:56:36
2
495
TRex
75,931,368
19,504,610
FastAPI - switching off a switch some time later
<p>Let's say I have this <code>sqlmodel.SQLModel</code> which has a table name <code>Project</code>.</p> <p>My intention is to feature a record of a <code>Project</code> for a definite period of time, e.g. 3 days, i.e. setting it's field <code>featured</code> to be <code>True</code>, and automatically set its field <co...
<python><fastapi><pydantic><sqlmodel>
2023-04-04 15:49:25
1
831
Jim
75,931,355
4,466,012
pandas Series sort_index with key
<p>I am trying to sort a Series using <code>sort_index(key = lambda idx: foo(idx))</code>, which should take the first item of the list and put it at the end. My sorting function <code>foo</code> looks like this:</p> <pre><code>def foo(idx): print(&quot;pre&quot;,idx) if idx.name == &quot;pca_n&quot;: r...
<python><pandas>
2023-04-04 15:47:52
2
740
GregarityNow
75,931,340
20,176,161
Extract a number within a string
<p>I have a string that looks like this:</p> <pre><code>T/12345/C T/153460/613 </code></pre> <p>I would like to extract the number between the slash <code>/</code> i.e. <code>12345</code> and <code>153460</code>. Sometimes I have 5 numbers, sometimes 6 or more.</p> <p>I tried <code>df[2:7]</code> which extracts from ...
<python><string><dataframe><extract>
2023-04-04 15:46:24
1
419
bravopapa
75,931,337
19,003,861
Call parent model field m2m relationship field from child
<p>I am trying to call the list of <code>M2M</code> object referenced in <code>ModelB</code> from <code>ModelC</code>.</p> <p>I normally use it the other way around (start with parent model and filter down to child), but this time I cant see a way around it.</p> <p>I feel there might be something to do with the related...
<python><django><django-views>
2023-04-04 15:46:06
2
415
PhilM
75,931,332
16,739,739
Python server is killed when started using docker-compose exec
<p>I start docker container and want to start simple python server in it. I can't use <code>ENTRYPOINT/CMD</code> of Dockerfile as it is already used for other things.</p> <p>I am trying to do it the following way:</p> <pre><code>docker-compose exec &lt;service_name&gt; /bin/bash -c &quot;./server.py &amp;&quot; </code...
<python><ubuntu><docker-compose>
2023-04-04 15:45:19
1
693
mouse_00
75,931,038
6,466,366
How to correctly filter a QuerySet based on a form MultipleChoice field?
<p>This is how I have defined my form:</p> <pre><code>class TaskFilterForm(forms.Form): status = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=PLAN_STATUS, ) </code></pre> <p>And I'm trying to get my QuerySet filtered like this:</p> <pre><code>cl...
<python><django><python-requests><request>
2023-04-04 15:11:21
2
656
rdrgtec
75,931,002
425,893
Unable to set a lambda's role from CDK
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>EventbridgeToLambda( self, &quot;Some&quot;, lambda_function_props=lambda_.FunctionProps( code=lambda_.InlineCode(lambda_code), handler=&quot;index.lambda_handler&quot;, runtime=lambda_.Runtime.PYTHON_3...
<python><aws-lambda><aws-cdk>
2023-04-04 15:07:34
1
5,645
John O
75,930,775
236,195
Pydantic field with custom data type and mypy
<p>Following the <a href="https://docs.pydantic.dev/usage/types/#custom-data-types" rel="nofollow noreferrer">Custom Data Types</a> example from Pydantic docs, I made my own <code>Timestamp</code> data type subclassing <code>str</code>. Everything works OK except that mypy is complaining when passing literal string val...
<python><mypy><python-typing><pydantic>
2023-04-04 14:44:46
1
13,011
frnhr
75,930,734
896,627
How to wrap custom C++ types for use with pybind11 if they can be initialized with literals?
<p>I'm embedding a Python interpreter into my C++ code with pybind11.</p> <p>I want to call C++ functions from Python code, so I have to wrap them first. Unfortunately, they take all kinds of custom types as parameters.</p> <p><code>void func_i_like_to_use(CustomeType a, AnotherCustomeType b);</code></p> <p>Typically, ...
<python><c++><pybind11>
2023-04-04 14:41:31
1
2,324
Chaos_99
75,930,720
10,266,106
Selecting Array Values With A Separate Array of Indices
<p>I am attempting to index a stacked 3-D Numpy array (named <code>stack</code>) by a group of 2-D indices contained inside of a separate Numpy array (named <code>piece</code>). The separate array contains several groups of 2-D index pairs. Inspection of these indices at the first entry of the array is as follows:</p> ...
<python><numpy><multidimensional-array><indexing><numpy-ndarray>
2023-04-04 14:39:52
0
431
TornadoEric
75,930,656
1,614,862
Splunk python SDK to upload a CSV file to lookup table of specific destination app
<p>I want to automate uploading a csv file to lookup tables of a specific destination app in my splunk. I can do this from splunk GUI as shown below, however I was trying to find a way to do it from python. I tried the following code which doesn't seem to be correct.</p> <pre><code>path = 'data/inputs/oneshot' Service....
<python><csv><upload><splunk><splunk-sdk>
2023-04-04 14:33:44
1
4,269
user1614862
75,930,570
3,744,747
SQLAlchemy cast to PostgreSQL TIMESTAMP WITH TIME ZONE
<p>I have seen that in postgresql we can cast datetime to <code>timestamp</code> or <code>timestamptz</code> which is <code>TIMESTAMP WITHOUT TIME ZONE</code> or <code>TIMESTAMP WITH TIME ZONE</code>.</p> <p>For instance using <code>psql(Postgres shell)</code>:</p> <pre><code>db=# select '2023-03-31 00:00:00'::timestam...
<python><postgresql><datetime><sqlalchemy><timestamp>
2023-04-04 14:25:12
1
11,103
Mehrdad Pedramfar
75,930,541
3,980,808
Extracting information from oddly shaped tables with python-docx
<p>I am using <code>python-docx</code> to try and extract some information from tables in word documents. Most of my sample files work well but I have a few tables that are failing. The basic code I am running is this:</p> <pre><code>from docx.api import Document document = Document(file_path) [[cell.text for cell ...
<python><python-docx>
2023-04-04 14:22:22
0
973
Ivar Eriksson
75,930,486
4,647,519
pandas.Series.map depending on order of items in dictionary?
<p>I tried to map the data types of a pandas DataFrame to different names using the map method. It works for 2 out of 3 permutations of the data types within the dictionary argument to map. But the 3rd one is ignoring 'int64'. Is the order of the dictionary keys supposed to matter or what am I missing here?</p> <pre><c...
<python><pandas>
2023-04-04 14:17:56
1
545
tover
75,930,356
19,130,803
python documentation using sphinx
<p>I am using sphinx to create document for the python project, I have google type docstring with following settings:</p> <pre><code>extensions = [ &quot;sphinx.ext.autodoc&quot;, &quot;sphinx.ext.autosummary&quot;, &quot;sphinx.ext.viewcode&quot;, &quot;sphinx_autodoc_typehints&quot;, &quot;sphinx....
<python>
2023-04-04 14:07:44
0
962
winter
75,930,300
4,716,625
PySpark - filter data frame based on field containing any value from a list
<p>I have a list of values called <code>codes</code>, and I want to exclude any record from a Spark dataframe whose <code>codelist</code> field includes any of the values in the <code>codes</code> list.</p> <pre><code>codes = ['O30', 'O81', 'Z38'] from pyspark.sql.types import StructType,StructField, StringType, Inte...
<python><pyspark>
2023-04-04 14:02:01
1
1,223
bshelt141
75,930,288
14,653,659
Send e-mail with ssl.PROTOCOL_TLS_CLIENT
<p>I wrote some code to send e-mails over a relay in Python. The code can be seen below. I have marked variables like which I changed from the real code in {}:</p> <pre><code>import smtplib, ssl port = 587 # For TLS # Create a secure SSL context context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) message = &quot;&quot;&...
<python><ssl>
2023-04-04 14:01:01
0
807
Manuel
75,930,214
15,673,412
python - boolean mask on array of custom objects
<p>Let's suppose I have defined the following class:</p> <pre><code>class Event(object): def __init__(self, time): self.time = time self.alive = True def __repr__(self,): return f&quot;t = {self.time:.2E}&quot; </code></pre> <p>And then I have a <code>numpy.ndarray</code> of <code>Event...
<python><arrays><object><numpy-ndarray>
2023-04-04 13:53:16
1
480
Sala
75,930,204
9,690,045
Using pandas library without bz2 (No root access, can't install bz2)
<p>I am trying to run a python code which uses <code>pandas</code> library. I am getting an error saying that <code>bz2</code> can not be found. I do not have root access and can not install anything. <strong>Is there a way to use <code>pandas</code> in another way?</strong> <em>There are similar questions to mine in s...
<python><python-3.x><pandas><bz2>
2023-04-04 13:51:43
2
836
SMMousaviSP
75,930,172
10,581,944
Type hinting for loading a machine learning PMML model pipeline using `pickle.load()`
<p>i have a function like:</p> <pre><code>def load_model(model_path: str) -&gt; ???: with open(&quot;XXX.pkl&quot;, &quot;rb&quot;) as f: model_pipeline = pickle.load(f) return model_pipeline </code></pre> <p>My question is what type hint i should specify for the output? thanks.</p>
<python><pickle><type-hinting><pmml>
2023-04-04 13:49:15
0
3,433
wawawa
75,930,160
8,962,929
How to override createsuperuser command in django
<p>I'm trying to customize the <code>createsuperuser</code> command.</p> <p>The purpose of this is:</p> <p>I've a table called <code>administrator</code>, and its have OneToOne relationship with <code>auth_user</code> table</p> <pre><code>class Administrator(models.Model): user = models.OneToOneField(get_user_model...
<python><django><django-rest-framework><superuser>
2023-04-04 13:47:49
1
830
fudu
75,930,094
8,962,929
Nested Serializer for prefetch_related in Django Rest Framework
<p>I'm trying to make a nested serializer with <code>prefetch_related</code> but it doesn't work, here's my code:</p> <p>models.py</p> <pre><code>from django.db import models class Student(models.Model): phone = models.IntegerField(null=True) birth_date = models.DateField(null=True) user = models.OneToOne...
<python><django><django-rest-framework><django-serializer><django-prefetch-related>
2023-04-04 13:41:20
1
830
fudu
75,930,033
18,018,869
How to avoid building numpy array iteratively
<p>I know iterating through numpy arrays is more costly than using the numpy functions. This is crucial to me since my arrays are quite large.</p> <p>Please use provided code as explanation what I want to achieve</p> <pre class="lang-py prettyprint-override"><code>start_value = 12 start_arr = np.array([-2, -4, -60, -0....
<python><arrays><numpy>
2023-04-04 13:35:43
3
1,976
Tarquinius
75,929,991
10,581,944
Type hinting pandas dataframe with specific columns/vectors
<p>i have a function likes this:</p> <pre><code>def func(y, predicted_y, sample_weights: pd.core.series.Series) -&gt; float: result = y / (predicted_y + y) return (result * sample_weights).sum() / sample_weights.sum() </code></pre> <p>where <code>y</code>, <code>predicted_y</code> are vectors - the actual targ...
<python><pandas><machine-learning><type-hinting>
2023-04-04 13:31:20
1
3,433
wawawa
75,929,908
11,261,546
Get channel to split in web request
<p>I have a web request that can get string parameters as (I'm simplifying the code to show the challenging part):</p> <pre><code>ch1 = &quot;RGB&quot; # or &quot;HSV&quot; sing1 = &quot;G&quot; # or &quot;V&quot; </code></pre> <p>I also get an image from the request and I want to perform a color conversion and a spli...
<python><string><opencv>
2023-04-04 13:24:00
1
1,551
Ivan
75,929,807
13,606,342
Run two different jobs depending upon the start and end time
<ul> <li>I am trying to implement a simple schedule in python3.6. Given two time start and end time. It will execute the respective job.</li> <li>All the time will be in 24hrs clock. Execute JobA if the current time falls between JobA start and end time. Execute JobB if the current time falls between JobB start and end...
<python><datetime>
2023-04-04 13:12:46
1
337
Lav Sharma
75,929,742
7,603,109
Pyspark: Read csv file with multiple sheets
<p>The <strong>.csv</strong> file I am using will have <strong>multiple sheets</strong> (Dynamic sheet names).</p> <p>I have to create <strong>dataFrames</strong> for all the sheets</p> <p>The syntax I am using:</p> <pre><code>df = self.spark.read .option(&quot;sheetName&quot;, None) .option('header',...
<python><dataframe><apache-spark><pyspark>
2023-04-04 13:05:46
1
22,283
Adrita Sharma
75,929,721
13,518,426
How to show full column width of a Polars dataframe?
<p>I'm trying to display the full width of column in polars dataframe. Given the following polars dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ 'column_1': ['TF-IDF embeddings are done on the initial corpus, with no additional N-Gram representations or furt...
<python><dataframe><python-polars>
2023-04-04 13:03:41
3
433
Ahmad
75,929,620
10,232,932
Count space character before a letter/number in a python pandas column
<p>I have a pandas dataframe, which looks like this:</p> <pre><code>columnA columnB A 10 B 12 C 13 D 14 010 17 </code></pre> <p>How can i count the space characters before the first string/number/letter in the column A in a new column? So for example:</p> <pre><code>columnA columnB coun...
<python><pandas>
2023-04-04 12:52:44
3
6,338
PV8
75,929,501
402,649
Python connect to MySQL and MariaDB from same application?
<p>How can I connect to both MySQL and MariaDB from the same Python 3.6+ application? The application is installed on RHEL8, same issue seems to exist on Ubuntu.</p> <p>Due to security vulnerabilities, I have to use MySQL client 8.0.30 or later</p> <p>mysql.connector with client 8.0.30 can not connect to MariaDB (chars...
<python><mysql><mariadb><mysql-connector>
2023-04-04 12:39:43
0
3,948
Wige
75,929,474
2,966,197
dictionary update() only keeping last dictionary when adding multiple dictionary from different files in a directory in python
<p>I have a directory which contains multiple <code>JSON</code> files. Each <code>JSON</code> file has a <code>JSON</code> structure (with 3 dictionary elements in each). I want to read each <code>JSON</code> file, and append the dictionary into a single <code>dictionary</code> - a master <code>dictionary</code> which ...
<python><json><dictionary>
2023-04-04 12:36:22
1
3,003
user2966197
75,929,413
11,338,984
Cannot install diffusion with pip
<p>I am trying to install diffusion by running <code>pip install diffusion</code> but I get the error below. I tried it with both Python version 3.10.9 and 3.9.16. I also tried it in another computer but I got &quot;Module not found&quot; on <code>diffusion.one_shot</code> when I use it like <code>from diffusion.one_sh...
<python>
2023-04-04 12:29:39
0
1,783
Ertan Hasani
75,929,336
610,569
How to test exceptions in mock unittests for non-deterministic functions?
<p>I've a chain of functions in my library that looks like this, from <code>myfuncs.py</code></p> <pre class="lang-py prettyprint-override"><code>import copy import random def func_a(x, population=[0, 0, 123, 456, 789]): sum_x = 0 for _ in range(x): pick = random.choice(population) if pick == 0...
<python><unit-testing><mocking><monkeypatching>
2023-04-04 12:19:56
2
123,325
alvas
75,929,309
4,940,741
grid arrange tsne plots from a for loop in scanpy using matplotlib
<p>I want to pu together generated tsnes from the loop below:</p> <pre><code>import scanpy as sc import seaborn as sns import matplotlib.pyplot as plt # Subset the data by condition conditions = adata_all.obs['condition'].unique() # Create a grid of subplots with 1 row and 3 columns fig, axes = plt.subplots(1, 3, fig...
<python><grid><visualization><scanpy><tsne>
2023-04-04 12:16:52
1
575
minoo
75,929,123
13,836,083
Losing Data in TCP socket connectivity
<p>I am working on socket programming.Here server sends random number of bytes to the machine who connected to server.This random number simulate that server is also receving data from somwhere else and data length can vary much and we are not sure how much.</p> <p>I am running a server and client both on the same mach...
<python><sockets>
2023-04-04 12:00:40
2
540
novice
75,929,062
17,119,272
One loop with all lists in one instead of two loops with separated lists
<p>I have an algorithmic question. Sorry if it seems to you silly.</p> <p>Consider I have two lists:</p> <pre class="lang-py prettyprint-override"><code>list_a = [&quot;Red&quot;, &quot;Blue&quot;, &quot;Black&quot;] list_b = [&quot;Samsung&quot;, &quot;Apple&quot;] </code></pre> <p>So the question is, if I iterate thr...
<python><algorithm>
2023-04-04 11:53:53
1
510
Ali Bahaari
75,929,002
11,942,948
How to properly patch sys.argv using mock patch in python unit test
<p>I have a file seed_dynamodb.py whose code is below. I want to write a unit test for it using mock patch. I am successfully able to patch boto3. Now I need to patch <code>sys.argv</code> as well. I have tried with below test code but it is giving an <code>IndexError</code>.</p> <p>==========seed_dynamodb.py==========...
<python><unit-testing><mocking><patch><sys>
2023-04-04 11:47:48
3
417
Deepak Gupta
75,928,961
1,616,738
ICE connection is stuck on checking and PeerConnection ConnectionState is stuck on connecting in Python Linux desktop application
<p>I am currently working on a video calling application for Linux desktops. To establish peer-to-peer connections, I have used aiortc for RTC connections and utilized WebSockets for handling offer, answer, candidate, and message data transactions. Moreover, I have integrated OpenCV for video capture and streaming thro...
<python><linux><webrtc><pyqt6><aiortc>
2023-04-04 11:44:25
0
1,954
Pavan V Parekh
75,928,922
6,439,229
Is it possible to pass kwargs to customised python enum
<p>You can customise an enum so the members have extra attributes. There are plenty of examples of that to be found. They all look something like this:</p> <pre><code>class EnumWithAttrs(Enum): def __new__(cls, *args, **kwargs): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj....
<python><enums><keyword-argument>
2023-04-04 11:39:57
2
1,016
mahkitah
75,928,730
1,432,980
return JSON payload and byte response
<p>I have REST endpoint that returns</p> <pre><code>{ &quot;dataset&quot;: [ { &quot;name&quot;: &quot;file1&quot;, &quot;location&quot;: &quot;https://container/file1.csv&quot; }, { &quot;name&quot;: &quot;file2&quot;, &quot;location&quot;: &q...
<python><fastapi>
2023-04-04 11:20:19
0
13,485
lapots
75,928,414
14,269,252
Rang-slider or similar solution to avoid overlapping of label in Y axis in Plotly
<p>I can not find the solution to my question. I made a plot with Plotly express, does range slider exist for Y axis? I already implemented range slider for X axis as follow, but the Y axis is messy, I was trying to come up with an solution but I can not implement rang slider on y axis, is there any way to make this ch...
<python><matplotlib><plot><charts><plotly>
2023-04-04 10:44:27
1
450
user14269252
75,928,216
1,850,007
Implementing __mul__ for timeseries in Python for different items
<p>I am trying to implement a piecewise constant function class in python. I am wondering what is the best way to implement these <code>__mul__</code> and <code>__add__</code> functions. Essentially, I want to be able to handle two cases: multiply by a constant or multiply by another timeseries.</p> <p>For multiply or ...
<python><operator-overloading>
2023-04-04 10:20:53
1
1,062
Lost1
75,928,204
4,502,950
Fill nan based on two columns in another data frame
<p>I have two data frames like (WITH DIFFERENT COLUMN HEADERS) only highlighting it because people are marking it as duplicates</p> <pre><code>df1 = pd.DataFrame({'Date':['7/03/2022', '9/3/2022'], 'Client':['Client 1','Client 2'], 'Course 2':['Computer skill','CCC']}) ...
<python><pandas><dataframe>
2023-04-04 10:19:53
3
693
hyeri
75,927,965
146,289
How can the Django ORM perform an aggregate subquery in a WHERE statement?
<p>I'm trying to construct the following query similar to this the Django ORM:</p> <p><code>SELECT * FROM table WHERE depth = (SELECT MIN(depth) FROM table)</code></p> <p>How can this be written in Django ORM notations? So far it seems hard to use an aggregate like this, because <code>QuerySet.aggregate()</code> isn't ...
<python><django><django-orm>
2023-04-04 09:53:30
2
22,626
vdboor
75,927,945
1,720,897
What does `pip install unstructured[local-inference]` do?
<p>I was following a tutorial on langchain, and after using loader.load() to load a PDF file, it gave me an error and suggested that some dependencies are missing and I should install them using <code>pip install unstructured[local-inference]</code>. So, I did. But it is now installing a whole lot of packages. A whole ...
<python><langchain>
2023-04-04 09:51:17
4
1,256
user1720897
75,927,772
10,564,162
Python script on Docker printing twice while in detached mode
<p>I am running a simple python script that prints &quot;Hello&quot; every minute</p> <p><strong>app.py</strong></p> <pre><code>import time from croniter import croniter from pytz import timezone from datetime import datetime def main(): print('Starting...') # Set the timezone to 'Europe/London' to account fo...
<python><docker>
2023-04-04 09:33:59
0
2,668
Álvaro
75,927,766
1,581,090
How to avoid recursive error when returning python dict elements in python?
<p>Suppose you want to return elements of a python dictionary as attributes of the class itself, you might implement it as follows:</p> <pre><code>class MyClass: def __init__(self): print(self.x) self.metadata = { &quot;a&quot;: 42, &quot;b&quot;: 1, } ...
<python>
2023-04-04 09:33:20
1
45,023
Alex
75,927,519
9,974,205
Problem installing a Python program from GitHub
<p>I am trying to install the <a href="https://github.com/DamascenoRafael/mqtt-simulator" rel="nofollow noreferrer">MQTT simulator</a>.</p> <p>I have python v3.3.10 installed in my computer. I followed <a href="https://www.youtube.com/watch?v=jjF9wmA4ik4&amp;t=398s" rel="nofollow noreferrer">this video</a> between 1:48...
<python><json><windows><github><pip>
2023-04-04 09:09:34
1
503
slow_learner
75,927,503
6,695,297
Use Column Value as key and another Column Value as dict from django ORM
<p>In Django, I am trying an output without using a for loop to optimise the operation.</p> <p>My model structure seems like this</p> <pre><code>class Test(BaseClass): id = model.UUIDField(uniq=True) ref = models.ForeignKey(Ref) name = model.CharField(max_length=50) </code></pre> <p>Sample data in the table...
<python><python-3.x><django><django-models><django-orm>
2023-04-04 09:08:32
1
1,323
Shubham Srivastava
75,927,440
11,193,122
Group by a column and then sum an array column elementwise in pyspark
<p>Hi I have a pyspark dataframe in the form:</p> <pre><code> CATEGORY VALUE 0 A [4, 5, 6] 1 A [1, 2, 3] 2 B [7, 8, 9] </code></pre> <p>I would like my output to be</p> <pre><code> CATEGORY VALUE 0 A [5, 7, 9] 1 B [7, 8, 9] </code></pre> <p>The a...
<python><pyspark>
2023-04-04 09:02:11
1
336
liamod
75,927,299
13,775,842
After running an open3d window and closing it, tkinter messagebox crashes and gives X Error of failed request: BadWindow (invalid Window Parameter)
<p>I am trying to add a messagebox yes no question after closing a open3d window.</p> <p>code to reproduce the error:</p> <pre class="lang-py prettyprint-override"><code>open3d.visualization.draw_geometries([]) #create yes no dialougdialog = messagebox.askquestion(&quot;Remove Object&quot;, &quot;Remove Object?&quot;, ...
<python><tkinter><open3d>
2023-04-04 08:46:40
2
483
Meyer Buaharon
75,927,084
1,864,294
Are pickle files reproducible?
<p>I would like to hash some <code>pickle</code> files for verification but I wonder if Python's <code>pickle</code> always produces the same output for the same input, at least within a protocol version? I wonder if the OS makes a difference? Do you have any references?</p>
<python><hash><pickle>
2023-04-04 08:23:19
1
20,605
Michael Dorner
75,927,048
1,571,823
stacking 0s and 1s vectors in TensorFlow
<p>Suppose <code>z = 3</code> and <code>e = 3</code>. I need to create a <code>z x (e*z)</code> design matrix that looks like this</p> <pre><code>[[1., 1., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 1., 1., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 1., 1.]] </code></pre> <p>How can I get such a matrix in <code>Tenso...
<python><concatenation><tensorflow2.0>
2023-04-04 08:20:13
0
404
user1571823
75,926,918
2,622,678
Pytest AttributeError: 'TestMyTest' object has no attribute
<p>I have multiple tests written in the following format. When the test is run, why do some tests fail with exception <code>AttributeError: 'TestMyTest' object has no attribute 'var1'</code>?</p> <p><code>var1</code> is defined as class variable in <code>test_init()</code>. Still the exception is thrown in <code>test_1...
<python><pytest>
2023-04-04 08:04:36
1
443
user2622678
75,926,636
19,079,397
Databricks: Issue while creating spark data frame from pandas
<p>I have a pandas data frame which I want to convert into spark data frame. Usually, I use the below code to create spark data frame from pandas but all of sudden I started to get the below error, I am aware that pandas has removed iteritems() but my current pandas version is 2.0.0 and also I tried to install lesser v...
<python><pandas><apache-spark><pyspark><databricks>
2023-04-04 07:32:51
5
615
data en
75,926,634
10,020,441
pandas column-slices with mypy
<p>Lately I've found myself in a strange situation I cannot solve for myself:</p> <p>Consider this MWE:</p> <pre class="lang-py prettyprint-override"><code>import pandas import numpy as np data = pandas.DataFrame(np.random.rand(10, 5), columns=list(&quot;abcde&quot;)) observations = data.loc[:, :&quot;c&quot;] featur...
<python><pandas><slice><mypy>
2023-04-04 07:32:34
1
515
Someone2
75,926,569
9,776,699
Excluding certain string using regex in python
<p>I would like to apply regex to the below code such that I remove any string that appears between a comma and the word 'AS'.</p> <pre><code>Select customer_name, customer_type, COUNT(*) AS volume\nFROM table\nGROUP BY customer_name, customer_type\nORDER BY volume DESC\nLIMIT 10 </code></pre> <p>Expected output:</p> <...
<python><regex>
2023-04-04 07:25:31
2
1,571
Kevin Nash
75,926,017
7,745,011
os.environ['SSL_CERT_FILE'] stores a path to a non-existing file in visual studio code while debugging
<p>This question is directly connected to <a href="https://stackoverflow.com/q/75904821/7745011">my last question</a>, however tackles a different topic so I am opening a new one.</p> <p>As mentioned there I am getting an error relating to a missing SSL cert. The error does not appear when the script is started from Te...
<python><visual-studio-code><environment-variables><urllib3>
2023-04-04 06:12:24
2
2,980
Roland Deschain
75,925,905
1,780,761
openCvSharp4 - apply graytone mask to image
<p>In my code, I take a picture, find the edges, make them thicker, invert the image, apply a blur and end up with a white image, with black blurred lines. The blurred zones are obviously gray tones.</p> <p>I want to use this as a mask to apply to a base image, but for some reason the mask is taken as binary mask, so e...
<vb.net><mask><opencv><grayscale><python>
2023-04-04 05:54:32
1
4,211
sharkyenergy
75,925,852
12,357,035
Getting syntax error while using virtualenv package in Ubuntu 16.04
<p>I am running Ubuntu 16.04 in VMware virtual environment. When I try to install virtualenv, I am facing issues.</p> <p>What I did:</p> <pre><code>sudo apt install python3-pip sudo pip3 install virtualenv virtualenv --version </code></pre> <p>The last command is showing this:</p> <pre><code>Traceback (most recent ca...
<python><python-3.x><virtualenv><ubuntu-16.04><apt>
2023-04-04 05:44:19
1
3,414
Sourav Kannantha B
75,925,741
15,010,256
Monitor batch job by Prometheus
<p>There is a Python batch job that pushes huge file(s) to a shared location, once the file(s) are pushed, couple of tests will be run against that/those file(s). I'm trying to get some metrics around the batch job &amp; planning to use Node exporter having below metrics or labels.</p> <pre><code>file_push_status (succ...
<python><prometheus><prometheus-node-exporter>
2023-04-04 05:18:22
1
466
Chel MS
75,925,705
21,346,793
Answers after fune-tuning model
<p>I make fine-tuning with my model on essays like :</p> <pre><code>[{ &quot;topic&quot;: &quot;Мы были достаточно цивилизованны, чтобы построить машину, но слишком примитивны, чтобы ею пользоваться». (Карл Краус)&quot;, &quot;text&quot;: &quot;Высказывание Карла Крауса, австрийского писателя, о том, чт...
<python><nlp>
2023-04-04 05:10:50
0
400
Ubuty_programmist_7
75,925,620
13,049,379
Find all pixels bounded between two contours in a binary image in Python
<p>I have a binary image, like the one shown below, which has two contours shown in white,</p> <p><a href="https://i.sstatic.net/VDCOz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VDCOz.png" alt="enter image description here" /></a></p> <p>I wish to make all the pixels in between the contours white so...
<python><numpy><opencv><image-processing><binary>
2023-04-04 04:52:16
1
1,433
Mohit Lamba
75,925,524
610,569
Accessing the `chrome://` pages inside Python without Selenium
<p>There's the <code>requests</code> and <code>urllib</code> page that can access <code>http(s)</code> protocol pages in Python, e.g.</p> <pre class="lang-py prettyprint-override"><code>import requests requests.get('stackoverflow.com') </code></pre> <p>but when it comes to <code>chrome://</code> pages, e.g. <code>chrom...
<python><google-chrome><selenium-webdriver><unix><python-requests>
2023-04-04 04:28:53
2
123,325
alvas
75,925,200
1,898,734
How to sum values of rows based on condition within each row?
<p>Can you please help me with a better solution on summarizing data based on conditions in separate rows.</p> <p>I have to group by the deal with a custom logic on amount column. Add Investment and Capital and subtract borrow and interest amounts from that, this should happen only if currency key matches else create a...
<python><pandas>
2023-04-04 03:00:45
1
460
Pavan Kumar Polavarapu
75,925,138
342,553
Is it safe to add user_id column to Django db session model?
<p>Currently the Django session model doesn't have an user ID field:</p> <pre class="lang-py prettyprint-override"><code>class AbstractBaseSession(models.Model): session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date =...
<python><django>
2023-04-04 02:43:55
0
26,828
James Lin
75,924,802
3,312,274
web2py: How to target a div using the response.menu
<p>The A() helper can take a <code>cid</code> or <code>target</code> attribute to target a DIV to load content. Using the response.menu tuples, how can this be achieved?</p> <pre><code>response.menu = [ (T('Home'), False, URL('default', 'index'), []), (T('Library'), False, None, [ (T('Services'), False...
<python><web2py>
2023-04-04 01:16:06
1
565
JeffP
75,924,661
2,591,343
New users on Django app at heroku doesn't persist on database
<p>We started a project on Heroku, using Django, but users aren't persisted on Django User table on our database, but as Admin users at Django?</p> <p>We use User.objects.create_user() from django.contrib.auth.models.User</p> <p>Database is MySQL</p> <p>Any tips?</p> <h2><strong>Update 1 (2023-04-04)</strong></h2> <p>S...
<python><mysql><django><heroku>
2023-04-04 00:32:56
1
463
HufflepuffBR
75,924,536
5,212,614
Trying to Optimize Process Using Linear Programming. Getting error about: IndexError: index 1 is out of bounds for axis 0 with size 1
<p>I am trying to optimize worker's schedules, based on the following dataframe.</p> <pre><code> Time Windows Shift 1 Shift 2 Shift 3 Shift 4 Workers Required 0 6:00 - 9:00 1 0 0 1 55.0 1 9:00 - 12:00 1 0 0 0 46.0 2 12:00 - 15:00 ...
<python><python-3.x><optimization><linear-programming>
2023-04-03 23:54:41
1
20,492
ASH
75,924,358
1,405,736
How can I convert my aggregate result set data type into the correct data type for Jinja 2?
<p>How can I convert my aggregate result set data type into the correct data type for Jinja 2?</p> <p>I can't figure out what the difference is between what a MongoDB .find() returns and what .aggregate() returns. The .find works as expected. the .aggregate doesn't. I'm sure my problem is converting the aggregate resul...
<python><jinja2>
2023-04-03 23:13:37
1
375
user1405736
75,924,321
1,876,739
Setting the timezone of a pandas datetime64 column to another column
<p>Given a pandas <code>DataFrame</code> with a <code>datetime64</code> column and a column representing the timezone:</p> <pre><code>dates_df = pandas.read_json(&quot;&quot;&quot;[{&quot;event_time&quot;: &quot;2023-04-03T15:03:52&quot;, &quot;event_tz&quot;: &quot;EDT&quot;}, {&quot;event_time&quot;: &quot;2023-04-03...
<python><pandas>
2023-04-03 23:00:25
1
17,975
Ramón J Romero y Vigil
75,923,964
10,140,821
extracting contents of file as variables in python
<p>I have a file like below in <code>Linux</code>.</p> <p><code>file_name</code> is <code>batch_file.txt</code>.</p> <p><code>sub_directory</code> is <code>code_base/workflow_1</code></p> <p><code>script_name</code> is <code>code_base/workflow_1/session_1.py</code></p> <p><code>batch_file.txt</code> contents are:</p> <...
<python>
2023-04-03 21:39:26
3
763
nmr
75,923,928
12,297,666
Check duplicated indices for each subset of values in pandas dataframe
<p>I have the following dataframe:</p> <pre><code>import pandas as pd df_test = pd.DataFrame(data=[['AP1', 'House1'], ['AP1', 'House1'], ['AP2', 'House1'], ['AP3', 'House2'], ['AP4','House2'], ...
<python><pandas>
2023-04-03 21:31:42
2
679
Murilo
75,923,812
2,178,850
Error when trying to concatenate lists with pd.concat
<p>I have a folder with 100 PDF files. Page 1 of all PDF files contains a table that I am extracting. Then I am concatenating all the tables into a dataframe and writing as a CSV file. However, I am getting error while concatenating.</p> <pre class="lang-py prettyprint-override"><code>import os import camelot import p...
<python><pandas><concatenation><tabula-py>
2023-04-03 21:12:52
1
669
akang
75,923,450
5,032,387
How memory consumption works when passing large objects to functions
<p>I would like to understand how memory management works when an argument is passed to a function in Python. The motivation for this question is that I am passing a dictionary with many keys to wrapper functions as my code progresses. The wrapper functions take in some arguments and write new key-value pairs to the ...
<python><memory-management>
2023-04-03 20:17:35
0
3,080
matsuo_basho
75,923,324
5,859,583
python seperating values
<p>I am getting a response like this <code>id=51555263943&amp;code=q15cd225s6s8</code> and I want to define the value of the <code>id</code> and the value of the <code>code</code> in separate strings How can I do this in python selenium maybe with regex(which I don't completely understand it)?</p>
<python>
2023-04-03 19:56:16
3
589
CatChMeIfUCan