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,330,113
10,595,871
Bulk vectors in elasticsearch using python
<p>I'm new to elasticsearch and I think I'm missing some hints. I'm trying to put some data into an index using python, that's my code:</p> <pre><code>from elasticsearch import Elasticsearch, helpers import json df = pd.read_excel('analisi rna.xlsx') </code></pre> <p>data are something like this:</p> <pre><code>name ...
<python><elasticsearch>
2023-10-20 10:15:19
0
691
Federicofkt
77,329,890
9,893,918
DAG-level Params for string and integer
<p>I have a Airflow <code>SparkSubmitOperator</code> and I want to add DAG-level Params to configure:</p> <pre><code>executor_cores executor_memory application_args </code></pre> <p>I’ve wrote next code:</p> <pre><code>dag = DAG( 'spark_submit_ex', params={ &quot;executor_cores&quot;: Param(2, type=&quo...
<python><airflow>
2023-10-20 09:42:18
1
835
Vadim
77,329,798
18,771,355
SimCLR/ResNet18 : last fractional batch mecanism not functional ? (tensor shapes incompatible)
<p>I'm implementing a SimCLR/ResNet18 architecture over a custom dataset.</p> <p>I know that</p> <blockquote> <p>Number of Iterations in One Epoch=Batch Size/Total Training Dataset Size​</p> </blockquote> <p>And if the result is floating then the size of the last batch is adapted for the leftovers (the 'fractional batc...
<python><deep-learning><pytorch><resnet>
2023-10-20 09:30:00
1
316
Willy Lutz
77,329,701
1,682,470
Sphinx: custom Pygments' lexer not found
<p>I created <code>Pygments</code> customized lexer and style:</p> <ul> <li><code>acetexlexer.py</code> (lexer file),</li> <li><code>acedracula.py</code> (style file),</li> </ul> <p>that work pretty well since the following command returns the expected result:</p> <pre><code>pygmentize -O style=acedracula -x -l acetexl...
<python><python-sphinx><lexer><pygments>
2023-10-20 09:14:09
0
674
Denis Bitouzé
77,329,606
4,795,075
Save custom field in Keras model
<p>Consider the situation in which I have a trained Keras Sequential model. I save the model using</p> <pre><code>keras.saving.save_model(model, path, save_format=&quot;...&quot;) </code></pre> <p>Before saving, however, I set a custom <code>list[str]</code> attribute in the model this way:</p> <pre><code>setattr(model...
<python><keras>
2023-10-20 08:58:54
2
356
leqo
77,329,554
1,142,881
What's the difference between connection and connect, and when should I use one over the other?
<p>I'm using peewee extensively with the <code>play_house.db_url.connect</code> to connect to a database. This method allows for a lot of flexibility and it is very straightforward when opening a single connection to a database i.e., open and close a single connection.</p> <p>However, this gets unclear when attempting ...
<python><peewee>
2023-10-20 08:51:00
1
14,469
SkyWalker
77,329,511
13,560,598
usage of tf.gather to index lists containing non-Tensor types
<p>Consider the following code. I'd like to know how I can gather non-Tensor types from a list.</p> <pre><code>import tensorflow as tf class Point(tf.experimental.ExtensionType): xx: tf.Tensor def __init__(self,xx): self.xx = xx super().__init__() list1 = [ 1, 2, 3, 4] list2 = [ Point(1), Poi...
<python><list><tensorflow>
2023-10-20 08:45:34
3
593
NNN
77,329,213
10,737,147
Import DLL | Ctypes
<p>I am trying to import the functions of the DLL comes in the package XFLR5. <a href="https://sourceforge.net/projects/xflr5/files/6.59/" rel="nofollow noreferrer">https://sourceforge.net/projects/xflr5/files/6.59/</a></p> <p>I have 2 questions.</p> <ol> <li>The function names look very different to what is being decl...
<python><dll><ctypes>
2023-10-20 07:55:43
0
437
XYZ
77,329,074
16,473,860
Python's "No module named 'ultralytics'" Error
<p>I've written a simple code using yolov5 and opencv. I then deployed it into an exe file using pyinstaller. However, this deployed file exits immediately upon execution. When I ran this file directly from the terminal, I encountered an error stating <strong>&quot;No module named 'ultralytics'&quot;</strong>.</p> <p>B...
<python><deep-learning><pytorch><yolo><yolov5>
2023-10-20 07:33:09
1
747
Kevin Yang
77,329,023
2,005,559
Parsing a python dict to a list of values
<p>I am writing a python code, to parse bibtex file:</p> <pre><code>import bibtexparser #to be installed with pip --pre bibtex_str = &quot;&quot;&quot; @ARTICLE{Cesar2013, author = {Jean César}, title = {An amazing title}, year = {2013}, volume = {12}, pages = {12--23}, journal = {Nice Journal} } &quot;&qu...
<python>
2023-10-20 07:22:34
1
3,260
BaRud
77,328,794
9,091,991
Django app for loop through list containing a single dictionary
<p>I am creating a Django app to use json to parse data from the internet using an API. The Result is displayed in the form a a list containing a dictionary as follows</p> <p>The following is the code used in the views page</p> <pre><code> def home(request): import requests import json #### api_reque...
<python><django><list><loops>
2023-10-20 06:44:25
1
1,285
Raghavan vmvs
77,328,739
9,647,709
subtraction from a dictionary of dictionaries in a pandas dataframe
<p>I have a dataframe where I want to find the difference in the unique_users for the latest day(2023-09-06) and previous day(2023-09-07) for a specific hour 2 and 13 separately for each key 'bsnl' and 'other' and for a specific <code>Exception</code>. I need to consider the <code>Exception</code> and <code>Hour</co...
<python><pandas>
2023-10-20 06:30:43
2
414
Sam
77,328,548
3,542,535
Dynamically get a list of keys to access the deepest non-dict values in a nest dictionary
<p>I have a dictionary where I want to return a dynamic list of the keys that would access any non-dict values. I do not know the structure of the dictionary beforehand and nesting could go n-levels.</p> <pre><code>{ &quot;parent&quot;: { &quot;a&quot;: 1, &quot;b&quot;: { &quot;nested&q...
<python><dictionary><recursion>
2023-10-20 05:40:46
1
413
alpacafondue
77,328,530
672,452
Fix Python3 syntax error in CheckMK plugin
<p>I'm using CheckMK 2.2.0 and its plugin for Nginx to monitor some hosts. The agent is running on a host using Python 3.4.2 that can not be updated. When running the Nginx plugin on this host, I'm getting a syntax error:</p> <pre><code># python3 nginx_status.py File &quot;nginx_status.py&quot;, line 126 config: ...
<python><python-3.x><syntax-error><python-3.4>
2023-10-20 05:36:46
1
7,782
rabudde
77,328,216
1,857,373
Class MRJob Python TypeError: super(type, obj): obj must be an instance or subtype of type
<p><strong>Problem</strong></p> <p>Running Class MRJob custom code in Python 3.x. The MRJob class is define. Unit testing in Jyputer Notebook ok running fine on unit test. Saved Jyputer Notebook into Python .py file to run on console for final unit test.</p> <p>Seeking help on the Type Error for super on configure_args...
<python><class><instance><mrjob>
2023-10-20 03:44:24
1
449
Data Science Analytics Manager
77,328,200
11,743,016
Disable a Plotly Dash component during callback execution, then re-enabling it after the callback has finished
<p>I have Plotly Dash components that need to be disabled after a callback has been triggered. The same components need to be enabled after the callback has finished running. I have tried the approach below. While the component gets disabled, it does not get enabled after finishing the callback function.</p> <pre class...
<python><user-interface><callback><plotly-dash>
2023-10-20 03:37:39
2
349
disguisedtoast
77,328,167
2,955,541
Speeding Up NumPy Array Generation from SymPy Poly Expression
<p>I have a multivariable polynomial expression that I would like to convert into a square <code>numpy</code> matrix:</p> <pre><code>import sympy n = 225 x, C = sympy.symbols(f'x:{n+1}'), sympy.symbols('C') expr = -1 for i in range(1, n+1): expression += x[i] penalty = sympy.Poly(C*(expr)**2) </code></pre> <...
<python><sympy>
2023-10-20 03:24:48
1
6,989
slaw
77,328,072
1,844,518
How to test that the method of an instance has been called?
<p>Let's say I have the following piece of code:</p> <pre class="lang-py prettyprint-override"><code>class MyClass: def __init__(self, value=1): self.value = value self.destructive_stuff() def destructive_stuff(self): print(&quot;Running destructive commands on the host...&quot;) d...
<python><unit-testing><testing><mocking>
2023-10-20 02:51:51
2
432
Pierre
77,327,854
7,898,913
How to use secondary source as a fallback for Python package installs?
<p>My users have some software that depends on a package distribution in a private index and its source code in a private git repository. Because it is more inconvenient for my users to authenticate to the private index (e.g., local dev environment), they can instead install from a git source. At the same time if the s...
<python><pip><package><pyproject.toml>
2023-10-20 01:27:29
1
2,338
Keto
77,327,708
1,285,061
How do we fit previous models' data into the last model?
<p>How do we fit previous models' data into the last model? The last <code>fit</code> in this code isn't working. I am trying to build a fairly complicated model, about 40 models. How do I <code>fit</code> data only to the last model that feeds to all previous models? I start with <code>a_in</code> <code>b_in</code> pr...
<python><tensorflow><machine-learning><keras>
2023-10-20 00:25:05
1
3,201
Majoris
77,327,679
1,887,919
Fastest way to add matrices of different shapes in Python/Numba
<p>I want to &quot;add&quot; two matrices, a matrix <code>a</code> with shape (<code>K,T</code>) and a matrix <code>b</code> of shape <code>(K,N)</code>, to result in a matrix of shape <code>(K,T,N</code>)</p> <p>The following works ok:</p> <pre class="lang-py prettyprint-override"><code> import numpy as np from numba...
<python><numpy><matrix><vectorization><numba>
2023-10-20 00:13:29
2
923
user1887919
77,327,589
523,124
How can I modify a customized build class derived from build_py so that it builds in a temporary directory?
<p>I have a setup.py file with a customized build class derived from build_py, which is imported from either distutils (for older setups) or setuptools:</p> <pre><code>try: warnings.filterwarnings('ignore', message='.*distutils package is deprecated.*', category=DeprecationWarning) from distut...
<python><pip><setuptools><distutils>
2023-10-19 23:43:20
0
2,258
Alan
77,327,474
13,324,244
MemoryError when using requests_cache (with sqlite backend) inside Celery worker
<p>I have <code>requests-cache==1.1.0</code> and <code>celery==5.3.4</code> installed on M1 MacBook.</p> <p>Nothing special about the config on either, but posting here just incase its somehow helpful</p> <p>Celery config:</p> <pre><code>broker_url=&quot;redis://localhost&quot;, result_backend=&quot;redis://localhost&q...
<python><sqlite><python-requests><celery>
2023-10-19 23:03:33
1
1,228
sarartur
77,327,247
1,930,402
How to join two PySpark DataFrames on a common list column
<p>I have two PySpark DataFrames, df1 and df2, with a column named 'conditions' that contains lists of strings. I want to join these DataFrames based on the common elements in the 'conditions' column, where the entire list in one DataFrame matches the entire list in the other DataFrame.</p> <p>Here's a simplified examp...
<python><pyspark>
2023-10-19 21:44:50
1
1,509
pnv
77,327,165
3,469,243
Creating a categorical heatmap with sparklines?
<p>Does anyone know of an example of how to create a categorical heat map with individual sparklines within each cell? Or have a suggestion on how to use matplotlib's annotation to produce this (or something similar)?</p> <p>Essentially turning this: <a href="https://matplotlib.org/stable/gallery/images_contours_and_fi...
<python><matplotlib><heatmap><sparklines>
2023-10-19 21:21:45
1
2,486
As3adTintin
77,326,989
5,516,822
How to specify null value character for `csv.reader`?
<p>I want to read &quot;csv&quot; file with <code>\u0000</code> as null, <code>\u0001</code> as line terminator and <code>u0002</code> as delimiter. For last two there is two parameters:</p> <pre><code>csv.reader(csvfile, lineterminator='\u0001', delimiter='\u0002') </code></pre> <p>Is there parameter for null value ch...
<python><csv>
2023-10-19 20:45:15
2
1,283
Makrushin Evgenii
77,326,740
13,676,462
optimizing 3 variables in a differential equation based on available data point from solution of differential equation
<p>I have following data points (I call them actual data points):</p> <pre><code>y_data = np.array([0, 32.1463583, 33.1915926, 37.9100309, 39.2501778, 40.8225707, 48]) t_data = np.array([0, 26.75, 72.25, 163.4166667, 209.25, 525, 1250]) </code></pre> <p>and I have a differential equation which is includes y and t:</p>...
<python><optimization><gradient-descent><odeint>
2023-10-19 19:57:33
0
923
Yellow_truffle
77,326,539
7,351,855
Infinite axline in 3D
<p>I am trying to draw a scene like in the picture below using Python matplotlib, but I got stuck on drawing the infinite line (the black &amp; dotted one in the picture). In 2D, this line can be drawn using <code>axline</code>, but I couldn't find an alternative in 3D.</p> <p>Is there any solution to this?</p> <p><a h...
<python><matplotlib><matplotlib-3d>
2023-10-19 19:21:56
1
830
Matej
77,326,473
2,410,605
selenium 4.13 python unable to change default download directory
<p>I feel like I'm in a viscous cycle of fixing one thing and breaking another. I've recently upgraded to Selenium 4.13 to take advantage of Selenium Manager's auto chromedriver feature. I think I finally have it installed correctly, but now I cannot change my default download directory no matter what I try. I've read ...
<python><selenium-webdriver>
2023-10-19 19:09:22
0
657
JimmyG
77,326,470
7,055,769
class not seeing its properties
<p>my class</p> <pre><code>from django.db import models from django.contrib.auth.models import User class Task(models.Model): id: models.UUIDField(unique=True, auto_created=True) content: models.CharField(default=&quot;&quot;) deadline: models.IntegerField(default=None) creationDate: models.DateField(a...
<python><django><django-models><django-rest-framework>
2023-10-19 19:08:20
2
5,089
Alex Ironside
77,326,270
2,231,299
how to display parallel output results within Jupyter Notebook, using AsyncSSH + IPyWidget?
<p>ChatGPT is running in circles now and it keeps failing at the task: having multiple boxes monitoring in real time the output of a remote python script.</p> <p>So far, here is the notebook code:</p> <pre><code>import asyncssh import asyncio from ipywidgets import Output, HBox import traceback class MySSHClientSessio...
<python><ipywidgets><asyncssh>
2023-10-19 18:29:41
1
875
Myoch
77,326,158
3,825,948
Function Not Found in Sanic Server
<p>In Sanic server, a have a function defined in a file called controller.py with path /views/controller.py. My Sanic app is created in main.py at the root level (/) and can't find this function. The function has the decorator</p> <pre><code>@app.post(&quot;/get_x&quot;) </code></pre> <p>What do I have to do to make th...
<python><routes><sanic>
2023-10-19 18:06:10
1
937
Foobar
77,326,149
14,829,523
Sorting algorithm on dataframe with swapping rows
<p>I have the following dummy df:</p> <pre><code>import pandas as pd data = { 'address': [1234, 24389, 4384, 4484, 1234, 24389, 4384, 188], 'old_account': [200, 200, 200, 300, 200, 494, 400, 100], 'new_account': [300, 100, 494, 200, 400, 200, 200, 200] } df = pd.DataFrame(data) print(df) address old_a...
<python><pandas><dataframe><sorting>
2023-10-19 18:04:12
1
468
Exa
77,326,060
4,234,062
Find & replace values in presenter notes using pptx-python
<p>I have a dictionary of values that I'd like to use to find &amp; replace in the presenter notes of a powerpoint presentation. My code works for replacing the values in the slides themselves, but I can't figure out the presenter notes. This is what I have so far - any help would be appreciated!</p> <pre><code>from pp...
<python><powerpoint><python-pptx>
2023-10-19 17:48:55
1
739
chris_aych
77,325,943
6,379,197
Tensorflow 2.11.0 Cannot dlopen some GPU libraries
<p>I am tryng to use GPU for tensorflow. I have installed tensorflow by the following command:</p> <pre><code>pip install tensorflow. </code></pre> <p>The code to access gpu on tensorflow is as follows:</p> <pre><code>import tensorflow as tf from tensorflow.compat.v1.keras import backend as K def set_gpu_option(which...
<python><tensorflow><gpu>
2023-10-19 17:31:09
0
2,230
Sultan Ahmed
77,325,768
8,869,570
Querying sqlite3 table based on inferring another column
<p>I have a sqlite3 table <code>table_name</code> with columns <code>start, end, id, val_end</code> and note that <code>val_end</code> is not a nullable column. Suppose there's a value <code>val_start</code> such that <code>val_start</code> for a row is the <code>val_end</code> for the previous row, e.g.,</p> <pre><cod...
<python><sql><sqlite>
2023-10-19 17:02:15
0
2,328
24n8
77,325,701
7,534,658
How to handle python type hint for class method overrides
<p>I want to give type hint for a class inheritance scenario:</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar(&quot;T&quot;) U = TypeVar(&quot;U&quot;) class Mother(Generic[T, V]): def process(self, x: T) -&gt; V: ... class Child(Mother[int, str]): def process(self, x: int) -&gt; str: ... ...
<python><generics><inheritance><python-typing>
2023-10-19 16:49:55
0
631
p9f
77,325,636
1,841,839
How to load an existing vector db into Langchain?
<p>I have the following code which loads my pdf file generates embeddings and stores them in a vector db. I can then use it to preform searches on it.</p> <p>The issue is that every time i run it the embeddings are regrated and stored in the db along with the ones already created.</p> <p>Im trying to figurer out How t...
<python><langchain><palm-api><hnswlib>
2023-10-19 16:38:56
1
118,263
Linda Lawton - DaImTo
77,325,334
3,256,651
Running a gams file from python - gams system directory error
<p>I would like to run GAMS mdoel from python through the gams python API.</p> <p>I insalled the API and it works fine:</p> <pre><code>import gams print(f'API OK -- Version {gams.__version__}')''' </code></pre> <p>I get:</p> <pre><code>API OK -- Version 45.1.0 </code></pre> <p>However when I try to:</p> <pre><code>fro...
<python><gams-math>
2023-10-19 15:50:57
1
1,922
esperluette
77,325,323
1,914,781
apply function which return dataframe
<p>Below code works but wish if get better way to implement.</p> <p>The idea is combine first dataframe with another dataframe, which depends on first dataframe's row values.</p> <pre><code>import pandas as pd def getdf(x): df2 = pd.DataFrame( {'rkey': ['X', 'Y', 'Z'], 'rval': [x, x*2, x*3]}) ...
<python><pandas>
2023-10-19 15:48:18
1
9,011
lucky1928
77,325,233
7,318,120
how to convert a dict to a dataclass (reverse of asdict)?
<p>the dataclasses module lets users make a dict from a dataclass reall conveniently, like this:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, asdict @dataclass class MyDataClass: ''' description of the dataclass ''' a: int b: int # create instance c = MyDataCl...
<python><python-dataclasses>
2023-10-19 15:35:31
4
6,075
darren
77,325,131
2,504,762
pyarrow not able to handle nulls for required fields when writing to parquet files
<p>I am trying to create a pyarrow table and then write that into parquet files.</p> <pre class="lang-py prettyprint-override"><code>def test_pyarow(): import pyarrow as pa import pyarrow.parquet import pandas as pd fields = [pa.field('id', pa.string(), nullable=False), pa.field('name', p...
<python><pyarrow>
2023-10-19 15:24:33
0
13,075
Gaurang Shah
77,325,120
776,543
Accessing model attributes results in Self not defined error
<p>Can anyone help me understand why I am receiving the error <code>self is not defined</code> while accessing a class attribute? Thanks for your help</p> <pre><code> class Receipt(models.Model): &quot;&quot; receipt_id = models.AutoField( primary_key=True, db_comment=&quot;&q...
<python><django>
2023-10-19 15:22:44
1
1,312
SeaSky
77,325,095
22,407,544
Why does my Django view return 'Reverse for 'initiate_transcription' with arguments '('',)' not found'?
<p>A user uploads a file on page 1 and the site redirects them to page 2 where they can click a button which triggers the service. I'm trying to create a unique URL for each user upload and I know the error has to do with the <code>{% url 'initiate_transcription' session_id %}</code> in HTML page 2 form but i'm not sur...
<javascript><python><html><django><forms>
2023-10-19 15:19:52
1
359
tthheemmaannii
77,325,058
853,462
Run `multiprocessing.Pool.initialize` on a method of the forked class
<pre class="lang-py prettyprint-override"><code>import os from multiprocessing import Pool class A: def initialize(self): print('initialize', self, os.getpid()) def run(self): print('run ', self, os.getpid()) a = A() print('root ', a, os.getpid()) with Pool(1, initializer=a.initialize) as poo...
<python><python-3.x><python-multiprocessing>
2023-10-19 15:16:21
1
5,685
Herbert
77,324,859
9,983,652
how to convert list of tuple into a string?
<p>I have a list of tuple and I'd like to convert the list into a string of tuple pair separted by comman. Not sure how to do it?</p> <p>For example if I have list of this</p> <pre><code>a=[(830.0, 930.0), (940.0, 1040.0)] </code></pre> <p>I'd like to convert it to a string like this</p> <pre><code>b=&quot;(830.0, 930...
<python><list><tuples>
2023-10-19 14:53:25
5
4,338
roudan
77,324,551
4,105,440
Radial text annotation polar plot with clockwise direction
<p>I want to place some text on a radius of a polar plot. When using the default theta zero location and direction it works as expected</p> <pre class="lang-py prettyprint-override"><code>fig = plt.figure(figsize=(6,6)) ax = fig.add_subplot(111, polar=True) ax.set_yticklabels(&quot;&quot;) ax.annotate('test', ...
<python><matplotlib><polar-coordinates><plot-annotations>
2023-10-19 14:12:56
1
673
Droid
77,324,210
14,301,545
QtCreator; AttributeError: 'Constant' object has no attribute 'id'; JSONDecodeError: running pyside6-metaobjectdump
<p>QtCreator does not want to run an application that I wrote a few months ago on another computer. Interestingly, the application itself works OK if I run it directly from the disk, or e.g. via PyCharm. Does anyone know what the reason could be?</p> <p>Minimal (non)working example:</p> <p>main.py:</p> <pre><code>impor...
<python><qt><qml><pyside6>
2023-10-19 13:29:22
1
369
dany
77,324,061
10,430,394
How to place inset axes of image in upper right corner
<p>I am trying to place an inset axes exactly in the upper right of my existing axes. This is usually very simple if you use the <code>bbox_to_anchor</code> keyword in conjunction with the <code>transform</code> of the parent axes.</p> <pre class="lang-py prettyprint-override"><code>axins = inset_axes(ax, width=&quot;4...
<python><matplotlib>
2023-10-19 13:09:27
1
534
J.Doe
77,323,993
774,133
Groupby returns Series, then DataFrames
<p>Please consider this code:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({&quot;a&quot; : [1, 1, 2, 2], &quot;b&quot; : [1, 1, 2, 3], &quot;s1&quot;: [1, np.nan,3, np.nan], &quot;s2&quot;: [np.nan,2, 3, np.nan]}) print(df) def co...
<python><pandas>
2023-10-19 13:01:23
0
3,234
Antonio Sesto
77,323,928
13,217,286
In Polars, is there a better way to only return items within a string if they match items in a list using .is_in?
<p>Is there a better way to only return each <code>pl.element()</code> in a polars list if it matches an item contained within another list?</p> <p>While it works, I believe there's probably a more concise/better way:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl terms = ['a', 'z'] (pl.LazyF...
<python><regex><dataframe><python-polars>
2023-10-19 12:53:35
2
320
Thomas
77,323,830
6,067,528
Why is this python priority queue failing to heapify?
<p>Why is this priority queue failing to heapify? Where (150, 200, 200) are the priority values assigned to the dictionaries</p> <pre><code>import heapq priority_q = [ (150, {'intel-labels': {'timestamp': 150}}), (200, {'intel-labels': {'timestamp': 200}}), (200, {'intel-labels': {'timestamp': 200, 'xx':...
<python><heapq>
2023-10-19 12:38:26
3
1,313
Sam Comber
77,323,754
14,512,983
Create or Maintain a single CHANGELOG from multiple Git repositories
<p>I tried to look up any examples or GitHub actions if there is a way to generate or maintain a single CHANGELOG.md file for all GitHub repositories (say more than 10).</p> <p>I would like to know if this can be achieved through any automation work (through Python) if possible. Any help (any ideas, reference examples,...
<python><github><github-actions>
2023-10-19 12:26:17
0
818
Ranji Raj
77,323,740
14,485,257
Find the segment ordinal number and the inner index for a given search index on a splitted array
<p>I have a pandas dataframe having 1 column:</p> <pre><code>df = pd.DataFrame({&quot;Value&quot;: [10,9,5,11,2,8,6,7,4,2,1,9]}) </code></pre> <p>If I take a subset of this, the starting index value changes from 0,1,2,3,4,5,6,7,8,9,10,11 to 3,4,5,6,7:</p> <pre><code>df = df[3:8] </code></pre> <p>When I try to convert t...
<python><arrays><pandas><dataframe><numpy>
2023-10-19 12:24:16
3
315
EnigmAI
77,323,575
1,701,504
How do I change the project from GCP text to speech python library?
<p>I am playing with the playing with the gcp python sdk sample (<a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/texttospeech/snippets/README.rst" rel="nofollow noreferrer">https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/texttospeech/snippets/README.rst</a>). I am able...
<python><google-cloud-platform>
2023-10-19 12:00:27
1
3,215
Kintarō
77,323,156
9,811,964
Cluster people based on spatial coordinates with constraints
<p>I have a pandas dataframe <code>df</code>. The columns <code>latitude</code> and <code>longitude</code> represent the spatial coordinates of people.</p> <pre><code>import pandas as pd data = { &quot;latitude&quot;: [49.5619579, 49.5619579, 49.56643220000001, 49.5719721, 49.5748542, 49.5757358, 49.5757358, 49.575735...
<python><pandas><machine-learning><cluster-analysis><k-means>
2023-10-19 10:52:38
1
1,519
PParker
77,323,105
5,002,316
Can NetworkX actually handle None weights as hidden edges in dijkstra's algorithm?
<p>Based on the sparse and opaque documentation of NetworkX, when calculating shortest paths, I've tried assigning weights using function to limit traversals to specific modes of travel. This weight function assigns the proper weight if the edge is among the traversable types, and <code>None</code> if the edge is any ...
<python><networkx><dijkstra>
2023-10-19 10:46:26
0
1,287
Aaron Bramson
77,322,856
9,234,092
Filter langchain vector database using as_retriever search_kwargs parameter
<p>How to <strong>filter a langchain vector database using search_kwargs parameter</strong> from the <em>as_retriever</em> function ?</p> <p>Here is an example of what I would like to do :</p> <pre class="lang-py prettyprint-override"><code># Let´s say I have the following vector database db = {'3c3bc745': Document(pag...
<python><langchain><information-retrieval><large-language-model><vector-database>
2023-10-19 10:10:35
3
703
JeanBertin
77,322,847
2,549,828
Mocking instance methods in python unittest
<p>I'm a software developer for several years but new to python. I'm writing a unit test (so no database connection present) that involves a model in Django that accesses another model referenced via a foreign key connection. I want to mock the method that accesses this connection and replace the result with a hard cod...
<python><python-3.x><django><django-rest-framework><python-unittest>
2023-10-19 10:09:36
1
1,148
Phocacius
77,322,763
1,193,138
python-configparser not found on ubuntu 22.04
<p>I'm trying to install this <a href="https://github.com/pimoroni/displayhatmini-python" rel="nofollow noreferrer">https://github.com/pimoroni/displayhatmini-python</a> on a raspberry pi running Ubuntu 22.04 and when I run the install.sh it fails on this:</p> <pre><code>E: Unable to locate package python-configparser ...
<python><raspberry-pi><python-3.10><ubuntu-22.04>
2023-10-19 09:56:17
1
1,072
omega1
77,322,726
11,737,958
How to filter words based on the position using regex in python
<p>I am new to python. I use python 3.8 version. I am trying to filter only the first whole word and then last word from the string except the numbers globally for any format using regex.</p> <p>Thanks in advance</p> <pre><code> s = 'abcd xyz efgh 1691 2191.7 1296 15.4 efgh eghj' print(re.search(r'[A-Za-z]+',s)) ...
<python><regex>
2023-10-19 09:52:06
1
362
Kishan
77,322,627
4,469,565
How to convert numbers from an image to a csv file using python
<p>I am trying to extract the words and numbers from this image:</p> <p><a href="https://i.sstatic.net/0tTTs.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0tTTs.png" alt="enter image description here" /></a></p> <p>my desired output is a csv table that directly imitates the table in the image.</p> <p>C...
<python><python-imaging-library><ocr><tesseract><python-tesseract>
2023-10-19 09:40:02
0
944
Joey
77,322,418
1,632,812
empty recordset. Why?
<p>In a Odoo 14 shell, I'm doing this</p> <pre><code>env['model_A'].search(['model_B_id', '=', '17' ]) </code></pre> <p>I know for sure that there are several records in model_A with the field model_B_id set to 17</p> <p>I get an empty recordset back</p> <pre><code>model_A() </code></pre> <p>Why ?</p>
<python><odoo><odoo-14>
2023-10-19 09:09:44
1
603
user1632812
77,322,412
2,123,706
Extract all keys from nested Python dictionary
<p>I have a nested Python dictionary, with lower levels containing lists of dictionaries. The nesting goes up to 7 levels.</p> <p>My sample data:</p> <pre><code>d = {'a':'ewr0', 'b':1234, 'c':{'c1':1234,'c2':456}, 'd':[{'d1':123, 'd2':[12,23,34,45,56], 'd3':{'d4':98,'d5':87}},{'d6':1,'d7':[1,2,3,4,5,6],'d8'...
<python><dictionary>
2023-10-19 09:08:38
2
3,810
frank
77,322,360
3,420,542
AWS Lambda HTTP 503 when opening amazon urls
<p>Hello I developed an AWS Lambda which makes an http request to amazon url to get the web page content. The problem I have regards the HTTP 503 error I get every time I run the lambda. Running the code locally it works fine but on AWS it doesn't.</p> <p>I am using <code>Python 3.7</code> and <code>urllib</code> modul...
<python><http><aws-lambda><urllib><http-status-code-503>
2023-10-19 09:01:41
0
748
xXJohnRamboXx
77,322,139
1,210,075
blob.generate_signed_url() cloud urls return SignatureDoesNotMatch after a few days occasionally
<p>When I sign a google cloud storage url in App Engine, the url returns <code>SignatureDoesNotMatch</code> after a few days, but only sometimes.</p> <p>Based on <a href="https://stackoverflow.com/questions/55231676/cloud-storage-download-urls-fail-after-three-days-maybe-due-to-content-type">Cloud Storage download URLs...
<python><google-app-engine><google-cloud-storage>
2023-10-19 08:30:36
1
2,929
Scott Driscoll
77,321,879
11,688,559
Deploying Python functions that compile via Numba on the Google Cloud Platform: state must be maintained
<p>I am running timeseries forecasts for multiple products using the <a href="https://nixtla.github.io/statsforecast/" rel="nofollow noreferrer">StatsForecast library from Nixtla</a>. It is a brilliant library. Its most attractive feature would be the speed and reliability of its autoARIMA script. According to the docu...
<python><google-cloud-platform><virtual-machine><google-compute-engine><numba>
2023-10-19 07:49:30
1
398
Dylan Solms
77,321,812
1,864,294
ThreadPoolExecutor exits before queue is empty
<p>My goal is to concurrently crawl URLs from a queue. Based on the crawling result, the queue may be extended. Here is the MWE:</p> <pre><code>import queue from concurrent.futures import ThreadPoolExecutor import time def get(url): # let's assume that the HTTP magic happens here time.sleep(1) return f'data fr...
<python><concurrent.futures>
2023-10-19 07:37:33
2
20,605
Michael Dorner
77,321,688
1,123,094
calling sg.popup when SystemTray (psgtray) running
<pre class="lang-py prettyprint-override"><code>import PySimpleGUI as sg from psgtray import SystemTray import pyaudio import threading def findAudioDevices(): p = pyaudio.PyAudio() info = p.get_host_api_info_by_index(0) numdevices = info.get('deviceCount') device_info = &quot;&quot; for i in rang...
<python><pysimplegui><system-tray>
2023-10-19 07:15:40
1
2,250
willwade
77,321,623
13,560,598
Tensorflow float64 error while running in eager execution
<p>I'm using TF 2.13.0 and I'm getting an error only when eager execution is enabled. Is there a workaround?</p> <p>The error is</p> <pre><code>tensorflow.python.framework.errors_impl.InvalidArgumentError: TensorArray dtype is float64 but Op is trying to write dtype float32 </code></pre> <p>The code is</p> <pre><code>i...
<python><tensorflow><eager-execution>
2023-10-19 07:03:01
1
593
NNN
77,320,932
1,609,428
how to constrain a (cubic) regression model to pass through certain points?
<p>Consider the following example:</p> <pre><code>import statsmodels.formula.api as smf import random import pandas as pd df = pd.DataFrame({'y' : [x**2 + random.gauss(2) for x in range(10)], 'x' : [x for x in range(10)]}) model = smf.ols(data = df, formula = 'y ~ x + I(x**2) + I(x**3)').fit() df['...
<python><scikit-learn><statsmodels>
2023-10-19 04:16:38
1
19,485
ℕʘʘḆḽḘ
77,320,798
1,686,628
Connecting MongoDB from localhost
<p>I have an EC2 instance (<code>EC2_VM</code>) where I can connect mongodb (<code>MONGO_HOST</code>)from</p> <pre><code>with sshtunnel.open_tunnel( (EC2_VM, 22), ssh_username=&quot;ec2-user&quot;, ssh_pkey=EC2_KEY, remote_bind_address=(MONGO_HOST, 27017), local_bind_address=(&quot;0.0.0.0&quot;, 27...
<python><pymongo><ssh-tunnel><aws-documentdb>
2023-10-19 03:27:20
1
12,532
ealeon
77,320,733
1,588,847
Preserving DatetimeIndex `freq` in MultiIndex in Pandas
<p>I have a <code>pd.DatetimeIndex</code> with a <code>freq</code> which I want to use as part of a <code>pd.MultiIndex</code>, but when I do so the freq gets set to <code>None</code>. Can I preserve the freq?</p> <pre><code>[1]: dates = pd.date_range('2000-01-01', '2000-03-31', freq='M') labls = pd.Index(['AA','B...
<python><pandas><multi-index>
2023-10-19 03:09:44
0
2,124
Jetpac
77,320,676
10,431,629
Update a Table using a Python Dictionary keys and values for where Clause
<p>I wish to update a SQL Server table. Its a big table (with multiple items to be updated at one shot) and I have an issue in updating that by putting where statements manually. So I created a Python dictionary to use the key value pairs as set value for the value (if it exists) for where condition from the key. If th...
<python><sql-server><pandas><dictionary><sql-update>
2023-10-19 02:49:30
1
884
Stan
77,320,560
471,478
map numpy array by numpy array
<p>I want to map the values in an array by some other array which maps the values from that array to new values by index.</p> <p>Example:</p> <pre><code>arr = np.array([0, 1, 2, 3, 0, 4, 3, 3, 1, 4, 0, 0, 0, 2]) tbl = np.array([0, 1, 1, 0, 2]) res = np.array([tbl[x] for x in arr]) print(arr) # [0 1 2 3 0 4 3 3 1 4 0 ...
<python><arrays><numpy>
2023-10-19 02:12:39
1
12,364
scravy
77,320,495
5,792,426
How to bypass the TTL of 30 seconds while waiting response of post request from external server
<p>I am building a view in Django , which will send a POST request to chat-gpt API, the problem that I am facing that the response from chat-gpt is taking more than 30 seconds (we are having a long prompts) the idea that I have in mind is:</p> <ol> <li>The client sends a request to the server.</li> <li>The server write...
<python><django><kubernetes><google-cloud-platform><openai-api>
2023-10-19 01:48:36
1
557
ladhari
77,320,462
2,954,547
Row indexing/subsetting with only part of a MultiIndex
<p>Given the following DataFrame and MultiIndex instances:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( {'x': [1,2,3]}, index=pd.MultiIndex.from_tuples( [('a', 'p', 1), ('b', 'z', 3), ('a', 'q', 2)], names=['l1', 'l2', 'l3'], ), ) idx = pd.Mult...
<python><pandas><dataframe>
2023-10-19 01:37:30
1
14,083
shadowtalker
77,320,311
6,759,459
HTTP401 Error in Twilio WhatsApp when retrieving Audio Message
<p>I am trying to access the audio message a user sends over WhatsApp via the Twilio API.</p> <p>Here's my error:</p> <blockquote> <p>ERROR:services.audio_processing:HTTP error: 401 Client Error: Unauthorized for url: <a href="https://api.twilio.com/2010-04-01/Accounts/ACa6d0fade9bfb1f8bfdd3238b6ca522b1/Messages/MM503f...
<python><twilio><chatbot><openai-whisper>
2023-10-19 00:30:06
1
926
Ari
77,320,301
1,634,986
Drawing text along an arbitrary path using matplotlib TextPath
<p>Similar to drawing text along an arbitrary path using SVG <code>textPath</code>, I would like to do something similar using <code>matplotlib</code> From <a href="https://stackoverflow.com/a/44521963/1634986">this SO answer</a>, it is possible to do by subclassing the <code>Text</code> class. However, I'd like to use...
<python><matplotlib>
2023-10-19 00:24:36
0
384
nawendt
77,320,211
310,399
pathlib replace() fails to move existing files
<p>I have a script that dumps output into a &quot;RUNNING&quot; directory tree. When the script completes, I want to move the output into a PASS or FAIL directory tree, depending on how things went.</p> <p>I'm having a devil of a time getting pathlib replace() to perform the move. For example:</p> <pre><code>source_d...
<python><pathlib>
2023-10-18 23:54:07
1
16,427
JS.
77,320,064
3,821,009
polars read_json schema named colums with inferred types
<p>The docs for <a href="https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.read_json.html#polars.read_json" rel="nofollow noreferrer">polars.read_json</a> say:</p> <blockquote> <p>schema : Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict The DataFrame schema may be declared in several...
<python><python-polars>
2023-10-18 23:02:24
0
4,641
levant pied
77,319,957
3,103,957
Necesscity of pip inside conda environment
<p>When Anaconda installed, additional packages can be installed in the environments using <code>conda install</code> command. But I see people using <code>pip</code> command inside an activated environment created/managed by conda.</p> <p>Are there any reasons why it becomes necessary to use <code>pip</code> when we h...
<python><pip><anaconda>
2023-10-18 22:28:01
1
878
user3103957
77,319,904
13,084,917
Why am I getting the same result in different elements with Selenium?
<p>I have a simple question. I am not sure why - maybe a really silly mistake - but I couldn't figure out why this code gives me the same result.</p> <p>The code:</p> <pre><code>rows = table.find_elements(By.XPATH, &quot;//div[@role='row']&quot;) for row in rows: print(row) print(row.find_element(By...
<python><selenium-webdriver>
2023-10-18 22:13:34
1
884
omerS
77,319,901
9,760,446
Show percentage of total in pandas pivot table with multiple columns based on single field in dataframe
<p>Example dataframe, also available as <a href="https://onecompiler.com/python/3zqvhgc2g" rel="nofollow noreferrer">a fiddle</a>:</p> <pre><code>import pandas as pd d = { &quot;year&quot;: [2021, 2021, 2021, 2021, 2022, 2022, 2022, 2023, 2023, 2023, 2023], &quot;type&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;B&...
<python><pandas>
2023-10-18 22:11:26
2
1,962
Arthur Dent
77,319,872
4,707,978
Text to Tag similarity word2vec
<p>Our users will give a 2 to 3 sentence description about their profession. Example user A (profile description): <code>I am a data scientist living in Berlin, I like Japanese food and I am also interested in arts.</code></p> <p>Then they also give a description about what kind of person they are looking for. Example ...
<python><machine-learning><artificial-intelligence><word2vec><part-of-speech>
2023-10-18 22:04:40
2
3,431
Dirk
77,319,805
1,887,919
Vectorization of complicated matrix calculation in Python
<p>I have a 3x3 matrix which I can calculate as follows</p> <pre class="lang-py prettyprint-override"><code> e_matrix = np.array([m[i]*m[j]-n[i]*n[j] for i in range(3) for j in range(3)]) </code></pre> <p>where <code>m</code> and <code>n</code> are both length-3 vectors. This works ok ✅</p> <p>Now suppose that <cod...
<python><numpy><matrix><vectorization><numba>
2023-10-18 21:49:03
3
923
user1887919
77,319,729
160,245
How to store decimals and dates using PyMongo from a Python Dictionary (to MongoDB)
<p>Here is a code fragment that I used to test. I'm trying to determine what happens when you use dictionary vs JSON style, and when you use a variable.</p> <pre><code> from decimal import * from pymongo import MongoClient my_int_a = &quot;21&quot; my_int_b = 21 row_dict = {} row_dict[...
<python><python-3.x><mongodb><decimal><pymongo>
2023-10-18 21:32:09
2
18,467
NealWalters
77,319,639
3,377,314
Running a shiny python app from a script with `reload`
<p>I was trying to run the example python shiny app directly from a script</p> <pre><code>&quot;&quot;&quot;Test shiny app.&quot;&quot;&quot; import argparse from shiny import App, render, ui app_ui = ui.page_fluid( ui.input_slider(&quot;n&quot;, &quot;N&quot;, 0, 100, 20), ui.output_text_verbatim(&quot;txt&...
<python><py-shiny>
2023-10-18 21:12:53
1
969
Devil
77,319,595
4,212,875
Python script containing connection to psycopg2 exits without error on Windows Command Prompt
<p>When I try to run a python script on windows command prompt using</p> <pre><code>&quot;C:\path_to_conda_env\anaconda3\envs\virutal_env\python.exe&quot; &quot;C:\path_to_script\script.py&quot; </code></pre> <p>the script executes until it hits a connection I'm making to using <code>psycopg2</code> and then exits with...
<python><python-3.x><windows><command-line>
2023-10-18 21:05:27
0
411
Yandle
77,319,523
19,123,103
ValueError: putmask: mask and data must be the same size
<p>I have a pandas dataframe and I wanted to replace its index values using the <code>where()</code> method, but I got the following error.</p> <blockquote> <p>ValueError: putmask: mask and data must be the same size</p> </blockquote> <p>How do I solve this error?</p> <p>Steps to reproduce the error:</p> <pre class="la...
<python><pandas><valueerror>
2023-10-18 20:50:36
1
25,331
cottontail
77,319,516
21,024,780
Lazy import from a module (a.k.a. lazy evaluation of variable)
<p>Lazy imports in Python have been long discussed and some proposals (for example the <a href="https://peps.python.org/pep-0690/" rel="nofollow noreferrer">PEP609 - Lazy Imports</a>) have been made to make it a built-in (optional) feature in the future.</p> <p>I am developing a CLI package, so startup time is very imp...
<python><python-3.x><python-import><python-importlib>
2023-10-18 20:49:05
2
478
atteggiani
77,319,444
19,299,757
How to specify API Gateway URL in cloudformation script
<p>I am using cloudformation script yaml file to create resources on AWS dev account.</p> <p>My goal is to create a lambda function with API gateway endpoint. The lambda function is created successfully and also the gateway within it. But when I tried to specify the API end point URL in the script, I am greeted with th...
<python><amazon-web-services><aws-lambda><aws-cloudformation><aws-api-gateway>
2023-10-18 20:35:51
1
433
Ram
77,319,419
788,022
Redeploying Google cloud function looses python dependencies
<p>I have a simple cloud function that contains the main.py file, and a requirements.txt.</p> <p>This is the content of the main.py:</p> <pre><code>from superpackage.subpackage import TheSuperClass def watch_function(event, context): print(f&quot;Event ID: {context.event_id}&quot;) print(f&quot;Event type: {co...
<python><google-cloud-functions><google-cloud-sdk>
2023-10-18 20:30:57
1
1,255
pjotr_dolphin
77,319,397
10,886,283
How to avoid overlapping between boxes and whiskers in boxplot?
<p>When trying not to show outlines while plotting boxes in a boxplot, whiskers may overlap. Is there a way to avoid it? (perhaps changing the order patches are display and send whiskers behind)</p> <p>Consider this minimal reproducible example:</p> <pre><code>import matplotlib.pyplot as plt bp = plt.boxplot([1,2,3], ...
<python><matplotlib><boxplot><overlap>
2023-10-18 20:26:59
1
509
alpelito7
77,319,342
3,973,175
Adding color bar to 1D heatmap
<p>I have found an excellent answer from <a href="https://stackoverflow.com/questions/45841786/creating-a-1d-heat-map-from-a-line-graph">Creating a 1D heat map from a line graph</a> but I need a color reference/side bar to show what numerical values each color represents.</p> <p>There is a comment asking this same ques...
<python><matplotlib><colorbar><imshow>
2023-10-18 20:16:54
0
6,227
con
77,319,296
2,334,833
JQ Query - Restructuring a nested JSON
<p>I have a JSON which looks like this:</p> <pre><code>{ &quot;orders&quot;: [ { &quot;order&quot;: [ { &quot;items&quot;: [ { &quot;name&quot;: &quot;Item 1&quot;, &quot;id&quot;: [], &quot;type&quot;: [ { ...
<python><json><jq>
2023-10-18 20:09:43
3
329
Aksanth
77,319,282
1,445,660
AWS RDS Postgres error - "no pg_hba.conf entry for host..."
<p>I have two rds postgres databases. One in eu-west-1 (Ireland) and one in us-east-1 (N. Virginia). The one in eu-west-1 suddenly throws this error:</p> <pre><code> sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at &quot;database-2.&lt;xxx&gt;.eu-west-1.rds.amazonaws.com&quot; (&lt;d...
<python><postgresql><amazon-web-services><sqlalchemy><amazon-rds>
2023-10-18 20:07:51
1
1,396
Rony Tesler
77,319,279
740,488
langchain csvLoader error openai.error.InvalidRequestError: '$.input' is invalid
<p>I am using a simple langchain CSVLoader to load a sample data that I downloaded from <a href="https://www.stats.govt.nz/assets/Uploads/Annual-enterprise-survey/Annual-enterprise-survey-2021-financial-year-provisional/Download-data/annual-enterprise-survey-2021-financial-year-provisional-csv.csv" rel="nofollow norefe...
<python><openai-api><langchain><py-langchain>
2023-10-18 20:07:32
0
1,220
gospodin
77,319,228
1,391,441
Conflict between logging module, Latex and matplotlib
<p>The following example:</p> <pre><code>import logging import matplotlib.pyplot as plt import matplotlib.pyplot as mpl mpl.rc('font', family='serif', serif=&quot;DejaVu Serif&quot;) mpl.rc('text', usetex=True) # Set up logging module level = logging.INFO frmt = '%(message)s' handlers = [ logging.FileHandler(&quo...
<python><matplotlib><logging><latex>
2023-10-18 19:56:04
1
42,941
Gabriel
77,319,204
9,811,964
Shift rows with identical spatial coordinates into a different cluster in pandas dataframe
<p>I have a pandas dataframe <code>df</code>. The columns <code>latitude</code> and <code>longitude</code> represent the spatial coordinates of people.</p> <pre><code>import pandas as pd data = { &quot;latitude&quot;: [49.5619579, 49.5619579, 49.56643220000001, 49.5719721, 49.5748542, 49.5757358, 49.5757358, 49.575735...
<python><pandas><dataframe><cluster-analysis>
2023-10-18 19:52:49
0
1,519
PParker