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
74,972,261
2022-12-31
https://stackoverflow.com/questions/74972261/multiple-lists-in-a-for-loop-numpy-shape-command-requiring-list-entry
I created the following for loop for ItemTemplate in ItemTemplates: x = 0 self.needle_images.append(cv.imread(ItemTemplate, cv.IMREAD_UNCHANGED)) self.needle_widths.append(self.needle_images[x].shape[1]) self.needle_heights.append(self.needle_images[x].shape[0]) x = x+1 I originally tried to write the for loop like th...
The last two lines of the loop are always using the last image appended to needle_images. The index of the last item in a list is -1. for ItemTemplate in ItemTemplates: self.needle_images.append(cv.imread(ItemTemplate, cv.IMREAD_UNCHANGED)) self.needle_widths.append(self.needle_images[-1].shape[1]) self.needle_heights....
3
1
74,971,657
2022-12-31
https://stackoverflow.com/questions/74971657/split-every-occurrence-of-key-value-pairs-in-a-string-where-the-value-include-on
I have a situation where user can enter commands with optional key value pairs and value may contain spaces .. here are 4 - different form user input where key and value are separated with = sign and values have space: "cmd=create-folder name=SelfServe - Test ride" "cmd=create-folder name=SelfServe - Test ride server=p...
I would suggest using split, and then zip to feed the dict constructor: def get_dict(s): parts = re.split(r"\s*(\w+)=", s) return dict(zip(parts[1::2], parts[2::2])) Example runs: print(get_dict("cmd=create-folder name=SelfServe - Test ride")) print(get_dict("cmd=create-folder name=SelfServe - Test ride server=prd")) ...
3
4
74,968,761
2022-12-31
https://stackoverflow.com/questions/74968761/pip3-cant-download-the-latest-tflite-runtime
The current version of tflite-runtime is 2.11.0: https://pypi.org/project/tflite-runtime/ Here is a testing for downloading the tflite-runtime to the tmp folder: mkdir -p /tmp/test cd /tmp/test echo "tflite-runtime == 2.11.0" > ./test.txt pip3 download -r ./test.txt Here is the error: ERROR: Could not find a version t...
tflite-runtime 2.11.0 released packages: https://pypi.org/project/tflite-runtime/2.11.0/#files Python 3.7, 3.8 and 3.9. Only Linux, different Intel and ARM 64-bit architectures. No Python 3.10 and no source code. Use Python 3.9 if you don't want to compile from sources.
7
3
74,966,861
2022-12-31
https://stackoverflow.com/questions/74966861/activating-python-virtual-environment-on-windows-11
I am trying to create a venv virtual enviroment for Python in Window's command prompt. I created the enviroment; however, I am having difficulties using it because when I run the "activate" command it is not working. I think the problem is related to that the virtual enviroment does not have a scripts file like other w...
Open a command prompt terminal by either searching command prompt in the Windows search bar, or press the Windows Key + R and enter cmd. Create the virtual environment in a desired directory using the following command: python -m venv env This will create a new folder called env inside the directory where you executed...
6
9
74,967,657
2022-12-31
https://stackoverflow.com/questions/74967657/userwarning-the-grad-attribute-of-a-tensor-that-is-not-a-leaf-tensor-is-being
import torch from torch.autograd import Variable x = Variable(torch.FloatTensor([11.2]), requires_grad=True) y = 2 * x print(x) print(y) print(x.data) print(y.data) print(x.grad_fn) print(y.grad_fn) y.backward() # Calculates the gradients print(x.grad) print(y.grad) Error: C:\Users\donhu\AppData\Local\Temp\ipykernel_...
Call y.retain_grad() before calling y.backward(). The reason is because by default PyTorch only populate .grad for leaf variables (variables that aren't results of operations), which is x in your example. To ensure .grad is also populated for non-leaf variables like y, you need to call their .retain_grad() method. Also...
3
6
74,964,779
2022-12-30
https://stackoverflow.com/questions/74964779/how-do-i-read-extended-annotations-from-annotated
PEP 593 added extended annotations via Annotated. But neither the PEP nor the documentation for Annotated describes how we're supposed to access the underlying annotations. How are we supposed to read the extra annotations stored in the Annotated object? from typing import Annotated class Foo: bar: Annotated[int, "save...
To avoid accessing dunder names, which are reserved by python (such access should be avoided whenever possible): [...] Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning. You should use typing.get_args helper. It is actually smarter than gett...
3
4
74,964,472
2022-12-30
https://stackoverflow.com/questions/74964472/sum-columns-in-numpy-2d-array
I have a 2D NumPy array V: import numpy as np np.random.seed(10) V = np.random.randint(-10, 10, size=(6,8)) This gives V as: [[ -1 -6 5 -10 7 6 7 -2] [ -1 -10 0 -2 -6 9 6 -6] [ 5 1 1 -9 -2 -6 4 7] [ 9 3 -5 3 9 3 2 -9] [ -6 8 3 1 0 -1 5 8] [ 6 -3 1 7 4 -3 1 -9]] Now, I have 2 lists, r1 and r2, containing column indice...
Just add V[:, r2] at V[:, r2], like below: V[:, r1] += V[:, r2] print(V) Output [[ -1 -16 12 -10 7 4 7 -2] [ -1 -12 -6 -2 -6 3 6 -6] [ 5 -8 -1 -9 -2 1 4 7] [ 9 6 4 3 9 -6 2 -9] [ -6 9 3 1 0 7 5 8] [ 6 4 5 7 4 -12 1 -9]]
5
3
74,963,990
2022-12-30
https://stackoverflow.com/questions/74963990/different-behavior-for-dict-and-list-in-match-case-check-if-it-is-empty-or-not
I know there are other ways to check if dict is empty or not using match/case (for example, dict(data) if len(data) == 0), but I can't understand why python give different answers for list and dict types while we check for emptiness data = [1, 2] match data: case []: print("empty") case [1, 2]: print("1, 2") case _: pr...
There are different patterns used on the match case Python implementation. When a list or tuple is used, the pattern used is the one called Sequence Patterns. Here's an example found on the PEP: match collection: case 1, [x, *others]: print("Got 1 and a nested sequence") case (1, x): print(f"Got 1 and {x}") So let's s...
4
2
74,963,651
2022-12-30
https://stackoverflow.com/questions/74963651/how-do-i-get-find-a-word-that-contains-some-specific-letter-and-one-in-particula
Hello everyone and thank you in advance, I am trying to get a all the words in the following list except for "motiu" and "diomar" using regex and python: amfora difamador difamar dimorf dofi fada far farao farda fiar fiord fira firar firma for motiu diomar The word must not contain a letter outside the list [diomarf],...
^f[diomarf]*$|^[diomarf]*f[diomarf]*$|^[diomarf]*f$ demo Explanation: ^f[diomarf]*$ : A string either starts with f and then has any number of characters from this list [diomarf] (including 0!) OR ^[diomarf]*f[diomarf]*$ the string has f somewhere in the middle OR ^[diomarf]*f$ f at the end The previous solution I pro...
3
2
74,962,787
2022-12-30
https://stackoverflow.com/questions/74962787/sqlalchemy-module-not-found-despite-definitely-being-installed-with-pipenv
I'm learning to use FastAPI, psycopg2 and SQLAlchemy with python, which has been working fine. Now for some reason whenever I run my web app, the SQLAlchemy module cannot be found. I am running this in a Pipenv, with python 3.11.1 and SQLAlchemy 1.4.45, and running pip freeze shows SQLAlchemy is definitely installed, a...
Most likely issue is that the uvicorn executable is not present in the same python (v)env. When a python process starts, it looks into the location of the binary (uvicorn in this case), determines the python base location (either the same folder as the binary is in, or one above), and finally adds the appropriate site_...
3
2
74,957,732
2022-12-30
https://stackoverflow.com/questions/74957732/how-can-i-order-dates-and-show-only-monthyear-on-the-x-axis-in-matplotlib
I would like to improve my bitcoin dataset but I found that the date is not sorted in the right way and want to show only the month and year. How can I do it? data = Bitcoin_Historical['Price'] Date1 = Bitcoin_Historical['Date'] train1 = Bitcoin_Historical[['Date','Price']] #Setting the Date as Index train2 = train1.se...
I've made the following edits to your code: converted the column Date column as datetime type cleaned up the Price column and converting to float removed the line plt.xlim(0,20) which is causing the output to display 1970 used alternative way to plot, so that the x-axis can be formatted to get monthly tick marks, more...
4
2
74,959,199
2022-12-30
https://stackoverflow.com/questions/74959199/add-new-value-to-specific-position-in-json-using-python
I have a JSON file and need to update with new key value pair. cuurent json: [{'Name': 'AMAZON', 'Type': 'Web', 'eventTimeEpoch': 1611667194}] I need to add a location parameter and update it as "USA".But when try to update it with below code it append to location parameter with value to end. Like below. [{'Name': 'AM...
First off, your current JSON file is not correctly formatted. JSON needs double quotes not single quotes. While the order of the inserted key-value pairs is guaranteed to be preserved in Python 3.7 above, you don't have any option to "insert" to specific location inside a dictionary.(like list for example.) And people ...
3
4
74,958,496
2022-12-30
https://stackoverflow.com/questions/74958496/how-to-transpose-a-list-of-lists
Let ll be a list of lists, and tt a tuple of tuples Input: ll = [["a1","a2"],["b1","b2"],["c1","c2"]] Desired output: tt = (("a1","b1","c1"),("a2","b2","c2")) I have managed to solve it for a list of two-element lists, meaning that the internal list only contained two elements each. def list_of_list_to_tuple_of_tuple(l...
Try this one-liner - tuple(zip(*l)) Example 1 l = [["a1","a2"], ["b1","b2"], ["c1","c2"]] tuple(zip(*l)) (('a1', 'b1', 'c1'), ('a2', 'b2', 'c2')) Example 2 l2 = [["a1","a2","a3","an"], ["b1","b2","b3","bn"], ["c1","c2","c3","cn"]] tuple(zip(*l2)) (('a1', 'b1', 'c1'), ('a2', 'b2', 'c2'), ('a3', 'b3', 'c3'), ('an', '...
3
9
74,955,725
2022-12-29
https://stackoverflow.com/questions/74955725/getting-the-generic-arguments-of-a-subclass
I have a generic base class and I want to be able to inspect the provided type for it. My approach was using typing.get_args which works like so: from typing import Generic, Tuple, TypeVarTuple, get_args T = TypeVarTuple("T") class Base(Generic[*T]): values: Tuple[*T] Example = Base[int, str] print(get_args(Example)) #...
Use get_args with __orig_bases__: print(get_args(Example2.__orig_bases__[0])) # prints "(<class 'int'>, <class 'str'>)" For convenience, you can store the generic type parameters in the __init_subclass__ hook: from typing import Generic, TypeVarTuple, get_args T = TypeVarTuple("T") class Base(Generic[*T]): values: tup...
4
5
74,946,632
2022-12-29
https://stackoverflow.com/questions/74946632/jax-jit-compatible-sparse-matrix-slicing
I have a boolean sparse matrix that I represent with row indices and column indices of True values. import numpy as np import jax from jax import numpy as jnp N = 10000 M = 1000 X = np.random.randint(0, 100, size=(N, M)) == 0 # data setup rows, cols = np.where(X == True) rows = jax.device_put(rows) cols = jax.device_pu...
You can do a bit better than the first answer by using the mode argument of set() to drop out-of-bound indices, eliminating the final slice: out = jnp.zeros(N, bool).at[jnp.where(cols==3, rows, N)].set(True, mode='drop')
3
3
74,941,717
2022-12-28
https://stackoverflow.com/questions/74941717/what-would-a-python-list-nested-parser-look-like-in-pyparsing
I would like to understand how to use pyparsing to parse something like a nested Python list. This is a question to understand pyparsing. Solutions that circumvent the problem because the list of the example might look like JSON or Python itself should not prevent the usage of pyparsing. So before people start throwing...
Thanks to the answer from Xiddoc I was able to slightly adjust the answer to also work when the expression starts with a list (no idea why the solution with nested_expr does not work) import pyparsing as pp expr = pp.Forward() group_start, group_end = map(pp.Suppress, r"{}") number = pp.Word(pp.nums).setParseAction(lam...
3
0
74,949,455
2022-12-29
https://stackoverflow.com/questions/74949455/combine-date-and-time-inputs-in-streamlit-with-dataframe-time-column
I have a df that has a column 'Time' in seconds: Time 1 2 3 4 I want the user to input the date with a timestamp (eg format: 25/09/2022 12:30:00). Then, I need to add a new column 'DateTime' which combines the user input datetime with my 'Time' column. The 'DateTime' column should look like this: DateTime 25/09/2022 1...
You can use the .combine() function from pandas to combine your start_date with start_time, after you have accomplished that. Make a new df named DateTime and loop through your Time df to concatenate the seconds to DateTime, after the concatenation, format the DateTime. You can then drop Time column after haven looped ...
3
2
74,948,525
2022-12-29
https://stackoverflow.com/questions/74948525/futurewarning-save-is-not-part-of-the-public-api-in-python
I am using Python to convert Pandas df to .xlsx (in Plotly-Dash app.). All working well so far but with this warning tho: "FutureWarning: save is not part of the public API, usage can give unexpected results and will be removed in a future version" How should I modify the code below in order to keep its functionality a...
just replace save with close. writer = pd.ExcelWriter("File.xlsx", engine = "xlsxwriter") workbook = writer.book df.to_excel(writer, sheet_name = 'Sheet', index = False) writer.close()
23
35
74,945,819
2022-12-28
https://stackoverflow.com/questions/74945819/draw-shapes-on-top-of-networkx-graph
Given an existing networkx graph import networkx as nx import numpy as np np.random.seed(123) graph = nx.erdos_renyi_graph(5, 0.3, seed=123, directed=True) nx.draw_networkx(graph) or import networkx as nx G = nx.path_graph(4) nx.spring_layout(G) nx.draw_networkx(G) how can you draw a red circle on top of (in the sa...
To be able to draw a networkx graph, each node needs to be assigned a position. By default, nx.spring_layout() is used to calculate positions when calling nx.draw_networkx(), but these positions aren't stored. They are recalculated each time the function is drawn, except when the positions are explicitly added as a par...
4
5
74,944,224
2022-12-28
https://stackoverflow.com/questions/74944224/add-a-value-to-a-list-of-paired-values
I have an array that has pairs of numbers representing row, col values in a model domain. I am trying to add the layer value to have a list of lay, row, col. I have an array rowcol: array([(25, 65), (25, 66), (25, 67), (25, 68), (26, 65), (26, 66), (26, 67), (26, 68), (26, 69), (27, 66), (27, 67), (27, 68), (27, 69), (...
You can use numpy.insert. >>> import numpy as np >>> a = np.array([(25, 65), (25, 66), (25, 67), (25, 68), (26, 65), (26, 66),(26, 67), (26, 68), (26, 69), (27, 66), (27, 67), (27, 68),(27, 69), (28, 67), (28, 68)], dtype=object) >>> b = np.insert(a, 0, 8, axis=1) Output: array([[8, 25, 65], [8, 25, 66], [8, 25, 67], ...
3
2
74,943,259
2022-12-28
https://stackoverflow.com/questions/74943259/minmax-scaling-on-numpy-array-multiple-dimensions
How to minmax normalize in the most efficient way, a XD-numpy array in "columns" of each 2D matrix of the array. For example with a 3D-array : a = np.array([[[ 0, 10], [ 20, 30]], [[ 40, 50], [ 60, 70]], [[ 80, 90], [100, 110]]]) into the normalized array : b = np.array([[[0., 0.], [1., 1.]], [[0., 0.], [1., 1.]], [[0...
With sklearn.preprocessing.minmax_scale + numpy.apply_along_axis single applying: from sklearn.preprocessing import minmax_scale a = np.array([[[0, 10], [20, 30]], [[40, 50], [60, 70]], [[80, 90], [100, 110]]]) a_scaled = np.apply_along_axis(minmax_scale, 1, a) # a_scaled [[[0. 0.] [1. 1.]] [[0. 0.] [1. 1.]] [[0. 0.]...
3
2
74,941,669
2022-12-28
https://stackoverflow.com/questions/74941669/how-to-interpret-the-output-of-statsmodels-model-summary-for-multivariate-line
I'm using the statsmodels library to check for the impact of confounding variables on a dependent variable by performing multivariate linear regression: model = ols(f'{metric}_diff ~ {" + ".join(confounding_variable_names)}', data=df).fit() This is how my data looks like (pasted only 2 rows): Age Sex Experience using...
This is more of a stats question but I'll do my best to help. A multivariate regression is of the form: Where, Y, B, and, U are vectors associated with the dependent variable, coefficients, and error terms respectively. X then is the design matrix that houses all of your predictor variables. Such as Age, Glasses, etc....
3
5
74,940,964
2022-12-28
https://stackoverflow.com/questions/74940964/how-to-extend-sqlalchemy-base-class-with-a-static-method
I have multiple classes similar to the following: class Weather(Base): __tablename__ = "Weather" id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) temperature = Column(Integer) humidity = Column(Integer) wind_speed = Column(Float) wind_direction = Column(String) I want to add a method df() tha...
Declare an auxiliary class (say DfBase) with classmethod df(cls) having the desired behavior. Then each derived class will access its __tablename__ attribute seamlessly via cls object which refers to the derived class itself. class DfBase: __tablename__ = None @classmethod def df(cls): with engine.connect() as conn: re...
3
2
74,941,247
2022-12-28
https://stackoverflow.com/questions/74941247/mypy-using-other-pyhton-version-as-in-venv-positional-only-parameters-are-only
MyPy thinks it has to check for Python <3.8 when instead it should use 3.10 As you can see, Python3.10 is active (myvenv) gitpod /workspace/myfolder (mybranch) $ python --version Python 3.10.7 however mypy think its <3.8? (myvenv) gitpod /workspace/myfolder (mybranch) $ mypy -p my_folder_with_code /workspace/.pyenv_m...
Ok, i found it out miself. Apparently it was a bug in mypy. Update MyPy and it works again pip install -U mypy Or in my case poetry update mypy
5
6
74,940,265
2022-12-28
https://stackoverflow.com/questions/74940265/apply-custom-function-on-all-columns-increase-efficiency
I apply this function def calculate_recency_for_one_column(column: pd.Series) -> int: """Returns the inverse position of the last non-zero value in a pd.Series of numerics. If the last value is non-zero, returns 1. If all values are non-zero, returns 0.""" non_zero_values_of_col = column[column.astype(bool)] if non_zer...
You can treat columns not as Series objects but as numpy arrays. To do this, simply specify the raw=True parameter in the apply method. also need to slightly change the original function. import time import numpy as np import pandas as pd def calculate_recency_for_one_column(column: np.ndarray) -> int: """Returns the i...
3
3
74,939,164
2022-12-28
https://stackoverflow.com/questions/74939164/i-want-to-validate-password-for-user-input-in-fastapi-python
i need a password validation in fastapi python, in this when user signup and create a password and passowrd are too sort not capital letter, special character etc. than fastapi give validation error i make a password validation code in python but i don't know how to use in fastapi def validate_password(s): l, u, p, d =...
You can import validator from Pydantic and fill it by your field name of your schema (in this case "password"). Usage in your schema file: from pydantic import BaseModel, validator class User(BaseModel): password: str @validator("password") def validate_password(cls, password, **kwargs): # Put your validations here ret...
3
6
74,938,890
2022-12-28
https://stackoverflow.com/questions/74938890/transform-n-columns-into-rows
i am looking for a way to disaggregate data from a single row in a pandas df. My data looks like this edit: n stands for an unspecified number, e.g. in my working dataset I have 8 plots giving me 8 x 2 = 16 columns I would like to transform. data = { 'key':['k1', 'k2'], 'plot_name_1':['name', 'name'], 'plot_area_1':[1,...
pd.wide_to_long can do this: In [160]: pd.wide_to_long(df, stubnames=["plot_name", "plot_area"], i="key", j="plot_number", sep="_", suffix=r"(?:\d+|n)").reset_index() Out[160]: key plot_number plot_name plot_area 0 k1 1 name 1 1 k2 1 name 2 2 k1 2 name 1 3 k2 2 name 2 4 k1 n name 1 5 k2 n name 2 where "stubnames" are...
3
5
74,936,196
2022-12-28
https://stackoverflow.com/questions/74936196/how-should-i-organize-my-path-operations-in-fastapi
I am creating an application with FastAPI and so far it goes like this: But I'm having a problem with the endpoints. The /api/items/filter route has two query parameters: name and category. However, it gives me the impression that it is being taken as if it were api/items/{user_id}/filter, since when I do the validati...
Ordering your endpoints matters! Endpoints are matched in order they are declared in your FastAPI object. Let say you have only two endpoints, in this order: api/items/{user_id} api/items/filter In this order, when you request endpoint api/items/user_a, your request will be routed to (1) api/items/{user_id}. However,...
4
4
74,877,580
2022-12-21
https://stackoverflow.com/questions/74877580/discover-missing-module-using-command-line-dll-load-failed-error
On Windows, when we try to import a .pyd file, and a DLL that the .pyd depends on cannot be found, we get this traceback: Traceback (most recent call last): ... ImportError: DLL load failed: The specified module could not be found. When this happens, often one has to resort to a graphical tool like Dependencies to fig...
First, let's chose a concrete example: NumPy's _multiarray_umath*.pyd (from Python 3.9 (pc064)). Note that I'll be reusing this console: [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q074877580]> sopr.bat ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### [prompt]> [prompt]> "e:\Wor...
7
4
74,904,389
2022-12-23
https://stackoverflow.com/questions/74904389/how-to-check-if-pyspark-dataframe-is-empty-quickly
I'm trying to check if my pyspark dataframe is empty and I have tried different ways to do that, like: df.count() == 0 df.rdd.isEmpty() df.first().isEmpty() But all this solutions are to slow, taking up to 2 minutes to run. How can I quicly check if my pyspark dataframe is empty or not? Do anyone have a solution for t...
The best way to check if your dataframe is empty or not after reading a table or at any point in time is by using limit(1) first which will reduce the number of rows to only 1 and will increase the speed of all the operation that you are going to do for dataframe checks. df.limit(1).count() == 0 df.limit(1).rdd.isEmpty...
4
3
74,895,640
2022-12-23
https://stackoverflow.com/questions/74895640/how-to-do-regression-simple-linear-for-example-in-polars-select-or-groupby-con
I am using polars in place of pandas. I am quite amazed by the speed and lazy computation/evaluation. Right now, there are a lot of methods on lazy dataframe, but they can only drive me so far. So, I am wondering what is the best way to use polars in combination with other tools to achieve more complicated operations, ...
If you want to pass multiple columns to a function, you have to pack them into a Struct as polars expression always map from Series -> Series. Because polars does not use numpy memory which statsmodels does, you must convert the polars types to_numpy. This is often free in case of 1D structures. Finally, the function s...
11
9
74,902,695
2022-12-23
https://stackoverflow.com/questions/74902695/multiple-aggregations-on-multiple-columns-in-python-polars
Checking out how to implement binning with Python polars, I can easily calculate aggregates for individual columns: import polars as pl import numpy as np t, v = np.arange(0, 100, 2), np.arange(0, 100, 2) df = pl.DataFrame({"t": t, "v0": v, "v1": v}) df = df.with_columns((pl.datetime(2022,10,30) + pl.duration(seconds=d...
There are various ways of selecting multiple columns "at once" in polars: df.select(pl.all()).columns # ['v0', 'v1', 'datetime'] df.select(pl.col("v0", "v1")).columns # by name(s) # ['v0', 'v1'] df.select(pl.exclude("datetime")).columns # by exclusion # ['v0', 'v1'] The output column names can be controlled using the ...
3
3
74,917,772
2022-12-26
https://stackoverflow.com/questions/74917772/how-to-make-an-empty-tensor-in-pytorch
In python, we can make an empty list easily by doing a = []. I want to do a similar thing but with Pytorch tensors. If you want to know why I need that, I want to get all of the data inside a given dataloader (to create another customer dataloader). Having an empty tensor can help me gather all of the data inside a ten...
We can do this using torch.empty. But notice torch.empty needs dimensions and we should give 0 to the first dimension to have an empty tensor. The code will be like this: # suppose the data generated by the dataloader has the size of (batch, 25) all_data_tensor = torch.empty((0, 25), dtype=torch.float32) # first dimens...
9
8
74,917,051
2022-12-26
https://stackoverflow.com/questions/74917051/tensorflow-error-on-macbook-m1-pro-notfounderror-graph-execution-error
I've installed Tensorflow on a Macbook Pro M1 Max Pro by first using Anaconda to install the dependencies: conda install -c apple tensorflow-deps Then after, I install the Tensorflow distribution that is specific for the M1 architecture and additionally a toolkit that works with the Metal GPUs: pip install tensorflow-...
After extensive searching, this is due to the dependencies with Anaconda compared to the Tensorflow version installed via pip: conda list | grep tensorflow tensorflow-deps 2.9.0 0 apple tensorflow-estimator 2.11.0 pypi_0 pypi tensorflow-macos 2.11.0 pypi_0 pypi tensorflow-metal 0.7.0 pypi_0 pypi The version of Tensorf...
3
11
74,886,164
2022-12-22
https://stackoverflow.com/questions/74886164/pycharm-doesnt-recognize-packages-with-remote-interpreter
TL;DR - This is a PyCharm remote interpreter question. Remote libraries are not properly synced, and PyCharm is unable to index properly when using remote interpreter. Everything runs fine. Following is the entire (currently unsuccessful) debug process See update section for a narrowing down of the problem I am using ...
The problem was a file in one of the packages (uvrabbit) which is named aux.py. Naming files aux in Windows is forbidden. Good to know. This made the auto-unpacking crash, and thus the indexing failed. It also made it so git clone fails [which is how I found it eventually]. When manually unpacking, Winrar renamed aux.p...
12
4
74,885,225
2022-12-22
https://stackoverflow.com/questions/74885225/cast-features-to-classlabel
I have a dataset with type dictionary which I converted to Dataset: ds = datasets.Dataset.from_dict(bio_dict) The shape now is: Dataset({ features: ['id', 'text', 'ner_tags', 'input_ids', 'attention_mask', 'label'], num_rows: 8805 }) When I use the train_test_split function of Datasets I receive the following error: t...
You should apply the following class_encode_column function: ds = ds.class_encode_column("label")
8
9
74,923,308
2022-12-26
https://stackoverflow.com/questions/74923308/how-can-i-keep-poetry-and-commitizen-versions-synced
I have a pyproject.toml with [tool.poetry] name = "my-project" version = "0.1.0" [tool.commitizen] name = "cz_conventional_commits" version = "0.1.0" I add a new feature and commit with commit message feat: add parameter for new feature That's one commit. Then I call commitizen bump Commitizen will recognize a minor...
refer to support-for-pep621 and version_files you can add "pyproject.toml:^version" to pyproject.toml: [tool.commitizen] version_files = [ "pyproject.toml:^version" ]
7
6
74,892,481
2022-12-22
https://stackoverflow.com/questions/74892481/how-to-authenticate-a-github-actions-workflow-as-a-github-app-so-it-can-trigger
By default (when using the default secrets.GITHUB_TOKEN) GitHub Actions workflows can't trigger other workflows. So for example if a workflow sends a pull request to a repo that has a CI workflow that normally runs the tests on pull requests, the CI workflow won't run for a pull request that was sent by another workflo...
Links: Working demo repo Workflow that sends PRs Example PR sent by the workflow (notice that the ci.yml workflow was automatically triggered on the PR) Workflow run that sent the PR To create a GitHub App and a workflow that authenticates as that app and sends PRs that can trigger other workflows: Create a GitHub A...
4
5
74,904,221
2022-12-23
https://stackoverflow.com/questions/74904221/how-to-switch-page-on-button-click-using-streamlit
I have made separate functions for each page, but i want to change page to file upload when I click button on welcome_page.py. Found a switch_page function but I don't think I understand how it works. import streamlit as st from login import check_password from file_upload import file_upload from welcome import welcome...
Unfortunately, there isn't a built-in way to switch pages programmatically in a Streamlit multipage app. There is an open feature request here if you'd like to upvote it.
4
2
74,892,927
2022-12-22
https://stackoverflow.com/questions/74892927/seaborn-lineplot-typeerror-ufunc-isfinite-not-supported-for-the-input-types
I am getting the following error when trying to plot a lineplot with seaborn. TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Minimal example reproducing error: import matplotlib.pyplot as plt import...
Numpy 1.24.0 has a bug that causes an exception within several seaborn functions. The bug has been fixed and numpy has released a new version to address it. The solution is to install numpy 1.24.1 the same way that you installed numpy 1.24.0.
9
12
74,894,318
2022-12-22
https://stackoverflow.com/questions/74894318/how-can-i-match-a-pattern-and-then-everything-upto-that-pattern-again-so-matc
Context I have the following paragraph: text = """ בביהכנ"ס - בבית הכנסת דו"ח - דין וחשבון הת"ד - התיקוני דיקנא בגו"ר - בגשמיות ורוחניות ה"א - ה' אלוקיכם התמי' - התמיהה בהנ"ל - בהנזכר לעיל ה"א - ה' אלקיך ואח"כ - ואחר כך בהשי״ת - בהשם יתברך ה"ה - הרי הוא / הוא הדין ואת"ה - ואיגוד תלמידי """ this paragraph is combined w...
You can do something like this: import re pattern = r'(\b[\u05D0-\u05EA]*\"\b[\u05D0-\u05EA]*\b)\s*-\s*([^"]+)(\s|$)' text = """בביהכנ"ס - בבית הכנסת דו"ח - דין וחשבון הת"ד - התיקוני דיקנא""" for word, acronym, _ in re.findall(pattern, text): print(word + ' == ' + acronym) which outputs בביהכנ"ס == בבית הכנסת דו"ח == ...
3
1
74,871,172
2022-12-21
https://stackoverflow.com/questions/74871172/python-how-to-speed-up-this-function-and-make-it-more-scalable
I have the following function which accepts an indicator matrix of shape (20,000 x 20,000). And I have to run the function 20,000 x 20,000 = 400,000,000 times. Note that the indicator_Matrix has to be in the form of a pandas dataframe when passed as parameter into the function, as my actual problem's dataframe has time...
Assuming the answer of @CrazyChucky is correct, one can implement a faster parallel Numba implementation. The idea is to use plain loops and care about reading data the contiguous way. Reading data contiguously is important so to make the computation cache-friendly/memory-efficient. Here is an implementation: import nu...
4
8
74,922,884
2022-12-26
https://stackoverflow.com/questions/74922884/dynamically-change-tray-icon-with-pystray
I want the tray icon to change according to the value of p_out. Specifically depending on its value, I want it to get a different color. Here's the code import pystray import ping3 while True: p_out = ping3.ping("google.com", unit="ms") if p_out == 0: img = white elif p_out >= 999: img = red else: print(f'\n{p_out:4.0f...
As correctly stated in the comments, providing code that cannot run, does not help the community members to assist you. Τhe code references variables named white, red, green, yellow and orange, but these variables have not been defined or assigned values. Despite all this, the dynamic update of the tray icon is certain...
5
9
74,893,922
2022-12-22
https://stackoverflow.com/questions/74893922/sublime-text-4-folding-python-functions-with-a-line-break
I'm running Sublime Text Build 4143. Given a function with parameters that spill over the 80 character limit like so: def func(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6): """ """ print("hello world") return ST will show a PEP8 E501: line too long warning and highlight the line (which...
This is not a "fair" answer, but may be helpful. If you use black-like line folding (or anything similar, but with one important property: the closing parenthesis should be on its own line and be indented to the same level as def, see below), then folding works even better: def func( parameter_1, parameter_2, parameter...
3
1
74,925,822
2022-12-27
https://stackoverflow.com/questions/74925822/how-to-shorten-the-command-when-filtering-data-frame-in-python
In Python, a common way to filter a data frame is like this df.loc[(df['field 1'] == 'a') & (df['field 2'] == 'b'), 'field 3']... When df name is long, or when there are more filter conditions (only two in the above), the above line will be long naturally. Moreover, it is a bit tedious to have type out df name for eac...
you can use the query method as follows which is has an SQL like syntax df.query('field_1 == "a" and field_2 == "b" and field_3 > 3.2 ') Here are the docs for it https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html
3
3
74,910,247
2022-12-24
https://stackoverflow.com/questions/74910247/python-multiprocessing-sharing-variables-between-processes
I'm trying to write a multiprocessing program which shares one or more variables (values or matrix) between the child processes. In my current test program I'm trying to spawn two processes, each sharing the num variable. Each adds 1 to the variable and then prints. However, whenever I try to run the program it tells m...
You have several issues with your code: When you create a multiprocessing.Value instance (num in your case), you must use the value attribute of that instance to read or write actual value of that shared variable. Incrementing such an instance, even if you replace num.value = num.value + 1 with num.value += 1 as I hav...
4
5
74,930,893
2022-12-27
https://stackoverflow.com/questions/74930893/how-to-modify-in-channel-of-the-firstly-layer-cnn-in-the-timm-model
everyone. I hope to train a CV model in the timm library on my dataset. Due to the shape of the input data is (batch_size, 15, 224, 224), I need to modify the "in_channel" of the first CNN layer of different CV models. I try different methods but still fail. Could you help me solve this problem? Thanks! import torch im...
Do you want to change the first conv2d layer of resnet200d? Let me point out a few things that went wrong here. Changing only the value of in_channels does not change the shape of the weight. resnet200d is composed of sequential layers and has a conv2d layer in them. So, you cannot access conv2d with a for statement l...
4
1
74,930,922
2022-12-27
https://stackoverflow.com/questions/74930922/how-to-load-a-custom-julia-package-in-python-using-pythons-juliacall
I already know How to import Julia packages into Python. However, now I have created my own simple Julia package with the following command: using Pkg;Pkg.generate("MyPack");Pkg.activate("MyPack");Pkg.add("StatsBase") where the file MyPack/src/MyPack.jl has the following contents: module MyPack using StatsBase function...
You need to run the following code to load the MyPack package from Python via juliacall from juliacall import Main as jl from juliacall import Pkg as jlPkg jlPkg.activate("MyPack") # relative path to the folder where `MyPack/Project.toml` should be used here jl.seval("using MyPack") Now you can use the function (note ...
11
10
74,934,472
2022-12-27
https://stackoverflow.com/questions/74934472/use-on-bad-lines-to-write-invalid-rows-from-pandas-read-csv-to-a-file
I have a CSV file in which I am using Python to parse. I found that some rows in the file have different number of columns. 001;Snow,Jon;19801201 002;Crom,Jake;19920103 003; ;Wise,Frank;19880303 <-- Invalid row 004;Wiseau,Tommy;4324;1323;2323 <-- Invalid row I would like to write these invalid rows into a separate tex...
Since pandas 1.4.0 allows callable for on_bad_lines parameter - that allows you to apply a more sophisticated handling of bad lines. New in version 1.4.0: callable, function with signature (bad_line: list[str]) -> list[str] | None that will process a single bad line. bad_line is a list of strings split by the sep. If...
3
10
74,922,314
2022-12-26
https://stackoverflow.com/questions/74922314/yield-from-vs-yield-in-for-loop
My understanding of yield from is that it is similar to yielding every item from an iterable. Yet, I observe the different behavior in the following example. I have Class1 class Class1: def __init__(self, gen): self.gen = gen def __iter__(self): for el in self.gen: yield el and Class2 that different only in replacing ...
What Happened? When you use next(iter(instance_of_Class2)), iter() calls .close() on the inner generator when it (the iterator, not the generator!) goes out of scope (and is deleted), while with Class1, iter() only closes its instance >>> g = (i for i in range(3)) >>> b = Class2(g) >>> i = iter(b) # hold iterator open ...
32
27
74,933,956
2022-12-27
https://stackoverflow.com/questions/74933956/laplace-correction-with-conditions-for-smoothing
I have a data (user_data) that represent the number of examples in each class (here we have 5 classes), for example in first row, 16 represent 16 samples in class 1 for user1, 15 represent that there is 15 samples belong to class 2 for user 1, ect. user_data = np.array([ [16, 15, 14, 10, 0], [0, 13, 6, 15, 21], [12, 29...
I have noticed that your smoothing approach will cause P > 1, you are to clip or normalize the values later on: probs = user_data/55 alpha = (user_data+1)/(55+2) extreme_values_mask = (probs == 0) | (probs == 1) probs[extreme_values_mask] = alpha[extreme_values_mask] Result: array([[0.29090909, 0.27272727, 0.25454545,...
3
1
74,933,637
2022-12-27
https://stackoverflow.com/questions/74933637/order-of-operations-python
The order of operations in my code seems off... numbers=[7, 6, 4] result = 1 for num in numbers: result *= num - 3 print(result) In this code, I would expect the following to occur... result=1 result = 1 * 7 - 3 = 7 - 3 = 4 result = 4 * 6 - 3 = 24 - 3 = 21 result = 21 * 4 - 3 = 84 - 3 = 81 HOWEVER, running the progr...
Why with the *= operator is the order of operations altered? The *= is not an operator, it's delimiter. Check the '2. Lexical analysis' of 'The Python Language Reference': The following tokens are operators: + - * ** / // % @ << >> & | ^ ~ := < > <= >= == != The following tokens serve as delimiters in the grammar...
3
1
74,930,714
2022-12-27
https://stackoverflow.com/questions/74930714/why-async-function-binds-name-incorrectly-from-the-outer-scope
Here is an async function generator by iterating a for loop. I expected this closure to respect the names from the outer scope. import asyncio coroutines = [] for param in (1, 3, 5, 7, 9): async def coro(): print(param ** 2) # await some_other_function() coroutines.append(coro) # The below code is not async, I made a p...
The included code does not run asynchronously or uses coro as a closure. Functions are evaluated at runtime in python. An asynchronous solution would look like this import asyncio def create_task(param): async def coro(): await asyncio.sleep(1) # make async execution noticeable print(param ** 2) return coro # return cl...
3
2
74,899,215
2022-12-23
https://stackoverflow.com/questions/74899215/how-to-increase-the-number-of-vertices
I need a parametric form for a matplotlib.path.Path. So I used the .vertices attribute, and it works fine except that the number of points given is too low for the use I want. Here is a code to illustrate : import numpy as np from matplotlib import pyplot as plt import matplotlib.patches as mpat fig, ax = plt.subplots(...
It's not ideal, but you can just loop over many shorter arcs, e.g.,: import numpy as np from matplotlib import pyplot as plt import matplotlib.patches as mpat fig, ax = plt.subplots() ax.set(xlim=(-6, 6), ylim=(-6, 6)) # generate a circular path dr = 30 # change this to control the number of points path = np.empty((0, ...
4
1
74,928,049
2022-12-27
https://stackoverflow.com/questions/74928049/how-to-multiply-all-columns-with-each-other
I have a pandas dataframe and I want to add to it new features, like this: Say I have features X_1,X_2,X_3 and X_4, then I want to add X_1 * X_2, X_1 * X_3, X_1 * X_4, and similarly X_2 * X_3, X_2 * X_4 and X_3 * X_4. I want to add them, not replace the original features. How do I do that?
for c1, c2 in combinations(df.columns, r=2): df[f"{c1} * {c2}"] = df[c1] * df[c2] you can take every r = 2 combination of the columns, multiply them and assign. Example run: In [66]: df Out[66]: x1 y1 x2 y2 0 20 5 22 10 1 25 8 27 2 In [67]: from itertools import combinations In [68]: for c1, c2 in combinations(df.colu...
3
1
74,921,764
2022-12-26
https://stackoverflow.com/questions/74921764/how-to-display-plotly-dash-on-python-to-a-website
I have created many interactive graphs on Plotly Dash (using Python) that are working perfectly on the local port. But I would like to integrate this into other products on a website. Is this possible? What would be the best way to display exactly what I'm seeing on my local port? I have read that we may use <iframe> f...
This is a somewhat open-ended question, but I would recommend following @Federico Tartarini's excellent YouTube guide here that will allow you to deploy your plotly-dash app to Google Cloud. His video will provide more exact instructions than I'll be able to type in this answer, but I'll summarize the main points: You’...
3
1
74,925,007
2022-12-27
https://stackoverflow.com/questions/74925007/python-package-exists-on-pypi-but-cant-install-it-via-pip
The package PyAudioWPatch is shown as available on PyPi with a big old green check mark. https://pypi.org/project/PyAudioWPatch/ However when I try to install it, I am getting the following error: % pip install PyAudioWPatch ERROR: Could not find a version that satisfies the requirement PyAudioWPatch (from versions: no...
The project has only wheels for Windows, and your system is not Windows, hence the error. And I should assume that to be by design, because it declares to be a PortAudio fork with WASAPI loopback support. As WASAPI is a Windows thing, it does not make sense to install it on a non Windows system. IMHO, you'd better inst...
4
7
74,882,136
2022-12-21
https://stackoverflow.com/questions/74882136/memory-efficient-dot-product-between-a-sparse-matrix-and-a-non-sparse-numpy-matr
I have gone through similar questions that has been asked before (for example [1] [2]). However, none of them completely relevant for my problem. I am trying to calculate a dot product between two large matrices and I have some memory constraint that I have to meet. I have a numpy sparse matrix, which is a shape of (10...
TL;DR: SciPy consumes significantly more memory than strictly needed for this due to temporary arrays, type promotion, and due to an inefficient usage. It is also not very fast. The setup can be optimized so to use less memory and Numba can be used to perform the computation efficiently (both for the memory usage and t...
5
4
74,924,478
2022-12-26
https://stackoverflow.com/questions/74924478/python-eval-fails-to-regonize-numpy-and-math-symbols-if-used-together-with-a-d
I have the following formula that I would like to evaluate: import math import numpy as np formula = 'np.e**x + math.erf(x) + np.pi + math.erf(u)' I can easily then evaluate the formula for given float values of x and u and eval() recognizes math.erf, np.pi and np.e. For example: x=1.0; u=0.3; eval(formula) yields 7....
Passing var as globals to eval() means the global names np and math are not available to the expression (formula). Simply pass var as locals instead. var = {'x': 1.0, 'u': 0.3} eval(formula, None, var) # -> 7.031202034457681 Note that this code doesn't work with arrays since the math module only works on scalars.
3
4
74,920,178
2022-12-26
https://stackoverflow.com/questions/74920178/minmaxscaler-for-a-number-of-columns-in-a-pandas-dataframe
I want to apply MinmaxScaler on a number of pandas DataFrame 'together'. Meaning that I want the scaler to perform on all data in those columns, not separately on each column. My DataFrame has 20 columns. I want to apply the scaler on 12 of the columns at the same time. I have already read this. But it does not solve m...
IIUC, you want the sklearn scaler to fit and transform multiple columns with the same criteria (in this case min and max definitions). Here is one way you can do this - You can save the initial shape of the columns and then transform the numpy array of those columns into a 1D array from a 2D array. Next you can fit yo...
3
1
74,895,750
2022-12-23
https://stackoverflow.com/questions/74895750/should-i-use-poetry-in-production-dockerfile
I have a web app built with a framework like FastAPI or Django, and my project uses Poetry to manage the dependencies. I didn't find any topic similar to this. The question is: should I install poetry in my production dockerfile and install the dependencies using the poetry, or should I export the requirements.txt and ...
There's no need to use poetry in production. To understand this we should look back to what the original reason poetry exists. There are basically two main reasons for poetry:- To manage python venv for us - in the past people use different range of tools, from home grown script to something like virtualenvwrapper to ...
7
13
74,916,685
2022-12-26
https://stackoverflow.com/questions/74916685/installing-greenlet-with-pip-fails-on-macos-13-1
I am trying to install greenlet in a virtualenv on my mac. pip install greenlet This renders the following output: Collecting greenlet Using cached greenlet-2.0.1.tar.gz (163 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: greenlet Building wheel for greenlet (setup.py) ... error err...
Solution: Turns out my whole pip/python-versions etc. mess was causing the issue. I followed this wonderfully written article and everything is working now: https://gist.github.com/MuhsinFatih/ee0154199803babb449b5bb98d3475f7
3
0
74,917,035
2022-12-26
https://stackoverflow.com/questions/74917035/dont-truncate-columns-output
I am setting the options like this pd.options.display.max_columns = None When I try to print the DataFrame, I get truncated columns: <class 'pandas.core.frame.DataFrame'> Index(['contractSymbol', 'strike', 'currency', 'lastPrice', 'change', 'volume', 'bid', 'ask', 'contractSize', 'lastTradeDate', 'impliedVolatility', ...
I think you need to set the display size to a larger value. According to the documentation, display.max_columns defines the behavior taken when max_cols is exceeded. I'm not sure if this is referring to the number of columns, or the width of all columns. In either case, setting display.width to a larger value: pd.optio...
3
2
74,913,169
2022-12-25
https://stackoverflow.com/questions/74913169/how-can-i-make-pdf2image-work-with-pdfs-that-have-paths-containing-chinese-chara
Following this question, I tried to run the following code to convert PDF with a path that contains Chinese characters to images: from pdf2image import convert_from_path images = convert_from_path('path with Chinese character in it/some Chinese character.pdf', 500) # save images I got this error message: PDFPageCountE...
You could use the convert_from_bytes to avoid the issue: from pdf2image import convert_from_bytes with open('chinese_filename.pdf', 'rb') as f: images = convert_from_bytes(f.read(), 500)
3
2
74,904,866
2022-12-24
https://stackoverflow.com/questions/74904866/repeated-categorical-x-axis-labels-in-matplotlib
I have a simple question: why are my x-axis labels repeated? Here's an MWE: X-Axis Labels MWE a = { # DATA -- 'CATEGORY': (VALUE, ERROR) 'Cats': (1, 0.105), 'Dogs': (2, 0.023), 'Pigs': (2.6, 0.134) } compositions = list(a.keys()) # MAKE INTO LIST a_vals = [i[0] for i in a.values()] # EXTRACT VALUES a_errors = [i[1] fo...
You can use bax.locator_params(axis='x', nbins=len(compositions)) to reduce the number of x-ticks so that it matches the length of compositions. More on locator_params() method, which controls the behavior of major tick locators: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.locator_params.html import ...
3
2
74,910,864
2022-12-24
https://stackoverflow.com/questions/74910864/why-is-the-included-in-removeprefix-definition
In PEP-616, the specification for removeprefix() includes this code block: def removeprefix(self: str, prefix: str, /) -> str: if self.startswith(prefix): return self[len(prefix):] else: return self[:] Why does the last line say return self[:], instead of just return self?
[:] is an old idiom for copying sequences. Nowadays, we use the idiomatic .copy for lists; there isn't normally a good reason to copy strings, since they are supposed to be immutable, so the str class doesn't provide such a method. Furthermore, due to string interning, [:] may well return the same instance anyway. So, ...
4
7
74,910,159
2022-12-24
https://stackoverflow.com/questions/74910159/sort-a-pandas-dataset-by-date
I have a CSV dataset like this. import pandas as pd from io import StringIO data=""" Date| Link April 1, 2009, 12:00 PM| 4 March 27, 2009, 12:00 PM| 8 April 29, 2009, 12:00 PM| 15 May 12, 2009, 12:00 PM| 9 June 9, 2009, 12:00 PM| 11 July 3, 2009, 12:00 PM| 329 June 16, 2009, 12:00 PM| 12 September 26, 2009, 12:00 PM| 4...
You can convert the Date column to datetime objects, and then use .sort_values: df["Date"] = pd.to_datetime(df["Date"]) df.sort_values("Date") This outputs: Date Link 1 2009-03-27 12:00:00 8 0 2009-04-01 12:00:00 4 12 2009-04-01 12:00:00 4 2 2009-04-29 12:00:00 15 3 2009-05-12 12:00:00 9 4 2009-06-09 12:00:00 11 6 20...
3
2
74,909,057
2022-12-24
https://stackoverflow.com/questions/74909057/if-dataframe-column-has-specific-words-alter-value
I have a dataframe, example: df = [{'id': 1, 'text': 'text contains ok words'}, , {'id':2, 'text':'text contains word apple'}, {'id':3, 'text':'text contains words ok'}] Example: keywords = ['apple', 'orange', 'lime'] And I want to check all columns 'text' to check if contains any word from my keywords, if so I want ...
this worked for me using pandas and a loop import pandas as pd keywords=['apple', 'orange', 'lime'] df = pd.DataFrame([{'id': 1, 'text': 'text contains ok words'}, {'id':2, 'text':'text contains word apple'}, {'id':3, 'text':'text contains words ok'}]) print(df) for i in range(len(df)): if any(word in df.iat[i,1] for w...
3
3
74,891,109
2022-12-22
https://stackoverflow.com/questions/74891109/write-import-call-same-python-module-multiple-times-runs-outdated-code
import sys import os import time MODULE_NAME = "mycode" def write_module(version): with open(MODULE_NAME+".py", "w") as f: f.write("def fun():"+os.linesep) f.write(" print('Code version:',"+str(version)+")") for i in range(5): # WRITE A PYTHON FILE AUTOMATICALLY write_module(i) # IMPORT IT if MODULE_NAME in sys.modules...
The source bytes are cached in __pycache__ directory. _validate_timestamp_pyc validates it against the source last-modified time — same without time.sleep(1) — and the source size. You can remove the pyc file before deleting the module from sys.modules. if MODULE_NAME in sys.modules: os.remove(sys.modules[MODULE_NAME]...
3
3
74,901,599
2022-12-23
https://stackoverflow.com/questions/74901599/django-where-do-you-store-non-django-py-files-in-your-app
I have three python files (two that scrape data and 1 with my functions) I'm using in my app. Each file is about 150 lines, I don't want to include this code in views.py to keep my views as clean and readable as possible. Is there a best practice to keep things tidy? A separate folder inside the app with all external n...
You could create a separate app-- it depends on how sectioned off you want things. I prefer to just include the non-django .py files in the app that you expect to use them in the most. And then import the relevant functions in views.py from there. Sample of how the import would look in views.py for a function (called f...
3
1
74,899,785
2022-12-23
https://stackoverflow.com/questions/74899785/psycopg2-errors-activesqltransaction-create-database-cannot-run-inside-a-transa
I am trying to create a Django app that creates a new database for every user when he/she signs up. I am going with this approach due to some reason. I have tried many ways using management commands and even Celery. But I am still getting the same error. 2022-12-23 07:16:07.410 UTC [49] STATEMENT: CREATE DATABASE tenan...
Use the autocommit property of the connection: from psycopg2 import sql def create_database(tenant_id): conn = psycopg2.connect(database="mydb", user="dbuser", password="mypass", host="db") cursor = conn.cursor() conn.autocommit = True #! # transaction.set_autocommit(True) #? dbname = sql.Identifier(f'tenant_{tenant_id...
3
10
74,901,020
2022-12-23
https://stackoverflow.com/questions/74901020/python-typing-mypy-errors-with-overload-overlap-when-signatures-are-different
The following code appears to generate two mypy errors: Overloaded function signatures 1 and 3 overlap with incompatible return types and Overloaded function signatures 2 and 3 overlap with incompatible return types; but all overloads have different signatures - Literal[True], Literal[False] and None do not overlap. @o...
The problem is that by writing = ... default values for every overload, you've marked the parameter as optional in every overload. A plain func_a() call matches every single overload of your function. You need to resolve that, so func_a() only matches one overload. Here's one way: @overload def func_a(*, a: Literal[Fal...
4
9
74,899,987
2022-12-23
https://stackoverflow.com/questions/74899987/create-a-list-of-lists-of-lists-in-a-single-line
This code creates a list of 25 lists of 25 lists: vals = [] for i in range(25): vals.append([]) for j in range(25): vals[i].append([]) How could I translate this code to a single line instead of using 5 lines in Python?
You can use list_comprehension. res = [[[] for _ in range(25)] for _ in range(25)] To check that result is the same, we can use numpy.ndarray.shape. >>> import numpy as np >>> np.asarray(vals).shape (25, 25, 0) >>> np.asarray(res).shape (25, 25, 0)
3
9
74,895,292
2022-12-23
https://stackoverflow.com/questions/74895292/why-do-breakpoints-in-my-function-with-a-yield-do-not-break
I am writing Python in VSCode. I have a file with two functions, and a second file that calls those function. When I put breakpoints in one of the functions, the breakpoint does not hit. Here is test2.py that has the two functions... def func1(): for i in range(10): yield i def func2(): for i in range(10): print(i) He...
You never actually advanced the generator, so it set up a generator instance for func1, but didn't begin executing it. If you want it to run out the generator, iterate the result of calling func1, e.g. replace: test2.func1() with: # Extracts and prints all items for x in test2.func1(): print(x) # Or to extract and pri...
3
2
74,894,148
2022-12-22
https://stackoverflow.com/questions/74894148/aligning-two-images-with-manual-homography
I'm creating an application that uses manual calibration to align two images. I'm trying to align them almost pixel perfectly, so I'm not relying on automatic calibration as it did not work the best for this scenario. I'm doing it manually by choosing pixels. However, the result is not what I hoped for, and I do not kn...
So I figured it out! I accidentally flipped parameters in the findHomography function. So it should be matrix, mask = cv2.findHomography(self.points_right, self.points_left, 0) And, of course, delete the offset for the homography matrix.
6
5
74,893,354
2022-12-22
https://stackoverflow.com/questions/74893354/is-literal-ellipsis-really-valid-as-paramspec-last-argument
Quote from Python docs for Concatenate: The last parameter to Concatenate must be a ParamSpec or ellipsis (...). I know what ParamSpec is, but the ellipsis here drives me mad. It is not accepted by mypy: from typing import Callable, ParamSpec, Concatenate, TypeVar, Generic _P = ParamSpec('_P') _T = TypeVar('_T') clas...
According to PEP-612's grammar, the ellipsis is not permitted in the Concatenate expression: We now augment that with two new options: a parameter specification variable (Callable[P, int]) or a concatenation on a parameter specification variable (Callable[Concatenate[int, P], int]). callable ::= Callable "[" paramete...
3
3
74,893,662
2022-12-22
https://stackoverflow.com/questions/74893662/transpose-pandas-df-based-on-value-data-type
I have pandas DataFrame A. I am struggling transforming this into my desired format, see DataFrame B. I tried pivot or melt but I am not sure how I could make it conditional (string values to FIELD_STR_VALUE, numeric values to FIELD_NUM_VALUE). I was hoping you could point me the right direction. A: Input DataFrame |FI...
You can use: # dic = {np.int64: 'NUM', object: 'STR'} (df.set_index('FIELD_A') .pipe(lambda d: d.set_axis(pd.MultiIndex.from_arrays( [d.columns, d.dtypes], # or for custom NAMES #[d.columns, d.dtypes.map(dic)], names=['FIELD_NAME', None]), axis=1) ) .stack(0).add_prefix('FIELD_').add_suffix('_VALUE') .reset_index() ) ...
6
5
74,889,280
2022-12-22
https://stackoverflow.com/questions/74889280/combine-and-fill-a-pandas-dataframe-with-the-single-row-of-another
If I have two dataframes: df1: df1 = pd.DataFrame({'A':[10,20,15,30,45], 'B':[17,33,23,10,12]}) A B 0 10 17 1 20 33 2 15 23 3 30 10 4 45 12 df2: df2 = pd.DataFrame({'C':['cat'], 'D':['dog'], 'E':['emu'], 'F':['frog'], 'G':['goat'], 'H':['horse'], 'I':['iguana']}) C D E F G H I 0 cat dog emu frog goat horse iguana ...
Use DataFrame.assign with Series by first row: df = df1.assign(**df2.iloc[0]) print (df) A B C D E F G H I 0 10 17 cat dog emu frog goat horse iguana 1 20 33 cat dog emu frog goat horse iguana 2 15 23 cat dog emu frog goat horse iguana 3 30 10 cat dog emu frog goat horse iguana 4 45 12 cat dog emu frog goat horse iguan...
4
4
74,887,536
2022-12-22
https://stackoverflow.com/questions/74887536/how-to-generate-powers-of-10-with-list-comprehension-or-numpy-functions
I am generating this series of numbers using a for loop [1.e-03 1.e-04 1.e-05 1.e-06 1.e-07 1.e-08 1.e-09 1.e-10 1.e-11 1.e-12] This is the for loop: alphas = np.zeros(10) alphas[0] = 0.001 for i in range(1,10): alphas[i] = alphas[i-1] * 0.1 My heart of hearts tells me this is not "pythonic", but my brain can't come ...
Think about what you want the range on: it's powers of 10 [10**x for x in range(-3, -13, -1)] Or 10.0**np.arange(-3, -13, -1) # or 10.0**-np.arange(3, 13) The numpy example uses a float 10.0 because in numpy, Integers to negative integer powers are not allowed Try it online
3
4
74,884,921
2022-12-22
https://stackoverflow.com/questions/74884921/how-to-add-attributes-to-a-enum-strenum
I have an enum.StrEnum, for which I want to add attributes to the elements. For example: class Fruit(enum.StrEnum): APPLE = ("Apple", { "color": "red" }) BANANA = ("Banana", { "color": "yellow" }) >>> str(Fruit.APPLE) "Apple" >>> Fruit.APPLE.color "red" How can I accomplish this? (I'm running Python 3.11.0.) This ques...
The answer is much the same as in the other question (but too long to leave in a comment there): from enum import StrEnum class Fruit(StrEnum): # def __new__(cls, value, color): member = str.__new__(cls, value) member._value_ = value member.color = color return member # APPLE = "Apple", "red" BANANA = "Banana", "yellow...
5
7
74,879,617
2022-12-21
https://stackoverflow.com/questions/74879617/vs-code-suggestions-do-not-display-documentation
My VS code suggestions will not display any documentation next to the suggestions. What settings do I need to change? I have editor>suggest>show inline details active but it is doing it. Here is mine: I want it to look like this: I am using python. I tried searching through the settings. I tried looking it up on the ...
It seems that the space is too small. This setting has been deprecated. You can use the following alternatives: Use command "ctrl + space" when you get intellisense: And this is a switch. You only need to use this command once, and you can get the prompt of this window in the future.
5
5
74,881,801
2022-12-21
https://stackoverflow.com/questions/74881801/how-to-move-a-patch-along-a-path
I am trying to animate a patch.Rectangle object using matplotlib. I want the said object to move along a path.Arc. A roundabout way to do this would be (approximately) : import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import matplotlib.patches as mpat fig, ax = plt.subplots() ax...
Here is one way to use matplotlib.path.Path to generate a path, whose vertices can be obtained using the method cleaned, to move a patch along it. I have tried to showcase how blue and red colored Rectangles can be moved along a (blue) linear path and a (red) circular path, respectively: import numpy as np from matplot...
3
1
74,882,096
2022-12-21
https://stackoverflow.com/questions/74882096/automatically-add-decorator-to-all-inherited-methods
I want in class B to automatically add the decorator _preCheck to all methods that have been inherited from class A. In the example b.double(5) is correctly called with the wrapper. I want to avoid to manually re-declare (override) the inherited methods in B but instead, automatically decorate them, so that on the call...
Decorators need to be added the class itself not the instance: from functools import wraps class A(object): def __init__(self, name): self.name = name def add(self, a, b): return a + b class B(A): def __init__(self, name, foo): super().__init__(name) self.foo = foo def _preCheck(func): @wraps(func) def wrapper(self, *a...
3
3
74,879,897
2022-12-21
https://stackoverflow.com/questions/74879897/numpy-isin-for-multi-dimmensions
I have a big array of integers and second array of arrays. I want to create a boolean mask for the first array based on data from the second array of arrays. Preferably I would use the numpy.isin but it clearly states in it's documentation: The values against which to test each value of element. This argument is flatte...
Try numpy.apply_along_axis to work with numpy.isin: np.apply_along_axis(lambda x: np.isin(a, x), axis=1, arr=b) returns array([[[ True, True, False, False, False, False, False, False, False, False]], [[False, False, True, True, False, False, False, False, False, False]], [[False, False, False, False, True, True, False...
3
4
74,878,253
2022-12-21
https://stackoverflow.com/questions/74878253/how-to-filter-3d-array-with-a-2d-mask
I have a (m,n,3) array data and I want to filter its values with a (m,n) mask to receive a (x,3) output array. The code below works, but how can I replace the for loop with a more efficient alternative? import numpy as np data = np.array([ [[11, 12, 13], [14, 15, 16], [17, 18, 19]], [[21, 22, 13], [24, 25, 26], [27, 28...
import numpy as np data = np.array([ [[11, 12, 13], [14, 15, 16], [17, 18, 19]], [[21, 22, 13], [24, 25, 26], [27, 28, 29]], [[31, 32, 33], [34, 35, 36], [37, 38, 39]], ]) mask = np.array([ [False, False, True], [False, True, False], [True, True, False], ]) output = data[mask]
3
2
74,877,323
2022-12-21
https://stackoverflow.com/questions/74877323/how-to-extract-two-values-from-dict-in-python
I'm using python3 and and i have data set. That contains the following data. I'm trying to get the desire value from this data list. I have tried many ways but unable to figure out how to do that. slots_data = [ { "id":551, "user_id":1, "time":"199322002", "expire":"199322002" }, { "id":552, "user_id":1, "time":"199322...
Lots of good answers here. If I was doing this, I would base my answer on setdefault and/or collections.defaultdict that can be used in a similar way. I think the defaultdict version is very readable but if you are not already importing collections you can do without it. Given your data: slots_data = [ { "id":551, "use...
4
2
74,873,524
2022-12-21
https://stackoverflow.com/questions/74873524/selenium-unable-to-locate-button-on-cookie-popup
I am trying to parse this website using selenium but I fail to find the buttons of the cookie popup which I need to confirm to proceed. I know that I first need to load the page and then wait for the cookie popup to appear, although that should be well handled by the sleep function. The html of the buttons inside the p...
By inspecting the HTML we can see that the button is inside a shadow root. So in order to be able to interact with the button we must first select the parent of the shadow root, which is the div element with id=usercentrics-root, and then we can select the button and click it: driver.execute_script('''return document....
4
4
74,818,677
2022-12-15
https://stackoverflow.com/questions/74818677/problem-to-install-pyproject-toml-dependencies-with-pip
I have an old project created with poetry. The pyproject.toml create by poetry is the following: [tool.poetry] name = "Dota2Learning" version = "0.3.0" description = "Statistics and Machine Learning for your Dota2 Games." license = "MIT" readme = "README.md" homepage = "Coming soon..." repository = "https://github.com/...
Multiple issues: 1. As the error message clearly states, there is an issue with the license key under the [project] section. Its value should be a table. As of December 2024, it seems like this should be fine. See specification. 2. The new pyproject.toml file that you are showing us is missing the [build-system] sectio...
7
4
74,798,626
2022-12-14
https://stackoverflow.com/questions/74798626/why-is-loginf-inf-j-equal-to-inf-0-785398-j-in-c-python-numpy
I've been finding a strange behaviour of log functions in C++ and numpy about the behaviour of log function handling complex infinite numbers. Specifically, log(inf + inf * 1j) equals (inf + 0.785398j) when I expect it to be (inf + nan * 1j). When taking the log of a complex number, the real part is the log of the abso...
See Edit 2 at the bottom of the answer for a mathematical motivation (or rather, at least, the reference to one). The value of 0.785398 (actually pi/4) is consistent with at least some other functions: as you said, the imaginary part of the logarithm of a complex number is identical with the phase angle of the number. ...
55
39
74,800,989
2022-12-14
https://stackoverflow.com/questions/74800989/how-to-add-a-duration-to-datetime-in-python-polars
Update: This was fixed by pull/5837 shape: (3, 3) ┌─────────────────────┬─────────┬──────────────┐ │ dt ┆ seconds ┆ duration0 │ │ --- ┆ --- ┆ --- │ │ datetime[μs] ┆ f64 ┆ duration[μs] │ ╞═════════════════════╪═════════╪══════════════╡ │ 2022-12-14 00:00:00 ┆ 1.0 ┆ 1µs │ │ 2022-12-14 00:00:00 ┆ 2.2 ┆ 2µs │ │ 2022-12-14 ...
Update: The values being zero is a repr formatting issue that has been fixed with this commit. pl.duration() can be used in this way: df.with_columns( pl.col("dt").str.to_datetime() + pl.duration(nanoseconds=pl.col("seconds") * 1e9) ) shape: (3, 2) ┌─────────────────────────┬─────────┐ │ dt ┆ seconds │ │ --- ┆ --- │ │...
4
4
74,814,175
2022-12-15
https://stackoverflow.com/questions/74814175/replace-value-by-null-in-polars
Given a Polars DataFrame, is there a way to replace a particular value by "null"? For example, if there's a sentinel value like "_UNKNOWN" and I want to make it truly missing in the dataframe instead.
Update: Expr.replace() has also since been added to Polars. df.with_columns(pl.col(pl.String).replace("_UNKNOWN", None)) shape: (4, 3) ┌──────┬──────┬─────┐ │ A ┆ B ┆ C │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞══════╪══════╪═════╡ │ a ┆ null ┆ 1 │ │ b ┆ d ┆ 2 │ │ null ┆ e ┆ 3 │ │ c ┆ f ┆ 4 │ └──────┴──────┴─────┘ ...
3
8
74,854,903
2022-12-19
https://stackoverflow.com/questions/74854903/not-required-in-pydantics-base-models
Im trying to accept data from an API and then validate the response structure with a Pydantic base model. However, I have the case where sometimes some fields will not come included in the response, while sometimes they do. The problem is, when I try to validate the structure, Pydantic starts complaining about those fi...
Pydantic v2 Either a model has a field or it does not. In a sense, a field is always required to have a value on a fully initialized model instance. It is just that a field may have a default value that will be assigned to it, if no value was explicitly provided during initialization. (see Basic Model Usage in the docs...
6
11
74,851,128
2022-12-19
https://stackoverflow.com/questions/74851128/language-detection-for-short-user-generated-string
I need to detect the language of text sent in chat, and I am faced with 2 problems: the length of the message the errors that may be in it and the noise (emoji etc...) For the noise, I clean the message and that works fine, but the length of the message is a problem. For example, if a user writes "hi", Fasttext detec...
I have found a way to have better results. If you sum all probabilities of all languages on different detectors like fastText and lingua, and add a dictionary-based detection for short texts, you can have very good results (for my task, I also made a fastText model trained on my data).
3
1
74,822,543
2022-12-16
https://stackoverflow.com/questions/74822543/colab-libtorch-cuda-cu-so-cannot-open-shared-object-file-no-such-file-or-dire
I'm trying to use the python package aitextgen in google Colab so I can fine-tune GPT. First, when I installed the last version of this package I had this error when importing it. Unable to import name '_TPU_AVAILABLE' from 'pytorch_lightning.utilities' Though with the help of the solutions given in this question I co...
It seems that it is due to your CUDA version (it can be the cuDNN version too) not matching the supported version by tf, torch, or jax. As of Aug 2023, If your CUDA or cuDNN versions are +12, try downgrading them. You can find your CUDA version with nvcc --version and your cuDNN version via apt list --installed | grep ...
7
1
74,826,436
2022-12-16
https://stackoverflow.com/questions/74826436/importerror-cannot-import-name-ugettext-from-django-utils-translation
I installed djangorestframework as shown below: pip install djangorestframework -jwt Then, I used rest_framework_jwt.views as shown below: from rest_framework_jwt.views import ( obtain_jwt_token, refresh_jwt_token, verify_jwt_token ) ... path('auth-jwt/', obtain_jwt_token), path('auth-jwt-refresh/',refresh_jwt_token),...
Upgrading djangorestframework-jwt will solve the error: pip install djangorestframework-jwt --upgrade
4
-1
74,829,469
2022-12-16
https://stackoverflow.com/questions/74829469/polars-native-way-to-convert-unix-timestamp-to-date
I'm working with some data frames that contain Unix epochs in ms, and would like to display the entire timestamp series as a date. Unfortunately, the docs did not help me find a polars native way to do this, and I'm reaching out here. Solutions on how to do this in Python and also in Rust would brighten my mind and day...
Adapting the answer of @jqurious. Polars has a dedicated from_epoch function for this: (pl.DataFrame({"timestamp": [1397392146866, 1671225446800]}) .with_columns( pl.from_epoch("timestamp", time_unit="ms") ) ) shape: (2, 1) ┌─────────────────────────┐ │ timestamp │ │ --- │ │ datetime[ms] │ ╞═════════════════════════╡ ...
5
15
74,797,663
2022-12-14
https://stackoverflow.com/questions/74797663/convert-timedelta-to-milliseconds-python
I have the following time: time = datetime.timedelta(days=1, hours=4, minutes=5, seconds=33, milliseconds=623) Is it possible, to convert the time in milliseconds? Like this: 101133623.0
I found a possibility to solve the problem import datetime time = datetime.timedelta(days=1, hours=4, minutes=5, seconds=33, milliseconds=623) result = time.total_seconds()*1000 print(result)
12
11
74,836,151
2022-12-17
https://stackoverflow.com/questions/74836151/nothing-provides-cuda-needed-by-tensorflow-2-10-0-cuda112py310he87a039-0
I'm using mambaforge on WSL2 Ubuntu 22.04 with systemd enabled. I'm trying to install TensorFlow 2.10 with CUDA enabled, by using the command: mamba install tensorflow And the command nvidia-smi -q from WSL2 gives: ==============NVSMI LOG============== Timestamp : Sat Dec 17 23:22:43 2022 Driver Version : 527.56 CUDA ...
I ran into this today and found a solution that works (after also seeing your GitHub post). Long story short, you need to use CONDA_OVERRIDE_CUDA to make this work as described in this conda-forge blog post. For example, with CUDA 11.8 and mamba, use: CONDA_OVERRIDE_CUDA="11.8" mamba install tensorflow -c conda-forge F...
5
13
74,818,160
2022-12-15
https://stackoverflow.com/questions/74818160/huge-margin-when-using-matplotlib-supxlabel
I am trying to add a common label in a matplotlib's subplots, but I am having some troubles. I am using python 3.10 and matplotlib 3.5.1 There is a minimal working example illustrating the problem: import matplotlib.pyplot as plt fig, axs = plt.subplots(3, 2, figsize=(8, 12), sharex=True, sharey=True) fig.supxlabel('Ex...
Edit: simplest is plt.subplots(layout='constrained'), works very nicely for all sorts of manipulations; below is if full control is desired, which 'constrained' (from what I can tell) won't permit. My current workaround is y = np.sqrt(height) / 100 * 2.2, which seems to work well at least for height from 5 to 25. If u...
5
5
74,857,446
2022-12-20
https://stackoverflow.com/questions/74857446/how-to-specify-python-version-range-in-environment-yml-file
Does it make sense to specify range of allowed Python versions in environment.yml file? I got this idea while reading the Google's Biq Query documentation Supported Python Versions Python >= 3.7, < 3.11 If this makes sense then what is the right syntax to specify the range in the environment.yml file?
Recommendation: Prefer exact version, not range While there is nothing logically incorrect with specifying a version range for Python, it has the downside of defining a large solution space, which can lead to slow solving. For practical environments, I would recommend specifying the version for python through the minor...
7
7