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,593,966
11,267,783
Colored background for gridspec subplots
<p>I wanted to have a background for each subplot of my figure. In my example, I want the left side to be red and the right side to be blue.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec fig = plt.figure() gs = GridSpec(1...
<python><matplotlib><matplotlib-gridspec>
2023-02-28 15:20:05
2
322
Mo0nKizz
75,593,873
5,817,109
Most Efficient Way to Fetch Large Amount of Data and Write It to Postgresql
<p>I am writing a Python Lambda function in AWS that does the following:</p> <ul> <li>fetch data from an external API using the requests library</li> <li>write the data to a postgresql table</li> </ul> <p>The catch: the returned json has only 2 fields that need to be written to the db, but the data is fairly large, and...
<python><postgresql>
2023-02-28 15:12:50
0
305
Moneer81
75,593,863
4,971,866
Continue to match next case after match?
<p>I have a match case that I want to execute even if a previous statement already matched.</p> <p>Here's what I currently have:</p> <pre class="lang-py prettyprint-override"><code>key: Literal['all', 'a', 'b'] = 'a' def do_a(): pass def do_b(): pass match key: case 'a': do_a() case 'b': ...
<python><switch-statement>
2023-02-28 15:12:02
2
2,687
CSSer
75,593,855
9,550,917
Constrain elements in a PyTorch tensor to be equal
<p>I have a PyTorch tensor and would like to <strong>impose equality constraints on its elements while optimizing</strong>. An example tensor of 2 * 9 is shown below, where the same color indicates the elements should always be equal.</p> <p><a href="https://i.sstatic.net/TVXUN.jpg" rel="nofollow noreferrer"><img src="...
<python><pytorch><tensor>
2023-02-28 15:11:14
3
341
Cheng
75,593,703
17,996,202
Allowing passing a function as an argument with an optional kwarg in Python
<p>I have a function that takes in another function as a parameter, and then runs it when a condition is met. However, some of the function passed in will have a keyword argument, and if it is present, I want it to be filled. This should also work with <code>threading</code>, so try/except is not an option here. Here i...
<python><multithreading>
2023-02-28 14:57:42
2
318
Yetiowner
75,593,629
7,668,453
How to load a tensorflow .yaml config file now that model_from_yaml is depricated?
<p>I am trying to load an object detection model from the official <a href="https://github.com/tensorflow/models/blob/master/official/vision/MODEL_GARDEN.md" rel="nofollow noreferrer">tensorflow model zoo</a>. I have one problem however. They all seem to use the old config + checkpoint system. The config files are save...
<python><tensorflow><parsing><keras><yaml>
2023-02-28 14:50:40
1
351
Torben Nordtorp
75,593,531
4,971,866
Python custom package: how to specify paths of yaml files within the package?
<p>I want to create a python package with below folder structure:</p> <pre><code>/package /package __init__.py /main __init__.py main.py ... /data __init__.py constants.py &lt;-- data.yml pyproject.toml ... </code></pre> <p>And inside <code>constants.py</code>, I d...
<python>
2023-02-28 14:41:54
1
2,687
CSSer
75,593,515
998,318
How to pass columns to select as a parameter?
<p>How do I pass as parameters the columns I want to select, especially when I want to select an unknown number of columns?</p> <p>I'm using psycopg2 in python</p> <p>This is my query:</p> <pre><code>columns_to_select = &quot;errors, requests&quot; sql = &quot;select bucket, %(metrics_to_select)s from metrics&quot; cur...
<python><postgresql><psycopg2>
2023-02-28 14:40:33
1
16,064
Moshe Shaham
75,593,477
8,681,249
gpytorch, regression on targets and classification of gradients to negative or positive
<p>i would like to set up the following model in GPYtorch: i have 4 inputs and i want to predict an output (regression) at the same time, i want to constrain the gradients of 3 inputs to be positive and of 1 input to be negative (with respect to the input)</p> <p>However, i dont know how to set this problem up with mul...
<python><gpytorch><gpy>
2023-02-28 14:35:48
0
413
john
75,593,462
1,239,123
Is there a practical way to determine whether two (Python) regular expressions are (likely to be) mutually exclusive?
<p>TL;DR: There's no generic solution, but is there something better than a simple (Python) string equality test for identical regexes?</p> <p>From reading this <a href="https://stackoverflow.com/questions/2967991/mutually-exclusive-regular-expressions">answer</a>, I gather that a generic solution is theoretically impo...
<python><regex>
2023-02-28 14:34:38
0
391
Joe
75,593,291
2,998,077
Python Numpy polyfit gets the same as Excel Linear for slope
<p>By the use of below, I get the slope of a list of number.</p> <p>It's referenced from the answer to this question, <a href="https://stackoverflow.com/questions/42920537/finding-increasing-trend-in-pandas">Finding increasing trend in Pandas</a>.</p> <pre><code>import numpy as np import pandas as pd def trendline(dat...
<python><excel><numpy><trend>
2023-02-28 14:20:48
1
9,496
Mark K
75,593,217
7,093,241
Outer scope variable not registered in contained functions
<p>I was coding this code snippet provided as a leetcode solution in Python but found that my variable <code>flag</code> isn't available.</p> <pre><code>public class Solution { boolean flag = false; public boolean checkInclusion(String s1, String s2) { permute(s1, s2, 0); return flag; }...
<python><java>
2023-02-28 14:14:13
0
1,794
heretoinfinity
75,593,113
14,269,252
Plot timeseries data against categorical column
<p>I plotted a huge dataset with x axis as date and y axis a categorical variable. I tried with the code as follows but the plot is unreadable.</p> <p>I want to show it in specific date, specific event (Code) happened based on different sources such as creating a timeline with lines, dates, and text.</p> <pre><code> ...
<python><dataframe><matplotlib><plot><plotly>
2023-02-28 14:03:28
2
450
user14269252
75,593,046
2,908,017
How to create a masked password box in a Python FMX GUI app?
<p>I'm making an app using <a href="https://github.com/Embarcadero/DelphiFMX4Python" rel="nofollow noreferrer">DelphiFMX GUI library for Python</a>. I need to have a component where I can enter a password and have that password masked. Sure I can use an <code>Edit</code> component, but then the password is in plain tex...
<python><user-interface><passwords><firemonkey>
2023-02-28 13:57:13
1
4,263
Shaun Roselt
75,592,945
5,506,400
Django: Model attribute looks for field works in view, but not in template
<p>Say I have a model:</p> <pre class="lang-py prettyprint-override"><code>from django.db import models class Foo(models.Model) fav_color = models.CharField(max_length=250, help_text=&quot;What's your fav color?&quot;) print(Foo.fav_color.field.help_text) # prints: What's your fav color? </code></pre> <p>Say I h...
<python><django><django-models><django-templates><django-model-field>
2023-02-28 13:47:51
2
2,550
run_the_race
75,592,867
2,908,017
How do I display tooltips in a Python FMX GUI app?
<p>I have created a window <code>Form</code> with a <code>Button</code> on it with the <a href="https://github.com/Embarcadero/DelphiFMX4Python" rel="nofollow noreferrer">DelphiFMX GUI library for Python</a>. I want to be able to add a hover tooltip to the button which explains what it does. Here's an example of a butt...
<python><user-interface><tooltip><firemonkey>
2023-02-28 13:41:10
1
4,263
Shaun Roselt
75,592,701
610,569
How to read directory that contains different parquets in parts?
<p>Given a parquet dataset with a job_id <code>abc</code>, saved in parts as such:</p> <pre><code>my_dataset/ part0.abc.parquet part1.abc.parquet part2.abc.parquet </code></pre> <p>It is possible to read the dataset with vaex or pandas:</p> <pre><code>import vaex df = vaex.open('my_dataset') import pandas as pd ...
<python><pandas><dataframe><parquet><partitioning>
2023-02-28 13:24:48
0
123,325
alvas
75,592,567
9,034,438
Django auth error on azure sql server, can't find object (table)
<p>I'm currently building a custom api auth path on django rest framework, the application is connected to azure sql-server. the connexion to the database works perfectly, the table and migrations have been applied to the database, the necessary table have been filled with the necessary column and data, Django Admin ta...
<python><sql-server><django><django-rest-framework>
2023-02-28 13:12:22
0
452
Dezz H
75,592,412
6,352,677
Inherited class methods with different signatures in python
<p>Let's consider the following code snippet:</p> <pre class="lang-py prettyprint-override"><code>class A: def foo(self) -&gt; None: raise NotImplementedError class B(A): def foo(self) -&gt; None: print(&quot;I'm B(A)&quot;) class C(A): def foo(self, x: int) -&gt; None: print(f&quo...
<python><class><abstract><mypy><python-typing>
2023-02-28 13:00:23
2
2,096
Colas
75,592,279
4,478,466
Is it possible to get object in Python from a string name?
<p>I'm trying to create dynamic filtering in SQLAlchemy with relationship entities. I have the following SQLAlchemy models:</p> <pre><code>Owner(Model): __tablename__ = 'Owners' Id = Column(Integer, primary_key=True, autoincrement=True) Name = Column(String(100)) Vehicle(Model): __tablename__ = 'Vehicl...
<python><sqlalchemy><flask-sqlalchemy>
2023-02-28 12:47:33
1
658
Denis Vitez
75,592,276
827,281
typing definitions without circular imports
<p>I have a package where I would like to</p> <ol> <li>use typing for code-hinting</li> <li>export some of the typing variables for users of the package to allow them to use typing as well, but simultaneously use them in the package it-self</li> </ol> <p>My main problem is that this will often result in circular import...
<python><python-typing>
2023-02-28 12:47:22
0
792
nickpapior
75,592,229
7,479,675
How to copy text with formatting using Python + Selenium?
<p>I'm using Python and Selenium and I need to copy text from a webpage to the OS Windows clipboard with formatting.</p> <p>For example, when you copy text from a webpage by pressing the Ctrl+C key combination, and then paste it into Microsoft Word using the Ctrl+V key combination, you can see that the text is copied w...
<python><selenium-webdriver>
2023-02-28 12:43:21
1
392
Oleksandr Myronchuk
75,592,052
2,776,885
Azure Synapse: Connect to Apache spark pool using a local Python script
<p>I am working with Azure Synapse. Here, I can create a notebook, select one of the Apache Spark Pools and execute the following code:</p> <pre><code>%%pyspark df = spark.sql(&quot;SELECT * FROM DataBaseName&quot;) df.show(10) </code></pre> <p>I have the use-case where I need to be able execute code from a local Pytho...
<python><azure><apache-spark><azure-synapse>
2023-02-28 12:26:01
0
4,040
The Dude
75,591,563
6,930,340
Mocking datetime.now using pytest-mock
<p>I have a function <code>func_to_mock</code> in module <code>module_to_mock.py</code>. My unit test is located in <code>test_func_to_mock.py</code></p> <p>I am trying to mock <code>datetime.datetime.now</code>, however, I am struggling. I get the error <code>TypeError: cannot set 'now' attribute of immutable type 'da...
<python><mocking><pytest><pytest-mock>
2023-02-28 11:40:18
1
5,167
Andi
75,591,496
20,920,790
Why autopep8 don't format on save?
<p>Autopep8 don't working at all.</p> <p>Here's my setting:</p> <pre><code>{ &quot;editor.defaultFormatter&quot;: &quot;ms-python.autopep8&quot;, &quot;editor.formatOnSave&quot;: true, &quot;editor.formatOnPaste&quot;: true, &quot;editor.formatOnType&quot;: true, &quot;autopep8.showNotifications&qu...
<python><visual-studio-code><autopep8>
2023-02-28 11:33:44
1
402
John Doe
75,591,413
12,320,370
Dictionary sometimes featuring with multiple keys
<p>I have a pandas data frame, and I would like to make a new column/s based on the dictionary values.</p> <p>Here is my df and dictionary:</p> <pre><code>data = ['One', 'Two', 'Three', 'Four'] df = pd.DataFrame(data, columns=['Count']) dictionary = {'One':'Red', 'Two':['Red', 'Blue'], 'Three':'Green','Four':['Green'...
<python><pandas><dictionary><lambda><key-value>
2023-02-28 11:26:49
3
333
Nairda123
75,591,403
12,013,353
Cannot open pickle file because of missing module which created it
<p>I've created a pickle file using a python file which uses a custom module I made, named module_v9.py . Now I've done some insignificant modifications and saved the module as module_v10.py, and when I try to open the pickle .p file I get the error saying &quot;no module named module_v9.py&quot;. How does it know the ...
<python><pickle>
2023-02-28 11:25:54
1
364
Sjotroll
75,591,315
11,162,983
ModuleNotFoundError: No module named 'tensorflow'--Pycharm
<p>I installed <code>pip install tensorflow==2.2.0</code> following <a href="https://towardsdatascience.com/installing-tensorflow-gpu-in-ubuntu-20-04-4ee3ca4cb75d" rel="nofollow noreferrer">this</a></p> <p>when I run these lines:</p> <pre><code>import tensorflow as tf tf.config.list_physical_devices(&quot;GPU&quot;) </...
<python><tensorflow><pycharm>
2023-02-28 11:18:59
0
987
Redhwan
75,591,314
3,482,266
Overwriting a method, during runtime, to raise an exception, on first pass only
<p>I want to rewrite, during runtime, the print method of the class below so that the first pass raises an exception, but the second time it runs normally. I <strong>cannot</strong> change the code of the <code>Test</code> class. Assume it's in a file I don't have access to, and I cannot mock (nor use a deepcopy, since...
<python>
2023-02-28 11:18:33
1
1,608
An old man in the sea.
75,591,296
15,759,796
'EntryPoints' object has no attribute 'get' during running pre-commit
<p>I am getting an error from importlib_metadata <code>AttributeError: 'EntryPoints' object has no attribute 'get'</code> during pre-commit install even though I have already installed <code>importlib_metadata==4.13.0</code> as suggested by below StackOverflow answer. What I am doing wrong here?</p> <p>This is my pre-c...
<python><django><pre-commit>
2023-02-28 11:16:54
1
477
raj-kapil
75,591,264
5,404,647
Calling module in a folder in docker
<p>I have the following project structure</p> <pre><code>. ├── app │   ├── main.py │   ├── foo.py │   └── bar.py ├── Dockerfile ├── input │   ├── data ├── output ├── README.md ├── requirements.txt └── rest_api.py </code></pre> <p>And my Dockerfile</p> <pre><code>FROM python:3.9-slim # install require OS packages # we ...
<python><docker>
2023-02-28 11:14:18
0
622
Norhther
75,591,225
11,546,773
Dask delayed data mismatch
<p>I wish to combine many dataframes into 1 dataframe with dask. However when I try to read those dataframes with dd.from_delayed(parts, meta=types) I get the error <code>Metadata mismatch found in 'from_delayed'</code>.</p> <p><strong>The full error:</strong></p> <pre><code>Metadata mismatch found in `from_delayed`. ...
<python><pandas><dask><dask-dataframe><dask-delayed>
2023-02-28 11:11:13
2
388
Sam
75,591,121
5,224,881
Updating label for specific version of a model in Model registry in Vertex AI
<p>I have a model with several different versions in model registry in Vertex AI: <a href="https://i.sstatic.net/pBn4T.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pBn4T.png" alt="enter image description here" /></a></p> <p>I want to change labels only for specific version programatically, using the p...
<python><google-cloud-vertex-ai>
2023-02-28 11:00:51
1
1,814
Matěj Račinský
75,591,115
9,479,925
How to work with .mdf extension files using python?
<p>I have a file with an extension .mdf in a path as below.</p> <pre><code>C:\A\B\sql\MP_000001.mdf; </code></pre> <p>I have installed pyodbc drivers as</p> <p><a href="https://i.sstatic.net/Sz3e4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Sz3e4.png" alt="enter image description here" /></a></p> <p>...
<python><sql-server><sqlalchemy><pyodbc>
2023-02-28 11:00:34
0
1,518
myamulla_ciencia
75,591,027
11,328,614
Annotating function argument accepting an instance of a class decorated with @define
<p>I'm using pythons <code>attrs</code> package to <code>@define</code> some classes containing some members with little logic for isolation purposes. However, when I run the following stripped down example:</p> <pre><code>from attrs import define @define class DefTest: attr1: int = 123 attr2: int = 456 at...
<python><python-typing><python-attrs>
2023-02-28 10:53:18
1
1,132
Wör Du Schnaffzig
75,590,749
19,328,707
Python / MySQL - Python INSERT INTO not inserting data
<p>I'm testing a combination with Python and MySQL. For this example I want to insert data into a MySQL Database from my Python code. The problem I'm facing now is that there is no actual data inserted into the table when I run the SQL command via Python, but it works when I run it via the MySQL Command Line Client.</p...
<python><mysql>
2023-02-28 10:28:03
1
326
LiiVion
75,590,659
4,233,642
Set figure options for Python with knitr
<p>I have a <code>knitr</code> document (either Rmd or Rnw) in which I want to generate some output with R and some with Python. However, I'm not able to change the figure options that are being used in Python.</p> <p>Specifically, if I use <code>knitr::opts_chunk$set(fig.width = ..., fig.height = ...)</code> <strong>b...
<python><r><matplotlib><r-markdown><knitr>
2023-02-28 10:19:47
1
18,083
Achim Zeileis
75,590,618
9,183,027
PyGithub: How to create a branch off the master and check out?
<p>How can I create a new branch off the master and check out the branch?</p> <p>The documentation at <a href="https://pygithub.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://pygithub.readthedocs.io/en/latest/</a> does not show how to do this.</p> <p>Thanks a lot!!</p>
<python><github><pygithub>
2023-02-28 10:16:15
1
1,585
Kay
75,590,605
17,507
How can I mock python's subprocess.check_putput when it makes several different calls
<p>I have a function which makes several subprocess.check_output calls to glean various bits of information. To unit test the code I want to mock the results of check_output depending on the args so I tried this:</p> <pre><code>@pytest.fixture def overlay_subprocess_calls(mocker): def my_outputs(*args, **kwargs): ...
<python><unit-testing><subprocess><python-mock>
2023-02-28 10:15:28
1
6,040
stsquad
75,590,589
423,839
Use key as byte array for DES3 in python
<p>I have a key and IV for DES3 as byte array (generated by C#):</p> <pre><code>var _algo = TripleDES.Create(); _algo.GenerateIV(); _algo.GenerateKey(); Console.WriteLine(string.Join(&quot;, &quot;, _algo.IV)); Console.WriteLine(string.Join(&quot;, &quot;, _algo.Key)); </code></pre> <p>I get these values for example:</...
<python><pycryptodome>
2023-02-28 10:14:02
1
8,482
Archeg
75,590,580
2,115,409
Using pandas in django, how to release memory?
<p>In a django project that focuses on data analysis, I use pandas to transform the data to a required format. The process is nice and easy, but the project quickly starts using 1GB of RAM.</p> <p>I know that Python doesn't really free up memory in this case (<a href="https://stackoverflow.com/a/39377643/2115409">https...
<python><django><pandas>
2023-02-28 10:13:24
1
2,704
Private
75,590,485
12,281,404
boost the speed of recusrive function
<p>The function is too slow, or infinite, i didnt get the result. how to fix that?</p> <pre class="lang-py prettyprint-override"><code>def x(a): return x(a - 1) + x(a - 2) + 42 if a &gt; 1 else a print(x(195)) </code></pre>
<python><python-3.x>
2023-02-28 10:05:16
2
487
Hahan't
75,590,442
18,756,733
How to change line width of a KDE plot in seaborn
<p>I can't change the tickness of the kde line in seaborn.</p> <p><a href="https://i.sstatic.net/ZHvUk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZHvUk.png" alt="enter image description here" /></a></p> <p>Here is the line of the code:</p> <pre><code>sns.kdeplot(ax=ax2,x=dots['Longitude'],y=dots['La...
<python><matplotlib><seaborn>
2023-02-28 10:00:52
1
426
beridzeg45
75,590,319
14,269,252
Interactive time series data over categorical feature
<p>I am new to python. I want to learn how make an interactive plot, this is a time series data that I want to show DATE over categorical column (CODE) by selecting Source and ID and also once for all data per ID. I also want to show the Code as a label over the bar, if this is bar plot or over a dot if this is dot plo...
<python><matplotlib><plot><plotly><bokeh>
2023-02-28 09:47:42
0
450
user14269252
75,590,316
1,788,771
How to hook up two viewsets to a single django url
<p>I hava a standard DRF viewset for a model which I hook up in my <code>urls.py</code> as such:</p> <pre class="lang-py prettyprint-override"><code>router = routers.SimpleRouter() router.register(&quot;&quot;, ResourceViewSet, basename=&quot;resource&quot;) urlpatterns = [ path( &quot;&quot;, incl...
<python><django><django-rest-framework>
2023-02-28 09:47:33
2
4,107
kaan_atakan
75,590,290
16,511,234
How to extract nested list data from a GeoJSON file in each key into dataframe
<p>I have a GeoJSON file with multiple keys. I want to extract the <code>name</code> and <code>coordinates</code>. I can access each of the elements, but I do not know how to loop over them to add them into a dataframe or another appropriate format maybe like dict. I want the name with the corresponding coordinates (la...
<python><json><parsing><geojson>
2023-02-28 09:45:29
1
351
Gobrel
75,590,242
19,238,204
Python PyGMT Plotting Data Points from CSV
<p>I try the tutorial here:</p> <p><a href="https://www.pygmt.org/latest/tutorials/basics/plot.html#sphx-glr-tutorials-basics-plot-py" rel="nofollow noreferrer">https://www.pygmt.org/latest/tutorials/basics/plot.html#sphx-glr-tutorials-basics-plot-py</a></p> <p>But, instead of getting their already have example of <cod...
<python><pygmt>
2023-02-28 09:40:16
2
435
Freya the Goddess
75,590,142
7,802,894
Decorators to configure Sentry error and trace rates?
<p>I am using Sentry and <a href="https://docs.sentry.io/platforms/python/" rel="nofollow noreferrer">sentry_sdk</a> to monitor errors and traces in my Python application. I want to configure the error and trace rates for different routes in my FastAPI API. To do this, I want to write two decorators called <code>sentry...
<python><fastapi><sentry>
2023-02-28 09:30:28
1
1,451
Yohann L.
75,590,032
282,328
How do I create a model instance using raw SQL in async SQLAlchemy?
<p>I have asyncio sqlalchemy code:</p> <pre><code>import asyncio from sqlalchemy.orm import sessionmaker, declarative_base from sqlalchemy import text, Column, Integer, String from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession async_engine = create_async_engine(f'mysql+aiomysql://root:example@127.0.0...
<python><python-3.x><sqlalchemy>
2023-02-28 09:20:04
2
8,574
Poma
75,590,029
2,304,074
Write Linux kernel in Python and compile with Cython
<p>Python compiles to C compatible bytecode with Cython. You rewrite Linux kernel source code files something.c in Python and compile with Cython. <br> Is it possible to compile Python files to bytecode using Cython without Python's memory management and then insert them into the linking process during the normal kerne...
<python><linux><kernel>
2023-02-28 09:19:49
0
337
user145453
75,589,788
9,811,964
Modify given regular expression for German mobile numbers
<p>I have a regular expression (regex) which matches German mobile numbers.</p> <p>The expression looks like this:</p> <p><code>[^\d]((\+49|0049|0)\s?(1|9)[1567]\d{1,2}([ \-/]*\d){7,8})(?!\d)</code></p> <p>It covers number formats like this and many more:</p> <pre><code>+4915368831169 +49 15207955279 +49 1739341284 </c...
<python><regex><match>
2023-02-28 08:56:24
1
1,519
PParker
75,589,667
4,865,723
How to realize one() like Python's any() and all()
<p>I like to use <code>any()</code> and <code>all()</code> in Python. But sometimes I need a <code>one()</code>.</p> <p>I want to know if <strong>only one</strong> value or condition in a list is <code>True</code>.</p> <p>Currently I do it with such a nested ugly <code>if</code>.</p> <pre><code># In real world there co...
<python>
2023-02-28 08:44:12
3
12,450
buhtz
75,589,568
14,617,762
Why am I getting a UnicodeDecodeError when installing manim-voiceover?
<p>I want to install manim-voiceover in a Windows environment, but a UnicodeDecode error occurs. Even though the PYTHONIOENCODING environment variable is set to utf-8, the UnicodeDecode error is repeated. Below is the error message.</p> <pre><code>C:\MyFirstFolder&gt;pip install manim-voiceover Collecting manim-voiceo...
<python><unicode><manim>
2023-02-28 08:31:51
1
563
Normalbut_Genuine
75,589,454
13,916,049
K-medoids clustering using precomputed matric
<p>I want to perform Gower clustering (on mixed binary and non-binary data) and then perform K-medoids clustering based on the distance matrix <code>dm</code>.</p> <pre><code>import gower from sklearn_extra.cluster import KMedoids dft = df.T X = dft.iloc[:-5,:] y = dft.iloc[-5:,:] mms = MinMaxScaler() mms.fit(X) data...
<python><pandas><machine-learning><scikit-learn>
2023-02-28 08:20:17
1
1,545
Anon
75,589,451
1,506,850
storing numbers efficiently in a json
<p>For some reason, I need to pass some large numerical vectors through a json.</p> <p>A trivial serialization leads to the following plain text:</p> <pre><code>[[0, 0.0003963873381352339], [1, 0.0008297143834970196], [2, 0.0007295088369519877], [3, 0.0007836414989179601], [4, 0.0007501355526877312], ... </code></pre>...
<javascript><python><json><serialization>
2023-02-28 08:20:05
0
5,397
00__00__00
75,589,400
5,192,123
pandas apply zscore on certain columns
<p>I have a pandas dataframe:</p> <pre><code> DATE value1 value2 value3 value4 0 2020-01-06 1432.474761 96.215891 1488.882633 96.015154 1 2020-01-07 1023.868069 97.645627 1054.100066 97.536370 2 2020-01-08 837.560896 98.281260 788.085172 98.445618 3 2020-01-09 1351.789373 96...
<python><pandas>
2023-02-28 08:13:58
2
2,633
MoneyBall
75,589,293
11,267,783
Issue with colorbar and imshow with gridspec
<p>I wanted to plot 2 imshow on a figure, but I only want the sub figure on the right to have the colorbar at the bottom of its plot.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec cm = 1/2.54 fig = plt.figure() fig.set_si...
<python><matplotlib><colorbar><imshow><matplotlib-gridspec>
2023-02-28 08:01:56
1
322
Mo0nKizz
75,589,224
3,811,401
Add zero vector row per group in pandas
<p>I want to create equal sized numpy (padded) array from pandas, ultimately to be given as input to keras model</p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 1.2, 2.2], [1, 3.2, 4.6], [2, 5.5, 6.6]], columns = ['id', 'X1', 'X2'] ) df &gt;&gt; id ...
<python><pandas><numpy><keras>
2023-02-28 07:54:52
1
4,820
Hardik Gupta
75,589,033
9,104,942
Schedule DAG to run once in a two months on last Sunday
<p>I need to run my Airflow DAG <strong>once in a two months on last Sunday at 3 am</strong>. For Example February's last Sunday, April's last Sunday, June's last Sunday and etc. (It skips January, March, May and etc) I was thinking of using this cron expression, but it does not work as I want.</p> <pre><code>0 3 * */2...
<python><cron><airflow>
2023-02-28 07:33:03
1
659
Abdusoli
75,588,985
10,305,444
how to `set_shape` of `Tensor` to a muli-input dataset
<p>I'm trying to create a Dataset with multiple input, which can be feed into a model with multiple inputs. It works fine when I'm working with single input, then I can easily set the shape using <code>set_shape</code> of that tensor inside my <code>Dataset.map</code> function. But now I don't know which shape I should...
<python><tensorflow><keras><tensorflow-datasets>
2023-02-28 07:27:41
0
4,689
Maifee Ul Asad
75,588,957
7,032,878
Managing scheduled functions with threading in Python script
<p>I have to set up a Python script which should be always up &amp; running and should be responsible to call several functions at determined schedules. I was considering the following approach, which leverages the libraries <code>pycron</code> and <code>threading</code>, assuming that <code>func1</code>, <code>func2</...
<python><python-multithreading>
2023-02-28 07:23:57
2
627
espogian
75,588,949
10,844,937
fastapi-RuntimeError: attached to a different loop
<p>I use <code>fastapi</code> to do async work with <code>BackgroundTasks</code> in a <code>post</code> request to run a heavy task. And I have a <code>get</code> request to check the status of the heavy task.</p> <pre><code>from fastapi import BackgroundTasks @router.post(&quot;/upload&quot;) async def upload(backgro...
<python><asynchronous><async-await><fastapi>
2023-02-28 07:21:54
1
783
haojie
75,588,757
809,440
Grammar file for key=value pairs
<p>I’m attempting to define a grammar file that parses the following:</p> <pre><code>Section0: Key0 = “Val0” Key1 = “Val1” … </code></pre> <p>My attempts thus far have just resulted in one long concatenation string with no real ability to split.</p> <pre><code>Section0: (var=ID ‘=‘ String)* </code></pre> <p>I’m l...
<python><textx>
2023-02-28 06:57:12
1
387
5k1zk17
75,588,670
14,351,788
Cannot test my flask app on AWS EC2 via postman
<p>Update: I update my code by adding &quot;host = '0.0.0.0'&quot;, but the question sill here</p> <p>I create a simple flask app on AWS CE2</p> <pre><code>import json from sutime import SUTime from flask import Flask app = Flask(__name__) @app.route(&quot;/test/&quot;, methods = [&quot;POST&quot;]) def time_word_reg...
<python><amazon-web-services><flask><amazon-ec2>
2023-02-28 06:47:16
1
437
Carlos
75,588,271
8,550,160
Unable to determine why eigenvalue results are different between Julia and Python for specific case
<p>I'm using Julia to do some linear algebra calculations but it gave me negative eigenvalues when I know the matrix is positive definite.</p> <p>I'm fairly new to Julia so is there some reason the Julia code below would have such different behavior than the corresponding python code? Could it be the <code>abs</code> ...
<python><numpy><julia><eigenvalue>
2023-02-28 05:47:23
1
703
jman
75,588,250
4,237,198
What are the downsides to relying purely on pyproject.toml?
<p>Say you have a Python program that you can successfully package using only <code>pyproject.toml</code>. What are the downsides? Why use <code>setup.py</code> or <code>setup.cfg</code> in this case?</p>
<python><setuptools><setup.py><python-packaging><pyproject.toml>
2023-02-28 05:43:21
1
367
Thermodynamix
75,588,227
14,546,482
Connect to many databases and run sql query using pyodbc - multi threading?
<p>I'm trying to connect to many Pervasive databases using pyodbc and then perform a sql query on each database. The current problem Im facing is that this script takes too long to run because its trying to connect and run a sql query 1 at a time. I thought multi threading might be a good solution for this. Im very new...
<python><pandas><multithreading><pyodbc>
2023-02-28 05:39:51
1
343
aero8991
75,588,158
1,905,276
How to insert a line at a particular offset in a file using Python
<pre class="lang-py prettyprint-override"><code>file_name = '/Users/xxxx/PycharmProjects/pythonProject/HWDataList.txt' for line in fileinput.FileInput(file_name, inplace=1): if 'nail' in line: line = line.rstrip() line = line.replace(line, line+'\n'+'hammer'+'\n') print(line) </code>...
<python>
2023-02-28 05:25:26
4
411
Santhosh Kumar
75,587,804
3,811,401
Keras Compute loss between 2 Ragged Tensors
<p>I have 2 ragged tensors defined as follows</p> <pre><code>import tensorflow as tf # Tensor 1 pred_score = tf.ragged.constant([ [[-0.51760715], [-0.18927467], [-0.10698503]], [[-0.58782816], [-0.13076714], [-0.04999146], [-0.1772059], [-0.14299354]] ]) pred_score = tf.squeeze(pred_score, axis=-1) pred_score_...
<python><tensorflow><keras><tensorflow2.0><tf.keras>
2023-02-28 04:09:58
1
4,820
Hardik Gupta
75,587,763
2,056,201
What does Mat[0,0,i,2] function do in Python with OpenCV
<p>I am trying to understand this code and to convert it to Java</p> <p>Code is from this tutorial, full code snippet shown below <a href="https://pyimagesearch.com/2017/09/11/object-detection-with-deep-learning-and-opencv/" rel="nofollow noreferrer">https://pyimagesearch.com/2017/09/11/object-detection-with-deep-learn...
<python><java><android><opencv>
2023-02-28 04:01:26
1
3,706
Mich
75,587,700
12,870,750
Vispy and PyQt5 fullscreen resize event problem
<p>I have a line viewer made in <code>PyQt5</code>; I managed to make a <code>vispy</code> scene as the viewport for the <code>QGrapichsView</code>. I have made it zoom and pan capable.</p> <p><strong>Problem</strong></p> <p>The viewer works very fast but the problem comes when I try to manually (push the fullscreen b...
<python><pyqt5><vispy>
2023-02-28 03:48:30
1
640
MBV
75,587,622
13,638,243
Accumulating lists in Polars
<p>Say I have a <code>pl.DataFrame()</code> with 2 columns: The first column contains <code>Date</code>, the second <code>List[str]</code>.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame([ pl.Series('Date', [2000, 2001, 2002]), pl.Series('Ids', [ ['a'], ...
<python><python-polars>
2023-02-28 03:30:40
2
363
Neotenic Primate
75,587,611
6,063,706
Scale gradient for specific parameter in pytorch?
<p>Suppose I have some neural network with parameters A,B,C. Whenever a gradient update is applied to C, I want it to be scaled differently than what the normal gradient would be (i.e. every gradient update is 2x or 1/3x what the calculated gradient is). I want the gradients applied to all other parameters to stay the ...
<python><deep-learning><pytorch><neural-network>
2023-02-28 03:28:54
1
1,035
Tob
75,587,442
134,044
Validate Pydantic dynamic float enum by name with OpenAPI description
<p>Following on from <a href="https://stackoverflow.com/questions/67911340/pydantic-enum-load-name-instead-of-value">this question</a> and <a href="https://github.com/pydantic/pydantic/discussions/2980" rel="nofollow noreferrer">this discussion</a> I am now trying to create a Pydantic <code>BaseModel</code> that has a ...
<python><dynamic><enums><openapi><pydantic>
2023-02-28 02:49:57
3
4,109
NeilG
75,587,316
3,819,007
Subtract values of single row polars frame from multiple row polars frame
<p>Lets say I have a polars dataframe like this in python</p> <pre class="lang-py prettyprint-override"><code> newdata = pl.DataFrame({ 'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 11, 12], 'D': [13, 14, 15, 16] }) </code></pre> <p>And I want to subtract from every value in ...
<python><python-polars>
2023-02-28 02:21:59
1
3,325
visibleman
75,587,171
3,821,009
Pandas set values from another DataFrame based on dates
<p>This:</p> <pre><code>periods = 5 * 3 df1 = pandas.DataFrame(dict( v1=numpy.arange(2, 2 + periods) * 2, v2=numpy.arange(3, 3 +periods) * 3), ...
<python><pandas><dataframe>
2023-02-28 01:41:54
1
4,641
levant pied
75,587,139
796,634
Get Jupyter notebook URL without using IPython.notebook.kernel.execute
<p>I'm attempting to access the current URL of a Jupyter notebook including parameters, however I'm operating in a custom environment that has disabled direct access to IPython from javascript so I can't use IPython.notebook.kernel.execute. AFAIK all other communication works fine, input widgets still work etc.</p> <p...
<python><url><jupyter-notebook>
2023-02-28 01:35:12
0
2,194
Geordie
75,587,046
1,418,326
Tensorfow 2.11.0: Cannot dlopen some GPU libraries. Skipping registering GPU devices
<p>I am following the instruction here:<a href="https://www.tensorflow.org/install/pip" rel="nofollow noreferrer">https://www.tensorflow.org/install/pip</a> I was able to follow the instruction step by step without any problems, but TF doesn't detect GPUs.</p> <p>tensorflow2.11.0 and python: 3.7.10</p> <p><a href="http...
<python><tensorflow><gpu>
2023-02-28 01:14:41
1
1,707
topcan5
75,586,997
4,402,572
How can I enforce black's `--preview` option when invoking black with pre-commit?
<p>I just found out that <code>black</code>'s default behavior for long logfile messages does not enforce a maximum line length. I have verified that I can enforce max line length if I invoke black manually (v 23.1.0, in a Python 3.9.9 venv). Now I'd like to make sure that enforcement happens with every commit, using p...
<python><pre-commit><pre-commit.com><python-black>
2023-02-28 01:03:26
1
1,264
Jeff Wright
75,586,994
9,616,557
Pandas - How to enforce two digits after decimal point using regex?
<p>I have a <code>dataframe</code> which has some values like this:</p> <pre><code>propvalue 3000.2343 4000.4334554 </code></pre> <p>That column is a string (str) type.</p> <p>How can I leave only two decimals after point?</p> <p>Desired:</p> <pre><code>propvalue 3000.23 4000.43 </code></pre> <p>I've researched and s...
<python><pandas>
2023-02-28 01:03:03
2
767
Astora
75,586,975
5,718,551
Change format of all logger instances
<p>I need to standardize logging format for multiple Python scripts.</p> <p>I've written a custom handler; a handler is required rather than a custom format string, since I need to perform additional processing.</p> <pre class="lang-py prettyprint-override"><code>import logging class CustomHandler(logging.Handler): ...
<python><python-logging>
2023-02-28 00:58:24
0
944
Inigo Selwood
75,586,935
5,530,152
Can functions in python reference previously logged events?
<p>Is there a way for python functions to reference previously logged events that occur within their scope or another specific function's scope?</p> <p><strong>For example:</strong></p> <p>Within a larger program, <code>process_files(files)</code> raises and handles an <code>OSError</code> as <code>logging.error(f'foo ...
<python><logging><python-logging>
2023-02-28 00:49:53
0
933
Aaron Ciuffo
75,586,757
12,043,946
Spyder issues without anaconda distribution "distfit" package. Cannot change PATH
<p>I am using python 3.11. I was setting up a remote development enviornment and the anaconda distribution was just messing everything up. In order to get it to work I had to uninstall the conda distribution. Now that I have gotten the remote enviornment to work my computer is messed up. I cannot write python comma...
<python><scipy><spyder><scipy.stats>
2023-02-28 00:11:27
1
392
d3hero23
75,586,723
6,552,836
Scipy Optimize - Singular Matrix issue when creating constraints in a loop
<p>I'm trying to optimize a 20x5 matrix to maximize a return value y. There are main type of constraints that I need to include:</p> <p>Total sum of all the elements must between a min and max range</p> <p>However, I keep getting this singular matrix error as below when I try to create the constraints in a loop.</p> <p...
<python><optimization><scipy><scipy-optimize>
2023-02-28 00:04:58
1
439
star_it8293
75,586,690
5,568,265
Is it possible to create "parameter decorators" (like TypeScript) in Python?
<p>TypeScript has a feature known as <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators" rel="nofollow noreferrer">parameter decorators</a> — literally a decorator that you can apply to a parameter of a function or method:</p> <pre><code>class BugReport { // ... print(@requi...
<python><decorator>
2023-02-27 23:56:52
2
1,142
todofixthis
75,586,687
2,369,000
Multi-line title alignment using plotly
<p>Is it possible to make the title have pixel-perfect alignment with the top of the image when using line breaks in the title? Normally you can do this with yanchor='top' and y=1, but line breaks in the title appear to break this.</p> <p>Code:</p> <pre><code>layout = go.Layout( height=500, width=500, margin=di...
<python><plotly>
2023-02-27 23:56:38
0
461
HAL
75,586,605
10,886,849
PyQT5 - how to use QWidget, QScrollArea and QBrush all together
<p><strong>I am trying to:</strong></p> <ol> <li>Display an image which is bigger than the window size;</li> <li>Make the window scrollable, so I can roll through the whole image;</li> <li>Draw over the image;</li> </ol> <p><strong>Problem is:</strong></p> <ol> <li>As soon as I make the window scrollable, I can't see t...
<python><pyqt><pyqt5>
2023-02-27 23:41:55
2
990
Julio S.
75,586,471
3,821,009
Pandas groupby transform yields Series instead of DataFrame on empty DataFrames
<p>Running this:</p> <pre><code>for periods in [8, 4, 0]: print(f'--- periods {periods}') df = pandas.DataFrame(dict( ...
<python><pandas><dataframe>
2023-02-27 23:17:43
1
4,641
levant pied
75,586,451
15,781,591
Finding all possible solution pairs to an algebra problem with constraints in python
<p>I am trying to use python to create list of all pairs of numbers between 2 and 75 that average to 54, where each value in each solution pair can go up to 6 decimal places. And so I want to have a list of all of these solution pairs.</p> <p>I have tried using <code>solve()</code> from <code>SymPy</code> to solve this...
<python><sympy><algebra>
2023-02-27 23:14:03
1
641
LostinSpatialAnalysis
75,586,277
6,471,140
Sagemaker training jobs metrics not shown in monitoring nor cloudwatch/no widget on this dashboard
<p>Using sagemaker, from previous experience and the official documentation we know it is possible to create plots and visualizations for metrics during training jobs(ex: accuracy, error, etc) however now we cannot see any metrics, this applies to both &quot;Monitoring&quot; tab for the sagemaker jobs and for Cloudwatc...
<python><amazon-web-services><machine-learning><amazon-cloudwatch><amazon-sagemaker>
2023-02-27 22:46:06
0
3,554
Luis Leal
75,586,210
4,487,457
Dataflow Flex Template: module not found
<p>I'm trying to use Dataflow to do some parallel operations in <code>pandas</code>. I understand that <code>pandas</code> is installed on the workers <a href="https://cloud.google.com/dataflow/docs/concepts/sdk-worker-dependencies#sdk-for-python_1" rel="nofollow noreferrer">nodes</a>. But every time I submit a Flex te...
<python><google-cloud-platform><google-cloud-dataflow><apache-beam>
2023-02-27 22:34:59
1
2,360
Minh
75,586,132
16,421,247
numpy selecting multiple columns excluding certain ones - concise way
<p>I have a short question about indexing in numpy. I'm trying to select subset of columns of a 2D array. For example, if I wanted columns other than 3, 6 and 9, then I would plug in a list of indicies excluding those positions:</p> <pre><code>x = np.arange(20).reshape(2,10) x[:, [i for i in range(len(x[0])) if i not i...
<python><numpy>
2023-02-27 22:22:46
1
1,058
nightstand
75,586,082
3,449,093
Ignoring None as one of the values
<p>I need to plot two sets of data on the same chart with error bars. But I don't have one of the measurements.</p> <pre><code>days = [0.43, 1.72, 3.97, 4.81, 9.54, 10.9] magB = [None, 3.36, 3.9, 4.27, 5.47, 5.59] magV = [10.8, 2.88, 3.59, 3.89, 5.57, 5.82] fix, ax = plt.subplots() plt.xlabel(&quot;days&quot;) plt.yla...
<python><matplotlib>
2023-02-27 22:16:47
2
1,399
Malvinka
75,585,994
17,274,113
open cv cv2.imread a grayscale image pixel values
<p>I am attempting to load a grayscale image using <code>cv2.imread</code> for further blob extraction. To start I have an image (as seen below) for which black pixels have values (typically between 0 and 1) and white pixels have value of 0.</p> <p><a href="https://i.sstatic.net/vtIrh.png" rel="nofollow noreferrer"><im...
<python><opencv><blob><arcgis><resampling>
2023-02-27 22:05:38
1
429
Max Duso
75,585,988
1,788,771
Django filter for not null
<p>I have a filter defined as such:</p> <pre class="lang-py prettyprint-override"><code>class MessageFilterSet(filters.FilterSet): seen = filters.BooleanFilter(field_name=&quot;seen_at&quot;, lookup_expr=&quot;isnull&quot;) </code></pre> <p>And it sort of works. But it's the wrong way around, passing seen=True will...
<python><django><django-filter>
2023-02-27 22:04:40
1
4,107
kaan_atakan
75,585,933
3,713,236
Unable to export Jupyter notebook to Python Script in Azure ML Studio
<p>I am stuck on <a href="https://microsoftlearning.github.io/mslearn-azure-ml/Instructions/08-Script-command-job.html" rel="nofollow noreferrer">step 5 in this Azure tutorial</a>: <a href="https://i.sstatic.net/2F764.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2F764.png" alt="enter image description...
<python><azure><jupyter-notebook>
2023-02-27 21:56:14
1
9,075
Katsu
75,585,768
2,908,017
How can I prevent a Python FMX GUI Form from being resized?
<p>I have a window <code>Form</code> that is created with the <a href="https://github.com/Embarcadero/DelphiFMX4Python" rel="nofollow noreferrer">DelphiFMX GUI library for Python</a>. My code and Form look like this:</p> <pre><code>from delphifmx import * class frmMain(Form): def __init__(self, owner): sel...
<python><user-interface><resize><firemonkey>
2023-02-27 21:32:04
1
4,263
Shaun Roselt
75,585,728
17,517,315
Parse float from string in regex python with conversion unit
<p>I am trying to convert all cases below as a float number</p> <p>See below:</p> <pre><code> ['$1.5 million', '$2.6 million', '$2.28 million', '$600,000', '$950,000', '$858,000', '$788,000', '$1.35 million', '$2.125 million', '$1.5 million', '$1.5 million', '$2.2 million', '$1.8 million', '$3 million', '...
<python><python-3.x><regex><python-re>
2023-02-27 21:27:14
1
391
matt.aurelio
75,585,665
11,500,371
How can I rename columns based on matching data in another dataframe in Pandas?
<p>I have two dataframes where the labeling of products does not always match:</p> <pre><code>import pandas as pd df1 = pd.DataFrame(data={'Product 1':['Shoes'],'Product 1 Price':[25],'Product 2':['Shirts'],'Product 2 Price':[50],'Product 3':['Pants'],'Product 3 Price':24}) df2 = pd.DataFrame(data={'Product 1':['Shirt...
<python><pandas><dataframe>
2023-02-27 21:18:49
2
337
Sean R
75,585,657
2,908,017
How to specify where a Python FMX GUI Form opens?
<p>I'm creating a <code>Form</code> using <a href="https://github.com/Embarcadero/DelphiFMX4Python" rel="nofollow noreferrer">DelphiFMX GUI library for Python</a> and I would like to choose a specific location where the Form should open. Here's the code that I use to create my Form:</p> <pre><code>from delphifmx import...
<python><user-interface><firemonkey><centering>
2023-02-27 21:17:26
1
4,263
Shaun Roselt