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,836,608
1,801,968
Antlr4 compiler PyCharm Plugin produces incorrect Python3 code. Is this a bug or an operator error?
<p>I am compiling the <a href="https://github.com/antlr/grammars-v4/blob/master/antlr/antlr4/examples/CPP14.g4" rel="nofollow noreferrer">https://github.com/antlr/grammars-v4/blob/master/antlr/antlr4/examples/CPP14.g4</a> grammar (I renamed the grammar file to C.g4 and changed the first line in the grammar file to <co...
<python><parsing><pycharm><antlr4>
2024-01-18 02:42:26
1
1,870
P Moran
77,836,541
1,914,781
print dataframe to be used in markdownhere
<p>I would like to print dataframe to markdown and use it in markdownhere.</p> <p>I saw to_markdown() api but the format not work in markdownhere.</p> <p>So I try below code, it works fine:</p> <pre><code>import pandas as pd def dumpmd(df): out = [] out.append(&quot;|&quot;.join(df.columns)) r = [] for...
<python><pandas><markdown>
2024-01-18 02:22:07
2
9,011
lucky1928
77,836,522
7,563,454
Non-blocking thread pool that posts results as soon as they're ready for the main thread to access
<pre><code>import multiprocessing as mp pool = mp.Pool() def calc(i): return i * 2 def done(results): for result in results: print(result) def loop(): pool.map_async(calc, [0, 1, 2, 3], callback = done): while True: loop() </code></pre> <p>I'm using a thread pool setup as described in this s...
<python><python-3.x><multithreading><threadpool><python-multithreading>
2024-01-18 02:15:04
1
1,161
MirceaKitsune
77,836,455
1,107,474
Python global variable within map task isn't incrementing in global scope
<p>Below I have a self-contained Python example demonstrating a thread pool. Each of the three thread calls the function <code>task()</code>.</p> <p>I have a global variable. <code>task()</code> should increment <code>created</code> three times. However, <code>created</code> is always 1, instead of 1, 2, 3.</p> <p>Coul...
<python>
2024-01-18 01:49:41
0
17,534
intrigued_66
77,836,326
9,996,859
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
<p>I have a discord command attempting to integrate Dall-E:</p> <pre><code>import opena9 from Classes import Dalle from PIL import Image, ImageDraw, ImageFont import discord from discord import Message as DiscordMessage, Color import logging from openai import Image from pathlib import Path from typing import Union @...
<python><discord.py>
2024-01-18 01:01:37
0
889
andrewedgar
77,836,174
395,857
How can I add a progress bar/status when creating a vector store with langchain?
<p>Creating a vector store with the Python library <a href="https://github.com/langchain-ai/langchain" rel="noreferrer">langchain</a> may take a while. How can I add a progress bar?</p> <hr /> <p>Example of code where a vector store is created with langchain:</p> <pre><code>import pprint from langchain_community.vector...
<python><progress-bar><langchain><faiss>
2024-01-17 23:59:14
2
84,585
Franck Dernoncourt
77,836,108
23,190,147
Playwright not opening up link
<p>I'm trying to open a certain link using <code>playwright</code>, and I want to scrape the contents of the link. Snippet of code:</p> <pre><code>from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(channel=&quot;msedge&quot;) page = browser.new_page() p...
<python><url><playwright>
2024-01-17 23:29:13
0
450
5rod
77,836,107
3,555,115
Remove Day, Date, year from Timestamp column in dataframe Python
<p>I have a dataframe: df1 =</p> <pre><code>Load sort_begin comp_begin a Mon Jan 15 23:17:58 PST 2024 - b Mon Jan 15 23:17:58 PST 2024 Mon Jan 15 23:23:58 PST 2024 c Mon Jan 15 23:17:58 PST 2024 ...
<python><pandas><dataframe>
2024-01-17 23:29:05
1
750
user3555115
77,836,103
11,357,623
How to tell unit tests where the package library is in GitHub Actions
<p>I have built a python library and I have unit tests running inside GitHub Actions but unit tests are failing for this reason.</p> <pre><code>Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/hostedtoolcache/Python/3.11.7/x64/lib/python3.11/importlib/__init__.py:126: in import_module...
<python><testing><github-actions>
2024-01-17 23:27:49
1
2,180
AppDeveloper
77,836,047
11,147,107
How to create new pandas row at every "\n" instance?
<p>I have a pandas DataFrame as follows:</p> <pre><code>df = pd.DataFrame({'A': ['foo\nbar', 'tre\ndex', 'hello\nworld'], 'B': ['abc', 'def', 'ghi']}) </code></pre> <p>There are 3 rows made of strings (including <code>\n</code> but I'd like to separate the string into two whenever <code>\n</code> app...
<python><pandas><string><dataframe>
2024-01-17 23:11:57
1
335
Luiz Scheuer
77,836,045
11,618,586
indexing periods in a dataset that spans an increasing and decreasing range
<p>I have a dataframe like so:</p> <pre><code>data = {'column1': [1, 2, 3, 4, 5,4,3,2,1,1, 2, 3, 4, 5,4,3,2,1]} df=pd.DataFrame(data) column1 0 1 1 2 2 3 3 4 4 5 5 4 6 3 7 2 8 1 9 1 10 2 11 3 12 4 13 5 14...
<python><python-3.x><pandas><indexing>
2024-01-17 23:11:02
1
1,264
thentangler
77,835,927
19,675,781
How to replace dataframe values based on index statistics
<p>I have a dataframe like this:</p> <pre><code>l1 = [1,2,3,4,5,6,7,8,9,10] l2 = [11,12,13,14,15,16,17,18,19,20] index = ['FORD','GM'] df = pd.DataFrame(l1,l2).reset_index().T df.index = index </code></pre> <p>I want to replace these integer values based on this:</p> <p>For every index, if the value is less than mean-2...
<python><pandas><dataframe><statistics>
2024-01-17 22:35:35
2
357
Yash
77,835,886
2,727,655
Adding Linear layers to Thinc Model Example - Understanding Data Dimensions Through Model Architecture
<p>Trying to learn the inner workings of models trained with Spacy, and Thinc models are it. Looking at <a href="https://colab.research.google.com/github/explosion/thinc/blob/master/examples/02_transformers_tagger_bert.ipynb#scrollTo=EYYyAeLqRc6S" rel="nofollow noreferrer">this tutorial</a> and I'm modifying the model ...
<python><nlp><neural-network><spacy><spacy-transformers>
2024-01-17 22:26:29
1
554
lrthistlethwaite
77,835,777
23,260,297
Convert custom string to date in python
<p>I am reading data in from a csv file and I need to convert 3 columns from strings to dates.</p> <p>The date string are given in this format, where the day is first, then the month abbreviation and then the year abbreviated:</p> <pre><code>01Aug23 02Dec22 03Jan24 </code></pre> <p>I have tried the following, but it le...
<python><pandas>
2024-01-17 22:01:43
0
2,185
iBeMeltin
77,835,699
963,319
How to use kfold to train model in scikit-learn
<p>I expected the <code>kfold</code> object to have a <code>fit</code> function attached to just like <code>GridSearchCV</code>:</p> <pre><code>spipe = Pipeline([ ('scale', StandardScaler()), ('model', somemodel()) ]) grid = GridSearchCV( estimator=pipe, cv=4 ) grid.fit(X, Y) </code></pre> <p>But <cod...
<python><scikit-learn>
2024-01-17 21:48:15
1
2,751
Jenia Be Nice Please
77,835,555
3,555,115
Convert column fields to multiple columns and rearrange data in Python Dataframe
<p>I have a python dataframe.</p> <pre><code>df1 Load Instance_name counter_name counter_value 0 A bytes_read 0 0 A bytes_written 90 0 A last_time 1...
<python><pandas><dataframe>
2024-01-17 21:13:54
1
750
user3555115
77,835,519
13,350,341
just: command alias could not be run because just could not find the shell
<p>I'd like to reference some commands I've set up in my <code>justfile</code> to be used in some steps of the CI pipeline (namely in my <code>actions.yaml</code> file) and I'm encountering issues. For personal preference, I'd like <code>just</code> commands to be run on <code>powershell</code> both locally and in the ...
<python><powershell><github-actions><powershell-core><just>
2024-01-17 21:07:30
0
3,157
amiola
77,835,414
2,175,534
Flask Toggle Button
<p>I want to add a toggle button to my page and saw this previous question: <a href="https://stackoverflow.com/questions/51057966/flask-toggle-button-with-dynamic-label">Flask - Toggle button with dynamic label</a>. I did some testing with it and it worked as expected and I was so excited to implement! Then I moved the...
<javascript><python><html><ajax><flask>
2024-01-17 20:43:16
0
1,406
Bob
77,835,393
278,205
Poetry2nix flake build errors because the `poetry2nix.overrides` attribute seems to be missing
<h3>Describe the issue</h3> <p>I'm trying to build the following flake, which apart from the overrides section is verbatim from <a href="https://github.com/nix-community/poetry2nix/blob/master/templates/app/flake.nix" rel="nofollow noreferrer">a templates from poetry2nix's repo</a></p> <pre class="lang-hs prettyprint-o...
<python><python-poetry><nix><nix-flake>
2024-01-17 20:39:10
1
5,297
thepandaatemyface
77,835,127
998,248
Pyright exhaustive check on literal only works for parameter, not properties
<p>This works:</p> <pre class="lang-py prettyprint-override"><code>def test(it: Literal['a', 'b']) -&gt; str: if it == 'a': return 'a' elif it == 'b': return 'b' # No error, exhaustive </code></pre> <p>But this doesn't:</p> <pre class="lang-py prettyprint-override"><code>@dataclass class Foo...
<python><python-typing><pyright>
2024-01-17 19:46:52
1
2,791
Anthony Naddeo
77,835,107
673,600
Converting .ipynb to .py in colab
<p>Is there a simple way to do this? I have a <code>.ipynb</code> file I want to convert to a python module and import it, hence want to make it into a <code>.py</code> file. Is there a way to do it?</p>
<python><google-colaboratory>
2024-01-17 19:43:21
1
6,026
disruptive
77,835,037
2,658,228
Programatically create multiple instances of CustomTkinter Combobox Python
<p>New to python and trying to create an app with <code>customtkinter</code>. The app lets users pick values from different drop-downs and generates codes based on the chosen value.</p> <p>Updated per comment from Mike-SMT:</p> <pre><code>import customtkinter as ctk ctk.set_appearance_mode('light') # define fonts gene...
<python><python-3.x><tkinter><python-class><customtkinter>
2024-01-17 19:29:53
1
2,763
Gautam
77,834,994
5,594,008
Wagtail, register settings singleton
<pre><code>from wagtail.contrib.settings.models import BaseGenericSetting, register_setting @register_setting class Glossary(BaseGenericSetting) ... </code></pre> <p>Is it possible to restrict max number of instances that can be created? Maybe there is some easy way or only overwriting <code>save</code> method</p>...
<python><wagtail>
2024-01-17 19:18:49
1
2,352
Headmaster
77,834,959
673,600
importing python module in colab fails
<p>I'm importing a test function in colab but it's not working as I would expect. I create a simple <code>.py</code> file to test, but I failed to import it despite the fact that I the file can be seen in the path.</p> <pre><code>from google.colab import drive import sys import os drive.mount('/content/drive', force_re...
<python><google-colaboratory>
2024-01-17 19:10:56
1
6,026
disruptive
77,834,850
10,203,572
Parsing stringified array fields when reading csv files with Pandas
<p>I have a csv file dumped from a DataFrame that had array fields, which looks like below:</p> <pre><code>col1,col2,col3 &quot;[454.40145382, 254.9620727, 0.9147141790444601]&quot;,2.1299914162447497,-29.85771596074138 </code></pre> <p>When I read this back with <code>pd.read_csv</code>, col1 is parsed as a string...
<python><pandas><numpy>
2024-01-17 18:53:04
2
1,066
Layman
77,834,781
801,894
How does Python parse `7 in x == True`?
<p>I saw a <a href="https://es.stackoverflow.com/q/611715/349223">question on es.stackoverflow.com</a> in which the author tried to explicitly compare the result of a boolean expression to <code>True</code>.</p> <pre class="lang-python prettyprint-override"><code>if nota in lista1 == True: ... </code></pre> <p>I wa...
<python><operator-precedence>
2024-01-17 18:37:35
0
27,562
Solomon Slow
77,834,659
6,815,248
How to calculate the similarity(0%-99%) of two polylines in Python
<p>Both two polylines contains a set of geo positions(like 38.663610000000006,-121.29237), the total number of position for each polylines are different.</p> <p>How to calculate the similarity(0%-99%) of two polylines in Python?</p>
<python><geometry><compare><polyline>
2024-01-17 18:13:35
1
423
John
77,834,629
14,101,494
Abstract private attributes in Python
<p>In Python &gt;= 3.12, how do I declare private attributes in abstract classes?</p> <p>The following snippet should declare an abstract attribute. Though, from my understanding, this actually forces a getter on non-abstract subclasses (which produces the same behavior):</p> <pre class="lang-py prettyprint-override"><...
<python><python-typing>
2024-01-17 18:08:39
1
414
lsc
77,834,603
1,711,271
Read multiple csv files in a pandas dataframe, in parallel
<p>This question develops on the preceding one:</p> <p><a href="https://stackoverflow.com/q/77832160/1711271">Read multiple csv files in a pandas dataframe</a></p> <p>Basically, I have a set of files like:</p> <p>file 1:</p> <pre><code>&lt;empty line&gt; #----------------------------------------- # foo bar baz #...
<python><pandas><csv><parallel-processing><joblib>
2024-01-17 18:03:34
2
5,726
DeltaIV
77,834,580
9,283,107
PySide / QT Align text in vertical center for QPushButton
<p>How can I vertically align the text in a large font QPushButton? For example this Python code creates a button where the text is not vertically aligned. I have tried everything I can think of to solve it but I can't get it working.</p> <pre><code>from PySide2 import QtCore, QtGui, QtWidgets button = QtWidgets.QPush...
<python><css><qt><fonts><pyside2>
2024-01-17 17:58:21
2
2,501
Frank
77,834,575
2,464,386
Calling `mock.patch` before a `with` statement
<p>Could someone explain why <code>testAAA_with_patch_from_function_outside_with</code> fails, but the other two tests succeed?</p> <pre><code>import unittest from unittest import mock class BBB: def __init__(self, param1, param2): self.param1 = param1 self.param2 = param2 def func1(self): ...
<python><unit-testing><mocking><python-unittest>
2024-01-17 17:57:07
0
31,779
ajb
77,834,447
274,460
Changing a class's base class for unit testing
<p>I've got a class I'm trying to test. It inherits from a base class which has some functionality which is both inconvenient and irrelevant to the testing so I'm trying to replace it for the purpose of the unit test.</p> <p>I've got this far:</p> <pre><code>class Foo: pass class Bar(Foo): def __init__(self):...
<python><python-3.x><class><pytest><metaprogramming>
2024-01-17 17:34:15
1
8,161
Tom
77,834,401
4,243
Setting up a truly non-required subparser with argparse
<p>I'd like my program to allow any string to be passed as an argument, but also to allow subcommands. For example, these would all be valid:</p> <pre><code>$ python argtest.py 'hello world' $ python argtest.py version $ python argtest.py help </code></pre> <p>I do not want users to have to use <code>--</code>, e.g., <...
<python><argparse>
2024-01-17 17:26:00
1
23,762
kristina
77,834,124
4,564,080
Add a new instance variable to a subclass on construction without overriding the parent class's __init__()?
<p>Let's say I have a base class <code>Parent</code> defined as:</p> <pre class="lang-py prettyprint-override"><code>class Parent: def __init__(self, a: int, b: int, c: int, d: int): self.a = a self.b = b self.c = c self.d = d </code></pre> <p>And a class <code>Child</code> which in...
<python>
2024-01-17 16:48:00
1
4,635
KOB
77,834,118
7,060,972
How to properly deploy a Django app while following 12FA?
<p>I am deploying a Django app and I got stuck. I am trying to follow the <a href="https://12factor.net/" rel="nofollow noreferrer">12 factor app</a> principles. Specifically, they state that you should have all your configuration in environment variables. Also, I don't want to have multiple <code>settings.py</code> fi...
<python><django><deployment><cicd><12factor>
2024-01-17 16:46:25
0
706
Dj Sushi
77,834,102
6,421,394
Converting PDF to Markdown in Python with structure preservation
<p>I need to convert a PDF text document to Markdown and maintaining its structure (ie. indexed numbered headers and subheaders should have their correspective number of hashtags # in markdown to keep the same structure tree). I have explored alone <code>PDFMinersix</code> but I am basically extracting text and I don't...
<python><pdf><markdown><document-conversion><pdfminersix>
2024-01-17 16:45:12
1
493
Guido
77,834,002
1,892,308
Django ORM: how to cast geometry to geography in filter?
<p>In my Django project, I have defined a <code>geometry</code> field on one of my model. Its SRID is 4326 (WGS 84).</p> <p>I would like to write with Django ORM a query that will translate to:</p> <pre class="lang-sql prettyprint-override"><code>select * from building where (ST_DWITHIN(shape::geography, ST_Mak...
<python><django><postgis><geodjango>
2024-01-17 16:30:03
0
1,773
Istopopoki
77,833,856
11,864,933
downloading camera snapshot via http url in python
<p>I have NVR from Dahua, and I have access to admin user on this device. Using this account I'm trying to get snapshots from IP cameras, connected to this NVR. According to dahua documentation, to do this, I can use this url link http://Username:Password@IP-Address/cgi-bin/snapshot.cgi?channel=1</p> <p>When i replace ...
<python><http>
2024-01-17 16:06:15
1
318
Mateusz Boruch
77,833,798
3,994,193
Create Azure static web hosting from storage account using Python SDK
<p>I am trying to create the static webhosting for the azure storage account using the python SDK. I am trying to find the examples but not able to find anything.</p> <p>As per SDK we have to use BlobServiceClient to create static hosting. But i am not able to find any code for this <a href="https://github.com/Azure/az...
<python><azure><azure-storage>
2024-01-17 15:57:41
1
390
Sandhu
77,833,712
14,852,106
Odoo 16 / custom website : Pagination problem
<p>I paginated the search result. For the first, query set gives me perfect result , but the pagination set all pages, and I get all data from database by clicking on any page number.</p> <p>Here is my code:</p> <p>This is the controller which I added :</p> <pre><code> class MyCustomWeb(http.Controller): @http....
<python><xml><controller><odoo>
2024-01-17 15:43:55
1
633
K.ju
77,833,627
4,627,471
Why does my PySide6 wizard page have the first button in blue?
<p>Note to reviewers: I concede this may be a dupe, however IMHO it was marked as a dupe of the wrong question. Better would be <a href="https://stackoverflow.com/q/56478207">Why is the first button blue in color when I run the PyQt5 program?</a> as mentioned by @musicamente.</p> <pre><code>import sys from PySide6.Qt...
<python><pyside6>
2024-01-17 15:28:19
0
1,015
Keeely
77,833,511
10,232,932
Visual Studio Code behind a proxy with pip install
<p>I try to install a package behind a company proxy in visual studio code on windows on python.</p> <p>The error I get is:</p> <blockquote> <p>WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', ConnectionResetError(...
<python><pip><proxy>
2024-01-17 15:10:55
0
6,338
PV8
77,833,379
17,307,978
How apply changes on ods file using the library ezodf in python?
<p>I have 2 .ods files :</p> <ul> <li><p>The first is called AppAndroid.ods. This has the heading Application No. Version Category Encryption Interest Comments Counter Each column is separated by a space but in my file this corresponds to different columns. This file lists all previously encountered applications with t...
<python><ods>
2024-01-17 14:54:52
0
439
Louis Chabert
77,833,227
15,897,793
KivyMD Android App crashing because of error in material_resources.py file
<p>I developed a kivyMD app specifically for android which is running great on windows as .py but when converted to apk using ubuntu on windows, its giving an error that:</p> <pre><code>/mnt/c/Users/Ayan/Documents/rackcalculator/.buildozer/android/build-arm64-v8a_armeabi-v7a/build/python-installs/rackcalculator/arm64-v...
<python><android><kivy><kivymd><buildozer>
2024-01-17 14:33:50
1
490
AaYan Yasin
77,833,094
6,884,119
Scrapy carousel categories not extracting
<p>I am trying to scrap a website to get the list of categories from a carousel but it's not working.</p> <p>Below is my code</p> <pre><code>import scrapy class CourtsmuSpider(scrapy.Spider): name = &quot;courtsmu&quot; allowed_domains = [&quot;www.courtsmammouth.mu&quot;] start_urls = [&quot;https://www.c...
<python><python-3.x><web-scraping><xpath><scrapy>
2024-01-17 14:12:39
0
2,243
Mervin Hemaraju
77,832,989
777,377
Sink is not written into delta table in Spark structured streaming
<p>I want to create a streaming job, that reads messages from a folder within TXT files, does the parsing, some processing, and appends the result into one of 3 possible delta tables depending on the parse result. There is a parse_failed table, an unknwon_msgs table, and a parsed_msgs table.</p> <p>Reading is done with...
<python><pyspark><databricks><azure-databricks><spark-structured-streaming>
2024-01-17 13:54:25
0
653
bayerb
77,832,920
5,779,083
How to Efficiently Copy Detectron2 Build Files in a Multi-Stage Docker Build?
<p>I'm working on a application that uses <a href="https://huggingface.co/docs/transformers/model_doc/layoutlmv2" rel="nofollow noreferrer">LayoutMV2 model</a>, which uses Facebook AI’s <a href="https://github.com/facebookresearch/detectron2/" rel="nofollow noreferrer">Detectron2</a> package for its visual backbone. Bo...
<python><docker><python-wheel><nvidia-docker><detectron>
2024-01-17 13:44:54
1
4,782
Tom
77,832,899
7,454,177
Why is this monkeypatch in pytest not working?
<p>As I am switching from Django to FastAPI, I also need to change tests from unittests to pytests. I build a custom TestAPI class and have test cases as methods, which works fine. However I want to override some functions (not dependencies) which are used in the code in one testcase. I tried this, but it doesn't work:...
<python><pytest><fastapi><pytest-mock>
2024-01-17 13:42:13
1
2,126
creyD
77,832,878
3,104,974
Django: Subclassing django.forms.widgets.Media
<p>I want to use a custom javascript widget in my Django 5.0 app. The javascript is not static, but dependant on template variables that I have already successfully attached to the widget as attributes (it's a MultiWidget in case that matters).</p> <p>Since the <a href="https://docs.djangoproject.com/en/4.2/topics/form...
<python><django><dynamic><django-templates><widget>
2024-01-17 13:40:08
0
6,315
ascripter
77,832,803
10,232,932
Avoid nested if function and skip line of codes
<p>I have a combination of functions, the code in python has the following format. In the code i am looping over an SQL Table where I always check a key, which get filled with done, after I run the function. So for example I have the &quot;QUEUE_TEST&quot; table which keys:</p> <pre><code>Key Status A Pending B Pendi...
<python>
2024-01-17 13:28:22
3
6,338
PV8
77,832,724
647,151
(wrong-type-argument markerp nil) during shell-mode PDB tracking
<p>With the built-in <code>python-mode</code> that comes with the standard distribution of Emacs, you can set up a hook so that a PDB session gets <em>tracked</em> when initiating through <code>shell-mode</code>:</p> <pre class="lang-lisp prettyprint-override"><code>(defun my-shell-mode-hook () (add-hook 'comint-o...
<python><emacs>
2024-01-17 13:16:16
0
1,457
malthe
77,832,596
12,890,458
Programmatically click the ok button in ms-word
<p>I am trying to automatically convert pdf files to docx files in python, using (copied from <a href="https://stackoverflow.com/a/63255120/12890458">this</a>):</p> <pre><code>import win32com.client word = win32com.client.Dispatch(&quot;Word.Application&quot;) word.visible = 1 pdfdoc = 'NewDoc.pdf' todocx = 'NewDoc.doc...
<python><ms-word><com><win32com><office-automation>
2024-01-17 12:54:38
1
460
Frank Tap
77,832,460
4,822,772
Converting Matplotlib's filled contour plot (contourf_plot) to GeoJSON
<p>I am working on a project where I have successfully generated filled contour plots using plt.contourf in Matplotlib in a Google Colab environment. Now, I am attempting to convert these filled contour polygons into GeoJSON for seamless integration with Folium.</p> <pre><code>import numpy as np import folium from foli...
<python><polygon><geojson><contour><contourf>
2024-01-17 12:30:54
1
1,718
John Smith
77,832,448
10,944,175
Solve matrix and vector multiplication with parameters instead of values (preferably in python)
<p>I want to look at some vector operations and see which matrix elements go into which vector, e.g. if I define a matrix with elements</p> <pre><code>mat = [[&quot;a11&quot;, &quot;a12&quot;], [&quot;a21&quot;, &quot;a22&quot;]] </code></pre> <p>and a vector</p> <pre><code>vec = [&quot;v1&quot;, &quot;v2&quot;] </code...
<python><numpy><math><sympy>
2024-01-17 12:28:19
1
549
Freya W
77,832,441
4,626,254
How to Execute Oracle SQL Query with Multiple Database Links in Django?
<p>I'm working on a Django project where I need to execute a complex Oracle SQL query that involves multiple database links. I have already configured the database credentials for both databases in my Django settings, but I'm struggling with how to correctly execute a query that fetches data from different databases th...
<python><django><oracle-database><django-database>
2024-01-17 12:27:10
1
5,266
Underoos
77,832,417
3,747,486
Use Python to call SharePoint API get 401 response while I have the token
<p>I have registered my App in Azure with API permission as below:</p> <p><a href="https://i.sstatic.net/gd6XO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gd6XO.png" alt="enter image description here" /></a></p> <p>Here is my python code.</p> <pre><code>import requests from msal import ConfidentialCl...
<python><azure><azure-active-directory><azure-web-app-service><sharepoint-rest-api>
2024-01-17 12:22:37
1
326
Mark
77,832,241
17,471,060
Polars dataframe sorting based on absolute value of a column
<p>I would like to sort a polars dataframe based on absolute value of a column in either ascending or descending order. It is easy to do in <code>Pandas</code>, or using <code>sorted</code> function in python. Let's say I want to sort based on <code>val</code> column in the below dataframe.</p> <pre><code>import numpy ...
<python><dataframe><python-polars>
2024-01-17 11:56:01
2
344
beta green
77,832,227
10,122,822
Pyautogui/win32api scrolling does nothing when called per hotkey
<p>The scroll function on pyautogui doesn't work on my system. I have python <code>3.8.10</code> installed and the latest version of <code>pyautogui</code>. The code I want to run is pretty simple:</p> <pre><code>import pyautogui import keyboard def scroll(): scrollAmount = 100 pyautogui.scroll(scrollAmount) ...
<python><winapi><pyautogui>
2024-01-17 11:54:34
0
748
sirzento
77,832,216
8,076,158
Typing Numba functions using classes and dictionaries
<p>This is a simplified version of my program:</p> <pre><code>import numpy as np from numba import types, typed, njit @njit(signature_or_function=types.unicode_type(types.unicode_type)) def my_func(symbol): return &quot;*&quot; + symbol + &quot;*&quot; @njit def run_numba(symbols): for symbol in symbols: ...
<python><numba>
2024-01-17 11:52:41
2
1,063
GlaceCelery
77,832,160
1,711,271
Read multiple csv files in a pandas dataframe
<p>I have a set of text files like these:</p> <p>file corresponding to ID <code>A</code></p> <pre><code>&lt;empty line&gt; #----------------------------------------- # foo bar baz #----------------------------------------- 0.0120932 1.10166 1.08745 0.0127890 1.10105 1.08773 ...
<python><pandas><csv><row>
2024-01-17 11:42:24
1
5,726
DeltaIV
77,831,986
5,868,293
How to get rows with consecutive dates with groupby in pandas
<p>I have the following pandas dataframe</p> <pre><code>import pandas as pd pd.DataFrame({ 'id': [1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3], 'week': ['2022-W9','2022-W10', '2022-W11', '2022-W15', '2022-W17', '2022-W10','2022-W11', '2022-W15', '2022-W19', '2022-W24', '2022-W1...
<python><pandas>
2024-01-17 11:13:00
1
4,512
quant
77,831,751
3,727,079
How can I merge two dataframes, keeping overlapping values and NaN for other values, using only timestamps from the first dataframe?
<p>I've got two dataframes, one of which is a timestamp, and the other also has timestamps, but has gaps in it. The two dataframes have some overlap in timestamps, and some not. MWE:</p> <p>This code creates the first dataframe:</p> <pre><code>daterange = pd.date_range(start='1/1/2023 09:30:00', end='1/3/2023 09:35:00'...
<python><pandas><dataframe>
2024-01-17 10:38:00
1
399
Allure
77,831,701
13,775,842
save data in a class object with multiprocess python
<p>I am learning multiprocess, and I want to create an array of 20 objects of class and save data to each object with multiprocess.</p> <p>when I try to print the data, the data is empty..</p> <p>Im trying to figure out why it happen but im struggling with knowing what is the problem, because when i run with debug, the...
<python><python-multiprocessing>
2024-01-17 10:28:27
1
483
Meyer Buaharon
77,831,687
6,243,534
How to find valleys and intersections in a distance field?
<p>I have a 2d array representing height. It contains peaks, and then a linear gradient in between the peaks.</p> <p>I am generating the array myself, based on the positions of the peaks. The gradient is simply the distance to the nearest peak. So the resolution of the actual array is higher than that of the posted ima...
<python><geometry><distance><voronoi><delaunay>
2024-01-17 10:26:30
2
306
LangerNZ
77,831,677
6,312,979
Django Weasyprint PDF output into Postgres Database
<p>I am trying to stick a WeasyPrint html PDF into the Model. Using Django.</p> <p>I can generate the PDF file fine.</p> <pre><code>pdf_file = HTML(string=html,base_url=base_url).write_pdf(stylesheets, [css_path],font_config=font_config) </code></pre> <p>Now what is best way to convert the pdf_file output to a format ...
<python><django><pdf><weasyprint>
2024-01-17 10:25:30
1
2,181
diogenes
77,831,497
4,928,212
Pandas merge dataframe with the same columns and one one varying
<p>Probably already asked before, buy I cannot find it even after 30 mins of searching.</p> <p>I have two pandas dataframes with the same columns. The values match except for one column and I want to perform a full outer join, where I get both values if both are there and only one value if one of them is present. There...
<python><pandas><merge><outer-join>
2024-01-17 09:59:50
1
340
mnzl
77,831,408
2,386,113
How to change the default device in cuPy?
<p>I am using cuPy in a python program to perform computations on GPU. My program consists of several functions/classes spread across multiple files.</p> <p>I am using a GPU cluster (NVIDIA V100), consisting of four GPUs.</p> <p>How can I select a particular GPU as the default GPU for the whole program? I found some in...
<python><gpu><cupy>
2024-01-17 09:48:33
2
5,777
skm
77,831,293
1,517,918
How to “template” a registry class that uses __new__ as a factory?
<p>I wrote a class <code>BaseRegistry</code> that uses a classmethod as a decorator to register other classes with a string name in a class attribute dictionary <code>registered</code>.</p> <p>This dictionary is used to return the class associated to the string name given to its <code>__new__</code> method.</p> <p>This...
<python><metaclass>
2024-01-17 09:31:48
3
1,240
PhML
77,831,093
8,356,936
How to do TRY_CAST in Snowpark?
<p>I am doing <code>try_cast</code> as on this column <code>df.select(split(col(&quot;spc_value&quot;),lit(&quot;~&quot;))[0])</code> that has value <code>&quot;1.419000&quot;</code> <a href="https://i.sstatic.net/E8zSl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/E8zSl.png" alt="enter image descripti...
<python><sql><casting><snowflake-cloud-data-platform>
2024-01-17 08:56:26
1
418
axiom
77,830,911
10,353,865
Function which changes a dataframe inplace used to slices of the dataframe
<p>Suppose I have a function which takes as input a dataframe d and which alters the dataframe <strong>inplace</strong>. In the example below the function writes the number 9 to the first two rows.</p> <p>Suppose I wanted to use the same function to achieve the following: (a) write 9 to the first two rows - but only to...
<python><pandas><slice>
2024-01-17 08:25:48
0
702
P.Jo
77,830,728
11,942,410
Python : appened the value of created_date based on the condition
<p>i am trying to write one function which will create a new column called <code>last_created_date</code>, and appened the value in that column as per condition.</p> <p>so this is the data.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>rounded_geo_lat</th> <th>rounded_geo_lng</th> <th>cre...
<python><pandas><dataframe><numpy><numpy-slicing>
2024-01-17 07:54:20
0
326
vish
77,830,589
7,454,513
how to use python jsonpath_ng filter nested data
<p>need to find dict in <code>[]</code> , according specific value , but cannot find. which I hope return value is <code>[{ &quot;uid&quot;: {&quot;type&quot;: &quot;t2&quot;, &quot;id&quot;: &quot;world&quot;}, &quot;attrs&quot;: { &quot;value&quot;: 456 } }]</code></p> <pre><code>import json from jsonpath_ng.ext impo...
<python><json>
2024-01-17 07:26:48
1
683
Relax ZeroC
77,830,587
8,176,763
FastAPI - Swagger UI docs not rendering list array as query parameter
<p>According to the docs it is possible to pass a list of values <a href="https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values" rel="noreferrer">https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values</a> .</p> <p>I hav...
<python><swagger><fastapi><openapi><swagger-ui>
2024-01-17 07:26:18
1
2,459
moth
77,830,492
15,893,581
reconstruct Covariance matrix from dataset generated given that Covariance matrix (using Cholesky factorization)
<p>Recalling that <code>C = L@L.T</code> using <a href="https://scicoding.com/how-to-calculate-cholesky-decomposition-in-python/" rel="nofollow noreferrer">Cholesky</a> factorization, I'm trying to repeat transformations described in <a href="https://blogs.sas.com/content/iml/2012/02/08/use-the-cholesky-transformation-...
<python><matrix-factorization><covariance-matrix>
2024-01-17 07:04:51
1
645
JeeyCi
77,830,306
16,798,185
newSession from a Parent Session
<p>When we create new session using <code>newSession()</code>, would the new session inherits all config properties set from parent session?</p> <p>As per the <a href="https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.SparkSession.newSession.html" rel="nofollow noreferrer">spark doc</a>, <code>ne...
<python><apache-spark><pyspark>
2024-01-17 06:14:25
1
377
user16798185
77,830,176
3,555,115
Merge two different data frames by same column in Python dataframe
<p>df1 =</p> <pre><code>A ANTS AGE 0 ABC 18 1 ABC 25 3 ABC 24 2 DEF 20 </code></pre> <p>df2 =</p> <pre><code>ANTS LOC ABC WIND DEF FIND </code></pre> <p>My output should be</p> <p>df3 =...
<python><pandas><dataframe>
2024-01-17 05:37:39
0
750
user3555115
77,830,159
1,266,109
What is thresh in this statement?
<p>I am trying to do the equivalent in c++ of some code written in python.</p> <p>In the following link:</p> <p><a href="https://stackoverflow.com/questions/13584586/how-to-automatically-detect-and-crop-individual-sprite-bounds-in-sprite-sheet">How to automatically detect and crop individual sprite bounds in sprite she...
<python><c++><opencv>
2024-01-17 05:32:34
2
21,085
Rahul Iyer
77,830,117
9,501,508
Web Scraping and POST Request Issue: Unable to Retrieve Expected Data
<p>I am currently working on a Python script using the <code>requests</code> library and <code>BeautifulSoup</code> for web scraping. The goal is to retrieve specific information from the website &quot;<a href="https://letmepost.com/check-da-pa" rel="nofollow noreferrer">https://letmepost.com/check-da-pa</a>,&quot; par...
<python><web-scraping><beautifulsoup><python-requests><request>
2024-01-17 05:20:13
1
1,558
Humayun Ahmad Rajib
77,830,094
1,447,953
Python get all sets of N pairs from two lists
<p>This is some kind of elementary task in itertools probably, but my brain is not working today and I can't seem to find it answered here already.</p> <p>Suppose I have two lists with different numbers of elements. Their indices are</p> <pre><code>i1 = list(range(N)) i2 = list(range(M)) </code></pre> <p>for say <code>...
<python><python-itertools>
2024-01-17 05:12:45
2
2,974
Ben Farmer
77,829,919
3,747,241
PyTorch3D file io throws error - AttributeError: _evt
<p>I finally got PyTorch3D to install on my conda environment with the following configuration -- <code>torch=1.13.0</code> and <code>torchvision=0.14.0</code> and <code>pytorch3d=0.7.5</code>.</p> <p>I am trying to load a mesh from an .obj file using pytorch3d.io from <a href="https://pytorch3d.readthedocs.io/en/v0.6....
<python><pytorch><pytorch3d>
2024-01-17 04:08:29
1
1,135
Aditya
77,829,899
2,178,942
legend=False in sns.stripplot rises an error
<p>I am using seaborn's stripplot and pointplot to plot my data (<a href="https://seaborn.pydata.org/generated/seaborn.pointplot.html" rel="nofollow noreferrer">Reference</a>)</p> <p>My code is:</p> <pre><code>sns.set_palette(&quot;Purples&quot;) sns.stripplot( data=df_d_pt, x=&quot;feat&quot;, y=&quot;acc&quot;, ...
<python><python-3.x><matplotlib><seaborn><figure>
2024-01-17 04:00:08
1
1,581
Kadaj13
77,829,697
534,674
How to get sphinx to gracefully ignore 3rd party reference targets in intersphinx mappings
<p>I've run into issues a few times that are solved by <code>intersphinx_mapping</code>, but that can be <a href="https://stackoverflow.com/a/42513684/534674">difficult</a>. I'm also wary of coupling my doc build success to another library's success, especially if I'm in charge of the other library. Is there a way to...
<python><python-sphinx>
2024-01-17 02:34:29
0
1,806
Jake Stevens-Haas
77,829,653
2,998,077
Python, Docx, to replace soft returns (^l or manual line breaks) to hard returns (^p or paragraph marks)
<p>Some Word documents (.docx) that have soft returns (^l or manual line breaks).</p> <p>When counting the number of paragraphs in the document, it shows there is only 1 paragraph (by script below).</p> <p>What is the way to recognize the soft returns (^l or manual line breaks) and replace them to hard returns (^p or p...
<python><docx>
2024-01-17 02:15:26
1
9,496
Mark K
77,829,374
3,734,914
Python Decorator to Cast Class Attributes for MyPy
<p>I have a class that has multiple methods that can only be called if an attribute that may be <code>None</code> is not <code>None</code>. E.g.</p> <pre class="lang-py prettyprint-override"><code>class Connection: def read(self) -&gt; str: return &quot;data&quot; def write(self, data: str) -&gt; N...
<python><mypy><python-decorators><python-typing>
2024-01-17 00:20:29
0
9,017
Batman
77,829,347
7,563,454
Include script in local directory from a dynamic path
<p>I'm working on a game engine intended to support modding, which includes loading a custom mod directory with an init script. I can't find a clear answer as to the best way of dynamically loading a script from a string variable path. The name of the active mod will likely be specified as a script parameter: While I k...
<python><python-3.x>
2024-01-17 00:12:08
1
1,161
MirceaKitsune
77,829,278
12,671,057
Keep list elements with three or more on either side
<p>How can we keep only elements that have three or more elements on either side? For example:</p> <pre><code>[1, 2, 3, 4] =&gt; [1, 4] </code></pre> <ul> <li><p>The <code>1</code> has three elements on its right, so we keep it.</p> </li> <li><p>The <code>2</code> and <code>3</code> each have only one or two elements...
<python><list>
2024-01-16 23:48:17
3
27,959
Kelly Bundy
77,829,130
4,822,772
Folium GeoJson not displaying fill color correctly
<p>I'm working on a project where I need to display GeoJSON data using Folium in Python. I'm facing an issue with the fill color not displaying correctly.</p> <p>I'm using the following code:</p> <pre><code>import folium import requests import json # Load GeoJSON data from the provided URL url = &quot;https://earthqua...
<python><geojson><folium>
2024-01-16 22:56:04
0
1,718
John Smith
77,829,118
4,822,772
Issues with Folium Grid Visualization
<p>I'm working on a grid visualization using Folium and Xarray in Python. The code is designed to display rectangles on a map, representing grid cells with associated wind speeds. The visualization works well when zoomed in, but becomes problematic when zooming out – at certain zoom levels, the rectangles are not visib...
<python><folium>
2024-01-16 22:51:14
1
1,718
John Smith
77,829,091
963,319
How to use cross validation on linear regression model in scikit-learn
<p>I want to use <a href="https://scikit-learn.org/stable/_images/grid_search_cross_validation.png" rel="nofollow noreferrer">grid search cross validation</a> in scikit learn to train the Linear Regression model on lets say 10 folds just like in the image I shared.</p> <p>But when I do that I get:</p> <pre><code>spipe ...
<python><machine-learning><scikit-learn>
2024-01-16 22:44:50
0
2,751
Jenia Be Nice Please
77,828,965
4,398,966
Updating global variables across modules
<p>I'm trying to figure out the best or most pythonic way of updating a global variable across modules. Suppose I have two scripts:</p> <pre class="lang-python prettyprint-override"><code># master.py import functions as ff moves = 0 def main(): update() def update(): global moves moves = moves + 1 ff...
<python>
2024-01-16 22:10:59
0
15,782
DCR
77,828,858
3,555,115
Difference of timestamps from two columns in seconds to a new column
<p>I am very new to python and have a dataframe as strings in each column</p> <pre><code>df1 = A B C 0 23:14:25 23:16:34 90 1 23:14:32 23:19:44 91 </code></pre> <p><strong>I need to generate a new df with difference in timestamps from colu...
<python><pandas><dataframe>
2024-01-16 21:43:11
2
750
user3555115
77,828,849
2,255,757
passing generic python class by reference with type initialized (AttributeError: 'typing.TypeVar' object has no attribute)
<p>This is the pseudo code for what I wish to achieve.</p> <pre><code>class A: @classmethod def run(): print(&quot;lul&quot;) class Test[T](): def run(self): return T.run() t = Test[A]() t = t.run() </code></pre> <p>error:</p> <pre><code>File &quot;.../main.py&quot;, line 13, in test r...
<python><generics>
2024-01-16 21:39:51
0
766
user2255757
77,828,836
67,476
Sqlalchemy query LIKE statement on an Array column
<p>I am having following model and the column skills is of type VARCHAR[] in the Postgres DB</p> <pre><code>class Job(Base): __tablename__ = &quot;jobs&quot; id = Column(BigInteger, primary_key=True) job_title = Column(String) is_remote = Column(String) skills = Column(ARRAY(String)) </code></pre> <...
<python><postgresql><sqlalchemy>
2024-01-16 21:34:58
0
7,961
harshit
77,828,620
3,555,115
get the value after a search string in python
<p>I need to retrieve the values from logs that contain the lines in similar below format as My input line looks like this:</p> <pre><code>line = &quot;(last_bytes wrote 66560002, cur_bytes read 33280206, curr_bytes wrote 66560002, blks read 103335128)&quot; </code></pre> <p>I need to get the value based on my sea...
<python><string><split>
2024-01-16 20:43:39
4
750
user3555115
77,828,618
8,416,255
Should I use Multithreading or Async IO to speed up a network bound task?
<p>I have a python function that SSHs into a device, runs some commands and uses the data to make HTTP calls. I want to make <code>migrate_devices</code> run in parallel when processing the devices.</p> <p>Existing function, simplified:</p> <pre class="lang-py prettyprint-override"><code>def migrate_devices(devices: Li...
<python><python-3.x><multithreading><async-await><python-asyncio>
2024-01-16 20:43:11
0
409
rsn
77,828,534
2,651,073
How to concat two dataframes with interleaved rows sorted by a column of the first dataframe
<p>Suppose I have two dataframes:</p> <pre><code>&gt;&gt; df1 X Y avg id f g 30 3 a b 20 1 d e 10 2 &gt;&gt; df2 X Y avg id D E 10 2 A B 0 1 F G 20 3 </code></pre> <p><code>df1</code> is sorted by <code>avg</code> column. I want to concat them so that put corres...
<python><pandas><dataframe>
2024-01-16 20:22:10
2
9,816
Ahmad
77,828,507
2,142,728
How to bundle my monorepo poetry subproject into an executable?
<p>I have a monorepo with multiple poetry projects.</p> <p>They may depend on each other with the usual path dependencies of poetry (i.e <code>{path='../some-lib',develop=true}</code>).</p> <p>During development everything works ok (not like a charm, but ok).</p> <p>When bundling it all, I assume dependencies must be c...
<python><docker><monorepo><python-poetry>
2024-01-16 20:17:44
0
3,774
caeus
77,828,490
12,318,454
Use latest version of SQLite for Python in ubuntu-latest
<p>I have created a GitHub Actions workflow. which is supposed to run a SQL query. It uses the <a href="https://www.sqlite.org/json1.html#jptr:%7E:text=4.9.-,The%20%2D%3E%20and%20%2D%3E%3E%20operators,-Beginning%20with%20SQLite" rel="nofollow noreferrer">arrow operators</a> for JSON. This requires SQLite &gt;= 3.38.0.<...
<python><sqlite><github-actions>
2024-01-16 20:11:26
1
553
Rahul A Ranger
77,828,286
4,352,930
Matplotlib eventplot without space between events
<p>I want to create a matplotlib event plot of integers with two colours. A position in the eventplot can be white (no event) or have a colour (red or green, which means there is an event).</p> <p><a href="https://i.sstatic.net/H5Kjc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/H5Kjc.png" alt="enter i...
<python><matplotlib>
2024-01-16 19:31:23
1
6,259
tfv
77,828,272
6,936,582
Column with lists of dicts to new columns
<p>I have a dataframe with a <code>column2</code> which for each row have a list of dicts.</p> <pre><code>import pandas as pd data = [{&quot;id&quot;:1, &quot;column1&quot;:123, &quot;column2&quot;:[{&quot;a&quot;:1}, {&quot;b&quot;:&quot;X&quot;}, {&quot;c&quot;:'2023-01-16'}]}] df = pd.DataFrame(d...
<python><pandas>
2024-01-16 19:27:31
1
2,220
Bera