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
⌀
77,105,594
7,848,740
Use Django messages framework when a webhook is called
<p>I have set up an URL in Django that is being used as webhook from another service. It has implemented like:</p> <pre><code>@csrf_exempt @require_POST def hoof_alert(request): json_rx = json.loads(request.body.decode(&quot;utf-8&quot;)) if json_rx[&quot;alerts&quot;][0][&quot;status&quot;] == &quot;firing&quot;...
<python><django><webhooks><django-messages>
2023-09-14 13:52:24
1
1,679
NicoCaldo
77,105,565
6,464,947
Why this error with pygbag: file not found in folder assets #python #pygbag
<p>When I run the localhost it will not work and the #debug says that there is an error and that it does not find the png files. I also put them into an assets folder, but it doesn't find them even if I try to figure out different solutions</p>
<python><pygbag>
2023-09-14 13:49:31
0
23,563
PythonProgrammi
77,105,434
264,136
python read stored credentials in credential manager
<pre><code>target_name = &quot;rtp-abs-cache.com&quot; credential = win32cred.CredRead(target_name, win32cred.CRED_TYPE_GENERIC) </code></pre> <p>gives error:</p> <pre><code> Traceback (most recent call last): File &quot;c:\code\daily_files_uploader.py&quot;, line 11, in &lt;module&gt; credential = win...
<python>
2023-09-14 13:33:59
1
5,538
Akshay J
77,105,414
1,014,217
How to iterate over a pyspark dataframe to increment a value and reset it to 0
<p>I have a pyspark dataframe with the following fields: dt = timestamp (one row per hour) rain_1h = rain in mm that hour</p> <p>Now I need to calculate the number of Dry Hours, when it doesnt rain, so it must increment it when it doesnt rain, and when it rains it should reset to 0.</p> <p>I tried the following:</p> <p...
<python><pandas><pyspark>
2023-09-14 13:31:36
1
34,314
Luis Valencia
77,105,226
561,243
Specify many option in argparse using *
<p>I have a question for you! I have developed a command line tools with many options using argparse. Here is a simplified version of what I have:</p> <pre class="lang-py prettyprint-override"><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('--skip-part1', action='store_true', default=Fals...
<python><argparse>
2023-09-14 13:10:12
2
367
toto
77,105,126
11,932,905
Pandas: re-assign values for groups to same value in one column if they have at least one common in another
<p>I have following dataframe:</p> <pre><code>df = pd.DataFrame({&quot;zip&quot;:['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A','C', 'C', 'C','C', 'C', 'C'], &quot;zip_splitted&quot;:['A_1', 'A_1', 'A_1','A_1', 'A_1', 'A_1', 'A_2', 'A_2', 'A_2','A_2', ...
<python><pandas><group-by>
2023-09-14 12:58:35
2
608
Alex_Y
77,105,076
3,433,875
Curve text around a polar plot
<p>I am trying to curve text on a polar chart in matplotlib.</p> <p>Here is an example of my case:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np text = [&quot;Electoral Process&quot;, &quot;Political Pluralism&quot;, &quot;Rule of Law&quot;, &quot;Freedom of expression&quot;, &quot;F...
<python><matplotlib><plot-annotations><polar-plot>
2023-09-14 12:53:21
2
363
ruthpozuelo
77,105,067
15,320,579
Create a new dictionary based on 2 dictionaries with not same key name in python
<p>I have the following 2 dictionaries:</p> <pre><code>dict1 = {'imgsss/modifiedmerged/modifiedmerged-2.png': 3, 'imgsss/modifiedmerged/modifiedmerged-4.png': 5} dict2 = {&quot;form1&quot;: &quot;POLICY NUMBER COMMERCIAL GENERAL&quot;, &quot;form2&quot;: &quot;ACP GLDO7285650787&quot;} </code></pre> <p>I want to crea...
<python><python-3.x><dictionary>
2023-09-14 12:52:14
2
787
spectre
77,105,050
9,139,930
Python relative imports that skip intermediate folder in VSCode
<p>I am trying to understand the code in someone else's mixed-language repository (part of a large, complicated code base). The directory structure is like this:</p> <pre><code>module_A/ python/ __init__.py script_A.py script_B.py other/ other_scripts.cxx </code></pre> <p>The con...
<python><visual-studio-code><python-import><python-module><relative-import>
2023-09-14 12:50:03
1
367
book_kees
77,105,015
1,652,219
Python Polars: Low memory read, process, writing of parquet to/from Hadoop
<p>I would like to be able to process very large files in Polars without running out of memory. In the documentation they suggest using scanning, lazyframes and sinks, but it is hard to find proper documentation of how to do this in practice. Hopefully some experts on here can help.</p> <p>Here I provide an example of ...
<python><dataframe><parquet><python-polars><pyarrow>
2023-09-14 12:44:28
1
3,944
Esben Eickhardt
77,104,909
22,326,950
Why does the same win32.com GetObject call (same line of code) only in certain circumstances find 'SAPGUI' in the Running Object Table
<p>While writing a generic function (for python and Excel vba) to return a available SAP session (existing or new) for further scripting, I encountered a strange behavior of the GetObject call when it comes to finding the <code>SAPGUI</code> object in the ROT.</p> <ul> <li>With a session open the function behaves as ex...
<python><excel><vba><winapi><sap-gui>
2023-09-14 12:31:57
0
884
Jan_B
77,104,513
1,473,517
Why is numba popcount code twice as fast as equivalent C code?
<p>I have this simple python/numba code:</p> <pre><code>from numba import njit import numba as nb @nb.njit(nb.uint64(nb.uint64)) def popcount(x): b=0 while(x &gt; 0): x &amp;= x - nb.uint64(1) b+=1 return b @njit def timed_loop(n): summand = 0 for i in range(n): ...
<python><c><performance><x86-64><numba>
2023-09-14 11:36:18
2
21,513
Simd
77,104,419
17,561,414
Call one notebook from another notebook
<p>I would like to call one notebook from another notebook in databricks.</p> <p>lets say I have notebook_main and notebook_variable.</p> <p>I want to run the notebook_variable from notebook_main and the out of the notebook vairiable I want to pass in the notebook_main.</p> <p>For example:</p> <p>In notebook_variable I...
<python><sql><databricks><azure-databricks>
2023-09-14 11:24:14
1
735
Greencolor
77,104,373
903,011
Select n columns, with the rest of line added to the end of the last column, using read_csv()
<p>I am using Pandas to read with <code>read_csv()</code> a file with fields separated by spaces. There is a fixed number of columns, but a few lines do not follow the pattern.</p> <p>The solution I used so far is to add <code>on_bad_lines='warn'</code> which skips them and informs me that there is a faulty line.</p> <...
<python><pandas><regex><csv>
2023-09-14 11:15:25
3
30,596
WoJ
77,104,355
7,465,516
How to open a textfile in python on windows with the correct encoding?
<p>I am aware that <a href="https://stackoverflow.com/a/436299/7465516">correctly determining the encoding of text is impossible</a>. I notice however, that programs such as notepad can correctly read a file encoded in utf-8, and I want to do the same in python.</p> <p><code>open</code> can not do it, it is <a href="ht...
<python><windows><unicode><utf-8><character-encoding>
2023-09-14 11:12:54
1
2,196
julaine
77,104,336
15,759,796
How to serialize a list of ndarray?
<p>I have a script which reads a video frame by frame and accumulate them in a deque.</p> <pre><code>labeled_frame_dequeue = [numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray] </code></pre> <p>I am trying to pass this list to a celery task</p> <pre><code>generate_clip_from_frames.delay(labeled_video_path, lab...
<python><celery><numpy-ndarray><celery-task>
2023-09-14 11:10:39
2
477
raj-kapil
77,104,206
9,669,142
Python - curve_fitting automating initial guesses
<p>I asked the following question yesterday and this is an extension of this question: <a href="https://stackoverflow.com/questions/77099062/python-curve-fitting-doesnt-work-properly-with-high-x-values/77099276#77099276">Python - curve_fitting doesn&#39;t work properly with high x-values</a></p> <p>For completeness, I ...
<python><scipy><curve-fitting>
2023-09-14 10:53:13
2
567
Fish1996
77,103,963
630,866
Method keyword argument is same in every call
<p>I have following method</p> <pre><code>&gt;&gt;&gt; import uuid &gt;&gt;&gt; def get_sample(sample_value=str(uuid.uuid4())): ... return sample_value ... &gt;&gt;&gt; print(get_sample()) 2ca4a40c-62c4-4efa-add4-8f13067349d5 &gt;&gt;&gt; print(get_sample()) 2ca4a40c-62c4-4efa-add4-8f13067349d5 &gt;&gt;&gt; print(g...
<python>
2023-09-14 10:18:56
0
2,763
Bhaskar
77,103,869
6,645,564
How can I figure out the source of an error from code that occurs when I run it within a Jupyter notebook?
<p>I am running some code through a Jupyter notebook and I have been having an incredibly frustrating time trying to find the source of a bug that has been plaguing my work. I have set up my virtual environment (venv) in python to have these packages at this versions installed:</p> <pre><code>#For python 3.9.0 scipy==1...
<python><debugging><jupyter-notebook>
2023-09-14 10:06:33
0
924
Bob McBobson
77,103,814
7,132,596
How to optimize Django's model's string representation database hits in browsable API
<p>I am currently trying to optimize my API and noticed that the browsable API is responsible for N+1 queries. This only happens when I add the parent-class in the child's <code>__str__</code> method.</p> <p>Comparison using django-debug-toolbar:</p> <ul> <li><code>f&quot;{self.name} ({self.client.name})&quot;</code>: ...
<python><django><django-rest-framework>
2023-09-14 09:58:42
1
956
Hans Bambel
77,103,813
1,254,528
Python 3.11 , converting serialzier to data model object getting error object has no attribute '_sa_instance_state
<p>I am new python and I am trying to convert serialize object to data model and my flow is Json request to serialize and from serialize to model-object in python to persist the object.</p> <p>Json request :</p> <pre><code>{ &quot;id&quot;: &quot;string&quot;, &quot;href&quot;: &quot;string&quot;, &quot;cat...
<python><python-3.x><list><sqlalchemy><fastapi>
2023-09-14 09:58:42
1
499
karthik selvaraj
77,103,791
5,663,844
Custom methods for pandas df, that selects prespecified column by column name
<p>I would like to write a custom method for the the <code>pd.DataFrame</code> class. That would allow me to directly place new values at prespecified location.</p> <pre class="lang-py prettyprint-override"><code>class myDF(pd.DataFrame): def func1(self, row, value): self.df.at[row,&quot;prespecified_column...
<python><pandas>
2023-09-14 09:56:20
1
480
Janosch
77,103,773
3,480,297
Convert array of strings with single quotes to array of strings with double quotes
<p>Suppose I have a list of strings, where each string in the list can either start with a single or double quote, such as:</p> <pre><code>my_list = ['a string with a single quote', &quot;my organisation's goals&quot;, 'another string with double quote'] </code></pre> <p>Notice that the string that contains double quot...
<python>
2023-09-14 09:54:39
2
2,612
Adam
77,103,701
4,391,360
Keep only two digits after the first digit other than zero
<p>I know how to keep only two decimal places after the decimal point. For example (there are other methods):</p> <pre><code>&gt;&gt;&gt; print(f'{10000.01908223295211791992:.2f}') 10000.02 </code></pre> <p>But I want to keep the first two digits other than zero after the decimal point:</p> <p>10000.0190822329521179199...
<python><rounding>
2023-09-14 09:46:21
4
727
servoz
77,103,687
11,729,033
How do I rename a Diskcache memoization cache?
<p><code>diskcache.Cache</code> objects provide a <code>memoize</code> function, which can be used like this:</p> <pre><code>cache = Cache(...) @cache.memoize() def long_computation(*args): ... </code></pre> <p>One can provide a <code>name</code> argument to <code>cache.memoize</code> to uniquely identify the call...
<python><python-3.x><diskcache>
2023-09-14 09:44:04
0
314
J E K
77,103,643
6,156,353
Polars - efficiently partition large csv dataset into parquet
<p>I need to partition large CSV dataset into smaller year-month partitions. What I do:</p> <pre class="lang-py prettyprint-override"><code>for year in range(2016, 2019): year_df = (pl .scan_csv('some.csv', infer_schema_length=100000, null_values=['\\N'], cache=True) .with_columns( pl.co...
<python><dataframe><csv><parquet><python-polars>
2023-09-14 09:39:56
2
1,371
romanzdk
77,103,376
10,970,202
pandas split string column on any character that is not an alphabet
<p>I have dataframe something like below</p> <pre><code>a str_col 1 ABC*EFG 2 DDC/DSD 3. sew^sds ... </code></pre> <p>I want to split them on non alphabet and into a list. Desired df is as follows</p> <pre><code>a str_col. new_col 1 ABC*EFG. [ABC, EFG] 2 DDC/DSD. [DDC, DSD] 3. sew^sds [s...
<python><pandas>
2023-09-14 09:07:30
3
5,008
haneulkim
77,103,226
8,588,743
VSCode does not recognize installed packages, despite correct interpreter selected and correct environment
<p>I'm trying to do some forecasting using facebook prophet using an environment named <code>'fbprophet'</code> where I've installed several dependencies. However when I select the correct interpreter and run <code>'import pandas as pd'</code> I get the error: <code>'ModuleNotFoundError: No module named 'pandas''</code...
<python><visual-studio-code>
2023-09-14 08:51:47
1
903
Parseval
77,103,225
6,664,393
Highlighting non-local variables in VS Code Python
<p>The VS Code syntax highlighter is able to highlight unused variables in a function body.</p> <p>I'm looking for the &quot;converse&quot;: variables that are used, but not parameters or defined inside the function. Instead they're defined somewhere else in the same module.</p> <p>For example:</p> <pre class="lang-py ...
<python><visual-studio-code>
2023-09-14 08:51:40
0
1,913
user357269
77,103,160
8,740,854
Check if (pos/neg) polygon is inside another (pos/neg) polygon
<h2>Description</h2> <p>I have the problem to decide if a region <code>A</code> is inside a region <code>B</code>. These regions are defined by a list of vertices <code>polyA</code> and <code>polyB</code>:</p> <ul> <li>If the vertices <code>polyA</code> are counter-clockwise, <ul> <li>then <code>A</code> is the interio...
<python><algorithm><geometry><polygon><point-in-polygon>
2023-09-14 08:41:57
0
472
Carlos Adir
77,102,998
8,124,392
Loading .npy into torch throws a missing key error
<p>This is my code where I'm trying to load a .npy file to torch:</p> <pre><code># Load the state dictionary from the numpy file state_dict_np = np.load(model_path, allow_pickle=True).item() # Convert numpy arrays within the state dictionary to PyTorch tensors state_dict_torch = {k: torch.tensor(v, dtype=torch.float32...
<python><numpy><deep-learning><pytorch>
2023-09-14 08:20:57
1
3,203
mchd
77,102,860
1,473,517
How to use native popcount with numba
<p>I am using numba 0.57.1 and I would like to exploit the native CPU popcount in my code. My existing code is too slow as I need to run it hundreds of millions of times. Here is a MWE:</p> <pre><code>import numba as nb @nb.njit(nb.uint64(nb.uint64)) def popcount(x): b=0 while(x &gt; 0): x &amp;...
<python><llvm><numba>
2023-09-14 08:00:54
1
21,513
Simd
77,102,848
17,561,414
Autoloader - creating tmp view
<p>Im using autoloader to incrementally load the data into silver layer from bronze tables where I use changeFeed feature.</p> <p>This is how I read the <code>df</code></p> <pre><code>df = spark.readStream.format(&quot;delta&quot;) \ .option(&quot;readChangeFeed&quot;, &quot;true&quot;) \ .table(&quot;mdp_prd.bronze.nr...
<python><pyspark><azure-databricks><spark-structured-streaming><databricks-autoloader>
2023-09-14 07:58:34
1
735
Greencolor
77,102,842
10,744,889
Keras One hot encoding (to_categorical) returns wrong output
<p>I have an output with three distinctive classes:</p> <pre><code>import numpy as np np.unique(y_train) </code></pre> <blockquote> <p>array([0, 2, 5], dtype=uint8)</p> </blockquote> <p>When I one-hot-encode it using the following code, I get an output with the shape of (number of instances, 6), not (number of instance...
<python><tensorflow><keras>
2023-09-14 07:58:05
2
537
Mojtaba Abdi Khassevan
77,102,762
13,706,389
Plotly show minor tick values
<p>In Python, I'm making a large figure with 15 subplots using Plotly. On these subplots, I want to indicate some important points along the x-axis. Initially, I used fig.add_vline to draw a vertical line + a label at these points. For some reason, this is extremely slow:</p> <pre class="lang-py prettyprint-override"><...
<python><plotly>
2023-09-14 07:46:59
1
684
debsim
77,102,707
10,090,254
Type hinting of dependency injection
<p>I'm creating a declarative http client and have a problem with mypy linting.</p> <p>Error:</p> <pre><code>Incompatible default for argument &quot;user&quot; (default has type &quot;Json&quot;, argument has type &quot;dict\[Any, Any\]&quot;) </code></pre> <p>I have a &quot;Dependency&quot; class that implements the l...
<python><python-typing><mypy>
2023-09-14 07:37:57
2
486
floydya
77,102,648
11,164,450
Escape JSON double quotes in Azure Pipeline
<p>I am trying to pass in Azure Pipeline Template JSON parameter as string but can't figure out how to make this right so i could do <strong>json.loads</strong> in main pipeline to convert string to JSON. <br> Template pipeline:</p> <pre><code>trigger: none resources: repositories: - repository: P1-T_automation ...
<python><json><yaml><azure-pipelines>
2023-09-14 07:29:46
2
321
gipcu
77,102,437
2,383,070
Polars from_pandas() fails with "ComputeError: only string-like values are supported in dictionaries"
<p>Converting a Pandas DataFrame to a Polars DataFrame will result in an error if the Pandas DataFrame has any columns with categorical dtypes that are either <code>int</code> or <code>float</code>.</p> <p>For example, this...</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import polars as pl ...
<python><pandas><python-polars>
2023-09-14 06:50:54
2
3,511
blaylockbk
77,102,291
219,153
How to broadcast this array with Numpy?
<p>In this Python 3.11 code snippet:</p> <pre><code>import numpy as np state = np.arange(48, dtype='u1').reshape((2, 8, 3)) pixels = [3, 4, 5] colors = [[42, 43, 44], [0, 1, 2]] state[0, pixels] = colors[0] # line 1 state[1, pixels] = colors[1] # line 2 # state[:, pixels, :] = colors # error </code></pre> <p>I woul...
<python><numpy><array-broadcasting>
2023-09-14 06:27:22
1
8,585
Paul Jurczak
77,102,001
14,430,730
How to Package and Publish a Script That Calls Other Scripts as a Pip Wheel
<p>I'm trying to create wheel for scripts generated with bazel <code>py_binary</code> rule, and encountered some problem.</p> <p>I try to give a minor example of the problem. I have a directory like this:</p> <pre><code>. ├── MANIFEST.in ├── bin │ ├── __init__.py │ ├── mytest │ └── mytest.lib │ ├── used1 │ ...
<python><setuptools><python-wheel><distribute>
2023-09-14 05:26:23
1
336
XuanInsr
77,101,989
9,681,645
How to run Flet app without Flutter for mobile
<p>I discovered that Flet app runs on desktop (linux) without the needs of flutter. I want to know if there is anyway to package or run Flet app without Flutter on Android or iOS.</p> <pre><code>import flet as ft def main(page: ft.Page): page.add(ft.Text(&quot;Hello World!&quot;) ft.app(target=main) </code></pre...
<python><flutter><mobile><flet>
2023-09-14 05:23:18
1
709
ganiular
77,101,602
3,228,800
Is there a way to find all models that contain a GenericRelation to a particular model in Django?
<p>Lets say we have the following model with a <code>GenericForeignKey</code></p> <pre><code>class Comment(models.Model): customer_visible = models.BooleanField(default=False) comment = models.TextField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.Positive...
<python><python-3.x><django><reflection>
2023-09-14 03:28:07
1
567
Kylelem62
77,101,575
3,400,316
Python 3.10 type hinting for decorator to be used in a method
<p>I'm trying to use <code>typing.Concatenate</code> alongside <code>typing.ParamSpec</code> to type hint a decorator to be used by the methods of a class. The decorator simply receives flags and only runs if the class has that flag as a member. Code shown below:</p> <pre><code>import enum from typing import Callable...
<python><decorator><mypy><typing>
2023-09-14 03:17:27
1
795
Coxy
77,101,344
22,371,917
selenium headless not functioning with buttons properly
<p>I have some code to open a search url for a site, click the first result, and click a button. This all works fine until I try to use headless Chrome.</p> <p>Code (working -&gt; not using headless Chrome):</p> <pre class="lang-py prettyprint-override"><code>from selenium import webdriver from selenium.webdriver.commo...
<python><selenium-webdriver><selenium-chromedriver><headless><google-chrome-headless>
2023-09-14 01:49:57
1
347
Caiden
77,101,323
11,107,192
Debugging azure python durable function on vscode
<p>I have faithfully followed <a href="https://learn.microsoft.com/en-us/azure/azure-functions/durable/quickstart-python-vscode?tabs=linux%2Cazure-cli-set-indexing-flag&amp;pivots=python-mode-configuration" rel="nofollow noreferrer">this tutorial</a> on how to create a python durable function and everything went well.<...
<python><azure><visual-studio-code><vscode-debugger>
2023-09-14 01:42:03
1
717
basquiatraphaeu
77,101,303
10,132,474
python asyncio is much slower than threads when reading files from hard disk
<p>There are about 1M images, I need to read them and insert the bytes into redis with python. I have two choices, the first is to use a thread pool, and the second is to use asyncio, since this is only IO task. However, I find out that the thread pool method is much faster than asyncio method. A piece of example code ...
<python><io><python-asyncio>
2023-09-14 01:35:22
2
1,147
coin cheung
77,101,296
1,445,660
"ENOTEMPTY: directory not empty" when running 'cdk deploy'
<p>I have this error when I run <code>cdk deploy</code>. How can I know what causes this?</p> <pre><code>node:internal/fs/rimraf:202 throw err; ^ Error: ENOTEMPTY: directory not empty, rmdir '\\?\C:\Users\ro\AppData\Local\Temp\jsii-kernel-WYBhQW\node_modules\@aws-cdk\asset-kubectl-v20\layer' at Object....
<python><python-3.x><amazon-web-services><aws-cloudformation><aws-cdk>
2023-09-14 01:33:48
0
1,396
Rony Tesler
77,101,287
3,387,716
Python - wild grouping of friends
<p>I generated a <code>dict</code> with about 60×10<sup>6</sup> elements:</p> <pre class="lang-py prettyprint-override"><code>friends = { 'aaron': {'john'}, 'bob': {'john'}, 'amy': {'gael', 'joe'}, 'gael': {'amy'}, 'joe': {'amy', 'patrick'}, 'john': {'aaron', 'bob'}, 'patrick': {'joe'} } </c...
<python><set>
2023-09-14 01:30:20
2
17,608
Fravadona
77,101,265
8,471,995
python yaml save and load a nested class
<p>I have a nested class:</p> <pre class="lang-py prettyprint-override"><code># hello.py import pydantic as dan class Hello: @dan.dataclasses.dataclass class Data: data_a: int import yaml data = Hello.Data(1) filename = &quot;hi.yaml&quot; with open(filename, &quot;w&quot;) as fh: yaml.dump(data,...
<python><yaml>
2023-09-14 01:20:27
2
1,617
Inyoung Kim 김인영
77,101,068
3,260,052
PySpark - How to filter dates with OR clause?
<p>I need to create a PySpark script that, among other conditions and filters, queries a given table to look for rows either after a given date OR another. This is how my code looks:</p> <pre class="lang-py prettyprint-override"><code>#imports from pyspark.sql import HiveContext from pyspark.sql.functions import col, c...
<python><python-3.x><pyspark>
2023-09-13 23:56:40
1
1,305
Marcos Guimaraes
77,100,962
8,942,319
Which is best for defining a complex type: CustomType(TypedDict) or CustomType = NewType(...)?
<pre><code>from typing import TypedDict class CustomType(TypedDict): id: str path: str targets: list[str] </code></pre> <p>or</p> <pre><code>from typing import NewType CustomType = NewType(&quot;CustomType&quot;, dict[str, str, list[str]]) </code></pre> <p>Looks like in either case I can use <code>CustomT...
<python><python-typing>
2023-09-13 23:08:11
1
913
sam
77,100,890
8,145,356
Pydantic v2 custom type validators with info
<p>I'm trying to update my code to pydantic v2 and having trouble finding a good way to replicate the custom types I had in version 1. I'll use my custom date type as an example. The original implementation and usage looked something like this:</p> <pre><code>from datetime import date from pydantic import BaseModel c...
<python><python-3.x><pydantic>
2023-09-13 22:43:56
3
1,191
hamdog
77,100,877
3,842,845
How to select certain columns and rows based on keyword in column1?
<p>I am trying to extract/select the bottom two areas (blues) based on the values in column1.</p> <p>The data is in a CSV file.</p> <pre><code>Case1 Not Started: 12 Sent: 3 Completed: 3 Division Community ResidentName Date DocumentStatus Last Update Test Station Jane Doe 9/6/202...
<python><pandas>
2023-09-13 22:41:34
2
1,324
Java
77,100,832
643,357
conda install <package> in a read-only multiuser miniconda setup results in an orphaned package installation
<p>I admin in a computer science department where hundreds of users with limited filesystem usage quotas are trying to set up conda environments for various computational tasks. So I've been experimenting with setting up multi-user miniconda environments on shared storage in an attempt to get at least the package insta...
<python><anaconda><conda><miniconda>
2023-09-13 22:27:03
1
919
pgoetz
77,100,651
13,457,123
How to find confidence Yolo V8
<p>I trained a model to detect traffic lights and classify thier color, <code>[red,green,yellow,off]</code>.</p> <p>I want to only display the lights with a confidence above 50%, but I cant figure out how to do that with yolo v8. Ive tried using <code>.conf</code> and <code>.prob</code> as the documentation states but ...
<python><machine-learning><computer-vision><yolo><yolov8>
2023-09-13 21:40:28
1
598
Stephan Yazvinski
77,100,616
12,133,280
Using odeint on multidimensional array
<p>I would like to apply odeint to an array of initial conditions and return a derivative that has the same size as those initial conditions. I could loop over each initial condition, but I think that will be very slow with higher N. The example below is from the <a href="https://docs.scipy.org/doc/scipy/reference/gene...
<python><numpy><scipy><differential-equations><odeint>
2023-09-13 21:31:02
2
447
pasnik
77,100,598
993,812
Percentage Monthly Data
<p>I've got some volume data on a daily level with a type column.</p> <pre><code> Day Type Volume 0 20230101 0 -23336.289 1 20230101 1 2930009.848 2 20230101 2 -2906673.559 3 20230102 0 7377.021 4 20230102 1 2892521.704 5 2023...
<python><pandas>
2023-09-13 21:27:57
4
555
John
77,100,467
1,659,599
FontFamily in music21 lyrics
<p>Is it possible to change the FontFamily of the lyrics of a note or a chord?</p> <p>I've tried <code>style.fontFamily</code> on <code>Lyric</code> but no success.</p> <p>With <code>TextBox</code> class I can change the fontFamily. But I cannot tell music21 to display the <code>TextBox</code> aligned with the note or ...
<python><music21>
2023-09-13 21:00:38
1
7,359
wolfrevo
77,100,435
2,954,839
Re-usable Utility Methods in Digital Ocean Functions in Python
<p>I would like to be able to re-use code across multiple Digital Ocean Functions (their serverless tool). I do not want to publish a library if I can avoid it.</p> <p>I have tried a couple of approaches, but am willing to do about anything to get this to work.</p> <h2>Approach 1. Single File</h2> <p>My first attemp...
<python><function><digital-ocean>
2023-09-13 20:54:30
1
445
Dilapidus
77,100,252
1,668,622
How to reliably terminate a process started via asyncssh?
<p>I have the following snippet starting a long-going process locally via ssh:</p> <pre class="lang-py prettyprint-override"><code>from asyncio import gather, run import asyncssh async def listen(stream): async for line in stream: print(line) async def main(): async with asyncssh.connect(&quot;localho...
<python><ssh><multiprocessing><asyncssh>
2023-09-13 20:19:10
0
9,958
frans
77,100,239
13,112,739
Extract multicolumn(?) PDFs in python
<p>I'm trying to write a program to convert multi-page PDFs to plain text in bulk (think many page textbooks). If I run it through <code>PyPDF2</code>, I find issues where if a particular page has 2 columns, it reads incorrectly.</p> <p>The best solution I have found is the use <a href="https://github.com/ocrmypdf/OCRm...
<python><pdf><ocr><pdfbox><text-mining>
2023-09-13 20:16:25
1
616
user760900
77,100,236
13,112,739
Extracting tables in line from PDF
<p>I'm trying to extract text from PDF files in bulk. I found that I can use tabula/camelot for extracting tables, but I'm unsure how I can put them in the appropriate places. The closest I've come is using <code>tabulizer::extract_text()</code> and <code>tabulizer::extract_tables()</code>, and trying to match table te...
<python><python-camelot><tabula-py>
2023-09-13 20:14:59
0
616
user760900
77,100,212
14,293,020
Which layers to use for a Neural Network fit of a strange function?
<p>I am using a neural network to find the best fit of a function that has a step aspect (blue is my real data, orange is the neural network prediction): <a href="https://i.sstatic.net/wmdJq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wmdJq.png" alt="enter image description here" /></a></p> <p>I am n...
<python><keras><deep-learning><neural-network><curve-fitting>
2023-09-13 20:11:40
0
721
Nihilum
77,100,163
11,188,140
Building an array that combines indices and values in pairings
<p>Consider an array <code>a</code> whose rows hold unique values from 0 to 7, and no value matches its own column index.</p> <pre><code>a = np.array([[1, 0, 5, 6, 7, 2, 3, 4], [1, 0, 7, 4, 3, 6, 5, 2], [4, 2, 1, 7, 0, 6, 5, 3]]) </code></pre> <p>I plan to use <code>a</code> to build a new a...
<python><arrays><numpy>
2023-09-13 20:01:36
1
746
user109387
77,100,083
3,646,720
stack 2d density maps along the z axis direction
<p>I know how to do it using contourf, which has an option <code>contourf(X,Y,Z,...,offset=?,zdir=&quot;z&quot;)</code>, see attached figure for illustration.</p> <p>I tried to do something similar for pcolor but couldn't seem to find similar option. My question is is matplotlib capable of stacking 2d density maps? If ...
<python><matplotlib>
2023-09-13 19:44:33
1
375
Rain
77,100,067
7,339,624
Fill the Diagonal of Each Matrix in a 3D numpy Array with a Vector
<p>Having a 3D numpy array, where each 2D slice represents an individual matrix. I'm looking to replace the diagonal elements of every matrix with a specific set of values.</p> <p>For instance, if I have a <code>3x3x3</code> array:</p> <pre><code>array([[[a1, a2, a3], [a4, a5, a6], [a7, a8, a9]], ...
<python><arrays><numpy><matrix><diagonal>
2023-09-13 19:41:21
5
4,337
Peyman
77,100,051
893,254
Python Pandas apply a string splitting function to an index
<p>I have a Pandas DataFrame containing Postcodes and counts. It has been created using <code>value_count</code>.</p> <p>The DataFrame looks like this:</p> <pre><code> count Postcode AL1 1AJ 151 AL1 1AR 36 AL1 1AS 21 AL1 1AT 12 AL1 1AU 11 ... ... YO8 9YD 10 YO8 9YE ...
<python><pandas><dataframe><series>
2023-09-13 19:38:42
1
18,579
user2138149
77,099,997
268,847
Passing a Python union type parameter to a function that expects a non-union type
<p>I have a data type that, because of where the data comes from, has to be flexible. It is a mapping from a string into either a string, an int, or a list of strings. However, when I run the code through the mypy type checker I get an error.</p> <p>Here is an example of the code and the result of running it through <c...
<python><types><mypy>
2023-09-13 19:27:43
0
7,795
rlandster
77,099,956
11,370,582
Filter pandas dataframe for first N unique values per group
<p>I need to filter a large dataset of variables with entries for multiple dates. In this instance I want to keep only data entered on the very first date.</p> <p>For example in the dataset below:</p> <pre><code>dfex = pd.DataFrame({'names':['jim','jim','jim','jim','jim','jim','jim','jim','jim', ...
<python><pandas><dataframe><date><datetime>
2023-09-13 19:21:26
1
904
John Conor
77,099,891
8,869,570
How to properly write a unit test that checks that a path doesn't exist?
<p>I need to write a unit test for a class:</p> <pre><code>import os class my_class: def __init__(self, path): assert os.path.exists(path) </code></pre> <p>I want to write a unit test that intentionally passes an incorrect path. Currently, I have this:</p> <pre><code>def unit_test: non_existent_path = '/non_exi...
<python>
2023-09-13 19:07:59
4
2,328
24n8
77,099,794
1,473,517
Why can't you use bitwise & with numba and uint64?
<p>I have the following MWE:</p> <pre><code>import numba as nb @nb.njit(nb.uint64(nb.uint64)) def popcount(x): b=0 while(x &gt; 0): x &amp;= x - 1 b+=1 return b print(popcount(43)) </code></pre> <p>It fails with:</p> <pre><code>numba.core.errors.TypingError: Failed in nopyth...
<python><numba>
2023-09-13 18:54:07
2
21,513
Simd
77,099,756
2,779,432
list assignment index out of range but range seems to work
<p>I'm using OpenCV to read some pixels from several images and store the pixels in an array of which each index represents a single image, like this:</p> <pre><code>path = os.getcwd() c = 0 for path in os.listdir(path + '\scribbles'): imgs[c] = cv2.imread(str(path),0) index[c] = np.where(imgs[c]!= [0]) c =...
<python>
2023-09-13 18:47:13
1
501
Francesco
77,099,749
1,304,376
Can I change the Anchor of a Path object in pathlib?
<p>I want to process files in a remote share and when I find a file I want, I want to copy it to my local machine. Something like:</p> <pre><code>copy \\remote_server\share\path\to\file.txt d:\path\to\file.txt </code></pre> <p>I could do something like :</p> <pre><code>path_str = '\\remote_server\share\path\to\file.txt...
<python><pathlib>
2023-09-13 18:45:58
1
1,676
Ching Liu
77,099,705
876,375
How do I obtain Django's user password reset URL within Python (i.e., not within a template)
<p>I am generating a variable text in Python where I need to inject the URL for the user to navigate to after they requested password reset. I.e., I am building a string for content of an email and thus cannot use the standard template language <code>{% url 'password_reset_confirm' uidb64=uid token=token %}</code></p> ...
<python><django>
2023-09-13 18:38:03
1
1,123
Lenka Pitonakova
77,099,509
5,440,823
How to use back_populates() in SQLAlchemy with two (or more) foreign keys from same table?
<p>I have three tables: Competitor, Competition and Duel.</p> <pre><code>class Competitor(db.Model): # type: ignore __tablename__ = 'competitors' id_competitor = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), nullable=False) class Duel(db.Model): # type: ig...
<python><postgresql><sqlalchemy><orm><flask-sqlalchemy>
2023-09-13 18:06:45
1
754
dosvarog
77,099,356
5,924,264
Is there an analogous "pass" keyword for attributes like the one for methods?
<p>I want to define a skeleton class (a class that has doesn't yet have the implementations and initializations for the attributes).</p> <p>For methods of the class, I can just use <code>pass</code>, but how do I do something analogous for the attributes?</p> <p>e.g.,</p> <pre><code>class MyClass: def __init__(self):...
<python>
2023-09-13 17:38:35
2
2,502
roulette01
77,099,182
3,808,179
Cannot unpack non-iterable 'datetime.time'
<p>My primary question is: <strong>How can one iterate over a column full of dates?</strong></p> <pre><code># Assume an excel file with one column called 'Time' that contains datetime.time values df = pd.read_excel(&quot;some/file.xls&quot;) for index, time in df['Time']: println(time + &quot; &quot; + index) # OR...
<python><pandas><excel><datetime>
2023-09-13 17:11:12
0
2,267
kristyna
77,099,174
11,277,108
Why will standard scrapy scrape an API but selenium version returns 401 error?
<p>I'm using a selenium driven scrapy scraper to scrape a website to avoid detection as a bot. Within the site are a number of APIs that I can call to get data without downloading a whole page. However, I keep getting a 401 error from the following:</p> <pre><code>import logging from scrapy import Request, Spider, sig...
<python><selenium-webdriver><scrapy>
2023-09-13 17:10:19
0
1,121
Jossy
77,099,117
2,781,105
Pandas groupby to create additional columns from one column
<p>I have a dataframe that contains a date column and a discount value column, as follows:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'date': ['2023-09-01', '2023-09-02', '2023-09-03', '2023-09-04', '2023-09-05', '2023-09-06','2023-09-07', '2023-09-08', '2023-09-09', '2023-09-10'], ...
<python><pandas><dataframe><group-by>
2023-09-13 17:00:50
3
889
jimiclapton
77,099,080
8,248,194
datetime.utcfromtimestamp changing time in python
<p>I have a string representing a datetime (ts). I want to transform it to int and then use <code>datetime.utcfromtimestamp</code> to recover the same datetime:</p> <pre class="lang-py prettyprint-override"><code>ts = '2023-07-10 14:06:22.000 UTC' int_ts = int(datetime.strptime(ts, &quot;%Y-%m-%d %H:%M:%S.%f %Z&quot;)....
<python><datetime><timezone><utc>
2023-09-13 16:54:29
1
2,581
David Masip
77,099,062
9,669,142
Python - curve_fitting doesn't work properly with high x-values
<p>I have four XY-points for which I need to obtain a curve, hence I use <code>scipy.optimize.curve_fit</code>. Looking at the points, I want to use an exponential function. This works for the lower x-values, but not for the higher x-values.</p> <p>The code is the following (you can switch between <code>low_x_values</c...
<python><scipy><curve-fitting>
2023-09-13 16:51:27
1
567
Fish1996
77,098,930
2,015,461
Making comparison between specific columns two dataframes more efficient
<p>I have two datasets, each with a number of email addresses and a record ID. I am comparing the data, finding every record where an email in dataset1 matches a an email for a record in dataset 2.</p> <p>I take the record id's from each dataset, name of the columns that match &amp; values and add them to a dataset tha...
<python><pandas><performance>
2023-09-13 16:31:42
1
1,546
wilson_smyth
77,098,926
2,614,378
Snowflake error - 253003: While putting file(s) there was an error: 'HTTPError('403 Client Error: Forbidden for url
<p>I have the following snowflake code which will basically connect to snowflake cloud after which I try to read local csv file to df and then push df to Snowflake cloud db</p> <pre><code>import pandas as pd # The Snowflake Connector library. import snowflake.connector as snow from snowflake.connector.pandas_tools imp...
<python><python-3.x><snowflake-cloud-data-platform>
2023-09-13 16:30:54
1
1,070
null
77,098,919
12,394,134
Wrapping head around sequential GitHub Actions
<p>I am wanting to run some sequential GitHub Actions. I have a GitHub action for a data cleaning step and then another one to produce some topline reports from these data.</p> <p>My thoughts were, that I could do a process like so.</p> <pre><code>setup.yml --&gt; clean.yml --&gt; topline.yml </code></pre> <p>This is w...
<python><github-actions><python-poetry>
2023-09-13 16:30:13
0
326
Damon C. Roberts
77,098,918
1,955,231
Printing out the OPCODES to which a Python Re is compiled?
<p>Python's <code>re</code> module allows for some compilation of a given regex pattern.</p> <p>For example,</p> <pre><code>import re c = re.compile('(?&lt;=abc)def') </code></pre> <p>How can I print out the code the expression is compiled to? Any links to some documentation about the implementation details would also ...
<python><regex><compilation>
2023-09-13 16:30:05
1
2,051
Agnishom Chattopadhyay
77,098,917
21,395,742
Inbuilt python command to run user input script
<p>Is there a inbuilt command to run user input as python script? e.g.</p> <pre><code>a = 3 command(&quot;Enter command: &quot;) </code></pre> <p>Then when run on terminal:</p> <pre><code>Enter command: print(a) 3 </code></pre>
<python><python-3.x>
2023-09-13 16:29:46
1
845
hehe
77,098,807
8,385,599
Allocating large shared memory leads to "Bus error (core dumped)"
<p>When allocating a large amount of shared memory (60% of total 128GiB RAM, 3GiB used), I got &quot;Bus error (core dumped)&quot; after several seconds and the memory usage went up. But if I allocate normal memory (in <code>b()</code>), it works ok.</p> <pre class="lang-py prettyprint-override"><code>from multiprocess...
<python><linux><shared-memory><coredump>
2023-09-13 16:12:48
1
677
obfish
77,098,690
1,914,781
Insert rows with previous row to keep column value continuously increase
<p>I have some data which missed some value, I need insert fake row with previous row.</p> <p>example:</p> <pre><code>import pandas as pd data = [ [1,'A'], [2,'B'], [3,'C'], [4,'D'], [5,'E'], [7,'G'], [9,'H'], [10,'I'] ] df = pd.DataFrame(data,columns=['v1','v2']) ...
<python><pandas>
2023-09-13 15:56:10
1
9,011
lucky1928
77,098,653
13,040,314
SQLAlchemy: select nested columns
<p>I have following models and associations. AA can have multiple BB i.e AA.bbs is a list of BB. I want to select only few columns from AA and BB i.e name of AA and name, username from BB.</p> <pre><code>aa2cc_association = Table( 'aa2bbassociation', Base.metadata, Column('aa_id', Integer, Forei...
<python><sqlalchemy><orm><foreign-keys>
2023-09-13 15:51:16
1
325
StaticName
77,098,619
16,864,869
Deepcopy of openpyxl workbook object
<p>I was wondering if there's a way to create a deep copy of a workbook object that's created using the <code>load_workbook</code> method.</p> <p>I want to create a process like this (this project will be in a Jypter Notebook):</p> <pre class="lang-py prettyprint-override"><code> #Cell 1 import openpyxl #Cell ...
<python><openpyxl>
2023-09-13 15:47:28
1
1,348
Brian Gonzalez
77,098,480
6,560,267
Polars + Psycopg2: write column of lists to PostgreSQL
<p>I'm trying to write a table that has a column of lists. When writing, I was initially getting an error due to psycopg2 not being able to transform the <code>np.array</code> datatype to a postgre type.</p> <p>After reading <a href="https://stackoverflow.com/questions/39564755/programmingerror-psycopg2-programmingerro...
<python><postgresql><psycopg2><python-polars>
2023-09-13 15:28:02
1
913
Adrian
77,098,444
17,471,060
Disable font colour formatting for negetive values in python Polars generated excel
<p>I would like to disable automatic font colouring of negetive values in polars <code>write_excel</code>. Any tip?</p> <pre><code>import polars as pl import xlsxwriter df2 = pl.DataFrame(data=np.random.randint(-10, 10, 5*3).reshape(-1, 3), schema=['x', 'y', 'z']) with xlsxwriter.Workbook(r'_out_.xlsx') as workbook: ...
<python><python-3.x><python-polars>
2023-09-13 15:23:33
2
344
beta green
77,098,398
18,108,367
Why is executed only one module import instead of 2?
<p>I suppose to have 3 files in the folder <code>project</code> as showed following:</p> <pre><code>project |- module_b.py |- script_B1.py |- script_B2.py </code></pre> <h2>Content of 3 python files</h2> <p>The content of <code>module_b.py</code> is:</p> <pre><code>print(&quot;Inside module_b&quot;) </code></pre> <p...
<python><import><module>
2023-09-13 15:17:16
1
2,658
User051209
77,098,347
9,415,280
UserWarning: Input dict contained keys which did not match any model input. They will be ignored by the model
<p>I try to convert my code to use data.dataset. I'm not far but still have proble with my features and model input layer never seen before I use data.dataset</p> <p>I load a lot of .csv with many columns for features, csv had heather with name string.</p> <p>my simple test code is:</p> <pre><code>import tensorflow as ...
<python><tensorflow><keras><deep-learning><tf.data.dataset>
2023-09-13 15:11:08
1
451
Jonathan Roy
77,098,297
1,479,670
TensorFlow: failure to convert elements of BinaryCrossentropy to Tensor
<p>I´m following an online course for TensorFlow, but one of the examples that works in the video does not work for me (I've checked - there are no typos).</p> <p>I have a feature array <code>X</code> of shape <code>(1000,2)</code> and a label array <code>y</code> of shape <code>(1000,)</code>. Here's the code that fai...
<python><tensorflow>
2023-09-13 15:03:41
0
1,355
user1479670
77,098,140
2,826,892
Reusing detached ORM objects across SQLAlchemy sessions during testing
<p>I'm trying to understand what SQL-Alchemy does to orm objects. They must have some state attached to them I'm not groking. In the below example, <code>test_one</code> will succeed, but <code>test_two</code> will fail because the Employee object will not be added to the session in <code>test_two</code>. Somewhere in ...
<python><sqlalchemy><pytest><flask-sqlalchemy>
2023-09-13 14:43:07
1
924
mikew
77,098,111
4,239,879
QlistWidget won't show in a custom QFrame
<p>I can't get <code>ModMergeFrame</code> frame to show the <code>self.mod_list</code>. I have tried reading the docs and examples, but failed to understand and fix the problem.</p> <p>Below code in <code>ModMergeFrame</code> class works correcty. Displaying the <code>self.mod_list.count()</code> returns 2, as expected...
<python><pyqt6>
2023-09-13 14:38:26
1
2,360
Ivan
77,098,066
1,132,544
Why do I miss rows if I split a dataframe on a condition and the opposite?
<p>I have a dataframe <code>df</code> which I want to split.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Product</th> <th>Category</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>non-food</td> </tr> <tr> <td>B</td> <td>food</td> </tr> <tr> <td>C</td> <td>non-food</td> </tr> <tr> <td>D</...
<python><apache-spark><pyspark><azure-synapse>
2023-09-13 14:31:36
1
2,707
Gerrit
77,097,909
5,379,479
Collect data from side table(s) in wikipedia page(s)
<p>I'm trying to create a python script that can collect information from the side tables in a wikipedia page. For an example see <a href="https://en.wikipedia.org/wiki/Ford_Fusion_(Americas)" rel="nofollow noreferrer">this page</a>. Along the right hand side of the page, there are 3 vertical looking HTML <code>table...
<python><web-scraping><python-requests><wikipedia>
2023-09-13 14:13:36
1
2,138
Jed
77,097,816
1,585,652
Why is my KafkaConsumer stuck in a Joining Group Loop?
<p>I have a KafkaConsumer that is stuck in a &quot;joining group&quot; loop.</p> <p>It's a simple Kafka Python consumer, here is the python script:</p> <pre><code>from kafka import KafkaConsumer import logging import sys root = logging.getLogger('kafka') root.setLevel(logging.INFO) handler = logging.StreamHandler(sys...
<python><apache-kafka><kafka-consumer-api><kafka-python>
2023-09-13 14:01:23
0
1,997
jceddy