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
78,489,770
188,331
Difference of special token handling of the BertTokenizer's batch_decode() and decode() method?
<p>For <code>BertTokenizer</code>, I am trying to decode sentences produced after tokenization. Here is my code:</p> <pre><code>from transformers import BertTokenizer ref = '這件衣服皺巴巴的,幫我燙一下吧。' our = '衣服皺了,幫我燙一燙' tokenizer = BertTokenizer.from_pretrained('fnlp/bart-base-chinese') tokenized_our = tokenizer(our, text_ta...
<python><huggingface-transformers><tokenize><cjk><huggingface-tokenizers>
2024-05-16 12:09:57
0
54,395
Raptor
78,489,644
903,651
How to parse case-insensitive with lrparsing?
<p>This following example attempt to parse a simplified <code>Delphi</code> language where keywords and variables are case-insensitive.</p> <pre><code>import sys import lrparsing from lrparsing import Keyword, List, Prio, Ref, Token, Tokens, Grammar, TokenRegistry, Some, Choice, Opt, Left, Right, THIS class DelphiPasP...
<python><lrparsing>
2024-05-16 11:49:53
0
14,979
Adrian Maire
78,489,368
13,285,583
How to calculate the w and b of linear regression with python using the loss function?
<p>My goal is to create a <code>ipynb</code> file to learn about how to create a Linear Regression Model.</p> <p>The problem:</p> <ol> <li>How to set the initial w and b, should I set it randomly?</li> <li>When to change the w or b on each iteration.</li> <li>By how many should I update the w or b on each iteration.</l...
<python><numpy>
2024-05-16 10:58:10
0
2,173
Jason Rich Darmawan
78,489,233
17,487,457
Function to Oversample - Undersample instances in dataset
<p>I want to create a function, that takes data instances, labels, and a target-proportion. The function should determine the proportion of classes in the given dataset/labels, and resample the data into the given target proportion using either <code>imblearn.over_sampling.SMOTE</code> for classes that require over-sam...
<python><valueerror><resampling><smote>
2024-05-16 10:30:32
0
305
Amina Umar
78,489,093
3,918,996
Python Invoke and root for imports when loading modules
<p>We use a Python module named <a href="https://github.com/pyinvoke/invoke" rel="nofollow noreferrer">invoke</a> to execute a large set of Python scripts in a nice neat way: <a href="https://github.com/pyinvoke/invoke" rel="nofollow noreferrer">invoke</a> loads Python scripts from a <code>tasks</code> sub-directory an...
<python><pyinvoke>
2024-05-16 10:05:48
0
947
Rob
78,488,981
3,662,734
Set a part of weight tensor to requires_grad = True and keep rest of values to requires_grad = False
<p>I am doing some kind of transfer learning, where I load a dense model and then expand the weight tensor and train only the new values after expanding it and keep the old trained values frozen. in this case I need to set the new weights to <code>requires_grad = True</code> and old weights to <code>requires_grad = Fal...
<python><deep-learning><pytorch>
2024-05-16 09:46:29
1
579
Emily
78,488,965
10,200,497
How can I get the first row that meets conditions of a mask if another condition is not present before it?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'close': [109, 109, 105, 110, 105, 120, 120, 11, 90, 100], 'high': [110, 110, 108, 108, 115, 122, 123, 1120, 1000, 300], 'target': [107, 107, 107, 107, 107, 124, 124, 500, 500, 500] } ) </code></pre> <p>Mas...
<python><pandas><dataframe>
2024-05-16 09:43:39
1
2,679
AmirX
78,488,678
2,496,293
Cannot reproduce numpy.typing.NBitBase example with `numpy.typing.mypy_plugin`
<p>I am having trouble getting the <code>numpy.typing.mypy_plugin</code> to work. Following the <a href="https://numpy.org/devdocs/reference/typing.html#numpy.typing.NBitBase" rel="nofollow noreferrer">example</a> of how to use <code>NBitBase</code>, I get different output from mypy.</p> <h1>Problem</h1> <h3>expected b...
<python><numpy><mypy>
2024-05-16 08:56:07
0
2,441
Sam De Meyer
78,488,599
18,618,577
unexpected reversed secondary y axis on dataframe plot
<p>I'm trying to plot a electrical consumption, first in mA with a date, and with secondary axis in W with julian day. I refered to <a href="https://matplotlib.org/stable/gallery/subplots_axes_and_figures/secondary_axis.html" rel="nofollow noreferrer">this matplotlib article</a>, and even if the example works perfectly...
<python><pandas><matplotlib><axis>
2024-05-16 08:41:54
1
305
BenjiBoy
78,488,561
3,453,776
Configuring Sentry GRPC Integration: grpcio is not installed
<p>I'm trying to configure the Sentry GRPCIntegration in a new project, just as it's <a href="https://docs.sentry.io/platforms/python/integrations/grpc/" rel="nofollow noreferrer">described in the docs</a>. When running the application, I get this error:</p> <pre><code> from sentry_sdk.integrations.grpc import GRPCI...
<python><grpc><sentry>
2024-05-16 08:36:49
1
571
nnov
78,488,320
8,884,239
Convert each key value pair to columns of dataframe in pyspark
<p>I have following array of map and I want to convert it into array of structs to convert all key value pairs to columns of a dataframe</p> <pre><code>-- DurationPeriod: array (nullable = true) | |-- element: map (containsNull = true) | | |-- key: string | | |-- value: string (valueContainsNull = tru...
<python><apache-spark><pyspark><apache-spark-sql><pyspark-schema>
2024-05-16 07:50:32
1
301
Bab
78,488,102
19,506,623
How to get classnames with a site in categories/subcategories?
<p>I'm trying to get only the classnames of each level of <a href="https://locations.bojangles.com/" rel="nofollow noreferrer">this site</a>. What I mean with levels? Well, the structure of the site it has 3 or 4 levels or it shows the information in categories and subcategories and is needed to drilldown to go deeper....
<python><web-scraping><selenium-chromedriver>
2024-05-16 07:06:00
0
737
Rasec Malkic
78,487,990
7,712,908
Finding pid for python script B execution on a terminal using popen from python script A
<p>I have a python script &quot;A&quot; that uses <code>subprocess.Popen</code> to launch a <code>gnome-terminal</code> and then executes a different python script &quot;B&quot; in there. I am stuck with retrieving the pid for that newly spawned <code>gnome-terminal</code> so that I can terminate it later on when I see...
<python><linux><subprocess><popen><pid>
2024-05-16 06:40:38
0
405
blackbeard
78,487,838
5,409,315
How to use multiprocessing locks in joblib?
<p>I want to use a lock in joblib using backend multiprocessing or loky. It seems to be simple enough with using standard lib's multiprocessing, but with joblib it's not: It complains that the lock is not picklable:</p> <pre><code>#!Python from multiprocessing import Process, Lock from joblib import Parallel, delayed ...
<python><multiprocessing><locking><joblib>
2024-05-16 06:06:23
1
604
Jann Poppinga
78,487,476
22,963,183
How does Langchain AgentExecutor serving model LLM?
<p>I followed <a href="https://github.com/zenml-io/zenml-projects/tree/main/llm-agents" rel="nofollow noreferrer">this tutorial</a></p> <p>I conducted some changes:</p> <ul> <li><p>I built model gemma:2b from Ollama</p> <ul> <li><a href="https://hub.docker.com/r/ollama/ollama" rel="nofollow noreferrer">built Ollama by ...
<python><langchain><large-language-model><langchain-agents>
2024-05-16 03:37:34
0
515
happy
78,487,385
3,727,079
Is there a way to get the average from the standard deviation in Numpy? (Or a way to feed np.std the average)
<p>I've got an application where I need both the average and the standard deviation of a list of data.</p> <p>Numpy can calculate both with <code>np.avg</code> and <code>np.std</code>. However, <code>np.std</code> does not give the average, even though you need the average to <a href="https://en.wikipedia.org/wiki/Stan...
<python><numpy>
2024-05-16 02:59:54
0
399
Allure
78,487,312
13,737,893
Hide input components streamlit
<pre><code>import os from PIL import Image import streamlit as st from openai import OpenAI from utils import ( delete_files, delete_thread, EventHandler, moderation_endpoint, is_nsfw, render_custom_css, render_download_files, retrieve_messages_from_thread, retrieve_assistant_created...
<python><streamlit>
2024-05-16 02:27:16
1
334
Maximiliano Vazquez
78,487,264
251,589
Pretty print why two objects are not equal
<p>When using <code>pytest</code>, I get nice pretty printing when two objects are not equivalent:</p> <pre><code>Expected :Foo(id='red', other_thing='green') Actual :Foo(id='red', other_thing='blue') &lt;Click to see difference&gt; def test_baz(): oneFoo = Foo(id=&quot;red&quot;, other_thing=&quot;blue...
<python><testing><pydantic>
2024-05-16 02:11:48
2
27,385
sixtyfootersdude
78,486,997
678,572
How to reproduce `kneighbors_graph(include_self=True)` using `KNeighborsTransformer` in sklearn?
<p>My ultimate goal is replace some methods that use <code>kneighbors_graph</code> with transformers from the <a href="https://sklearn-ann.readthedocs.io/en/latest/" rel="nofollow noreferrer">sklearn-ann package</a>. All the methods in <code>sklearn-ann</code> are implemented as sklearn-compatible transformer objects....
<python><arrays><numpy><matrix><nearest-neighbor>
2024-05-16 00:01:02
2
30,977
O.rka
78,486,966
15,587,184
LangChaing Text Splitter & Docs Saving Issue
<p>I'm trying to use the langchain text splitters library fun to &quot;chunk&quot; or divide A massive str file that has Sci-Fi Books I want to split it into n_chunks with a n_lenght of overlaping</p> <p>This is my code:</p> <pre><code>from langchain_text_splitters import CharacterTextSplitter text_splitter = Characte...
<python><split><langchain><py-langchain>
2024-05-15 23:43:21
2
809
R_Student
78,486,957
10,906,068
how to properly loop and print json record in a single line
<p>The code below loops through the records and displays the result vertical one after another.</p> <p><strong>Here is what i want</strong></p> <p>I need to print this text in a single line Eg. <strong>Stackoverflow.com is a Programmers Question and Answering Site</strong></p> <pre><code>import os import json my_json ...
<python><json>
2024-05-15 23:40:26
1
2,498
Nancy Moore
78,486,683
6,300,467
PyQt6 designer won't install. Error: /usr/lib/x86_64-linux-gnu/libQt6Core.so.6: version `Qt_6.4' not found
<p>I have attempted to install <code>PyQt6</code> and its pyqt6 designer and I can't resolve the following error message when using the following command,</p> <pre><code>pyqt6-tools designer </code></pre> <p>It results in this error message,</p> <pre><code>~/projects/.venv/lib/python3.10/site-packages/qt6_applications/...
<python><linux><pyqt6>
2024-05-15 21:50:47
0
785
AlphaBetaGamma96
78,486,645
976,299
Django Tests Throw ORA-00942: table or view does not exist
<p>I haven't found any questions with respect to Django tests and Oracle DB. I am trying to run a test on an existing application, but am running into the table or view doesn't exist error.</p> <p>I am confused as the test says it is deleting and creating those tables/views.</p> <pre><code>Creating test database for al...
<python><django><oracle-database><python-2.7>
2024-05-15 21:39:49
1
572
Casey
78,486,622
12,415,855
How to read the font color of an excel-cell?
<p>i have the folowing excel-sheet and try to read the font-color of the cell B3:</p> <p><a href="https://i.sstatic.net/26Kf3DFM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/26Kf3DFM.png" alt="enter image description here" /></a></p> <p>using the following code:</p> <pre><code>import openpyxl as ox wb...
<python><openpyxl><xlrd><xlwings>
2024-05-15 21:32:17
0
1,515
Rapid1898
78,486,471
678,572
How to add a .transform Nystroem method to project new observations into an existing space? (Diffusion Maps in Python)
<p>I am copying over some code from <a href="https://github.com/satra/mapalign/blob/3e8c7af51355896666e24d49544b1afa47e78364/mapalign/embed.py#L204" rel="nofollow noreferrer">mapalign</a> for <a href="https://github.com/scikit-learn/scikit-learn/issues/5818" rel="nofollow noreferrer">calculating diffusion maps using th...
<python><numpy><scikit-learn><transform><dimensionality-reduction>
2024-05-15 20:54:37
0
30,977
O.rka
78,486,451
16,547,860
Connecting to MSSQL Server database using pyspark
<p>I am new to pyspark and trying to connect to mssql server database. Here are the details: This gets printed when I run the script I have.</p> <pre><code>('Processing table:', u'POL_ACTION_AMEND') ('Table schema:', u'dbo') ('Source_database:', u'PRD01_IPS') ('SQL Query:', '(SELECT TOP 100 * FROM PRD01_IPS.dbo.POL_EVE...
<python><apache-spark><pyspark><jdbc><mssql-jdbc>
2024-05-15 20:50:17
2
312
Shiva
78,486,446
11,751,799
Border around plotly figure
<p>I have some <code>plotly</code> plots that I like and just need one final piece before I can present them: a border around the entire figure. I have gotten this to work in <code>matplotlib.pyplot</code> via <code>fig.patch.set_linewidth</code> and <code>fig.patch.set_edgecolor</code>, but I have not been successful ...
<python><jupyter-notebook><graphics><plotly>
2024-05-15 20:48:25
1
500
Dave
78,486,428
2,072,241
Is it possible in Python to type a function that uses the first elements of an arbitrary sized arguments list
<p>I have a Python function that retrieves the first element of an arbitrary number of *args:</p> <pre class="lang-py prettyprint-override"><code>def get_first(*args): return tuple(a[0] for a in args) </code></pre> <p>Lets say that I call this function as follows:</p> <pre class="lang-py prettyprint-override"><code...
<python><mypy><python-typing>
2024-05-15 20:44:54
1
351
Huub Hoofs
78,486,265
3,649,441
How to access DateTime index when running apply() on a pandas DataFrame?
<p>I have two pandas DataFrames, daily_data contains daily close price data for a stock and weekly_data contains weekly close price data.</p> <p>daily_data:</p> <pre><code> close Date 2022-05-02 00:00:00-04:00 30.389999 2022-05-03 00:00:00-04:00 29.469999 2022-05-04 00:00:00-04:00 28.10...
<python><pandas>
2024-05-15 20:04:20
1
1,009
Chris
78,486,218
16,674,436
Networx and ipysigma, how to remove isolated nodes of degree <= 2 on graph?
<p>Context: I’m processing Reddit data. There is too much data to handle, therefore I created a random sample of the data. That leads in my network to have a lot of <em>isolated</em> nodes (emphasized, because isolated nodes are usually of degree 0, but here I am referring to degree &lt;=2). An image is better than any...
<python><networkx><network-analysis>
2024-05-15 19:54:58
1
341
Louis
78,486,167
2,487,835
Set import path for python with jupyter notebooks / vscode
<p>I connect to my own jupyter server via vpn/ssh with vscode. Jupyter server runs as a daemon.</p> <p>Having asked gpt, read articles here and tried many config versions, I still end up doing this at the beginning of each notebook:</p> <pre><code>BASE_PATH = '/home/bartsimpson/dev/' import sys sys.path.append(BASE_P...
<python><visual-studio-code><jupyter-notebook><jupyter-server>
2024-05-15 19:42:07
1
3,020
Lex Podgorny
78,486,065
13,395,230
What does <type>.<attr> do during a match/case?
<p>In general, the code <code>&lt;type&gt;(arg1=value1)</code> is changed to the code <code>&lt;type&gt;(attr1=value1)</code> during a <code>case</code> in a <a href="https://docs.python.org/3/reference/compound_stmts.html#match" rel="nofollow noreferrer"><code>match</code> statement</a>. This allows for some very inte...
<python><structural-pattern-matching>
2024-05-15 19:15:12
1
3,328
Bobby Ocean
78,486,064
1,028,270
How do I get the model type inside a PydanticBaseSettingsSource?
<p>I'm writing a custom PydanticBaseSettingsSource and processing fields of a specific type <code>MyModel</code></p> <pre><code>class CustomSettingsSource(PydanticBaseSettingsSource): # Must implement def get_field_value( self, field: FieldInfo, field_name: str ) -&gt; Tuple[Any, str, bool]: ...
<python><pydantic><pydantic-v2>
2024-05-15 19:15:04
1
32,280
red888
78,485,759
34,372
Intellij wizard to create new Project from an existing Poetry project is incorrect
<p>When I create a new Python project using poetry and then try to open it in Intellij the wizard is wildly wrong. Here are the steps and the problems with the wizard. In the bash shell:</p> <pre><code>$ poetry new 2_0 $ cd 2_0 $ poetry env use /usr/bin/python3.12 Creating virtualenv 2-0-8FFCH961-py3.12 in /home/dean...
<python><intellij-idea><pycharm><python-poetry>
2024-05-15 18:05:37
1
10,409
Dean Schulze
78,485,621
8,378,817
Passing multiple arguments during langchain chain.invoke()
<p>I am experimenting with a langchain chain by passing multiple arguments. Here is a scenario:</p> <pre><code>TEMPLATE = &quot;&quot;&quot;Task: Generate Cypher statement to query a graph database. Instructions: Use only the provided relationship types and properties in the schema. Do not use any other relationship ty...
<python><langchain><retrievalqa>
2024-05-15 17:37:39
1
365
stackword_0
78,485,530
2,056,201
Does python not automatically convert integer types when doing math?
<p>I had an issue with a collision function returning very large values for distances</p> <p>I would think python would not overflow a 16 bit integer when doing this math, since it's dynamically typed, but apparently it does.</p> <p>If I were to do these operations directly on an array, I understand why it would overfl...
<python><arrays><numpy>
2024-05-15 17:16:54
1
3,706
Mich
78,485,348
363,796
odd behavior changing dir from .xonshrc
<p>I am using the xonsh shell and my .xonshrc file contains a call to <code>os.chdir()</code>, which works, but oddly. When I start xonsh, my prompt, which shows my current path, seems to indicate I am still in my home dir until after I execute a command or even simply press enter. e.g.</p> <pre><code>[etlsmart@msd-c...
<python><xonsh>
2024-05-15 16:40:17
1
1,653
zenzic
78,485,327
2,079,306
Python Flask Ubuntu Apache2 website, serving images outside of DocumentRoot using apache2's alias_mod. Am I missing something?
<p>Context:</p> <p>I created a webtool using Python Flask to retrieve filenames from a database with a backend sql post method to my database code. This works fine. Filenames are always returned appropriately and presented to the client with file sizes. The client then selects which files they wish to download and hits...
<python><apache><flask>
2024-05-15 16:35:50
0
1,123
john stamos
78,485,326
2,893,712
Pandas Extract Phone Number if it is in Correct Format
<p>I have a column that has phone numbers. They are usually formatted in <code>(555) 123-4567</code> but sometimes they are in a different format or they are not proper numbers. I am trying to convert this field to have just the numbers, removing any non-numeric characters (if there are 10 numbers).</p> <p>How can I ap...
<python><pandas><regex><dataframe><text-extraction>
2024-05-15 16:35:27
4
8,806
Bijan
78,485,311
16,674,436
Networkx remove_from_nodes <= 2 gives unexpected behavior: removing randomly?
<p>I’m trying to graph a network based on some interactions. I want to remove nodes that have a degree smaller than or equal to 2. So here is my code.</p> <pre class="lang-py prettyprint-override"><code>G = nx.Graph() G.add_nodes_from(['player1', 'player2', 'player3', 'player4', 'player5', 'player6', 'player7' ]) G.add...
<python><nodes><networkx><network-analysis>
2024-05-15 16:32:22
0
341
Louis
78,485,236
6,382,969
TensorFlow Keras compilation successful; still model summary is undefined
<p>I am using the following code to define and compile a Keras model. Then when I print the model.summary() I am still getting unbuilt and erroneous summary. I am using Python3.10.12 and tensorflow 2.16.1. Please do not hesitate to reach out for any additional information you need.</p> <p><strong>Code to build the mode...
<python><tensorflow><keras>
2024-05-15 16:13:59
1
1,246
PHcoDer
78,485,109
2,153,235
Is a pandas MultiIndex a counterpart to a SQL composite index?
<p>I posted this on <a href="https://www.reddit.com/r/dfpandas/comments/1cratw2" rel="nofollow noreferrer">reddit</a> some days ago, but haven't received any response.</p> <p>Everything I've read online about the pandas MultiIndex makes it seem like a counterpart to a SQL composite index. Is this the correct understan...
<python><pandas><multi-index>
2024-05-15 15:48:55
1
1,265
user2153235
78,485,053
8,543,025
Aligning Sparse Boolean Arrays
<p>I have two (very) long and sparse boolean arrays <code>n1</code> and <code>n2</code>, representing spikes of two neurons that are responding to the same stimulus. Because they are responding to the same stimulus, they have many &quot;overlapping&quot; spikes (up to some <code>t</code> time-difference); but also beca...
<python><arrays><python-3.x><boolean>
2024-05-15 15:39:11
0
593
Jon Nir
78,485,031
1,505,832
Argparse - Check if positional argument is entered
<p>with argparse, is it possible to check whether the first positional argument has been entered:</p> <pre><code>import argparse if __name__ == &quot;__main__&quot;: parser = argparse.ArgumentParser() parser.add_argument(&quot;object_type&quot;, type=str) parser.add_argument(&quot;--pass1&quot;, type=str)...
<python><argparse>
2024-05-15 15:36:46
0
693
laloune
78,485,024
17,487,457
AttributeError: can't set attribute: How do I fix this this class to work well?
<p>Given the following SMOTEBoost class implementeation in <code>smoteboost.py</code> file:</p> <pre class="lang-py prettyprint-override"><code>import numbers import numpy as np from collections import Counter from sklearn.base import (clone, is_regressor) from sklearn.ensemble import AdaBoost...
<python><numpy><scikit-learn>
2024-05-15 15:35:00
1
305
Amina Umar
78,484,978
166,229
Make (a quite simple) pyparsing based parser fault tolerant
<p>I wrote a little parser using <code>pyparsing</code> to parse Google-like search strings, like <code>foo AND (bar OR baz)</code> (full code below). Like Google, I would like to make the parser fully fault-tolerant. It should ignore errors and parse as much as it can.</p> <p>I wonder if I should adapt my grammar some...
<python><parsing><pyparsing>
2024-05-15 15:26:20
1
16,667
medihack
78,484,934
10,240,072
Dataframe - Rolling product - timedelta window
<p>I am trying to do a simple rolling multiplication of a dataframe (each new value should be the product of all the input values in the window). Realizing that rolling does not allow of products, I tried to look for alternate solutions but they seem not to work with variable lenghth windows :</p> <pre><code>start_date...
<python><pandas><rolling-computation>
2024-05-15 15:20:13
1
313
Fred Dujardin
78,484,891
7,456,317
pydantic: default values for None fields
<p><em><strong>Update:</strong></em> Inspired by @chepner's answer, I change the validator as follows:</p> <pre><code> @field_validator(&quot;age&quot;, mode=&quot;before&quot;) @classmethod def lower_age(cls, value: int) -&gt; Union[int, None]: if value is None or pd.isna(value): return ...
<python><pydantic>
2024-05-15 15:12:05
1
913
Gino
78,484,847
8,543,025
Best way to match between arrays of different length
<p>I have two sorted numerical arrays of unequal length and I'm looking for a way to match between elements in both arrays such that there's a one-to-one match between (most) <code>gt</code> and <code>pred</code> elements. A match is only considered valid if it is below some threshold <code>thrsh</code> (so there could...
<python><arrays><numpy>
2024-05-15 15:05:25
1
593
Jon Nir
78,484,828
1,028,270
Does BaseSettings support adding arbitrary input params without having to override the constructor?
<p>In my Config class:</p> <pre><code>class MyConfig(BaseSettings): err_if_not_found: bool = False model_config = SettingsConfigDict( env_file=MyConfigs(err_if_not_found).configs, env_prefix=&quot;MY_APP&quot;, ) </code></pre> <p>I have my own class for loading configs and it supports option...
<python><pydantic>
2024-05-15 15:01:05
1
32,280
red888
78,484,794
6,714,667
How can i remove fractions from the first string in this list of lists?
<p>e.g i have the following:</p> <pre><code>test = [['6 / 24 hello','4 / 5 askdskjf'],['2 / 3 dentist']] </code></pre> <p>i'd like to remove 6 / 24 and 2 /3 so the first string which contains a fraction. to get:</p> <pre><code>[[' hello', '4 / 5 askdskjf'], [' dentist']] </code></pre> <p>i've tried this: <code>[x for x...
<python><regex>
2024-05-15 14:54:53
1
999
Maths12
78,484,792
15,394,019
Python (Polars): Vectorized operation of determining current solution with the use of previous variables
<p>Let's say we have 3 variables <strong>a</strong>, <strong>b</strong> &amp; <strong>c</strong>.</p> <p>There are <strong>n</strong> instances of each, and <strong>all but the first instance of c are null</strong>.</p> <p>We are to calculate each <em>next</em> <strong>c</strong> based on a given formula <strong>compri...
<python><dataframe><vectorization><python-polars><rolling-computation>
2024-05-15 14:54:39
2
934
mindoverflow
78,484,732
8,995,379
Multiple substrings in string python within variable check
<p>I have the following code:</p> <pre><code>check = &quot;red&quot; in string_to_explore </code></pre> <p>How can I replicate it for multiple substrings?</p> <p>I tried with:</p> <pre><code>check = &quot;red|blue&quot; in string_to_explore </code></pre> <p>but doesn't seem to work.</p> <p>Thanks in advance,</p>
<python><python-3.x><string><find><substring>
2024-05-15 14:44:08
3
840
iraciv94
78,484,689
511,302
Django test if all objects that refer to an object have a certain "flag"?
<p>When I need to test if an object isn't reffered to anymore I could use</p> <pre><code>class ModelA(models.Model): pass class ModelB(models.Model): retired = models.BooleanField(default=False) modelA = models.ForeignKey( ModelA, ) ModelA.objects.filter(~Q(modelb__isnull=False)) </code></pre...
<python><django><orm>
2024-05-15 14:36:58
1
9,627
paul23
78,484,486
1,071,405
How to group 3d points closer than a distance threshold in python?
<p>I have a set of 3d points and I want find any groups of them that are &quot;close together&quot; based on some threshold distance and make a group (removing them from my set). So I end up with a set of groups of points and the remainder.</p> <p>The definition of &quot;close together&quot; would be that they fit in a...
<python><algorithm><3d>
2024-05-15 14:01:35
2
683
Jules
78,484,063
6,912,069
reverse order by group in polars
<p>I'd like to <strong>reverse</strong> (not sort!) the order of a column in a polars dataframe, but only for the scope of a group. I know this is not so common, but I stumbled over a use case, where I need a symmetric group by operation for both ordereings (normal and reversed).</p> <p>Here is some example code:</p> <...
<python><python-polars>
2024-05-15 12:46:18
3
686
N. Maks
78,483,941
822,896
Pandas DataFrame With Counted Values
<p>I have the following data:</p> <pre class="lang-py prettyprint-override"><code>data = [{'Shape': 'Circle', 'Color': 'Green'}, {'Shape': 'Circle', 'Color': 'Green'}, {'Shape': 'Circle', 'Color': 'Green'}] </code></pre> <p>Which I create a DataFrame from:</p> <pre class="lang-py prettyprint-override"><code>df = pd.Dat...
<python><pandas><dataframe>
2024-05-15 12:28:13
2
1,229
Jak
78,483,843
525,865
How to scrape links from summary section / link list of wikipedia?
<p>update: many thanks for the replies - the help and all the efforts! some additional notes i have added. below (at the end)</p> <p>howdy i am trying to scrape all the Links of a large wikpedia page from the &quot;List of <strong>Towns and Gemeinden in Bayern</strong>&quot; on Wikipedia using python. The trouble is th...
<python><pandas><web-scraping><beautifulsoup><python-requests>
2024-05-15 12:08:20
2
1,223
zero
78,483,799
2,178,942
Plotting an array with size n*512 to the PC components of another array with size n*256
<p>I have an array <code>a</code> with size <code>n*512</code>, I first want to plot it using PCA.</p> <p>Next, I have another array <code>b</code> with size <code>n*256</code>, I want to plot it on the PCA components obtained above...</p> <p>How can I do it?</p>
<python><algorithm><plot><pca><dimensionality-reduction>
2024-05-15 12:02:04
1
1,581
Kadaj13
78,483,761
770,513
Wagtail Django migration doesn't get applied when running `migrate`
<p>When I run Django <code>makemigrations</code> on Wagtail I get a migration (pasted at the bottom) which doesn’t seem to migrate properly. Here you see me making the migration successfully, applying it without errors and then, after doing <code>runserver</code>, being told that I have migrations to run.</p> <pre><cod...
<python><django><migration><wagtail>
2024-05-15 11:55:05
1
3,251
KindOfGuy
78,483,689
6,468,053
pyinstaller and kaleido not working together
<p>I'm building an exe using pyinstaller. A line of code involves writing a static image in the usual way like this:</p> <pre><code>fig.write_image(file=thumb_file, format='jpeg', scale=0.4) </code></pre> <p>I've installed conda install -c conda-forge python-kaleido=0.1.0 as per <a href="https://stackoverflow.com/ques...
<python><pyinstaller><kaleido>
2024-05-15 11:43:18
1
1,528
A Rob4
78,483,553
619,774
Why does Pygame Mixer not work when using sudo?
<p>I have a super simple python script:</p> <pre><code>import pygame pygame.mixer.init() </code></pre> <p>When executing this on a RaspberryPi, it works like a charm:</p> <pre><code>python mytest.py -&gt; OK </code></pre> <p>But when running as sudo, I get a weird error:</p> <pre><code>sudo python mytest.py -&gt; Not...
<python><linux><pygame><raspberry-pi><sudo>
2024-05-15 11:19:42
0
9,041
Boris
78,483,476
6,808,376
How and where to download headless chrome (offline) latest for RHEL7.9
<p>I am trying web scrapping using the pyppeteer module. I am using the executablePath for headless chrome. Few sites failing to open the page due to older version of chrome.</p> <p>My team used the <strong>HeadlessChrome/119.0.6045.105</strong>. So I am trying to use the latest version but no idea what's the latest ve...
<python><google-chrome><puppeteer><google-chrome-headless><rhel7>
2024-05-15 11:03:53
0
601
thulasi39
78,483,296
3,572,950
strange behavior of aiohttp with pytest
<p>So, I want to return <code>HTTPNoContent</code> response in specific controller (I'm using <code>aiohttp</code>). And then I want to test it with <code>pytest</code>:</p> <pre><code>from aiohttp import web from aiohttp.web import HTTPNoContent async def hello(request): raise HTTPNoContent(text=&quot;some test!&...
<python><python-3.x><pytest><aiohttp>
2024-05-15 10:27:43
1
1,438
Alexey
78,483,238
4,784,914
How to return a default object instead of `None` for an optional relationship in SQLAlchemy?
<p>I have a <code>users</code> table and a <code>roles</code> table, such that a <code>User</code> optionally has a single <code>Role</code>:</p> <pre><code>class User(Base): id: Mapped[int] = mapped_column(primary_key=True) role: Mapped[Optional[&quot;Role&quot;]] = relationship(back_populates=&quot;user&quot...
<python><sqlalchemy><orm>
2024-05-15 10:18:16
1
1,123
Roberto
78,483,223
11,803,687
flask-caching config ignores the redis password
<p>Hey I do not understand why flask-caching seems to be ignoring the redis password</p> <p>I have a redis setup with a password set to 1234, but when I configure flask-caching with a config using a CACHE_REDIS_PASSWORD also set to 1234, I am still getting the &quot;Authentication Required&quot; error</p> <p>i put this...
<python><flask><redis>
2024-05-15 10:15:07
2
1,649
c8999c 3f964f64
78,483,141
17,176,829
printing decision tree as an image in python
<p>I have written a decision tree class in Python which uses the Node class as tree nodes, as shown below:</p> <pre><code>class Node: ''' Helper class which implements a single tree node. ''' def __init__(self, feature=None, threshold=None, data_left=None, data_right=None, gain=None, value=None): ...
<python><classification><visualization><decision-tree>
2024-05-15 10:04:08
1
433
Narges Ghanbari
78,482,883
10,595,871
Strange behaviour on Random Forest Classifier
<p>I've build two identical rf_classifier, like so:</p> <pre><code>rf_PB = RandomForestClassifier(n_estimators=800, min_samples_split = 10, min_samples_leaf = 4, max_features = 'sqrt', max_depth = 50, bootstrap = True, random_state=59) </code></pre> <p>And trained with two identical datasets but with 2 different...
<python><random-forest>
2024-05-15 09:19:30
0
691
Federicofkt
78,482,683
5,746,996
How to add type inference to Python Flask and Marshmallow
<p>I'm new to Python from a Typescript background. Putting together a Flask API server and using Marshmallow to validate input DTOs.</p> <p>How can I get VSCode to infer types from the Marshmallow Schema load?</p> <pre><code>class PostInput: myString = fields.Str( required=True ) @app.route('/foo', met...
<python><python-typing><marshmallow><pyright>
2024-05-15 08:45:55
1
2,057
Tobin
78,482,407
7,800,726
How not to perform rounding from float to torch.float64
<p>I want to convert a list of floats into a tensor. How can I do it without rounding being performed?</p> <pre><code>tensor = torch.tensor(res, dtype=torch.float64) # res:[-0.5479744136460554, -0.5555555555555556, -1.0] # currently tensor = [tensor([-0.5480, -0.5556, -1.0000], dtype=torch.float64) # goal tensor = [...
<python><tensor><torch>
2024-05-15 07:51:36
1
558
Ian Gallegos
78,482,316
12,427,876
Decrypt & Re-Encrypt Chrome cookies
<p>I'm trying to decrypt Chrome's cookie SQLite DB, and move the decrypted cookies to another computer (browser), and re-encrypt the DB, and replicate sessions.</p> <p>Here is what I plan:</p> <ol> <li>Decrypt AES key from <code>Local State</code> in <code>C:\Users\[username]\AppData\Local\Google\Chrome\User Data\Local...
<python><google-chrome><encryption><cookies><dpapi>
2024-05-15 07:34:03
1
411
TaihouKai
78,482,279
19,146,511
past key values from hidden states
<p>I'm trying to extract past key, value pair using attention_layers and hidden_state for a particular layer</p> <pre><code>import torch import torch.nn.functional as F from transformers import LlamaConfig from transformers import LlamaModel, LlamaTokenizer, LlamaForCausalLM tokenizer = LlamaTokenizer.from_pretrained(...
<python><nlp><huggingface-transformers><large-language-model>
2024-05-15 07:26:02
0
307
lazytux
78,482,270
11,022,199
Saving and dropping a dataframe in a for loop
<p>I have a number of dataframes from which I have to take a sample. The samples taken from that dataframe, have to be excluded from the next dataframe in order to not have any 'double' samples as there is some overlap.</p> <p>my code is as follows</p> <pre><code>df_list = [df1, df2, df3, df4, df5] samplesizes = [8, 2,...
<python><pandas><dataframe>
2024-05-15 07:24:35
1
794
borisvanax
78,482,107
6,573,770
How to Loop through each element of a loop and filter out conditions in a python dataframe
<p>I have a list of subcategories and a dataframe. I want to filter out the dataframe on the basis of each subcategory of the list.</p> <pre><code>lst = [7774, 29409, 36611, 77553] import pandas as pd data = {'aucctlg_id': [143424, 143424, 143424, 143388, 143388, 143430], 'catalogversion_id': [1, 1, 1, 1, 1, 1...
<python><pandas><loops>
2024-05-15 06:54:27
2
329
Ami
78,482,092
22,400,527
Accessing the files in a folder of google drive using google oauth
<p>I am trying to create a web application using FastAPI for backend and ReactJS for frontend. I need the users to give me a link of a folder in their google drive in the frontend. I then need to access the files in that folder from my backend.</p> <p>I created a new project in console.cloud.google.com and created clie...
<python><google-drive-api><google-oauth><fastapi>
2024-05-15 06:51:31
0
329
Ashutosh Chapagain
78,482,068
1,869,935
Docker build . hangs indefinitely without feedback on MacOS Big Sur
<p>I'm new to Docker, and following along a course. I went step by step creating some basic files to start a Django project on Docker, which are the following:</p> <p><a href="https://i.sstatic.net/OJ8x8A18.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OJ8x8A18.png" alt="enter image description here" /...
<python><django><docker><build>
2024-05-15 06:45:22
0
757
user1869935
78,482,038
1,028,133
Shift + Tab tooltips not showing in JupyterLab 4.2.0 / Python 3.12.3 (pyenv) on Ubuntu 24
<p>SHIFT + TAB tooltips are not showing for me in my fresh Jupyterlab install.</p> <p>Platform: Python 3.12.3 (via pyenv) on Ubuntu 24.04.</p> <p>Here's the output of <code>$ jupyter --version</code>:</p> <pre><code>Selected Jupyter core packages... IPython : 8.24.0 ipykernel : 6.29.4 ipywidgets :...
<python><ubuntu><jupyter-lab>
2024-05-15 06:38:29
2
744
the.real.gruycho
78,481,849
1,084,174
Kernel Restarting: The kernel for .ipynb appears to have died. It will restart automatically
<p>I have trained a model using keras. Model summary:</p> <pre><code>Model: &quot;sequential_1&quot; ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━...
<python><tensorflow><tflite>
2024-05-15 05:50:05
0
40,671
Sazzad Hissain Khan
78,481,813
1,930,462
Type-correct implementation of a python decorator that drops the first argument to a function
<p>I'm trying to figure out how to write a decorator that passes strict type checks as well as preserve type information about the original arguments of a function.<br /> What makes <em><strong>this case</strong></em> tricky, is that the decorator must drop the first argument of the function it is wrapping.</p> <p>I've...
<python><mypy><python-typing>
2024-05-15 05:40:31
0
956
Ru Hasha
78,481,798
7,700,802
How to adjust pictures alignment on fpdf
<p>I have this code that generates a investment summary and some analytic images</p> <pre><code>def investment_summary(pdf, text, bullet_indent=15): pdf.set_font(&quot;Arial&quot;, size=8) for point in text.splitlines(): if point.startswith(&quot;-&quot;): pdf.set_x(bullet_indent) p...
<python><pyfpdf>
2024-05-15 05:38:02
1
480
Wolfy
78,481,761
15,460,398
Can not open Video file using opencv on JETSON NANO
<p>Tried to use opencv to open a <code>.mp4</code> file in NVIDIA JETSON NANO using code:</p> <pre><code>import cv2 video_path = 'bird.mp4' cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print(&quot;Error: Could not open video.&quot;) exit() while True: ret, frame = cap.read() if not ret: ...
<python><opencv><nvidia-jetson-nano>
2024-05-15 05:28:28
0
361
BeamString
78,481,723
6,401,403
Pandas read_html: keep cell content format as html
<p>I have a Word document with multiple tables. I'm converting it to html format and read it with pandas:</p> <pre><code>tables = pd.read_html('report.htm') </code></pre> <p>But the text in cells has subscripts, superscripts and special characters, so, for example, 5×10<sup>-5</sup> becomes 5?10-5, while in html format...
<python><html><pandas><richtext>
2024-05-15 05:14:27
0
5,345
Michael
78,481,661
22,213,065
Get SubPath info with python
<p>I have a large number of GIF files that are very similar to the following sample:</p> <p><a href="https://i.sstatic.net/H3MIbj4O.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/H3MIbj4O.gif" alt="enter image description here" /></a></p> <p>Now, I want to create a <code>color range selection</code> wit...
<python><opencv><imagemagick><photoshop>
2024-05-15 04:49:40
0
781
Pubg Mobile
78,481,611
748,493
Get value from ElementTree using the full path
<p>Let's say we have the following xml string</p> <pre><code>xml_string = ''' &lt;Wikimedia&gt; &lt;projects&gt; &lt;project name=&quot;Wikipedia&quot; launch=&quot;2001-01-05&quot;&gt; &lt;editions&gt; &lt;edition language=&quot;English&quot;&gt;en.wikipedia.org&lt;/edition&gt; &lt;edition ...
<python><xml><elementtree>
2024-05-15 04:29:24
1
522
Confounded
78,481,546
107,294
What are the differences between pdoc and pdoc3?
<p>I've found what appear to be two forks of the pdoc documentation generator <a href="https://pypi.org/project/pdoc/" rel="nofollow noreferrer">pdoc</a> (<a href="https://github.com/mitmproxy/pdoc" rel="nofollow noreferrer">GitHub</a>) and <a href="https://pypi.org/project/pdoc3/" rel="nofollow noreferrer">pdoc3</a> (...
<python><documentation-generation>
2024-05-15 04:01:03
2
27,842
cjs
78,481,462
1,603,480
HTTPS GET with API Bearer Token: working with cURL but not with Python requests.get
<p>When I launch the following cURL command on a https URL with an API token, I get the expected response (a list of files in my storage): <code>curl -H &quot;Authorization: Bearer &lt;TOKEN&gt;&quot; &quot;https://my_website.com:443/api/storage&quot;</code>.</p> <p>However, when I try with <code>requests.get</code> in...
<python><curl><https><python-requests><bearer-token>
2024-05-15 03:24:28
1
13,204
Jean-Francois T.
78,481,278
15,587,184
Splitting HTML file and saving chunks using LangChain
<p>I'm very new to LangChain, and I'm working with around 100-150 HTML files on my local disk that I need to upload to a server for NLP model training. However, I have to divide my information into chunks because each file is only permitted to have a maximum of 20K characters. I'm trying to use the LangChain library to...
<python><html><split><langchain><py-langchain>
2024-05-15 01:44:46
2
809
R_Student
78,481,247
1,330,974
Python Pool.apply_async() is returning None type objects
<p>I have a 4GB+ file in which each line represents a very nested JSON string. An example of what the file looks like would be below:</p> <pre><code>{&quot;core&quot;:{&quot;id&quot;:&quot;1&quot;,&quot;field1&quot;:{&quot;subfield1&quot;:1, &quot;subfield2&quot;:{&quot;subsubfield1&quot;: 1}},....,&quot;field700&quot;...
<python><multiprocessing><python-multiprocessing><python-multithreading>
2024-05-15 01:22:19
2
2,626
user1330974
78,481,195
3,398,324
Reinforcement Learning Shape Error: ValueError: Error
<p>I am using the below approach to create simple DL-RL Model, but I am getting this error:</p> <pre><code>ValueError: Error when checking input: expected flatten_1_input to have 2 dimensions, but got array with shape (1, 1, 2) </code></pre> <p>I am using the following versions of libraries and Python:</p> <p>Python 3....
<python><tensorflow><tf.keras>
2024-05-15 00:52:22
0
1,051
Tartaglia
78,481,178
2,803,777
How to do matrix multiplication under numpy in higher dimensions?
<p>Under numpy I want to perform a &quot;usual&quot; matrix multiplication like this:</p> <p>C=A*B</p> <p>where</p> <p>A is a &quot;2D-kind&quot; Matrix, but each matrix element has shape (1,5)</p> <p>and</p> <p>B is a &quot;1D-kind&quot; Vector, but each vector element element has shape (20,5)</p> <p>The result</p> <p...
<python><numpy>
2024-05-15 00:42:45
2
1,502
MichaelW
78,481,175
1,429,450
Easy way to store SciPy sparse symmetric matrix in a local file, load it into shared memory (shm), and reconstruct it from shm?
<p>Easy way to store the upper diagonal (including the diagonal) of a <a href="https://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow noreferrer">SciPy sparse matrix</a> in a local file, load the file into shared memory (shm), and reconstruct the sparse matrix from the shm?</p> <p><a href="https://chat.o...
<python><scipy><sparse-matrix><shared-memory><symmetric>
2024-05-15 00:41:14
1
5,826
Geremia
78,480,373
1,658,080
Evenly Distribute Stars on a Sphere According to Categories
<p>I'm working on a project where I need to map stars onto a virtual sphere. The stars must be evenly spaced from each other and from the center of the sphere (0,0,0), with a specific distribution of brightness categories across the sphere's surface. Each segment of the sphere should have a proportional mix of stars ba...
<python><algorithm><math><geometry><visualization>
2024-05-14 19:51:00
1
725
Clms
78,480,305
616,460
Unknown target CPU 'x86-64-v3' when building via pip/clang
<p>When installing the <code>netifaces</code> package with <code>pip</code>, I get the following error while building its wheel (Debian 10, and Python 3.10):</p> <pre class="lang-none prettyprint-override"><code>building 'netifaces' extension clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrap...
<python><pip><clang>
2024-05-14 19:34:48
1
40,602
Jason C
78,480,228
14,250,641
how to find regional overlap between two dfs
<p>I have one df that has chr and position and the other has chr, start, end. I want to find all of the regions from df1 that match the chr and overlap with the position of df0. Please see the example below for more clarity. FYI I have large dfs</p> <pre><code>df0: chr position 1 33 1 100 1 ...
<python><pandas><dataframe><bioinformatics>
2024-05-14 19:15:01
1
514
youtube
78,480,187
2,276,022
How do I delete all documents from a Marqo index?
<p>I have a ton of documents that have been vectorized poorly / are using an old multimodal_field_combination.</p> <pre><code>mappings={ 'combo_text_image': { &quot;type&quot;: &quot;multimodal_combination&quot;, &quot;weights&quot;: { &quot;name&quot;: 0.05, &quot;descriptio...
<python><vector><vespa><marqo>
2024-05-14 19:06:24
1
351
nostrebor
78,479,791
16,136,190
Getting requests.exceptions.InvalidHeader: Header part (1) from ('Sec-Gpc', 1) must be of type str or bytes, not <class 'int'> though Chrome sends it
<p>I get <code>requests.exceptions.InvalidHeader: Header part (1) from ('Sec-Gpc', 1) must be of type str or bytes, not &lt;class 'int'&gt;</code> when trying to use the <code>Sec-Gpc</code> attribute in a header:</p> <pre class="lang-json prettyprint-override"><code>headers = { ..., &quot;Sec-Gpc&quot;: 1, ...
<python><python-requests><cross-browser><request-headers><http-request-attribute>
2024-05-14 17:33:58
1
859
The Amateur Coder
78,479,625
5,317,274
How do you mix 1d and 2d variables in a pandas dataframe?
<p>I am working with a bucketload of data that has the form:</p> <pre><code>import pandas as pd import numpy as np lat = np.array([80.589, 80.592, 80.595]) lon = np.array([50.268, 50.264, 50.260]) wav = np.array([[486, 605, 666, 821, 777, 719], [ 65, 60, 68, 67, 72, 64], [866, 94...
<python><pandas>
2024-05-14 17:00:40
2
377
EBo
78,479,519
6,652,048
Django Update on UniqueConstraint
<p>I'm trying to work with UniqueConstraint but I've been facing some issues trying to update it the way I want.</p> <p>I have the following model</p> <pre><code>class QueryModel(models.Model): id = models.AutoField(_(&quot;query id&quot;), primary_key=True) user = models.ForeignKey(UserModel, on_delete=models...
<python><django><django-rest-framework>
2024-05-14 16:38:49
1
303
Pedro Daumas
78,479,439
7,746,472
Run Python script from shell script, with Virtualenv, and as module with -m
<p>How can I run a Python script from a shell script, with the conditions:</p> <ol> <li>it uses a helper script from a parallel folder</li> <li>it uses the virtual environment for its subfolder</li> </ol> <p>My file/folder structure looks like this:</p> <pre><code>project_folder -subfolder_prog_1 -prog1.py -sub...
<python><python-3.x><pipenv>
2024-05-14 16:20:56
2
1,191
Sebastian
78,479,399
810,815
Running Flask in Debug Mode
<p>I am working on my first Flask app. All I am trying to do is to make sure that my Flask server restarts after I edit the hello.py file.</p> <p>Here is my app structure: <a href="https://i.sstatic.net/KKh64CGy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KKh64CGy.png" alt="enter image description he...
<python><flask>
2024-05-14 16:15:18
3
9,764
john doe