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,239,640
11,199,298
Selenium error on Chrome version 113- Message: javascript error: Object.hasOwn is not a function
<p>Chrome has been updated recently and some of the functions raises</p> <pre><code>selenium.common.exceptions.JavascriptException: Message: javascript error: Object.hasOwn is not a function (Session info: chrome=113.0.5672.93) </code></pre> <p>This happens for clicks, and find_elements and I can't find any solution ...
<python><selenium-webdriver><selenium-chromedriver>
2023-05-12 20:09:40
2
2,211
Tugay
76,239,626
2,178,774
xarray: preprocess for nearest Lat/Lon non-NaN variable
<p>Each <code>latitude</code>/<code>longitude</code> location in the dataset is associated with typically one <code>sss</code> value per day. I would like to retrieve the <code>sss</code> value nearest to a specified location on a given day. For example, find the <code>sss</code> value nearest to <code>latitude=-89.88<...
<python><geospatial><python-xarray>
2023-05-12 20:07:05
0
516
There
76,239,472
12,436,050
Merge two pandas dataframes on multiple columns
<p>I have two dataframes and I would like to join these dataframes based on column 'Name' of df1 and multiple columns of df2.</p> <pre><code>df1 Name id ZYMAXID 9416X 6390 ZYPRED 6391 df2 label pref_label alt_label ZYPRED None None None ZYMAXID 9416X None </code></pre> <p>The f...
<python><pandas><dataframe>
2023-05-12 19:41:19
3
1,495
rshar
76,239,464
1,739,325
How to properly set st.session_state in streamlit
<p>So I have such sample code. As you can see locale setted twice. However I keep getting error:</p> <p><em>AttributeError: st.session_state has no attribute &quot;locale&quot;. Did you forget to initialize it? More info: <a href="https://docs.streamlit.io/library/advanced-features/session-state#initialization" rel="no...
<python><attributeerror><streamlit>
2023-05-12 19:40:11
1
5,851
Rocketq
76,239,461
489,088
How to properly specify the type of a local array in Numba?
<p>I have a local array declared in a cuda-compiled numba kernel:</p> <pre><code>from numba import cuda, types @cuda.jit((types.void(), device=True) def A(): arr = cuda.local.array(30, dtype=types.int64) </code></pre> <p>I need then to pass this array to another cuda compiled function:</p> <pre><code>@cuda.jit((ty...
<python><python-3.x><cuda><numba>
2023-05-12 19:39:45
1
6,306
Edy Bourne
76,239,420
3,908,009
How does Celery worker run the code defined elsewhere in a task?
<p>I tried reading official documentation as well as other SO threads, but it is still not clear how Celery works.</p> <p>From what I understand:</p> <ol> <li><strong>Django app</strong>: Celery is installed in Django (or any app) where <code>@shared_task</code> decorator function defines the work to be performed.</li>...
<python><django><celery><message-queue><django-celery>
2023-05-12 19:33:03
1
1,086
Neil
76,239,350
10,576,322
Options for configuration of python libraries
<p>I wrote a library around a REST API that I am going to use in other libraries or python projects. In this library I need some variables like URLs that I didn't want to hardcode into the library, but make it configurable. I don't want the URL or the USER and so on to be in input in the functions of that library, beca...
<python><configuration><environment-variables>
2023-05-12 19:21:43
0
426
FordPrefect
76,239,230
13,850,111
Is it possible to connect to a websocket on the same server using Flask?
<p>I'm trying to make a minimal implementation of an API that responds to a POST request by connecting to a websocket on the same server, using <code>Flask</code>, <code>websocket-client</code>, and <code>flask-sock</code></p> <p>Here is the code:</p> <pre class="lang-py prettyprint-override"><code>from flask import Fl...
<python><flask><websocket>
2023-05-12 19:00:51
0
429
WhoDatBoy
76,239,211
1,137,713
How to use typing overrides for pandas, torch, and numpy inputs
<p>I'm currently trying setup overloaded type definitions for my module to show that passing a data type will return the same type. My current module looks like:</p> <pre><code>class MyModule: @overload def __call__(self, inputs: pd.DataFrame) -&gt; pd.DataFrame: ... @overload def __call__(sel...
<python><numpy><pytorch><mypy><python-typing>
2023-05-12 18:57:44
1
2,465
iHowell
76,239,192
3,247,006
How to pass multiple arguments to a template tag with multiple "as" arguments in Django Template?
<p>With <a href="https://docs.djangoproject.com/en/4.2/howto/custom-template-tags/#simple-tags" rel="nofollow noreferrer">@register.simple_tag</a>, I defined the custom tag <code>test()</code> which has 2 parameters as shown below:</p> <pre class="lang-py prettyprint-override"><code>from django.template import Library ...
<python><django><django-templates><arguments><templatetags>
2023-05-12 18:53:42
1
42,516
Super Kai - Kazuya Ito
76,239,157
7,822,387
how to call databricks notebook from python with rest api
<p>I want to create a python notebook on my desktop that pass an input to another notebook in databricks, and then return the output of the databricks notebook. For example, my local python file will pass a string into a databricks notebook, which will reverse the string and then output the result back to my local pyth...
<python><databricks><databricks-rest-api>
2023-05-12 18:47:05
1
311
J. Doe
76,238,864
7,339,624
Center a tensor in pytorch
<p>Cantering means shifting a vector so that its mean will be zero.</p> <p>I want to center each row of a tensor, for example:</p> <pre><code>A = |1 , 1| A_center = |0, 0| |0 , 4| |-2,2| </code></pre> <p>For this, I use this approach:</p> <pre><code>a_center = a - a.mean(dim=1).unsqueeze(1) </code...
<python><numpy><pytorch><tensor>
2023-05-12 17:54:42
1
4,337
Peyman
76,238,813
3,247,006
How to apply custom "css" and "js" files to all admins in only one app efficiently?
<p>I have custom <code>css</code> and <code>js</code> files, <code>admin.py</code> and overridden <a href="https://github.com/django/django/blob/main/django/contrib/admin/templates/admin/base.html" rel="nofollow noreferrer">base.html</a> located in <code>templates/admin/app1/</code> as shown below:</p> <pre class="lang...
<javascript><python><css><django><django-admin>
2023-05-12 17:46:27
1
42,516
Super Kai - Kazuya Ito
76,238,761
9,058,482
Why does running the following code with os.fork() in a Jupyter Notebook cause the notebook to crash?
<p>I am trying to run the following Python code in a Jupyter Notebook cell that utilizes os.fork() to create a child process. However, the notebook crashes when executing the cell. The code is as follows:</p> <pre><code>import os def main(): print(&quot;Starting process...&quot;) # Call os.fork() to create a ...
<python><jupyter-notebook>
2023-05-12 17:38:25
1
569
Harsh Kumar Chourasia
76,238,730
12,961,237
Is a websocket connection handled by one single lambda instance on AWS?
<p>If I have a websocket connection:</p> <pre><code>client &lt;=&gt; AWS Lambda [Python] </code></pre> <p>While a connection is active: Will the client be connected to the same lambda instance for the whole time or can it change?</p>
<python><amazon-web-services><websocket>
2023-05-12 17:33:28
1
1,192
Sven
76,238,569
2,687,317
pandas- create new series from multilevel columns and aggregate
<p>So I have some complicated analysis to do. I have this data in a df:</p> <pre><code> Date/Time TimeStamp CallerId CallType watts Band slot Channel 0 20:02.0 3113677432 17794800 C1 0.060303 12 1 2 1 20:02.0 3113677432 5520488 OP8 0.302229 12 1 1 2 20:02.0 3113677432 55204...
<python><pandas><group-by>
2023-05-12 17:07:31
1
533
earnric
76,238,519
572,575
Python Cannot search data in Facebook
<p>I want to search data in facebook by using <a href="https://github.com/kevinzg/facebook-scraper" rel="nofollow noreferrer">facebook_scraper</a> like this code</p> <pre><code>from facebook_scraper import get_posts for post in get_posts('nintendo', cookies=&quot;cookies.json&quot;, pages=10): print(post) </code><...
<python><facebook><web-scraping>
2023-05-12 17:01:01
0
1,049
user572575
76,238,495
2,062,470
python "from datetime import date" gets forgotten
<p>Trying to parse csv dates (climate date) as datetime date objects but somehow &quot;from datetime import date&quot; gets forgotten. The error: <code>TypeError: 'str' object is not callable</code> is shown when calling date().</p> <pre><code>import csv from datetime import date file = 'nbcn-monthly_SMA_previous.csv'...
<python><datetime>
2023-05-12 16:57:07
1
409
mercergeoinfo
76,238,414
5,605,073
Recursively lookup value with polars?
<p>I want to be able to get the manager_id of each manager recursively using a polars DF which has two columns:</p> <p>&quot;employee_id&quot;, &quot;manager_1_id&quot;</p> <p>In pandas, this code was:</p> <pre><code>id_index = df.set_index(&quot;employee_id&quot;)[&quot;manager_1_id&quot;] for i in range(1, 12): d...
<python><dataframe><python-polars>
2023-05-12 16:43:07
2
588
ldacey
76,238,412
2,233,608
Getting a mypy type error using pydantic generics and don't know why
<p>With the following project setup</p> <p>pyproject.toml</p> <pre><code>[tool.poetry] name = &quot;test&quot; version = &quot;0.1.0&quot; description = &quot;&quot; authors = [&quot;Joe Smith &lt;joe.smith@example.com&gt;&quot;] [tool.poetry.dependencies] python = &quot;^3.11&quot; pydantic = &quot;^1.10.7&quot; mypy...
<python><mypy><pydantic>
2023-05-12 16:42:49
1
1,178
niltz
76,238,390
13,921,399
Identify first block in a pandas series based on switching values
<p>Consider the following pandas series:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd s = pd.Series([0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1]) </code></pre> <p>I want to identify the first block of 1 values. The block starts when 0 switches to 1 for the first time and ends when it swit...
<python><pandas>
2023-05-12 16:39:52
1
1,811
ko3
76,238,354
6,866,311
Can't install PyTorch with CUDA enabled on WSL
<p>For the last few months, I've been intermittently running into an issue where I can't install PyTorch with CUDA enabled on WSL on Windows 11.</p> <p>I use a Windows 11 Desktop PC with an RTX 4090 GPU. The Windows installation has WSL installed and enabled, and I run all my Jupyter Notebooks from WSL.</p> <p>I used t...
<python><pytorch><gpu><nvidia>
2023-05-12 16:35:22
1
549
Oion Akif
76,238,268
10,634,126
Retrieve transferred file size from AWS S3 put_object
<p>I have code to upload a file to AWS S3 in Python using <code>boto3.client</code> and <code>put_object</code> like (example below assumes JSON data):</p> <pre><code>def snapshot(data, path): s3_client = boto3.client(&quot;s3&quot;, region_name=&quot;us-east-1&quot;) r = s3_client.put_object( Body=byte...
<python><amazon-web-services><amazon-s3><boto3><filesize>
2023-05-12 16:23:23
0
909
OJT
76,238,241
1,473,517
How to read and insert an image in a Word document?
<p>I have a skeleton Word document in .docx format that includes an image of my signature. I want to update the document using Python. This works well but the signature image disappears when I do this. How can I read the image from the file and then insert it somewhere? I tried</p> <pre><code>from docx import Document...
<python><python-docx>
2023-05-12 16:20:22
0
21,513
Simd
76,238,185
15,637,435
Apply conditional opacity in plotly figure
<h3>Problem</h3> <p>I'm trying to create a Plotly chart where I would like to apply conditional opacity if an entry is selected (column 'selected': True or False) or not. Unfortunately, the things I tried did not work out. How can I apply conditional opacity to my Plotly chart?</p> <h2>What I tried</h2> <p>I tried to h...
<python><plotly>
2023-05-12 16:12:15
2
396
Elodin
76,238,102
3,247,006
How to show alert messages with the buttons in "Change List" page in Django Admin?
<p>There is <code>Person</code> model as shown below:</p> <pre class="lang-py prettyprint-override"><code># &quot;app1/models.py&quot; from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) </code></pre> <p>And, there i...
<javascript><python><django><django-models><django-admin>
2023-05-12 16:01:46
1
42,516
Super Kai - Kazuya Ito
76,238,069
2,471,211
EMR - Pyspark, No module named 'boto3'
<p>I am running an EMR with the following creation statement:</p> <pre><code>$ aws emr create-cluster \ --name &quot;my_cluster&quot; \ --log-uri &quot;s3n://somebucket/&quot; \ --release-label &quot;emr-6.8.0&quot; \ --service-role &quot;arn:aws:iam::XXXXXXXXXX:role/EMR_DefaultRole&quot; \ --ec2-attributes '{&quo...
<python><pyspark><amazon-emr>
2023-05-12 15:57:22
1
485
Flo
76,237,883
5,896,319
How to display a Foreign key serializer as a dropdown?
<p>I have three different models:</p> <pre><code>class Province(Model): province = models.CharField(max_length=250) class BaseCase(ModelWithStamps): ... province = models.ForeignKey(Province, null=True, blank=True, on_delete=models.CASCADE) class Event(BaseEvent): .... @property def province(se...
<python><django>
2023-05-12 15:34:24
3
680
edche
76,237,843
1,745,291
Is it possible to create a dynamic module with a custom `__dict__` class?
<p>When doing <code>module = types.ModuleType('mymodule')</code>, we don't get any chance of doing further customization, and we can't override <code>module.__dict__</code> since it's readonly...</p> <p>The same seems to apply with all other <code>importlib</code> functions (<code>module_from_spec</code> alike)</p> <p>...
<python><import><python-importlib>
2023-05-12 15:30:03
1
3,937
hl037_
76,237,791
14,957,517
ModuleNotFoundError: No module named 'jax.experimental.vectorize'
<p>I had this issue when I was working on a code that was not mine, and I was really overwhelmed by it for a month without a fixed any help online.</p> <p>I have jax-0.4.10 installed and Using a Mac book Pro.</p> <p>I never found any solution online probably because this error was specifically my problem.</p>
<python><module><vectorization><modulenotfounderror><jax>
2023-05-12 15:24:22
1
987
Cyebukayire
76,237,762
9,937,874
Pandas select rows where value is in either of two columns
<p>I have a dataframe that looks like this</p> <pre><code>Title Description Area 51 Aliens come to earth on the 4th of July. Matrix Hacker Neo discovers the shocking truth. Spaceballs A star-pilot for hire and his trusty sidekick must come to the rescue of a princess. </code></pre> <p>I am want to s...
<python><pandas>
2023-05-12 15:21:45
2
644
magladde
76,237,729
180,826
Python, FASTAPI and PlanetScale - I cannot connect to the my MySQL Database because of some strange SSL error
<p>I'm hosting FASTAPI app inside of a docker container. I can build and run docker and run the application perfectly fine in the browser. The issue occurs when I call an API that attempts to talk to my MySQL db from the hosting platform PlanetScale. Provided are my dockerfile:</p> <p>DOCKERFILE</p> <pre><code>FROM pyt...
<python><mysql><docker><fastapi>
2023-05-12 15:17:07
0
1,221
Brandon Michael Hunter
76,237,647
3,196,122
Is there a way to set the color of plotly legend items?
<p>I want to visualize multiple boolean arrays using Scatter traces with timestamps as x and the array-index as y. The values should be visualized using the colors. However, what I do not like is that the colors of the legend items are always set to the first element of these traces. Is there a way to set the legend it...
<python><colors><plotly><legend><scatter-plot>
2023-05-12 15:07:28
1
483
KrawallKurt
76,237,511
3,692,455
Unable to validate a YAML file using PyYAML library
<p>I am trying to validate YAML files using Python and I am using the PyYAML library for that.</p> <p>But unfortunately, it reports any files it checks as valid YAML files, not only YAML files. I am not sure why.</p> <p>Below is the Python script. Suppose you pass a sample bash script <code>file_path = './testbashscrip...
<python><python-3.x><pyyaml>
2023-05-12 14:54:29
1
903
vjwilson
76,237,417
12,155,713
How to combine multiple crosstabs while preserving same binary column
<p>I would like stack 2 crosstabs for 2 categorical variables (gender, race) while preserving the same binary variable (goal) as columns.</p> <p>Take for example this dataset:</p> <pre><code>df = pd.DataFrame({'GenderDSC':['Male','Female','Female','Male','Male','Male'], 'Goal':[0,1,0,1,0,0], '...
<python><pandas><pivot-table>
2023-05-12 14:41:29
2
354
Gabe Verzino
76,237,353
5,389,418
Unable to import module 'vc__handler__python'
<p>I am trying to deploy django web app through vercel. I have added django in requirements.txt file but it shows this error:</p> <p><code>[ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django'</code></p> <p>Feel free to share if it can be fixed.</p>
<python><django><vercel><modulenotfounderror>
2023-05-12 14:32:57
0
506
Leo
76,237,292
239,879
My Transformer Encoder / Decoder has the same values for all time steps in eval with PyTorch
<p>I have a model:</p> <pre><code># model.py import torch import torch.nn as nn import math class TransformerAutoencoder(nn.Module): def __init__(self, d_model, nhead, num_layers, dim_feedforward, dropout=0.0): super(TransformerAutoencoder, self).__init__() self.encoder = nn.TransformerEncoder( ...
<python><pytorch><transformer-model>
2023-05-12 14:26:07
0
43,875
Shamoon
76,237,273
9,318,323
Get info about Jenkins job from within python while the job is running
<p>So, I have this python script on Jenkins.</p> <p>I would like to write a function that, when called from Jenkins pipeline, will tell me which job it belongs to and ideally a link to the job itself.</p> <p><strong>Basically, the script must know that it is being run on Jenkins and tell which job / pipeline is running...
<python><jenkins><jenkins-pipeline>
2023-05-12 14:22:58
1
354
Vitamin C
76,237,230
10,895,042
Python: function only works when created inside main code, not when imported with from functions import *
<p>I'm finding lots of variations on this question on Stackoverflow, but not quite the same:</p> <p>I have something like the code below. If I define it within my main code it will find <em>df</em>, even when <em>df</em> itself is only defined after this function definition. It also works as expected: <em>df</em> is ta...
<python><import><scope>
2023-05-12 14:19:29
2
833
StephanT
76,237,219
5,050,431
LangChain: ValueError: 'not' is not a valid parameter name
<p>I am using 3.11.3 and langchain 0.0.166 on Windows. When I try and run</p> <p><code>from langchain.document_loaders import UnstructuredPDFLoader</code></p> <p>I get an error of</p> <blockquote> <p>ValueError &quot;'not' is not a valid parameter name&quot;</p> </blockquote> <p>It seems like FastAPI had this <a href="...
<python><python-3.11><py-langchain>
2023-05-12 14:18:19
1
4,199
A_Arnold
76,237,114
3,412,607
XSL to flatten XML converted Pandas dataframe
<p>I have the following XML Structure:</p> <pre><code>&lt;ml:Meals xmlns:ml=&quot;http://www.food.com&quot;&gt; &lt;ml:Meal&gt; &lt;ml:type&gt;lunch&lt;/ml:type&gt; &lt;ml:main_course&gt;turkey sandwich&lt;/ml:main_course&gt; &lt;ml:desert ml:Descriptor=&quot;cookie&quot;&gt; &lt;ml:ID ml:type=&quot...
<python><pandas><xml><xslt><lxml>
2023-05-12 14:05:25
2
815
daniel9x
76,237,040
5,531,578
combine multiple GridSearchCV instances
<p>I could save time by splitting up parameters that I would like to put into a GridSearchCV so that I could have further parallelization of parameter space exploration (beyond setting <code>n_jobs</code>).</p> <p>For instance instead of:</p> <pre class="lang-py prettyprint-override"><code>all_params = {'n_estimators' ...
<python><scikit-learn><gridsearchcv>
2023-05-12 13:56:59
1
303
BML
76,237,016
5,790,653
How to show the output of shell commands in Flask python
<p>I started learning Flask recently and I'm at the early stages.</p> <p>I googled and these are the links I used to help:</p> <p><a href="https://www.digitalocean.com/community/tutorials/how-to-use-a-postgresql-database-in-a-flask-application" rel="nofollow noreferrer">this</a> and <a href="https://stackoverflow.com/q...
<python><flask>
2023-05-12 13:54:16
1
4,175
Saeed
76,237,007
16,383,578
How to call class methods during instantiation of frozen dataclasses?
<p>I have a wrapper that adds some methods to a bunch of <code>dataclass</code>es, the <code>dataclass</code>es are all meant to be frozen, and should check the data types of the initialization values during instantiation.</p> <p>And I also wanted to overload the constructor of the <code>dataclass</code>es, so that the...
<python><python-3.x><python-dataclasses>
2023-05-12 13:52:36
1
3,930
Ξένη Γήινος
76,236,985
1,282,773
How to compare string enums in python
<p>Let's say I have <code>MyEnum</code> enum, and I want to define total ordering for it. My approach is:</p> <pre class="lang-py prettyprint-override"><code>from enum import Enum from functools import total_ordering @total_ordering class MyEnum(Enum): ONE = &quot;one&quot;, TWO = &quot;two&quot;, THREE = ...
<python><enums>
2023-05-12 13:49:58
4
6,807
ivaigult
76,236,933
12,753,007
Plotting two lines with the same starting point
<p>Given the coordinates of 3 points x, y, z, I would like to join x-y and x-z as 2 line segments, with the same starting point x. But the plot is displaying 2 intersecting lines, with starting and ending points other than x, y, z. I would like some help fixing this.</p> <pre><code>x = [0, 9] y = [7, 2] z = [4, 3] plt....
<python><matplotlib>
2023-05-12 13:44:18
0
461
siegfried
76,236,860
8,937,353
Find all matching points in multiple CSV list
<p>I have 4 CSVs with 5 columns and over 500 rows. 1st column is say Plane. second is Points. 3rd and 4th are x and y coordinates of Points. 5th is Values. For each Plane, there can be multiple Points. In each CSV Plane is matched. For e.g. Plane = 3 in 1 CSV is also Plane = 3 in other CSVs. But the Points number is di...
<python><csv>
2023-05-12 13:35:11
0
302
A.k.
76,236,755
353,337
Read XML processing instrutions with attributes
<p>I have an XML file</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?foo class=&quot;abc&quot; options=&quot;bar,baz&quot;?&gt; &lt;document&gt; ... &lt;/document&gt; </code></pre> <p>and I'm interested in the processing instruction <code>foo<...
<python><xml><processing-instruction>
2023-05-12 13:21:04
3
59,565
Nico Schlömer
76,236,652
3,247,006
How to prevent the text in Django Admin to get bigger when overriding "base.css" set in overridden "base.html"?
<p>I could change the header color to black in all admin pages with the following steps.</p> <p>So, this is Django Admin as shown below:</p> <p><a href="https://i.sstatic.net/u9JkE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/u9JkE.png" alt="enter image description here" /></a></p> <p>Then, I copied <...
<python><django><django-templates><django-admin><django-staticfiles>
2023-05-12 13:08:31
1
42,516
Super Kai - Kazuya Ito
76,236,370
5,510,713
GIMP script-fu to ImageMagic conversion
<p>I have written the following GIMP <code>script-fu</code> function to remove lens distortion from an image using the <code>lens-distortion-plugin</code>. I execute this script through a command line function from my main python script. Just wondering if there is an equivalent ImageMagic function (or any other library...
<python><python-3.x><imagemagick><gimp><gimpfu>
2023-05-12 12:35:17
0
776
DhiwaTdG
76,236,236
11,311,927
Is it possible to create mock data using pydantic-factories in such a way that attributes adhere to pydantic validator requirements?
<p>I'm trying to create some mock data, where one of my classes (for which I specified a Pydantic dataclass by inheriting from <code>Pydantic.BaseModel</code>) has date attributes. I want to make sure that the <code>end_date</code> is always later than the <code>start_date</code>, and validate this using the pydantic v...
<python><validation><attributes><factory><pydantic>
2023-05-12 12:21:06
2
315
Sam
76,235,975
8,838,303
Why does this dictionary suddenly become empty?
<p>I have a CSV file &quot;country.csv&quot; that looks precisely like this:</p> <pre><code>Country Code,Country Name,Country-ID US,United States,0 DE,Germany,1 AU,Australia,2 CZ,Czechia,3 CA,Canada,4 AR,Argentina,5 BR,Brazil,6 PT,Portugal,7 GB,United Kingdom,8 IT,Italy,9 GG,Guernsey,10 RO,Romania,11 ES,Spain,12 FR,Fra...
<python><csv><dictionary>
2023-05-12 11:47:34
1
475
3nondatur
76,235,910
9,479,564
Using scipy.optimize.curve_fit does not fit curve properly
<p>I want to fit a random time series segment to a predefined list of functions. For demo purposes, I only use the sine function and a demo time series.</p> <pre class="lang-py prettyprint-override"><code>amplitude = 1 omega = 2 phase = 0.5 offset = 4 def sine(x, a, b, c, d): &quot;&quot;&quot;Sine function&quot;&qu...
<python><numpy><scipy><curve-fitting>
2023-05-12 11:37:57
0
888
Oddaspa
76,235,874
15,295,149
Downgrade Python from 3.11.2 to 3.10 in specifc environment
<p>I am using Python's virtual environment 'venv'. My current version is 3.11.2</p> <p>I need to downgrade it.</p> <p>I have already tried the following steps:</p> <pre><code>pip3 install python==3.10.10 </code></pre> <p>and got the following error:</p> <p><strong>ERROR: Could not find a version that satisfies the requ...
<python><python-3.x>
2023-05-12 11:32:02
2
746
devZ
76,235,868
11,065,874
In python pytest, How do I start a new runtime for each test function?
<p>I have a singlton function that I want to test as below:</p> <pre><code>import abc class SingletonABCMeta(abc.ABCMeta): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(SingletonABCMeta, cls).__call__(*args, **kwargs) ...
<python><pytest><singleton>
2023-05-12 11:31:07
1
2,555
Amin Ba
76,235,454
13,734,451
Using np.where to create a column
<p>I would like to create number of days based on two variables. If the units are in week, multiply the <code>nums</code> by 7, if by month by 12 and 365 if by year. Am unable to achieve this...any leads??</p> <pre><code>import pandas as pd import numpy as np nums = [2, 3, 4, 1, 4, 2, 4, 11, 1, 1] units = ['days', 'we...
<python><pandas><numpy>
2023-05-12 10:37:48
1
1,516
Moses
76,235,423
10,441,038
How to specify discrete color of markers in Plotly.graph_objects?
<p>After a lot of searching, I still have <strong>NOT</strong> found how to specify discrete color mapping for markers in a scatter figure that created by plotly.<strong>graph_objects (instead of plotly.express)</strong>.</p> <p>There are some docs about specifying discrete color mapping of plotly, but all of them are ...
<python><colors><plotly><visualization><plotly.graph-objects>
2023-05-12 10:33:43
1
2,165
Leon
76,235,372
8,699,450
Why is multiplying a 62x62 matrix slower than multiplying a 64x64 matrix?
<p>Using the code below (in a google colab), I noticed that multiplying a <code>62x62</code> with a <code>62x62</code> is about 10% slower than multiplying a <code>64x64</code> with another <code>64x64</code> matrix. Why is this?</p> <pre class="lang-py prettyprint-override"><code>import torch import timeit a, a2 = to...
<python><performance><pytorch><matrix-multiplication>
2023-05-12 10:27:11
0
380
Robin van Hoorn
76,235,238
4,471,415
Ignoring malformed utf8 in python3
<p>I have a script to convert xml to text (extract document content sans xml tags) that needs to deal with corrupt xml files.</p> <p>The corruption comes from a partially decoded zip file, so there may be a utf8 character that got truncated. <code>lxml</code> throws an error when encountering the last few bytes.</p> <p...
<python><lxml>
2023-05-12 10:08:48
1
628
Reinstate Monica
76,235,197
18,904,265
How to handle Exceptions in a series of functions, which call another?
<p>I have multiple functions, which are chained together, something like this:</p> <pre class="lang-py prettyprint-override"><code>def first_function(params): value = None try: value = some_api_call(params) except ValueError: print(&quot;some ValueError Message!&quot;) if value is not No...
<python>
2023-05-12 10:02:59
2
465
Jan
76,235,139
12,430,846
Read a large TAD data with Dask
<p>I have a very large dataframe. It was originally a TAD file. Someone saved it with CSV extension.</p> <p>I was trying to read it in pandas but it takes hours, even with <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">chunksize</a> parameter.</p> <pre><code>start ...
<python><pandas><dask>
2023-05-12 09:56:21
0
543
coelidonum
76,235,109
6,165,496
Missing dependency 'openpyxl' when using pandas in Lambda
<p>I'm trying to read an excel file from S3 using pandas in Lambda. To make pandas work in my Lambda function I've created a custom layer. This custom layer uses a zip file which I've created using the following script:</p> <pre><code>python3 -m pip install wheel curl -LO https://files.pythonhosted.org/packages/e9/d7/e...
<python><pandas><amazon-web-services><aws-lambda>
2023-05-12 09:51:55
1
1,284
RudyVerboven
76,235,000
1,145,666
Information sent in DELETE body is not processed by CherryPy
<p>I have this Javascript (jQuery) code:</p> <pre><code>$.ajax({ url: `/rest/order`, type: 'DELETE', data: { &quot;magentoid&quot;: order_id }, success: function(data) { }, error: function(xhr, status, error) { } }); </code></pre> <p>And when checking this call in the Chrome developer consol...
<javascript><python><jquery><cherrypy><http-delete>
2023-05-12 09:38:27
0
33,757
Bart Friederichs
76,234,895
3,679,054
Problem with Qt Designer - pglive integration for real-time plotting
<p>I followed the tutorial on the <a href="https://pypi.org/project/pglive/" rel="nofollow noreferrer">pglive docs</a> and I was able to have a real-time sine plot on my computer. Then I used an arduino to stream some random number through the serial port and I was able to read and plot the data using pglive.</p> <p>No...
<python><pyqt><real-time><qt-designer><pyqtgraph>
2023-05-12 09:24:12
1
421
Sfrow
76,234,657
4,255,096
Pandas: Shorten string for multiple columns
<p>I have a pandas dataframe with over 100 columns, a good portion of them are type string but not all of them. I want to find a way to shorten the length each column for those rows that exceed a certain length.</p> <p>What would be a sensible approach to do this?</p> <p>I thought about storing which columns I want to ...
<python><pandas><dataframe>
2023-05-12 08:53:30
1
375
Geosphere
76,234,472
19,318,120
Django Inline for m2m field
<p>I've a Page model with m2m field to model called content I created an inline page but when testing the performance with django silk, I saw 11 queries mostly because of language field that's being fetched at least 4 times here's my code:</p> <p>models.py</p> <pre><code>class Page(models.Model): created_at = model...
<python><django>
2023-05-12 08:28:25
0
484
mohamed naser
76,234,452
2,562,058
ClobberWarning with a simple conda build
<p>I am trying to build a simple package (only python code) and I get this warning:</p> <pre><code>ClobberWarning: This transaction has incompatible packages due to a shared path. packages: conda-forge/noarch::tomli-2.0.1-pyhd8ed1ab_0, conda-forge/osx-arm64::mypy-1.2.0-py311he2be06e_0 path: 'lib/python3.11/site-pac...
<python><anaconda><conda><miniconda><conda-build>
2023-05-12 08:27:03
1
1,866
Barzi2001
76,234,354
1,020,139
How does Poetry associate a project to its virtual environment?
<p>How does Poetry associate a project to its virtual environment in <code>~/.cache/pypoetry/virtualenvs</code>? I can't find any link inside the project, e.g. <code>grep -ie NKJBdMnE .</code> returns nothing.</p> <p><code>poetry env info</code>:</p> <pre><code>Virtualenv Python: 3.10.11 Implementation: CPython...
<python><python-poetry>
2023-05-12 08:10:34
1
14,560
Shuzheng
76,234,337
404,109
langchain\\chains\\llm_summarization_checker\\prompts\\create_facts.txt error when try to package python file
<p>I tried to <code>pyinstaller</code> package my python file which uses <code>langchain</code>. i.e it imports:</p> <pre><code>from langchain.text_splitter import CharacterTextSplitter from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import FAISS from langchain.chains.question_answe...
<python><pyinstaller><langchain>
2023-05-12 08:07:28
6
1,059
Jason
76,234,312
13,916,049
ImportError: cannot import name 'is_categorical' from 'pandas.api.types'
<p>I want to convert <code>file1.hic</code> file into <code>.cool</code> format using <a href="https://github.com/4dn-dcic/hic2cool" rel="noreferrer">hic2cool</a>, which is written in Python. I converted the files using command line:</p> <pre><code>hic2cool convert file1.hic file1.cool -r 10000 </code></pre> <p>Traceba...
<python><pandas><linux>
2023-05-12 08:03:48
2
1,545
Anon
76,234,027
21,404,794
How to sort the index of a pandas.Dataframe to pass pd.testing.assert_frame_equal
<p>I'm using pd.testing.assert_frame_equal to test if a function I've written works as expected, and I'm getting a weird error:</p> <p>When I compare the 2 dataframes that are printed in exactly the same way (I checked the values are the same with np.array_equal(df1.values, df2.values), so I know they're the same by hu...
<python><pandas><dataframe>
2023-05-12 07:24:45
2
530
David Siret Marqués
76,233,986
20,646,427
How to upload doc/docx file and return pdf file in FastAPI?
<p>I'm looking for a way to convert word or excel file to pdf file using in my FastAPI project.</p> <p>I tried to use <code>comtypes</code> library but that didn't help. I guess this library is not what i exactly need</p> <p>I got an error</p> <blockquote> <p>ctypes.ArgumentError: argument 1: TypeError: Cannot put &lt;...
<python><fastapi>
2023-05-12 07:20:03
0
524
Zesshi
76,233,888
7,752,049
Scrape data with scrapy
<p>I am going to scrape the Pararius.nl as a practice with scrapy but when I start crawling it returns the fairlane protection, how can I pass it? Do I need any tools? please help with one example</p> <pre><code>def parse(self, response): url = 'https://www.pararius.nl/{deal_type}/nederland/p-{page}/' for ...
<python><scrapy>
2023-05-12 07:05:30
2
2,479
parastoo
76,233,767
9,717,388
How to implement case-insensitive in SlugRelatedField in drf serializers?
<p>I'm using SlugRelatedField in my serializer. I want to validate it on a case-insensitive basis, so I add postfix &quot;__iexact&quot; to the &quot;slug_field&quot; attr. And validation works as I need (case-insensitive).</p> <pre><code>class MySerializer(ModelSerializer): customer = serializers.SlugRelatedField(...
<python><django><django-rest-framework>
2023-05-12 06:48:14
1
343
PolYarBear
76,233,637
1,702,957
Offline Anaconda Installation package
<p>This is relatively simple question but after surfing on internet for about an hour, I have to ask. I am looking for Anaconda offline installation but couldn't find any link to the installer. According to <a href="https://docs.anaconda.com/anaconda-repository/admin-guide/install/airgap-archive/" rel="nofollow norefer...
<python><installation><anaconda><offline>
2023-05-12 06:26:56
1
1,639
aneela
76,233,578
2,287,458
Group/Pivot Data Values By First & Last Entry in DataFrame
<p>Let's assume I have the following data (in reality I have millions of entries):</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import datetime as dt df_data = pd.DataFrame([ [dt.date(2023, 5, 8), 'Firm A', 'AS', 250.0, -1069.1], [dt.date(2023, 5, 8), 'Firm A', '...
<python><python-3.x><pandas><dataframe><pivot-table>
2023-05-12 06:15:48
2
3,591
Phil-ZXX
76,233,570
8,236,050
Show cursor in Selenium Webdriver and s
<p>I am building a Selenium Webdriver script in Python. My issue is that I am performing some actions that consist on moving to a certain position and clicking there. My action is not working, so I wanted to run the script as non headless to see what is happening, but, as the cursor does not appear in the screen, I am ...
<python><google-chrome><selenium-webdriver><selenium-chromedriver><google-chrome-headless>
2023-05-12 06:14:02
2
513
pepito
76,233,348
2,552,290
idiom for protecting against inexact native division in code that uses sympy?
<p>I am developing some code whose variables and function params are sometimes native python numeric types (int, float) and sometimes sympy types (sympy.core.numbers.Integer, sympy.core.numbers.Rational, sympy.core.symbol.Symbol, sympy.core.add.Add, etc.). And I sometimes want to express division (/), but I'm having tr...
<python><sympy>
2023-05-12 05:23:14
2
5,611
Don Hatch
76,233,333
13,916,049
Convert selected files in directory into another format
<p>For all the files in the input directory ending with &quot;hic&quot;, I want to convert them to cool format. A single file can be converted using:</p> <pre><code>hic2cool_convert(&lt;infile&gt;, &lt;outfile&gt;) </code></pre> <p>But I'm not sure how to write a for loop to convert all the relevant files.</p> <pre><co...
<python><file><directory>
2023-05-12 05:18:58
2
1,545
Anon
76,233,316
597,858
Main window shrinks in tkinter
<p>I have a simple tkinter app that plots a sine curve. The problem I am facing is that when I press the PLOT button, original root window shrinks in size. I want to keep the window size fixed, irrespective of pressing the PLOT button or not. what shall I do?</p> <pre><code>import tkinter as tk import matplotlib.pyplot...
<python><tkinter>
2023-05-12 05:15:13
1
10,020
KawaiKx
76,233,267
10,576,322
Python logging of conditional imports in libraries
<p>I have a library with a module that does an conditional import.</p> <p>I want to be able in my applications to log the outcome of the conditional import. But that forces me to configure my handlers etc. before the import of that module, which is regarded bad style.</p> <p>The module looks something like that.</p> <p...
<python><logging><import><python-logging>
2023-05-12 05:03:11
1
426
FordPrefect
76,233,184
302,102
Defining fst and snd with type variables
<p>I sometimes encounter typing errors when using Haskell-style <code>fst</code> and <code>snd</code> functions defined in Python as follows:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar a = TypeVar(&quot;a&quot;) b = TypeVar(&quot;b&quot;) def fst(x: tuple[a, b]) -&gt; a: &quot...
<python><mypy>
2023-05-12 04:44:13
0
1,935
aparkerlue
76,233,172
19,079,397
How to convert geopandas dataframe with multi-polygon into geojson?
<p>I have a Geopandas data frame with multi-polygons geometries. Now, I want to convert the data frame into geojson. So, I have converted the dataframe into <code>dict</code> and then used <code>json.dump(dict)</code> to convert the data frame into json. This works well when I have single polygon but throws error <code...
<python><json><geojson><geopandas><multipolygons>
2023-05-12 04:42:04
2
615
data en
76,233,092
3,009,875
Django ReportLab 'list' object has no attribute 'getKeepWithNext'
<p>I am trying to generate a pdf that will look like this:<a href="https://i.sstatic.net/lecxv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lecxv.png" alt="enter image description here" /></a></p> <p>Here is my code:</p> <pre><code>doc = doc = SimpleDocTemplate(invoice_name) flowable = [] flowable.app...
<python><django><reportlab>
2023-05-12 04:18:20
1
2,209
Yax
76,234,086
7,090,396
Scan Gun returning empty data in Python Script
<p>I have a symbol barcode scanner model DS4308 that I am trying to pull scan data from.</p> <p>In my python script, I am using the &quot;hid&quot; library via <code>import hid</code> to connect to the device. Here is the code block that is used to connect to the scanner:</p> <pre><code> def initScanner(self): ...
<python>
2023-05-12 04:02:37
1
1,512
Eric Brown
76,233,033
3,741,571
Why do Python and Java behave differently when decoding GBK
<p>This question is related to <a href="https://stackoverflow.com/questions/76232910/">How to decode bytes in GB18030 correctly</a>.</p> <p>I would like to decode an array of bytes which are encoded with <a href="https://en.wikipedia.org/wiki/GBK_(character_encoding)" rel="nofollow noreferrer">GBK</a>, but found that P...
<python><java><unicode><character-encoding>
2023-05-12 03:58:03
1
6,975
chenzhongpu
76,232,951
8,205,099
Docker configuration working in one machine(Ubuntu) but not in other(Mac M1)
<p>I have setup Django with MySQL in docker compose in my mac M1. Everytime I do docker-compose up I get error for django application</p> <pre><code>&quot;Error: File &quot;/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py&quot;, line 166, in __init__ web_1 | super(Connection, self).__init__(*args, **k...
<python><python-3.x><django><docker><docker-compose>
2023-05-12 03:36:14
1
4,176
Wahdat Jan
76,232,910
3,741,571
How to decode bytes in GB18030 correctly
<p>Recently, I am studying <a href="https://en.wikipedia.org/wiki/GB_18030" rel="nofollow noreferrer">GB 18030</a>, and found that some characters cannot encoded/decoded correctly when they are mapped to the <em>private user area</em> (PUA). For example, according to the specification of GB 18030, this is <em>A6</em> d...
<python><java><character-encoding>
2023-05-12 03:21:56
0
6,975
chenzhongpu
76,232,802
14,399,602
What's wrong with using df.loc to assign new values?
<p>I do suppose the following two functions generate the same results:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def test_fn1(df: pd.DataFrame) -&gt; pd.DataFrame: df['b'] = df['b'].apply(lambda x: [x] if isinstance(x, dict) else x) return df def test_fn2(df: pd.DataFrame) -&gt; p...
<python><pandas><dataframe>
2023-05-12 02:42:04
1
880
Michael Chao
76,232,426
12,091,935
How to generate random variables from a probability density function/ probability mass function
<p>I am trying simulate random arrival times for cars that will park in a small parking lot. I want to use a random generator to create random parking events. I am not sure if numpy is the correct library for this job.</p> <p>Example: I use randint to generate the number of cars that will park on that day randint(3, hi...
<python><numpy><scipy><data-science><probability-density>
2023-05-12 00:32:50
1
435
Luis Enriquez-Contreras
76,232,399
8,838,303
Python: How to handle indirect references when inserting into PostgreSQL-tables?
<p>I have two .csv files named &quot;country.csv&quot;, which looks like this:</p> <pre><code>Country Code,Country Name,Country-ID US,United States,0 DE,Germany,1 AU,Australia,2 CZ,Czechia,3 CA,Canada,4 AR,Argentina,5 BR,Brazil,6 PT,Portugal,7 GB,United Kingdom,8 IT,Italy,9 GG,Guernsey,10 RO,Romania,11 </code></pre> <p...
<python><sql><database><postgresql>
2023-05-12 00:22:31
1
475
3nondatur
76,232,300
4,422,095
How to create DAGs with Spark?
<p>I'm new to Spark and I've realized that, for the pipeline I'm making, it would be much more convenient to have a DAG to represent the pipeline to improve monitoring, scheduling, etc.</p> <p>I connected Spark to my MySQL database and ran a few scripts with Spark dataframes using PyTorch and it worked great. I was abl...
<python><apache-spark><airflow><dagster>
2023-05-11 23:55:35
1
2,244
Stan Shunpike
76,232,295
8,243,535
python get a file by relative path
<p>I have been fumbling with this for a while, and I am thinking maybe there is no real way of doing this in python and the best approach is to always let the user figure out their absolute path and pass that in to my function and I can run it.</p> <p>this code works if I run it from the directory that the code <code>r...
<python><python-3.x><path>
2023-05-11 23:54:11
1
443
AugustusCaesar
76,232,123
3,486,773
How to replace string in column names of pyspark dataframe?
<p>I have a pyspark data frame that every column appends the table name ie: <code>Table.col1</code>, <code>Table.col2</code>...</p> <p>I would like to replace '<code>Table.'</code> with <code>''</code> (nothing) in every column in my dataframe.</p> <p>How do I do this? Everything I have found deals with doing this to...
<python><dataframe><apache-spark><pyspark><regex-replace>
2023-05-11 23:03:16
2
1,278
user3486773
76,232,118
1,120,370
CURL works for an Elasticsearch instance but Python interfaces do not: what am I missing?
<p>The devops team at my company has set up an Elasticsearch/Kibana server for me. Everything works fine through the Kibana interface (including Dev Tools), however, I am having trouble accessing the server via Python. I think it's an SSL issue, but I'm sure if my diagnosis is correct or what exactly I have to do to fi...
<python><elasticsearch><ssl-certificate>
2023-05-11 23:02:32
1
17,226
W.P. McNeill
76,232,039
5,379,479
ImportError from Great Expectations
<p>I've been using Great Expecations for a while and recently when I rebuilt a docker image I started to get this error. The image builds fine, but when I try to run code and import the package this error appears.</p> <pre><code> import great_expectations as ge File &quot;/opt/conda/envs/my_env/lib/python3.8/site...
<python><importerror><great-expectations>
2023-05-11 22:38:05
0
2,138
Jed
76,232,029
3,385,948
Pip could not find a version that satisfies the requirement, but it IS there in my private PyPI repository
<p>I know many questions have been asked along these lines, but I'm stumped.</p> <p>I've got a private PyPI repo at something like &quot;https://pypi.my_domain.com&quot; and it's been working well for a few years now. However, when I run the following command (which previously worked), it says it can't find the file, b...
<python><python-3.x><linux><pip>
2023-05-11 22:36:50
1
5,708
Sean McCarthy
76,231,996
7,025,033
Weighted element-wise between two arrays, numpy
<p>I want to perform</p> <pre><code>array_0 = np.array([ [1,2,3], [1,2,3], [1,2,3] ]) array_1 = np.array([ [1,2,3], [1,2,3], [1,2,3] ]) weights = np.array([ 1, 5 ]) result = array_0 * weights[0] + array_1 * weights[1] </code></pre> <p>Is there a <code>numpy</code> function that does just that?</p> <p>Obviously, I coul...
<python><numpy>
2023-05-11 22:27:53
0
1,230
Zoltan K.
76,231,987
4,487,457
Unable to install poetry in dataflow
<p>I am getting this error when running any poetry executables</p> <pre><code>Traceback (most recent call last): File &quot;/root/.local/bin/poetry&quot;, line 5, in &lt;module&gt; from poetry.console.application import main File &quot;/root/.local/share/pypoetry/venv/lib/python3.8/site-packages/poetry/console/...
<python><google-cloud-dataflow><python-poetry>
2023-05-11 22:25:20
1
2,360
Minh
76,231,984
11,065,874
In python, How do I create a abstract base singleton class that can only be initialized once?
<p>I have this piece of code</p> <pre><code>import abc class SingletonABCMeta(abc.ABCMeta): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(SingletonABCMeta, cls).__call__(*args, **kwargs) return cls._instances[cls] c...
<python><oop><singleton><abstract-class>
2023-05-11 22:25:05
1
2,555
Amin Ba