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,695,727
1,947,961
Write data from hadoop file into dbf using pyspark is time consuming
<p>We've requirement to query the data in our hadoop (hive) and save it into a dbf file. To achieve that we use spark as our processing engine especially pyspark (python 3.4). We use dbf package as package dbf writer, <a href="https://pypi.org/project/dbf/" rel="nofollow noreferrer">https://pypi.org/project/dbf/</a> Af...
<python><multithreading><pyspark><hive><dbf>
2023-12-21 04:16:19
1
418
m hanif f
77,695,724
690,573
How can I make add type annotations to this Python code that dynamically assigns attributes to a class?
<p>I have the following Python code that dynamically imports a module and sets an attribute on a class dynamically:</p> <pre class="lang-py prettyprint-override"><code>class _ModuleRegistry(object): _modules = {} def defer_import( self, import_statement: str, import_name: str, ): ...
<python><mypy><typing>
2023-12-21 04:15:20
1
5,214
Nathan Jones
77,695,718
3,469,243
How to read in report-style excel data into pandas dataframe
<p>I've downloaded the data (from <a href="https://www.nalpdirectory.com/" rel="nofollow noreferrer">https://www.nalpdirectory.com/</a>) as seen in this excel screen shot:</p> <p><a href="https://i.sstatic.net/HiaVL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HiaVL.png" alt="enter image description h...
<python><pandas><excel><dataframe>
2023-12-21 04:12:55
1
2,486
As3adTintin
77,695,665
1,236,858
Strict-Transport-Security response header always gets overridden
<p>I have an application that uses Python (FastAPI). In the python code, I have this <code>Strict-Transport-Security</code> set</p> <pre><code>application.add_middleware(HSTS, Option={'max-age': 31536000, 'includeSubDomains': True }) </code></pre> <p>When I try using Postman to my local, it returns the value correctly ...
<python><https><fastapi><hsts>
2023-12-21 03:54:35
0
7,307
rcs
77,695,581
5,120,376
How to select a single column from the index of a multi-index dataframe?
<p>I am having trouble getting a column from the indexes of a multi-index pandas dataframe.</p> <p>Normally if I want to get a column from a regular dataframe that does not have multi-index it is easy. I simply do df['col_name'] or df.col_name and I get the column. However with a multi-index dataframe this does not wor...
<python><pandas><dataframe>
2023-12-21 03:22:18
2
552
liyuan
77,695,324
1,019,139
How do I get Python BRISQUE package score to match OpenCVSharp BRISQUE score
<p>My goal is to get the BRISQUE score from OpenCVSharp to match the BRISQUE score from Python OpenCV BRISQUE for the same image. The problem is the two platforms take different and incompatible format inputs for the model and range files, and I haven't been able to figure out how to convert one to the other. OR wher...
<python><c#><opencv><image-quality>
2023-12-21 01:40:29
0
447
Matt
77,695,152
1,964,707
How to configure pandas.read_sql() when using SQLalchemy models with bind_key
<p>I'm using the following model sqlalchemy ORM (flask-sqlalchemy to be precise) with a table/model Result that is stored in a secondary sqlite database, to bind which the <strong>__bind_key__</strong> mechanism is used. The definition is similar to this (fields omitted):</p> <pre><code>class Result(db.Model): __bind...
<python><sqlalchemy><flask-sqlalchemy>
2023-12-21 00:27:46
0
3,909
Mindaugas Bernatavičius
77,695,145
2,687,635
AWS Glue shuffles columns when writing to Snowflake
<p>When writing a dynamic frame from AWS Glue to an existing Snowflake table, my data gets shuffled into other columns.</p> <p>For example: Writing this dataframe with the code below...</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> ...
<python><amazon-web-services><snowflake-cloud-data-platform><aws-glue>
2023-12-21 00:25:47
0
2,236
MyJBMe
77,695,141
338,825
Check numpy array changes sign or stays the same sign
<p>I have a 2d array. I want to check whether starting from left to right, the columns in the array change sign, or they stay the same sign. If they do change sign, I want to assign negative if they go positive and then negative, and vice versa assign positive, if they go negative then positive. If they remain only pos...
<python><numpy>
2023-12-21 00:23:57
1
24,204
siamii
77,695,028
5,597,541
How can I make a class variable unique
<p>This is a sample code:</p> <pre><code>from PySide2.QtCore import Signal class MyClass: pass class PSClass(QObject): onRequest = Signal(str) onMySignal = MyClass() def __init__(self): super().__init__() self.onRequest.connect(self.printSomething) def send(self, message:str): ...
<python><python-3.x>
2023-12-20 23:44:49
1
572
Bear
77,694,942
2,299,692
create_csv_agent from langchain creates sample data frame instead of using the one provided
<p>I am using langchain version '0.0.350'. I am using a sample small csv file with 101 rows to test create_csv_agent.</p> <p>The file has the column Customer with 101 unique names from Cust1 to Cust101. The agent correctly identifies that the data contains 101 rows.</p> <p>But when I ask the agent to return the unique ...
<python><pandas><csv><agent><langchain>
2023-12-20 23:12:45
1
1,938
David Makovoz
77,694,879
11,781,149
How to avoid the error 404 (Not found) using pandas read_html in Python
<p>I am trying to obtain the market capitalization of the AVY stock through Yahoo Finance using the function read_html() of pandas. I am finding problems with some stock symbols but not with others. For example, if I use the below code, I can get the Market Value of the stock AAPL correctly:</p> <pre><code>import panda...
<python><pandas>
2023-12-20 22:53:51
2
523
Martingale
77,694,820
20,122,390
How can I implement retry policy with httpx in Python?
<p>I need to communicate with other services in my Python and FastAPI application, therefore I use the httpx library to be able to communicate asynchronously. So, I have the following code for POST requests:</p> <pre><code>from typing import Any, Dict, Optional, Tuple from fastapi import File from httpx._client import...
<python><rest><request><httpx>
2023-12-20 22:33:51
2
988
Diego L
77,694,664
293,995
Get Parent object from child object in Python 3.10
<p>I have a child and parent class. I want to get the parent object from the child object.</p> <pre><code>class A: def __init__(self, property1): self.property1 = property1 class B(A): def __init__(self, property1, property2): super().__init__(property1) self.property2 = property2 ...
<python><python-3.x><oop>
2023-12-20 21:48:08
1
2,631
hotips
77,694,453
2,633,704
postgres SSL SYSCALL error: EOF detected in python code
<p>I have the below code for connecting to all kinds of databases I need in my project:</p> <pre><code>import sqlalchemy as db from clickhouse_driver import Client from clickhouse_connect import get_client from sqlalchemy.orm import create_session from src.data.connection import ConectionInfo import psycopg2 import ma...
<python><postgresql>
2023-12-20 21:01:56
0
990
MarziehSepehr
77,694,383
4,398,966
running python from cmd
<p>I have python installed through anaconda and have it running in spyder. Is there a way to run python from a command shell (cmd) using the installed version from spyder or do I need to install python through the Microsoft store? Is there an environment variable that I need to set?</p>
<python><windows><installation><anaconda>
2023-12-20 20:47:37
0
15,782
DCR
77,694,368
284,932
A fine-tuned Llama2-chat model can’t answer questions from the dataset
<p>I've fined tuned llama2-chat using this dataset: <a href="https://huggingface.co/datasets/celsowm/guanaco-llama2-1k1" rel="nofollow noreferrer">celsowm/guanaco-llama2-1k1</a></p> <p>It's basically a fork with an additional question:</p> <blockquote> <p><code>&lt;s&gt;[INST] Who is Mosantos? [/INST] Mosantos is vilar...
<python><huggingface-transformers><llama>
2023-12-20 20:44:46
1
474
celsowm
77,694,277
5,947,365
Django Schema Reverse Related Objects
<p>I have the following two Django models:</p> <pre><code>class Participant(models.Model): name = models.TextField() sport = models.TextField() bookmaker = models.ForeignKey(Bookmaker, on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_...
<python><django><orm><django-ninja>
2023-12-20 20:24:08
1
607
Sander Bakker
77,694,123
14,245,686
When to know if Python parallelism is enough?
<p>I know a little bit about the basics of Python parallelism (CPU-bound, use multiprocessing, IO-bound, use threads), but I am wondering what the best way to parallelize functions that spend almost all of their time in library code. My specific use case is parallelizing training thousands of XGBoost models. Importantl...
<python><c><multithreading><multiprocessing><xgboost>
2023-12-20 19:55:14
2
482
stressed
77,693,922
4,542,117
python - bz2 not recompressing properly
<p>The following code is able to read in a bzipped file:</p> <pre><code>offset = 24 # Open the object fobj = open(filey,'rb') # Read the data buffer = fobj.read() # Apply bz2 compression buffer_unbzip,places_to_bzip = bzip_blocks_decompress_all(buffer,offset) </code></pre> <p>where the bzip_blocks_decompress_all fun...
<python><hex><byte><bz2>
2023-12-20 19:08:26
1
374
Miss_Orchid
77,693,886
5,287,011
The use of >> operator in a logical construct with Gurobi
<p>I am going through someone else's code (optimization using Gurobi) and I am puzzled:</p> <pre><code>x = model.addVars(A, vtype=GRB.BINARY, name=['x_'+str(i)+'_'+str(j) for i in V for j in V if i != j]) u1 = model.addVars(N, vtype=GRB.CONTINUOUS, name=[&quot;Dummy_Quantity_&quot;+str(i) for i in N]) u2 = mode...
<python><if-statement><constraints><gurobi>
2023-12-20 19:01:01
2
3,209
Toly
77,693,879
7,926,069
How can I install python3-dev for armhf using debian multiarch
<p>I have been going in circles trying to install this package as it is a dependency I need for something else (<code>libboost-all-dev:armhf</code>).</p> <p>I have added <code>armhf</code> architecture and installed <code>python3:armhf</code> just fine. However, whenever I try to install <code>python3-dev:armhf</code>,...
<python><multiarch>
2023-12-20 18:59:02
0
988
itsLydt
77,693,837
6,457,407
Specifying C compiler for setup.py compilation
<p>Is there something I can do, (either by setting an environment variable, running a command before running Python, or adding some code to my <code>setup.py</code>) to tell Python I want <code>setup.py</code> to use a different version of the compiler.</p> <p>I can see that <code>distutils</code> on this Windows machi...
<python><visual-studio><github><distutils>
2023-12-20 18:48:48
0
11,605
Frank Yellin
77,693,813
7,077,532
Populate NaN cells in dataframe table based on reference table based on specific row(s) and column values
<p>I have two tables. The first reference table is below:</p> <pre><code>| Name | Target | Bonus | |------|--------:|------:| | Joe | 40 | 46 | | Phil | 38 | 42 | | Dean | 65 | 70 | </code></pre> <p>The Python code to generate the table is:</p> <pre><code># Data for the table data = { 'Na...
<python><pandas><dataframe><lookup><fillna>
2023-12-20 18:42:06
4
5,244
PineNuts0
77,693,646
2,714,301
How to write to a file in batches in python performantly. Anything else I need?
<p>I am trying to move a large amount of data around and I read I can use a couple libraries in python to speed things up.</p> <ol> <li>generators</li> <li>itertools.islice</li> <li>multiprocessing</li> </ol> <p>Here is some code, generically, that I intend to expand on. Is this the right path:</p> <pre><code>import mu...
<python><file-writing>
2023-12-20 18:08:29
0
11,747
Jwan622
77,693,566
16,852,890
Dynamically create eval condition in python
<p>I've got a list with n elements, let's say there are 3 for example:</p> <pre><code>[Condition1, Condition2, Condition3] </code></pre> <p>I want to build up a string which looks like this, in the order that appears in the list (that order is vital!):</p> <pre><code>eval(Condition1).otherwise(eval(Condition2).otherwis...
<python>
2023-12-20 17:52:54
1
316
tommyhmt
77,693,508
3,383,640
How to Export OSM Maps / Plots Into Vector Graphics Using Python Plotly
<p>Taking <a href="https://plotly.com/python/mapbox-layers/" rel="nofollow noreferrer">this example from the manual</a>,</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd us_cities = pd.read_csv(&quot;https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv&quot;) import plot...
<python><plotly><vector-graphics>
2023-12-20 17:39:55
1
5,078
Suuuehgi
77,693,477
8,456,253
Defining two foreign keys in one entity targeting one other entity in SQLAlchemy
<p>I have the entities set up as follows</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import ForeignKey from sqlalchemy.orm import mapped_column, relationship, Mapped, DeclarativeBase class Base(DeclarativeBase): pass class UserEntity(Base): __tablename__ = &quot;user&quot; id: Map...
<python><sqlalchemy><orm>
2023-12-20 17:35:40
1
830
kuco 23
77,693,446
11,901,834
Conditonal tasks in Airflow
<p>I have an Airflow DAG that has two tasks that I only want to run if certain conditions are met. If these conditions aren't met, I'd like them skipped.</p> <p>The DAG looks like this:</p> <pre><code>@dag( dag_id=&quot;id_123&quot;, schedule=DAG_SCHEDULE, start_date=days_ago(0), catchup=False, defa...
<python><airflow>
2023-12-20 17:30:28
1
1,579
nimgwfc
77,693,163
2,650,325
scrapy stops crawling with 500 Internal Server Error
<p>I am crawling a web with scrapy and I receive the error:</p> <pre><code>Gave up retrying &lt;GET https://www.something.net&gt; (failed 3 times): 500 Internal Server Error </code></pre> <p>even though in the parse method I have added this parameter to the meta of the <code>scrapy.Request</code> that calls the parse f...
<python><scrapy>
2023-12-20 16:39:04
1
2,417
Manuel Perez Heredia
77,693,044
12,633,371
transform a string representing a list in each cell of a polars DataFrame column to an actual list
<p>I am new to polars library and the title says it all regarding what I am trying to do.</p> <p>Doing this with the pandas library I would use <code>apply()</code> and the build in <code>eval()</code> function of Python. since <code>eval(&quot;[1,2,3]&quot;)</code> returns <code>[1,2,3]</code>.</p> <p>This can be done...
<python><python-polars>
2023-12-20 16:18:29
1
603
exch_cmmnt_memb
77,692,997
1,492,613
Is there any configuration can force initalize the NumPy module during import pytorch?
<p>I have things like</p> <pre><code>python3.11/site-packages/torch/nn/modules/transformer.py:20: UserWarning: Failed to initialize NumPy: module compiled against API version 0x10 but this version of numpy is 0xf (Triggered internally at ../torch/csrc/utils/tensor_numpy.cpp:84.) </code></pre> <p>But I definitely need t...
<python><numpy><pytorch>
2023-12-20 16:11:02
1
8,402
Wang
77,692,945
5,775,358
xarray plot sparse data
<p>Xarray uses pcolormesh for plotting. For example 2D data, but where 1 axes is not continuous pcolormesh will interpolate values. The nice thing from xarray is that it is &quot;coordinate aware&quot;, i.e. it does not just plot like imshow but the real dimensions are used.</p> <pre><code>import numpy as np import xar...
<python><plot><mask><python-xarray>
2023-12-20 16:01:23
0
2,406
3dSpatialUser
77,692,927
3,785,430
What is the best way for large data movement task
<p>I am working on a solution that downloads the files from a third party service and need to upload those files into aws s3. I need to download 1year of data and upload to s3.</p> <ul> <li>for each day no of files are 10K to 15K</li> <li>Download each file and upload to s3</li> <li>add a metadata record in db for futu...
<python><amazon-s3><multiprocessing>
2023-12-20 15:59:14
0
413
kishore
77,692,872
9,311,137
Pandas: Use first layer of nested dict as columns then the inner dict as rows
<p>I'm after creating a table that looks like the below from a 2-layer nested dictionary:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Day</th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> </thead> <tbody> <tr> <td>mon</td> <td>11,791</td> <td>22,099</td> <td>7...
<python><pandas><dictionary>
2023-12-20 15:52:02
1
684
ch4rl1e97
77,692,864
1,961,574
Django: request from RequestFactory on Windows does not include session attribute
<p>My drone pipeline suddenly started failing on Windows only (the Linux pipeline, executing the same tests, works fine).</p> <p>error:</p> <blockquote> <pre><code>assert hasattr(request, 'session'), &quot;The session-based temporary &quot;\ AssertionError: The session-based temporary message storage </code></pre> <p>r...
<python><django>
2023-12-20 15:50:49
1
2,712
bluppfisk
77,692,665
13,955,154
Find chains of identical elements in ndarray and modify them
<p>I have ndarrays like [1,1,1,1,3,3,3].</p> <p>I want that, if there are consecutive elements with the same value like the case of the example, the content of the identical chain is modified in this way: we calculate delta as the 0.1% of the identical value, subtract it to the first element of the chain and add it to ...
<python><arrays><numpy-ndarray>
2023-12-20 15:18:43
2
720
Lorenzo Cutrupi
77,692,602
16,688,854
Plotly Python - Multiple traces update with slider
<p>I use Plotly Python. I have a list of spectrums I want to plot. This list contains 2d arrays. Each array corresponds to a time frame and contains the spectrums for a certain number of sources (n*m with n number of sources and m length of the spectrums). Here is a dummy version of that list (random values instead of ...
<python><plotly>
2023-12-20 15:09:37
1
337
Antoine101
77,692,566
2,506,946
Using Python's gspread, can I read the modifiedTime without fetching the entire spreadsheet? I want to use a local cache if there was no change
<p>I'm using gspread to load read from my spreadsheets and it's working great. However, I'm hitting Google data caps quite often, especially when I'm testing.</p> <p>I created a caching method that uses a local copy if it is less than a minute old. However, when debugging, I often have to change things in the spreadshe...
<python><google-sheets><google-drive-api><google-sheets-api><gspread>
2023-12-20 15:05:21
1
341
user2506946
77,692,292
19,204,171
tesseract inaccuracy in extracting meaningless words
<p>i can not extract text with reliable accuracy from an image</p> <p><a href="https://i.sstatic.net/RizGs.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RizGs.png" alt="image" /></a></p> <pre><code>import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\t...
<python><ocr><tesseract><python-tesseract><image-preprocessing>
2023-12-20 14:22:53
1
438
mishal shanavas
77,692,284
11,283,324
Pandas dataframe cumsum splited by zero
<p>There is a df:</p> <pre><code>import pandas as pd df = pd.DataFrame([0,0,1,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1], columns = ['A']) </code></pre> <p>How to add a B column, its elements are based on the cumsum of cells in column A value of 1, and if it encounters 0, then cumsum start over.</p> <p>Expected result: <a href="ht...
<python><pandas>
2023-12-20 14:22:06
0
351
Sun Jar
77,692,270
561,243
Change background transparency of AnchoredText in Matplotlib
<p>I'm trying to use an AnchoredText to print some information on an axis in Matplotlib, but I would like to have its background semitransparent (say alpha=0.5).</p> <p>My initial guess was:</p> <pre class="lang-py prettyprint-override"><code> info_box = AnchoredText('test', loc='upper left', prop=dict(size=8, alpha=0....
<python><matplotlib>
2023-12-20 14:19:07
1
367
toto
77,692,187
13,906,951
How to return errors from a Python gRPC interceptor?
<p>How do I check authentication in this interceptor and reject the request with an authentication error?</p> <pre class="lang-py prettyprint-override"><code>class Authentication(grpc.ServerInterceptor): def intercept_service(self, continuation, details): # How to raise an error? </code></pre> <p>I've seen ...
<python><grpc><interceptor>
2023-12-20 14:06:28
1
1,487
Clark McCauley
77,692,095
15,222,211
How can I run a function once after starting the FastAPI server?
<p>I need to start the <code>create_data</code> function once after the FastAPI <code>app</code> is started. I tried using <a href="https://fastapi.tiangolo.com/advanced/events/#lifespan" rel="nofollow noreferrer">lifespan</a> but found it not useful because <code>FastAPI</code> only starts working after <code>create_d...
<python><fastapi><uvicorn>
2023-12-20 13:54:52
2
814
pyjedy
77,692,022
10,544,599
How to use strip method correctly?
<p>I've a string <code>'XCeed Plug-in Hybride'</code> and I'm trying to get <code>'XCeed'</code>.</p> <p>Using <code>strip</code> method:</p> <pre><code>&gt;&gt;&gt; 'XCeed Plug-in Hybride'.strip(' Plug-in Hybride') 'XC' </code></pre> <p>I even tried using <code>rstrip</code>, still getting same output.</p> <pre><code>...
<python>
2023-12-20 13:41:28
1
379
David
77,691,979
5,615,873
How to do a correct insensitive sorting of a string list in Python?
<p>It seems that I cannot sort insensitively a string list correctly. I will give a simple example. I have tried the following methods with lst = ['b', 'B', 'a', 'A'].</p> <ol> <li><code>lst.sort(key=str.lower)</code></li> <li><code>lst.sort(key=str.upper)</code></li> <li><code>lst.sort(key=str.casefold)</code></li> </...
<python><list><sorting>
2023-12-20 13:35:29
4
3,537
Apostolos
77,691,855
2,067,492
For keras layers with unknown sizes is it possible to know the output size for a specific input?
<p>We can create a Convolution Neural Network with variable size inputs</p> <pre><code>ip = keras.layers.Input((None, None, 3)) op = keras.layers.Conv2D(3, (2, 2))(ip) model=keras.models.Model(inputs = [ip], outputs = [op]) </code></pre> <p>Is there a way to know the size of the output layer op for a specific input?</...
<python><keras><keras-3>
2023-12-20 13:11:44
3
12,395
matt
77,691,809
8,776,330
Batch update entity property in pyautocad
<p>I am making a pyqt widget tool which should operate with data in AutoCAD. Basically it allow user to select color and fill it in selected hatch objects in AutoCAD. It actually can be done directly in AutoCAD but sometimes it's time consuming task to open custom palette and manually select color.</p> <p>My current to...
<python><lisp><autocad>
2023-12-20 13:04:22
1
509
Pavel Pereverzev
77,691,801
1,734,097
How to solve Tabula error reading pdf to pandas?
<p>Help. I am having the following error in reading pdf files using tabula:</p> <blockquote> <p>Error importing jpype dependencies. Fallback to subprocess. No module named 'jpype' Error from tabula-java: The operation couldn’t be completed. Unable to locate a Java Runtime. Please visit <a href="http://www.java.com" rel...
<python>
2023-12-20 13:03:17
1
1,099
Cignitor
77,691,749
5,539,782
Close login window when scraping facebook groups using selenium
<p>I want to open facebook group page using selenium, but can't close the window that ask for login or signup: <a href="https://i.sstatic.net/FDW9Y.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FDW9Y.png" alt="enter image description here" /></a></p> <p>I tried selenium but always return an <code>Inval...
<python><selenium-webdriver><web-scraping>
2023-12-20 12:54:32
1
547
Khaled Koubaa
77,691,693
19,041,863
How to limit x axis to non-empty region of histogram with predetermined bins
<p>I have this data (dfe) that I want to plot in a histogram</p> <pre><code>Nr O18ad 0 -4.268475 1 -4.265793 2 -4.263120 3 -4.260457 4 -4.257803 ... 359995 -7.813345 359996 -7.821394 359997 -7.773479 359998 -7.807605 359999 -7.797769 </code></pre> <p>Here...
<python><matplotlib>
2023-12-20 12:43:49
1
303
Weiss
77,691,579
521,347
Environmental variables not accessible in Dataflow workers
<p>have a Python application which is using Apache beam and Dataflow as runner. The application uses a non-public Python package 'uplight-telemetry' which is configured using 'extra_packages' while creating pipeline_options object. This package expects an environmental variable named 'OTEL_SERVICE_NAME' and since this ...
<python><google-cloud-platform><google-cloud-dataflow><apache-beam>
2023-12-20 12:25:46
2
1,780
Sumit Desai
77,691,456
5,423,080
Error when read a single column from a huge CSV file with Pandas and PyArrow engine
<p>I am trying to read in Pandas a single column from a huge CSV file using the answer from another <a href="https://stackoverflow.com/questions/75029194/most-efficient-way-to-read-a-specific-column-in-large-csv-file">question</a>:</p> <pre><code>import pandas as pd test_df = pd.read_csv(&quot;test.csv&quot;, usecols=...
<python><pandas><csv><pyarrow>
2023-12-20 12:07:09
1
412
cicciodevoto
77,691,408
4,405,794
Slow Initialization and Inference Time with PyTorch and Pyannote on EC2 Instance Despite Caching
<p>The following code, which uses <code>pytorch</code> and <code>pyannote</code> and runs a simple inference is taking a good amount of time to load on a freshly created <code>g4dn</code> EC2 instance using an Amazon Machine Image in which all these imports were cached and the model has already been run.</p> <pre><code...
<python><amazon-ec2><pytorch>
2023-12-20 11:59:45
0
659
Ali Hassaine
77,691,074
9,974,205
Clustering data using scipy and a distance matriz in Python
<p>I am working in Python. I am using a binary dataframe in which I have a ser of values of 0 and 1 for diferent users at diferent times.</p> <p>I can perform hierarchical clustering directly from the dataframe as</p> <pre><code> metodo='average' clusters = linkage(user_df, method=metodo,metric='hamming') ...
<python><dataframe><matrix><scipy><hierarchical-clustering>
2023-12-20 11:06:00
2
503
slow_learner
77,691,019
10,143,378
Python Dataframe : Std using rolling period
<p>I have a Dataframe with a Date column (daily, from 2000 to 2023) and a Value column. What I need is to extract the global mean and std for all the year per days. Particularity is that I need each time to consider the day as a rolling period of 3 days. So if I want the global mean for all the 05 of Jan, in fact I nee...
<python><pandas><math>
2023-12-20 10:57:08
1
576
kilag
77,690,729
22,912,974
Django built in Logout view `Method Not Allowed (GET): /users/logout/`
<pre><code>Method Not Allowed (GET): /users/logout/ Method Not Allowed: /users/logout/ [10/Dec/2023 12:46:21] &quot;GET /users/logout/ HTTP/1.1&quot; 405 0 </code></pre> <p>This is happening when I went to url <a href="http://127.0.0.1:8000/users/logout/" rel="noreferrer">http://127.0.0.1:8000/users/logout/</a></p> <p>...
<python><python-3.x><django><django-forms><django-authentication>
2023-12-20 10:12:19
6
1,804
christopher johnson mccandless
77,690,691
11,594,202
Pdf2text not working in Azure function app
<p>I build a script using textract, which reads the content of pdf files. Which contains the following function:</p> <pre><code>import textract import tempfile def read_file(bytes): with tempfile.NamedTemporaryFile('wb', delete=True) as temp: temp.write(bytes) temp.flush() context = textra...
<python><azure><azure-functions><text-extraction><pdf-reader>
2023-12-20 10:05:43
1
920
Jeroen Vermunt
77,690,680
1,499,280
Websocket connection to remote server gives error "SSL alert number 40"
<p>Please forgive me if this question seems long. I am in process of developing an IOT device which talk to a website over websockets. My IOT device supports TCP communication using sockets right now. Before moving to websockets in the IOT device, I thought of trying websockets on my raspberry pi 4. So I did a simple s...
<python><ssl><websocket>
2023-12-20 10:04:28
1
393
Ravi
77,690,640
1,652,219
Pandas.to_datetime when dates are 9999-01-01
<p>I have read an SQL table into pandas, and now I want to convert the dates from strings into the pandas datetime type. The problem is, however, that SQL has a maximum date of &quot;9999-12-31 23:59:59.9999&quot;, while Pandas has a maximum date somewhere in 2262.</p> <p>So I could do the following, which is extremely...
<python><sql><pandas><datetime>
2023-12-20 09:58:02
1
3,944
Esben Eickhardt
77,690,451
14,259,321
pypy3 performs better on W11
<p>I have ryzen 9 7950x3d and two system in dual boot:</p> <ul> <li>Ubuntu 22.04.3 LTS</li> <li>Windows 11</li> </ul> <p>I have a task in python that is CPU intesive (multi thread)</p> <p>When I run it with pypy3 it takes approximately:</p> <ul> <li>Ubuntu: 9387 seconds.</li> <li>Windows 11: 8275 seconds.</li> </ul> <p...
<python><windows><performance><ubuntu><pypy>
2023-12-20 09:27:53
1
661
Luboš Hájek
77,690,364
15,222,211
How to return plain text in FastAPI
<p>In this example, the entrypoint <a href="http://127.0.0.1:8000/" rel="noreferrer">http://127.0.0.1:8000/</a> returns formatted text:</p> <p><code>&quot;Hello \&quot;World\&quot;!&quot;</code></p> <p>The quotes are masked by a slash, and quotes are added both at the beginning and at the end. How to return unformatted...
<python><fastapi>
2023-12-20 09:12:58
2
814
pyjedy
77,690,231
3,650,477
How to stream the output of an AgentExecutor in LangChain to my final application
<p>I have an instance of an <a href="https://python.langchain.com/docs/modules/agents/#agentexecutor" rel="nofollow noreferrer"><code>AgentExecutor</code></a> in LangChain. The whole chain is based on <a href="https://python.langchain.com/docs/expression_language/" rel="nofollow noreferrer">LCEL</a>. Therefore, I'd ass...
<python><langchain>
2023-12-20 08:45:45
0
2,729
Pythonist
77,689,970
5,559,342
Python not working on a bash script but working on the terminal. How to solve it?
<p>I am trying to run a <strong>Python</strong> program through a <strong>Bash</strong> script. When I execute the python file by shell it works with no problem, but when I try to execute the script, the <code>python</code> keyword is not recognized.</p> <p>I have a fresh Ubuntu 23.10 installation and I added, on top o...
<python><bash><ubuntu-23.10>
2023-12-20 07:50:59
3
5,075
Robb1
77,689,948
7,884,793
How to find the value in exact pattern and extract it into dataframe?
<p>I have some text files which were sent daily. They have same pattern (tag + value, end with quote notation) whose values changes in every files. You can see in images below:</p> <p><a href="https://i.sstatic.net/ooKdM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ooKdM.png" alt="enter image descript...
<python><dataframe><python-re>
2023-12-20 07:48:13
0
390
Tung Nguyen
77,689,912
1,089,412
Python unit test assert fails by trying compare mock to string
<p>I'm trying to learn how to do unit tests with pytest and mocks. I have this very simple use case:</p> <pre><code>from simple_salesforce import Salesforce from unittest.mock import Mock class SFClient: def __init__(self, sf_client: Salesforce): self._simple_sf_client = sf_client def bulk2(self, quer...
<python><unit-testing><mocking>
2023-12-20 07:40:41
1
3,306
piotrekkr
77,689,903
2,529,125
Python - Reading a SQL script with multiple queries using 'latin1' encoding | Issue with whitespaces and begins with ascii characters
<p><strong>Overview</strong> Im currently reading a sql script with multiple queries in python. Once the script is read into python as string type, the code establish connection to the SQL server via sql alchemy. Each query is split by &quot;;&quot; and executed on the SQL server.</p> <p><strong>Problem</strong> The is...
<python><sql><string>
2023-12-20 07:38:46
1
511
Sade
77,689,843
7,709,727
Why does multiprocessing.Queue stuck when parent process of fork() puts to the queue before fork?
<p>I recently write this program:</p> <pre class="lang-py prettyprint-override"><code>import os, time from multiprocessing import Queue q = Queue(1000) q.put(1) # Line 6 result = os.fork() if result == 0: while True: q.put(2) time.sleep(1) elif result &gt; 0: while True: print(q.g...
<python><multiprocessing><fork>
2023-12-20 07:23:31
1
1,570
Eric Stdlib
77,689,414
1,527,244
opencv: Exact polygon of contour
<p>Based on the following binary image, I'm trying to get a polygon of the outer contour. (This is already processed and looks promising).</p> <p><a href="https://i.sstatic.net/BU1Wb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BU1Wb.png" alt="enter image description here" /></a></p> <p>Now, I want to...
<python><opencv><image-processing><computer-vision>
2023-12-20 05:37:14
0
2,290
Danyel
77,689,378
9,983,652
how to calculate mean value of each column within range of quantile?
<p>I'd like to calculate mean value of each column but only consider values are within range of quantile, like 20%-80% only.</p> <p>Here is why I have done, but not complete</p> <pre><code>df=pd.DataFrame({&quot;A&quot;:[1,1,20,2,2,3,50,7,8,15,20,35,50,70],&quot;B&quot;:[10,100,20,20,200,30,50,70,80,150,200,350,500,700...
<python><pandas>
2023-12-20 05:26:15
1
4,338
roudan
77,689,317
1,874,170
Dynamic linking in Python CFFI?
<p>I'm trying to use CFFI for dynamic linking of dependent C libraries in Python; am I mis-understanding it?</p> <p>In the following extremely simplified example, library <code>foo_b</code> depends on library <code>foo_a</code>. Specifically, it depends on <code>bar</code>, and it exposes its own function <code>baz</co...
<python><dynamic-linking><python-cffi>
2023-12-20 05:07:40
1
1,117
JamesTheAwesomeDude
77,689,274
788,488
How can I add a type hint for a number coming from some unknown numpy array?
<p>I'm making a library that contains some methods whose parameters include numbers that may come from numpy arrays. E.g., one of my methods is roughly <code>some_func(my_array, my_array[0, 0])</code>, where the second param is a number of an unknown type (it could be a <code>np.float64</code>, some numpy integer type,...
<python><numpy><python-typing>
2023-12-20 04:54:16
1
2,603
meisel
77,689,241
903,501
How can 'Literal' be invoked with square brackets (e.g. Literal["Test1"])?
<p>The following code snippet shows a function named <code>Literal</code> being invoked with square brackets:</p> <pre><code>Literal['r', 'rb', 'w', 'wb'] </code></pre> <p>The example is from <a href="https://github.com/python/cpython/blob/main/Lib/typing.py#L728" rel="nofollow noreferrer">the CPython GitHub repo</a></...
<python><python-typing>
2023-12-20 04:34:34
2
978
psaw.mora
77,689,215
1,828,605
How to produce waterfall plot using shapely from loaded xgboost model
<p>I have this xgboost model that I created as a test to save as JSON in R. After I built the model in R, I saved it using <code>xgb.save(model, fname='xgboost_classifer_model.json')</code>.</p> <p>I then used <code>xgboost</code> package in python to load the model like the following:</p> <pre><code>import xgboost bst...
<python><xgboost><shap>
2023-12-20 04:24:44
1
1,735
user1828605
77,688,887
1,732,694
JSON Pickle serialize object list
<p>I want to serialize a list of objects using <code>jsonpickle</code>. Each of these objects contains a list of objects within them:</p> <pre class="lang-py prettyprint-override"><code>class ImageManipulationConfiguration: region_list = [] def to_json(self): return jsonpickle.encode(self.region_li...
<python><json><serialization><jsonpickle>
2023-12-20 02:07:19
3
546
ESD
77,688,883
10,844,607
How to connect to Google Cloud PostgreSQL database from Cloud Functions?
<p>I was following the <a href="https://codelabs.developers.google.com/codelabs/connecting-to-cloud-sql-with-cloud-functions" rel="nofollow noreferrer">Connecting to Cloud SQL with Cloud Functions</a> tutorial but my <strong>Cloud Function won't connect to the PostgreSQL database</strong>.</p> <p>Here's my function cod...
<python><postgresql><google-cloud-platform><google-cloud-functions><google-cloud-sql>
2023-12-20 02:04:17
2
5,694
Dr-Bracket
77,688,670
2,681,662
astropy exits none zero on header update
<p>I have an astronomical image <code>fits</code> format with WCS (World Coordinate System) in its header.</p> <p>I want to do some morphological operations on the image and understandably I want to correct the WCS.</p> <p>Say I crop the image. Applying to the header would be:</p> <pre><code>from astropy.io import fits...
<python><astropy><fits>
2023-12-20 00:34:15
0
2,629
niaei
77,688,632
13,608,794
winreg - SaveKey() returns WinError 1314 and creates empty file
<p>I don't know the reason of this behavior, but <strong>while running <code>winreg</code>'s <code>SaveKey</code> function on Python 3.11</strong> an empty file is written while returning WinError 1314 (<em>A required privilege is not held by the client.</em>)</p> <p>I am running shell as an administrator (code below) ...
<python><registry><winreg>
2023-12-20 00:17:45
0
303
kubinka0505
77,688,601
4,447,853
GPU/RAM out of Memory PyTorch/Transformers
<p>Context: I have six 3070 tis (48gb vram) and 8gb-32gb of ram along with 150gb ssd storage on my ubuntu 20.0.4 desktop. I am attempting to fine-tune <a href="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf" rel="nofollow noreferrer">meta-llama/Llama-2-7b-chat-hf</a> with a very small dataset as a proof-of-concep...
<python><pytorch><artificial-intelligence><huggingface-transformers>
2023-12-19 23:59:18
0
527
chriscrutt
77,688,568
1,103,911
Extend pandas Timestamp class
<p>I tried to extend <code>pandas</code> <code>Timestamp</code> class by inheriting and adding a new method to the class</p> <pre><code>class T(pd.Timestamp): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def to_unix_epoch(self) -&gt; int: return int(self.to_pydatetime().t...
<python><pandas>
2023-12-19 23:47:31
1
588
Eliy Arlev
77,688,286
2,998,447
Giving legend labels in calls to matplotlib.pyplot.text
<p>Based on my interpretation of the <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html" rel="nofollow noreferrer">documentation</a>, text arguments can have a <code>label</code> kwarg that will show up in the legend (following the link for <code>label</code> takes you <a href="https://matpl...
<python><matplotlib>
2023-12-19 22:19:09
0
2,305
ramzeek
77,688,251
20,122,390
Why is a celery task not consumed by a worker that is free?
<p>I have an application in Python with a microservices architecture and pipelines for which I use Celery along with RabbitMQ and Redis. In an application flow (machine learning training) 8 methodologies are needed, therefore a first worker called &quot;Worker Training&quot; sends 8 tasks to another worker called &quot...
<python><rabbitmq><celery>
2023-12-19 22:11:08
1
988
Diego L
77,688,198
13,118,338
How to decode string address into Pubkey address on Solana
<p>I am querying data from raydium using their SDK, but i am trying to do it in Python instead. So, I am obtaining an address:</p> <pre><code>&lt;BN: b870e12dd379891561d2e9fa8f26431834eb736f2f24fc2a2a4dff1fd5dca4df&gt; </code></pre> <p>And I know it correspond to :</p> <pre><code>PublicKey(DQyrAcCrDXQ7NeoqGgDCZwBvWDcYm...
<python><typescript><solana>
2023-12-19 21:54:14
1
481
Nicolas Rey
77,688,183
3,749,836
Streaming chatbot with nicegui
<p>I am trying to follow the example in this link <a href="https://github.com/zauberzeug/nicegui/blob/main/examples/chat_with_ai/main.py" rel="nofollow noreferrer">https://github.com/zauberzeug/nicegui/blob/main/examples/chat_with_ai/main.py</a> but for a streaming chatbot use case.</p> <p>Every single time, I send a m...
<python><nicegui>
2023-12-19 21:51:28
1
1,987
gibbz00
77,688,037
12,708,740
Pairwise cohen's kappa of values in two dataframes
<p>I have two dataframes that look like the toy examples below:</p> <pre><code>data1 = {'subject': ['A', 'B', 'C', 'D'], 'group': ['red', 'red', 'blue', 'blue'], 'lists': [[0, 1, 1], [0, 0, 0], [1, 1, 1], [0, 1, 0]]} data2 = {'subject': ['a', 'b', 'c', 'd'], 'group': ['red', 'red', 'blue', '...
<python><pandas><dataframe><heatmap><cohen-kappa>
2023-12-19 21:15:22
3
675
psychcoder
77,687,928
480,118
Convert pandas.offsets.CustomBusinessDay to numpy offset
<p>i have code that looks like this which gets an offset for a date:</p> <pre><code>import pandas as pd, numpy as np from pandas.tseries.holiday import USFederalHolidayCalendar from pandas.tseries.offsets import CustomBusinessDay from datetime import datetime biz_day_only= True offset = 1 us_biz_days = CustomBusinessD...
<python><pandas><numpy>
2023-12-19 20:50:13
1
6,184
mike01010
77,687,880
2,868,899
Range matching to return value
<p>I'm having trouble finding the solution to this one. It'd usually be a <code>merge()</code> to attain something similar but I can't find if it'd be extra tacked on</p> <p>Data:</p> <pre><code>import pandas as pd import numpy as np num = {'serial':[10,20,30,50]} df = pd.DataFrame(num) cols = {'StartSerial':[9,19,29,...
<python><pandas>
2023-12-19 20:35:40
2
2,790
OldManSeph
77,687,844
11,628,437
Mujoco: `gym.error.DependencyNotInstalled: dynamic module does not define module export function (PyInit_cymj)`
<p>I installed mujoco-py by doing pip install <code>mujoco-py==1.50.1.0</code>. It installed successfuly. However, when I try to import it using Python, I get the following error -</p> <pre><code>import mujoco_py running build_ext Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;modu...
<python><openai-gym><mujoco>
2023-12-19 20:28:32
0
1,851
desert_ranger
77,687,815
5,094,589
ORA-01036: illegal variable name/number oracledb (python)
<p>I want to insert data into my Oracle table, which has the following structure:</p> <pre><code>SUBJECT VARCHAR2(4000 BYTE) TEXT LONG PREDICTED_CATEGORY VARCHAR2(1000 BYTE) TRUE_CATEGORY VARCHAR2(1000 BYTE) PROBABILITY VARCHAR2(4000 BYTE) NUMBER_ANONYMIZED_TOKENS VARCHAR2(1...
<python><oracle-database><cx-oracle><python-oracledb>
2023-12-19 20:23:11
1
1,106
Daniil Yefimov
77,687,761
3,928,553
Numpy : check if any array in 3D array is in another shorter 3D array with duplicates
<p>I've got a Numpy array like this one :</p> <pre><code>source = np.array([[[0,0,0],[0,0,1],[0,1,0],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]]) </code></pre> <p>And I'm trying to compare it to an other array, which has shorter Axis2 and duplicates in Axis3 :</p> <pre><code>values = np.array([[[0,1,0],[1,0,0],[1,1,1],[1,1,1],[0...
<python><arrays><numpy>
2023-12-19 20:11:11
2
617
Raphadasilva
77,687,743
618,579
Issue with grabbing text from SPAN using Selenium
<p>I'm trying to get the start of the warranty start date from the Lenovo website using Selenium, i have successfully found the search box, where i enter the serial number and press return. I have then put a 5 second delay in and try to read the text from the span with the following.</p> <pre><code> info = driver.fi...
<python><selenium-webdriver>
2023-12-19 20:08:11
2
2,513
Nathan
77,687,707
301,774
Clearing an interactive animated plot
<p>I have the following simple exmample of animation across subplots and now I am trying to make it interactive. When I changes the parameters via interaction I have know it is calling <code>run</code> because my print statement is outputing the new values. However the chart doesn't redraw.</p> <pre><code> %matplo...
<python><matplotlib><matplotlib-animation><python-interactive>
2023-12-19 19:59:58
0
6,896
akaphenom
77,687,649
11,391,711
how to use min_ function in LinExpr() when writing an expression in Gurobi
<p>I would like to use the built-in min function provided by Gurobi, however, I receive an error and cannot use the variable within the function.</p> <p>After installing the required libraries as shown below,</p> <pre><code>import gurobipy as gp from gurobipy import quicksum, min_ </code></pre> <p>I write down my expre...
<python><mathematical-optimization><gurobi>
2023-12-19 19:46:05
1
488
whitepanda
77,687,578
4,439,019
How to change the filename of pytest-html's generated HTML report?
<p>I know how to change the report name, the following does that for me just fine:</p> <pre><code>conftest.py def pytest_html_report_title(report): report.title = 'My API Testing' </code></pre> <p>But that doesn't change the name of the actual file itself. It is still showing up as <code>report.html</code> and jus...
<python><pytest><pytest-html>
2023-12-19 19:32:26
2
3,831
JD2775
77,687,260
2,803,777
Why is my sliced array variant in Python slower as compared with the element-wise operation?
<p>I refer to <a href="https://stackoverflow.com/questions/77683855/can-i-use-a-more-pythonic-way-for-my-conditional-array-operations">this question</a>, which has already a good answer; but there were unnecessary operations identified (see discussion in the posting) and I was just curious if I could succeed in elimina...
<python><arrays><numpy>
2023-12-19 18:24:34
2
1,502
MichaelW
77,687,182
1,753,640
Update database table once asyncio co-routine is complete
<p>I want to do the following</p> <ol> <li>Insert a database record to indicate a job is running</li> <li>Kick off an asyncio routine</li> <li>Update the database table once the routine is complete</li> </ol> <p>This is my current code:</p> <pre><code>db = sqlite3.connect('database.db') conn = db.cursor() insert_query ...
<python><python-asyncio>
2023-12-19 18:09:39
0
385
user1753640
77,687,160
139,692
Python Logging Config
<p>I'm trying a simple setup with python logging using the json format. I've copied some config data from the logging config tutorial but when importing it I get:</p> <pre><code>(env) pi@omni-demo:~/omni-reader $ python Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux Type &quot;help&quot;, &quot;copy...
<python><logging><yaml>
2023-12-19 18:04:59
2
946
Neil Benn
77,687,047
10,333,668
tkinter ttk copy Style layout
<p>I found this solution to extend a ttk theme:</p> <pre><code>import tkinter as tk import tkinter.ttk as ttk class Style(ttk.Style): EXTENDS = 'extends' def __init__(self, parent): super().__init__(parent) self._style = {} def configure(self, cls, **kwargs): self._style.setdefaul...
<python><tkinter><ttk>
2023-12-19 17:42:17
0
377
Bálint Cséfalvay
77,686,967
521,347
Dataflow not able to find a module specified using extra_package
<p>I have created a Dataflow pipeline in batch mode using Apache beam Python SDK. I am using one non-public dependency 'uplight-telemetry'. I have specified it using parameter extra_package while creating pipeline_options object. However, the pipeline loading is failing with an error <code>No module named 'uplight_tele...
<python><google-cloud-platform><google-cloud-dataflow><apache-beam>
2023-12-19 17:25:33
1
1,780
Sumit Desai
77,686,822
1,804,173
Why am I getting a "wrong" mean from cumprod / cumsum of log-normal returns?
<p>I'm trying to generate a <a href="https://en.wikipedia.org/wiki/Geometric_Brownian_motion" rel="nofollow noreferrer">Geometric Brownian motion</a> &quot;price&quot; time series, i.e., based on log-normal returns. The goal:</p> <ul> <li>The time series should start with a price value of 1.0,</li> <li>should have a le...
<python><numpy><mean><cumsum>
2023-12-19 17:00:08
0
27,316
bluenote10