question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
76,503,643
2023-6-19
https://stackoverflow.com/questions/76503643/how-to-change-traceback-back-to-normal
My most recent env prints traceback like this ╭───────────────────── Traceback (most recent call last) ──────────────────────╮ which is beyond useless. I've already looked at this How to make typer traceback look normal but it doesn't help. My hunch is it may be about Huggingface but maybe something else like datasets...
It is this thing that causes the issue. So pip uninstall rich solved everything. Edit July 3rd, 2023 This seems to be the issue with accelerate as I originally anticipated. In this case it default to use rich when available. So ACCELERATE_DISABLE_RICH=1 should fix the issue in case other libs require rich for something...
3
2
76,469,795
2023-6-14
https://stackoverflow.com/questions/76469795/does-anyone-see-where-the-error-in-the-following-gekko-ipopt-nonlinear-optimizat
In my code, I get the following error when running: Exception: @error: Equation Definition Equation without an equality (=) or inequality (>,<) ((((((((((-cos(v4)))*(sin(v5)))-((((sin(v4))*(cos(v5))))*(cos(v3)))))*(((sqrt(( 398574405096000.0/((v1)*((1-((v2)^(2))))))))*([(-sin(v6))(v2+cos(v6))0])))))^(2 ))+((((((((-sin(...
The square brackets indicate that a list or numpy array was used instead of a scalar value in one of the expressions. Adding names (e.g. name='a') to the variables helps with a more readable model apm file that is in the local run directory m.path. Open the directory with m.open_folder(). #variables and initial guesses...
3
0
76,509,707
2023-6-19
https://stackoverflow.com/questions/76509707/plotly-sankey-diagram-how-to-display-the-value-for-each-links-and-node-on-the-l
In the Plotly Sankey diagram, you are able to see the 'value' of a link/node by hovering over it. I want the image to display the values without hovering though. I've looked through the documentation and see virtually no way of doing this beside replacing the labels themselves with the desired value. That is not a good...
The node positions are determined by non-trivial algorithms and I am afraid that Plotly does not make the coordinates explicit, as of now, see Extract X and Y coordinates from Plotly Sankey diagram. I think you can: Pass locations computed on your own (may be tricky!), and use the locations to anchor custom annotation...
4
4
76,515,800
2023-6-20
https://stackoverflow.com/questions/76515800/the-difference-between-poetry-add-and-poetry-install
I've thought that poetry add package would simply add the package to pyproject.toml but it seems it doesn't just add but also installs it in a virtual environment. But what does poetry install do? When I run it after I added the deps with add, I am getting the following message: Installing dependencies from lock file N...
poetry add library_name installs the library and adds it to the pyproject.toml file. Note - both installs the library and adds it to the file. poetry install is used when you've directly edited the pyproject.toml file and added the dependency names manually. In that case, they aren't installed yet, so, poetry install t...
8
16
76,495,086
2023-6-17
https://stackoverflow.com/questions/76495086/not-able-to-override-unittest-starttest-and-stoptest-isn-t-working-correctly
I have override startTest and stopTest from unittest TextTestResult class and used it in my custom test runner. It’s working correctly in normal scenario but not working correctly when using with --parallel flag. I tried to debug and found the time elapsed b/w startTest and stopTest is coming very very small. Like 4.80...
test_runner.resultclass (CustomTestRunnerTextTestResult) methods are not called in real-time if using --parallel flag. Rather, parallel_test_suite.runnerclass.resultclass (RemoteTestResult) methods are called, which queue events (method calls to test_runner.resultclass) to be dispatched together by parallel_test_suite ...
3
1
76,517,805
2023-6-20
https://stackoverflow.com/questions/76517805/is-there-a-difference-between-permission-classes-a-b-permission-classes
What is the difference between permission_classes = [A, B] permission_classes = [A & B] ?? I understand that the first one processes permission sequentially, and the second one does it at once. Is there a difference in the result? Also, I wonder which method is preferred and why.
In short: two or more elements in a list or tuple is advisable. Semantically the two are nearly the same. Indeed, Django checks the permissions in the .check_permissions(…) method [GitHub]: def check_permissions(self, request): """ Check if the request should be permitted. Raises an appropriate exception if the reques...
2
4
76,512,183
2023-6-20
https://stackoverflow.com/questions/76512183/efficient-python-function-to-get-value-of-specific-key-in-nested-dict-without-an
The following initial situation: I am looking for a custom function that will extract a corresponding value from a nested dict and return it without external libs and without kowning the whole static path to the corresponding key. The function "search path" (dict key) should be similar to the CSS or XPATH selector, e.g...
One possible approach: Recursive generator to find all values for a single key anywhere within a nested dict: def find(nested_dict, key): if key in nested_dict: yield nested_dict[key] for v in nested_dict.values(): if isinstance(v, dict): yield from find(v, key) find(test_dict, "3") # {"b31" : 31} # {"c31" : 55} Helpe...
3
2
76,518,869
2023-6-20
https://stackoverflow.com/questions/76518869/tweepy-errors-forbidden-403-forbidden-issue-with-twitter-api-authentication-u
I'm encountering tweepy.errors.Forbidden: 403 Forbidden When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal. while trying to run the following code that fetches a user's ...
Your app has the Free access tier which only allows: Posting tweets with the Twitter API v2 Media Upload and Login With Twitter with the Twitter API v1.1 To do anything else, you need at least the Basic access tier, which costs some money. The access tiers are documented in https://developer.twitter.com/en/docs/twitt...
5
9
76,517,809
2023-6-20
https://stackoverflow.com/questions/76517809/how-can-i-make-this-function-more-numerically-stable
The following function is supposed to work similarly to pow(x, 1/k) but to be symmetric around the line y = 1 - x as well as not having a 0 or 1 slope at either end of [0, 1]: def sym_gamma(x, k): if k == 1.0: return x a = 1.0 / k - 1.0 b = 1.0 / a c = k + 1.0 / k - 2.0; return 1.0 / (a - c * x) - b As can be seen, it...
Simplifying your expression seems to help with the precision. Numerical errors tends to accumulate in each operation. Thus, reducing the number of operation will reduce the chance of numerical errors. We can notice that: a = (1 - k) / k b = k / (1 - k) c = (1 - k) ** 2 / k a - c * x = (1 - k) * (1 + x*k - x) / k 1.0 / ...
3
5
76,488,582
2023-6-16
https://stackoverflow.com/questions/76488582/python-proper-way-to-run-an-async-routine-in-a-pytest-fixture
The test below passes, but I have doubts that I am using asyncio correctly: The code mixes asyncio and threading The test is passing but never exits (probably because the "loop.run_until_complete" never ends) import asyncio import threading import pytest import websockets async def echo(websocket): async for message ...
You need some other code in the thread running the server to receive a signal from the main thread and shut itself down. Fortunately, due to asyncio nature, this control can be built in a separate function, without interfering at all with the function implementing the server itself. Only the function that creates the l...
6
3
76,501,267
2023-6-18
https://stackoverflow.com/questions/76501267/randomly-generate-all-unique-pair-wise-combination-of-elements-between-two-list
I have two lists: a = [1, 2, 3, 5] b = ["a", "b", "c", "d"] And would like to generate all possible combinations with a python generator. I know I could be doing: combinations = list(itertools.product(a,b)) random.shuffle(combinations) But that one has an extreme memory cost as i would have to hold in memory all poss...
We create a sequence using a prime number and one of its primitive roots modulo n that visits each number in an interval exactly once. More specifically we are looking for a generator of the multiplicative group of integers modulo n. We have to pick our prime number a little larger than the product len(a)*len(b), so we...
3
1
76,491,765
2023-6-16
https://stackoverflow.com/questions/76491765/docker-buildx-failing-with-problem-executing-scripts-aptupdatepost-invoke
I have a docker image building through a circle.ci pipeline, it's pulling an ECR image from AWS and hosted on EB/EC2 and its failing to build continuously with this error: #5 0.329 Get:1 http://deb.debian.org/debian bookworm InRelease [147 kB] #5 0.339 Get:2 http://deb.debian.org/debian bookworm-updates InRelease [52.1...
Looks like the version of docker being used needs updating. I was also having this problem using an old version of docker (20.10.6 - don't ask). There was a Debian release a few days ago. python:3.9-slim derives from this new Debian version and there are some issues with running images based on this Debian version with...
5
4
76,490,589
2023-6-16
https://stackoverflow.com/questions/76490589/valueerror-when-using-model-fit-even-with-the-vectors-being-aligned
I am attempting to build a naive Bayes model for text classification. Here is a sample of the data I'm working with: df_some_observations = filtered_training.sample(frac=0.0001) df_some_observations.to_dict() The output looks like this: {'Intitulé (Ce champ doit respecter la nomenclature suivante : Code action – Libel...
I think that the main problem that TfidfVectorizer is able to work with one-dimensional text data only (as I see it from here). That's why when it tries to convert several columns with text data it tries to do it for column names for some reason. In your case I see 2 ways how to solve this problem: If you want to appl...
4
1
76,509,000
2023-6-19
https://stackoverflow.com/questions/76509000/large-matrix-multiplication-with-low-memory-usage-in-numpy
I have a complex matrix multiplication with several hundreds of thousands of rows and columns. At some point the memory usage grows to 100% and then the computer is freezed and I have to restart it manually. I have tried with Numba (writing the code inside a function with a decorator) and Dask (transforming the numpy a...
Main issue The main issue is that 1j*np.outer(a1,a2) takes 100_000 * 100_000 * (8 * 2) = 149 GiB. On top of that, np.exp needs to read this matrix and produce another one of the same size so you need at least ~300 GiB of RAM just for this. This is HUGE and inefficient. You should avoid creating the matrix A at any pric...
5
4
76,509,992
2023-6-19
https://stackoverflow.com/questions/76509992/add-a-column-with-the-new-value-from-a-tuple-value-in-another-column
I have this df: df = pd.DataFrame( {'loss': [0.044, 0.044, 0.038, 0.037, 0.036], 'code': ["('ac',)", "('ac', 'be')", "('ab', 'ac', 'be')", "('ab', 'ac', 'be', 'fi')", "('ab', 'ac', 'be', 'de', 'fi')"]} ) df loss code 0 0.044 ('ac',) 1 0.044 ('ac', 'be') 2 0.038 ('ab', 'ac', 'be') 3 0.037 ('ab', 'ac', 'be', 'fi') 4 0.0...
Assuming there is one new value per row, you can convert to tuples, explode and drop_duplicates: from ast import literal_eval df['added'] = (df['code'] .apply(literal_eval) .explode() .drop_duplicates() ) Output: loss code added 0 0.044 ('ac',) ac 1 0.044 ('ac', 'be') be 2 0.038 ('ab', 'ac', 'be') ab 3 0.037 ('ab', '...
2
5
76,509,045
2023-6-19
https://stackoverflow.com/questions/76509045/how-to-hide-the-errorbar-if-there-are-less-than-3-data-points-in-the-category
I want to have error bars in my bar plots when more than 3 data points are available (Condition A) but omit error bars when there are less than 3 data points for that specific condition (Condition B). I've only found options to show or hide error bars for all bars, not for specific conditions. import pandas as pd impor...
You can use a custom errorbar function in sns.barplot. It should return a [y1, y2] iterable with the position of the min/max error: # defining a custom function to only compute # the error if more than 3 values def cust_error(s): if len(s)<3: return [None, None] else: avg = s.mean() std = s.std() return [avg-std, avg+s...
3
5
76,509,006
2023-6-19
https://stackoverflow.com/questions/76509006/typeerror-cannot-cast-datetimearray-to-dtype-datetime64d
I recently updated my python install from 3.11.2 to 3.11.3, pandas version is 2.0.2 I am now getting this error: TypeError: Cannot cast DatetimeArray to dtype datetime64[D] When I try to perform this: df = df[df['CancelDate'].astype('datetime64[D]') >= (datetime.now() - relativedelta(years=2))] On this dataframe: myd...
To solve this issue, you can use the pd.pd.to_datetime function to convert the 'CancelDate' column to a DatetimeArray before performing the comparison. df['CancelDate'] = pd.to_datetime(df['CancelDate']) # Convert to DatetimeArray df = df[df['CancelDate'] >= (datetime.now() - relativedelta(years=2))]
5
3
76,489,928
2023-6-16
https://stackoverflow.com/questions/76489928/error-when-importing-pandas-importerror-cant-determine-version-for-numexpr
I am having problems with importing the pandas package. I used the following command to import it: import pandas as pd However, I receive the following error message: Traceback (most recent call last): Cell In[54], line 1 import pandas as pd File ~\AppData\Local\anaconda3\lib\site-packages\pandas\__init__.py:48 from p...
If you are on ubuntu linux, you can try sudo apt-get install python-numexpr. Refer this answer - https://askubuntu.com/questions/446644/why-do-i-get-importerror-when-trying-to-import-pandas-python-module After installing numexpr and bottleneck, you can try pip install --force-reinstall pandas or pip install --upgrade -...
4
2
76,499,565
2023-6-18
https://stackoverflow.com/questions/76499565/python-does-not-find-module-installed-with-pipx
Debain stable wants me to install Python modules using pipx. So I do $ pipx install auditwheel $ pipx ensurepath $ python3 -m pipx ensurepath $ python3 Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import auditwheel Traceback...
From Python 3.11 onward, Debian encourages the users to create a separate Python virtual environment to install Python packages. Because Debian declares its Python install to be externally-managed, pip (and other installers) will refuse to install packages system-wide. Installation is only possible in virtual environme...
21
14
76,504,640
2023-6-19
https://stackoverflow.com/questions/76504640/pandas-group-by-find-the-difference-with-respect-to-flag-ids
I Have the following Data frame: id flag col_1 col_2 name 0 1 1 11 13 a 1 2 0 62 14 b 2 1 0 13 15 a 3 2 1 74 16 b 4 3 1 25 17 c 5 3 0 22 18 c I need this as the output - id col_3 col_4 name 0 1 2 2 a 1 2 -12 -2 b 2 3 -3 1 c I need to group by id, name and take flag[0] of col_1 - flag[1] of the col_1 which has id, n...
Using simple indexing with a temporary index (set_index and reset_index) tmp = df.set_index(['flag', 'id', 'name']) out = (tmp.loc[0] - tmp.loc[1]).reset_index() Output: id name col_1 col_2 0 1 a 2 2 1 2 b -12 -2 2 3 c -3 1 Used input: df = pd.DataFrame({'id': [1, 2, 1, 2, 3, 3], 'flag': [1, 0, 0, 1, 1, 0], 'col_1':...
2
3
76,504,339
2023-6-19
https://stackoverflow.com/questions/76504339/pandas-update-multiple-rows-using-list
I am trying to update pandas dataframe using list. Dataframe with columns A, B, C A B C ------ 1 a F 2 b F 3 c F 4 d F 5 e F I have 2 lists, one contains list of elements whose value needs to update from column B and second contains actual value to replace in column C. Elements to update from column B names=['a', 'd',...
You can use boolean indexing combined with map: names = ['a', 'd', 'e'] values = ['T', 'T', 'G'] m = df['B'].isin(names) df.loc[m, 'C'] = df.loc[m, 'B'].map(dict(zip(names, values))) Less efficient alternatives: df['C'] = df['B'].map(dict(zip(names, values))).fillna(df['C']) df['C'] = df['C'].mask(df['B'].isin(names),...
3
3
76,483,104
2023-6-15
https://stackoverflow.com/questions/76483104/why-does-calling-time-sleep-with-different-values-alter-the-execution-time-of-pa
I run this code multiple time with different SLEEP_TIME, for example SLEEP_TIME=0, SLEEP_TIME=1e-3, SLEEP_TIME=10e-3 and also omitted the time.sleep line altogether from the code. For every value of SLEEP_TIME the measured average work time changes, even though the sleep is outside the measured code. This makes zero se...
I reproduced the behavior of your python script on my Ubuntu machine. In my case it was not specific to python, and I found similar performance degradation in a c++ program that sleeps between each computation. There are various mechanisms in Linux that reduce the frequency of the CPU(s) in order to save power when the...
3
2
76,469,459
2023-6-14
https://stackoverflow.com/questions/76469459/firebase-cloud-functions-python-cannot-add-dependencies
I'm using python cloud functions in my firebase project. After initializing cloud functions, adding firebase-admin to the requirements.txt file worked, and I could test with firebase emulators:start and also successfully deploy with firebase deploy --only functions. The issue is when I try to add other packages. I adde...
The following solved the issue for me: Delete the venv folder created by firebase init functions. Create a new one as follows: python3.11 -m venv venv source venv/bin/activate pip3 install --upgrade pip python3.11 -m pip install -r requirements.txt Now deploy with firebase deploy --only functions
4
8
76,500,990
2023-6-18
https://stackoverflow.com/questions/76500990/why-is-beautifulsoup-returning-none-when-scraping-google-search-results
I'm trying to use BeautifulSoup to find the birth years of different authors. I'm working in VS Code, if that's relevant. This is my first attempt at web scraping so please explain things as clearly as possible For authors with wikipedia pages, I can successully find birth years using the following code: source_code = ...
If you want to parse the born date I'd chose different strategy: Find a <span> tag with text "Born:" and then next sibling. Also add hl=en parameter to URL to get english results: import requests from bs4 import BeautifulSoup url = 'https://www.google.com/search?q=Guillermo+Saccomanno&hl=en' headers = {'User-Agent': 'M...
3
1
76,502,018
2023-6-18
https://stackoverflow.com/questions/76502018/tkinter-throws-importerror
I was trying to make my first Tkinter project in Python but it just shows me this: >>> from tkinter import * Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.11/tkinter/__init__.py", line 38, in <module> import _tkinter # If this fails your Python may not be configured for T...
Try # pacman -S tk I had the same problem and that fixed it.
3
2
76,498,784
2023-6-18
https://stackoverflow.com/questions/76498784/is-there-a-way-to-access-feature-names-labels-from-a-keras-model-alone
I'm trying to retrieve feature names from a Keras model in a generalized way. I want to load a pretrained model and obtain its feature names, like this: labels = model.get_feature_names() I'm looking for something that works with any Keras model, ideally as a method that takes a black box Keras model and returns the f...
No, unlike sklearn there isn't a Keras/Tensorflow equivalent for obtaining feature names. This is because tensorflow-keras models focus more on the shape and dimensions of the input tensors rather than the individual features. The model utilizes the input features as tensors, regardless of name. With some effort you mi...
3
1
76,500,916
2023-6-18
https://stackoverflow.com/questions/76500916/numba-crashes-python-with-parallel-true-flag-set
I'm trying to speed up some calculations using the Numba. The call of the nnleapfrog_integrate function lead to segmentation fault and crash of the Python process. The function works fine if the parallel=True flag is removed from its jit decorator. But then it runs in single thread. I want this fuction to run as fast a...
The parallelisation of the i-based loop is not efficient because creating and synchronizing threads is expensive. Indeed, this overhead is usually at least dozens of microseconds on PC and often significantly even bigger on computing server (mainly because of the additional cores). The thing is there is i_steps=43200 i...
4
3
76,501,256
2023-6-18
https://stackoverflow.com/questions/76501256/assign-different-color-to-each-plt-step-line
I have a code which draws lines for the teams according to their tournament position in each game week. Pretty much I managed to make it work, except 2 things: For some reason a 4th (violet) line is drawn (teams are only 3) which goes from the top to the bottom throughout each game week. As I found out this line is dr...
The issues is with the plt.step(), where you are using zip. As per documentation here, you just need to give the x and y values. Updating that line as below... for i, (team, l) in enumerate(df.groupby('Team', sort=False)): plt.step(l['Game_week'], l['Position'], ## No zip '-', color=colors[team], linewidth=8, alpha=0.2...
3
2
76,500,626
2023-6-18
https://stackoverflow.com/questions/76500626/pytest-with-multiprocessing-lock-not-working-as-expected-when-running-tests-in-p
I am trying to run my pytests in parallel using the pytest plugins parallel-0.1.1 and xdist-3.2.1 along with the --tests-per-worker n flag. I have a set of tests that require a preprocessing step which must be run in a critical section. This section is protected by a multiprocessing lock to avoid simultaneous execution...
A library such as https://pypi.org/project/fasteners/ has better locking mechanisms for the goal you're trying to accomplish. You want a lock based around a file so that different processes don't create different locks. import fasteners lock = fasteners.InterProcessLock('path/to/lock.file') with lock: ... # exclusive a...
3
2
76,499,319
2023-6-18
https://stackoverflow.com/questions/76499319/what-is-the-fastest-way-to-find-intersection-of-two-numpy-arrays-while-preservin
I have two one-dimensional NumPy arrays, A and B, of the same length. I want to find the intersection of the two arrays, meaning I want to find all the elements of A that are also present in B. The result should be a boolean array that is True when an element in array A at the index is also a member of array B, preserv...
Why the provided solutions are not efficient np.isin has two implementation. The first consists in sorting the two arrays (using a merge-sort) and then merge them. This solution runs in O(n log n + m log m + n+m) that is O(n log n + m log m). The other implementation is based on a lookup table. This second implementati...
2
5
76,499,877
2023-6-18
https://stackoverflow.com/questions/76499877/create-subplot-by-overlapping-two-dataframes-for-every-group-id
I have the below two dataframe: #Load the required libraries import pandas as pd import matplotlib.pyplot as plt #Create dataset_1 data_set_1 = {'id': [1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3,3, 4, 4, 4, 4, 4,4,], 'cycle': [0.0, 0.2,0.4, 0.6, 0.8, 1,1.2,1.4,1.6,1.8,2.0,2.2, 0.0, 0.2,...
I would concat the two dataframes, then use a single groupby to make the subplots : colors = {"df_1": "blue", "df_2": "red"} df = pd.concat([df_1, df_2], keys=colors) fig, axs = plt.subplots(figsize=(10, 8), nrows=2, ncols=2) for (n, g), ax in zip(df.groupby("id"), axs.flatten()): for s in df.index.levels[0]: g.loc[s]....
3
2
76,478,913
2023-6-15
https://stackoverflow.com/questions/76478913/polars-is-much-slower-than-duckdb-in-conditional-join-group-by-agg-context
For the following example, where it involves a self conditional join and a subsequent groupby/aggregate operation. It turned out that in such case, DuckDB gives much better performance than Polars (~10x on a 32-core machine). My questions are: What could be the potential reason(s) for the slowness (relative to DuckDB)...
EDIT: 2023-7-18 The latest polars release has brought the difference down from 15x to 2x. polars v0.18.2 1125 polars v0.18.3 140 duckdb 0.8.2-dev1 75 Original answer Streaming engine The streaming API isn't as optimized yet. Polars is a younger project than DuckDB and we haven't got as many paid developers on the proj...
3
4
76,496,565
2023-6-17
https://stackoverflow.com/questions/76496565/how-to-reverse-strings-in-a-numpy-array
I want to reverse the order of characters in each string element of a NumPy array. For example, given the following input: array(['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97'], dtype='<U2') I want to obtain the followin...
np.array([e[::-1] for e in arr]) is the straight forward way of doing this, and is NOT bad numpy. or bypass numpy entirely with [e[::-1] for e in arr.tolist()]. You could also do something similar with np.vectorize or np.frompyfunc. These might scale a bit better. 'vectorize' in numpy means using compiled methods (and ...
2
3
76,473,134
2023-6-14
https://stackoverflow.com/questions/76473134/how-can-i-use-duckdb-read-json-auto-in-python-without-creating-a-temporary-file
I have a simple function that inserts a Python dictionary into DuckDB. How can I insert it into my table without creating a temporary file? def save_to_duckdb(data): # Connect to the Duckdb database conn = duckdb.connect('nodes_log_duck.db') # Get the table name from the "name" field in the dictionary table_name = data...
It seems there is no way to insert a Python dictionary into DuckDB 0.8.1. I use Polars DataFrame for this, and based on a GitHub discussion in the DuckDB repository, someone suggested using fsspec, which works fine. Although using read_json with fsspec creates better data types for DuckDB tables. **fsspec** def save_to...
3
1
76,493,809
2023-6-16
https://stackoverflow.com/questions/76493809/is-there-a-method-to-convert-a-metpy-output-to-numpy-variable
I calculated the wind direction using Metpy. How can I extract the values and use the values as input in another part of my program? In the sample code below, I would like to display the direction as a numpy variable, so I can use it in my program. import metpy.calc as mpcalc import numpy as np # Make some fake data fo...
To convert a metpy result from a wind calculation to a numpy array, simply use the numpy np.array function. import metpy.calc as mpcalc from metpy.units import units import numpy as np np.random.seed(19990503) u = np.random.randint(0, 15, 10)*units("m/s") v = np.random.randint(0, 15, 10)*units("m/s") direction = mpcalc...
2
2
76,492,575
2023-6-16
https://stackoverflow.com/questions/76492575/calculate-the-signed-area-of-piecewise-constant-functions-without-using-integrat
I have defined a step function in Python using the following code. The function takes in an array a and x values, applies some calculations, and returns a step function f. Additionally, I have defined two helper functions rect and psi_j_n. I'd like to calculate the signed area of the product of step_function and psi_j_...
As you said, the only missing thing in your code is the base of the rectangle. You choose it to 0.01, so why not just multiply the result by 0.01? signed_area = 0 for x_values in x: signed_area += 0.01*step_function(x_values, a) * psi_j_n(x_values, -10, 0) signed_area Note that I could have multiplied by 0.01 the fina...
3
2
76,493,293
2023-6-16
https://stackoverflow.com/questions/76493293/iterate-over-numpy-array-to-get-sub-arrays
Given the following numpy array: arr = np.array([0, 1, 2, 3, 4, 5]) what iterable would return sub-arrays of length x from arr? (Given that len(arr) is a multiple of x) x = 2 sub_arrays = [sub_arr for sub_arr in iterable(arr, x)] sub_arrays = [ np.ndarray( [0, 1] ), np.ndarray( [2, 3] ), np.ndarray( [4, 5] ) ] I kn...
To iterate over a numpy array and obtain sub-arrays of a specific length, you can use the numpy.reshape function. By reshaping the array with the desired shape, you can obtain sub-arrays of the specified length. Here's an example: import numpy as np arr = np.array([0, 1, 2, 3, 4, 5]) x = 2 sub_arrays = np.reshape(arr, ...
2
3
76,491,552
2023-6-16
https://stackoverflow.com/questions/76491552/alternative-to-deprecated-makemixeddataframe-in-pandas
Until recently, it was possible to generate sample dataframes in Pandas using functionality of pd.util.testing module: In [22]: import pandas as pd In [23]: pd.util.testing.makeMixedDataFrame() Out[23]: A B C D 0 0.0 0.0 foo1 2009-01-01 1 1.0 1.0 foo2 2009-01-02 2 2.0 0.0 foo3 2009-01-05 3 3.0 1.0 foo4 2009-01-06 4 4.0...
Actually, there is two different testing modules (if we can say so). An official one (which is documented in the API with only four available functions as of 2.0.0+) and a second one (for internal use). So, I guess you're looking for the latter (i.e pandas._testing) : import pandas as pd #pd.__version__ #2.0.2 df = pd....
7
5
76,489,981
2023-6-16
https://stackoverflow.com/questions/76489981/how-to-shift-a-pcolor-plot-along-the-x-axis
I'd like to shift a pcolor plot along the x direction. But I'm not sure how to do it, as it's not as simple as using plot with a vector that specifies the x values With this code: import matplotlib.pyplot as plt import numpy as np np.random.seed(0) Z = np.random.rand(6, 5) tk = list(range(0,10+1)) fig, ax = plt.subplot...
One 'simple' way of achieving that is by just adding 2 empty (NaN) values to the Z: Z = np.insert(Z, 0, np.nan, axis=1) Z = np.insert(Z, 0, np.nan, axis=1) Gives:
2
3
76,485,082
2023-6-15
https://stackoverflow.com/questions/76485082/package-and-find-non-python-files-in-a-python-package
I'm fairly new to python packaging and I'm trying to create a command line tool so that I can send to client to interact with my service in AWS. My goal is to have a command line tool to upload files that are in the folder resources to s3 that will later be used by other services. It's my first time using setuptools fo...
Starting point With the given project structure 📁 <project root>/ ├─📄 pyproject.toml ├─📁 src/ │ └─📁 code/ │ ├─📄 __init__.py │ └─📄 myscript.py ├─📁 resources/ └─📁 artifacts/ └─📄 code1.jar and by specifying [tool.setuptools.packages.find] where = ["src","resources"] include = ["code*"] exclude = [] [tool.setupto...
6
11
76,487,970
2023-6-16
https://stackoverflow.com/questions/76487970/splitting-the-elements-of-a-list-by-some-separator-in-the-same-list
I have an array: array([nan, 'Stressful day', 'Drank coffee:Drank tea', 'Drank tea', 'Ate late:Drank coffee', 'Drank coffee:Drank tea:Worked out', 'Drank tea:Worked out', 'Drank coffee:Drank tea:Stressful day', 'Drank coffee', 'Drank coffee:Drank tea:Stressful day:Worked out', 'Drank coffee:Worked out', 'Ate late:Drank...
Assuming a the input array, you could use str.extractall: out = pd.Series(a).str.extractall('([^:]+)')[0].unique() From the original Series s: out = s.unique().drop_duplicates().str.extractall('([^:]+)')[0].unique() Output: array(['Stressful day', 'Drank coffee', 'Drank tea', 'Ate late', 'Worked out'], dtype=object) ...
3
3
76,486,080
2023-6-15
https://stackoverflow.com/questions/76486080/pandas-read-json-script-that-used-to-work-now-produces-an-error
I have a script that up until recently worked fine, but is now producing an error. import requests import pandas as pd # Set the url to given endpoint url = "https://SomeURL/SomeEndpoint" print('URL set') # Connect to endpoint with credentials and put results in dictionary URLresponse = requests.get(url,auth=("SomeUser...
You can change df = pd.read_json(rawdata) to df = pd.read_json(io.StringIO(rawdata.decode('utf-8'))) You will need to include import io earlier in your file as well.
2
6
76,485,237
2023-6-15
https://stackoverflow.com/questions/76485237/how-to-implement-multi-level-sorting-of-a-list-of-dictionaries-in-python
I am working with a list of dictionaries in Python that represents a set of data records. The data structure looks like this: data = [ {'Name': 'Tom', 'Age': 25, 'Score': 85}, {'Name': 'Alex', 'Age': 30, 'Score': 80}, {'Name': 'Tom', 'Age': 20, 'Score': 90}, {'Name': 'Alex', 'Age': 25, 'Score': 95}, {'Name': 'Tom', 'Ag...
You can use key= parameter in sorted() or .sort(). The key parameter will return 3-item tuple, where the score is negated (to have it in descending order): data.sort(key=lambda d: (d["Name"], d["Age"], -d["Score"])) print(data) Prints: [ {"Name": "Alex", "Age": 25, "Score": 95}, {"Name": "Alex", "Age": 30, "Score": 85...
3
4
76,484,652
2023-6-15
https://stackoverflow.com/questions/76484652/numpy-aggregate-across-multiple-axes
Let's say I have a 3d numpy array.shape of (27,27,27). I want to compress this to (9,9,9) by averaging every 3 elements across every axis simultaneously (e.g. make 3x3x3 pixels into 1x1x1). The objective is to effectively compress by a single integer across all three axes simultaneously (with the assumption that any ar...
Another solution but take advantage of as_strided a = np.arange(27**3).reshape(27, 27, 27) tile_size = (3, 3, 3) tile_shape = tuple(np.array(a.shape) // np.array(tile_size)) tile_strides = tuple(np.array(a.strides) * np.array(tile_size)) + tuple(a.strides) tile_view = np.lib.stride_tricks.as_strided( a, shape=tile_shap...
2
3
76,482,024
2023-6-15
https://stackoverflow.com/questions/76482024/how-to-get-more-detailed-results-sources-with-langchain
I am trying to put together a simple "Q&A with sources" using Langchain and a specific URL as the source data. The URL consists of a single page with quite a lot of information on it. The problem is that RetrievalQAWithSourcesChain is only giving me the entire URL back as the source of the results, which is not very us...
ChatGPT is very flexible, and the more explicit you are better results you can get. This link show the docs for the function you are using. there is a parameter for langchain.prompts.BasePromptTemplate that allows you to give ChatGPT more explicit instructions. It looks like the base prompt template is this Use the fo...
6
3
76,479,504
2023-6-15
https://stackoverflow.com/questions/76479504/poetry-add-using-a-caret-and-a-symbol
I am confused as to what the "@" operator actually does in poetry add pandas@^1.3.0. Both following commands install pandas version 1.5.3 and set the dependency in my pyproject.toml to pandas = "^1.3.0": poetry add pandas@^1.3.0 poetry add pandas^1.3.0 I have no other dependencies listed (aside from Python 3.8). I tho...
The "@" operator in the add command is a delimiter between the package name and the version. If the "@" operator is followed by its required version, e.g. poetry add pendulum@2.0.5 is the same as: poetry add pendulum==2.0.5 If you use caret, e.g.: poetry add requests@^2.13.0 Then you specify a version range. The "@"...
3
3
76,479,392
2023-6-15
https://stackoverflow.com/questions/76479392/identifying-ones-in-each-row-and-creating-a-list-in-python
I have an array A. I am identifying ones in each row except the row number itself and creating a list. For example, in A[0], the ones should be identified for locations 2,3,5 and not 0. I present the current and expected output. import numpy as np A=np.array([[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 1, 0, 1, ...
The numpy approach would be to fill_diagonal, then to use where: np.fill_diagonal(A, 0) row, idx = np.where(A==1) # np.where(A) if only 0/1 Output: (array([ 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11]), array([ 2,...
2
4
76,474,969
2023-6-14
https://stackoverflow.com/questions/76474969/why-does-the-ks-test-give-a-p-value-of-1-if-the-distribution-is-different
Let's take two sets: a = [5,5,5,5,5,4,4,4,4,3,3,3,2,2,1] b = [5,4,3,2,1] We perform the KS-Test using Python: from scipy import stats stats.ks_2samp(b,a) KstestResult(statistic=0.2, pvalue=0.9979360165118678, statistic_location=2, statistic_sign=1) Why is the result a p-value of 0.9979? This means that the distributi...
The observed value of the KS test statistic, namely 0.2, is actually relatively small, considering the distribution of the test statistic for a reasonable null hypothesis; I think this is where the surprise is coming from. As mentioned, the usual KS test assumes there are no ties, so we'll have to compute the p-value o...
3
2
76,477,949
2023-6-14
https://stackoverflow.com/questions/76477949/attribute-error-str-object-has-no-attribute-ignore-local-proxy-with-chrom
I've just started with Selenium and I'm already stuck at the first step: setting up the driver. I keep getting this error: 'str' object has no attribute '_ignore_local_proxy'. Here's the code : from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import requests driver = webdriver.C...
This is due to changes in selenium 4.10.0: https://github.com/SeleniumHQ/selenium/commit/9f5801c82fb3be3d5850707c46c3f8176e3ccd8e Note that the first argument is no longer executable_path, but options. (ChromeDriverManager().install() returns the path to the install location.) Since selenium manager is now included wi...
4
2
76,475,409
2023-6-14
https://stackoverflow.com/questions/76475409/why-does-the-text-widget-event-modified-get-triggered-when-specifically-usin
I've come across a bug that I can't seem to understand. I have a tkinter Text widget that has a bind that triggers on text modification. For some reason this event gets triggered when I use the key combination even though it shouldn't, as it doesn't modify the contents of the Text widget. Here comes the weird part: thi...
The default binding on the text widget for <Control-o> adds a newline. This is from the section bindings in the official Tcl/Tk documentation for the text widget: Control-o opens a new line by inserting a newline character in front of the insertion cursor without moving the insertion cursor. Returning the string "bre...
3
7
76,470,779
2023-6-14
https://stackoverflow.com/questions/76470779/how-to-understand-the-following-fancy-index-behaviour-for-multi-dimensional-arra
We noticed that the mixed usage of fancy indexing and slicing is so confusing and undocumented for multi-dimensional arrays, for example: In [114]: x = np.arange(720).reshape((2,3,4,5,6)) In [115]: x[:,:,:,0,[0,1,2,4,5]].shape Out[115]: (2, 3, 4, 5) In [116]: x[:,:,0,:,[0,1,2,4,5]].shape Out[116]: (5, 2, 3, 5) I have ...
Some additional insight into why there is ambiguity: In the latter case in the question, the 3rd and 5th axes are indexed, and thus disappear from the new array. A new axis (with shape equal to the broadcasting of the indices) has to be added somewhere. If I was numpy, and had to insert a shape (5,) array into the arra...
5
2
76,472,782
2023-6-14
https://stackoverflow.com/questions/76472782/how-to-make-color-bar-ticks-white-and-internal
I am drawing a heatmap and this is my MWE: import matplotlib import seaborn as sns import numpy as np matplotlib.rcParams.update({"figure.dpi": 96}) np.random.seed(7) A = np.random.randint(0,100, size=(20,20)) cmap = matplotlib.cm.get_cmap('viridis').copy() g = sns.heatmap(A, vmin=10, vmax=90, cmap=cmap, cbar_kws={}) #...
add this line before plt.show()... cbar.ax.yaxis.set_ticks_position('both') cbar.ax.tick_params(axis="y",direction="in", color='white') Output plot
3
3
76,472,329
2023-6-14
https://stackoverflow.com/questions/76472329/numpy-vectorization-for-linear-combination-of-numpy-matrices
I have a numpy ndarray of shape (5,4,4) that is a set of 5 matrices 4x4. I would like to multiply that ndarray by a matrix of shape (3,5) and I would like to get a numpy ndarray of shape (3,4,4) where each matrix 4x4 in the result is the linear combination of the 5 4x4 matrices with the coefficients coming from the row...
For these type of operations, np.einsum is perfect. Is the following what you want? B = np.einsum('ij,jkl->ikl', A, X) print(B.shape) # (3,4,4) In words, the string ij,jkl->ikl means: A has indices (dimensions) i and j respectively X has indices j, k and l respectively ->ikl multiply A[i,j]*X[j,k,l] and sum over j
2
4
76,470,472
2023-6-14
https://stackoverflow.com/questions/76470472/guarantee-asyncio-execution-order
I have seen other answers on here stating that asyncio doesn't guarantee execution order, only that the order of the outputs will match that of the inputs. Is there a way I can guarantee the execution order For example, if I have a list of the functions I want to run, will calling create task on each of them before cal...
You could do this with asyncio.Event: async def perform_task(listen_event, push_event): await do_some_paralell_work() await listen_event.wait() await do_some_work_in_order() if push_event: await push-event.set() async def main(): events = [asyncio.Event() for i in range(100)] tasks = [asyncio.Task(events[i], events[i+1...
4
3
76,452,551
2023-6-11
https://stackoverflow.com/questions/76452551/reference-polars-dataframe-height-in-with-columns
Take this example: df = (polars .DataFrame(dict( j=polars.datetime_range(datetime.date(2023, 1, 1), datetime.date(2023, 1, 3), '8h', closed='left', eager=True), )) .with_columns( k=polars.lit(numpy.random.randint(10, 99, 6)), ) ) j k 2023-01-01 00:00:00 47 2023-01-01 08:00:00 22 2023-01-01 16:00:00 82 2023-01-02 00:00:...
You can use .pipe() df = ( pl.datetime_range( datetime.date(2023, 1, 1), datetime.date(2023, 1, 3), "4h", closed="left", eager=True ) .alias("date") .to_frame() ) df.pipe(lambda df: df.with_columns(pl.lit(np.random.randint(10, 99, df.height)).alias("rand")) ) shape: (12, 2) ┌─────────────────────┬──────┐ │ date ┆ ran...
3
3
76,462,548
2023-6-13
https://stackoverflow.com/questions/76462548/in-polars-is-there-a-way-to-remove-character-accents-from-string-columns
I want to remove character accents from a text column, ex. convert Piña to Pina. This is how I would do it in pandas: (names .str.normalize('NFKD') .str.encode('ascii', errors='ignore') .str.decode('utf-8')) Polars has str.decode and str.encode but they don't seem to be what i'm looking for. Thanks!
To expand on @jqurious's comment you can do one of two things: map_elements/lambda like this: from unicodedata import normalize df.with_columns( a=pl.col('a') .map_elements(lambda x: normalize('NFKD',x) .encode('ascii', errors='ignore') .decode('utf-8'))) define function/map_batches like this: from unicodedata imp...
2
3
76,455,828
2023-6-12
https://stackoverflow.com/questions/76455828/what-does-the-torch-gather-and-torch-index-select-do
Basically when to use torch.gather vs torch.index_select I have a scenario where I am using positional embedding (max_len, batch_size, embedding_dim). Here, I would like to select only particular indices from the max_len axis. I want the result to be (new_indices, batch_size, embedding_dim). Searching around I found tw...
I made a post about this (because I also always kept forgetting). The jist is in this image, the full version is here if you're interested.
4
3
76,461,596
2023-6-13
https://stackoverflow.com/questions/76461596/unable-to-use-selenium-webdriver-getting-two-exceptions
I am getting the following error when trying to create an object with Selenium Webdriver. "\selenium\webdriver\common\driver_finder.py", line 42, in get_path path = SeleniumManager().driver_location(options) if path is None else path "\selenium\webdriver\common\selenium_manager.py", line 74, in driver_location browser ...
If the Selenium version you are using is v4.6.0 or above (which I think it is as I see SeleniumManger in the error trace), then you don't really have to set the driver.exe path. Selenium can handle the browser and drivers by itself. So your code can be simplified as below: from selenium import webdriver driver = webdri...
22
63
76,458,771
2023-6-12
https://stackoverflow.com/questions/76458771/minecraft-proxy-in-python-using-socket-only-2-packages-get-sent
I'm trying to code a proxy in python for a Minecraft server that is hosted on my own computer. While I want to intercept and modify the packages that get sent between the client and the server, at first I just want to send all packages through without modifying them. The problem is that only 2 packages get sent: one fr...
Hi will test I founded how to do it here the code. So the in your code is that problem is you need to handle server and client in thread because the two in the same while as recv wait for data and that blocking the client part as two separate thread send server data to client and one send client data to the server. Tha...
3
0
76,423,510
2023-6-7
https://stackoverflow.com/questions/76423510/plotting-of-trendlines-with-certain-conditions-post-significant-pivot-point-dete
I'm trying to get a point which is higher in a range of points, i.e., pivot high, then among a range of pivot high I want to find a significant pivot high. For this I am trying to create a range which is not pre-defined but calculated on every go. It is being calculated by knee plot to identify the best parameters whic...
Here's an example which uses KMeans Clustering and Linear Regression techniques to plot optimized trendlines The number of clusters is hard-coded (and can be easily changed via the variable n_clusters); in a more sophisticated version an optimal number of clusters based on the data itself would be arrived at (e.g., thi...
7
1
76,448,287
2023-6-10
https://stackoverflow.com/questions/76448287/how-can-i-solve-importerror-using-the-trainer-with-pytorch-requires-accele
I'm using the transformers library in Google colab, and When i am using TrainingArguments from transformers library i'm getting Import error with this code: from transformers import TrainingArguments training_args = TrainingArguments( output_dir = "/content/our-model", learning_rate=2e-5, per_device_train_batch_size= 6...
If you're not particular about which transformers and accelerate version to tie to, then do this to use the most up-to-date version in Google Colab: ! pip install -U accelerate ! pip install -U transformers Then the issue you are having with accelerate should auto-resolve itself. Note: Underspecifying pip install -U ...
26
37
76,450,609
2023-6-11
https://stackoverflow.com/questions/76450609/firebase-functions-gen2-python-init-does-not-work
I have only one python installed in my system: 3.10.10. it includes the latest pip: 23.1.2 and I installed the latest module of firebase_functions After I try to init firebase functions in my machine I follow the instructions and when it asks me to install dependencies I get this error: ERROR: To modify pip, please run...
Apparently firebase creates its own python dependency separately from your own python version in your machine. It is stored in the venv folder. To make it work follow the following steps: firebase init Choose functions: Functions: Configure a Cloud Functions directory and its files When it asks: Do you want to install...
3
4
76,465,343
2023-6-13
https://stackoverflow.com/questions/76465343/huggingface-transformers-model-config-reported-this-is-a-deprecated-strategy-to
I am training a sequence-to-sequence model using HuggingFace Transformers' Seq2SeqTrainer. When I execute the training process, it reports the following warning: /path/to/python3.9/site-packages/transformers/generation/utils.py:1219: UserWarning: You have modified the pretrained model configuration to control generati...
Root-Cause This is a warning about using the API in the outdated manner (=unsupported soon). However, as of now, the code is fixing this on its own - hence only a warning not a breaking error. See these lines in the source code. Remedy The transformers library encourages the use of config files. In this case, we need t...
7
4
76,464,175
2023-6-13
https://stackoverflow.com/questions/76464175/setfit-training-with-a-pandas-dataframe
I would like to train a zero shot classifier on an annotated sample dataset. I am following some tutorials but as all use their own data and the same pretarined model, I am trying to confirm: Is this the best approach? Data example: import pandas as pd from datasets import Dataset # Sample feedback data, it will have 8...
I tried to run the example you posted on Google Colab, it took 37 seconds to run the training. Here's you code with some tweak to make it work on Colab: ### Install libraries %%capture !pip install datasets setfit After installing the libraries, run the following code: ### Import dataset import pandas as pd from datas...
4
4
76,468,665
2023-6-13
https://stackoverflow.com/questions/76468665/why-does-object-new-accept-parameters
Besides the obvious asking "again" about __new__ and __init__ in Python - I can ensure, I know what it does. I'll demonstrate some strange and to my opinion undocumented behavior, for which I seek professional help :). Background I'm implementing several features like abstract methods, abstract classes, must-override ...
That is sure a lot of research for a question. But the answer is more simple: objects __new__ and __init__ simply special case the "forgiveness of extra arguments" in a way that it feels natural to create new classes with a custom __init__ method, with no need to fiddle with __new__. So, in short, object new checks if ...
5
3
76,440,090
2023-6-9
https://stackoverflow.com/questions/76440090/pinecone-maxretryerror-and-newconnectionerror
An application I've hosted online throws an error whenever it tries to query a pinecone database that I've set up. Whenever I run the same code (same pinecone environment and API key) on my local device, the queries go through just fine. Any ideas on what could be causing this issue? urllib3.exceptions.MaxRetryError: H...
I faced the exact same thing. I just fixed it, also my first SO answer ever. Using Python 3.10, pinecone-client you have to pass their proxy server during Pinecone init. Like this from pinecone.core.client.configuration import Configuration as OpenApiConfiguration openapi_config = OpenApiConfiguration.get_default_copy(...
2
4
76,468,978
2023-6-13
https://stackoverflow.com/questions/76468978/problem-using-tweepy-the-error-403-forbidden-apeared-without-making-any-changes
Hello there thanks for reading my post. I was using this same code yesterday and it was okay but today stoped working and i got this error: raise Forbidden(response) tweepy.errors.Forbidden: 403 Forbidden When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer...
With the "free" plan of the Twitter API you can no longer lookup tweets, GET /2/tweets/:id is only available in the "basic" plan, see: https://developer.twitter.com/en/portal/products/free
3
2
76,459,034
2023-6-12
https://stackoverflow.com/questions/76459034/how-to-load-a-fine-tuned-peft-lora-model-based-on-llama-with-huggingface-transfo
I've followed this tutorial (colab notebook) in order to finetune my model. Trying to load my locally saved model model = AutoModelForCausalLM.from_pretrained("finetuned_model") yields Killed. Trying to load model from hub: yields import torch from peft import PeftModel, PeftConfig from transformers import AutoModelF...
To load a fine-tuned peft/lora model, take a look at the guanco example, https://stackoverflow.com/a/76372390/610569 import torch from peft import PeftModel from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer model_name = "decapoda-r...
19
15
76,447,153
2023-6-10
https://stackoverflow.com/questions/76447153/how-to-use-a-llama-model-with-langchain-it-gives-an-error-pipeline-cannot-infe
finetuned a model (https://huggingface.co/decapoda-research/llama-7b-hf) using peft and lora and saved as https://huggingface.co/lucas0/empath-llama-7b. Now im getting Pipeline cannot infer suitable model classes from when trying to use it along with with langchain and chroma vectordb: from langchain.embeddings import ...
Before using the langchain API to the huggingface model, you should try to load the model in Huggingface: from transformers import AutoModel model = AutoModel.from_pretrained('lucas0/empath-llama-7b') And that'll throw some errors: --------------------------------------------------------------------------- OSError Tra...
2
14
76,469,330
2023-6-13
https://stackoverflow.com/questions/76469330/using-cppyy-with-rvalue-pointers-and-maps
I would love to love cppyy. However the codebase I am using has heavy use of std.unique_ptr, rvalue pointers, and templates. I am confused about how to translate these into something I can call from python. For instance, I am stuck on how to create an std::map from classes. I understand that I can make an std::map by d...
You can insert Key/Value pairs using .emplace and you can lookup a value from a Key using .at. Example: #!/bin/python import cppyy import cppyy.gbl as Cpp # the class with an added operator<< overload to support printing: cppyy.cppdef(r"""\ template<typename T> class MyClass { public: MyClass(T t) : m_data(t) {} T m_da...
3
4
76,468,406
2023-6-13
https://stackoverflow.com/questions/76468406/create-many-confusion-like-matrices-concatenated-in-python
I have the following pandas dataframe import pandas as pd df = pd.DataFrame({'cl1': ['A','A','A','A', 'A','A','A','A', 'D','D','D','D', 'D','D','D','D'], 'cl2': ['C','C','C','C', 'B','B','B','B', 'C','C','C','C', 'B','B','B','B'], 'p1p2': ['00','01','10','11', '00','01','10','11', '00','01','10','11', '00','01','10','1...
Assuming that p1p2 only contains values 00, 01, 10, or 11, it is easy to use pivot table to get something like this: d = df.copy() d['p1'] = d['p1p2'].str[0] d['p2'] = d['p1p2'].str[1] counts = d.pivot_table(values = 'val', columns = ['cl1', 'p1'], index = ['cl2', 'p2']) counts # cl1 A D # p1 0 1 0 1 # cl2 p2 # B 0 10 ...
2
2
76,450,952
2023-6-11
https://stackoverflow.com/questions/76450952/two-conditional-clause-count-in-pandas
I have a df which looks like this: api_spec_id type_of_change label 213 Breaking NaN 213 Breaking major 213 Non-Breaking patch 345 Non-Breaking NaN 345 Non-Breaking patch 345 Non-Breaking patch 678 Breaking NaN 678 Breaking minor 678 Breaking major 123 Breaking NaN 123 Breaking NaN I want to calculate the unique numbe...
A possible solution : from functools import partial grp = df.groupby("api_spec_id") def detect(g, how, change): if how == "all": return g["type_of_change"].eq(change).all() elif how == "any": return g["type_of_change"].eq(change).any() def get_id(df): return df["api_spec_id"].unique().tolist() v1 = grp.filter(partial(d...
2
3
76,466,400
2023-6-13
https://stackoverflow.com/questions/76466400/why-are-docstrings-and-block-comments-suddenly-the-same-color-as-a-single-line-c
My Python docstrings & block comments in Visual Studio Code always used to be a different color to the single line comment. They use to be: docstrings & block comments: orange single line comments: green I did a reinstall of Visual Studio Code this morning and the block comments and docstrings are now the same color ...
According to the Release notes for 1.79 (the pull request section), they changed the docstring comment colors with this pull request. You can set your own colors for this using the solution in the other answer.
5
5
76,466,694
2023-6-13
https://stackoverflow.com/questions/76466694/pandas-chaining-and-the-use-of-inplace-parameter
For pandas DataFrames in python, multiple member methods have an inplace parameter which purportedly allow you to NOT create a copy of the object, but rather to directly modify the original object*. [*Edited to add: however, this proves to not be the case as pointed out by @juanpa.arrivillaga. inplace=True DOES copy da...
Let's try it. import pandas as pd import numpy as np df = pd.DataFrame({'value' : [2, 2, 1, 1, 3, 4, 5, np.NaN]}) df.sort_values('value').drop_duplicates().dropna(inplace=True) Expect: value 2 1.0 0 2.0 4 3.0 5 4.0 6 5.0 Result: value 0 2.0 1 2.0 2 1.0 3 1.0 4 3.0 5 4.0 6 5.0 7 NaN Answer: No, inplace=True at the ...
3
3
76,466,162
2023-6-13
https://stackoverflow.com/questions/76466162/python-pass-by-object-reference-in-memory-using-id
I am trying to test out some code in reference to Robert Heaton's article explaining the difference between the different concepts of passing parameters into functions. Why are list and myList stored in the same location in memory when, according to Heaton, they should be two completely separate variables. Here is what...
You have to consider the entire paragraph. The article is not saying it should be 2 different objects. There is one list, but separate variables pointing to it. Consider the following (list variable changed to l because built-ins shouldn't be used for variable names.): def append(l): print(f"append's list: {id(l)}") l....
3
3
76,464,908
2023-6-13
https://stackoverflow.com/questions/76464908/fillna-by-avoiding-row-wise-operation-in-pandas
I have a data frame in which there is a column containing several NaN values. The dataframe looks like this: col_1 col_2 2022-10-31 99.094 102.498 2022-11-30 99.001 101.880 2022-12-31 NaN 108.498 2023-01-31 NaN 100.500 I want to fill those NaN based on the simple calculation below: desired_val = (previous value in co...
You can think of your operation and see that you multiply by x in one row and divide by x in the next row. Thus you can simplify the result to: col1_value = (last_valid_col1_value * current_col2_value) / col2_value_at_last_valid_col1_position Which can be translated as: # is the row a NA? m1 = df['col_1'].isna() # is ...
3
4
76,459,471
2023-6-12
https://stackoverflow.com/questions/76459471/cant-create-tables-in-test-database-while-testing-with-pytest-postgresql
I'm trying to write a pytest for models and database in Postgres using fixtures and pytest_postgresql. Running test gives: FAILED tests/test_model_with_test_db.py::test_authors - sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "authors" does not exist Why it doesn't created all tables with m...
Figured out myself. Modified db_session fixture like following: @pytest.fixture(scope="session") def db_session(test_db): pg_host = test_db.host pg_port = test_db.port pg_user = test_db.user pg_password = test_db.password pg_db = test_db.dbname with DatabaseJanitor(pg_user, pg_host, pg_port, pg_db, test_db.version, pg_...
2
3
76,456,495
2023-6-12
https://stackoverflow.com/questions/76456495/what-function-would-best-fit-the-data-i-have-from-a-galaxy
I have the following set of data: surface_brightnesses_o2 = [12076.0616666451, 11850.730704516911, 10265.598145816548, 9120.859898168235, 7070.26133100111, 5636.138833975608, 3968.1608109082404, 2923.2839406153525, 1963.9315683870766, 1417.3534005331746, 953.9023540784231, 705.6331341427699, 494.19332394388607, 368.683...
Use a different model, and when you do, perform a log-fit. You've applied your log on x when I believe you should apply it on y during fit. There's an infinite number of models to choose from; which are scientifically valid is up to you to determine. One that has a loosely reasonable fit is a generalized Gaussian with ...
3
2
76,460,679
2023-6-12
https://stackoverflow.com/questions/76460679/read-csv-file-with-columns-of-varying-length-as-dictionary-in-python
How do I read in a .csv file in Python with columns of varying lengths? I want to create a dictionary from the .csv file, with the .csv columns as lists of dictionary values. I've figured out how to write the dictionary to a .csv file, but I need help reading in that same file. import csv import itertools path = 'C:/Us...
To read the CSV file back I recommend to use csv.DictReader: import csv import itertools path = '<PATH>' out_dict = { "Class1": ["A", "B"], "Class2": ["C", "D", "E", "F", "G", "H", "I"], "Class3": ["J", "K", "L", "M", "N"], } # write dictionary to csv with open(path, 'wt', newline='') as csv_file: writer = csv.writer(c...
2
3
76,459,485
2023-6-12
https://stackoverflow.com/questions/76459485/replace-string-with-other-with-two-possible-patterns-in-python
I would like to replace everything in String untill "err" or "error" appear for empty string. So: "abc err efg" -> "efg", "abc error efg" -> "efg. How to do it with one pattern using re.sub? I tried this: lines_input = ['some line err hello', 'some line error hello'] rep = {r'^.*?err': '', r'^.*?error': ''} dict((re.es...
You don't need multiple regular expressions. The two patterns are the same except for the optional or at the end of error, so use an optional group. line = re.sub(r'.*err(or)?\s*', '', line)
2
5
76,450,603
2023-6-11
https://stackoverflow.com/questions/76450603/using-loop-run-in-executor-to-call-sync-functions-from-async-ones
I have 3 functions: func_1, func_2, and func_3. I would like to run these asynchronously, so that I do not have to wait for func_1 to finish before func_2 starts executing. The problem is, that the definition of func_1 for example looks something like this: async def func_1(a, b): x = some_sync_func(a) y = some_other_s...
Almost right, but since you are awaiting eagerly at each function call, the next line of code in each case (after the await) will only be called when the line with await finishes execution. However if you call func_1 in parallel from some other place, two instances of func_1 will work in parallel. (I am almost sure tha...
2
7
76,456,918
2023-6-12
https://stackoverflow.com/questions/76456918/typehint-method-as-returning-return-type-of-other-method-in-python
I have a base class: from abc import abstractmethod class Thing: @abstractmethod def _process(self): ... def process(self, x: int): self.pre_process(x) return self._process() How do I typehint process as returning the return type of _process? My first thought was something like: from abc import abstractmethod from typ...
You can make Thing inherit Generic[T]. from typing import TypeVar from typing import Generic from abc import abstractmethod T = TypeVar("T") class Thing(Generic[T]): @abstractmethod def _process(self) -> T: ... def process(self, x: int) -> T: return self._process() > mypy /tmp/t.py Success: no issues found in 1 source...
2
3
76,454,711
2023-6-12
https://stackoverflow.com/questions/76454711/display-only-existing-x-axis-values-for-each-facet-in-a-multi-faceted-bar-plot-u
For the following multifacet plot df = pd.DataFrame({ 'row': [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1], 'col': [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1 ], 'x_value': [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4], 'count': [1,7,4,0,0,3,1,3,1,9,2,2,0,0,3,4] }) df = df.query('count != 0 ') fig = px.bar(df, x='x_value', y='count', facet_col='col', f...
To get what you are looking for, you need to customize each x-axis (and y-axis, if required) to include matches=None. This will stop trying to match the columns across each of the subplots. So, replace the line... fig.for_each_xaxis(lambda xaxis: xaxis.update(showticklabels=True, title_font = dict(size =20), type = 'ca...
2
3
76,452,656
2023-6-11
https://stackoverflow.com/questions/76452656/unpacking-and-assignment-oddity-between-3d-list-and-numpy-array
I create a normal python list a = [[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]]] Now I want to shift the first row of each 2x2 array to the previous 2x2 array, wrapping the first back to the last. I use the following unpacking assignment statement: a[0][0],a[1][0],a[2][0] = a[1][0],a[2][0],a[0][0] I get the following...
The way I reason this out is that since b is a (3,2,2) array each of b[1,0],b[2,0],b[0,0] is a view of b. That is, 3 (2,) arrays, but each uses a different part of the b data_buffer. During the assignment, b[0,0] is set to the values at b[1,0]. By the time it assigns to b[2,0], B[0,0] now has the new values, [5,6]. I'...
2
3
76,443,511
2023-6-9
https://stackoverflow.com/questions/76443511/loss-of-data-in-short-time-fourier-transform-and-inverse-need-help-improving-au
I am currently developing my own audio library and have implemented the Short-Time Fourier Transform (STFT) and its inverse as part of the signal processing pipeline. However, I have noticed that the STFT and its inverse operations seem to be causing a significant loss of data, resulting in very poor audio quality. Fir...
Like Christoph Rackwitz said, the problem with this STFT implementation is that the blocks are non-overlapping. For invertibility, you want that each block has 50% overlap with the next block. Here is a possible simple implementation for extracting and overlap-adding the blocks: # Copyright 2023 Google LLC. # SPDX-Lice...
2
3
76,450,635
2023-6-11
https://stackoverflow.com/questions/76450635/how-to-hash-a-ring-buffer-of-integers
I am using Python. I have some lists containing integers, but they are actually ring buffers. The following are rules by examples: We do not add new elements or modify any elements. These rings are immutable. No repetitive elements in a ring. If two lists have different lengths, they are not the same ring. Between ...
It's faster and simpler to just compute a normalized form at construction: class Ring: def __init__(self, ids:List[int]) -> None: self.ids = ids i = ids.index(min(ids)) self.normed = min( ids[i:] + ids[:i], ids[i::-1] + ids[:i:-1] ) def __eq__(self, other: 'Ring') -> bool: return self.normed == other.normed Output wit...
2
2
76,446,124
2023-6-10
https://stackoverflow.com/questions/76446124/best-line-detector-algorithm-for-a-specific-content-bounding-box-measurement
The purpose of the algorithm is to auto align-sheet music pages based on staves/systems content. The algorithm need to detect the bounding box to allow to easily compute the left/right and top/bottom margin for the wholes pages. Current algorithm like morphological operations in openCV (using cv2.HoughLinesP for examp...
You already looked into "staff-line removers". For this task, you need a part of that: the part that identifies staff lines. Assuming the scan is upright, not rotated by a few degrees, that is usually done with morphology operations that use a "line" shaped kernel. To also drop the short thick vertical bars on the left...
3
5
76,444,601
2023-6-10
https://stackoverflow.com/questions/76444601/playwright-get-by-role-using-nth-selector
I'm writing a Playwright test in Python. I have a table that I want to grab every row from to perform some actions within a for loop but I want to skip the first row. I am able to grab every row within a table by doing something as simple as the following: table = page.get_by_role("row").all() for row in table: print(r...
Rather than manipulating the selector, you simply start the for loop at the second element, like this: table = page.get_by_role("row").all() # Using slice notation for row in table[1:]: print(row)
2
3
76,446,783
2023-6-10
https://stackoverflow.com/questions/76446783/question-about-fastapis-dependency-injection-and-its-reusability
from fastapi import Depends, FastAPI class MyDependency: def __init__(self): # Perform initialization logic here pass def some_method(self): # Perform some operation pass def get_dependency(): # Create and return an instance of the dependency return MyDependency() app = FastAPI() @app.get("/example") def example(depend...
Yes, each request will receive a new instance. If you don't want that to happen, use a cache decorator, such as the built-in lru_cache in functools: - it's just a regular function, so any decorators will still be invoked (since they replace the original function with a new one which wraps the old one): from functools i...
4
4
76,444,617
2023-6-10
https://stackoverflow.com/questions/76444617/cast-pl-date-to-unix-epoch
Trying to convert a pl.Date column to UNIX epoch as is, without any timezone offset: import datetime import polars as pl df = pl.DataFrame( {'Date': [datetime.datetime.now().date()]} ) Correct time (00:00:00) when converted to Datetime: df.with_columns( pl.col("Date").cast(pl.Datetime) ) ┌─────────────────────┐ │ Dat...
Note that vanilla Python datetime defaults to local time if you don't set a time zone (naive datetime). In contrast, polars assumes naive datetime to resemble UTC (as pandas does as well). Keep it consistent by setting the time zone, e.g. UTC: from datetime import datetime, timezone import polars as pl df = pl.DataFram...
2
3
76,444,501
2023-6-10
https://stackoverflow.com/questions/76444501/typeerror-init-got-multiple-values-for-argument-options
What could be the reason for this error being thrown: Traceback (most recent call last): File "/Users/me/sc/sc.py", line 30, in <module> driver = Chrome(ChromeDriverManager().install(), options=chrome_options) TypeError: __init__() got multiple values for argument 'options' During handling of the above exception, anoth...
This is due to changes in selenium 4.10.0: https://github.com/SeleniumHQ/selenium/commit/9f5801c82fb3be3d5850707c46c3f8176e3ccd8e Note that the first argument is no longer executable_path, but options. (That's why it complains that you're passing it in twice.) If you want to pass in an executable_path, you'll have to ...
2
4
76,434,535
2023-6-8
https://stackoverflow.com/questions/76434535/attributeerror-super-object-has-no-attribute-init
I was making a personal assistant. I got an error in starting code: import pyttsx3 engine = pyttsx3.init() engine.say('How are you today?') engine.runAndWait() Error: /usr/local/lib/python3.11/site-packages/pyttsx3/drivers/nsss.py:12: ObjCSuperWarning: Objective-C subclass uses super(), but super is not objc.super cla...
this turns out to be a little tricky. and this is a workaround! hope works for you. Under the hood, this module pyttsx3 uses PyObjC as a bridge between Python and Objective-C. Step 1: Check that pyobjc is installed(pip show pyobjc), if not install as pip install pyobjc. Step 2: open this file /usr/local/lib/python3.11...
7
28
76,443,923
2023-6-9
https://stackoverflow.com/questions/76443923/create-data-frame-with-month-start-and-end-in-python
I want to create a pandas dataframe from a given start and end date: import pandas as pd from pandas.tseries.offsets import MonthEnd start_date = "2020-05-17" end_date = "2020-07-23" For each row in this dataframe, I should have the start day and end day of the month, so the expected output is: start end month year 20...
You can use pd.date_range and pd.to_datetime: start = pd.to_datetime([start_date] + pd.date_range(start_date, end_date, freq='MS').tolist()) end = pd.to_datetime(pd.date_range(start_date, end_date, freq='M').tolist() + [end_date]) month = start.strftime('%B') year = start.year df = pd.DataFrame({'start': start, 'end': ...
3
2
76,443,854
2023-6-9
https://stackoverflow.com/questions/76443854/how-to-find-a-number-of-occurrences-of-every-element-of-a-numpy-array
Given an array of integers, I would like to obtain an array of the same size where every value is a number of occurrences of a corresponding element in the original array. For example given the following array: a = np.array([1, 1, 4, 10, 5, 3, 5, 5, 8, 9]) This should be the result: array([2, 2, 1, 1, 3, 1, 3, 3, 1, 1...
You could use np.unique and use the parameter return_inverse and return_counts. Use return_inverse to index return_counts to get desired results. return_inverse bool, optional If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar. return_counts bo...
4
6
76,442,097
2023-6-9
https://stackoverflow.com/questions/76442097/how-to-assign-a-color-to-a-specific-value-on-a-heatmap
I am making a heatmap in seaborn. I am using 'viridis', but I modify it slightly so some of the values get particular colors. In my MWE, .set_over is used to set the values above 90 to 'black', and .set_under is used to set the values below 10 to 'white'. I also mask out part of the heatmap. This all works fine. How ca...
Pulling from this answer, here is a solution that uses a mask rather than a custom colorbar: import matplotlib import seaborn as sns import numpy as np from matplotlib.colors import ListedColormap np.random.seed(7) A = np.random.randint(0,100, size=(20,20)) mask_array = np.zeros((20, 20), dtype=bool) mask_array[:, :5] ...
3
2
76,432,343
2023-6-8
https://stackoverflow.com/questions/76432343/auto-switching-python-virtual-environments-in-visual-studio-code-per-directory-w
I am working on a project in VSCode that has multiple directories, each of which requires a different Python virtual environment. My virtual environments are located in the ~/.virtualenvs directory and my workspace is structured like this: ~/.virtualenvs/ │ ├── venv_A/ │ └── venv_B/ my_workspace/ │ ├── project_A/ │ └──...
The easiest way is to open project_A and project_B as workspaces respectively, and then select an interpreter for the workspace, vscode will remember your choice, and will still use the previously selected interpreter when it is opened next time. Another approach is to use Multi-root Workspaces Open a new window and u...
4
2
76,434,311
2023-6-8
https://stackoverflow.com/questions/76434311/how-to-get-the-logits-of-the-model-with-a-text-classification-pipeline-from-hugg
I need to use pipeline in order to get the tokenization and inference from the distilbert-base-uncased-finetuned-sst-2-english model over my dataset. My data is a list of sentences, for recreation purposes we can assume it is: texts = ["this is the first sentence", "of my data.", "In fact, thats not true,", "but we are...
When you use the default pipeline, the postprocess function will usually take the softmax, e.g. from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased-finetuned-sst-2-english') model = AutoModelForSequenceClassification.from_pretrain...
8
10
76,435,305
2023-6-8
https://stackoverflow.com/questions/76435305/convert-python-list-of-dicts-to-mapping-of-key-to-rest-of-dict
Let's say I have the following list: l = [ {"a": 10, "b": 100, "c": 100}, {"a": 20, "b": 100, "c": 100}, {"a": 30, "b": 100, "c": 100}, ] I know "a" is unique in each item: assert len({x["a"] for x in l}) == len(l) I want to generate a mapping of the "a" value to the rest of each item so my end result is the followin...
Maybe dict.pop is what you want? out = {d.pop('a'): d for d in l} print(out) Prints: {10: {'b': 100, 'c': 100}, 20: {'b': 100, 'c': 100}, 30: {'b': 100, 'c': 100}}
2
4
76,435,071
2023-6-8
https://stackoverflow.com/questions/76435071/how-can-vectorization-be-used-for-row-dependent-functions-in-pandas
and sorry if this has been asked before (I could only find approaches that worked on previous rows and not the rest of the dataframe.) I'm currently trying to switch out my iterative approach for a problem to a more Pandas (and time) friendly version. The problem is as follows: I have two columns, "A" and "B" that are ...
Started writing this before you added your code -- but figure it might still be helpful. I was able to write 1 function that, based on the logic, returns a string of who wins based on a row index and given DataFrame with minimal (internal) iteration: # Sample data import pandas as pd data = {"Time":[1,2,3,4,5,6],"A":[2...
3
2
76,434,987
2023-6-8
https://stackoverflow.com/questions/76434987/why-does-this-simple-python-https-request-throw-an-ssl-error-even-when-given-an
I've recently started an internship at a company with pretty strict IT policies. I'm the only developer at the company and it is clear that I'm running into problems that most likely don't affect anyone else here, which makes them difficult to resolve. IT has inserted their own SSL certificate at the proxy level (proba...
The cert option of the request is meant to be for the client certificate authentication. What I believe you are trying to do is to add a trusted CA for the request. For this use the verify option. response = requests.get(url, verify = "/temp/certs/certificate.pem") You can find the difference in the documentation.
3
6