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,009,197
5,470,144
QSortFilterProxyModel - not updating
<p>I am trying to use <code>QTableView</code> with a custom model and <code>QSortFilterProxyModel</code>.</p> <p>If I set the base model: <code>self.setModel(self._model)</code> the table displays correctly.</p> <p>However, if I set the proxy model: <code>self.setModel(self._proxy_model)</code> no rows are displayed.</...
<python><pyqt><pyqt5><qtableview><qabstracttablemodel>
2023-08-30 14:58:20
0
4,082
Elad Weiss
77,009,176
1,583,083
Pandas: ValueError parsing UNIX timestamp
<p>I have a CSV of OHLC data that is indexed by seconds since the epoch: <a href="https://i.sstatic.net/iHUx1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iHUx1.png" alt="tabulated CSV data" /></a></p> <p>I am parsing it thus:</p> <pre><code>df = pd.read_csv(f&quot;{CSV}/{filename}&quot;, sep=&quot;,&...
<python><pandas><datetime><datetime-format>
2023-08-30 14:55:39
1
1,748
ultra909
77,009,090
6,645,564
How do I get the information in the hoverbox of my plotly figure to be reordered when I have hovermode set to 'x unified'?
<p>I have built a plotly figure that mostly consists of go.Scatter traces. Each of these traces have slightly different hovertemplates, but I want the information in the hoverbox to be consolidated, so I set the hovermode to 'x unified', which solves my main issue, but I have another small problem that I'd like to reso...
<python><plotly>
2023-08-30 14:44:14
1
924
Bob McBobson
77,009,012
1,028,270
How do I properly import RaisesContext from pytest for my type hints?
<p>I want to use type hints everywhere include my helper functions in my test suite.</p> <p>A snippet of a function looks like this:</p> <pre><code>def my_helper( should_exit: RaisesContext = None, ): # do stuff </code></pre> <p>And it is passed a RaisesContext like this:</p> <pre><code>my_helper(pytest.raises(...
<python><pytest>
2023-08-30 14:35:24
1
32,280
red888
77,008,905
6,849,045
anaconda falls back to wrong python version on a local environment in vscode
<p>I'm trying to run an ipynb file in vscode and I'm stuck. The extension host keeps crashing and I think I might've found a culprit.</p> <p>Some info about what I'm working with:</p> <ul> <li>I'm working on a relatively old macOS (10.13.6)</li> <li>I have a completely fresh anaconda install (conda 23.7.2)</li> </ul> <...
<python><visual-studio-code><anaconda><anaconda3>
2023-08-30 14:21:00
2
1,072
Typhaon
77,008,806
11,117,255
Youtube-dl error message: Got error: HTTP Error 403: Forbidden
<p>I want to download a video with youtubedl</p> <p>I have my options to set to:</p> <pre><code>ydl_opts = { 'verbose': False, 'ignoreerrors': True, 'cachedir': None, 'outtmpl': &quot;%(title)s.%(ext)s&quot;, 'format': 'm4a/bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudi...
<python><python-3.x><youtube><youtube-dl>
2023-08-30 14:08:29
2
2,759
Cauder
77,008,766
7,484,093
Trimming outliers in the pandas dataframe, using logical operators >= and <=
<p>I have a dataframe with 50+ (see an example with 2 only)</p> <pre><code>data = { &quot;Blood&quot;: [26, 48, 41, 80, 66, 40, 7, 73, 60, 61, 52, 76, 40, 53, 2, 9, 100, 59, 99, 82, 100, 82, 62, 73], &quot;Urine&quot;: [76, None, 20, 84, 30, 60, 0, 46, 50, 58, None, 66, 40, 22, 66, 18, 0, 60, 1, 78, None, 80, 77, 83]} ...
<python><numpy><operators><outliers>
2023-08-30 14:03:09
0
2,520
Anakin Skywalker
77,008,586
4,113,031
Detecting duplicates and managing documents in Redis
<p>Our team uses Redis as a vector store for our Langchain application. We store text chunks as hashes with indexed keys, and fields of metadata, content, and vector. The issue arises when we are trying to identify and remove duplicates from the vector store. Our current method requires retrieving all the keys into Pyt...
<python><redis><chatbot><langchain><semantic-search>
2023-08-30 13:38:46
0
1,178
Niv Cohen
77,008,560
16,428,425
How to make Kivy app stay in the Task Bar on close
<p>How to make the Kivy app stay in the Task Bar on close and how to add a list to manage it as I showed in the following pictures, Can anyone please show me where is that documented or I can read about it?</p> <p>here is an example:</p> <p><a href="https://i.sstatic.net/W7lpB.png" rel="nofollow noreferrer"><img src="h...
<python><kivy>
2023-08-30 13:36:10
1
562
Abdelrahman Khallaf
77,008,517
2,622,368
How to get object's value if key name contains dots in jsonpath
<p>The following code all returns False.</p> <pre class="lang-py prettyprint-override"><code>import jsonpath data = {'layers': {'urlencoded-form.key': [&quot;1234&quot;]}} assert jsonpath.jsonpath(data, '$..urlencoded-form.key') == False assert jsonpath.jsonpath(data, '$..[urlencoded-form.key]') == False assert jsonpa...
<python><jsonpath>
2023-08-30 13:30:44
0
829
wgf4242
77,008,404
913,098
Do I have to pass the dataset both to the loader and the RandomSampler?
<p>This is my code</p> <pre><code> def train_dataloader(self): if self._is_weighted_sampler: weights = list(self.label_weight_by_name.values()) sampler = torch.utils.data.sampler.WeightedRandomSampler( torch.tensor(weights), len(weights) ) else: ...
<python><deep-learning><pytorch>
2023-08-30 13:15:49
1
28,697
Gulzar
77,008,355
21,404,794
Efficiently finding values in pandas dataframe filtering by different columns
<p>I'm doing some work with a pandas dataframe, and I need to filter the data according to different columns. This is easily done with pandas syntax, as shown in the Minimal Working Example below:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd #Create DataFrame df = pd.DataFrame({'col1':['one'...
<python><pandas><dataframe>
2023-08-30 13:07:54
4
530
David Siret Marqués
77,008,280
4,935,114
Numpy: convert xyzV table to a grid
<p>I have this text file I can read with <code>numpy.loadtxt</code> into a 2D array:</p> <pre><code> X Y Z V -30 -15 -25 2 -29 -15 -25 2.1 -28 -15 -25 2.2 . . . . . . . . +29 -15 -25 2.1 +30 -15 -25 -2.0 -30 -14 -25 2 # now iterating X values while Y=-14 -29 -14 -25 2.1 -28 . . 2.2 ....
<python><numpy><reshape>
2023-08-30 12:59:26
1
2,916
Doron Behar
77,008,194
5,300,978
cannot import class ReduceDocumentsChain
<p>I am trying to import a library called <code>ReduceDocumentsChain</code>, I found out how to import <code>MapReduceDocumentsChain</code> but still no luck about the first one.</p> <p><code>from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain</code></p> <p>I am following this tutorial:</p...
<python><langchain>
2023-08-30 12:48:13
2
1,324
M. Mariscal
77,008,178
5,576,083
Fill a pandas dataframe with string values
<p>I have a pandas dataframe like this</p> <pre><code>import pandas as pd data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'year': [2012, 2012, 2013, 2014, 2014], 'reports': [4, 24, 31, 2, 3]} DF = pd.DataFrame(data) </code></pre> <p>I need to add a new column named &quot;key&quot; to be fil...
<python><pandas>
2023-08-30 12:46:03
1
301
ilFonta
77,008,165
9,681,081
Official API for typing.Generic.__orig_bases__
<p>I have a generic type for which I'd like to retrieve at runtime the type of its type variable.</p> <p>The following snippet runs well, but it uses <code>Generic.__orig_bases__</code> which is not an official API (its use is discouraged in <a href="https://peps.python.org/pep-0560/#mro-entries" rel="noreferrer">PEP 5...
<python><generics><python-typing>
2023-08-30 12:42:47
1
2,273
Roméo Després
77,008,053
9,311,137
Selective/Combined Type Hints (Literals etc.)
<p>Is it possible to combine (perhaps not the right word) two or more sets of type hints such that they are only valid in specific combinations?</p> <p>I have a function that takes <code>value</code> and <code>value_type</code> arguments. (these later get fed into a graphQL API where I use both values to set up filteri...
<python><python-typing>
2023-08-30 12:28:27
1
684
ch4rl1e97
77,007,885
21,303,427
Pydantic V2 `model_validator(mode="wrap")` - How to use `ModelWrapValidatorHandler`
<p>In short I want to implement a <code>model_validator(mode=&quot;wrap&quot;)</code> which takes a <code>ModelWrapValidatorHandler</code> as argument. I guess this validation handler just calls at least all before-validators.</p> <pre class="lang-py prettyprint-override"><code>class A(BaseModel): x: str y: int...
<python><pydantic>
2023-08-30 12:08:13
1
493
lord_haffi
77,007,846
2,988,360
Cannot open Edge with selenium on Ubuntu
<p>I am trying to open Edge from selenium with python selenium-4.11.2.</p> <p>I have downloaded the msedgedriver (version 115.0.1901.203; same as installed Edge) and run the following code snippet:</p> <pre><code>from selenium import webdriver edgedriver = join(HOME, &quot;webdrivers&quot;, &quot;msedgedriver&quot;) ...
<python><selenium-webdriver><webdriver><microsoft-edge>
2023-08-30 12:05:08
1
5,233
PKlumpp
77,007,440
14,282,714
ValueError: Tokenizer class LlamaTokenizer does not exist or is not currently imported
<p>I am trying to run the code from this <a href="https://huggingface.co/blog/llama2" rel="noreferrer">Hugging Face blog</a>. At first, I had no access to the model so this error: <a href="https://stackoverflow.com/questions/77006745/oserror-meta-llama-llama-2-7b-chat-hf-is-not-a-local-folder">OSError: meta-llama/Llama...
<python><huggingface-transformers><huggingface><llama>
2023-08-30 11:11:33
1
42,724
Quinten
77,007,331
1,801,242
Not able to click a button with Selenium Python
<p>I am using Selenium to click a button but I am getting a <code>ElementNotInteractableException</code>.</p> <p>Here is the Selenium Python snipit:</p> <pre><code>b.driver.find_element(By.CLASS_NAME,&quot;button-prm-light&quot;).click() </code></pre> <p>Here is the html:</p> <pre><code>&lt;button class=&quot;button-pr...
<python><selenium-webdriver>
2023-08-30 10:54:01
2
333
Justin
77,007,324
4,405,942
os.path.getmtime() inconsistent with time.time()
<p>I'm trying to verify the time of most recent modification of a file and got to the following:</p> <pre><code> print(&quot;before&quot;, time.time()) with open(file, &quot;wb&quot;) as fh: fh.write(b&quot;12345&quot;) print(&quot;after&quot;, time.time()) print(&quot;modified&quot;, os.path.get...
<python><python-os>
2023-08-30 10:52:51
1
2,180
Gerry
77,007,304
4,564,080
Count of specific value of column in group
<p>I am trying to achieve the following:</p> <pre class="lang-py prettyprint-override"><code>aggregate_commitment_df = commitment_df.group_by(&quot;sprint_start_date&quot;, &quot;squad&quot;).agg( stories_committed=pl.count(pl.col(&quot;issue_type&quot;) == &quot;Story&quot;), spikes_committed=pl.count(pl.col(&...
<python><python-polars>
2023-08-30 10:49:54
1
4,635
KOB
77,007,211
1,714,692
Scale only 2 axis in a 3d matplotlib
<p>Consider the case where a maplotlib 3d plot have 2 axis that represents the same kind of measurement (for example a length) and another one of a different kind (for example time). I would like to scale only 2 axis (the ones representing the length) but not the other one. In a 2d plot I would do this with <code>ax.ax...
<python><matplotlib>
2023-08-30 10:36:13
1
9,606
roschach
77,007,186
392,041
Apache beam python looking up value in other collection
<p>I am trying to lookup a value in a seperate big query table, i need to lookup the link_url in table one using the url in table 2. From table 1 i need just the link_id</p> <p>table 1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>link_id</th> <th>link_url</th> </tr> </thead> <tbody> <tr>...
<python><google-bigquery><apache-beam>
2023-08-30 10:31:28
1
562
Josh Fradley
77,007,171
1,627,466
Apply function with two arguments on same list and output only lower/upper triangular matrix without diagonal
<p>I want to compare strings without unecessary comparisons, so far I have:</p> <p><code>[[[dice_coefficient(x,y) for x in ['a','a','b'][j]] for y in ['a','a','b'][0:j]] for j in [1,2]]</code></p> <p>where <code>dice_coefficient</code> is defined <a href="https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/D...
<python><pandas><group-by><list-comprehension><apply>
2023-08-30 10:29:38
2
423
user1627466
77,006,962
10,291,435
how to keep sources field in answer of langchain while having custom prompt
<p>I am trying to write a code to answer questions using langchain like this:</p> <pre><code>db = ElasticVectorSearch( elasticsearch_url=url, index_name=index_name, embedding=embeddings ) qa_chain = RetrievalQAWithSourcesChain.from_chain_type( llm=llm, ch...
<python><elasticsearch><openai-api><langchain>
2023-08-30 10:00:27
1
1,699
Mee
77,006,924
17,082,611
Debugging autoencoder training (loss is low but reconstructed image is all black)
<p>I am implementing a (variational) autoencoder (VAE) in Keras following <a href="https://keras.io/examples/generative/vae/" rel="nofollow noreferrer">this guide</a>.</p> <p>The VAE reads data from <code>topomaps</code> folder and labels from <code>labels</code> folder. They both contain <code>.npy</code> files, <a hr...
<python><tensorflow><keras><deep-learning><autoencoder>
2023-08-30 09:57:06
2
481
tail
77,006,856
6,999,569
What is the best python data structure for the contents of jupyter notebook files?
<p>I want to convert jupyter notebooks to python files, but before doing so, I want to filter their contents, e.g. remove all markdown cells; therefore the gui export functionality or calling nbconvert from the command line doesn't exactly satisfy my needs.</p> <p>What I want to do therefore is to first load the conten...
<python><jupyter-notebook>
2023-08-30 09:49:26
1
846
Manfred Weis
77,006,745
14,282,714
OSError: meta-llama/Llama-2-7b-chat-hf is not a local folder
<p>I'm trying to replied the code from this <a href="https://huggingface.co/blog/llama2" rel="nofollow noreferrer">Hugging Face blog</a>. At first I installed the transformers and created a token to login to hugging face hub:</p> <pre><code>pip install transformers huggingface-cli login </code></pre> <p>After that it i...
<python><huggingface-transformers><huggingface><llama>
2023-08-30 09:34:39
2
42,724
Quinten
77,006,730
664,160
How can I check what is the maximum python version that I can use with in my Django?
<p>I'm using Django with many pip modules; python version is 3.7.5. I want to write a script that will tell me at any given moment what is the maximum python version that I can use without pip module changes. Thank you.</p>
<python><django><dependencies>
2023-08-30 09:33:13
1
3,433
kambi
77,006,669
2,195,440
how to install from the output of conda dependency export
<p>I generated <strong>dependency list</strong> using:</p> <pre><code>conda list -e &gt; requirements.txt </code></pre> <p>Here are some parts of the <code>depency</code> file:</p> <pre><code>transformers=4.28.1=pypi_0 typing-extensions=4.7.1=py310hecd8cb5_0 typing_extensions=4.7.1=py310hecd8cb5_0 tzdata=2023.3=pypi_0 ...
<python><anaconda><dependencies><conda><miniconda>
2023-08-30 09:25:34
1
3,657
Exploring
77,006,611
16,383,578
How to make all values in an array fall into a range?
<p>Say I have a NumPy array of <code>float</code>s, there are positive values and negative values. I have two numbers, say they are <code>a</code> and <code>b</code>, <code>a &lt;= b</code> and <code>[a, b]</code> is a (closed) number range.</p> <p>I want to make all of the array fall into the range <code>[a, b]</code>...
<python><arrays><python-3.x><numpy>
2023-08-30 09:17:53
1
3,930
Ξένη Γήινος
77,006,453
5,013,084
Nested axis labels in altair plot?
<p>It it possible to create nested in altair, similar to this from the <code>ggh4x</code> package?</p> <p><a href="https://i.sstatic.net/6D6Jb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6D6Jb.png" alt="enter image description here" /></a></p>
<python><altair>
2023-08-30 08:58:20
0
2,402
Revan
77,006,235
5,759,881
Route modules import
<p>I want to route a module import in python dynamically. See the example</p> <pre><code>src ├── main.py ├── module1 │   └── lib.py └── module2 └── lib.py </code></pre> <p>in main.py</p> <pre><code>import src.module.lib (... use the module...) </code></pre> <p>Imagine I have an env var <strong>$MODULE</strong>, if...
<python><module>
2023-08-30 08:32:44
0
1,646
Montenegrodr
77,006,133
2,195,440
Issue with running Starcoder Model on Mac M2 with Transformers library in CPU environment
<p>I'm attempting to run the Starcoder model on a Mac M2 with 32GB of memory using the Transformers library in a CPU environment. Despite setting load_in_8bit=True, I'm encountering an error during execution. Below is the relevant code:</p> <pre><code>from transformers import AutoModelForCausalLM, AutoTokenizer checkp...
<python><pytorch><huggingface-transformers><huggingface>
2023-08-30 08:18:32
0
3,657
Exploring
77,006,126
19,500,571
Merging dataframes on one column while replacing values with another column
<p>I have two dataframes:</p> <pre><code>mapping = pd.DataFrame({'idx': ['a','b','c'], 'val': [1, 2, 3]}) obs = pd.DataFrame({'obs': ['a','c','a','a','b','d']}) </code></pre> <p>I would like for all observations in <code>obs</code>, that are present in <code>mapping</code>s <code>idx</code> column, to get the value of ...
<python><pandas>
2023-08-30 08:17:49
2
469
TylerD
77,006,058
4,050,510
Differences between Protocol.__call__ vs Callable?
<p>I have a function</p> <pre class="lang-py prettyprint-override"><code>def run_thing(cb: Callback) -&gt; Result: w: Widget = make_widget() res: Result = cb(w) return res </code></pre> <p>I can imagine two ways to define the Callback type.</p> <pre class="lang-py prettyprint-override"><code># Option 1: Callable ...
<python><python-typing><callable>
2023-08-30 08:09:13
2
4,934
LudvigH
77,005,993
5,224,236
in kedro / pyspark how to use MemoryDataset
<p>I am trying to use a MemoryDataset with kedro, in order to not save the intermeiate result to disk.</p> <pre><code># nodes.py def preprocess_format_tracksessions(tracksess: DataFrame, userid_profiles:pd.DataFrame , parameters: Dict) -&gt; MemoryDataset: </code></pre> <p>In the pipeline I am defining the node output ...
<python><pyspark><kedro>
2023-08-30 07:58:37
1
6,028
gaut
77,005,980
1,864,294
Extent in cartopy
<pre><code>import matplotlib.pyplot as plt from cartopy import crs as ccrs, feature as cfeature import cartopy.io.shapereader as shpreader fig = plt.figure(figsize=(11, 11)) ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=0)) ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, ...
<python><cartopy>
2023-08-30 07:56:30
1
20,605
Michael Dorner
77,005,909
111,424
How do I test that a given shell has been executed in Python?
<p>I want to test a Python function that executes a shell command.</p> <p>According to <a href="https://testfixtures.readthedocs.io/en/latest/popen.html" rel="nofollow noreferrer">testfixtures</a> there are two approaches:</p> <ul> <li>execute a real process and check the result</li> <li>mock the subprocess module and ...
<python><linux><pytest><ptrace>
2023-08-30 07:46:28
2
21,216
Iain Samuel McLean Elder
77,005,545
9,202,041
Data subsets from multiyear timeseries data
<p>I have 15 mins multiyear timeseries data (a total of 16 years) from 2007 - 2022. Data looks like <a href="https://docs.google.com/spreadsheets/d/1FJ0n-hAPvtr62ZXwaVTHBhsDiRLxYyX_/edit#gid=1159949573" rel="nofollow noreferrer">this</a>. I want to make all possible subsets out of this data. Each subset should have one...
<python><dataframe><subset><permutation>
2023-08-30 06:49:03
1
305
Jawairia
77,005,457
1,117,103
PDFtron low level text extractore gly issue
<p>Base problem: The PDFTron lib font.MapToUnicode return wrong case character.</p> <p>Details: This is happens in particular book the snap are attached below, there are few character are getting in lower case but char.char_code is for upper case. as per my knowledge the font character and gly mapping having a problem....
<python><pdf><pdfnet>
2023-08-30 06:32:58
1
1,317
Damodhar
77,005,442
13,801,302
Pass a word2vec model from gensim package to langchain FAISS vectorstore
<p>I want to pass my trained gensim word2vec model as an embedding model to <code>FAISS.from_documents()</code>. Thereby I get an error</p> <blockquote> <p>AttributeError: 'Word2Vec' object has no attribute 'embed_documents'</p> </blockquote> <p>My code:</p> <pre class="lang-py prettyprint-override"><code> w2v_model = ...
<python><gensim><word2vec><langchain>
2023-08-30 06:30:54
1
621
Christian01
77,005,242
2,988,730
Combining use of `choices` and `action='extend'` in argparse
<p>I ran into a corner case with <code>choice</code> in <code>argparse</code>, when used in conjunction with <code>action='extend'</code>, introduced in python 3.8:</p> <pre><code>from argparse import ArgumentParser parser = ArgumentParser('test') parser.add_argument('-x', '--x', action='extend', choices=list('XYZ'), ...
<python><argparse>
2023-08-30 05:48:23
2
115,659
Mad Physicist
77,004,987
736,662
Setting a random value from a list in Python
<p>Basic question, but how do I pick random values from this list:</p> <pre><code>TS_IDs = { '69397': 30, '10259': 30, '87104': 30 } </code></pre> <p>Using this function:</p> <pre><code>def set_ts_id_random(): ts_id_random = &lt;here I want to pick a random value&gt; print(&quot;random_ts_id:&quot;, ts_id_random) retur...
<python><locust>
2023-08-30 04:27:40
1
1,003
Magnus Jensen
77,004,983
1,657,457
How to remove text from image (not inpainting but just solid color over the text)
<p>I have the following Python code that finds the text in a image, and uses cv2.inpaint to remove that text by covering with generated background, but I just want to put solid color over the text instead generating the background.</p> <pre><code>import matplotlib.pyplot as plt import keras_ocr import cv2 import math i...
<python><opencv><keras><ocr>
2023-08-30 04:26:44
0
968
dexter00x
77,004,957
4,212,875
What datatype is considered 'list-like' in Python?
<p>In the Pandas documentation <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html" rel="noreferrer">here</a> for <code>Series.isin(values)</code>, they state:</p> <blockquote> <p>values : set or list-like</p> </blockquote> <p>What is considered list-like? For a Python dictionary <code>temp_di...
<python><python-3.x><pandas><dictionary>
2023-08-30 04:17:01
2
411
Yandle
77,004,459
1,914,781
find duplicates and list values as columns
<p>I would like to find duplicates and list values as columns.</p> <p>Example,</p> <pre><code>import pandas as pd df = pd.DataFrame( [ ['A',1], ['B',2], ['C',3], ['D',4], ['E',5], ['C',6], ['D',7], ['E',8], ['F',9], ['G',10] ...
<python><pandas>
2023-08-30 01:23:57
5
9,011
lucky1928
77,004,443
5,374,289
Timers and user events (PyGame)
<p>My game is essentially flappy bird but with enemies, ammo (goatee's), and also flies instead of flaps (That part isn't necessary). I'm trying to figure out how to spawn the pipes in, the goatee's (ammo for the player to collect), and also the enemies. I've just learned about <code>pygame.time.set_timer()</code> toda...
<python><events><timer><pygame>
2023-08-30 01:20:17
1
333
Trevn Jones
77,004,157
2,981,639
Use of poetry dynamic version with non-package project for idempotent build
<p>I'm using poetry to manage a python project that's not a package (it's a machine learning model). I have a bash <code>build.sh</code> script that contains multiple stages (train, test, package, install).</p> <p>I added <code>poetry-dynamic-version</code> in order to add a version to the assets that are created when ...
<python><version><python-poetry>
2023-08-29 23:35:22
0
2,963
David Waterworth
77,004,048
1,484,601
how to use the H264 video encoder with ffmpeg / opencv2?
<p>I am on ubuntu 22.04.</p> <p>I installed ffmpeg with apt.</p> <p>I am creating a video from some image files using python/opencv2 (installed via pip)</p> <p>When I use:</p> <pre class="lang-py prettyprint-override"><code>cv2.VideoWriter_fourcc(*&quot;mp4v&quot;) </code></pre> <p>the video is successfully created, bu...
<python><opencv><ffmpeg><h.264><codec>
2023-08-29 22:57:51
1
4,521
Vince
77,003,982
3,973,175
How to plot color of line segments according to a 3rd value
<p>I've gotten the following python3 code that generates line segments</p> <pre><code>import numpy as np import pylab as pl from matplotlib import collections as mc from matplotlib.colors import to_rgba # https://matplotlib.org/2.0.2/api/colors_api.html#matplotlib.colors.to_rgba #https://stackoverflow.com/questions/213...
<python><matplotlib>
2023-08-29 22:38:22
1
6,227
con
77,003,904
8,028,576
How to add stacked x-axis labels to stacked bar chart
<p>Given the following code:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from itertools import groupby import pandas as pd percent_EVs = [0, 8, 21, 26, 37, 39, 41, 75, 95, 97] percent_DVs = [100, 92, 79, 74, 63, 61, 59, 25, 5, 3] num_buses = [1423, 1489, 1613, 1606, 1710, 1684, 1694, 2153, 2...
<python><matplotlib><x-axis>
2023-08-29 22:09:50
1
592
tcokyasar
77,003,897
6,440,589
How to automatically adjust the position of a layout image using plotly?
<p>I am trying to add a logo to a <strong>plotly</strong> figure that I then save as a <strong>html</strong> file.</p> <p>I adjusted the x and y coordinates to display the logo in the top left corner of my html page.</p> <p><a href="https://i.sstatic.net/V8DdK.png" rel="nofollow noreferrer"><img src="https://i.sstatic....
<python><html><plotly><graphical-logo>
2023-08-29 22:08:19
0
4,770
Sheldon
77,003,629
13,801,302
How to train gensim word2vec and check if the training was succesful?
<p>I want to train a word2vec model with gensim package. There are several approaches online how to train the model. In my case I have 500 finance reports as pdf-file with about 300 pages per file in german language.</p> <p>Currently, my codes looks like this:</p> <pre class="lang-py prettyprint-override"><code>w2v_mod...
<python><word2vec><word-embedding>
2023-08-29 21:02:22
1
621
Christian01
77,003,563
308,827
Isinstance returning incorrect answer
<p>I have the following variable:</p> <p><code>ar</code> with the value <code>datetime.date(2000, 3, 1)</code></p> <p>However when I try to check if it is datetime, like so <code>isinstance(ar, datetime)</code> it returns False.</p> <p>How is that possible? When I try <code>type(ar)</code>, I get <code>&lt;class 'datet...
<python><datetime>
2023-08-29 20:50:36
1
22,341
user308827
77,003,423
11,686,518
Class error, using __new__ , instead of __init__, trying to return value
<p><strong>Description</strong>:</p> <p>I am trying to return a value from a class when I call it.</p> <p>I want the result of an object's method call upon creating the object.</p> <p>I want to get the value of:</p> <pre class="lang-py prettyprint-override"><code>A().get_result() # by just calling&quot; A() </code></...
<python><python-3.x><class>
2023-08-29 20:21:40
2
1,633
Jesse Sealand
77,003,345
10,994,166
Pick n random records with same index from 2 different list column pyspark
<p>Hi I have dataframe like this:</p> <pre><code>cc doc_1 doc_2 4 [a, b,..] [1, 6,..] 9 [t, s,..] [4, 5,..] 4 [q, f,..] [6, 7,..] </code></pre> <p>I want to pick <code>n(1/2 of cc col)</code> random records from both the col <code>doc_1</code> <code>doc_2</code> with same index value. I can use <code>f...
<python><pyspark><random><apache-spark-sql>
2023-08-29 20:05:22
1
923
Chris_007
77,003,220
9,749,124
Add text and image to MultiColumnLayout in borb library
<p>I am new to this library. I want to create &quot;newspaper lookalike&quot; page with this library.</p> <p>I want to add headline, lead, text and image to the pdf file. Text is very long so i want to use MultiColumnLayout. I also want to set up the margins and spacing between the columns. Are there any explanations, ...
<python><borb>
2023-08-29 19:41:13
1
3,923
taga
77,003,180
14,555,505
Numpy assignment on *1D* chained indices like `arr[mask][range:]`
<p>As an <a href="https://stackoverflow.com/help/minimal-reproducible-example">MRE</a>, let's say I have an array of numbers <code>arr</code>. I then want to extract certain elements from <code>arr</code> (based on a boolean mask), and set only the first <code>n</code> of those extracted elements to zero.</p> <p>I'd ex...
<python><numpy><indexing><variable-assignment>
2023-08-29 19:34:48
0
1,163
beyarkay
77,002,897
223,960
How do I use flask_sqlalchemy and a GCP TLS protected DB connector?
<p>I'd like to use flask_sqlalchemy with GCP's db connector which does automatic TLS setup as described here: <a href="https://cloud.google.com/sql/docs/postgres/connect-connectors#python_1" rel="nofollow noreferrer">https://cloud.google.com/sql/docs/postgres/connect-connectors#python_1</a></p> <p>I tried their example...
<python><google-cloud-platform><sqlalchemy><flask-sqlalchemy>
2023-08-29 18:48:49
2
8,190
Brian C.
77,002,854
4,876,561
Formatting hierarchical matches - Pandas
<p>(Note, I have not set the requirements for this)</p> <p>I have two dataframes, here is a sample of <code>dataframe1</code>:</p> <pre><code>| Key | Description | Type | |------|-------------|-----------------------------| | 0 | No Dept | No Dept | | 1110 | RSF ...
<python><pandas><format><hierarchy>
2023-08-29 18:41:35
0
7,351
artemis
77,002,768
2,514,130
How to filter a Polars DataFrame with list type columns?
<p>My Polars DataFrame contains columns with list type values:</p> <pre><code>df = pl.DataFrame({ 'a': [['1', '3'], ['3'], ['1'], ['2']], 'b':[['8'],['6'],['6', '7'],['7']] }) </code></pre> <p>I want to filter this DataFrame based on the 'a' column containing the list ['1']. I tried using:</p> <pre><code>df...
<python><python-polars>
2023-08-29 18:25:37
2
5,573
jss367
77,002,763
8,173,981
why doesn't pygments discover my custom lexer after installation
<p>i've developed and tested a custom pygments lexer, as described <a href="https://pygments.org/docs/lexerdevelopment/" rel="nofollow noreferrer">here</a>... i then prepared a <code>pyproject.toml</code> file whose contents are as follows:</p> <pre><code>[build-system] requires = [&quot;setuptools&quot;] build-backen...
<python><plugins><setuptools><lexer><pygments>
2023-08-29 18:24:24
1
331
biosbob
77,002,719
3,156,300
Add SortFilterProxyModel to my QTreeView crashes
<p>When i insert the QSortFilterProxyModel to my QTreeview. It appears to crash and my buttons for adding, editing no longer appear to work reliably. Where did I go wrong here? My goal here is to add the Sort model so i can add a search bar which is simple to do.</p> <p><a href="https://i.sstatic.net/uprH2.png" rel="no...
<python><python-3.x><pyside2>
2023-08-29 18:18:47
1
6,178
JokerMartini
77,002,659
806,392
Efficient "bandmax" function in pyvips?
<p>I'm looking for a way to efficiently find the band that has the maximum value in a large multi-band image.</p> <p>For example if we had an image that looked like</p> <pre><code>band 1 band 2 band 3 [1 2 3] [3 4 5] [0 1 2] [3 2 1] [1 2 3] [1 0 1] [4 5 6] [6 7 5] [0 0 7] </code></pre> <p>I'd like to make som...
<python><vips><libvips>
2023-08-29 18:05:02
1
583
matth
77,002,544
17,082,611
Change Conv2DTranspose output from (None, 39, 39, 1) to (None, 40, 40, 1)
<p>I am implementing a Decoder (a type of Artificial Neural Network) using keras:</p> <pre><code>latent_dim = 25 latent_inputs = keras.Input(shape=(latent_dim,)) x = layers.Dense(units=100, activation=&quot;relu&quot;)(latent_inputs) x = layers.Dense(units=1024, activation=&quot;relu&quot;)(x) x = layers.Dense(units=4...
<python><tensorflow><keras><deep-learning>
2023-08-29 17:46:42
2
481
tail
77,002,525
12,468,387
Google chrome can't detect profiles
<p>I ran selenium python and the profiles in the browser disappeared: <a href="https://i.sstatic.net/c13kx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c13kx.png" alt="enter image description here" /></a></p> <p>However, the profiles are still located in the \AppData\Local\Google\Chrome\User Data fold...
<python><google-chrome><selenium-webdriver><browser>
2023-08-29 17:42:32
1
449
Denzel
77,002,345
20,200,927
Wierd GUI behaviour with pyinstaller
<p>I made a simple file organizer in Python with a GUI. When I run mu <code>app.py</code> with <code>conda</code> it works just as I intended it to, but when I run the executable that I made with <code>pyinstaller</code> it prints out the custom error message that I wrapped inside a try-catch block.</p> <p>Here is the ...
<python><pyinstaller>
2023-08-29 17:12:44
0
320
i_hate_F_sharp
77,002,343
22,407,544
com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None)
<p>I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I sometimes get a <code>com_error at /translator/translator_upload/ (-214722...
<python><django><pdf><ms-word><pywin32>
2023-08-29 17:12:09
0
359
tthheemmaannii
77,002,321
8,769,865
multiline string of values to a pandas dataframe
<p>I have a string of values from a file</p> <pre><code>my_list = [&quot;col1: va11 \n col2: val2 \n col3:va13&quot; , &quot;col1: k11 \n col2: k12 \n col3:k13&quot; ] </code></pre> <p>I wanted to convert these strings into a pandas dataFrame.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <t...
<python><pandas><string>
2023-08-29 17:08:21
1
763
IndPythCoder
77,002,315
1,084,875
Get 2D Gauss–Legendre quadrature points and weights using NumPy
<p>NumPy provides the <code>np.polynomial.legendre.leggauss()</code> function to compute the sample points and weights for Gauss-Legendre quadrature. I'm trying to use this function to get the 2D points and weights for a quadrilateral. I am able to use the function as shown here:</p> <pre class="lang-py prettyprint-ove...
<python><numpy><scipy>
2023-08-29 17:07:24
1
9,246
wigging
77,002,301
850,781
How to merge two `value_counts` results without data loss?
<p>I want to accumulate value counts, but the simple addition does not do the trick.</p> <p>Suppose I have many many <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.html" rel="nofollow noreferrer">Series</a>, e.g., :</p> <pre><code>a = pd.Series([1,2,2,None], dtype=object) b = pd.Series([3,2,2,None]...
<python><pandas><dataframe><series>
2023-08-29 17:04:20
1
60,468
sds
77,002,135
22,466,650
How to manually forward-fill values to make a boolean slice?
<p>That's a simple question to explain but the solution is not easy for me. I can't figure it out.</p> <p>I have a dataframe with two columns as input :</p> <pre><code>df = pd.DataFrame({'start': [True, False, False, False, False, True, False, False, False, False, False, False], 'stop': [False, False, False, Tr...
<python><pandas>
2023-08-29 16:41:22
2
1,085
VERBOSE
77,002,087
13,250,589
Get `scrapy` to produce a nested datastructure
<p>I am using <code>scrapy</code> to crawl <a href="https://savings.gov.pk/download-draws/" rel="nofollow noreferrer">this</a> website and scrape data</p> <p>I want the scraped data to have a nested structure. something like this</p> <pre class="lang-js prettyprint-override"><code>{ denomination1: { ...
<python><web-scraping><scrapy><web-crawler><generator>
2023-08-29 16:34:56
1
885
Hammad Ahmed
77,002,035
2,031,993
Can I use Python Numba on Google App Engine?
<p>Is it possible to use the Python package Numba in web-apps that are running on Google App Engine?</p> <p>Is it possible to use the caching feature of Numba, so the functions don't have to be JIT-compiled every time they are run on Google App Engine? Or is there another way of achieving the same effect, e.g. by someh...
<python><google-app-engine><numba>
2023-08-29 16:26:46
1
822
questiondude
77,001,962
7,254,576
Luxonis OAK-D S2 PoE: how do I use the SDK and flash a standalone application?
<p>I am unable to flash a standalone application if it is based on the SDK.</p> <p>It seems there might be a conflict between using the SDK <code>OakCamera()</code> and the API <code>dai.DeviceBootloader()</code> but I don't know why the conflict is there or how to resolve it. It does seem that each of these 2 calls re...
<python><sdk><luxonis>
2023-08-29 16:17:29
0
420
Craftonix - AA
77,001,956
14,385,814
Check duplicate data in database using Django
<p>I have a problem which I want to check if data is duplicate based on name and date_travel, let say I add an item name Lebron James and choose multiple date <code>flatpickr</code> like <code>24-08-2023, 25-08-2023</code> and the expected result should return a <code>JsonResponse</code> says Duplicate date travel sinc...
<python><html><django><flatpickr>
2023-08-29 16:16:55
2
464
BootCamp
77,001,954
5,924,264
What is "dynamic assignment of an attribute" in python?
<p>I've used Python sparingly, so maybe I'm just not privy to some verbiage. Someone at a talk today said that they want to avoid &quot;dynamic assignment of an attribute&quot; and didn't provide an example.</p> <p>I know what dynamically creating an attribute of a class means, but what does dynamic assignment mean? Th...
<python><terminology>
2023-08-29 16:16:38
1
2,502
roulette01
77,001,932
10,200,497
How to trigger a command when an inline button is pressed?
<p>I want to initiate a command when an inline button is pressed. This is the code:</p> <pre><code>from telegram import ( ReplyKeyboardMarkup, ReplyKeyboardRemove, Update, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton ) from telegram.ext import ( Application, CommandHandler, ContextTyp...
<python><telegram-bot><python-telegram-bot>
2023-08-29 16:14:52
1
2,679
AmirX
77,001,834
5,437,090
Pandas Dataframe with dictionary cells | accumulate by values | inefficient apply method
<p><strong>Given</strong>:</p> <p>Sample Pandas Dataframe with dictionaries in each cell:</p> <pre><code>user_token_df = pd.DataFrame( { &quot;usr&quot;: [&quot;u1&quot;, &quot;u2&quot;, &quot;u3&quot;, &quot;u4&quot;, &quot;u7&quot;, &quot;u9&quot;, &quot;u5&quot;, &quot;u8&quot;], &quot;colA&quot;: ...
<python><pandas><performance><coding-efficiency>
2023-08-29 16:01:21
1
1,621
farid
77,001,723
1,141,818
Abstract class parameter in intermediary class
<p>I'm trying to define an abstract class with a mandatory argument. It works fine, but if I add an intermediary class, it may raise an exception at some point. Here is a dummy code to replicate the issue:</p> <pre><code>from abc import ABC, abstractmethod from typing import Dict class AbcClass(ABC): @classmetho...
<python><abstract-class>
2023-08-29 15:47:37
0
3,575
GuillaumeA
77,001,599
16,611,809
What's the proper way to add Python modules via PyInstaller
<p>I am using <code>PyInstaller</code> to make my Python script an macOS .app file. It all works, but after building, I need to make some manual <code>codesign</code> steps that I want to get rid of. Currently, I add some of my Python modules via <code>--add-data</code> and this seems to be the reason, why they are not...
<python><pyinstaller>
2023-08-29 15:31:45
0
627
gernophil
77,001,530
3,656,916
Extract field in rows in array to columns
<p>I am struggling with extracting values from array of rows into columns on the highest level. Short version of the spark dataframe is as follows</p> <pre><code>root |-- data: struct (nullable = true) | |-- date: string (nullable = true) | |-- id: string (nullable = true) | |-- specifications: array (null...
<python><pyspark>
2023-08-29 15:22:31
1
507
DDR
77,001,525
7,648
Problem in migrating from PyTorch to fastai
<p>I am trying to migrate my code from PyTorch to fastai. I have the following migrated code:</p> <pre><code> train_loader = self.init_train_dl(self.df, self.train_subjects) test_loader = self.init_val_dl(self.df, self.val_subjects) data = DataLoaders(train_loader, test_loader) learn = Learner(data, Al...
<python><pytorch><fast-ai>
2023-08-29 15:21:40
1
7,944
Paul Reiners
77,001,472
12,730,406
how to backwards fill in pandas with group and split dataframes by group?
<p>I have this dataframe:</p> <pre><code>df = pd.DataFrame(data = {'genre': ['sci-fi','sci-fi','sci-fi','sci-fi','sci-fi', 'comedy', 'comedy', 'comedy', 'comedy', 'comedy', 'comedy', 'comedy'], 'score': [5,5,4,3,2,9,10,8,4,7,5,6], ...
<python><pandas>
2023-08-29 15:13:58
4
1,121
Beans On Toast
77,001,425
2,164,384
Can not get correction response from Flask server when sending data by a proxy
<p>I created a simple Flask application on my tiny VPS, and started by Gunicorn with a simple command <code>gunicorn -w 2 -b 0.0.0.0:8888 app:app --access-logfile=- --proxy-protocol</code>.</p> <p>I tried the code below on my local PC with Python requests</p> <pre><code>import requests url= 'http://124.202.218.128:5000...
<python><flask><proxy><gunicorn>
2023-08-29 15:08:13
0
783
l0o0
77,001,309
11,329,736
Snakemake: wildcard restriction
<p>I have the following <code>Snakemake</code> rules (I have only shown the relevant parts):</p> <pre><code>SAMPLE_IP = ['control_1_hif1a_hyp', 'control_2_hif1a_hyp'] SAMPLE_INPUT = ['control_1_input_hyp', 'control_2_input_hyp'] rule all: input: expand(&quot;bigwig/compare/{sample_ip}_vs_{sample_input}.bw&...
<python><python-3.x><wildcard><snakemake><expansion>
2023-08-29 14:55:16
1
1,095
justinian482
77,001,239
4,118,462
pytest: How to use temporary folders in a class-scoped fixture?
<p>Is there a way to share a temporary folder just across the tests in class?</p> <p>This <a href="https://docs.pytest.org/en/7.1.x/how-to/tmp_path.html" rel="nofollow noreferrer">pytest doc</a> mentions the function-scoped tmp_path and session-scoped tmp_path_factory fixtures. Didn't say anything about class scope.<b...
<python><python-3.x><pytest><fixtures>
2023-08-29 14:46:34
2
395
MCornejo
77,001,206
11,426,624
How to add a background color from a dataframe to segments of a line plot
<p>I have a dataframe as below and would like to get a plot with a line and background colour either red or white (depending on the value of color_var).</p> <pre><code> line_var color_var datetime 2023-04-20 13:45 3 1 2023-04-20 14:00 4 0 2023-04-20 15:00 5 0 2023-04-20 15:1...
<python><pandas><matplotlib>
2023-08-29 14:42:36
1
734
corianne1234
77,001,193
2,836,172
Recursive loop unpacking too many values in Jinja2
<p>I try to display a dict, which depth is unknown and represents a file tree, with a recursive loop. This is my simple example data:</p> <pre><code>{ &quot;smartphone&quot;:{ &quot;upload_1693308862&quot;:{ &quot;image1.png&quot;:{ &quot;url&quot;:&quot;&lt;url comes here&gt;&quot; ...
<python><jinja2>
2023-08-29 14:40:38
0
1,522
Standard
77,001,129
127,508
How to configure FastAPI logging so that it works both with Uvicorn locally and in production?
<p>I have the following FastAPI application:</p> <pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI import logging import uvicorn app = FastAPI(title=&quot;api&quot;) LOG = logging.getLogger(__name__) LOG.info(&quot;API is starting up&quot;) LOG.info(uvicorn.Config.asgi_version) @app.get(&qu...
<python><logging><fastapi><uvicorn>
2023-08-29 14:32:37
3
8,822
Istvan
77,001,053
2,876,079
How to update pip and keep the new version of pip portable (=use relative path to python.exe)?
<p>I use WinPython as portable app on Windows and get following hint:</p> <pre><code>A new release of pip is available: 23.1.2 -&gt; 23.2.1 [notice] To update, run: python.exe -m pip install --upgrade pip </code></pre> <p>If I run the command as suggested, the new version of pip stores the absolute path to python.exe.<...
<python><pip><portable-applications>
2023-08-29 14:21:32
2
12,756
Stefan
77,000,845
7,486,038
XGBOOST Model predicting, with nan Input values
<p>I am facing a weird behavior in the xgboost classifier. Reproducing the code from a response to <a href="https://stackoverflow.com/questions/61082381/xgboost-produce-prediction-result-and-probability">this</a> post</p> <pre><code>import xgboost as xgb import numpy as np from sklearn.datasets import make_moons from s...
<python><classification><xgboost>
2023-08-29 13:53:53
2
326
Arindam
77,000,806
11,317,776
Clearing cache of aiocache from unit test
<p>In FastAPI I have an endpoint:</p> <pre><code>from aiocache import Cache, cached @router.get(&quot;/id/{user_id}/permissions&quot;) @cached(ttl=30, cache=Cache.MEMORY) async def get_permissions(user_id: UUID4) -&gt; list[Permissions]: </code></pre> <p>And then in my unit test, I want to clear the cache.</p> <p>I ha...
<python><asynchronous><caching><fastapi><aio>
2023-08-29 13:48:27
2
3,048
DUDANF
77,000,608
16,883,182
How to prevent race conditions between the UI thread and a different one who both access the same list without blocking the UI thread?
<p>I'm currently working on a GUI toolkit from the ground up in Pygame just for the learning experience, and I'm running into a problem while working on the directory-tree widget. Let me explain the multi-threading system I'm using.</p> <p>All node objects are stored in a flat list. When a node is expanded, the UI thre...
<python><multithreading><user-interface><concurrency><race-condition>
2023-08-29 13:20:19
1
315
I Like Python
77,000,525
9,190,503
Apify Scrapy template returns Attribute error
<p>I install the Scrapy template from Apify CLI and run it as <a href="https://blog.apify.com/web-scraping-with-scrapy/#creating-a-new-actor" rel="nofollow noreferrer">intructed</a>. I don't do any changes.</p> <p>When I deploy it to Apify, the same problem occurs. Even when I used the same template from Apify console ...
<python><web-scraping><apify>
2023-08-29 13:09:24
1
1,041
Ulvi
77,000,439
20,762,114
Cumulative Max Sum in Polars
<p>In the following dataframe, I want to populate the column <code>cum_max_sum</code> using the columns <code>minimum</code> and <code>to_add</code>. How can I achieve this using Polars operations?</p> <pre><code>┌──────────────────┬─────────┬────────┬─────────────┐ │ prev_cum_max_sum ┆ minimum ┆ to_add ┆ cum_max_sum │...
<python><dataframe><python-polars>
2023-08-29 12:58:12
2
317
T.H Rice
77,000,400
11,399,142
List and download files in a folder in a blob with blob level SAS token
<p>I got a SAS token which was created for a specific folder on my Azure Datalake Gen2. The goal is, to download the folder with all its contents.</p> <p>I understand, that I can create a DataLakeServiceClient, a FileSystemClient, or a DataLakeDirectoryClient as follows:</p> <pre><code># configuration url = 'https://my...
<python><azure><azure-data-lake-gen2>
2023-08-29 12:52:58
3
1,148
elyptikus