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
75,093,819
2023-1-12
https://stackoverflow.com/questions/75093819/common-lisp-equivalent-of-pythons-itertools-starmap
Python's Itertools has what is called starmap. Given a collection of collections and a function, it applies the function to each collection strictly inside the collection, using the elements of said internal collection as arguments to the function. For example, from itertools import starmap NestedList = [(1, 2), (3, 4)...
Use a combination of mapcar and apply: (defun starmap (f list) (mapcar (lambda (x) (apply f x)) list)) Or loop with the keyword collect: (defun starmap (f list) (loop for x in list collect (apply f x))) Examples: > (starmap (lambda (x y) (+ x y)) '((1 2) (3 4) (5 6) (0 0) (1 1) (2 2))) (3 7 11 0 2 4) > (starmap #'exp...
7
7
75,085,270
2023-1-11
https://stackoverflow.com/questions/75085270/cv2-aruco-charucoboard-create-not-found-in-opencv-4-7-0
I have installed opencv-python-4.7.0.68 and opencv-contrib-python-4.7.0.68 The code below gives me the following error: AttributeError: module 'cv2.aruco' has no attribute 'CharucoBoard_create' Sample code: import cv2 aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50) board = cv2.aruco.CharucoBoard_c...
This is due to a change that happened in release 4.7.0, when the Aruco code was moved from contrib to the main repository. The constructor cv2.aruco.CharucoBoard_create has been renamed to cv2.aruco.CharucoBoard and its parameter list has changed slightly -- instead of the first two integer parameters squaresX and squa...
8
9
75,085,575
2023-1-11
https://stackoverflow.com/questions/75085575/importerror-cannot-import-name-build-py-2to3-from-distutils-command-build-py
I tried to install bipwallet through pip but it says there is no 'build_py_2to3' in distutils Defaulting to user installation because normal site-packages is not writeable Collecting bipwallet ... Collecting protobuf==3.0.0a3 Using cached protobuf-3.0.0a3.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: su...
It seems as though bipwallet or one of its dependencies (protobuf-3.0.0a3?) wants to use whatever version of setuptools is available rather than pinning a specific version. setuptools v58.0.0 has a breaking change, first included in Python 3.10, where build_py_2to3 was removed. You have a couple options: Find the offe...
5
5
75,084,387
2023-1-11
https://stackoverflow.com/questions/75084387/how-to-sort-columns-in-a-dataframe-such-that-the-values-in-the-first-row-are-fro
I have the following dataframe: Audi Hyundai Kia Mercedes Tesla VW Volvo 2019 0.25 nan nan 0.5 nan nan 0.25 2020 nan 0.125 nan 0.375 0.125 0.125 0.25 2021 nan nan 0.25 0.5 nan 0.25 nan I want to rearrange the columns such the the first row is sorted from largest to smallest. So the order of the columns...
You can reorder the columns based on the sorted order of the first row: out = df[df.iloc[0].sort_values(ascending=False).index] print(out) # Output Mercedes Audi Volvo Hyundai Kia Tesla VW 2019 0.500 0.25 0.25 NaN NaN NaN NaN 2020 0.375 NaN 0.25 0.125 NaN 0.125 0.125 2021 0.500 NaN NaN NaN 0.25 NaN 0.250
3
5
75,078,242
2023-1-11
https://stackoverflow.com/questions/75078242/how-to-generate-a-png-image-in-pil-and-display-it-in-jinja2-template-using-fasta
I have a FastAPI endpoint that is generating PIL images. I want to then send the resulting image as a stream to a Jinja2 TemplateResponse. This is a simplified version of what I am doing: import io from PIL import Image @api.get("/test_image", status_code=status.HTTP_200_OK) def test_image(request: Request): '''test di...
There are a couple of issues here. I'll make a new section for each to keep it clearly divided up. If you want to send a base64-encoded PNG, you need to change your HTML to: <img src="data:image/png;base64,{{ myImage | safe }}"> If you create an image of a single red pixel like this: im = Image.new('RGB',(1,1),'red'...
3
3
75,047,812
2023-1-8
https://stackoverflow.com/questions/75047812/remove-lines-link-two-scatter-points
Anyone please help me how to remove the lines link scatter points when plot with graph objects from Python enter image description here ` fig.add_trace(go.Scatter3d(x=x[65000:133083], y=y[65000:133083], z=z[65000:133083], marker=dict( size=1, # Changed node size... color=color[65000:133083], # ...and color colorscale='...
Have you tried to add: mode = 'markers', marker = dict( size = 12, # color = z, # set color to an array/list of desired values colorscale = "Viridis", # choose a colorscale opacity = 0.8 ) Though i'm not sure why you do have lines given your code...
3
2
75,040,507
2023-1-7
https://stackoverflow.com/questions/75040507/how-to-access-fastapi-backend-from-a-different-machine-ip-on-the-same-local-netw
Both the FastAPI backend and the Next.js frontend are running on localost. On the same computer, the frontend makes API calls using fetch without any issues. However, on a different computer on the same network, e.g., on 192.168.x.x, the frontend runs, but its API calls are no longer working. I have tried using a proxy...
Setting the host flag to 0.0.0.0 To access a FastAPI backend from a different machine/IP (than the local machine that is running the server) on the same network, you would need to make sure that the host flag is set to 0.0.0.0. The IP address 0.0.0.0 means all IPv4 addresses on the local machine. If a host has two IP a...
7
27
75,003,869
2023-1-4
https://stackoverflow.com/questions/75003869/how-to-handle-timestamps-from-summer-and-winter-when-converting-strings-in-polar
I'm trying to convert string timestamps to polars datetime from the timestamps my camera puts in it RAW file metadata, but polars throws this error when I have timestamps from both summer time and winter time. ComputeError: Different timezones found during 'strptime' operation. How do I persuade it to convert these su...
polars 0.16 update Since PR 6496, was merged you can parse mixed offsets to UTC, then set the time zone: import polars as pl pdf = pl.DataFrame([ {'name': 'BST 11:06', 'ts': '2022:06:27 11:06:12.16+01:00'}, {'name': 'GMT 7:06', 'ts': '2022:12:27 12:06:12.16+00:00'}, ]) pdfts = pdf.with_columns( pl.col('ts').str.to_date...
5
6
75,009,761
2023-1-4
https://stackoverflow.com/questions/75009761/do-we-need-to-run-load-dotenv-in-every-module
I have a .env defined with the following content: env=loc I have three python module that make use of this variable. ├── __init__.py ├── cli.py |── settings.py ├── commands │ ├── __init__.py │ └── output.py settings.py: from dotenv import load_dotenv load_dotenv() if not os.getenv("env"): raise TypeError("'env' varia...
This answer more or less repeats what's mentioned in the comments and adds a demo example. Once load_dotenv() is called, environment variables will be visible in the process it's called in (and in any child process) from that point. Suppose you have a project organized as follows. ├── commands │ ├── __init__.py │ └── o...
5
3
75,040,733
2023-1-7
https://stackoverflow.com/questions/75040733/is-there-a-way-to-use-strenum-in-earlier-python-versions
The enum package in python 3.11 has the StrEnum class. I consider it very convenient but cannot use it in python 3.10. What would be the easiest method to use this class anyway?
On Python 3.10, you can inherit from str and Enum to have a StrEnum: from enum import Enum class MyEnum(str, Enum): choice1 = "choice1" choice2 = "choice2" With this approach, you have string comparison: "choice1" == MyEnum.choice1 >> True Be aware, however, that Python 3.11 makes a breaking change to classes which i...
10
16
75,021,750
2023-1-5
https://stackoverflow.com/questions/75021750/deltatable-schema-not-updating-when-using-alter-table-add-columns
I'm currently playing with Delta Tables on my local machine and I encountered a behavior that I don't understand. I create my DeltaTable like so: df.write \ .format('delta') \ .mode('overwrite') \ .option('overwriteSchema', 'true') \ .save(my_table_path) dt = DeltaTable.forPath(spark, my_table_path) Then, I run the fo...
Thanks for your patience @wtfzambo - I just realized when I reproed this myself I should seen the issue immediately so sorry for taking so long to realize this. Actually, the way this works is as expected but allow me to explain. When you ran the ALTER TABLE statement, the schema in fact did change and it was register...
3
3
75,017,836
2023-1-5
https://stackoverflow.com/questions/75017836/convert-bytes-to-bits-with-leading-zeros
I know that i can do this : byte = 58 format ( byte , '08b' ) >>> '00111010' with two bytes i have to do format( bytes , '016b') but if i doesn't have the number of bytes i can't set a number for format so i have to do : with open('file','rb')as a: b = a.read() c = int.from_bytes ( b ) d = format( c ,'b') d = (8-len(a...
You can map each byte to an 8-bit representation with the str.format method and then join the byte representations into a single string for output (where b is the bytes object you read from a file): print(''.join(map('{:08b}'.format, b)))
4
1
75,052,206
2023-1-9
https://stackoverflow.com/questions/75052206/specifying-huggingface-model-as-project-dependency
Is it possible to install huggingface models as a project dependency? Currently it is downloaded automatically by the SentenceTransformer library, but this means in a docker container it downloads every time it starts. This is the model I am trying to use: https://huggingface.co/sentence-transformers/all-mpnet-base-v2 ...
I was not able to find a native way to do this with project dependency files, so I did this using a multi-stage docker file. First I clone the model locally, then copy it into the appropriate /root/.cache/torch/ folder. Here is an example: FROM python:3.10.3 as model-download-stage RUN apt update && apt install git-lfs...
3
3
75,040,990
2023-1-7
https://stackoverflow.com/questions/75040990/importerror-dll-load-failed-while-importing-path-the-specified-module-could-n
When I was trying to import matplotlib, I wrote import matplotlib.pyplot as plt in my code. and this error occured. Traceback (most recent call last): File "C:\aiProjects\opencv\test.py", line 2, in <module> import matplotlib.pyplot as plt File "C:\Users\blackhao\AppData\Local\Programs\Python\Python311\Lib\site-packag...
... reinstall the matplotlib python package with this argument --ignore-installed: pip3 install matplotlib --user --ignore-installed
5
4
75,016,155
2023-1-5
https://stackoverflow.com/questions/75016155/converting-onnx-model-to-tensorflow-fails
I am trying to convert detr model to tensor flow using onnx. I converted the model using torch.onnx.export with opset_version=12.(which produces a detr.onnx file) Then I tried to convert the onnx file to tensorflow model using this example. I added onnx.check_model line to make sure model is loaded correctly. import ma...
The problem that you are facing is due to the use of dynamic padding instead of static pad shape at source of the model. This is exposed when you lower the onnx opset version during export. import warnings warnings.filterwarnings("ignore") #import onnxruntime import math from PIL import Image import requests import mat...
7
1
75,042,153
2023-1-7
https://stackoverflow.com/questions/75042153/cant-load-from-autotokenizer-from-pretrained-typeerror-duplicate-file-name
I'm trying to load tokenizer and seq2seq model from pretrained models. from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained("ozcangundes/mt5-small-turkish-summarization") model = AutoModelForSeq2SeqLM.from_pretrained("ozcangundes/mt5-small-turkish-summarization") But ...
I ran into the same issue when trying to use the microsoft/deberta-v3-small model. That is, at first it complained about not being able to find protobuf, and when I installed the latest, it asked for version 3.20.x. The issue happened after I downgraded to the lower version. Anyway, I was experimenting with it on a loc...
6
6
75,073,085
2023-1-10
https://stackoverflow.com/questions/75073085/passing-array-object-from-php-to-python
This is my code so far $dataraw = $_SESSION['image']; $datagambar = json_encode($dataraw); echo '<pre>'; print_r($dataraw); echo '</pre>'; print($escaped_json); $type1 = gettype($dataraw); print($type1); $type2 = gettype($datagambar); print($type2); This is $dataraw output, the type is array Array ( [0] => Array ( [F...
Update: A Completely different approach There is a difficulty with the PHP script JSON-encoding a structure to produce a JSON string and then passing it as a command line argument since the string needs to be placed in double quotes because there can be embedded spaces in the encoded string. But the string itself can c...
4
5
75,056,435
2023-1-9
https://stackoverflow.com/questions/75056435/how-can-you-run-singular-parametrized-tests-in-pytest-if-the-parameter-is-a-stri
I have a test that looks as following: @pytest.mark.parametrize('param', ['my param', 'my param 2']) def test_param(self,param): ... This works fine when calling this test with python3 -m pytest -s -k "test_param" However, if I want to target a specific test as following: python3 -m pytest -s -k "test_param[my param]...
Answer to your question including "EDIT" section: You can use following syntax to run pytest pytest .\tests\test_package_1\test_module_1_1.py::TestClass111::test_1111["param_name"] where param_name can be both value of single parameter or pytest param id To assign some id to parameter set you can use following syntax:...
5
2
75,043,654
2023-1-7
https://stackoverflow.com/questions/75043654/converting-a-massive-into-a-3-dimensional-bitmap
Problem I need this massive to serve as an input (for C based arduino). This is our massive from the example above in the required format: const byte bitmap[8][8] = { {0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF}, {0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81}, {0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81}, {0x...
Definitely not the most efficient, but hopefully quite readable and simple solution. Start with a simple function that converts the indices into the desired layer bitmaps: def bitmap(indices, side=8): """Transform a list of indices to an 8x8 bitmap with those indices turned on""" indices = set(indices) return [[int(sid...
3
1
75,073,571
2023-1-10
https://stackoverflow.com/questions/75073571/how-to-add-a-google-formula-containing-commas-and-quotes-to-a-csv-file
I'm trying to output a CSV file from Python and make one of the entries a Google sheet formula: This is what the formula var would look like: strLink = "https://xxxxxxx.xxxxxx.com/Interact/Pages/Content/Document.aspx?id=" + strId + "&SearchId=0&utm_source=interact&utm_medium=general_search&utm_term=*" strLinkCellFormu...
Instead of reinventing the wheel, you should write your CSV rows using the builtin csv.writer class. This takes care of escaping any commas and quotes in the data, so you don't need to build your own escape logic. This helps you avoid the mess of escaping in your strLinkCellFormula = ... and strCSV = strCSV + ... lines...
3
3
75,043,093
2023-1-7
https://stackoverflow.com/questions/75043093/python-compiler-says-im-adding-an-extra-argument-to-int-in-an-enum
I'm trying to create a custom enumerator that can replace an int, but has additional fields. from enum import IntEnum class MD_Fields(IntEnum): ACCOUNT = (0, "Account", True) M_DESCRIPT = (4, "Description", False) def __new__(cls, value: int, description: str, identifier: bool): obj = int.__new__(cls, value) obj.descri...
You were close - it was only missing the obj._value_ = value assignment, which Enum needs: from enum import IntEnum class MD_Fields(IntEnum): ACCOUNT = (0, "Account", True) M_DESCRIPT = (4, "Description", False) def __new__(cls, value: int, description: str, identifier: bool): obj = int.__new__(cls, value) obj._value_ ...
3
3
75,019,859
2023-1-5
https://stackoverflow.com/questions/75019859/is-there-a-way-to-include-shell-scripts-in-a-python-package-with-pyproject
Previously with setup.py you could just add setuptools.setup( ... scripts=[ "scripts/myscript.sh" ] ) and the shell script was just copied to the path of the environment. But with the new pyproject scpecification, this seems to not be possible any more. According to the Python specification of entry points and the set...
Probably using the script-files field of the [tool.setuptools] section should work: [tool.setuptools] script-files = ["scripts/myscript.sh"] It was not standardized in PEP 621, so it belongs in a setuptools-specific section. Setuptools marks it as deprecated, but personally I would assume that it is safe to use for th...
5
2
75,067,735
2023-1-10
https://stackoverflow.com/questions/75067735/generate-a-period-timestamps-in-a-dataframe-with-multiple-columns-and-fill-missi
I have a DataFrame with multiple columns and it looks like this: date col1 col2 col3 2023-01-01 Y N NaN 2023-01-02 Y N Y Knowing the start and the end timestamp of df['date'], I want to generate the in between timestamps with the desired frequency. That I can do it using the code below: new_date = pd.Series(pd.date_ra...
You can reindex with those datetimes and forward fill the missings. This way, if the starting value was NaN, the followings will stay as NaN as well: >>> df.reindex(new_date, method="ffill") col1 col2 col3 2023-01-01 00:00:00 Y N NaN 2023-01-01 00:15:00 Y N NaN 2023-01-01 00:30:00 Y N NaN 2023-01-01 00:45:00 Y N NaN 20...
3
3
75,057,274
2023-1-9
https://stackoverflow.com/questions/75057274/saving-custom-tablenet-model-vgg19-based-for-table-extraction-azure-databric
I have a model based on TableNet and VGG19, the data (Marmoot) for training and the saving path is mapped to a datalake storage (using Azure). I'm trying to save it in the following ways and get the following errors on Databricks: First approach: import pickle pickle.dump(model, open(filepath, 'wb')) This saves the m...
Try making the following changes to your custom object(s), so they can be properly serialized and deserialized: Add the keywords arguments to your constructor: def __init__(self, **kwargs): super(TableMask, self).__init__(**kwargs) Rename table_mask to TableMask to avoid naming conflicts. So when you load your model, ...
4
0
75,065,937
2023-1-10
https://stackoverflow.com/questions/75065937/how-to-make-calculation-inside-annotate
This one when I run generates error qs = User.objects.annotate(days=(datetime.now() - F("created_at")).days) AttributeError: 'CombinedExpression' object has no attribute 'days' How can I make that calculation as an annotation When I run this code, it wroks fine qs = User.objects.annotate(days=(datetime.now() - F("cre...
This can be achieved with a combination of ExpressionWrapper, which tells django what the output field type should be, and ExtractDay which, well, extracts the day. In this case, the output field is a timedelta object (i.e DurationField). ExtractDay is just a DB-level function which the django ORM provides. from django...
3
2
75,064,656
2023-1-10
https://stackoverflow.com/questions/75064656/printing-pytorch-tensor-from-gpu-or-move-to-cpu-and-or-detach
I'm starting Pytorch and still trying to understand the basic concepts. If I have a network n on the GPU that produces an output tensor out, can it be printed to stdout directly? Or should it first be moved to the cpu, or be detached from the graph before printing? Tried several combinations below involving .cpu() and ...
You should not get surprised by the same value output. It shouldn't change anything value. cpu() transfers the tensor to cpu. And detach() detaches the tensor from the computation graph so that autograd does not track it for future backpropagations. Usually .detach().cpu() is what I do, since it detaches it from the co...
7
10
75,064,556
2023-1-10
https://stackoverflow.com/questions/75064556/how-can-i-vectorize-and-speed-up-this-pandas-iterrows
I cannot understand how to use previous indexes within an apply() or similar. This is the code: for i, row in data.iterrows(): index = data.index.get_loc(i) if index == 0: pass else: # changes data.at[i, '1_Day_%_Change'] = ( data.at[data.index[index], 'Adj_Close'] / data.at[data.index[index-1], 'Adj_Close'] ) - 1 data...
Use diff and shift methods. Example code is here. df['1_Day_%_Change'] = df['Adj_close'].diff() / df['Adj_close'].shift(1) df['5_Day_%_Change'] = df['Adj_close'].diff(5) / df['Adj_close'].shift(5)
3
2
75,063,547
2023-1-9
https://stackoverflow.com/questions/75063547/find-maximum-value-in-a-list-of-dicts
I'm new to Python, and I've been stuck at one point for several days now. There is a list of dicts like this one: dd = [{'prod': 'White', 'price': '80.496'}, {'prod': 'Blue', 'price': '9.718'}, {'prod': 'Green', 'price': '7161.3'}] I need to output the value in prod based on the maximum value of the price. Here is the ...
You need to convert the price values to floats for the key parameter: max(dd, key=lambda x: float(x['price']))['prod'] This outputs: Green
3
4
75,025,513
2023-1-5
https://stackoverflow.com/questions/75025513/is-this-a-general-bug-of-osmnxs-installation-cannot-import-shapely-geos-impor
When I want to import osmnx, this error comes up. I created a new environment before and followed the standard installation process via conda.
You're using a years-old version of OSMnx and a brand new version of Shapely. They are incompatible. OSMnx >= 1.3 works with Shapely >= 2.0, see here. OSMnx < 1.3 works with Shapely < 2.0, see here. Recreate your environment (and optionally explicitly specify osmnx=1.3.*) and it'll work. Make sure you follow the docu...
3
4
75,062,271
2023-1-9
https://stackoverflow.com/questions/75062271/aggregating-df-columns-but-not-duplicates
Is there a neat way to aggregate columns into a new column without duplicating information? For example, if I have a df: Description Information 0 text1 text1 1 text2 text3 2 text4 text5 And I want to create a new column called 'Combined', which aggregates 'Description' and 'Information' to get: Description Informat...
You can first run unique: df['Combined'] = (df[['Description', 'Information']] .agg(lambda x: ' '.join(x.unique()), axis=1) ) Output: Description Information Combined 0 text1 text1 text1 1 text2 text3 text2 text3 2 text4 text5 text4 text5
3
1
75,062,113
2023-1-9
https://stackoverflow.com/questions/75062113/how-to-check-if-list-includes-an-element-using-match-case
I'm trying to check if a single element is in a list using match case. I'm not very familiar with these new keywords so 90% sure I'm using them wrong. Regardless, is there a way to do this? This is my code. I'm expecting for this to print "hi detected in list. Hi!" and "hello detected in list. Hello!", but the match st...
Using match/case is not the most appropriate way to determine if a list contains some particular value. However, to answer the question then: mylist= ["hello", "hi", 123, True] for element in mylist: match element: case 'hello': print('hello detected') case 'hi': print('hi detected')
3
2
75,058,589
2023-1-9
https://stackoverflow.com/questions/75058589/annotating-function-with-typevar-and-default-value-results-in-union-type
When annotating a function parameter with a bound TypeVar, giving it a default value results in the parameter having a union type between the TypeVar and the default value type, even though the default value is of the TypeVar type. Example: class A: pass class B(A): pass Instance = TypeVar("Instance", bound=A) def get_...
It is a very old mypy issue. The general solution is using overload's, it can be applied in your case: from typing import TypeVar, overload class A: pass class B(A): pass _Instance = TypeVar("_Instance", bound=A) @overload def get_instance() -> A: ... @overload def get_instance(cls: type[_Instance]) -> _Instance: ... d...
4
5
75,052,604
2023-1-9
https://stackoverflow.com/questions/75052604/refresherror-invalid-grant-token-has-been-expired-or-revoked-google-api
About a week ago I set up an application on google. Now when I tri and run: SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] creds = None if os.path.exists('token.pickle'): with open(self.CREDENTIALS_PATH+self.conjoiner+'token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.vali...
token.pickle contains the access token and refresh token for your application. Token has been expired or revoked.' Means that the refersh token in this file is no longer working this can be caused by servral reasons. the user revoked your access The user has authorized your access token more then 50 times and this i...
7
10
75,041,095
2023-1-7
https://stackoverflow.com/questions/75041095/how-to-apply-a-custom-function-to-xarray-dataarray-coarsen-reduce
I have a (2x2) NumPy array: ar = np.array([[2, 0],[3, 0]]) and the same one in the form of xarray.DataArray: da = xr.DataArray(ar, dims=['x', 'y'], coords=[[0, 1], [0, 1]]) I am trying to downsample the 2d array spatially using a custom function to find the mode (i.e., the most frequently occurring value): def find_m...
The signature for functions passed to DatasetCoarsen.reduce must include axis and kwargs. A good example is np.sum. So your function would need to look something like: def find_mode(window, axis=None, **kwargs): # find the mode over all axes uniq = np.unique(window, return_counts=True) ret = uniq[0][np.argmax(uniq[1])]...
5
7
75,048,986
2023-1-8
https://stackoverflow.com/questions/75048986/way-to-temporarily-change-the-directory-in-python-to-execute-code-without-affect
I need to perform an action without changing the global working directory. My case is I have a few folders, and in each, there are a few files. I need to do some computations using those files. Initially, I tried the following: with os.chdir('/directory'): ...some code needing execution inside but got AttributeError: ...
You can write your own context manager to temporarily change the working directory. import contextlib @contextlib.contextmanager def new_cd(x): d = os.getcwd() # This could raise an exception, but it's probably # best to let it propagate and let the caller # deal with it, since they requested x os.chdir(x) try: yield f...
5
6
75,049,548
2023-1-8
https://stackoverflow.com/questions/75049548/why-cant-you-intern-bytes-in-python
As mentioned in Python documentation, sys.intern() only accepts string objects. I understand why mutable types are not supported by sys.intern. But there's at least one more immutable type for which interning would make sense: bytes. So here's my question: is there any particular reason why Python interning doesn't sup...
This was suggested a decade ago on the Python-Dev mailing list. The answer is: The main difference is that sys.intern() will remove the interned strings when every external reference vanishes. It requires either weakref'ability (which both str and bytes lack) or special cooperation from the object destructor (which is...
3
4
75,036,773
2023-1-6
https://stackoverflow.com/questions/75036773/pydantic-error-wrappers-validationerror-fastapi
I'm making a crud in fastapiI have a user model and I created another one called showuser to only show some specific fields in the query, but when I execute the request I get an error. I just want my request to show the fields I have in showuser. my schemas from pydantic import BaseModel from typing import Optional fr...
I think the return value of your get_user function is the issue. Rather than returning {"User": user}, try returning just the user object as shown below: @router.get('/{user_id}', response_model=ShowUser) def get_user(user_id: int, db: Session = Depends(get_db)): user = db.query(models.User).filter(models.User.id == us...
3
3
75,047,527
2023-1-8
https://stackoverflow.com/questions/75047527/how-to-add-a-new-column-to-dataframe-based-on-conditions-on-another-column
I have the following example dataframe: d = {'col1': [4, 2, 8, 4, 3, 7, 6, 9, 3, 5]} df = pd.DataFrame(data=d) df col1 0 4 1 2 2 8 3 4 4 3 5 7 6 6 7 9 8 3 9 5 I need to add col2 to this dataframe, and values of this new column will be set by comparing col1 values (from different rows) as described below. Each row of c...
You need a reversed rolling to compare the values to the next ones: N = 3 df['col2'] = (df.loc[::-1, 'col1'] .rolling(N+1) .apply(lambda s: s.iloc[:-1].gt(s.iloc[-1]).sum()) .fillna(-1, downcast='infer') ) Alternatively, using numpy.lib.stride_tricks.sliding_window_view: import numpy as np from numpy.lib.stride_tricks...
3
3
75,045,739
2023-1-8
https://stackoverflow.com/questions/75045739/faster-startup-of-processes-python
I'm trying to run two functions in Python3 in parallel. They both take about 30ms, and unfortunately, after writing a testing script, I've found that the startup-time to get the processes running in the background takes over 100ms which is a pretty high overhead that I would like to avoid. Is anybody aware of a faster ...
several points to consider: "Time to init pool" is wrong. The child processes haven't finished starting, only the main process has initiated their startup. Once the workers have actually started, the speed of "Time to reach run" should drop to not include process startup. If you have a long lived pool of workers, you ...
4
4
75,044,362
2023-1-7
https://stackoverflow.com/questions/75044362/weird-scikit-learn-python-intellisense-error-message
Lately I was doing some ML stuff with Python using scikit-learn package. I wanted to use make_blobs() function so I began writing code for example: X, y = make_blobs(n_samples=m, centers=2, n_features=2, center_box=(80, 100)) and of course this is fine. However while coding next lines my Intellisense within Visual Stu...
This is a known behaviour of pyright (which is a Python type checker used in Intellisense). It raises a return type mismatch warning if there is at least one return statement within the function that's incompatible with what you're expecting. See a similar issue in their repo for more details and an explanation from on...
5
6
75,043,981
2023-1-7
https://stackoverflow.com/questions/75043981/updating-entire-row-or-column-of-a-2d-array-in-jax
I'm new to JAX and writing code that JIT compiles is proving to be quite hard for me. I am trying to achieve the following: Given an (n,n) array mat in JAX, I would like to add a (1,n) or an (n,1) array to an arbitrary row or column, respectively, of the original array mat. If I wanted to add a row array, r, to the thi...
JAX arrays are immutable, so you cannot do in-place modifications of array entries. But you can accomplish similar results with the np.ndarray.at syntax. For example, the equivalent of mat[2,:] = mat[2,:] + r would be mat = mat.at[2,:].set(mat[2,:] + r) But you can use the add method to be more efficient in this case...
4
6
75,040,669
2023-1-7
https://stackoverflow.com/questions/75040669/how-do-i-split-a-column-to-many-colum-by-row-quantity
I got a long single column DataFrame as following table: Column A Cell 1 Cell 2 Cell 3 Cell 4 Cell 5 Cell 6 Cell 7 Cell 8 I want to split column A in order with specify row quantity and add to others new columns If I give 2 row quantity for each column Column A Column B Column C Column D ...
You can use the underlying numpy array to reshape in Fortran order (rows, then columns): from string import ascii_uppercase N = 2 out = (pd.DataFrame(df['Column A'].to_numpy().reshape(N, -1, order='F')) # the line below is optional, just to have the column names .rename(columns=dict(enumerate(ascii_uppercase))).add_pre...
3
2
75,039,674
2023-1-7
https://stackoverflow.com/questions/75039674/python-type-hinting-for-generic-container-constructor
What is the correct typing to use for the below marked in ???, where we cast a generic iterable data container type to an iterable container of different type? def foo(itr:Iterable, cast_type:???) -> ???: (For Py 3) # type: (Iterable[Any], ???) -> ??? (For Py 2.7) return cast_type(itr) foo([1,2], cast_type=set) # Examp...
No parameterized type variables! The problem is that so far the Python typing system does not allow higher-kinded variables, meaning type variables that are parameterized with yet another type variable. This would be helpful here, since we could define a type variable T annotate itr with Iterable[T], then define for ex...
3
4
75,039,860
2023-1-7
https://stackoverflow.com/questions/75039860/how-to-concat-column-y-to-column-x-and-replicate-values-z-in-pandas-dataframe
I have a pandas DataFrame with three columns: X Y Z 0 1 4 True 1 2 5 True 2 3 6 False How do I make it so that I have two columns X and Z with values: X Z 0 1 True 1 2 True 2 3 False 3 4 True 4 5 True 5 6 False
you can melt: In [41]: df.melt(id_vars="Z", value_vars=["X", "Y"], value_name="XY")[["XY", "Z"]] Out[41]: XY Z 0 1 True 1 2 True 2 3 False 3 4 True 4 5 True 5 6 False identifier variable is "Z": it will be repeated as necessary against value variables... ...which are X and Y name X and Y's together column to "XY", an...
4
5
75,036,858
2023-1-6
https://stackoverflow.com/questions/75036858/how-do-i-concatenate-each-element-of-different-lists-together
print(sgrades_flat) ['Barrett', 'Edan', '70', '45', '59', 'Bradshaw', 'Reagan', '96', '97', '88', 'Charlton', 'Caius', '73', '94', '80', 'Mayo', 'Tyrese', '88', '61', '36', 'Stern', 'Brenda', '90', '86', '45'] print(s_grades) ['F', 'A', 'B', 'D', 'C'] I want to combine sgrades_flat and s_grades to look like ... ['Barr...
I would combine the list by iterating manually on them: sgrades_flat=['Barrett', 'Edan', '70', '45', '59', 'Bradshaw', 'Reagan', '96', '97', '88', 'Charlton', 'Caius', '73', '94', '80', 'Mayo', 'Tyrese', '88', '61', '36', 'Stern', 'Brenda', '90', '86', '45'] s_grades=['F', 'A', 'B', 'D', 'C'] it1 = iter(sgrades_flat) i...
3
3
75,033,069
2023-1-6
https://stackoverflow.com/questions/75033069/type-hint-for-a-dict-that-maps-tuples-containing-classes-to-the-corresponding-in
I'm making a semi-singleton class Foo that can have (also semi-singleton) subclasses. The constructor takes one argument, let's call it a slug, and each (sub)class is supposed to have at most one instance for each value of slug. Let's say I have a subclass of Foo called Bar. Here is an example of calls: Foo("a slug") ...
This is a really great question. First I looked through and said "no, you can't at all", because you can't express any relation between dict key and value. However, then I realised that your suggestion is almost possible to implement. First, let's define a protocol that describes your desired behavior: from typing impo...
4
4
75,032,076
2023-1-6
https://stackoverflow.com/questions/75032076/python-typing-constrain-list-to-only-allow-one-type-of-subclass
I have 3 simple classes like: class Animal(abc.ABC): ... class Cat(Animal): ... class Dog(Animal): ... Then I have a function which is annotated as such: def speak(animals: List[Animal]) -> List[str]: ... My problem is that I want to constrain the List[Animal] to only include one type of animal, so: speak([Dog(), Dog...
I would consider your issue to be not yet well defined. Once you start filling in a more concrete implementation of Animal, you're possibly going to arrive at a convincing solution. Here, I'll reword your criteria for speak as it currently stands: You want it to accept a list of any individual subclass of Animal, but n...
7
1
75,031,831
2023-1-6
https://stackoverflow.com/questions/75031831/how-to-apply-fastapi-middleware-on-non-async-def-endpoints
According to https://fastapi.tiangolo.com/tutorial/middleware/, we could apply a FastAPI Middleware on async def endpoints. Currently I have several non-async def endpoints, how to apply FastAPI Middleware on non-async def endpoint? If I still register an async Middleware, will it work for the non-async def endpoint ? ...
A coroutine is created based on any synchronous function. So yes, this will work fine for you. You can read more about this here.
3
3
75,033,570
2023-1-6
https://stackoverflow.com/questions/75033570/how-do-i-add-constraints-to-itertools-product
I am trying to list all products with numbers = [1,2,3,4,5,6,7,8] string length of 4 with some constraints. Position 0 must be < 8 Positions 2 and 3 must be < 6 With the current code it is printing every possible combination so I was wondering how do I go about filtering it? import itertools number = [1,2,3,4,5,6,7,8...
I think you can simplify this and avoid wasting a lot of cycles by looking at the inputs carefully. repeat=4 means that you want to iterate over the following: [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8] However, what your question is asking is how to iterate thr...
3
3
75,019,496
2023-1-5
https://stackoverflow.com/questions/75019496/enable-try-it-out-in-openapi-so-that-no-need-to-click
I'm using FastAPI and OpenAPI/Swagger UI to see and test my endpoints. Each time I use an endpoint for the first time, in order to test it, I have to first click the Try it out button, which is getting tedious. Is there a way to make it disappear and be able to test the endpoint instantly?
Yes, you can configure the OpenAPI/swagger page by passing a dictionary to the kwarg "swagger_ui_parameters" when creating your FastAPI instance (docs). The full list of all settings you can update that way can be found here. For your example, it would look like this: from fastapi import FastAPI app = FastAPI(swagger_u...
6
7
75,031,868
2023-1-6
https://stackoverflow.com/questions/75031868/resampling-agg-apply-behavior
This question relates to resample .agg/.apply which behaves differently than groupby .agg/.apply. Here is an example df: df = pd.DataFrame({'A':range(0,100),'B':range(0,200,2)},index=pd.date_range('1/1/2022',periods=100,freq='D')) Output: A B 2022-01-01 0 0 2022-01-02 1 2 2022-01-03 2 4 2022-01-04 3 6 2022-01-05 4 8 ...
That's a really good question and I think I have not the right answer but. resample a timeseries returns a DatetimeIndexResampler instance. apply is an alias of aggregate function. Now check the source code: @doc( _shared_docs["aggregate"], see_also=_agg_see_also_doc, examples=_agg_examples_doc, klass="DataFrame", a...
3
3
75,030,842
2023-1-6
https://stackoverflow.com/questions/75030842/sorting-of-simple-python-dictionary-for-printing-specific-value
I have a python dictionary. a = {'1':'saturn', '2':'venus', '3':'mars', '4':'jupiter', '5':'rahu', '6':'ketu'} planet = input('Enter planet : ') print(planet) If user enteres 'rahu', dictionary to be sorted like the following a = {'1':'rahu', '2':'ketu', '3':'saturn', '4':'venus', '5':'mars', '6':'jupiter' } print('4t...
Your use of a dictionary is probably not ideal. Dictionaries are useful when the key has a significance and the matching value needs to be accessed quickly. A list might be better suited. Anyway, you could do: l = list(a.values()) idx = l.index(planet) a = dict(enumerate(l[idx:]+l[:idx], start=1)) NB. the above code r...
3
5
75,029,388
2023-1-6
https://stackoverflow.com/questions/75029388/how-do-i-distribute-fonts-with-my-python-package-using-python-m-build
Problem statement My package relies on matplotlib to use a specific font which may not be installed on the target device. I'm trying to install ttf font files from the source distribution to the matplotlib fonts/ttf directory, after building the package. With setuptools slowly removing parts of its CLI (python setup.py...
You can not do this with Python packaging tools. You need to go beyond that. Some platform specific packaging tools. Think .deb/apt on Debian/Ubuntu or full blown executable installers on Windows (or .msi if it still exists). This is for operations at "install-time"... ... but you do not need to do this at "install-tim...
4
1
75,022,315
2023-1-5
https://stackoverflow.com/questions/75022315/attributeerror-dataframe-object-has-no-attribute-write-trying-to-upload-a
I have created a dataframe in databricks as a combination of multiple dataframes. I am now trying to upload that df to a table in my database and I have used this code many times before with no problem, but now it is not working. My code is df.write.saveAsTable("dashboardco.AccountList") getting the error: AttributeEr...
Most probably your DataFrame is the Pandas DataFrame object, not Spark DataFrame object. try: spark.createDataFrame(df).write.saveAsTable("dashboardco.AccountList")
5
7
75,023,979
2023-1-5
https://stackoverflow.com/questions/75023979/odd-colours-in-cairo-conversion-to-pygame
When I run this: import pygame import cairo WIDTH, HEIGHT = 640, 480 pygame.display.init() screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) screen.fill((255, 255, 255)) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) ctx = cairo.Context(surface) ctx.set_source_rgb(0, 0, 1) ctx.rectangle(0, 0, 1...
This is a problem of endianness, or byte order. Cairo's pixel formats are endian-dependent, and pygame's pixel formats are independent of endianness. See https://github.com/pygame/pygame/issues/2972 for more of a discussion of interoperability. So if the bytes are flipped, and you say blue (0, 0, 1), you fill out the A...
3
4
75,023,226
2023-1-5
https://stackoverflow.com/questions/75023226/why-is-pip-not-letting-me-install-torch-1-9-1cu111-in-a-new-conda-env-when-i-h
When I run the pip install in the new conda env: (base) brando9~ $ pip install torch==1.9.1+cu111 torchvision==0.10.1+cu111 torchaudio==0.9.1 -f https://download.pytorch.org/whl/torch_stable.html Looking in links: https://download.pytorch.org/whl/torch_stable.html ERROR: Could not find a version that satisfies the requ...
To install pytorch 1.9.1cu11 you need python 3.9 to be avaiable. Added that to my bash install.sh # - create conda env conda create -n metalearning_gpu python=3.9 conda activate metalearning_gpu ## conda remove --name metalearning_gpu --all # - make sure pip is up to date which python pip install --upgrade pip pip3 ins...
3
1
75,020,740
2023-1-5
https://stackoverflow.com/questions/75020740/dbt-postgres-all-models-appending-schema-public-to-output
I am testing a local setup of dbt-postgres. I have a simple model, but for some reason, any table created is being placed in a schema with the prefix public appended to it. Desired output table: public.test Current output table: public_public.test As you can see, the public schema is being duplicated here. Using anothe...
See the docs on custom schemas. You are defining public as the "target schema" in your profiles.yml file. You do not need to add {{ config(schema='public') }} to your model file; that config sets a "custom schema" for that model, and by default, dbt will land your model at <target_schema>_<custom_schema>. You can chang...
5
5
75,021,051
2023-1-5
https://stackoverflow.com/questions/75021051/convert-pandas-series-of-strings-to-a-series-of-lists
For iinstance I have a dataframe as below import pandas as pd df = pd.DataFrame({"col":['AM RLC, F C', 'AM/F C', 'DM','D C']}) |col -------------------| 0 |"AM RLC, F C" | 1 |"AM/F C" | 2 |"DM" | 3 |"D C" | My expected output is as following |col ----|-----------------------| 0 |["AM", "RLC", "F", "C"]| 1 |["AM", "F"...
I would use str.split or str.findall: df['col'] = df['col'].str.split('[\s,/]+') # or df['col'] = df['col'].str.findall('\w+') Output: col 0 [AM, RLC, F, C] 1 [AM, F, C] 2 [DM] 3 [D, C] Regex: [\s,/]+ # at least one of space/comma/slash with optional repeats \w+ # one or more word characters
3
4
75,014,661
2023-1-5
https://stackoverflow.com/questions/75014661/why-does-my-while-loop-inside-function-keep-returning-true
I am trying to learn while loops. To practice, I created a simple while loop with an If statement inside a function to check and see if a word is a palindrome. For some reason, even if the word is not a palindrome, it keeps returning True. I expected the output of the print function on the last line to be False: from c...
If the program is written like this: from collections import deque word = "tacrocat" def check_palindrome(word): d = deque(word) while len(d) > 1: if d.pop() == d.popleft(): return True return False print(check_palindrome(word)) At iteration-1: Since both the first character('t') and last character('t') in the deque a...
3
2
75,010,631
2023-1-4
https://stackoverflow.com/questions/75010631/python-typing-cast-vs-built-in-casting
Is there any difference between the typing.cast function and the built-in cast function? x = 123 y = str(x) from typing import cast x = 123 y = cast(str, x) I expected that mypy might not like the first case and would prefer the typing.cast but this was not the case.
str(x) returns a new str object, independent of the original int. It's only an example of "casting" in a very loose sense (and one I don't think is useful, at least in the context of Python code). cast(str, x) simply returns x, but tells a type checker to pretend that the return value has type str, no matter what type ...
10
17
75,003,385
2023-1-4
https://stackoverflow.com/questions/75003385/what-is-equivalent-protocol-of-python-callable
I always though that Callable is equivalent to having the dunder __call__ but apparently there is also __name__, because the following code is correct for mypy --strict: def print_name(f: Callable[..., Any]) -> None: print(f.__name__) def foo() -> None: pass print_name(foo) print_name(lambda x: x) What is actual inter...
So the mypy position up until now seems to have been that most of the time, when a variable is annotated with Callable, the user expects it to stand for a user-defined function (i.e. def something(...): ...). Even though user-defined functions are technically a subtype of the callable and even though they are the ones ...
6
4
75,004,868
2023-1-4
https://stackoverflow.com/questions/75004868/interesting-results-with-the-increment-operator
I had learned that n = n + v and n += v are the same. Until this; def assign_value(n, v): n += v print(n) l1 = [1, 2, 3] l2 = [4, 5, 6] assign_value(l1, l2) print(l1) The output will be: [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] Now when I use the expanded version: def assign_value(n, v): n = n + v print(n) l1 = [1, 2, 3...
It may seem counter-intuitive, but they are not always the same. In fact, a = a + b means a = a.__add__(b), creating a new object a += b means a = a.__iadd__(b), mutating the object __iadd__, if absent, defaults to the __add__, but it also can (and it does, in the case of lists) mutate the original object in-place.
5
2
75,000,107
2023-1-4
https://stackoverflow.com/questions/75000107/sum-values-of-each-tuples-enclosed-of-two-lists-the-problem-is-that-they-add-to
I would sum the values of each tuple enclosed in two lists. The output i would like to get is: 125, 200.0, 100.0. The problem is that they don't sum, but they add like this [(87.5, 37.5), (125.0, 75.0), (50.0, 50.0)]. I need first and second to stay the same as mine, without changing any parentheses. I've searched for ...
The problem is that you are trying to add the tuples (if you do type(x) or type(y) you see that those are tuple values and not the specific floats that you have) if you want to add the values inside of the tuples then you have to access the elements you can do it like so: first = [(87.5,), (125.0,), (50.0,)] second = ...
3
3
74,953,540
2022-12-29
https://stackoverflow.com/questions/74953540/what-is-np-ndarrayany-np-dtypenp-float64-and-why-does-np-typing-ndarray
The documentation for np.typing.NDArray says that it is "a generic version of np.ndarray[Any, np.dtype[+ScalarType]]". Where is the generalization in "generic" happening? And in the documentation for numpy.ndarray.__class_getitem__ we have this example np.ndarray[Any, np.dtype[Any]] with no explanation as to what the t...
Note from the future: as of NumPy 2.0 the docs is more explicit to say A np.ndarray[Any, np.dtype[+ScalarType]] type alias generic w.r.t. its dtype.type. and as of 2.2 (dev docs currently) the type alias is changed to NDArray = np.ndarray[tuple[int, ...], np.dtype[+ScalarType]]. This now makes it clearer what the typ...
6
9
74,981,940
2023-1-2
https://stackoverflow.com/questions/74981940/performing-integer-based-rolling-window-group-by-using-python-polars
I have a outer/inner loop-based function I'm trying to vectorise using Python Polars DataFrames. The function is a type of moving average and will be used to filter time-series financial data. Here's the function: def ma_j(df_src: pl.DataFrame, depth: float): jrc04 = 0.0 jrc05 = 0.0 jrc06 = 0.0 jrc08 = 0.0 series = df_...
Are you searching for periods="10i"? Polars rolling accepts a period argument with the following query language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 day) - 1w (1 week) - 1mo (1 calendar month) - 1y (1 calendar year) - 1i (1 index count)...
4
3
74,976,153
2023-1-1
https://stackoverflow.com/questions/74976153/what-is-the-best-practice-for-imports-when-developing-a-python-package
I am trying to build a Python package, that contains sub-modules and sub-packages ("libraries"). I was looking everywhere for the right way to do it, but amazingly I find it very complicated. Also went through multiple threads in StackOverFlow of course.. The problem is as follows: In order to import a module or a pac...
This is a great question, and I wish more people would think along these lines. Making a module importable and ultimately installable is absolutely necessary before it can be easily used by others. On sys.path munging Before I answer I will say I do use sys.path munging when I do initial development on a file outside o...
5
13
74,976,313
2023-1-1
https://stackoverflow.com/questions/74976313/possible-to-stringize-a-polars-expression
Is it possible to stringize a Polars expression and vice-versa? For example, convert df.filter(pl.col('a')<10) to a string of "df.filter(pl.col('a')<10)". Is roundtripping possible e.g. eval("df.filter(pl.col('a')<10)") for user input or tool automation? I know this can be done with a SQL expression but I'm interested ...
Expressions >>> expr = pl.col("foo") > 2 >>> print(str(expr)) [(col("foo")) > (2i32)] LazyFrames >>> import io >>> df = pl.DataFrame({ ... "foo": [1, 2, 3] ... }) >>> json_state = df.lazy().filter(expr).serialize(format="json") >>> query_plan = pl.LazyFrame.deserialize(io.StringIO(json_state), format="json") >>> query...
3
2
74,946,845
2022-12-29
https://stackoverflow.com/questions/74946845/attributeerror-module-numpy-has-no-attribute-int
I tried to run my code in another computer, while it successfully compiled in the original environment, this error can outta nowhere: File "c:\vision_hw\hw_3\cv2IP.py", line 91, in SECOND_ORDER_LOG original = np.zeros((5,5),dtype=np.int) File "C:\Users\brian2lee\AppData\Local\Packages\PythonSoftwareFoundation.Python.3....
numpy.int was deprecated in NumPy 1.20 and was removed in NumPy 1.24. You can change it to numpy.int_, or just int. Several other aliases for standard types were also removed from NumPy's namespace on the same schedule: Deprecated name Identical to NumPy scalar type names numpy.bool bool numpy.bool_ numpy.int ...
25
34
74,968,585
2022-12-31
https://stackoverflow.com/questions/74968585/using-environment-variables-in-pyproject-toml-for-versioning
I am trying to migrate my package from setup.py to pyproject.toml and I am not sure how to do the dynamic versioning in the same way as before. Currently I can pass the development version using environment variables when the build is for development. The setup.py file looks similar to this: import os from setuptools i...
Another alternative that might be worth considering for your use case, if you use Git, is to use setuptools_scm. It uses your git tags to perform dynamic versioning. Your pyproject.toml would look something like this: [build-system] requires = ["setuptools", "setuptools-scm"] build-backend = "setuptools.build_meta" [to...
19
3
74,960,707
2022-12-30
https://stackoverflow.com/questions/74960707/poetry-stuck-in-infinite-install-update
My issue is that when I execute poetry install, poetry update or poetry lock the process keeps running indefinitely. I tried using the -vvv flag to get output of what's happening and it looks like it gets stuck forever in the first install. My connection is good and all packages that I tried installing exist. I use ver...
I found a clue in an issue on the GitHub repo. If you are using Linux you must delete all .lock files in the .cache/pypoetry dir in your user home directory. find ~/.cache/pypoetry -name '*.lock' -type f -delete If the directory does not exist maybe is in another location. Then I recommend removing the generated .lock...
26
22
74,981,558
2023-1-2
https://stackoverflow.com/questions/74981558/error-updating-python3-pip-attributeerror-module-lib-has-no-attribute-openss
I'm having an error when installing/updating any pip module in python3. Purging and reinstalling pip and every package I can thing of hasn't helped. Here's the error that I get in response to running python -m pip install --upgrade pip specifically (but the error is the same for attempting to install or update any pip ...
As version 39.0.0 presented this bug, downgrading the cryptography package solves this, without purging or touching your OS. pip install cryptography==38.0.4 to downgrade from 39.0.0 which presented this error EDIT per @thomas, The error is a result of incompatibility between cryptography and pyopenssl, so if possible,...
102
161
74,968,179
2022-12-31
https://stackoverflow.com/questions/74968179/session-state-is-reset-in-streamlit-multipage-app
I'm building a Streamlit multipage application and am having trouble keeping session state when switching between pages. My main page is called mainpage.py and has something like the following: import streamlit as st if "multi_select" not in st.session_state: st.session_state["multi_select"] = ["abc", "xyz"] if "select...
First, it's important to understand a widget's lifecycle. When you assign a key to a widget, then that key will get deleted from session state whenever that widget is not rendered. This can happen if a widget is conditionally not rendered on the same page or from switching pages. What you are seeing on the second page ...
11
6
74,975,596
2023-1-1
https://stackoverflow.com/questions/74975596/matplotlibs-show-function-triggering-unwanted-output
Whenever I have any Python code executed via Python v3.10.4 with or without debugging in Visual Studio Code v1.74.2, I get output looking like the following in the Debug Console window in addition to the normal output of the code. Otherwise, all of my Python programs work correctly and as intended at this time. 1 HIToo...
This problem appears to be caused by one or more bugs in macOS 13.1 and 13.2. It can be fully resolved only by downgrading macOS to 13.0 or earlier or upgrading it to 13.3 or later.
11
1
74,981,011
2023-1-2
https://stackoverflow.com/questions/74981011/t5-model-generates-short-output
I have fine-tuned the T5-base model (from hugging face) on a new task where each input and target are sentences of 256 words. The loss is converging to low values however when I use the generate method the output is always too short. I tried giving minimal and maximal length values to the method but it doesn't seem to ...
For whom it may concern, I found out the issue was with the max_length argument of the generation method. It limits the maximal number of tokens including the input tokens. In my case it was required to set max_new_tokens=1024 instead of the argument provided in the question.
3
1
74,939,758
2022-12-28
https://stackoverflow.com/questions/74939758/camelot-deprecationerror-pdffilereader-is-deprecated
I have been using camelot for our project, but since 2 days I got following errorMessage. When trying to run following code snippet: import camelot tables = camelot.read_pdf('C:\\Users\\user\\Downloads\\foo.pdf', pages='1') I get this error: DeprecationError: PdfFileReader is deprecated and was removed in PyPDF2 3.0.0...
This is issues #339. While there will hopefully be soon a release including the fix, you can still do this: pip install 'PyPDF2<3.0' after you've installed camelot. See https://github.com/camelot-dev/camelot/issues/339#issuecomment-1367331630 for details and screenshots.
33
46
74,965,764
2022-12-30
https://stackoverflow.com/questions/74965764/how-can-i-properly-hash-dictionaries-with-a-common-set-of-keys-for-deduplicatio
I have some log data like: logs = [ {'id': '1234', 'error': None, 'fruit': 'orange'}, {'id': '12345', 'error': None, 'fruit': 'apple'} ] Each dict has the same keys: 'id', 'error' and 'fruit' (in this example). I want to remove duplicates from this list, but straightforward dict and set based approaches do not work be...
What went wrong The first thing I want to point out about the original attempt is that it seems over-engineered. When the inputs are hashable, manually iterating is only necessary to preserve order, and even then, in 3.7 and up we can rely on the order-preserving property of dicts. Just because it's hashable doesn't me...
18
22
74,964,527
2022-12-30
https://stackoverflow.com/questions/74964527/attributeerror-module-cv2-aruco-has-no-attribute-dictionary-get
AttributeError: module 'cv2.aruco' has no attribute 'Dictionary_get' even after installing opencv-python opencv-contrib-python import numpy as np import cv2, PIL from cv2 import aruco import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd vid = cv2.VideoCapture(0) while (True): ret, frame = vid....
API changed for 4.7.x, I have updated a small snippet. Now you need to instantiate ArucoDetector object. import cv2 as cv dictionary = cv.aruco.getPredefinedDictionary(cv.aruco.DICT_4X4_250) parameters = cv.aruco.DetectorParameters() detector = cv.aruco.ArucoDetector(dictionary, parameters) frame = cv.imread(...) marke...
15
39
74,967,916
2022-12-31
https://stackoverflow.com/questions/74967916/how-to-create-predicted-vs-actual-plot-using-abline-plot-and-statsmodels
I am trying to recreate this plot from this website in Python instead of R: Background I have a dataframe called boston (the popular educational boston housing dataset). I created a multiple linear regression model with some variables with statsmodels api below. Everything works. import statsmodels.formula.api as smf ...
That R plot is actually for predicted ~ actual, but your python code passes the medv ~ ... model into abline_plot. To recreate the R plot in python: either use statsmodels to manually fit a new predicted ~ actual model for abline_plot or use seaborn.regplot to do it automatically Using statsmodels If you want to plo...
4
4
74,970,710
2022-12-31
https://stackoverflow.com/questions/74970710/type-annotations-for-full-class-hierarchy-in-python
Suppose we have the following code: class Base: a: int class Derived(Base): b: int print(Derived.__annotations__) Running this script in all recent versions of python will print {'b': <class 'int'>} (that is, the class members we explicitly defined in Derived. In python 3.10, using inspect.get_annotations(Derived) wil...
This is a job for typing.get_type_hints, not raw annotation inspection: import typing full_hints = typing.get_type_hints(Derived) This will also resolve string annotations, and recursively replace Annotated[T, ...] with T. Use cases that are interested in non-type-hint annotations can pass include_extras=True to get_t...
4
3
74,944,012
2022-12-28
https://stackoverflow.com/questions/74944012/how-to-convert-incredibly-long-decimals-to-fractions-and-back-with-high-precisio
I'm trying to convert very large integers to decimals, then convert those decimals to Fractions, and then convert the Fraction back to a decimal. I'm using the fractions and decimal packages to try and avoid floating point imprecision, however the accuracy still tapers off rather quickly. Is there any way to fix this /...
It's because of calling the limit_denominator(). Also it's quite inefficient to convert using an intermediate string. Convert a Decimal object into a Fraction object using the constructor like the following.(It's Mark Dickinson's solution.) import fractions import decimal decimal.getcontext().prec = 100 d = decimal.Dec...
3
4
74,978,154
2023-1-2
https://stackoverflow.com/questions/74978154/why-does-adding-multiprocessing-prevent-python-from-finding-my-compiled-c-progra
I am currently looking to speed up my code using the power of multiprocessing. However I am encountering some issues when it comes to calling the compiled code from python, as it seems that the compiled file disappears from the code's view when it includes any form of multiprocessing. For instance, with the following t...
I think this has the same root cause as [SO]: Can't import dll module in Python (@CristiFati's answer) (also check [SO]: PyWin32 and Python 3.8.0 (@CristiFati's answer)). A .dll (.so) is only loaded when its dependencies are successfully loaded (recursively). [SO]: Python Ctypes - loading dll throws OSError: [WinError ...
4
2
74,978,707
2023-1-2
https://stackoverflow.com/questions/74978707/optimizing-a-puzzle-solver
Over the holidays, I was gifted a game called "Kanoodle Extreme". The details of the game are somewhat important, but I think I've managed to abstract them away. The 2D variant of the game (which is what I'm focusing on) has a number of pieces that can be flipped/rotated/etc. A given puzzle will give you a certain amou...
I think your approach with bitmaps is a good start. One of the problems is that if a narrow area is created by a combination, where a cell could never be covered by any of the remaining pieces, the brute force search will only discover this much later -- after having added several pieces successfully in another area of...
15
2
74,998,112
2023-1-3
https://stackoverflow.com/questions/74998112/how-to-list-latest-posts-in-django
I'm working on my blog. I'm trying to list my latest posts in page list_posts.html.I tried but posts are not shown, I don't know why. I don't get any errors or anything, any idea why my posts aren't listed? This is models.py from django.db import models from django.utils import timezone from ckeditor.fields import Rich...
The reason this doesn't work is because the published_at is apparently NULL and is thus never filled in. With the .filter(published_at__lte=timezone.now()), it checks that the published_at is less than or equal to the current timestamp. If it is NULL, it thus is excluded. That means that you will either need to fill in...
3
2
74,993,877
2023-1-3
https://stackoverflow.com/questions/74993877/different-behavior-of-applystr-and-astypestr-for-datetime64ns-pandas-colum
I'm working with datetime information in pandas and wanted to convert a bunch of datetime64[ns] columns to str. I noticed a different behavior from the two approaches that I expected to yield the same result. Here's a MCVE. import pandas as pd # Create a dataframe with dates according to ISO8601 df = pd.DataFrame({"dt_...
The time information is never lost, if you use 2023-01-02 12:00, you'll see that all times will be present with astype, but also visible in the original datetime column: dt_column str_from_astype str_from_apply 0 2023-01-01 00:00:00 2023-01-01 00:00:00 2023-01-01 00:00:00 1 2023-01-02 00:00:00 2023-01-02 00:00:00 2023...
16
19
74,992,814
2023-1-3
https://stackoverflow.com/questions/74992814/pandas-confused-when-extending-dataframe-vs-series-column-index-why-the-dif
First off, let me say that I've already looked over various responses to similar questions, but so far, none of them has really made it clear to me why (or why not) the Series and DataFrame methodologies are different. Also, some of the Pandas information is not clear, for example looking up Series.reindex, https://pan...
I don't think you can directly modify the Series in place to add multiple values at once. If having a new object is not an issue: ss = pd.Series(np.random.randn(4), index=list('ABCD'), name='z') xs = pd.Series([99,-99], index=['X','Y'], name='z') # new object with updated index ss = ss.reindex(ss.index.union(xs.index))...
3
2
74,991,754
2023-1-3
https://stackoverflow.com/questions/74991754/how-to-yield-one-array-element-and-keep-other-elements-in-pyspark-dataframe
I have a pyspark DataFrame like: +------------------------+ | ids| +------------------------+ |[101826, 101827, 101576]| +------------------------+ and I want explode this dataframe like: +------------------------+ | id| ids| +------------------------+ |101826 |[101827, 101576]| |101827 |[101826, 101576]| |101576 |[...
The easiest way out is to copy id into ids. Explode id and use array except to exclude each id in the row. Code below. ( df1.withColumn('ids', col('id')) .withColumn('id',explode('id')) .withColumn('ids',array_except(col('ids'), array('id'))) ).show(truncate=False) +------+----------------+ |id |ids | +------+--------...
4
4
74,988,070
2023-1-3
https://stackoverflow.com/questions/74988070/how-can-i-overlay-one-image-over-another-so-that-dark-background-is-transparent
I have 2 images, test1.jpg and test2.jpg that are RGB images. They have been converted from a 2D numpy array so they are monochrome images. They have the same shape. When I use the paste function, I only see one of the images instead of both. Here are the test1 and test2 jpgs: . This is what I get after doing test1.pa...
You simply need to choose the lighter of your two images at each point with PIL Channel Operations: from PIL import Image, ImageChops im1 = Image.open('test1.jpeg') im2 = Image.open('test2.jpeg') # Choose lighter of the two images at each pixel location combined = ImageChops.lighter(im1,im2) Note that you could use ...
4
5
74,987,702
2023-1-2
https://stackoverflow.com/questions/74987702/how-to-parse-script-tag-using-beautifulsoup
I am trying to read the window.appCache from a glassdoor reviews site. url = "https://www.glassdoor.com/Reviews/Alteryx-Reviews-E351220.htm" html = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(html.content,'html.parser') text = soup.findAll("script")[0].text This isolates the dict I ne...
One solution is to parse the required data with re/json module: import json import pprint import re import requests url = "https://www.glassdoor.com/Reviews/Alteryx-Reviews-E351220.htm" html = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}).text reviews = re.search(r'"reviews":(\[.*?}\])}', html, flags=re.S).g...
4
1
74,987,641
2023-1-2
https://stackoverflow.com/questions/74987641/how-to-remove-square-after-2-seconds
I have this code and I don't know how to make the red cube disappear after 2 seconds. import pygame import sys from pygame.locals import * pygame.init() a=0 #display prozor = pygame.display.set_mode((800,800)) FPS = pygame.time.Clock() FPS.tick(60) #boje green=pygame.Color(0 ,255 , 0) red=pygame.Color(255, 0, 0) yellow...
Use pygame.time.get_ticks to measure the time in milliseconds. Calculate the time when the cube must disappear again and hide the cube if the current time is greater than the calculated time. You also need to clear the display (prozor.fill(0)) and redraw the scene in each frame: drawing_cube = False hide_cube_time = 0 ...
3
2
74,945,655
2022-12-28
https://stackoverflow.com/questions/74945655/dataspell-outputs-the-following-error-local-cdn-resources-have-problems-on-chro
faced with such an error: Local cdn resources have problems on chrome/safari when used in jupyter-notebook. It appears when working with the pyvis library. net = Network(notebook=True) net.add_nodes( [1, 2, 3, 4, 5], # node ids label=['Node #1', 'Node #2', 'Node #3', 'Node #4', 'Node #5'], # node labels # node titles (...
From pyvis documentation: while using notebook in chrome browser, to render the graph, pass additional kwarg ‘cdn_resources’ as ‘remote’ or ‘inline’ I did net = Network(notebook=True, cdn_resources='in_line') A note from me - you have to use 'in_line' instead of 'inline'. From sources: assert cdn_resources in ["local...
3
5
74,986,002
2023-1-2
https://stackoverflow.com/questions/74986002/attributeerror-updater-object-has-no-attribute-dispatcher
When I run this code: from telegram.ext import * import keys print('Starting a bot....') def start_commmand(update, context): update.message.reply_text('Hello! Welcome To Store!') if __name__ == '__main__': updater = Updater(keys.token, True) dp = updater.dispatcher # Commands dp.add.handler(CommandHandler('start', sta...
You probably found an example for v13, but since a few days the v20 for python-telegram-bot is out. Now you have to build your application differently and you have to use async functions. This should work: from telegram.ext import * import keys print('Starting a bot....') async def start_commmand(update, context): awai...
5
11
74,985,638
2023-1-2
https://stackoverflow.com/questions/74985638/how-to-plot-points-over-a-violin-plot
I have four pandas Series and I plot them using a violin plot as follows: import seaborn seaborn.violinplot([X1['total'], X2['total'], X3['total'], X4['total']]) I would like to plot the values on top of the violin plot so I added: seaborn.stripplot([X1['total'], X2['total'], X3['total'], X4['total']]) But this gives...
Currently (seaborn 0.12.1), sns.violinplot seems to accept a list of lists as data, and interprets it similar to a wide form dataframe. sns.striplot (as well as sns.swarmplot), however, interpret this as a single dataset. On the other hand, sns.stripplot accepts a dictionary of lists and interprets it as a wide form da...
3
5
74,984,318
2023-1-2
https://stackoverflow.com/questions/74984318/in-django-whats-the-difference-between-verbose-name-as-a-field-parameter-and
Consider this class: class Product(models.Model): name = models.Charfield(verbose_name="Product Name", max_length=255) class Meta: verbose_name = "Product Name" I looked at the Django docs and it says: For verbose_name in a field declaration: "A human-readable name for the field." For verbose_name in a Meta declarati...
The verbose_name in the Meta deals with the name of the model, not field(s) of that model. It thus likely should be 'Product', not 'Product Name': class Product(models.Model): name = models.Charfield(verbose_name='Product Name', max_length=255) class Meta: verbose_name = 'Product' This thus specifies the table name in ...
3
2
74,982,353
2023-1-2
https://stackoverflow.com/questions/74982353/problems-with-version-control-for-dictionaries-inside-a-python-class
I'm doing something wrong in the code below. I have a method (update_dictonary) that changes a value or values in a dictionary based on what is specificed in a tuple (new_points). Before I update the dictionary, I want to save that version in a list (history) in order to be able to access previous versions. However, my...
Try this from copy import deepcopy ... def update_dictionary(self, var0, var1, new_points): po_ = deepcopy(self.po) self.history.append(po_) for i in new_points: self.po[var0][var1][i[0]] = i[1] self.version += 1 ... The problem here is that when you assign po_= self.po you expect po_ to a new variable with a new memo...
3
4
74,982,325
2023-1-2
https://stackoverflow.com/questions/74982325/poetry-clean-remove-package-from-env-after-removing-from-toml-file
I installed a package with poetry add X, and so now it shows up in the toml file and in the venv (mine's at .venv/lib/python3.10/site-packages/). Now to remove that package, I could use poetry remove X and I know that would work properly. But sometimes, it's easier to just go into the toml file and delete the package l...
When ever you manual edit the pyproject.toml you have to run poetry lock --no-update to sync the locked dependencies in the poetry.lock file. This is necessary because Poetry will use the resolved dependencies from the poetry.lock file on install if this file is available. Once the pyproject.toml and poetry.lock file a...
8
18
74,959,175
2022-12-30
https://stackoverflow.com/questions/74959175/getting-the-command-bin-sh-c-pip-install-no-cache-dir-r-requirements-txt
here is my requirements.txt beautifulsoup4==4.11.1 cachetools==5.2.0 certifi==2022.12.7 charset-normalizer==2.1.1 click==8.1.3 colorama==0.4.6 Flask==2.2.2 Flask-SQLAlchemy==3.0.2 google==3.0.0 google-api-core==2.10.2 google-auth==2.14.1 google-cloud-pubsub==2.13.11 googleapis-common-protos==1.57.0 greenlet==2.0.1 grpc...
I tried to install your Python dependencies in a Docker environment and I identified an error while installing the psycopg2 package. The reason is this package relies on two core dependencies: libpq-dev gcc But the Docker base image you use python:3.10-slim does not contain these core dependencies natively. You must ...
5
7
74,979,693
2023-1-2
https://stackoverflow.com/questions/74979693/removing-elements-from-sublists-in-python
I have two lists A1 and J1 containing many sublists. From each sublist of A1[0], I want to remove the element specified in J1[0]. I present the current and expected outputs. A1 = [[[1, 3, 4, 6], [0, 2, 3, 5]], [[1, 3, 4, 6], [1, 3, 4, 6]]] J1 = [[[1], [2]], [[1], [4]]] arD = [] for i in range(0,len(A1)): for j in range...
Code:- A1 = [[[1, 3, 4, 6], [0, 2, 3, 5]], [[1, 3, 4, 6], [1, 3, 4, 6]]] J1 = [[[1], [2]], [[1], [4]]] arD=[] for i in range(0,len(A1)): tmp=[] #Created a tmp variable list for j in range(0,len(J1)): C=set(A1[i][j])-set(J1[i][j]) tmp.append(list(C)) #Appending result in tmp variable arD.append(tmp) #Storing tmp list as...
4
2
74,979,220
2023-1-2
https://stackoverflow.com/questions/74979220/drawing-2d-and-3d-contour-in-the-same-plot
Is it possible to draw 2D and 3D contour plot like this in python. Sorry I couldn't provide much detail on the plot in terms of mathematical equations and all.
Use plot_surface along with contour to project the contour. It is not limited to the Z plane; you can do this to the X and Y planes as well. There is an example in the official documentation of Matplotlib: https://matplotlib.org/stable/gallery/mplot3d/contourf3d_2.html#sphx-glr-gallery-mplot3d-contourf3d-2-py Note that...
3
2
74,975,799
2023-1-1
https://stackoverflow.com/questions/74975799/beautiful-soup-scraping
I am trying to scrape lineups from https://www.rotowire.com/hockey/nhl-lineups.php I would like a resulting dataframe like the following Team Position Player Line CAR C Sebastian Aho Power Play #1 CAR LW Stefan Noesen Power Play #1 .... This is what I have currently, but am unsure how to get the team and ...
Try: import pandas as pd import requests from bs4 import BeautifulSoup url = "https://www.rotowire.com/hockey/nhl-lineups.php" soup = BeautifulSoup(requests.get(url).content, "html.parser") all_data = [] for a in soup.select(".lineup__player a"): name = a["title"] pos = a.find_previous("div").text line = a.find_previou...
3
4
74,972,850
2023-1-1
https://stackoverflow.com/questions/74972850/jax-lax-select-vs-jax-numpy-where
Was taking a look at the dropout implementation in flax: def __call__(self, inputs, deterministic: Optional[bool] = None): """Applies a random dropout mask to the input. Args: inputs: the inputs that should be randomly masked. deterministic: if false the inputs are scaled by `1 / (1 - rate)` and masked, whereas if true...
jnp.where is basically the same as lax.select, except more flexible in its inputs: for example, it will broadcast inputs to the same shape or cast to the same dtype, whereas lax.select requires more strict matching of inputs: >>> import jax.numpy as jnp >>> from jax import lax >>> x = jnp.arange(3) # Implicit broadcas...
3
5