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,464,017
244,297
Finding the longest interval with a decrease in value faster than quadratic time
<p>I have a list of values for some metric, e.g.:</p> <pre><code># 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 [50, 52, 58, 54, 57, 51, 55, 60, 62, 65, 68, 72, 62, 61, 59, 63, 72] </code></pre> <p>I need to find the longest interval over which the value has decreased. For the above list such inter...
<python><algorithm><performance><intervals>
2023-02-15 18:27:19
1
151,764
Eugene Yarmash
75,463,993
5,962,981
What does async actually do in FastAPI?
<p>I have two scripts:</p> <pre><code>from fastapi import FastAPI import asyncio app = FastAPI() @app.get(&quot;/&quot;) async def root(): a = await asyncio.sleep(10) return {'Hello': 'World',} </code></pre> <p>And second one:</p> <pre><code>from fastapi import FastAPI import time app = FastAPI() @app.get...
<python><asynchronous><async-await><python-asyncio><fastapi>
2023-02-15 18:25:05
2
923
filtertips
75,463,912
2,635,863
normalize Euclidean distance - python
<pre><code>def euclidean_distance(n): L = np.linalg.cholesky( [[1.0, 0.60], [0.60, 1.0]]) uncorrelated = np.random.standard_normal((2, n)) correlated = np.dot(L, uncorrelated) A = correlated[0] B = correlated[1] v = np.linalg.norm(A-B) return v v50 = euclidean_di...
<python><numpy><euclidean-distance>
2023-02-15 18:15:53
1
10,765
HappyPy
75,463,740
1,208,071
Python class in Google Colab
<p>I am trying to add a new Python class within an existing Collab project which is already working with a similar structure using classes within files within a sub file director (filedir). I have placed the new class, NewClassMethod, within a new_class.py file and put it into a directory. However, I am getting an erro...
<python><google-colaboratory>
2023-02-15 17:58:57
0
395
geo derek
75,463,734
3,517,025
sqlalchemy engine/connection vs psycopg2 connection
<p>We currently use a <code>get_connection</code> functionality for our postgres via</p> <pre class="lang-py prettyprint-override"><code>import psycopg2 def get_db_connection(conn_str: str = '') -&gt; psycopg2._psycopg.connection: conn_str = conn_str if conn_str else os.environ.get(PG_CONNECTION_STRING) retur...
<python><pandas><sqlalchemy>
2023-02-15 17:58:19
0
5,409
Joey Baruch
75,463,704
3,482,266
os.getenv or os.environ don't reach variables in .env file
<p>In my directory, I have a .env file with:</p> <pre><code>HOST=&quot;url_to_host&quot; </code></pre> <p>I also have my <code>script.py</code>, where:</p> <pre><code>import os os.environ[&quot;HOST&quot;] </code></pre> <p>If I run the script in Vscode debug mode, everything works. However, in normal mode, I get a key ...
<python><python-os>
2023-02-15 17:55:40
2
1,608
An old man in the sea.
75,463,690
7,128,910
Numba JIT on static method works on one computer but throws an error on another
<p>I have a static method that I want to speed up with Numba:</p> <pre><code>@nb.njit def numba_loop_choice(population, weights, k): wc = np.cumsum(weights) m = wc[-1] sample = np.empty(k, population.dtype) sample_idx = np.full(k, -1, np.int32) i = 0 while i &lt; k: r = m * np.random.ran...
<python><numba>
2023-02-15 17:54:09
0
1,261
Nik
75,463,366
4,207,793
Validate relative path by the wildcard in Python
<p>I have a condition where I need to compare the relative name/path of the file (<code>string</code>) with another path that has wildcards:</p> <pre class="lang-none prettyprint-override"><code>files list: aaa/file1.txt bbb/ccc/file2.txt accepted files by the wildcard: aaa/* bbb/**/* </code></pre> <p>...
<python><regex><path>
2023-02-15 17:22:48
1
1,164
IgorZ
75,463,364
6,556,938
ModuleNotFoundError: No module named 'pyathena' when running AWS Glue Job
<p>Despite setting the parameter for my Python AWS Glue Job like this:</p> <pre><code>--additional-python-modules pyathena </code></pre> <p>I still get the following error when I try and run the job:</p> <pre><code>ModuleNotFoundError: No module named 'pyathena' </code></pre> <p>I have also tried the following parame...
<python><amazon-web-services><etl><aws-glue><pyathena>
2023-02-15 17:22:39
1
1,215
ChrisDanger
75,463,339
7,644,323
Is there a way to filter multiple related fields in a single filter for a table in python Dash?
<p>In Microsoft PowerBI I can filter multiple related fields in a single slicer. You do so by building what's called a <a href="https://learn.microsoft.com/en-us/power-bi/create-reports/power-bi-slicer-hierarchy-multiple-fields" rel="nofollow noreferrer">hierarchy slicer</a>. This slicer can then be used to filter a ta...
<python><plotly-dash>
2023-02-15 17:20:09
1
1,037
dshefman
75,463,288
9,748,823
Match value where string does not contain a certain word
<p>I am trying to match a word in a string only if a certain word occurs within the first 10 characters of the string.<br /> This is my approach:</p> <pre><code>import re string_array = [&quot;foo bar\nbaz qux&quot;, &quot;baz qux foo bar&quot;, &quot;baz qux&quot;] for string in string_array: a = re.search(&quot;...
<python><regex>
2023-02-15 17:15:50
2
381
Blob
75,463,161
12,297,666
Pivoting a pandas dataframe
<p>I have the following dataframe:</p> <pre><code> ID Datetime Y 0 1000 00:29:59 0.117 1 1000 00:59:59 0.050 2 1000 01:29:59 0.025 3 1000 01:59:59 0.025 4 1000 02:29:59 0.049 ... ... ...
<python><pandas>
2023-02-15 17:04:09
2
679
Murilo
75,463,027
6,664,990
Python Regex to find certain SQL statement from a SQL script (multiple SQL statements) and transform respecting the comments in input SQL
<p>I'm trying to find certain type of SQL statements from a list of SQLs for examples CTAS and then do some tranformation.</p> <p>Input :</p> <pre><code> sqltexts = &quot;&quot;&quot; --drop table test_schema.test_table; /* create table table2 as select * from table3 ; */ create table table4 as (select * f...
<python><sql><regex>
2023-02-15 16:52:14
0
908
Leo
75,462,898
12,458,212
Using an NLP vectorized output for subsequent model?
<p>I use SpaCy to output a vectorized array of my text field. I'm having issues plugging this output into my random forest and could use some guidance. I label encoded other fields so my pandas dataframe looks something like:</p> <pre><code>import pandas as pd import numpy as np from sklearn.ensemble import RandomFores...
<python><machine-learning><nlp>
2023-02-15 16:42:55
1
695
chicagobeast12
75,462,859
16,935,119
Find NA in all columns in pandas through loop and eliminate rows with NA
<p>This is a the dataframe in pandas I have</p> <pre><code>dict = {'First Score':[100, 90, np.nan, 95], 'Second Score': [30, 45, 56, np.nan], 'Third Score':[np.nan, 40, 80, 98]} # creating a dataframe from dictionary df = pd.DataFrame(dict) </code></pre> <p>I am trying to eliminate rows with NA values...
<python><pandas>
2023-02-15 16:39:43
1
1,005
manu p
75,462,745
12,396,154
Do I need to close pyodbc sql server connection when reading the data into the Pandas Dataframe?
<p>I am confused how to use context manager with <code>pyodbc</code> connection. As far as I know, it is usually necessary to close the database connection and using context manager is a good practice for that (for pyodbc, I saw some examples which closes the cursor only). Long story short, I am creating a python app w...
<python><sql-server><pandas><pyodbc>
2023-02-15 16:30:47
1
353
Nili
75,462,685
5,775,358
Polars columns subtract order does not matter (apparently)
<p>I would like to use <code>polars</code>, but when I try to subtract a 1x3 numpy array from three columns of the DataFrame. The problem is that is does not matter in which order the subtraction is applied:</p> <pre><code>import numpy as np import polars as pl # create polars dataframe: data = np.array([[1, 2, 3], [4...
<python><numpy><operation><python-polars>
2023-02-15 16:25:37
1
2,406
3dSpatialUser
75,462,630
20,898,396
Why is the difference between id(2) and id(1) equal to 32?
<pre><code>&gt;&gt;&gt; a = 1 &gt;&gt;&gt; b = 2 &gt;&gt;&gt; id(a), id(b), id(b) - id(a) (1814458401008, 1814458401040, 32) </code></pre> <p>Is the memory address returned by <code>id</code> in bits or in bytes? Per <a href="https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong" rel="nofollow noreferrer">the docs<...
<python><python-internals>
2023-02-15 16:21:00
1
927
BPDev
75,462,567
6,696,730
Airflow PyTest DagBag Import Error from local module
<p>I have a directory structure as follows for my DAGs:</p> <pre><code>. β”œβ”€β”€ __init__.py β”œβ”€β”€ _base.py β”œβ”€β”€ dag1.py β”œβ”€β”€ dag2.py β”œβ”€β”€ dag3.py β”œβ”€β”€ ... </code></pre> <p>When I run PyTest to fill my DagBag, I get the following error for each DAG file</p> <pre><code>ERROR - Failed to import: dags/dag2.py Traceback (most recent...
<python><airflow><pytest>
2023-02-15 16:15:49
1
713
K Pekosh
75,462,560
3,595,907
Unexpected behavior using if .. or .. Python
<p>I'm reading in a list of samples from a text file and in that list every now and then there is a &quot;channel n&quot; checkpoint. The file is terminated with the text <code>eof</code>. The code that works until it hits the <code>eof</code> which it obviously cant cast as a <code>float</code></p> <pre><code>log = op...
<python><if-statement>
2023-02-15 16:15:04
2
3,687
DrBwts
75,462,376
5,112,032
Convert custom string date to date
<p>Is there a way to convert a string date that is stored in some non-traditional custom manner into a date using <code>datetime</code> (or something equivalent)? The dates I am dealing with are S3 partitions that look like this:</p> <p><code>year=2023/month=2/dayofmonth=3</code></p> <p>I can accomplish this with sever...
<python><date>
2023-02-15 15:59:56
2
2,522
eljusticiero67
75,462,354
6,290,211
Converting string column to date time when strings slightly differ in format due to GMT specification
<p>I have a <code>df</code> with a columns that contains, in two different string format, several timestamps.</p> <p>These are the two formats:</p> <pre><code>fmt = &quot;%a %b %d %H:%M:%S %Z%z %Y&quot; fmt_2 = &quot;%a %b %d %H:%M:%S %Z %Y&quot; </code></pre> <p><a href="https://codereview.stackexchange.com/questions/...
<python><pandas><datetime>
2023-02-15 15:58:32
0
389
Andrea Ciufo
75,462,344
5,962,321
Make ``pip install -e .`` build cython extensions with pyproject.toml
<p>With the move to the new <code>pyproject.toml</code> system, I was wondering whether there was a way to install packages in editable mode while compiling extensions (which <code>pip install -e .</code> does not do).</p> <p>So I want pip to:</p> <ul> <li>run the <code>build_ext</code> I configured for Cython and gene...
<python><pip><cython><pyproject.toml>
2023-02-15 15:57:51
1
2,011
Silmathoron
75,462,324
14,179,793
Python Peewee EXISTS Subquery not working as expected
<p>I am using the peewee ORM for a python application and I am trying to write code to fetch batches of records from a SQLite database. I have a subquery that seems to work by itself but when added to an update query the <code>fn.EXISTS(sub_query)</code> seems to have no effect as every record in the database is update...
<python><sqlite><peewee>
2023-02-15 15:55:57
1
898
Cogito Ergo Sum
75,462,164
8,182,504
Vedo 3D-Gyroid structures STL export
<p>I need to generate a double 3D gyroid structure. For this, I'm using <a href="https://vedo.embl.es/" rel="nofollow noreferrer"><code>vedo</code></a></p> <pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt from scipy.constants import speed_of_light from vedo import * import numpy as n...
<python><vedo>
2023-02-15 15:41:50
1
1,324
agentsmith
75,462,103
20,612,566
Extract text with multiple regex patterns in Python
<p>I have a list with address information</p> <p>The placement of words in the list can be random.</p> <pre><code>address = [' South region', ' district KTS', ' 4', ' app. 106', ' ent. 1', ' st. 15'] </code></pre> <p>I want to extract each item of a list in a new string.</p> <pre><code>r = re.compile(&quot;.region&quo...
<python><regex>
2023-02-15 15:37:26
1
391
Iren E
75,461,848
8,899,386
Removing highly correlated columns of a huge Pyspark dataframe with missing values
<p>I have a huge dataframe with 6 million rows and 2k columns. I want to remove the highly correlated columns, and many of the columns are super sparse (90%+ missing values). Unfortunately, the Pyspark Correlation does not handle missing values, AFAIK. That's why I had to loop over columns and compute the correlation.<...
<python><dataframe><pyspark><bigdata><correlation>
2023-02-15 15:14:17
1
4,890
Hadij
75,461,623
10,057,842
Unable to use chromedriver on linux server [Exec format error]
<p>I have a raspberry-pi running linux-server as platform. Therefore there is no GUI and I execute all my tasks through terminal by SSH-ing into the Pi. Platform details:</p> <pre><code>uname -a &gt;&gt; Linux ubuntu 5.4.0-1080-raspi #91-Ubuntu SMP PREEMPT Thu Jan 19 09:35:03 UTC 2023 aarch64 aarch64 aarch64 GNU/Linux...
<python><linux><selenium-webdriver><raspberry-pi><selenium-chromedriver>
2023-02-15 14:56:22
1
398
Aakash Dusane
75,461,413
19,238,204
Create Graphs for the outcome of a Fair Coin Tossed 3 times with JULIA or Python
<p>I am creating this code with JULIA and GraphRecipes. But it seems really ugly and far from what I wanted here:</p> <p><a href="https://i.sstatic.net/czxTY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/czxTY.png" alt="1" /></a></p> <p>this is the code:</p> <pre><code>using GraphRecipes, Plots gr() de...
<python><julia>
2023-02-15 14:41:33
2
435
Freya the Goddess
75,461,410
6,296,020
pySpark / Databricks - How to write a dataframe from pyspark to databricks?
<p>I'm trying to write a dataframe from a pyspark job that runs on AWS Glue to a Databricks cluster and I'm facing an issue I can't solve.</p> <p>Here's the code that does the writing :</p> <pre><code>spark_df.write.format(&quot;jdbc&quot;) \ .option(&quot;url&quot;, jdbc_url) \ .option(&quot;dbtable&quot;, table_n...
<python><pyspark><apache-spark-sql><databricks><aws-glue>
2023-02-15 14:41:26
0
360
Meyer Cohen
75,461,388
6,367,971
Validate column format in dataframe
<p>I have a CSV where some rows are parents and some are children, and I want to validate whether the format of the child rows are correct by adding a <code>Yes/No</code> value to a new column via a dataframe.</p> <pre><code>Type,ID,Ext_ID,Name Parent,1111,abc.xyz.num1,yyy Child,1,break://abc.xyz.num1/break1,break1 Chi...
<python><pandas>
2023-02-15 14:39:53
1
978
user53526356
75,461,346
17,550,177
Different Result from MinMaxScaler() with Manual Calculations
<p>So i was tinkering with MinMaxScaler and want to see how it works with manual calculations here's the array i'm trying to scale</p> <pre><code>array = [[0, -1.73, -1.73, -2.0, -2.0, -2.0, -1.73], [-1.73, 0, -1.41, -1.73, -1.73, -1.73, -1.41], [-1.73, -1.41, 0, -1.73, -1.73, -1.73, -0.0], [...
<python><math><scikit-learn><scaling>
2023-02-15 14:36:02
1
756
Michael Halim
75,461,236
7,776,781
Dynamically updating type hints for all attributes of subclasses in pydantic
<p>I am writing some library code where the purpose is to have a base data model that can be subclassed and used to implement data objects that correspond to the objects in a database. For this base model I am inheriting from <code>pydantic.BaseModel</code>.</p> <p>There is a bunch of stuff going on but for this exampl...
<python><python-3.x><pycharm><mypy><pydantic>
2023-02-15 14:25:35
1
619
Fredrik Nilsson
75,461,232
6,357,916
Argument is not getting mapped in REST endpoint method in django
<p>I have following code in my <code>MyModuleViewSet</code>:</p> <pre><code>class MyModuleViewSet(viewsets.ModelViewSet): # ... @action(detail=False, permission_classes=(IsOwnerOrReadOnly,)) @debugger_queries def my_rest_api(self, request, pk=None): # ... return HttpResp...
<python><django><django-rest-framework><django-views><django-viewsets>
2023-02-15 14:25:14
1
3,029
MsA
75,461,143
12,474,157
Python: How to use requests library to get network data from a website
<p>Every time you enter into a website and you inspect the site, you can see you could get some information like &quot;elements&quot; which contains the html of the website, but also there is some data contained in the &quot;network&quot; tab. I would like to get the Fetch/XHR names of all the contents in the network</...
<python><request><fetch>
2023-02-15 14:18:03
0
1,720
The Dan
75,461,087
2,897,115
python how to access class variables inside init
<p>I want to access class variables inside the init</p> <pre><code>class Hare: APP = 10; def __init__(self): print(APP) h = Hare() </code></pre> <p>its giving error</p> <pre><code>!!! NameError: name 'APP' is not defined </code></pre>
<python>
2023-02-15 14:13:20
1
12,066
Santhosh
75,461,034
13,158,157
Seaborn distplot for data with high SD
<p>I am trying to map float pd.Series with high SD:</p> <pre><code>&gt;&gt;&gt;pd.Series(foo).describe() count 3.351198e+07 mean -2.337614e+02 std 4.788547e+04 min -9.999999e+06 25% 0.000000e+00 50% 0.000000e+00 75% 0.000000e+00 max 7.499913e+07 &gt;&gt;&gt;pd.Series(foo).std() 47885...
<python><pandas><matplotlib><seaborn>
2023-02-15 14:08:40
0
525
euh
75,460,996
1,056,563
After brew install of python@3.9 "python" is no longer found
<p><code>python3</code> is available after:</p> <pre><code>brew install python@3.9 </code></pre> <p>But there is no <code>python</code> to be found. Not in <code>/usr/local/bin</code> or in <code>/usr/local/Cellar/python@3.9/3.9.16/bin</code>. There are many programs that look for plain old <code>python</code> so what...
<python>
2023-02-15 14:05:54
1
63,891
WestCoastProjects
75,460,953
19,130,803
Dash generalize progress bar
<p>I am developing a data app using dash. I am doing a file copy task for that I am showing the progress bar.</p> <p>I have written this code from dash website as reference. This is pseduo code structure</p> <pre><code>import dash_bootstrap_components as dbc from dash import Input, Output, dcc, html, ctx progress = ht...
<python><plotly-dash>
2023-02-15 14:01:58
0
962
winter
75,460,835
2,996,797
Mocking environment variables with starlette config
<pre><code>from starlette.config import Config config = Config(&quot;.env&quot;) SOME_ENV_VAR: str = config(&quot;SOME_ENV_VAR&quot;, cast=str, default=&quot;abc&quot;) </code></pre> <p>I'm looking for a way to mock the value of <code>SOME_ENV_VAR</code> for unit tests. Is there such an option?</p> <pre><code># mock ...
<python><unit-testing><mocking><fastapi><starlette>
2023-02-15 13:52:52
1
530
Cauthon
75,460,641
127,508
How to build a Python project for a specific version of Python?
<p>I have an app that I would like to deploy to AWS Lambda and for this reason it has to have Python 3.9.</p> <p>I have the following in the pyproject.toml:</p> <pre class="lang-ini prettyprint-override"><code>name = &quot;app&quot; readme = &quot;README.md&quot; requires-python = &quot;&lt;=3.9&quot; version = &quot;0...
<python>
2023-02-15 13:38:40
1
8,822
Istvan
75,460,481
6,829,370
Combining multi one hot encoded columns in pandas dataframe along with removing duplicates
<p>I have a dataframe that looks like this :</p> <pre><code>ID A B C 1 1 0 0 1 0 1 0 2 1 0 0 </code></pre> <p>I want the output to be like this :</p> <pre><code>ID A B C 1 1 1 0 2 1 0 0 </code></pre> <p>Kindly guide how to achieve this.</p>
<python><python-3.x><pandas><scikit-learn>
2023-02-15 13:27:59
1
388
Shubham_geo
75,460,392
2,876,079
How to show pylint message codes/ids in PyCharm Problems view and get quick fix?
<p>I get some pylint warnings in the Problems view of PyCharm Community Edition:</p> <p><a href="https://i.sstatic.net/qzVlj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qzVlj.png" alt="enter image description here" /></a></p> <p><strong>a)</strong> How can I tell PyCharm to include the corresponding ...
<python><pycharm><pylint>
2023-02-15 13:20:18
3
12,756
Stefan
75,460,241
3,371,472
Speed up debugging the conda-build tutorial
<p>I'm working outward from <a href="https://docs.conda.io/projects/conda-build/en/latest/user-guide/tutorials/build-pkgs.html" rel="nofollow noreferrer">this conda-build example</a> to eventually build a conda package of my own. (If you try it out, note that the <code>meta.yaml</code> in the example is out of date and...
<python><conda><conda-build>
2023-02-15 13:06:24
1
538
eric_kernfeld
75,460,125
16,009,435
cpu performing better than gpu python opencv
<p>I am trying to run an openCV program with my GPU. I am using pre-trained models to detect faces on a playing video. The code works fine my question is, how is my CPU performing better than my GPU? Am I missing some attribute that should be defined to use the full potential of the GPU or is it just because the perfor...
<python><opencv>
2023-02-15 12:55:24
0
1,387
seriously
75,459,915
1,879,109
How do I return rust iterator from a python module function using pyo3
<p>Its not like I am not able to return any rust iterators from a python module function using pyo3. The problem is when lifetime doesn't live long enough!</p> <p>Allow me to explain.</p> <p><strong>First attempt:</strong></p> <pre class="lang-rust prettyprint-override"><code>#[pyclass] struct ItemIterator { iter: ...
<python><rust><pyo3>
2023-02-15 12:38:32
2
915
Kity Cartman
75,459,861
20,051,041
Why do I scrape corrupted PDFs of same size with BeautifulSoup?
<p>I went through similar topics here but did not find anything helpful for my case.</p> <p>I managed to get all PDFs (for personal learning purposes) in local folder but cannot open them. They also have the same (310 kB) size. Perhaps, you find some mistake in my code. Thanks.</p> <pre><code>import os import requests ...
<python><pdf><web-scraping><beautifulsoup><python-requests>
2023-02-15 12:33:24
1
580
Mr.Slow
75,459,846
1,436,800
How to set Time zone to TIME_ZONE = "Asia/Karachi" in Django Project?
<p>I want to change the timezone of my django project to Asia/Karachi. I have added this in my settings.py file:</p> <pre><code>TIME_ZONE = &quot;Asia/Karachi&quot; </code></pre> <p>Time zone of my postgres is also set to Asia/Karachi. But still when I create the objects, the time zone of DateTimeField is set to UTC.</...
<python><django><django-rest-framework><utc><django-timezone>
2023-02-15 12:32:29
1
315
Waleed Farrukh
75,459,841
11,814,875
Scrapy signals not connecting to class methods
<p>I've defined a <code>Crawler</code> class for crawling multiple spiders from script.<br> For spiders, instead of using pipelines, I defined a class, <code>CrawlerPipeline</code> and used signals for connecting methods.<br> In <code>CrawlerPipeline</code>, some methods require to use class variables such as <code>__E...
<python><web-scraping><scrapy><scrapy-pipeline>
2023-02-15 12:32:12
0
491
rish_hyun
75,459,700
1,436,800
How can I authenticate web socket connection in postman?
<p>This is my ASGI file: from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import os import app.routing from django.core.asgi import get_asgi_application</p> <pre><code> os.environ.setdefault(&quot;DJANGO_SETTINGS_MODULE&quot;, &quot;project.settings&quot;) app...
<python><django><websocket><postman><django-channels>
2023-02-15 12:17:45
0
315
Waleed Farrukh
75,459,630
14,239,638
warnings when running octave from python
<p>I am using oct2py python library to run octave script but I get the following error that I don't understand:</p> <pre><code>warning: function C:\Program Files\GNU Octave\Octave-7.3.0\mingw64\share\octave\packages\statistics-1.5.0\shadow\mean.m shadows a core library function warning: called from C:\Program Files...
<python><warnings><octave><oct2py>
2023-02-15 12:11:14
1
680
Wallflower
75,459,613
9,390,633
how to format larger dataframe better using pdfwriter using matplotlib
<p>When a large dataframe is been transformed to a pdf it tries fit too much on to one page so information looks small on pdf. How can I fix this so it formats correctly for small and larger dataframes?</p> <pre><code>fig, ax = plt.subplots(figsize=(12, 4)) ax.axis('tight') ax.axis('off') ax.set_title(title) ax.table(...
<python><matplotlib>
2023-02-15 12:10:16
0
363
lunbox
75,459,440
4,707,189
pathlib.Path.relative_to doesn't resolve path
<p>I'm getting a nonsymetric behavior when using <code>Path.relative_to</code> versus <code>os.path.relpath</code>, see examples below. In <a href="https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module" rel="nofollow noreferrer">Correspondence to tools in the os module</a>, I was guide...
<python><python-3.x><pathlib>
2023-02-15 11:54:55
1
1,149
Daniel
75,459,412
3,922,727
Azure http trigger is not allowing to create a folder in python using makedirs
<p>I am trying to create a new folder inside of Azure http trigger folder, in order to receive some files from an API call and save them based on the name.</p> <pre><code>config_country_folder = context.function_directory+&quot;/config/&quot;+country.upper() os.makedirs(config_country_folder, exist_ok=True) logging.inf...
<python><azure><azure-http-trigger>
2023-02-15 11:52:46
1
5,012
alim1990
75,459,385
8,406,122
Extracting data using python
<p>I have a text file like this</p> <pre><code>app galaxy store Galaxy Store app text editor Text Editor app smartthings SmartThings app samsung pay Samsung Pay app pdssgentool PdssGenTool app pdss-sample pdss-sample app encodertool EncoderTool app play store Play Store app play music Play Music app keep notes Ke...
<python>
2023-02-15 11:50:16
1
377
Turing101
75,459,348
13,566,716
do i need to use stripe listen - stripe cli in production?
<p>Is it required to run in command line:</p> <pre><code>stripe listen --forward-to localhost:5000/webhook </code></pre> <p>to receive stripe events to the webhook endpoint or does the endpoint automatically receive events if it is added to the stripe webhooks dashboard?</p> <p>I'm trying to ask if <code>stripe listen<...
<python><stripe-payments>
2023-02-15 11:47:13
1
369
3awny
75,459,341
10,260,806
How to parse txt file and make changes to a excel file based on the txt file in python
<p>I have a txt file with he following format and everyday I would like to run a python script so that the Name column, and end date column is used to parse the status column and make changed to a spreadsheet accordingly.</p> <p>Txt file format:</p> <pre><code>+------------+---------------------+---------------------+-...
<python><excel>
2023-02-15 11:46:31
1
982
RedRum
75,459,172
13,066,590
Loading a HuggingFace model on multiple GPUs using model parallelism for inference
<p>I have access to six 24GB GPUs. When I try to load some HuggingFace models, for example the following</p> <pre><code>from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained(&quot;google/ul2&quot;) model = AutoModelForSeq2SeqLM.from_pretrained(&quot;google/ul2&quot;) </...
<python><deep-learning><huggingface-transformers><torch><multi-gpu>
2023-02-15 11:33:12
1
930
andrea
75,458,965
15,001,463
T-test for determining which algorithm is experimentally faster
<p>I have written two algorithms to perform the Jacobi iterative method to simulate heat dissipation over a surface. I'd like to see if there is a significant difference between the run times of the two algorithms. I think that I can use a two-tailed <a href="https://www.statsmodels.org/dev/generated/statsmodels.stats....
<python><statistics>
2023-02-15 11:15:25
0
714
Jared
75,458,724
1,799,871
Tmux + python input() -- control characters taken literally
<p>I'm trying to get a simple console input in Python (<code>query = input('&gt;&gt;&gt; ')</code>). However, when I run this code inside Tmux, any control characters are taken literally, so I can't hit Enter to finish the input (prints <code>^M</code> instead) or break the process (prints <code>^C</code>).</p> <p>When...
<python><input><console><tmux>
2023-02-15 10:53:03
0
438
Tuetschek
75,458,603
10,270,590
How to Output Downloadable file after processing?
<h2>Specification</h2> <ul> <li><code>gr.__version__ --&gt; '3.16.2'</code></li> <li>I want to create a gradio tab in mygradio app</li> <li>Disregard TAB 1, I am only working on tab2</li> <li>where I upload an excel file</li> <li>save name of the excel fie to a variable</li> <li>process that excel file take data out o...
<python><excel><pandas><huggingface><gradio>
2023-02-15 10:44:23
1
3,146
sogu
75,458,549
9,860,033
How to show the line number from the file invoking the logger, not the logger file itself?
<p>I have a custom logging class, which has the following format:</p> <pre><code>log_format = &quot;%(asctime)s.%(msecs)d %(levelname)-8s [%(processName)s] [%(threadName)s] %(filename)s:%(lineno)d --- %(message)s&quot; </code></pre> <p>My project tree looks something like this:</p> <pre><code>. β”œβ”€β”€ exceptions.py β”œβ”€β”€ lo...
<python><logging><logfile><python-logging>
2023-02-15 10:40:50
1
1,134
waykiki
75,458,438
10,596,249
messagebird messages are not being delivered
<pre><code> import messagebird ACCESS_KEY = &quot;&quot; client = messagebird.Client(ACCESS_KEY) message = client.message_create( 'TestMessage', '+91XXXXXXXXX', 'working', { 'otp' : 1234 } ) print(client) </code></pre> <p>I am using above code to send message. But...
<python><messagebird>
2023-02-15 10:29:18
1
806
soubhagya
75,458,399
287,297
Batching the bulk updates of millions of rows with peewee
<ul> <li>I have an SQLite3 database with a table that has twenty million rows.</li> <li>I would like to update the values of some of the columns in the table (for all rows).</li> <li>I am running into performance issues (about only 1'000 rows processed per second).</li> <li>I would like to continue using the <code>peew...
<python><sqlite><sql-update><peewee>
2023-02-15 10:26:05
1
6,514
xApple
75,458,300
16,014,407
Efficient speaker diarization
<p>I am running a VM instance on google cloud. My goal is to apply speaker diarization to several .wav files stored on cloud buckets.</p> <p>I have tried the following alternatives with the subsequent problems:</p> <ol> <li>Speaker diarization on Google's API. This seems to go fast but the results make no sense at all....
<python><google-cloud-platform><speech-to-text><diarization>
2023-02-15 10:17:53
1
328
Luis
75,458,062
1,473,517
Why is a pure Python negative binomial pmf so much faster than the scipy version?
<p>scipy.stats has a function <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.nbinom.html" rel="nofollow noreferrer">nbinom.pmf()</a> which computes the <a href="https://en.wikipedia.org/wiki/Probability_mass_function" rel="nofollow noreferrer">probability mass function</a> of the <a href="htt...
<python><scipy>
2023-02-15 09:56:35
1
21,513
Simd
75,458,048
10,659,910
Populating each calendar month with a specific incrementing pattern
<p>Given a pandas <code>DataFrame</code> indexed by a timeseries, e.g.</p> <pre><code>import pandas as pd import numpy as np index = pd.date_range('2023-01-01', '2023-12-31', freq='1D') pd.DataFrame({'a' : np.random.randint(0, 10, len(index))}, index=index) </code></pre> <pre class="lang-none prettyprint-override"><co...
<python><pandas>
2023-02-15 09:55:40
1
10,368
William Miller
75,458,034
14,912,911
No module named 'PIL' after Installing pillow latest version
<p>I am installed pillow,following the documentation <a href="https://pillow.readthedocs.io/en/stable/installation.html#" rel="nofollow noreferrer">here</a>,</p> <pre><code>python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow </code></pre> <p>and import Image like this:</p> <pre><code>from PIL i...
<python><pip><python-imaging-library>
2023-02-15 09:54:41
2
448
Dude
75,458,001
8,511,544
I understand Python (3.x) is supposed to round to even. Why is round(0.975,2) = 0.97 but round(0.975*100)/100 = 0.98?
<p>So the question is in the title. Here are some more details:</p> <p>code:</p> <pre><code>a=0.975 print(round(a,2)) print(round(a*100)/100) a=-0.975 print(round(a,2)) print(round(a*100)/100) a=1.975 print(round(a,2)) print(round(a*100)/100) a=-1.975 print(round(a,2)) print(round(a*100)/100) </code></pre> <p>The pr...
<python><rounding><precision>
2023-02-15 09:51:46
1
637
dalleaux
75,457,897
20,612,566
Dict in List comprehension Python
<p>I have a List with API results:</p> <pre><code>result = [(True, {'result': {'skus': [{'sku': '123'}, {'sku': '124'}] } } ), (True, {'result': {'skus': [{'sku': '125'}, {'sku': '126'}] } ...
<python><python-3.x><list><loops><list-comprehension>
2023-02-15 09:41:28
3
391
Iren E
75,457,849
6,210,177
regex: Find all groups of consecutive groups, where the groups are separated by pattern
<p>I have a badly parsed text where multiple text blocks are separated by lines with only three digits. What I want is to get a regex that would help me capture all the text in a block (starting and including the three digits row until the last white space before the next three characters.</p> <p>This is the one I've t...
<python><regex>
2023-02-15 09:36:56
2
455
Jano
75,457,741
1,870,803
Dynamically generating marshmallow schemas for SQLAlchemy fails on column attribute lookup for Relationship
<p>I am automatically deriving marshmallow schemas for SQLAlchemy objects using the approach described in <a href="https://stackoverflow.com/questions/42891152/how-to-dynamically-generate-marshmallow-schemas-for-sqlalchemy-models">How to dynamically generate marshmallow schemas for SQLAlchemy models</a>.</p> <p>I am th...
<python><sqlalchemy><marshmallow><marshmallow-sqlalchemy>
2023-02-15 09:26:58
2
149,964
Yuval Itzchakov
75,457,670
859,227
Drop rows and reset_index in a dataframe
<p>I was wondering why <code>reset_index()</code> has no effect in the following piece of code.</p> <pre><code>data = [0,10,20,30,40,50] df = pd.DataFrame(data, columns=['Numbers']) df.drop(df.index[2:4], inplace=True) df.reset_index() df Numbers 0 0 1 10 4 40 5 50 </code></pre> <p>UPDATE:<...
<python><pandas><dataframe>
2023-02-15 09:20:30
2
25,175
mahmood
75,457,594
8,913,983
Extracting text from a binary PE file in python
<p>I am trying to extract strings from a PE files (.exe &amp; .dll) using <code>pefile</code> library but for a while I am stuck as this type of data format is new to new, I've read many questions similar to mine but with no success I am able to adapt the code to fit my needs.</p> <p>I have a following code:</p> <pre><...
<python><dll><binary><exe><portable-executable>
2023-02-15 09:14:35
0
4,870
Jonas Palačionis
75,457,486
3,270,696
Using LRU Cache with python's Gunicorn
<p>Trying to put data into LruCache and then get it back. I am using postman to get the data via api, every fourth or fifth time I retry the api, data is returned form the cache. Whereas for first tries, it takes time and never returns from the cache. I think data is not being cached in the first placed. Please help, w...
<python><gunicorn><lru>
2023-02-15 09:05:32
0
317
Jawwad Ahmed
75,457,389
17,696,880
Validate if a list has only None elements, strings that only have whitespaces or is empty
<pre class="lang-py prettyprint-override"><code> #examples: lista = [&quot; &quot;, None, None, &quot;&quot;, &quot; &quot;] #print 'yes!' lista = [] #print 'yes!' lista = [&quot; &quot;, None, None, &quot;&quot;, &quot; s&quot;] #print 'no!' lista = [&quot;sun is bright&quot;, &quot;aa&quot;, &quot;Hello!&quot;]...
<python><python-3.x><string><list><validation>
2023-02-15 08:57:16
2
875
Matt095
75,457,205
5,684,405
Error while installing jupyterlab with poetry
<p>I can't isntall JupyterLab with poetry. I keep getting this error. I've tried deleting cache by:</p> <pre><code> rm -rf ~/Library/Caches/pypoetry/artifacts/* </code></pre> <p>and</p> <pre><code>poetry cache clear pypi --all </code></pre> <p>but I keep getting the following error:</p> <pre><code>$ poetry add --grou...
<python><jupyter-lab><python-poetry>
2023-02-15 08:38:14
2
2,969
mCs
75,456,976
5,987,698
How can I compute the gradient of multiple outputs with respect to a batch of inputs in a single backward pass in PyTorch?
<p>I am performing multi-label image classification in PyTorch, and would like to compute the gradients of all outputs at ground truth labels for each input with respect to the input. I would preferably like to do this in a single backward pass for a batch of inputs.</p> <p>For example:</p> <pre><code>inputs = torch.ra...
<python><pytorch><backpropagation><multilabel-classification><autograd>
2023-02-15 08:07:18
0
8,627
GoodDeeds
75,456,586
1,942,868
Django url which accept both with parameter or without
<p>I want to accept both urls with and without parameters, such as <code>/top/</code> <code>/top/1</code></p> <p>I tried a few patterns:</p> <pre><code>path('top/&lt;int:pk&gt;/', views.top, name='top_edit'), path('top/(&lt;int:pk&gt;)/', views.top, name='top_edit'), path('top/(&lt;int:pk&gt;)/$', views.top, name='top_...
<python><django><django-rest-framework><django-views><django-urls>
2023-02-15 07:21:14
3
12,599
whitebear
75,456,244
17,835,656
how can i create a CSR with specific Configuration using python
<p>i need to create a CSR with specific configuration using python</p> <p>this is my configuration :</p> <pre><code>oid_section = OIDs [ OIDs ] certificateTemplateName= 1.3.6.1.4.1.311.20.2 [ req ] default_bits = 2048 emailAddress = test@gmail.com req_extensions = v3_req x509_extensions =...
<python><openssl><cryptography><private-key><csr>
2023-02-15 06:35:03
1
721
Mohammed almalki
75,456,242
3,386,779
hiding the testcase execution status as well report path
<p>I have created a robot framework tool with one testcase. now 'its showing testcase execution status &quot;Pass&quot; and well report path. I need to turn off the testcase execution status as well as report path.</p> <p><a href="https://i.sstatic.net/3nJOm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.ne...
<python><selenium-webdriver><robotframework>
2023-02-15 06:34:42
1
7,263
user3386779
75,456,096
1,942,868
How to get the authentication information in ModelViewSet?
<p>I am using rest framework with <code>ModelViewSet</code></p> <pre><code>class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer filterset_fields = ['user'] def list(self, request): queryset = m.Drawing.objects.all() serial...
<python><django><django-rest-framework><django-viewsets>
2023-02-15 06:15:26
2
12,599
whitebear
75,456,070
11,402,025
Can I have the same FastAPI GET endpoints accepting two different types of input?
<p>I want to use a GET endpoint <code>/Users</code> with body parameters being either a <code>person</code> or <code>country</code>. I do not want to change the request call signature, but the parameters I am sending will be changed. Is this possible ?</p> <pre><code>class PersonInfo(AppUserInfo): id: int perso...
<python><fastapi>
2023-02-15 06:11:30
1
1,712
Tanu
75,455,995
1,019,129
Is indexed slice a view
<p>In torch slicing creates a View i.e. the data is not copied into a new tensor i.e. it acts as ALIAS</p> <pre><code> b = a[3:10, 2:5 ] </code></pre> <p>My understanding is that is not the case for indexed slice. f.e.</p> <pre><code> b = a[[1,2,3] : [5,11]] </code></pre> <p>Is this correct ?</p> <p>And second is ther...
<python><indexing><view><pytorch>
2023-02-15 05:59:30
1
7,536
sten
75,455,721
15,358,800
Explode a string with random length equally to next empty columns pandas
<p>Let's say I've df like this..</p> <pre><code> string some_col 0 But were so TESSA tell me a little bit more t ... 10 1 15 2 14 3 Some other text x...
<python><pandas>
2023-02-15 05:15:48
3
4,891
Bhargav
75,455,659
2,091,585
Convertng a Pandas series of stringg of '%d:%H:%M:%S' format into datetime format
<p>I have a Pandas series which consists of strings of '169:21:5:24', '54:9:19:29', and so on which stand for 169 days 21 hours 5 minutes 24 seconds and 54 days 9 hours 19 minutes 29 seconds, respectively.</p> <p>I want to convert them to datetime object (preferable) or just integers of seconds.</p> <p>The first try wa...
<python><pandas><datetime><time><series>
2023-02-15 05:02:28
2
2,238
user67275
75,455,571
6,032,140
Exact sub-string match inside a string in Python
<ol> <li><p>I have a string as given below</p> <pre><code>dit ='{p_d: {a:3, what:3.6864e-05, s:lion, sst:{c:-20, b:6, p:panther}}}' </code></pre> </li> <li><p>And I have a list of elements which I wanted to search in the above string and replace them with double quotes.</p> <pre><code>['', 'p_d', '', '', 'a', '3', '', ...
<python><string>
2023-02-15 04:41:57
1
1,163
Vimo
75,455,405
10,534,633
Iterating over dictionary or its items
<p>What's a better practice and what's faster:</p> <ul> <li>iterating over dictionary (practically by its keys):<br /> <code>for key in dictionary: ...</code></li> <li>or iterating over its items:<br /> <code>for key, value in dictionary.items(): ...</code>?</li> </ul> <p>Using <code>dict.items()</code> seems to be a m...
<python><performance><dictionary>
2023-02-15 04:11:05
1
1,230
maciejwww
75,455,187
7,394,039
PLotly Scatter: Moving the colorbar to the left not working
<p>Here's the piece of code I am using (This plots a scatter plot with a colorbar to the right of the plot)</p> <pre><code>import plotly.express as px data_y = [758, 742.19, 731.57, 728.36, 718.76, 707.56] data_x = [10, 9, 8, 7, 6, 5] data_x_labels = ['A', 'B', 'C', 'D', 'E', 'F'] fig = px.scatter(x=data_x, y=data_y...
<python><python-3.x><plotly><plotly-express>
2023-02-15 03:15:06
1
1,270
Nikhil Mishra
75,455,115
19,425,874
Object has no attribute Python web scraping error
<p>I'm looking to scrape a set of URLs - I want to visit each link on the given URL, and return the player's pos1 pos2 and profile details.</p> <p>I have two sets of URLs I'm looking at, G League players (which is working perfectly) and International Players (which I'm completely stuck on).</p> <p>The sites seem to be ...
<python><beautifulsoup><python-requests><python-requests-html>
2023-02-15 02:55:19
1
393
Anthony Madle
75,455,067
1,897,151
getting the roi section dynamically ignoring resize
<p>i have a set of resolution for opencv and pytesseract to detect which is the standard 1920x1080</p> <p>but after getting the image and resize it to 1920x1080, i will get the ROI around center square of the image</p> <pre><code>img = cv2.imread(&quot;test.png&quot;) height, width, channels = img.shape print(f'origin...
<python><opencv><tesseract><python-tesseract>
2023-02-15 02:46:25
0
503
user1897151
75,454,835
1,334,858
VSCode Python IntelliSense Not working On Remove Machine
<p>I use VSCode &quot;Remote-SSH&quot; to access a VM to do all my coding.</p> <p>On the VM I have installed the &quot;Python&quot; and &quot;Pylance&quot; extensions hoping to get IntelliSense autocomplete.</p> <p>My python interpreter is not in the &quot;typical&quot; <code>/usr/bin/python3</code> location. So I have...
<python><python-3.x><vscode-extensions><vscode-remote>
2023-02-15 01:51:58
0
1,955
user1334858
75,454,637
9,273,406
How to fix python uvicorn server returning "426 Upgrade Required"?
<p><strong>I have a python uvicorn app which runs fine locally for my colleagues but not for me</strong>. After running <code>python src/main.py</code>, the server connects to database and loads perfectly:</p> <pre><code>INFO | uvicorn.server:serve:75 - Started server process [49720] INFO | uvicorn.lifespan.on:startup:...
<python><http><uvicorn>
2023-02-15 01:04:48
1
4,370
azizbro
75,454,557
1,306,666
Safe way to create an "out of band" alternative value for a function argument in Python
<p>I have a function like the following:</p> <pre><code>def do_something(thing): pass def foo(everything, which_things): &quot;&quot;&quot;Do stuff to things. Args: everything: Dict of things indexed by thing identifiers. which_things: Iterable of thing identifiers. Something is only ...
<python>
2023-02-15 00:45:25
0
7,145
nebuch
75,454,425
33,796
Access Blocked: <project> has not completed the Google verification process
<p>I am building a simple script which polls some data and then updates a spreadsheet that I am giving to my client. (It is a small project and I don't need anything fancy.)</p> <p>So I created a Google Cloud project, enabled the Sheets API, and got a credential for a Desktop app. When I try to run the <a href="https...
<python><google-cloud-platform><google-sheets-api>
2023-02-15 00:14:24
4
60,733
luqui
75,454,093
13,215,988
How can I improve my python environment setup on windows 10?
<p>This is my current python environment setup on Windows 10:</p> <p>For the remainder of this post I will assume you have chocolatey installed. Also I'm using the bash as admin terminal from cmder.</p> <p>Install python3 with <code>choco install python</code> and/or <code>choco install python3</code>. Verify that you ...
<python><virtualenv><python-venv><pyenv><virtualenvwrapper>
2023-02-14 23:10:59
0
1,212
ChristianOConnor
75,453,995
6,387,095
Pandas plot, vars() argument must have __dict__ attribute?
<p>It was working perfectly earlier but for some reason now I am getting strange errors.</p> <p>pandas version: <code>1.2.3</code></p> <p>matplotlib version: <code>3.7.0</code></p> <p>sample dataframe:</p> <pre><code>df cap Date 0 1 2022-01-04 1 2 2022-01-06 2 3 2022-01-07 3 4 2022...
<python><pandas><matplotlib>
2023-02-14 22:55:53
2
4,075
Sid
75,453,928
7,640,725
Is there a way to define step functions inside a class with pytest-bdd
<p>I'm wondering if there's a way to define step test functions inside Python class with <code>pytest-bdd</code> framework.</p> <p>Let me elaborate a bit further..., suppose that we have a feature file like this:</p> <p>&quot;<strong>test.feature</strong>&quot; file:</p> <pre><code>Feature: Transaction Calculate th...
<python><unit-testing><pytest><bdd><pytest-bdd>
2023-02-14 22:44:09
0
941
blue2609
75,453,886
15,569,921
Map the indices of 2d array into 1d array in Python
<p>Say I have a square 2d array (<code>mat</code>) and a 1d array (<code>arr</code>) which is the same <strong>length</strong> as the flattened 2d array (the values inside are different). Given the row and column index of the 2d array, how can I map it into the 1d array <strong>index</strong> to give the value of the s...
<python><arrays><indexing><mapping>
2023-02-14 22:36:30
1
390
statwoman
75,453,872
11,809,811
inconsistent result when getting location from ip address
<p>I am trying to get a location from an ip address, the code for that is:</p> <pre><code>import urllib.request import json with urllib.request.urlopen(&quot;https://geolocation-db.com/json&quot;) as url: data = json.loads(url.read().decode()) print(data) </code></pre> <p>This does produce a result but it is t...
<python><json>
2023-02-14 22:33:31
1
830
Another_coder