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
77,643,432
2023-12-12
https://stackoverflow.com/questions/77643432/why-is-pd-get-dummies-returning-boolean-values-instead-of-the-binaries-of-0-1
I don't know why my One-Hot encoding code; "pd.get_dummies" is returning Boolean values instead of the binaries of 0 1 df = pd.get_dummies(df) after writing the following line of code; df = pd.get_dummies(df) and also tried; df = pd.get_dummies(df, columns=['column_a', 'column_b', 'column_c']) the returning values of b...
By default pd.get_dummies return Boolean, try : df = pd.get_dummies(df, dtype=int)
3
12
77,640,545
2023-12-11
https://stackoverflow.com/questions/77640545/how-to-retrieve-the-line-number-where-a-c-function-is-called-from-python-using
I'm trying to make a C++ logger class for embedded python script with pybind11. How can I retrieve the line number where a C++ function is called from python? I have something like this in C++: class PythonLogger { public: PythonLogger(const std::string& filename) { /* opens log file */ } ~PythonLogger() { /* closes lo...
One possibility is to inspect the Python call stack from the C++ function and grab the info about the caller from there. This approach might involve a noticeable overhead -- I haven't measured it, but it would be a good idea before you use this in production. You could do this using the standard inspect module, for exa...
3
3
77,639,642
2023-12-11
https://stackoverflow.com/questions/77639642/the-attempt-to-terminate-a-function-in-a-thread-using-signals-fails-in-pyqt6
I have a time-consuming thread operation, but it cannot emit progress during the processing. So, I use another thread to simulate its progress. When the time-consuming operation is completed, it emits an end signal and simultaneously signals the end of the simulation process. However, the actual function operation in t...
The main problem with the example is that it uses blocking loops within each thread, which will prevent immediate processing of thread-local events. When a signal is emitted across threads, an event will be posted to the event-loop of the receiving thread. But if a blocking loop is being executed within the receiving w...
3
2
77,641,087
2023-12-11
https://stackoverflow.com/questions/77641087/fft-values-computed-using-python-and-matlab-dont-match
I have a super simple test code to compute FFT in MATLAB, which I am trying to convert to Python but the computed values do not match. MATLAB Code: rect=zeros(100,1); ffrect=zeros(100,1); for j=45:55 rect(j,1)=1; end frect=fft(rect); Python Code import numpy as np import matplotlib.pyplot as plt from scipy.fft import ...
scipy.fft.fft computes the FFT over the last axis unless you specify otherwise with the axis parameter. In the Python version, your input array is of shape (100, 1), so you're computing 100 different 1-point FFTs. To compute a single 100-point FFT, either reshape rect to have its 100 entries in the last dimension (for...
2
3
77,634,955
2023-12-10
https://stackoverflow.com/questions/77634955/why-is-the-simpler-loop-slower
Called with n = 10**8, the simple loop is consistently significantly slower for me than the complex one, and I don't see why: def simple(n): while n: n -= 1 def complex(n): while True: if not n: break n -= 1 Some times in seconds: simple 4.340795516967773 complex 3.6490490436553955 simple 4.374553918838501 complex 3.6...
I checked the source code of the bytecode (python 3.11.6) and found that in the decompiled bytecode, it seems that only JUMP_BACKWARD will execute a warmup function, which will trigger specialization in python 3.11 when executed enough times: PyObject* _Py_HOT_FUNCTION _PyEval_EvalFrameDefault(PyThreadState *tstate, _P...
63
66
77,639,326
2023-12-11
https://stackoverflow.com/questions/77639326/nested-dictionary-with-class-and-instance-attributes
I store some configuration details across several class attributes and one main class which references each of them. E.g. class A: a = 1 class B: b = 2 def __init__(self): self.a_ = A() x = B() I would like to display all class (and instance) attributes in a dictionary, i.e. {'b': 2, 'a_': {'a': 1}} I understood __di...
You can implement a Serializable class that both A and B inherit from that has a custom method to_dict() to achieve your desired output: class Serializable: def to_dict(self): d = {} for key, value in self.__class__.__dict__.items(): if not key.startswith('__') and not callable(value): d[key] = value for key, value in ...
3
2
77,637,539
2023-12-11
https://stackoverflow.com/questions/77637539/why-beautifulsoup-cant-find-this-supposed-to-be-xbrl-related-ix-tag
It turns out that the tag name should be: "ix:nonfraction" This does not work. No "xi" tag is found. from bs4 import BeautifulSoup text = """ <td style="BORDER-BOTTOM:0.75pt solid #7f7f7f;white-space:nowrap;vertical-align:bottom;text-align:right;">$ <ix:nonfraction name="ecd:AveragePrice" contextref="P01_01_2022To12_31...
The issue here arises from how BeautifulSoup handles namespaced tags like <ix:nonfraction>. With the lxml parser, namespaced tags might not be correctly parsed or recognized. In the XML you provided, ix is the namespace, and nonfraction is the local name of the element. In XML, a namespace is a method to avoid name con...
2
1
77,634,598
2023-12-10
https://stackoverflow.com/questions/77634598/how-to-get-file-type-from-complex-image-url-in-python
I want to get image file extensions from image URLs like below: from os.path import splitext image = ['ai','bmp','gif','ico','jpeg','jpg','png','ps','psd','svg','tif','tiff','webp'] def splitext_(path, extensions): for ext in extensions: if path.endswith(ext): return path[:-len(ext)], path[-len(ext):] return splitext(p...
Edit: here how to manage multiple extension. For this, it's better to use the @Andrej Kesely answer for parsing the url. Working on the url as string only will lead to have the host split and it's harder to manage (you would go to rewrite urlparse). from urllib.parse import urlparse val = "https://dkstatics-public.digi...
2
2
77,631,313
2023-12-9
https://stackoverflow.com/questions/77631313/python-root-logger-handlers-do-not-get-named-loggers-records
I have the following setup: root logger to log everywhere my programm adds a new handler after startup via an callback (for example a database) with CallbackHandler named logger in my modules do not call into the root-logger Online Python Compiler <- you need to have main.py selected to Run main.py in there main.py i...
How to fix: add the following line to your LOGGING_CONFIG dict: "disable_existing_loggers" : False, The problem is that the child logger is created before the logging gets its configuration and the default behaviour when configuring the logging is to disable existing loggers. Link to the docs (it's the last item in t...
2
1
77,632,067
2023-12-9
https://stackoverflow.com/questions/77632067/generate-html-page-with-specific-tags-from-another-page-using-beautifulsoup
I'm exploring BeautifulSoup and aiming to retain only specific tags in an HTML file to create a new one. I can successfully achieve this with the following program. However, I believe there might be a more suitable and natural approach without the need to manually append the strings. from bs4 import BeautifulSoup #soup...
You can have a list of desired tags, iterate through them, and use Beautiful Soup's append method to selectively include corresponding elements in the new HTML structure. from bs4 import BeautifulSoup with open('Test.html', 'r') as f: contents = f.read() soup = BeautifulSoup(contents, 'html.parser') new_html = Beautifu...
4
7
77,630,264
2023-12-9
https://stackoverflow.com/questions/77630264/could-not-install-packages-due-to-an-oserror-while-trying-to-download-python-p
I've been using python v3.12 for the past month without any problem, but now out of nowhere i'm unable to download any packages at all. It gives this long list of warnings and an error. > WARNING: Certificate did not match expected hostname: files.pythonhosted.org. Certificate: {'subject': ((('commonName', 'r.shared-31...
I encountered a similar issue and found that an entry in the hosts file for pythonhosted.org was causing the 'Misdirected Request' error. Here's how I resolved it: Open the Hosts File: On Windows: Run Notepad as an administrator, then open C:\Windows\System32\drivers\etc\hosts. On macOS/Linux: Open Terminal and use s...
4
8
77,629,866
2023-12-9
https://stackoverflow.com/questions/77629866/playwright-page-pdf-only-gets-one-page
I have been trying to convert html to pdf. I have tried a lot of tools but none of them work. Now I am using playwright, it is converting the Page to PDF but it only gets the first screen view. From that page the content from right is trimmed. import os import time import pathlib from playwright.sync_api import sync_pl...
Here's a somewhat dirty solution that worked on my end. The sleep and scroll isn't great and can probably be improved, but I'll leave this as a starter and see if I have time to tighten it up later (feel free to do the same). from playwright.sync_api import sync_playwright # 1.37.0 from time import sleep with open("ind...
3
3
77,625,508
2023-12-8
https://stackoverflow.com/questions/77625508/how-to-activate-verbosity-in-langchain
I'm using Langchain 0.0.345. I cannot get a verbose output of what's going on under the hood using the LCEL approach to chain building. I have this code: from langchain.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTemplate from langchain.schema.output_parser import StrOutputParser from langchai...
You can add a callback handler to the invoke method's configuration. Like this: from langchain.callbacks.tracers import ConsoleCallbackHandler # ...your code chain.invoke({"topic": "ice cream"}, config={'callbacks': [ConsoleCallbackHandler()]}) Code with change incorporated: from langchain.chat_models import ChatOpenA...
10
13
77,629,234
2023-12-8
https://stackoverflow.com/questions/77629234/how-to-get-second-pandas-dataframe-showing-net-trade-based-on-first-pandas-dataf
I have a pandas dataframe df1 as shown below: It shows exports volume from A to B, B to A and A to C in three rows. Trade is possible in both directions. df1.to_dict() returns {'Country1': {0: 'A', 1: 'B', 2: 'A'}, 'Country2': {0: 'B', 1: 'A', 2: 'C'}, 'Value': {0: 3, 1: 5, 2: 3}} I want a second dataframe df2 based...
You could swap the names, merge and filter: val = (df[['Country1', 'Country2']] .merge(df.rename(columns={'Country1': 'Country2', 'Country2': 'Country1'}), how='left')['Value'] .rsub(df['Value'], fill_value=0) ) out = (df.assign(**{'Net Value': val}) .query('`Net Value` >= 0') .drop(columns='Value') ) Output: Country...
2
2
77,628,451
2023-12-8
https://stackoverflow.com/questions/77628451/cannot-unify-float64-and-arrayfloat64-1d-c-for-mv2-3-defined-at-c
I tried to solve this problem by changing a lot of variables but nothing it's working. Here is my code: import numpy as np import matplotlib.pyplot as plt import math as mt from numba import njit N=1000 J=1 h=0.5 plt.rcParams['figure.dpi']=100 plt.xlabel('T', fontsize=14) ns=100000000 s=np.empty([N,0]) for i in range(N...
Here is fixed version of the code that compiles with numba: import math as mt import matplotlib.pyplot as plt import numpy as np from numba import njit N = 1000 J = 1 h = 0.5 plt.rcParams["figure.dpi"] = 100 plt.xlabel("T", fontsize=14) ns = 100000000 s = np.empty(N) # <-- don't use np.empty([N, 0]) for i in range(N): ...
2
2
77,626,069
2023-12-8
https://stackoverflow.com/questions/77626069/how-to-query-a-jsonb-column-that-has-deeply-nested-objects-in-python-fastapi-sq
In a PostgreSQL table "private_notion", I have a JSONB column "record_map" that may or may not contain nested objects, E.g. { "blocks": { "7a9abf0d-a066-4466-a565-4e6d7a960a37": { "name": "block1", "value": 1, "child": { "7a9abf0d-a066-4466-a565-4e6d7a960a37": { "name": "block2", "value": 2, "child": { "7a9abf0d-a066-4...
This extracts entire objects at any level that have your target uuid-based key in them: demo at db<>fiddle SELECT jsonb_path_query(record_map, 'strict $.**?(@.keyvalue().key==$target_id)', jsonb_build_object('target_id', '7a9abf0d-a066-4466-a565-4e6d7a960a37')) FROM private_notion WHERE site_id = '45bf37be-ca0a-45eb-83...
2
1
77,628,661
2023-12-8
https://stackoverflow.com/questions/77628661/how-to-print-out-another-column-after-a-value-counts-in-dataframe
I am learning pandas and python. I have this dataframe: dfsupport = pd.DataFrame({'Date': ['8/12/2020','8/12/2020','13/1/2020','24/5/2020','31/10/2020','11/7/2020','11/7/2020','4/4/2020','1/2/2020'], 'Category': ['Table','Chair','Cushion','Table','Chair','Mats','Mats','Large','Large'], 'Sales': ['1 table','3chairs','8 ...
Another possible solution, which uses pandas.DataFrame.groupby, pandas.DataFrame.transform and boolean indexing: s = dfsupport.groupby('Date')['Date'].transform(len) dfsupport[s.eq(s.max())] Output: Date Category Sales Paid Amount 0 8/12/2020 Table 1 table Yes 93.78 1 8/12/2020 Chair 3chairs Yes $51.99 5 11/7/2020 Ma...
2
2
77,628,455
2023-12-8
https://stackoverflow.com/questions/77628455/mypy-unreachable-on-guard-clause
I have a problem where when I try to check if the given value's type is not what I expect I'll log it and raise an error. However, mypy is complaining. What I'm doing wrong? Simplified example: from __future__ import annotations from typing import Union from logging import getLogger class MyClass: def __init__(self, va...
Mypy is complaining because due to the input you set Union[MyClass, float, int] and your condition if not isinstance(other, (MyClass, float, int)):, if the arguments follows the given types, the code will never be reached. Mypy expect that everybody using your code will sent correct argument types (that's why you add t...
2
2
77,623,684
2023-12-8
https://stackoverflow.com/questions/77623684/strange-warning-for-validationerror-in-pydantic-v2
I updated my FastAPI to Pydantic 2.5.2 and I suddenly get the following warning in the logs. /usr/local/lib/python3.12/site-packages/pydantic/_migration.py:283: UserWarning: `pydantic.error_wrappers:ValidationError` has been moved to `pydantic:ValidationError`. warnings.warn(f'`{import_path}` has been moved to `{new_lo...
Just use from from pydantic import ValidationError instead of from pydantic.error_wrappers import ValidationError. Now your code works correctly and it's just warning, but in the future versions of Pydantic it will cause the import error. If you don't import ValidationError in your code, it probably does one of the lib...
2
3
77,621,060
2023-12-7
https://stackoverflow.com/questions/77621060/add-annotations-to-plotly-candlestick-chart
I have been using plotly to create charts using OHLC data in a dataframe. The chart contains candlesticks on the top and volume bars at the bottom: I want to annotate the candlestick chart (not the volume chart) but cannot work out how to do it. This code works to create the charts: # Plot chart # Create subplots and ...
The issue is that you pass the whole df["Close"] series where you should pass only the value at index i, that is df.loc[i, "Close"]. This should work : fig.add_annotation(x=i, y=df.loc[i, "Close"], text="Test text", showarrow=True, arrowhead=1)
2
2
77,621,095
2023-12-7
https://stackoverflow.com/questions/77621095/how-to-rename-row-string-based-on-another-row-string
Imagine I have a dataframe like this: import pandas as pd df = pd.DataFrame({"a":["","DATE","01-01-2012"], "b":["","ID",18], "c":["CLASS A","GOLF",3], "d":["","HOCKEY",4], "e":["","BASEBALL",2], "f":["CLASS B","GOLF",15], "g":["","HOCKEY",2], "h":["","BASEBALL",3] }) Out[33]: a b c d e f g h 0 CLASS A CLASS B 1 DATE ID...
Using replace+ffill to forward the CLASS, and a boolean mask to change the strings by boolean indexing: s = df.loc[0].replace('', np.nan).ffill() m = s.notna() df.loc[1, m] = s[m]+' '+df.loc[1, m] Output: a b c d e f g h 0 CLASS A CLASS B 1 DATE ID CLASS A GOLF CLASS A HOCKEY CLASS A BASEBALL CLASS B GOLF CLASS B HOC...
2
2
77,620,231
2023-12-7
https://stackoverflow.com/questions/77620231/why-does-my-listbox-print-the-whole-list-in-one-line
I create a list by appending dictionary entries containing display_name, browse_name and node_id of OPCUA server nodes. When I print the list, all the elements are on one line. I have no idea why. Please help! # Code for inserting elements into the Listbox def display_nodes(self, nodes_list): # Code zum Anzeigen der No...
When i print the list, all the elements are in one line. The problem can be fixed by using asterik(*) Change this: self.nodes_listbox.insert(tk.END,display_text) to: self.nodes_listbox.insert(tk.END, *display_text)
2
0
77,620,439
2023-12-7
https://stackoverflow.com/questions/77620439/list-to-csv-python
When I try to save a Python list in a csv, the csv have the items that I want to save separated by each character. I have a list like this with links: links = ['https://www.portalinmobiliario.com/MLC-2150551226-departamento-los-talaveras-id-117671-_JM#position=1&search_layout=grid&type=item&tracking_id=01bab66e-7cd3-43...
writer.writerows expects the parameter to be an iterable of row lists (quoting the docs: "A row must be an iterable of strings or numbers for Writer objects"); right now it's interpreting your link strings as rows of 1-character columns (since a string is indeed an iterable of strings). In short, you'll need to wrap ea...
2
5
77,619,384
2023-12-7
https://stackoverflow.com/questions/77619384/how-to-load-multiple-files-with-custom-process-for-each-of-them
I have several CSVfiles with the same structure: data_product_1.csv data_product_2.csv data_product_3.csv etc. It is clear to me that to obtain a dataframe with all the data concatted together with polars, I can do something like: import polars as pl df = pl.read_csv("data_*.csv") What I would like to do is to add a...
It seems you're wanting the filename added as a column, e.g. duckdb.sql(""" from read_csv_auto('data_*.csv', filename = true) """) ┌────────────┬───────┬────────────────────┐ │ data │ value │ filename │ │ date │ int64 │ varchar │ ├────────────┼───────┼────────────────────┤ │ 2000-01-01 │ 1 │ data_product_1.csv │ │ 200...
4
4
77,615,883
2023-12-6
https://stackoverflow.com/questions/77615883/attributeerror-flags-object-has-no-attribute-c-contiguous
I am following Hands On Machine Learning Book by Aurélien Géron and running in to the following error. Code: y_train_large = (y_train.astype("int") >= 7) y_train_odd = (y_train.astype("int") % 2 == 1) y_multilabel = np.c_[y_train_large, y_train_odd] #model knn_clf = KNeighborsClassifier() knn_clf.fit(X_train, y_multila...
There seems to be a bug report for this in Scikit-learn 1.3.0 (although it seems to have been fixed in the nightly builds). Try downgrading to version 1.2.2: pip uninstall scikit-learn pip install scikit-learn==1.2.2
2
2
77,613,936
2023-12-6
https://stackoverflow.com/questions/77613936/how-to-create-a-vector-search-index-in-azure-ai-search-using-v11-4-0
I want to create an Azure AI Search index with a vector field using the currently latest version of azure-search-documents v11.4.0. Here is my code: from azure.core.credentials import AzureKeyCredential from azure.search.documents import SearchClient from azure.search.documents.indexes import SearchIndexClient from lan...
I finally found the answer. Turns out at this moment there is not a single correct sample from Microsoft to properly create an index with a vector field. They renamed a few function names and argument names which makes most other answers (e.g. on Microsoft support pages) outdated. The sample in the official GitHub repo...
4
7
77,615,967
2023-12-6
https://stackoverflow.com/questions/77615967/converting-pandas-dataframe-to-float32-changes-value-of-low-precision-number-by
I have a very large dataset with values that don't require a lot of decimal point precision. In one test scenario, my dataframe is 102 MB, and all columns have a float64 datatype. I was hoping to reduce the memory usage, and potentially the output file sizes by changing my pandas dataframe to hold float32 values. With ...
I'm going to flag your question as a duplicate of this question, but to help understand why I will also submit this answer. Part 1: Why would a float32 of "59.11", not just be "59.11000"? Answer: there is no way to represent exactly 59.11 as a binary floating point number (float). The float representation of 59.11 is...
2
2
77,614,679
2023-12-6
https://stackoverflow.com/questions/77614679/django-get-a-certin-value-from-a-dict-with-a-for-key-value-inside-of-a-template
Sorry if my title is a bit crypt, but this is the problem I have a list of dict data = [{"a": 1, "b": 2},{"a": 3, "b": 4} ] and a list with keys = ["a","b"] I want in a template do this: for dat in data: <tr> for k in keys: <th> dat[k]</th> </tr> to get this: <tr> <th>1</th> <th>2</th> </tr> <tr> <th>3</th> <th>4</th>...
Use one of these solutions if you want to keep the order given by the keys list. Result will be different with keys = ["a", "b"] VS keys = ["b", "a"]. Solution 1 - Prepare data in the view Process the data in the view. Create a list of list instead of dictionary to keep the order of your keys list. def home(request): ...
2
2
77,615,257
2023-12-6
https://stackoverflow.com/questions/77615257/avoid-runtimewarning-using-where
I want to apply a function to a numpy array, which goes through infinity to arrive at the correct values: def relu(x): odds = x / (1-x) lnex = np.log(np.exp(odds) + 1) return lnex / (lnex + 1) x = np.linspace(0,1,10) np.where(x==1,1,relu(x)) correctly computes array([0.40938389, 0.43104202, 0.45833921, 0.49343414, 0.5...
Another possible solution, based on np.divide, to avoid division by zero. This solution is inspired by @hpaulj's comment. def relu(x): odds = np.divide(x, 1-x, out=np.zeros_like(x), where=x!=1) lnex = np.log(np.exp(odds) + 1) return lnex / (lnex + 1) x = np.linspace(0,1,10) np.where(x==1,1,relu(x)) Output: array([0.40...
2
2
77,611,459
2023-12-6
https://stackoverflow.com/questions/77611459/pandas-vectorized-operation-making-counting-function-that-resets-when-threshol
I am quite new to the programming and Im struggling to this matter. Any help is appreciated! I have a dataframe of stocks including the prices and the signal if it will be up (1) or down (-1). I want to count the sequence of repetition into another column 'count'. So, when there is a sequence of 1,1,1; then the count w...
Use GroupBy.cumcount by consecutive values of sign with modulo 5: df['count'] = df.groupby(df['sign'].ne(df['sign'].shift()).cumsum()).cumcount() % 5 + 1 print (df) price sign count 0 13 1 1 1 12 1 2 2 11 -1 1 3 12 -1 2 4 13 1 1 5 14 1 2 6 14 1 3 7 14 1 4 8 14 1 5 9 14 1 1 10 14 1 2 Detail: print (df.assign(consecutiv...
2
2
77,584,118
2023-12-1
https://stackoverflow.com/questions/77584118/python-fastapi-how-to-return-a-response-with-unicode-or-non-ascii-characters-en
I am creating a FastAPI application that triggers file downloading through the StreamingResponse class (see FastAPI docs). This part is actually ok. My problem is that when the file contains accent (e.g., é) or another special character, it seems to not encode it well. For example, when there is a é, in a CSV it will b...
Python's json module, by default, converts non-ASCII and Unicode characters into the \u escape sequence. To avoid having non-ASCII or Unicode characters converted in that way, when encoding your data into JSON, you could set the ensure_ascii flag of json.dumps() function to False. Similalry, when using Panda's DataFram...
4
5
77,576,750
2023-11-30
https://stackoverflow.com/questions/77576750/futurewarning-dataframe-swapaxes-is-deprecated-and-will-be-removed-in-a-futur
Looks like numpy is using deprecated function DataFrame.swapaxes in fromnumeric.py. Anaconda3\lib\site-packages\numpy\core\fromnumeric.py:59: FutureWarning: 'DataFrame.swapaxes' is deprecated and will be removed in a future version. Please use 'DataFrame.transpose' instead. return bound(*args, **kwds) I am getting thi...
According to the numpy issue on github, this "bug" will not be fixed in numpy. The official statement is that np.split should not be used to split pandas DataFrames anymore. Instead, iloc should be used to split DataFrames as it is described in this answer. As it looks that you are splitting the DataFrame for machine l...
7
7
77,577,864
2023-11-30
https://stackoverflow.com/questions/77577864/issue-with-hierarchical-lucas-kanade-method-on-optical-flow
Issue with Hierarchical Lucas-Kanade method on optical flow I am implementing the hierarchical Lucas-Kanade method in Python based on this tutorial. However, when applying the method to a rotating sphere, I am encountering unexpected results. The data can be found here. Algorithm explained The overall structure of t...
Optical Flow Analysis using the Lucas-Kanade Method Simple Lucas-Kanade (without hierarchical approach) Here's a program based off of the code you provide. Below is just one example of the kind of parameter optimization which could be experimented with to fine-tune the accuracy of the optical flow analysis results. The...
2
2
77,586,285
2023-12-1
https://stackoverflow.com/questions/77586285/how-can-i-get-a-pytorch-tensor-containing-some-other-tensors-size-or-shape-wi
In the context of exporting pytorch code to ONNX, I get this warning: TracerWarning: torch.tensor results are registered as constants in the trace. You can safely ignore this warning if you use this function to create tensors out of constant variables that would be the same every time you call this function. In any oth...
EDIT As was pointed out in the comments, the original answer was incorrect. Using torch.tensor will lead to a constant value in the exported graph. When tracing, outputs of torch.tensor.shape and torch.tensor.size should return tensors (instead of python integers), so the code above should export as intended just with ...
3
2
77,578,724
2023-11-30
https://stackoverflow.com/questions/77578724/conformal-prediction-intervals-insample-data-nixtla
Given the documentation of nixtla y dont find any way to compute the prediction intervals for insample prediction (training data) but just for future predicitons. I put an example of what I can achieve but just to predict (future). from statsforecast.models import SeasonalExponentialSmoothing, ADIDA, ARIMA from statsfo...
You can access the in-sample forecast with a conformal prediction interval using the forecast_fitted_values method. Your selected models need to support in-sample fitted values. From your example code, SeasonalExponentialSmoothing and ADIDA didn't support in-sample fitted values currently. You can find the list of sup...
5
3
77,594,674
2023-12-3
https://stackoverflow.com/questions/77594674/azure-ml-deploymentidentityerror-failed-to-create-kubernetes-deployment-identi
I'm using Azure Machine Learning v2 SDK to create a model deployment on a kubernetes compute attached to an AML workspace. I'm able to deploy it locally as part of testing before deploying online. However, when tried to deploy online using KubernetesOnlineDeplyoment, I received DeploymentIdentityError: Failed to create...
Seems like the Azure ML Extension's deployment identity-controller was being interfered by aad-pod-identity. Removing aad-pod-identity resolved the issue.
4
0
77,594,625
2023-12-3
https://stackoverflow.com/questions/77594625/how-can-i-fix-my-perceptron-to-recognize-numbers
My exercise is to train 10 perceptrons to recognize numbers (0 - 9). Each perceptron should learn a single digit. As training data, I've created 30 images (5x7 bmp). 3 variants per digit. I've got a perceptron class: import numpy as np def unit_step_func(x): return np.where(x > 0, 1, 0) def sigmoid(x): return 1 / (1 + ...
There seems to be a few issues in the code, I will try to address them: It's missing the back progation function derivatives, as metioned in comments! Those are very important because they are the ones that guide the correction to the correct dirrection (based on the gradient). simillarly, the bias is not calculated c...
2
1
77,592,100
2023-12-2
https://stackoverflow.com/questions/77592100/how-to-show-axis-labels-of-all-subplots-when-the-labels-are-strings
Problem summary Whenever I try to create a plot with plotly express 5.18.0 containing a subplot and axes labels that are not numbers, I only get labels for the first subplot subsequent subplots show empty axis labels. How can I ensure that all subplots show their respective axes labels, even if they contain strings? Ex...
One of the plotly contributors suggested I use the .update_traces(bingroup=None) on my figure. This indeed shows the missing categories on the right plot and is a viable workaround for now.
3
1
77,593,997
2023-12-3
https://stackoverflow.com/questions/77593997/efficiently-compute-item-colaborating-filtering-similarity-using-numba-polars-a
Disclaimer The question is part of a thread including those two SO questions (q1, q2) The data resemble movie ratings from the ratings.csv file (~891mb) of ml-latest dataset. Once I read the csv file with polars library like: movie_ratings = pl.read_csv(os.path.join(application_path + data_directory, "ratings.csv")) L...
I'm not too familiar with numba, so before trying to compare timings, the first thing I would try to do is create a "fully native" Polars approach: This is a direct translation of the current approach (i.e. it still contains the "double for loop") so it just serves as a baseline attempt. Because it uses the Lazy API, n...
3
3
77,609,841
2023-12-5
https://stackoverflow.com/questions/77609841/fastest-way-to-construct-sparse-block-matrix-in-python
I want to construct a matrix of shape (N,2N) in Python. I can construct the matrix as follows import numpy as np N = 10 # 10,100,1000, whatever some_vector = np.random.uniform(size=N) some_matrix = np.zeros((N, 2*N)) for i in range(N): some_matrix[i, 2*i] = 1 some_matrix[i, 2*i + 1] = some_vector[i] So the result is a...
Variant 1 You can replace the loop with a broadcasting assignment, which interleaves the columns of an identity matrix with the columns of a diagonal matrix: a = np.eye(N) b = np.diag(some_vector) c = np.empty((N, 2*N)) c[:, 0::2] = a c[:, 1::2] = b This is concise, but not optimal. This requires allocating some unnec...
2
3
77,608,616
2023-12-5
https://stackoverflow.com/questions/77608616/merge-python-logging-handler-output
I am implementing python.logging for a project that relies on a 3rd-party software that also uses logging. The issue is we want console output, and the logs from the two are getting double printed. Is there a way to set up a handler to "combine" the output of sub-handlers? import logging import sys def third_party_use(...
class NoThirdParty(logging.Filter): def filter(self, record): return not record.name == "ThirdParty" if __name__ == '__main__': print_log = logging.StreamHandler(stream=sys.stdout) print_log.setLevel(logging.INFO) print_log.addFilter(NoThirdParty()) # Do Not Reproduce Third Party! print_log.name = "MyPrintLog" print_lo...
2
1
77,608,504
2023-12-5
https://stackoverflow.com/questions/77608504/convert-numpy-array-in-column-vector
I am new to python programming so excuse me if the question may seem silly or trivial. So for a certain function I need to do a check in case x is a vector and (in that case) it must be a column vector. However I wanted to make it so that the user could also pass it a row vector and turn it into a column vector. Howeve...
You can check the type using if not isinstance(x, np.ndarray). After that check you can check the number of dimension of the array and convert to a columnar array. In the code below, first if block checks and converts to an array. Then we get how many dimensions are missing. I.e. a scalar value is missing 2 dimensions,...
2
1
77,607,499
2023-12-5
https://stackoverflow.com/questions/77607499/remove-warning-when-using-concat-with-empty-dataframes
My old code concats some dataframes, some may be empty. I now receive two future warnings regarding this. My goal is to have the old logic but without any warnings. Mainly I need to retain all the column names without empty rows. I wrote the code below (fixed 1 of the 2 warning) but it still gives me FutureWarning: The...
You can create Index with all possible column names and then reindex the final dataframe: # create `column_names` index with all posible column names column_names = pd.Index([]) for df in df_list: column_names = column_names.union(df.columns) res_df = pd.concat([df for df in df_list if not df.empty]) # reindex the fina...
2
2
77,601,398
2023-12-4
https://stackoverflow.com/questions/77601398/aws-lambda-async-invocation-issue-function-getting-timed-out-intermittently-whe
I am attempting to invoke an AWS lambda function asynchronously within another Lambda function using the boto3 SDK. The invocation is done using the following code snippet: lambda_client = boto3.client('lambda') response = lambda_client.invoke( FunctionName='async_function:alias', InvocationType="Event", Payload=json.d...
The most likely reason for this intermittent connectivity is that your Lambda function has been configured for VPC access and you have chosen a mix of private and public subnets. The fix is to configure the Lambda function for private subnets only or, if your Lambda functions only need to reach AWS services, then confi...
2
3
77,605,089
2023-12-5
https://stackoverflow.com/questions/77605089/init-in-overridden-classmethod
I have a small class hierarchy with similar methods and __init__(), but slightly different static (class) read() methods. Specifically will the child class need to prepare the file name a bit before reading (but the reading itself is the same): class Foo: def __init__(self, pars): self.pars = pars @classmethod def read...
cls.__base__.read binds the read method explicitly to the base class. You should use super().read instead to bind the read method of the parent class to the current class. Change: return cls.__base__.read(fname0) to: return super().read(fname0)
2
3
77,601,477
2023-12-4
https://stackoverflow.com/questions/77601477/multipleobjectsreturned-or-objectdoesnotexist-error-when-accessing-google-pro
I'm encountering an issue when trying to access the 'google' provider in Django-allauth. I'm getting either a MultipleObjectsReturned or ObjectDoesNotExist exception. I have followed the documentation and tried various troubleshooting steps, but the problem persists. Here is the code snippet from my views.py file: from...
you probably have 2 instance of of your google account set up. one in your settings.py and the other one in your django admin console. best you delete anyone you think you should delete and make migrations and migrate #settings.py (you could delete this and leave the one in the admin) SOCIALACCOUNT_PROVIDERS = { 'googl...
6
5
77,594,086
2023-12-3
https://stackoverflow.com/questions/77594086/how-to-run-a-nlptransformers-llm-on-low-memory-gpus
I am trying to load an AI pre-trained model, from intel on hugging face, I have used Colab its resources exceeded, used Kaggle resources increased, used paperspace, which showing me an error: The kernel for Text_Generation.ipynb appears to have died. It will restart automatically. this is the model load script: import...
I would recommend looking into model quantization as this is one of the approaches which specifically addresses this type of problem, of loading a large model for inference. TheBloke has provided a quantized version of this model which is available here: neural-chat-7B-v3-1-AWQ. To use this, you'll need to use AutoAWQ,...
2
3
77,595,180
2023-12-3
https://stackoverflow.com/questions/77595180/list-all-files-containing-a-string-between-two-specific-strings-not-on-the-same
I'd like to recursively find all .md files of the current directory that contain the “Narrow No-Break Space” U+202F Unicode character between the two strings \begin{document} and \end{document}, possibly (and in fact essentially) not on the same line as U+202F. A great addition would be to replace such U+202Fs by norma...
Assuming you are correctly reading or decoding an encoded file... I would do something along these lines. from pathlib import Path import re p=Path('/tmp') # Use your root path here def replace_non_break_spaces(fn): with open(fn,"r") as f: cont=f.read() cont_update=re.sub(r"\\begin{document}[\s\S]*?\\end{document}", la...
3
2
77,596,271
2023-12-3
https://stackoverflow.com/questions/77596271/i-want-to-merge-my-peft-adapter-model-with-the-base-model-and-make-a-fully-new-m
As the title said, I want to merge my PEFT LoRA adapter model (ArcturusAI/Crystalline-1.1B-v23.12-tagger) that I trained before with the base model (TinyLlama/TinyLlama-1.1B-Chat-v0.6) and make a fully new model. And I got this code from ChatGPT: from transformers import AutoModel, AutoConfig # Load the pretrained mode...
The adapter can't be loaded with AutoModel from transformers and also the suggestion from ChatGPT of merging won't work. Luckily you don't need to rely on AI for that. The peft library has everything ready for you with merge_and_unload: from peft import AutoPeftModelForCausalLM # Local path, check post scriptum for exp...
6
4
77,595,144
2023-12-3
https://stackoverflow.com/questions/77595144/pygame-not-processing-input-fast-enough
I am making the game snake in pygame and have completed the game. I have one problem that does not happen every time, but every once in a while, it does not process the keys being pressed if I press them quickly. For instance if the apple is next to a wall and I need to turn really quickly to get it, I sometimes just r...
I suggest using a higher frame rate but a timer event for the movement and update (see Do something every x (milli)seconds in pygame): FRAME_RATE = 60 update_interval = 100 # 0.1 seconds update_event_id = pygame.USEREVENT + 1 pygame.time.set_timer(update_event_id, update_interval) while running: # Check if the user wan...
2
3
77,590,669
2023-12-2
https://stackoverflow.com/questions/77590669/drawmarker-in-cv2-aruco-not-found
I'm trying to use the function drawMarker() from OpenCV documentation in ArucoMarkers and for some reason it keeps giving me an error: AttributeError: module 'cv2.aruco' has no attribute 'drawMarker' If it helps, I am using VS code and coding in Python. I'm not sure why I don't have "drawMarker()" in my library. I'm t...
OpenCV 4.7.0 brought few changes in API. generateImageMarker() should be used instead of drawMarker(). Original c++ tutorial was updated with: cv::Mat markerImage; cv::aruco::Dictionary dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250); cv::aruco::generateImageMarker(dictionary, 23, 200, markerIm...
3
7
77,592,974
2023-12-3
https://stackoverflow.com/questions/77592974/create-new-rows-based-on-missing-grouped-by-values
Given the below dataframe, if rows are grouped by first name and last name, how can I find and create new rows for a group that does not have a row for every type in the types list. So in the example below, two new rows would be created for Bob Jack that are missing from the original dataframe: one with type 'DA' and a...
One way to do this is to create a dataframe which is all the combinations of names and types, then left join that to the original dataframe. This will create a df with all combinations, with NaN values where there was a missing entry in the original data. That can then be filled with 0. Note that because the value colu...
5
5
77,591,847
2023-12-2
https://stackoverflow.com/questions/77591847/how-can-i-draw-a-spiral-pattern-using-python-matrices
This is not a homework assignment, just me preparing for my final programming exam. We were introduced this problem just to think, not to solve, but I would like to know how to deal with this type of problems (using matrices to draw specific patterns). I'm asked to write a program that prints “spirals” of size n × n. I...
This problem repeats itself after every four edges have been drawn. For example, in the spiral below for n=9, you can clearly see the n=5 spiral (which I've modified to have Os instead of Xs, for contrast), set in from the edges of the grid by two spaces, and the n=1 "spiral" drawn with a single X at the very center, o...
2
3
77,577,973
2023-11-30
https://stackoverflow.com/questions/77577973/malloc-double-free-error-on-m3-macbook-pro
I am working on a Django python project with a postgres db hosted with render.com. The code works fine on server and my imac. I recently got a Macbook Pro M3 (running sonoma). I have replicated the exact same setup and environment however when I try to run the code locally, I get Python(40505,0x1704f7000) malloc: doubl...
if you have installed PostgreSQL with Homebrew, brew upgrade postgresql and ensure you have version 14.10_1 https://github.com/Homebrew/homebrew-core/issues/155651#issuecomment-1827988313 psql(6636,0x10f1de600) malloc: *** error for object 0x7f916b00bc00: pointer being freed was not allocated psql(6636,0x10f1de600) mal...
7
21
77,589,004
2023-12-2
https://stackoverflow.com/questions/77589004/problem-execute-calculations-in-a-nested-loop-typeerror-numpy-float64-object
I'm trying to calculate the sum of squared errors and i'm using a nested loop. I'm new to Python and i apologize, but i encounter the error: File "...", line 13, in <module> for y in values_subtraction_mean: TypeError: 'numpy.float64' object is not iterable The problem is with the second loop, when i have to calcula...
You seem to have problems understanding basic python iteration, let alone numpy. So lets look at your code in detail In [1]: import numpy as np ...: import math ...: ...: values = [5, 2, 3, 4, 0] ...: ...: mean = np.mean(values) ...: ...: for x in values: ...: values_subtraction_mean = x - mean ...: print(values_subtra...
2
1
77,590,201
2023-12-2
https://stackoverflow.com/questions/77590201/issue-with-triangles-borders-in-matplotlib
I am facing an issue with drawing triangle borders using Matplotlib in Python. I want to create a specific pattern, but I'm encountering unexpected behavior. I need assistance in identifying and resolving the problem. this is my code import numpy as np import matplotlib.pyplot as plt N = 5 A = np.array([(x, y) for y in...
The lines you want to delete belong to the triangules generated in the first (i = 1, j = 0) and last (i = N, J = N - 1) iterations of the nested for loops: import numpy as np import matplotlib.pyplot as plt N = 5 A = np.array([(x, y) for y in range(N, -1, -1) for x in range(N + 1)]) t = np.array([[1, 1], [-1, 1]]) A = ...
2
1
77,579,324
2023-11-30
https://stackoverflow.com/questions/77579324/how-to-register-multiple-pluggy-plugins-with-setuptools
Problem I can successfully register a single plugin in pluggy using load_setuptools_entrypoints, but I can only register one. If two different plugins try to register themselves, the last one registered will be the only one that runs. I think this is not how pluggy is intended to work, and that I am making a configurat...
As you also observed, there can be exactly one plugin with a specific name. When using entry points, the name of the plugin is the name of the entry point. As far as I understand the docs, hooks are matched by the spec/impl name and signature, and the plugin name does not matter in this process (plugins are just named ...
3
2
77,587,845
2023-12-1
https://stackoverflow.com/questions/77587845/modify-regex-capturing-group-in-column
How can I modify the capturing group in pandas df.replace()? I try to add thousands separators to the numbers within the string of each cell. This should happen in a method chain. Here is the code I have so far: import pandas as pd df = pd.DataFrame({'a_column': ['1000 text', 'text', '25000 more text', '1234567', 'more...
You can use replace in your pipe, looking for a point preceded by a digit and followed by some multiple of 3 digits using this regex: (?<=\d)(?=(?:\d{3})+\b) That can then be replaced by a comma (,). df = (df .reset_index() .replace({ 'a_column' : { r'(?<=\d)(?=(?:\d{3})+\b)' : ',' } }, regex=True) ) Output: index a...
2
1
77,585,972
2023-12-1
https://stackoverflow.com/questions/77585972/python-nested-lists-search-optimization
I have a search and test problem : in the list of prime numbers from 2 to 100k, we're searching the first set of 5 with the following criteria : p1 < p2 < p3 < p4 < p5 any combination of 2 primes from the solution (3 and 7 => 37 and 73) must also be a prime sum(p1..p5) is the smallest possible sum of primes satisfying...
Here is a numba version that computes the minimal combination of the prime numbers with restrictions as stated in the question. The majority of runtime is spent in pre-computing all valid combinations of prime numbers. On my computer (AMD 5700X) this runs in 1 minute 20 seconds: import numpy as np from numba import nji...
3
3
77,588,263
2023-12-1
https://stackoverflow.com/questions/77588263/how-to-make-session-state-persist-after-button-click-in-streamlit
I'm encountering an issue with Streamlit where I'm trying to allow the user to modify text using st.text_input and then display the modified text when a button is clicked. However, the modified text is not persisting as expected in the session state. Here's a simplified version of the code: import streamlit as st # Ini...
The problem is happening due to two things: The script is rerun every time a button is clicked 'text' is changed when the first button is clicked, so the update lags behind in the session state. This is even listed as a case in the documentation under Buttons to modify st.session_state section. There are two ways to...
2
2
77,586,290
2023-12-1
https://stackoverflow.com/questions/77586290/how-to-remove-a-tag-from-an-element-of-beautifulsoup
I have a page like this: ... <div class="myclass"> <p> text 1 to keep<span>text 1 to remove</span>and keep this too. </p> <p> text 2 to keep<span>text 2 to remove</span>and keep this too. </p> <div> I.e.: I want to remove all <span> tags from any <p> element from bs4 (BeautifulSoup in Python3). Currently this is my co...
You can try: from bs4 import BeautifulSoup html_text = """\ <div class="myclass"> <p> text 1 to keep<span>text 1 to remove</span>and keep this too. </p> <p> text 2 to keep<span>text 2 to remove</span>and keep this too. </p> <div>""" soup = BeautifulSoup(html_text, "html.parser") for span in soup.select("p span"): span....
2
2
77,587,016
2023-12-1
https://stackoverflow.com/questions/77587016/keyerror-when-applying-with-columns-iteratively-over-different-columns-when-usin
I have the following issue with Polars's LazyFrame "Structs" (pl.struct) and "apply" (a.k.a. map_elements) in with_columns The idea here is trying to apply a custom logic to a group of values that belong to more than one column I have been able to achieve this using DataFrames; however, when switching to LazyFrames, a ...
It's more of a general "gotcha" with Python itself: Official Python FAQ It breaks because col ends up with the same value for every lambda One approach is to use a named/keyword arg: lambda row, col=col: validate_stuff(row[col], row["notes"]) shape: (4, 3) ┌─────┬─────┬───────────────────────────────────┐ │ foo ┆ bar ...
2
5
77,580,121
2023-11-30
https://stackoverflow.com/questions/77580121/are-there-any-ways-to-actually-stop-awaited-long-running-asyncio-task
If there is a long-running background task, cancel() method does not work as I expected (does not work at all). And I cannot find a way to actually stop the task, is that even possible or am I missing something about asyncio work? Documentation says: "Task.cancel() does not guarantee that the Task will be cancelled." B...
Turns out its not possible in my case. If you await a long-running task - the caller will wait for task completion and therefore block (thanks to @mkrieger1 for the explanation in comments). To actually stop the task, you should either modify it and add some event or flag like @zShadowSkilled mentioned, or run it with ...
2
0
77,583,454
2023-12-1
https://stackoverflow.com/questions/77583454/pip-install-pycryptodome-returns-is-not-a-supported-wheel-on-this-platform
I am trying to install pycryptodome-3.19.0 and pycryptodomex-3.19.0 on Windows 11 and Python 3.10 in venv. Whl files were downloaded from pypi manually: pycryptodome-3.19.0-pp310-pypy310_pp73-win_amd64.whl pycryptodomex-3.19.0-pp310-pypy310_pp73-win_amd64.whl Trying to install any of them I have an error: ERROR: pycry...
You've downloaded a PyPy wheel, but you're trying to install it on CPython. Look for a wheel tagged with cp instead of pp. Run pip debug -v to see a list of supported compatibility tags for your Python installation / platform.
3
2
77,582,315
2023-11-30
https://stackoverflow.com/questions/77582315/rankn-type-equivalent-for-mypy-in-python
In Haskell we can use rankN types like so: rankN :: (forall n. Num n => n -> n) -> (Int, Double) rankN f = (f 1, f 1.0) Is the same thing possible in python with mypy? I tried the following code in python 3.10.2 with mypy 1.7.1: I = TypeVar("I", int, float) def rankN(f: Callable[[I], I]) -> tuple[int, float]: return (...
I’m not familiar with mypy, but my guess is that you can (and must) represent this as a protocol with a generic method, in order to scope the type variable to be per method call, rather than per invocation of rankN. from typing import Protocol, TypeVar class UnaryNumeric(Protocol): I = TypeVar("I", int, float) def __ca...
4
4
77,581,214
2023-11-30
https://stackoverflow.com/questions/77581214/produce-this-list-0-2-6-12-20-30-42-56-72-90-using-list-comprehension
I can produce the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90] using the following code: x = [] y = 0 for i in range(2,21,2): x.append(y) y += i However I'm not sure how to convert this into list comprehension syntax of the form [expression for value in iterable if condition ]
You can assign to y inside the comprehension, using an assignment expession, i.e. using :=: y = 0 x = [y := y + i for i in range(0,20,2)] Alternatively, you can make use of the fact that these are doubles of triangular numbers, and then you don't need y (but multiplication): x = [i * (i + 1) for i in range(10)]
3
6
77,580,556
2023-11-30
https://stackoverflow.com/questions/77580556/importing-data-from-two-xml-parent-nodes-to-a-pandas-dataframe-using-read-xml
I am having trouble in importing an XML file to Pandas where I need to grab data from two parent nodes. One parent node (AgentID) has data directly in it, and the other (Sales) has child nodes (Location, Size, Status) that contain data, as given below. test_xml = '''<TEST_XML> <Sales> <AgentID>0001</AgentID> <Sale> <Lo...
I don't think you can get the desired output using just read_xml(); however, it's possible by manipulating it a bit. Essentially, the idea is to get everything from the xml using a generic xpath, select the required columns, populate the AgentID column to corresponding to Sale columns; then remove redundant rows. df = ...
2
1
77,580,911
2023-11-30
https://stackoverflow.com/questions/77580911/fast-way-to-check-values-of-one-dataframe-against-another-dataframe-in-pandas
I have two dataframes. df1: Date High Mid Low 1 2023-08-03 00:00:00 29249.8 29136.6 29152.3 4 2023-08-03 12:00:00 29395.8 29228.1 29105.0 10 2023-08-04 12:00:00 29305.2 29250.1 29137.1 13 2023-08-05 00:00:00 29099.9 29045.3 29073.0 18 2023-08-05 20:00:00 29061.6 29047.1 29044.0 .. ... ... ... ... 696 2023-11-26 20:00:...
If you have enough memory (depends on df1 and df2), you can use a cross merge: df2['Match'] = (df2.reset_index() .merge(df1, how='cross') .loc[lambda x: (x.Start != x.Date) & (x.Bottom < x.High) & (x.Top > x[['Mid', 'Low']].max(axis=1))] .value_counts('index').reindex(df2.index, fill_value=0)) Output: >>> df2 Start To...
2
2
77,580,216
2023-11-30
https://stackoverflow.com/questions/77580216/starred-unpacking-in-subscription-index
Consider the following code: class A: def __getitem__(self, key): print(key) a = A() a[*(1,2,3)] With python 3.10.6, I get a SyntaxError : invalid syntax at the starred unpacking on the last line. On python 3.11.0, however, the code works fine and prints (1,2,3), as one could maybe expect. As far as I can tell, there ...
It appears that this change was introduced in 3.11 as a part of grammar changes for PEP 646. Relevant quote: To put it another way, note that x[..., *a, ...] produces the same result as x[(..., *a, ...)] (with any slices i:j in ... replaced with slice(i, j), with the one edge case that x[*a] becomes x[(*a,)]). The re...
2
3
77,579,387
2023-11-30
https://stackoverflow.com/questions/77579387/playwright-how-to-handle-new-windows
Im trying to login with steam on https://buff.163.com. My current code looks like this. from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(headless=False, slow_mo=50) page = browser.new_page() context = browser.new_context() page.goto("https://buff.163.com/market/cs...
Your sequence seems to be a bit out of order. There's a modal after clicking the Login button, then a popup after clicking Other login methods. Try this flow: from playwright.sync_api import sync_playwright # 1.37.0 with sync_playwright() as p: browser = p.chromium.launch(headless=False, slow_mo=50) page = browser.new_...
2
2
77,579,754
2023-11-30
https://stackoverflow.com/questions/77579754/identifying-all-the-entries-within-7-days-of-some-dates-pandas
I have two dataframes. One records the date of trades: trade = pd.DataFrame({'date': ['2019-08-31', '2019-09-01', '2019-09-04'], 'person': [1, 1, 2], 'code': [123, 123, 456], 'value1': [1, 2, 3]}) And the other records the dates of browsing history: view = pd.DataFrame({'date': ['2019-08-29', '2019-08-29', '2019-08-30...
There is no highly efficient way to do this in pure pandas, you can however use janitor's conditional_join with a helper column, then groupby.agg: import janitor trade['date'] = pd.to_datetime(trade['date']) view['date'] = pd.to_datetime(view['date']) out = (trade .assign(start_date=lambda d: d['date'].sub(pd.DateOffse...
2
2
77,579,302
2023-11-30
https://stackoverflow.com/questions/77579302/python-assignment-statement
I was going through the python assignment statement docs . Here python uses below Backus–Naur form for assignment statements. assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression) target_list ::= target ("," target)* [","] target ::= identifier | "(" [target_list] ")" | "[" [target_list] "]" | ...
Isn't it right here? starred_expression ::= expression | … A starred_expression can be just an expression. It must be the case that expression encompasses numeric literals like 9. (Edited for clarity following comments.) UPDATE Here is the full line from starred_expression to 9. starred_expression ::= expression | (st...
3
4
77,578,698
2023-11-30
https://stackoverflow.com/questions/77578698/selenium-not-working-with-correct-chromedriver-version-and-chrome-version
I want to just write a hello world with selenium and have the following code: from selenium import webdriver driver = webdriver.Chrome('C:/Users/[...]/chromedriver/chromedriver.exe') driver.get("https://www.google.com") But I keep getting the following error: Traceback (most recent call last): File "C:\Users\Username\...
You can simply get the driver by: from selenium import webdriver driver = webdriver.Chrome() then: driver.get("https://www.google.com") You don't need driver.exe anymore doc: https://www.selenium.dev/blog/2022/introducing-selenium-manager/
2
1
77,578,241
2023-11-30
https://stackoverflow.com/questions/77578241/how-to-get-anscombe-data-wide-format-from-long-format
I have the follwing anscombe data in long format import seaborn as sns # Load the example dataset for Anscombe's quartet anscombe_long = sns.load_dataset("anscombe") anscombe_long dataset x y 0 I 10.0 8.04 1 I 8.0 6.95 2 I 13.0 7.58 3 I 9.0 8.81 4 I 11.0 8.33 5 I 14.0 9.96 6 I 6.0 7.24 ... ... I wanted to convert th...
Use GroupBy.cumcount with DataFrame.pivot: out = (anscombe_long.assign(g = anscombe_long.groupby('dataset').cumcount()) .pivot(index='g', columns='dataset')) print (out) x y dataset I II III IV I II III IV g 0 10.0 10.0 10.0 8.0 8.04 9.14 7.46 6.58 1 8.0 8.0 8.0 8.0 6.95 8.14 6.77 5.76 2 13.0 13.0 13.0 8.0 7.58 8.74 12...
2
2
77,577,590
2023-11-30
https://stackoverflow.com/questions/77577590/whats-the-pythonic-way-to-pass-a-variable-into-another-class
I have different classes which calculate different positions. Lets say ClassX provides the function get_xpos() and ClassY therefore get_ypos() For the calculation inside ClassY in need the x_pos. I cant pass the value in the __init__ function because it changes every cycle. In C++ i would to this by passing a pointer.....
You can pass a reference to an instance of the ClassX to the constructor of ClassY. Then you can access the x_pos inside the simulate method of y without passing anything. Here's an example with random x and y=2x. import random class ClassX: def __init__(self): self.x_pos = 0 def calc_x(self): self.x_pos = random.randi...
3
2
77,574,103
2023-11-29
https://stackoverflow.com/questions/77574103/how-to-make-the-nested-for-loop-execute-faster-in-python
Here is my script: for a in range(-100, 101): for b in range(-100, 101): for c in range(-100, 101): for d in range(-100, 101): if abs(2**a*3**b*5**c*7**d-0.3048) <= 10**(-6): print('a=',a, ', b=', b, ', c=', c,', d=', d,', the number=', 2**a*3**b*5**c*7**d, ', error=', abs(2**a*3**b*5**c*7**d-.3048)) It took 27 mins a...
For these kind of computations you can try numba JIT: from numba import njit @njit def fn(): for a in range(-100, 101): for b in range(-100, 101): for c in range(-100, 101): for d in range(-100, 101): n = (2.0**a) * (3.0**b) * (5.0**c) * (7.0**d) v = n - 0.3048 if abs(v) <= 1e-06: print( "a=", a, ", b=", b, ", c=", c, ...
2
5
77,570,553
2023-11-29
https://stackoverflow.com/questions/77570553/conditionally-required-value-in-pydantic-v2-model
I'm working with an API that accepts a query parameter, which selects the values the API will return. Therefore, when parsing the API response, all attributes of the Pydantic model used for validation must be optional: class InvoiceItem(BaseModel): """ Pydantic model representing an Invoice """ id: PositiveInt | None =...
Inspired by Marks answer I ended up using something like this: Mixin generator pattern: from typing import Self from pydantic import BaseModel, model_validator def required_mixin(required_attributes: list[str | list[str]]): class SomeRequired(BaseModel): @model_validator(mode="after") def required_fields(self) -> Self:...
3
0
77,574,303
2023-11-29
https://stackoverflow.com/questions/77574303/get-a-dictionary-of-related-model-values
I have a model Post with some fields. Aside from that I have some models which have Post as a ForeignKey. Some examples are: class ViewType(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="view_types", verbose_name=_("Post"), ) view = models.CharField( max_length=20, choices=VIEW_...
With some trepidation.... class Post(models.Model): def dump(self): mydict = {} for k, v in Post.__dict__.items(): # find the attributes that represent the reverse foreign keys if type(v) == ReverseManyToOneDescriptor: print(k) mydict[k] = getattr(self, k).all() print(mydict) With that solution, each value in mydict h...
2
2
77,570,976
2023-11-29
https://stackoverflow.com/questions/77570976/cygpath-not-found-exec-cmd-not-found-for-pyenv-on-windows-wsl-2
I have been trying to get Tensorflow to recognize my GPU within WSL 2. However, I believe that is largely irrelevant for the problem I am having right now. Whenever I try to run the pyenv command within WSL I get the following error: /mnt/c/Users/USER/.pyenv/pyenv-win/bin/pyenv: 3: cygpath: not found /mnt/c/Users/USER/...
It seemed that my WSL environment was referring to the pyenv version installed on windows and not the pyenv version installed within WSL (ubuntu). Installing pyenv in WSL and setting the correct path should help. It can be done like this: curl https://pyenv.run | bash Then add the next bit of code to your ~/.bashrc an...
2
4
77,570,302
2023-11-29
https://stackoverflow.com/questions/77570302/how-can-i-pass-a-keyword-argument-to-a-function-when-the-name-contains-a-dot
Given a function that accepts "**kwargs", e.g., def f(**kwargs): print(kwargs) how can I pass a key-value pair if the key contains a dot/period (.)? The straightforward way results in a syntax error: In [46]: f(a.b=1) Cell In[46], line 1 f(a.b=1) ^ SyntaxError: expression cannot contain assignment, perhaps you meant "...
Python functions only accepts valid python names (letters, underscore, and digits except for the first character), a dot is not allowed. If you want to have a string a.b as parameter, then you must use a dictionary f(**{'a.b': 1}) # {'a.b': 1} You can combine this with other parameters: f(x=2, **{'a.b': 1}) # {'x': 2,...
2
3
77,568,371
2023-11-29
https://stackoverflow.com/questions/77568371/how-to-display-value-of-another-fields-of-related-field-in-odoo-form-views
is that possible to display value of another fields of related field? For example, by default, in Sale Order, the displayed value of partner_id is the value of partner_id.name .. how if I want to display value of partner_id.mobile instead of their default? I've tried explicitly declare "partner_id.{FIELD}" like this on...
You can't use dotted field names in the form view. You can use a related field and remove partner_id from the field name Example: Inherit sale order model: class SaleOrder(models.Model): _inherit = 'sale.order' cp_logistik = fields.Float(related="partner_id.cp_logistik") cp_finance = fields.Float(related="partner_id.c...
2
3
77,531,208
2023-11-22
https://stackoverflow.com/questions/77531208/python-3-12-syntaxwarning-invalid-escape-sequence-on-triple-quoted-string-d
After updating to Python 3.12, I get warnings about invalid escape sequence on some triple-quotes comments. Is this a new restriction? I have the habit of documenting code using triple-quoted string, but this has never been a problem prior to Python 3.12. python3 --version Python 3.12.0 $ ./some_script.py /some_script....
Back in Python 3.6, using invalid escape sequences in string literals was deprecated (bpo-27364). Since then, attempting to use an invalid escape sequence has emitted a DeprecationWarning. This can often go unnoticed if you don't run Python with warnings enabled. DeprecationWarnings are silenced by default. Python 3.12...
16
31
77,555,527
2023-11-27
https://stackoverflow.com/questions/77555527/how-to-effectively-create-duplicate-rows-in-polars
I am trying to transfer my pandas code into polars but I have a difficulties with duplicating lines (I need it for my pyvista visualizations). In pandas I did the following: df = pd.DataFrame({ "key": [1, 2, 3], "value": [4, 5, 6] }) df["key"] = df["key"].apply(lambda x: 2*[x]) df = df.explode("key", ignore_index=False...
You can use .repeat_by() and .flatten() df = pl.DataFrame({ "key": [1, 2, 3], "value": [4, 5, 6] }) df.select(pl.all().repeat_by(2).flatten()) shape: (6, 2) ┌─────┬───────┐ │ key ┆ value │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════╡ │ 1 ┆ 4 │ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ │ 3 ┆ 6 │ └─────┴───────┘
2
1
77,544,923
2023-11-24
https://stackoverflow.com/questions/77544923/aggregate-column-with-list-of-string-with-intersection-of-the-elements-with-pola
I'm trying to aggregate some rows in my dataframe with a list[str] column. For each id I need the intersection of all the lists in the group. Not sure if I'm just overthinking it but I can't provide a solution right now. Any help please? df = pl.DataFrame( {"id": [1,1,2,2,3,3], "values": [["A", "B"], ["B", "C"], ["A", ...
I'm not sure if this is as simple as it may first seem. You could get rid of the lists and use "regular" Polars functionality. One way to check if a value is contained in each row of the id group is to count the number of unique (distinct) row numbers per id, values group. (df.with_columns(group_len = pl.len().over("id...
5
5
77,527,847
2023-11-22
https://stackoverflow.com/questions/77527847/jax-vmap-limit-memory
I'm wondering if there is a good way to limit the memory usage for Jax's VMAP function? Equivalently, to vmap in batches at a time if that makes sense? In my specific use case, I have a set of images and I'd like to calculate the affinity between each pair of images; so ~order((num_imgs)^2 * (img shape)) bytes of memor...
Edit, Aug 13 2024 As of JAX version 0.4.31, what you're asking for is possible using the batch_size argument of lax.map. For an iterable of size N, this will perform a scan with N // batch_size steps, and within each step will vmap the function over the batch. lax.map has less flexible semantics than jax.vmap, but for ...
4
3
77,549,493
2023-11-25
https://stackoverflow.com/questions/77549493/modulenotfounderror-no-module-named-jupyter-server-contents
I got this error: Traceback (most recent call last): File "C:\ProgramData\anaconda3\Lib\site-packages\notebook\traittypes.py", line 235, in _resolve_classes klass = self._resolve_string(klass) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Cristian Valiante\AppData\Roaming\Python\Python311\site-packages\traitlets\traitlets...
Edit: https://github.com/jupyter/notebook/issues/7048#issuecomment-1724637960 https://github.com/jupyter/notebook/issues/7048#issuecomment-1720815902 pip install notebook==6.5.6 Or as @West commented, use: pip install --upgrade --no-cache-dir notebook==6.* Old Answer : The Workaround: Uninstall the Recent Problemati...
17
30
77,553,886
2023-11-26
https://stackoverflow.com/questions/77553886/pytorch-distributed-from-two-ec2-instances-hangs
# env_vars.sh on rank 0 machine #!/bin/bash export MASTER_PORT=23456 export MASTER_ADDR=... # same as below, private ip of machine 0 export WORLD_SIZE=2 export GLOO_SOCKET_IFNAME=enX0 export RANK=0 # env_vars.sh on rank 1 machine #!/bin/bash export MASTER_PORT=23456 export MASTER_ADDR=... # same as above export WORLD_S...
I solved this problem by enabling All Traffic between my nodes. Initially, I was just allowing the MASTER_PORT and that was not enough.
3
1
77,566,275
2023-11-28
https://stackoverflow.com/questions/77566275/how-to-use-sqlalchemys-on-conflict-do-update-returning-to-return-updated-values
I am trying to do an upsert statement and have the query return the updated values. On inserts, it works fine because there is no data but when there is an update, the query returns the old data that is getting updated. This is my upsert statement- def upsert(model, data, constraints): insert_stmt: Insert = insert(mode...
When returning ORM objects you have to populate existing objects otherwise they will not be updated. There is an example here: using-returning-with-upsert-statements Here is another example I made The key line is res = session.execute(q, execution_options={"populate_existing": True}).fetchone()[0] import sys from sql...
2
5
77,555,312
2023-11-27
https://stackoverflow.com/questions/77555312/langchain-chromadb-why-does-vectorstore-return-so-many-duplicates
import os from langchain.llms import OpenAI import bs4 import langchain from langchain import hub from langchain.document_loaders import UnstructuredFileLoader from langchain.embeddings import OpenAIEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores import Chroma o...
the issue is here: Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings()) everytime you execute the file, you are inserting the same documents into the database. you could comment out that part of code if you are inserting from same file. or you could detect the similar vectors using EmbeddingsRedun...
7
11
77,546,864
2023-11-25
https://stackoverflow.com/questions/77546864/connexion-3-0-2-modulenotfounderror-please-install-connexion-using-the-flask
Problem I use connextion with Flask. Today I upgraded connexion from 2.14.2 to 3.0.2 and see ModuleNotFoundError: Please install connexion using the 'flask' extra. https://connexion.readthedocs.io/en/latest/quickstart.html I checked the official documentation, which says "To leverage the FlaskApp, make sure you install...
https://github.com/spec-first/connexion/issues/779#issuecomment-441081238 I find this error was caused by zsh. pip install "connexion[flask]" worked. (Double quotations are needed.)
7
12
77,542,619
2023-11-24
https://stackoverflow.com/questions/77542619/what-is-the-exceptiontable-in-the-output-of-dis
In python3.13, when I try to disassemble [i for i in range(10)], the result is as below: >>> import dis >>> >>> dis.dis('[i for i in range(10)]') 0 RESUME 0 1 LOAD_NAME 0 (range) PUSH_NULL LOAD_CONST 0 (10) CALL 1 GET_ITER LOAD_FAST_AND_CLEAR 0 (i) SWAP 2 L1: BUILD_LIST 0 SWAP 2 L2: FOR_ITER 4 (to L3) STORE_FAST_LOAD_F...
ExceptionTable determines where to jump to when an exception is raised(it was implemented in python-3.11). Prior version uses separate opcodes to handle this. The advantage of this approach is that entering and leaving a try block normally does not execute any code, making execution faster. To access this table, you ca...
3
5
77,567,521
2023-11-28
https://stackoverflow.com/questions/77567521/optimize-computation-of-similarity-scores-by-executing-native-polars-command-ins
Disclaimer (1): This question is supportive to this SO. After a request from two users to elaborate on my case. Disclaimer (2) - added 29/11: I have seen two solutions so far (proposed in this SO and the supportive one), that utilize the explode() functionality. Based on some benchmarks I did on the whole (~3m rows dat...
CSV pl.read_csv loads everything into memory. pl.scan_csv() returns a LazyFrame instead. Parquet faster to read/write pl.scan_csv("imdb.csv").sink_parquet("imdb.parquet") imdb.csv = 891mb / imdb.parquet = 202mb Example: In the hopes of making things simpler for replicating results, I've filtered the dataset pl.co...
5
5
77,542,502
2023-11-24
https://stackoverflow.com/questions/77542502/incorrect-image-matching-results-despite-differences-human-fingerprints
I want to use python to compared two images to check whether they are the same or not, I want to use this for fingerprint functionality in django app to validate whether the provided fingerprint is matches the one stored in the database. I have decided to use OpenCV for this purpose, utilizing ORB_create with detectAnd...
Fingerprints are matched using features specific to fingerprints. Fingerprints are mostly just ridges running in parallel, so that's boring. The interesting and identifying features are swirls (ridges curve around), ridge ends, short "island" segments (and their lengths), forks, ... https://en.wikipedia.org/wiki/Finger...
2
4
77,544,825
2023-11-24
https://stackoverflow.com/questions/77544825/useless-parent-or-super-delegation-in-method-init
I'm working through the book Python Crash Course 2nd Edition, and I did what they outlined, but they did something that runs a warning in VS code (Useless parent or super() delegation in method '__init__'). They don't go over how to fix it, and I don't think it does anything (please tell me whether it does or not), but...
Let's say that you didn't add __init__ to your subclass at all. The parent __init__ has not been overridden and will be called when ElectricCar(...) is instantiated. Your ElectricCar.__init__ doesn't do anything that python wouldn't do anyway. You only need your own __init__ if you plan to do something different that t...
3
4
77,567,405
2023-11-28
https://stackoverflow.com/questions/77567405/how-to-convert-bytes-to-a-float32-array-in-go
I am writing an array of float32 numbers from a Python script to an Elasticache Redis cluster in bytes format, then reading the bytes (as a string) from Elasticache in a Go script. How do I convert the bytes-as-string back to the original float32 array in the Go script? Python example: import numpy as np import redis a...
The example code you are using is to "convert hex, represented as strings"; you have the raw bytes (I think based on aHex: CDCC8C3FCDCC0C4033335340) so its simpler to convert directly (while you could convert the bytes to a hex string, and then convert that, doing so just adds unnecessary work/complexity). Drawing from...
2
4
77,566,173
2023-11-28
https://stackoverflow.com/questions/77566173/is-there-anyway-to-run-brave-browser-with-seleniumbase
I'm trying to run a Brave browser with undetected_chrome on a Debian server. Attempt 1: Using undected_chrome library and binary_location Result: undected_chrome has problem with driver.quit() not working probably, while I need to close and reopen the browser every minutes. People suggest using Seleniumbase instead. At...
Upgrade to seleniumbase 4.21.6 (or newer) so that you can use Brave or Opera. (https://github.com/seleniumbase/SeleniumBase/issues/2324) (Set via binary_location). Eg. On a Mac: pytest basic_test.py --binary-location="/Applications/Opera.app/Contents/MacOS/Opera" pytest basic_test.py --binary-location="/Applications/Br...
2
2
77,564,155
2023-11-28
https://stackoverflow.com/questions/77564155/how-can-one-plot-a-3d-surface-in-matplotlib-by-points-coordinates
After awhole day of searching, in desperation, I address to you, my dear fellows. I want to draw a 3D surface of human head, for which I have found nice of 3D coordinates (you can download it from my Google drive here). Using 3D scatter plot, everything looks beautiful: For my further purposes, I'd like to plot it as ...
It is possible to plot the 3D surface over your scatter plot using the plt.plot_trisurf(...) function as long as you find the right ordering of vertices for the triangles. There is a function from SciPy called ConvexHull which finds the simplices of the points on the outside of the data set. This is very handy, but doe...
5
4
77,567,508
2023-11-28
https://stackoverflow.com/questions/77567508/filter-pandas-dataframe-for-rows-with-a-specific-date
I am new to python (I have used R in the past). I have a pandas data frame with one column containing dates. I would like to filter for observations occurring on one specific date. ## Create the pandas DataFrame with column named purchase-date data = ['2023-11-25', '2023-11-24', '2023-11-25', '2023-11-23'] df = pd.Data...
The issue you're encountering is related to the fact that you're trying to compare a datetime.date object with a string in your second attempt. filter based on dates, you need to compare datetime.date objects : import pandas as pd data = ['2023-11-25', '2023-11-24', '2023-11-25', '2023-11-23'] df = pd.DataFrame(data, c...
2
1
77,567,658
2023-11-28
https://stackoverflow.com/questions/77567658/finding-the-max-or-min-of-values-in-local-sets-of-rows-of-a-pandas-dataframe
So for example, I have a dataframe like this Value Placement 0 12 high 1 15 high 2 18 high 3 14 high 4 4 low 5 5 low 6 9 high 7 11 high 8 2 low 9 1 low 10 3 low 11 2 low I want to create a second dataframe that contains the the highest value in the "Value" column for each set of consecutive rows with "high" placement...
Group by consecutive values, swap the sign for Placement that match "low", and get the idxmax per group, then keep the selected rows with loc: # group consecutive rows group = df['Placement'].ne(df['Placement'].shift()).cumsum() # invert the low values, get idxmax per group keep = (df['Value'] .mul(df['Placement'].map(...
2
2
77,549,857
2023-11-25
https://stackoverflow.com/questions/77549857/iterate-over-a-list-of-lists-assert-multiple-conditions-and-render-when-true-in
I have the following variables to use in my Jinja template: list_python_version = [3, 9] all_python_version = [ [3, 8], [3, 9], [3, 10], [3, 11], [3, 12] ] Is there a way to use a combination of Jinja filters and tests so it iterates over all_python_version, checks that both the first and second elements of the list a...
Conveniently enough, since Jinja allows you to access elements of a list via both list[0] and list.0, this means that you can actually use a dictionary filter on a list. And selectattr is just the filter we need here, since it allows to select items out of a list of dictionaries based on a property of those dictionarie...
2
1