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,357,468
2023-2-6
https://stackoverflow.com/questions/75357468/matplotlib-supylabel-on-second-axis-of-multiplot
I'm not finding it possible to add a second supylabel for a right-hand y-axis of a multiplot. Can anyone please confirm 1) whether or not it can be done and/or 2)provide guidance on how? I am trying to achieve this: Because there are a variable number of subplots (sometimes an odd number, sometimes even) across the br...
I have found the suplabels to be a little unreliable in many cases, so I resort to low-level tricks in cases like these: import matplotlib.pyplot as plt fig = plt.figure(figsize=(4, 4)) # dummy axes 1 ax = fig.add_subplot(1, 1, 1) ax.set_xticks([]) ax.set_yticks([]) [ax.spines[side].set_visible(False) for side in ('lef...
5
2
75,354,617
2023-2-5
https://stackoverflow.com/questions/75354617/pip-install-dotenv-error-1-windows-10-pro
When I do pip install dotenv it says this - `Collecting dotenv Using cached dotenv-0.0.5.tar.gz (2.4 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [72 lines of output] C:\Users\Anju Tiwari\AppData\Local\Programs\Py...
pip install python-dotenv worked for me.
7
25
75,351,597
2023-2-5
https://stackoverflow.com/questions/75351597/how-can-i-chat-with-chatgpt-using-python
I asked ChatGPT to show me how I could use OpenAi's API to interact with it in my terminal window and it generated code which I modified a little bit in order to do what I wanted. Here is the Python code: import requests with open('../api-key.txt','r') as key: data = key.read().strip() api_key = data model="text-danvin...
I believe the engines API endpoints were deprecated in favour of models. For more info read here: https://help.openai.com/en/articles/6283125-what-happened-to-engines You will want to look at the completions endpoint instead https://platform.openai.com/docs/api-reference/completions Here's an example of the URL structu...
4
4
75,350,395
2023-2-5
https://stackoverflow.com/questions/75350395/how-should-we-manage-datetime-fields-in-sqlmodel-in-python
Let's say I want to create an API with a Hero SQLModel, below are minimum viable codes illustrating this: from typing import Optional from sqlmodel import Field, Relationship, SQLModel from datetime import datetime from sqlalchemy import Column, TIMESTAMP, text class HeroBase(SQLModel): # essential fields name: str = F...
Does [the HeroUpdate model] include the create_datetime and update_datetime fields? Well, you tell me! Should the API endpoint for updating an entry in the hero table be able to change the value in the create_datetime and update_datetime columns? I would say, obviously not. Fields like that serve as metadata about ...
5
5
75,333,446
2023-2-3
https://stackoverflow.com/questions/75333446/fastapi-create-a-generic-response-model-that-would-suit-requirements
I've been working with FastAPI for some time, it's a great framework. However real life scenarios can be surprising, sometimes a non-standard approach is necessary. There's a one case I'd like to ask your help with. There's a strange external requirement that a model response should be formatted as stated in example: D...
Generic model with static field name A generic model is a model where one field (or multiple) are annotated with a type variable. Thus the type of that field is unspecified by default and must be specified explicitly during subclassing and/or initialization. But that field is still just an attribute and an attribute mu...
5
14
75,331,219
2023-2-3
https://stackoverflow.com/questions/75331219/recursion-question-in-python-no-conditionals-or-loops
I am trying to figure out how to print the word "hello" 121 times in python. I need to use a function without conditionals or loops, no new lines, and no multiplying the string by an integer. I thinking something like: print_hello(): print('hello') print_hello() print_hello() but I can't seem to find a way to limit th...
(Note: I've edited the message. So see better solution at the end) If we don't try to find a silver bullet, using a trick that would have been forgotten in the restrictions (global variables to bypass parameters interdiction, and/try to bypass if interdiction, multiplying list to bypass multiplication of string interdi...
3
4
75,318,736
2023-2-2
https://stackoverflow.com/questions/75318736/how-do-you-analyze-the-runtime-complexity-of-a-recursive-function-with-both-expo
I'm not sure how the two recursive calls and the floor division of the following function interact regarding time complexity and big o notation. def recurse(n: int, k: int) -> int: if n <= 0 or k <= 0: return 1 return recurse(n//2, k) + recurse(n, k//2) I see how O(2^(nk)) could serve as an upper bound because the k p...
Here's an exact solution. The first thing to note is that, ignoring cases where n < 0 or k < 0, we only care about how many times we need to divide n or k by two (using floor division) before they reach zero. For example, if n = 7, then we have 7, 3, 1, 0, which is three divisions by two. The number of times a non-nega...
4
3
75,320,937
2023-2-2
https://stackoverflow.com/questions/75320937/why-doesnt-float-throw-an-exception-when-the-argument-is-outside-the-range-of
I'm using Python 3.10 and I have: a = int(2 ** 1023 * (1 + (1 - 2 ** -52))) Now, the value of a is the biggest integer value in double precision floating point format. So, I'm expecting float(a + 1) to give an OverflowError error, as noted in here: If the argument is outside the range of a Python float, an OverflowEr...
As was commented, 2**970 is the smallest addition that rounds up. This makes sense as follows: 1023 =exp - 52 =n, where the "smallest" field is 2**-n ----- 971 L G RS so, the largest is: (2**1023)*1.111...111(1)00 123...012 3 45 // bit #s ^ 555 5 55 2**1022 ^ ^ ^ ^ 2**-971 ^ ^ ^ 2**970 ...so adding 2**970 will round ...
4
3
75,312,706
2023-2-1
https://stackoverflow.com/questions/75312706/find-all-combinations-of-positive-integers-in-increasing-order-that-adds-up-to-a
How to write a function that takes n (where n > 0) and returns the list of all combinations of positive integers that sum to n? This is a common question on the web. And there are different answers provided such as 1, 2 and 3. However, in the answers provided, they use two functions to solve the problem. I want to do i...
You've got two main problems, one causing your current problem (out of memory) and one that will continue the problem even if you solve that one: You're accumulating all combinations before filtering, so your memory requirements are immense. You don't even need a single list if your function can be a generator (that i...
4
3
75,323,859
2023-2-2
https://stackoverflow.com/questions/75323859/choose-a-random-element-in-each-row-of-a-2d-array-but-only-consider-the-elements
I have a 2D array data and a boolean array mask of shapes (M,N). I need to randomly pick an element in each row of data. However, the element I picked should be true in the given mask. Is there a way to do this without looping over every row? In every row, there are at least 2 elements for which mask is true. Minimum W...
It is easier to work with the indices of the mask. We can get the indices of the True values from the mask and stack them together to create 2D coordinates array. All of the values inside the indices2d are possible to sample. Then we can shuffle the array and get the first index of the unique row values. Since the arra...
3
2
75,322,357
2023-2-2
https://stackoverflow.com/questions/75322357/how-to-run-unittest-tests-from-multiple-directories
I have 2 directories containing tests: project/ | |-- test/ | | | |-- __init__.py | |-- test_1.py | |-- my_submodule/ | |-- test/ | |-- __init__.py |-- test_2.py How can I run all tests? python -m unittest discover . only runs test_1.py and obviously python -m unittest discover my_submodule only runs test_2.py
unittest currently sees project/my_submodule as an arbitrary directory to ignore, not a package to import. Just add project/my_submodule/__init__.py to change that.
3
6
75,323,747
2023-2-2
https://stackoverflow.com/questions/75323747/polars-looping-through-the-rows-in-a-dataset
I am trying to loop through a Polars recordset using the following code: import polars as pl df = pl.DataFrame({ "start_date": ["2020-01-02", "2020-01-03", "2020-01-04"], "Name": ["John", "Joe", "James"] }) for row in df.rows(): print(row) ('2020-01-02', 'John') ('2020-01-03', 'Joe') ('2020-01-04', 'James') Is there ...
You can specify that you want the rows to be named for row in mydf.rows(named=True): print(row) It will give you a dict: {'start_date': '2020-01-02', 'Name': 'John'} {'start_date': '2020-01-03', 'Name': 'Joe'} {'start_date': '2020-01-04', 'Name': 'James'} You can then call row['Name'] Note that: previous versions re...
19
28
75,315,117
2023-2-1
https://stackoverflow.com/questions/75315117/attributeerror-connection-object-has-no-attribute-connect-when-use-df-to-sq
I am trying to store data retrieved from a website into MySQL database via a pandas data frame. However, when I make the function call df.to_sql(), the compiler give me an error message saying: AttributeError: 'Connection' object has no attribute 'connect'. I tested it couple times and I am sure that there is neither c...
I just run into this problem too. Pandas 1.x doesn't support SqlAlchemy 2 yet. As the relevant Github issue shows the next release of Pandas will require sqlalchemy<2.0. For now you have to downgrade to SqlAlchemy 1.4.x with eg : pip install --upgrade SQLAlchemy==1.4.46 The problem is caused by an incompatibility betw...
15
19
75,318,798
2023-2-2
https://stackoverflow.com/questions/75318798/in-a-2d-numpy-array-find-max-streak-of-consecutive-1s
I have a 2d numpy array like so. I want to find the maximum consecutive streak of 1's for every row. a = np.array([[1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [1, 1, 0, 1, 0], [0, 0, 0, 0, 0], [1, 1, 1, 0, 1], [1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [1, 0, 1, 1, 0], ] ) Desired Output: [5, 1, 2, 0, 3, 1, 2, 2] I have found the soluti...
The 2D equivalent of you current code would be using pad, diff, where and maximum.reduceat: # pad with a column of 0s on left/right # and get the diff on axis=1 d = np.diff(np.pad(a, ((0,0), (1,1)), constant_values=0), axis=1) # get row/col indices of -1 row, col = np.where(d==-1) # get groups of rows val, idx = np.uni...
5
6
75,316,741
2023-2-1
https://stackoverflow.com/questions/75316741/attributeerror-engine-object-has-no-attribute-execute-when-trying-to-run-sq
I have the following line of code that keeps giving me an error that Engine object has no object execute. I think I have everything right but no idea what keeps happening. It seemed others had this issue and restarting their notebooks worked. I'm using Pycharm and have restarted that without any resolution. Any help is...
There was a change from 1.4 to 2.0. The above code will run fine with sqlalchemy version 1.4 I believe. setting SQLALCHEMY_WARN_20=1 python and running the above code reveals this warning: <stdin>:1: RemovedIn20Warning: The Engine.execute() method is considered legacy as of the 1.x series of SQLAlchemy and will be remo...
25
52
75,316,207
2023-2-1
https://stackoverflow.com/questions/75316207/python-equivalent-to-as-type-assertion-in-typescript
In TypeScript you can override type inferences with the as keyword const canvas = document.querySelector('canvas') as HTMLCanvasElement; Are there similar techniques in Python3.x typing without involving runtime casting? I want to do something like the following: class SpecificDict(TypedDict): foo: str bar: str res = ...
If I understand you correctly, you're looking for typing.cast: from typing import cast res = cast(dict, request(url)) This will assert to a typechecker that res is assigned to a value that is a dictionary, but it won't have any effects at runtime.
10
7
75,315,550
2023-2-1
https://stackoverflow.com/questions/75315550/i-dont-understand-why-is-this-for-loop-so-fast
Today I was solving Project Euler's problem #43 Problem and I ran into a somewhat interesting problem. I don't understand why is my code so fast? from itertools import permutations def main(): numbers1_9 = [0,1,2,3,4,5,6,7,8,9] list_of_all_permutations = list(permutations(numbers1_9, 10)) length_of_my_list = len(list_o...
It runs so quickly because of the short-circuiting feature of logical operators. The first three conditions in the if statement are easy to calculate, and they filter out the vast majority (around 97%) of all the permutations, so you hardly ever need to execute the more expensive operations like int(str(n[4])+str(n[5])...
3
4
75,315,203
2023-2-1
https://stackoverflow.com/questions/75315203/is-the-last-parameter-of-glvertexattribpointer-a-0-or-none
I am trying to setup a simple 3D Engine in pyOpenGL. My current goal was to achieve a 2D rectangle being displayed to the screen, which isn't working at all. (nothing is being rendered to the screen, no exception is being thrown by the program.) The render method I use is following: @staticmethod def render(model: Raw...
The problem is here: glVertexAttribPointer(attribute_number, 3, GL_FLOAT, False, 0, 0) glVertexAttribPointer(attribute_number, 3, GL_FLOAT, False, 0, None) The type of the lase argument of glVertexAttribIPointer is const GLvoid *. So the argument must be None or ctypes.c_void_p(0), but not 0.
3
3
75,310,650
2023-2-1
https://stackoverflow.com/questions/75310650/how-to-get-font-path-from-font-name-python
My aim is to get the font path from their common font name and then use them with PIL.ImageFont. I got the names of all installed fonts by using tkinter.font.families(), but I want to get the full path of each font so that I can use them with PIL.ImageFont. Is there any other way to use the common font name with ImageF...
I'm not exactly sure what you really want - but here is a way to get a list of the full path to all the fonts on your system and their names and weights: #!/usr/bin/env python3 import matplotlib.font_manager from PIL import ImageFont # Iterate over all font files known to matplotlib for filename in matplotlib.font_mana...
4
1
75,313,574
2023-2-1
https://stackoverflow.com/questions/75313574/automate-the-update-of-packages-in-pyproject-toml-from-virtualenv-or-pip-tools
I am trying to update my Python CI environment and am working on package management right now. I have several reasons that I do not want to use Poetry; however, one nice feature of poetry is the fact that it automatically updates the pyproject.toml file. I know that pip-tools can create a requirements.txt file from the...
A standard tool-agnostic add command does not exist. It is being discussed here: https://discuss.python.org/t/poetry-add-but-for-pep-621/22957 I do not know if there is such a feature in pip-tools. I am pretty sure it does not exist in virtualenv, that would be quite out of scope. Your can always adopt a "dev workflow ...
6
3
75,307,905
2023-2-1
https://stackoverflow.com/questions/75307905/python-typing-for-a-metaclass-singleton
I have a Python (3.8) metaclass for a singleton as seen here I've tried to add typings like so: from typing import Dict, Any, TypeVar, Type _T = TypeVar("_T", bound="Singleton") class Singleton(type): _instances: Dict[Any, _T] = {} def __call__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: if cls not in cls._instanc...
This should work: from __future__ import annotations import typing as t _T = t.TypeVar("_T") class Singleton(type, t.Generic[_T]): _instances: dict[Singleton[_T], _T] = {} def __call__(cls, *args: t.Any, **kwargs: t.Any) -> _T: if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return...
5
7
75,308,944
2023-2-1
https://stackoverflow.com/questions/75308944/polars-case-statement
I am trying to pick up the package polars from Python. I come from an R background so appreciate this might be an incredibly easy question. I want to implement a case statement where if any of the conditions below are true, it will flag it to 1 otherwise it will be 0. My new column will be called 'my_new_column_flag' I...
pl.col selects a column with the given name (as string). What you want is a column with literal value set to one: pl.lit(1) df.with_columns( pl.when(pl.col('nrs') == 1).then(pl.lit(1)) .when(pl.col('names') == 'ham').then(pl.lit(1)) .when(pl.col('random') == 0.014575).then(pl.lit(1)) .otherwise(pl.lit(0)) .alias('my_ne...
8
10
75,308,719
2023-2-1
https://stackoverflow.com/questions/75308719/convert-a-series-of-number-become-one-single-line-of-numbers
If I have a series of numbers in a DataFrame with one column, e.g.: import pandas as pd data = [4, 5, 6, 7, 8, 9, 10, 11] pd.DataFrame(data) Which looks like this (left column = index, right column = data): 0 4 1 5 2 6 3 7 4 8 5 9 6 10 7 11 How do I make it into one sequence number, so (4 5 6 7 8 9 10 11) in python o...
You can use a f-string with conversion of the integers to string and str.join: text = f''' <Or> <numbers> <example>{" ".join(s.astype(str))}</example> </numbers> </Or>''' Output: <Or> <numbers> <example>4 5 6 7 8 9 10 11</example> </numbers> </Or>
3
2
75,308,496
2023-2-1
https://stackoverflow.com/questions/75308496/how-do-i-run-uvicorn-in-a-docker-container-that-exposes-the-port
I am developing a fastapi inside a docker container in windows/ubuntu (code below). When I test the app outside the container by running python -m uvicorn app:app --reload in the terminal and then navigating to 127.0.0.1:8000/home everything works fine: { Data: "Test" } However, when I docker-compose up I can neither ...
The issue here is that when you specify host="127.0.0.1" to uvicorn, that means you can only access that port from that same machine. Now, when you run outside docker, you are on the same machine, so everything works. But since a docker container is (at least to some degree) a different computer, you need to tell it to...
3
16
75,307,473
2023-2-1
https://stackoverflow.com/questions/75307473/how-to-read-a-sqlite-database-file-using-polars-package-in-python
I want to read a SQLite database file (database.sqlite) using polars package. I tried following unsuccessfully: import sqlite3 import polars as pl conn = sqlite3.connect('database.sqlite') df = pl.read_sql("SELECT * from table_name", conn) print(df) Getting following error: AttributeError: 'sqlite3.Connection' object ...
From the docs, you can see pl.read_sql accepts connection string as a param, and you are sending the object sqlite3.Connection, and that's why you get that message. You should first generate the connection string, which is url for your db db_path = 'database.sqlite' connection_string = 'sqlite://' + db_path And after ...
5
6
75,304,491
2023-2-1
https://stackoverflow.com/questions/75304491/difference-between-bare-except-and-specifying-a-specific-exception
I could write a simple except clause without writing an Exception in front of it. I mean, the last line could be like this : except: print('Hit an exception other than KeyError or NameError!') What is the point of writing Exception in front of an except clause? try: discounted_price(instrument, discount) except KeyErr...
A bare expect try: ... except: pass or catching any exception whatsoever try: ... except Exception: pass are bad practice, because you can be hiding bug or be interfering with the normal procedure of the program. You should only catch exception that you know how to handle, everything else you should let it propagate....
3
1
75,268,393
2023-1-28
https://stackoverflow.com/questions/75268393/yolov8-how-does-it-handle-different-image-sizes
Yolov8 and I suspect Yolov5 handle non-square images well. I cannot see any evidence of cropping the input image, i.e. detections seem to go to the enge of the longest side. Does it resize to a square 640x604 which would change the aspect ratio of objects making them more difficult to detect? When training on a custom ...
Modern Yolo versions, from v3 onwards, can handle arbitrary sized images as long as both sides are a multiple of 32. This is because the maximum stride of the backbone is 32 and it is a fully convolutional network. But there are clearly two different cases for how input images to the model are preprocessed: Training An...
12
17
75,229,981
2023-1-25
https://stackoverflow.com/questions/75229981/how-to-use-polars-cut-method-returning-result-to-original-df
Update: pl.cut was removed from Polars. Expression equivalents were added instead: .cut() .qcut() How can I use it in select context, such as df.with_columns? To be more specific, if I have a polars dataframe with a lot of columns and one of them is called x, how can I do pl.cut on x and append the grouping result int...
From the docs, as of 2023-01-25, cut takes a Series and returns a DataFrame. Unlike many/most methods and functions, it doesn't take an expression so you can't use it in a select or with_column(s). To get your desired result you'd have to join it to your original df. Additionally, it appears that cut doesn't necessaril...
5
4
75,303,038
2023-1-31
https://stackoverflow.com/questions/75303038/how-to-write-poisson-cdf-as-python-polars-expression
I have a collection of polars expressions being used to generate features for an ML model. I'd like to add a poission cdf feature to this collection whilst maintaining lazy execution (with benefits of speed, caching etc...). I so far have not found an easy way of achieving this. I've been able to get the result I'd lik...
It sounds like you want to use .map_batches() df.with_columns( pl.struct("count", "expected_count") .map_batches(lambda x: poisson.cdf(x.struct.field("count"), x.struct.field("expected_count")) ) .alias("poisson_cdf") ) shape: (5, 3) ┌───────┬────────────────┬─────────────┐ │ count | expected_count | poisson_cdf │ │ -...
3
1
75,272,909
2023-1-29
https://stackoverflow.com/questions/75272909/does-polars-module-not-have-a-method-for-appending-dataframes-to-output-files
When writing a DataFrame to a csv file, I would like to append to the file, instead of overwriting it. While pandas DataFrame has the .to_csv() method with the mode parameter available, thus allowing to append the DataFrame to a file, None of the Polars DataFrame write methods seem to have that parameter.
To append to a CSV file for example - you can pass a file object e.g. import polars as pl df1 = pl.DataFrame({"a": [1, 2], "b": [3 ,4]}) df2 = pl.DataFrame({"a": [5, 6], "b": [7 ,8]}) with open("out.csv", mode="a") as f: df1.write_csv(f) df2.write_csv(f, include_header=False) >>> from pathlib import Path >>> print(Pat...
6
8
75,268,283
2023-1-28
https://stackoverflow.com/questions/75268283/how-to-extract-date-from-datetime-column-in-polars
I am trying to move from pandas to polars but I am running into the following issue. df = pl.DataFrame( { "integer": [1, 2, 3], "date": [ "2010-01-31T23:00:00+00:00", "2010-02-01T00:00:00+00:00", "2010-02-01T01:00:00+00:00" ] } ) df = df.with_columns( pl.col("date").str.to_datetime().dt.convert_time_zone("Europe/Amster...
Update: .dt.date() has since been added to Polars. import polars as pl df = pl.DataFrame( { "integer": [1, 2, 3], "date": [ "2010-01-31T23:00:00+00:00", "2010-02-01T00:00:00+00:00", "2010-02-01T01:00:00+00:00", ], } ) df = df.with_columns( pl.col("date").str.to_datetime().dt.convert_time_zone("Europe/Amsterdam") ) df =...
6
5
75,285,711
2023-1-30
https://stackoverflow.com/questions/75285711/difference-between-collections-abc-sequence-and-typing-sequence
I was reading an article and about collection.abc and typing class in the python standard library and discover both classes have the same features. I tried both options using the code below and got the same results from collections.abc import Sequence def average(sequence: Sequence): return sum(sequence) / len(sequence...
Good on you for using type annotations! As the documentations says, if you are on Python 3.9+, you should most likely never use typing.Sequence due to its deprecation. Since the introduction of generic alias types in 3.9 the collections.abc classes all support subscripting and should be recognized correctly by static t...
13
25
75,284,417
2023-1-30
https://stackoverflow.com/questions/75284417/attributeerror-module-networkx-has-no-attribute-from-numpy-matrix
A is co occurrence dataframe. Why it shown AttributeError: module 'networkx' has no attribute 'from_numpy_matrix' import numpy as np import networkx as nx import matplotlib A=np.matrix(coocc) G=nx.from_numpy_matrix(A)
It was updated to nx.from_numpy_array(A)
15
13
75,281,114
2023-1-30
https://stackoverflow.com/questions/75281114/list-only-main-packages-with-pip-list
With pip list, we can see the install packages in our environment. There is no problem with that. We can also write them to a req.txt file with pip freeze and quickly load them in other environments with this req.txt file. My question here is, for example, when we install pandas, libraries such as numpy are installed w...
You can use --not-required flag. This will list packages that are not dependencies of installed packagespip.pypa.io. python -m pip list --not-required or if pip is in $PATH pip list --not-required
3
5
75,267,582
2023-1-28
https://stackoverflow.com/questions/75267582/python-environment-setup-seems-complicated-and-unsolvable
I've been a developer for about three years, primarily working in TypeScript and Node.js. I'm trying to broaden my skillset by learning Python (and eventually expanding my learning of computer vision, machine learning (ML), etc.), but I feel incredibly frustrated by trying to get Python to work consistently on my machi...
Instead of creating virtual environments using venv, you can use a more sophisticated tool like Poetry which enables you to manage you environments in a much better manner. I have been working on Python projects and one thing that sucks is compatibility issue with other host machines. This is where Poetry comes into th...
5
4
75,290,492
2023-1-30
https://stackoverflow.com/questions/75290492/how-to-get-model-specification-paramters-for-models-estimated-with-nixtlas-stat
I am using the statsforecast package to fit an AUTOarima model with an external regressor, which works fine. I need to get the model parameters and modify the parameter for the external regressor and rerun the model for scenario analysis. I also need a model summary to provide with my research. How can I get the model ...
Nixtla statsforecast model stores those information under the hood. There is no method like get_params() to access those, but you can do that pretty easily when you have the model trained. Please see the example below: import pandas as pd from statsforecast import StatsForecast from statsforecast.models import AutoARIM...
4
5
75,277,492
2023-1-29
https://stackoverflow.com/questions/75277492/yolov8-get-predicted-class-name
I just want to get class data in my python script like: person, car, truck, dog but my output more than this. Also I can not use results as a string. Python script: from ultralytics import YOLO model = YOLO("yolov8n.pt") results = model.predict(source="0") Output: 0: 480x640 1 person, 1 car, 7.1ms 0: 480x640 1 person,...
You can pass each class to the model's name dict like this: from ultralytics.yolo.engine.model import YOLO model = YOLO("yolov8n.pt") results = model.predict(stream=True, imgsz=512) # source already setup names = model.names for r in results: for c in r.boxes.cls: print(names[int(c)]) output: YOLOv8n summary (fused): ...
8
20
75,286,814
2023-1-30
https://stackoverflow.com/questions/75286814/flask-send-pyaudio-to-browser
I'm sending my servers microphone's audio to the browser (mostly like this post but with some modified options). All works fine, until you head over to a mobile or safari, where it doesn't work at all. I've tried using something like howler to take care of the frontend but with not success (still works in chrome and on...
EDITED 2023-03-12 It turns out that it is sufficient to convert the audio live stream to mp3. For this you can use ffmpeg. The executable has to be available in the execution path of the server process. Here is a working draft tested with windows laptop as server and Safari on iPad as client: from subprocess import Pop...
9
2
75,299,987
2023-1-31
https://stackoverflow.com/questions/75299987/boto3-get-query-runtime-statistics-sometimes-not-returning-rows-data
I have a lambda that attempts to find out whether a previously executed athena query has returned any rows or not. To do so I am using the boto3 function get_query_runtime_statistics and then extracting the "Rows" data: response = athena_client.get_query_runtime_statistics(QueryExecutionId=query_id) row_count = respons...
I raised a support ticket and got the follwoing responses: The query finished successfully but it failed as an async process of getting runtime stats. This is an internal issue and internal team is aware about it and is working on it to fix the same. I asked for clarification whether this issue only happens on querie...
4
3
75,299,506
2023-1-31
https://stackoverflow.com/questions/75299506/cannot-import-name-save-virtual-workbook-from-openpyxl-writer-excel
Is there an update to the library? Before it worked perfectly, and today I updated and it no longer loads I searched but I can't find any other option
Looks like the new recommendation from the developers is to use a temp-file: https://openpyxl.readthedocs.io/en/3.1/tutorial.html?highlight=save#saving-as-a-stream update: I ended up having to use this with modifications from tempfile import NamedTemporaryFile from openpyxl import Workbook wb = Workbook() with NamedTem...
10
10
75,287,534
2023-1-30
https://stackoverflow.com/questions/75287534/indexerror-descartes-polygonpatch-wtih-shapely
I used to use shapely to make a cirle and plot it on a previously populated plot. This used to work perfectly fine. Recently, I am getting an index error. I broke my code to even the simplest of operations and it cant even do the simplest of circles. import descartes import shapely.geometry as sg import matplotlib.pypl...
So from what I could tell, this issue comes from a broken implementation of shapely within descartes. My speculation is that shapely changed how it handles Polygon exteriors and descartes simply hasn't been updated. I don't know if it is the best idea, but I edited my installation of descartes directly to fix this issu...
5
20
75,233,794
2023-1-25
https://stackoverflow.com/questions/75233794/how-is-the-multiprocessing-queue-instance-serialized-when-passed-as-an-argument
A related question came up at Why I can't use multiprocessing.Queue with ProcessPoolExecutor?. I provided a partial answer along with a workaround but admitted that the question raises another question, namely why a multiprocessing.Queue instance can be passed as the argument to a multiprocessing.Process worker functio...
I wanted to expand on the accepted answer so I added my own which also details a way to make queues, locks, etc. picklable and able to be sent through a pool. Why this happens Basically, it's not that Queues cannot be serialized, it's just that multiprocessing is only equipped to serialize these when it knows sufficien...
9
7
75,289,130
2023-1-30
https://stackoverflow.com/questions/75289130/flatten-nested-pydantic-model
from typing import Union from pydantic import BaseModel, Field class Category(BaseModel): name: str = Field(alias="name") class OrderItems(BaseModel): name: str = Field(alias="name") category: Category = Field(alias="category") unit: Union[str, None] = Field(alias="unit") quantity: int = Field(alias="quantity") When i...
You should try as much as possible to define your schema the way you actually want the data to look in the end, not the way you might receive it from somewhere else. UPDATE: Generalized solution (one nested field or more) To generalize this problem, let's assume you have the following models: from pydantic import Base...
8
9
75,284,890
2023-1-30
https://stackoverflow.com/questions/75284890/how-to-cut-image-according-to-two-points-in-opencv
I have this input image (feel free to download it and try your solution, please): I need to find points A and B that are closest to the left down and right upper corner. And than I would like to cut of the image. See desired output: So far I have this function, but it does not find points A, B correctly: def CheckFo...
I noticed that your image has an alpha mask that already segment the foreground. This imply using the flag cv.IMREAD_UNCHANGED when reading the image with openCV (cv.imread(filename, cv.IMREAD_UNCHANGED)). If this is the case you can have a try to the following: import sys from typing import Tuple import cv2 as cv impo...
3
2
75,283,937
2023-1-30
https://stackoverflow.com/questions/75283937/capture-real-time-stdout-and-stderr-when-run-a-function-in-a-process-python
I have a python function and want to run it as a separate process with multiprocessing package. def run(ctx: Context): print("hello world!") return ctx afterward running it as a separate process with the following script: import multiprocessing p = multiprocessing.Process(target=run, args=(ctx, )) p.start() p.join() ...
My approach would be to create a custom context manager that can temporarily replace sys.stdout and sys.stderr with io.String() instances to capture the output and return this. For this you need to make the target of your Process a new function that can setup the context manager and return the results, for which a mult...
4
2
75,245,758
2023-1-26
https://stackoverflow.com/questions/75245758/how-to-use-poetry-in-google-colab
Context I am currently working on a team project, where we need to train neural networks. Some members are working on their local computer, and some on Colab (for GPU usage). We need to have the same dependencies. I am already familiar in using poetry on a local computer, but not on Colab, and I was wondering how to us...
Hello for everyone reading this post. I settled on a solution. The main issue was that pyproject.toml was not updated automatically, so I just decided to modify it by hand. Here is the steps for using poetry in Colab, whether you create your own poetry project, or cloning a repo on Github. https://github.com/elise-chin...
6
6
75,291,812
2023-1-31
https://stackoverflow.com/questions/75291812/how-do-i-normalize-a-path-format-to-unix-style-while-on-windows
I am storing paths in a json file using a python script. I want the paths to be stored in the same format (Unix-style) no matter which OS the script is run on. So basically I want to run the os.path.normpath function, but it only converts paths to Unix-style instead of changing its function depending on the host OS. Wh...
You can convert Windows-style path to UNIX-style after calling os.path.normpath. The conversion can be conveniently done with pathlib.PureWindowsPath.as_posix: import os.path from pathlib import PureWindowsPath path = r'\foo\\bar' path = os.path.normpath(path) if os.path.sep == '\\': path = PureWindowsPath(path).as_pos...
4
7
75,304,110
2023-1-31
https://stackoverflow.com/questions/75304110/keras-model-predicts-different-results-using-the-same-input
I built a Keras sequential model on the simple dataset. I am able to train the model, however every time I try to get a prediction on the same input I get different values. Anyone knows why? I read through different Stackoverflow here (Why the exactly identical keras model predict different results for the same input d...
The problem is setting stateful=True in your LSTM layer, as this keeps the state between predict calls, so each prediction depends on previous predictions. So as a solution, set stateful=False.
3
3
75,302,200
2023-1-31
https://stackoverflow.com/questions/75302200/python-types-literal-of-logging-level-as-type
the following code: import logging print(type(1)) print(type(logging.WARNING)) prints: <class 'int'> <class 'int'> yet, according to mypy, the first line of this code snippet is legal, but the second is not (Variable "logging.WARNING" is not valid as a type): OneOrTwo = Literal[1,2] # ok WarningOrError = Literal[logg...
Literal only accepts literal arguments. PEP586 has very rigid definitions of what constitutes a "literal" in this context. You can read about it here. The problem with your definition of WarningOrError is that the actual definition of logging.ERROR and WARNING makes them mutable (you can look at the source code of logg...
4
5
75,300,394
2023-1-31
https://stackoverflow.com/questions/75300394/pandas-replace-certain-values-within-groups-using-group-maximus
Here's my table: category number probability 1102 24 0.3 1102 18 0.6 1102 16 0.1 2884 24 0.16 2884 15 0.8 2884 10 0.04 so I want to replace the number column that has probability lower than 15% with the number that has the highest probability within groups: category number probability 1102...
Find the number corresponding to max prob in a group then use loc to update values n = df.sort_values('probability').groupby('category')['number'].transform('last') df.loc[df['probability'] <= 0.15, 'number'] = n category number probability 0 1102 24 0.30 1 1102 18 0.60 2 1102 18 0.10 3 2884 24 0.16 4 2884 15 0.80 5...
3
3
75,296,495
2023-1-31
https://stackoverflow.com/questions/75296495/sum-the-values-of-a-column-with-python
I'm new to python, I would like to read a column of values ​​from a csv file and add them together, but only those to the left of the "," My csv File: Name Code Angel 19;90 Eduardo 20;21 Miguel 30;45 I would like to be able to sum only the numbers to the left of the "Code" column, so that my output is "19+20+30 = 69"....
If need sum values before ; use Series.str.extract with casting to integers and then sum: out = df['Code'].str.extract('(.*);', expand=False).astype('int').sum() Or use Series.str.split with select first values of lists by str[0]: out = df['Code'].str.split(';').str[0].astype('int').sum() If need sum all values creat...
5
5
75,295,132
2023-1-31
https://stackoverflow.com/questions/75295132/how-to-place-specific-constraints-on-the-parameters-of-a-pydantic-model
How can I place specific constraints on the parameters of a Pydantic model? In particular, I would like: start_date must be at least "2019-01-01" end_date must be greater than start_date code must be one and only one of the values ​​in the set cluster must be one and only one of the values ​​in the set The code I'm u...
Pydantic has a set of constrained types that allows you to define specific constraints on values. start_date must be at least "2019-01-01" >>> class Foo(BaseModel): ... d: condate(ge=datetime.date.fromisoformat('2019-01-01') >>> Foo(d=datetime.date.fromisoformat('2018-01-12')) Traceback (most recent call last): File "<...
4
3
75,276,563
2023-1-29
https://stackoverflow.com/questions/75276563/tkinter-scroll-with-touchpad-mouse-gestures-two-fingers-scrolling-in-tkint
I wanted to implement two finger scrolling in tkinter. Here is the result of my own attempt: import tkinter as tk class Scene: def __init__(self, canvas): self.canvas = canvas self.elements = [ { "type": "rect", "x": canvas.winfo_width() / 2, "y": canvas.winfo_height() / 2, "width": 200, "height": 200, "color": (55 / 2...
tkinter does only support horizontal scrolling on windows from patchlevel 8.6.10 <= I've created a small example that works for me with tkinter 8.6.12 on Win11. When using two fingers with a little gap between them I can successfully scroll in both direction and move the View in a circle. I retrieve two different event...
4
2
75,237,114
2023-1-25
https://stackoverflow.com/questions/75237114/max-retries-exceeded-with-url-failed-to-establish-a-new-connection-errno-111
I keep getting this error: HTTPConnectionPool(host='127.0.0.1', port=8001): Max retries exceeded with url: /api/v1/auth/sign_in (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0f8cbdd430>: Failed to establish a new connection: [Errno 111] Connection refused')) I searched through the stac...
Answer of @jordanm was right and it fixed my problem: Change host = 'http://127.0.0.1:8001' to host = 'http://container_2:8000'
5
12
75,291,343
2023-1-30
https://stackoverflow.com/questions/75291343/what-is-the-internal-load-factor-of-a-sets-in-python
I am trying to find out what the internal load factor is for the Python sets. For dictionary which uses a hash table with a load factor of 0.66 (2/3) is. The number of buckets start at 8 and when the 6th key is inserted the number of buckets increases to 16 The table below shows the shift in buckets. bucket shift ...
Currently, it's about 3/5. See the source: if ((size_t)so->fill*5 < mask*3) return 0; return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); fill is the number of occupied table cells (including "deleted entry" markers), and mask is 1 less than the total table capacity.
3
5
75,284,768
2023-1-30
https://stackoverflow.com/questions/75284768/modulenotfounderror-after-installing-a-python-package
Problem summary I am very new to python package development. I developed a package and published it at TestPyPI. I install this package trough pip with no errors. However, python is giving me a "ModuleNotFoundError" when I try to import it, and I have no idea why. Can someone help me? Repro steps First, I install the p...
The source of the problem The source of the problem is at the "build process" of the package. In other words, pip install was installing a "not valid package". Basically, I use setuptools to build the package. When I compiled (or "build" the package with python -m build, the source code of the package (that is, all con...
7
5
75,286,085
2023-1-30
https://stackoverflow.com/questions/75286085/what-is-the-difference-between-assert-and-a-if-condition-embedded-with-a-raise
i am currently learning about the assert statement in python and i cant seem to understand its main usage and what seperates it from simply raising an exception. if i wrote an if statement along with my condition and simply raised an exception if the condition is not met, how is that different from using the assert sta...
Not much. The documentation provides the equivalent if statements to an assert statement. assert expression is the same as if __debug__: if not expression: raise AssertionError() while assert expression1, expression2 is the same as if __debug__: if not expression1: raise AssertionError(expression2) As you can see, ...
3
4
75,282,511
2023-1-30
https://stackoverflow.com/questions/75282511/df-to-table-throw-error-typeerror-init-got-multiple-values-for-argument
I have dataframe in pandas :- purchase_df. I want to convert it to sql table so I can perform sql query in pandas. I tried this method purchase_df.to_sql('purchase_df', con=engine, if_exists='replace', index=False) It throw an error TypeError: __init__() got multiple values for argument 'schema' I have dataframe name...
It seems that the version 2.0.0 (realeased on January 26, 2023) of SQLAlchemy is not compatible with earlier versions of pandas. I suggest you to upgrade your pandas version to the latest (version 1.5.3) with : pip install --upgrade pandas Or: conda upgrade pandas
23
29
75,274,640
2023-1-29
https://stackoverflow.com/questions/75274640/how-to-get-key-and-value-instead-of-only-value-when-filtering-with-jmespath
Input data: s = {'111': {'name': 'john', 'exp': '1'}, '222': {'name': 'mia', 'exp': '1'}} Code: import jmespath jmespath.search("(*)[?name=='john']", s) Output: [{'name': 'john', 'exp': '1'}] Output I want: [{'111': {'name': 'john', 'exp': '1'}}]
Convert the dictionary to the list l1 = [{'key': k, 'value': v} for k, v in s.items()] gives [{'key': '111', 'value': {'name': 'john', 'exp': '1'}}, {'key': '222', 'value': {'name': 'mia', 'exp': '1'}}] Select the values where the attribute name is john l2 = jmespath.search('[?value.name == `john`]', l1) gives [{'ke...
4
2
75,275,563
2023-1-29
https://stackoverflow.com/questions/75275563/attributeerror-module-sqlalchemy-has-no-attribute-all
In my GitHub CI I get errors like the one below since today: File "/home/runner/.local/lib/python3.8/site-packages/fb4/login_bp.py", line 12, in <module> from fb4.sqldb import db File "/home/runner/.local/lib/python3.8/site-packages/fb4/sqldb.py", line 8, in <module> db = SQLAlchemy() File "/home/runner/.local/lib/pyth...
It seems the .__all__ attribute has been removed in the recently released SQLAlchemy 2.0. You may need to pin the SQLAlchemy version in your config somehow. Or ensure that you are using Flask-SQLAlchemy 3.0.2 or later, as this issue suggests that version has the required fix.
27
27
75,275,130
2023-1-29
https://stackoverflow.com/questions/75275130/z-label-does-not-show-up-in-3d-matplotlib-scatter-plot
The z-label does not show up in my figure. What is wrong? import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") plt.show() Output Neither ax.set_zlabel("z") nor ax.set(zlabel="z") works. The x- and y-labels work fine.
That's a padding issue. labelpadfloat The distance between the axis label and the tick labels. Defaults to rcParams["axes.labelpad"] (default: 4.0) = 4. You can use matplotlib.axis.ZAxis.labelpad to adjust this value for the z-axis : import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, project...
10
10
75,257,369
2023-1-27
https://stackoverflow.com/questions/75257369/pypdf2-paper-size-manipulation
I am using PyPDF2 to take an input PDF of any paper size and convert it to a PDF of A4 size with the input PDF scaled and fit in the centre of the output pdf. Here's an example of an input (convert to pdf with imagemagick convert image.png input.pdf), which can be of any dimensions: And the expected output is: I'm no...
You almost got it! The transformations are applied only to the content, but not to the boxes (mediabox/trimbox/cropbox/artbox/bleedbox). You need to adjust the cropbox: from pypdf.generic import RectangleObject page.cropbox = RectangleObject((0, 0, A4_w, A4_h)) Full script from pypdf import PdfReader, PdfWriter, Trans...
4
6
75,235,531
2023-1-25
https://stackoverflow.com/questions/75235531/problem-when-installing-python-from-source-ssl-package-missing-even-though-open
The Problem Trying to install Python-3.11.1 from source on Zorin OS (Ubuntu16 based) I get the following errors when I try to pip install any package into a newly created venv: python3.11 -m venv venv source venv/bin/active pip install numpy WARNING: pip is configured with locations that require TLS/SSL, however the ss...
After some more research, I realized that I didn't have libbz2-dev installed, which is obviously the first thing one should check if they get the errors above but oh well. For anyone who still finds himself struggling, here are my complete steps I took: Make sure the following libraries are installed apt show libbz2-...
4
3
75,269,700
2023-1-28
https://stackoverflow.com/questions/75269700/pre-commit-fails-to-install-isort-5-11-4-with-error-runtimeerror-the-poetry-co
pre-commit suddenly started to fail installing the isort hook in our builds today with the following error [INFO] Installing environment for https://github.com/pycqa/isort. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: CalledProcessError: ...
Upgrading the hook to the freshly released isort 5.12.0 seems to be fixing the issue. Looking at the commit stack from isort repo, it sounds like recent version of Poetry had a breaking change incompatible with isort <= 5.11.4 (commit)
80
85
75,268,412
2023-1-28
https://stackoverflow.com/questions/75268412/python-type-hints-for-unpacking-object
I'm trying to implement type hinting for object unpacking. Here is what I have currently from typing import Tuple class A: def __init__(self, x: int, y: str): self.x = x self.y = y def astuple(self) -> Tuple[int, str]: return self.x, self.y # Need to annotate the return type of __iter__ def __iter__(self): return iter(...
There is no way to define your own heterogeneous iterable type in Python. Make A a subclass of NamedTuple instead. from typing import NamedTuple class A(NamedTuple): x: int y: str x, y = A(1, "a") reveal_type(x) # builtins.int reveal_type(y) # builtins.str
4
3
75,249,150
2023-1-26
https://stackoverflow.com/questions/75249150/how-to-use-class-based-views-in-fastapi
I am trying to use class based views in my FastApi project to reduce redundancy of code. Basically I need CRUD functionality for all of my models and therefor would have to write the same routes over and over again. I created a small example project to display my progress so far, but I ran into some issues. I know ther...
since your question is understandably very long, I will post a full working example at the bottom of this answer. Dependencies in FastAPI are callables that can modify an endpoints parameters and pass values down to them. In the api model they work in the endpoint level. To pass-on any dependency results you need to ex...
5
6
75,264,394
2023-1-27
https://stackoverflow.com/questions/75264394/class-function-vs-method
I was watching Learn Python - Full Course for Beginners [Tutorial] on YouTube here. At timestamp 4:11:54 the tutor explains what a class function is, however from my background in object oriented programming using other languages I thought the correct term would be method? Now I am curious if there is a difference betw...
Method is the correct term for a function in a class. Methods and functions are pretty similar to each other. The only difference is that a method is called with an object and has the possibility to modify data of an object. Functions can modify and return data but they dont have an impact on objects. Edit : Class func...
3
2
75,263,744
2023-1-27
https://stackoverflow.com/questions/75263744/adding-bar-labels-shrinks-dodged-bars-in-seaborn-objects
I am trying to add text labels to the top of a grouped/dodged bar plot using seaborn.objects. Here is a basic dodged bar plot: import seaborn.objects as so import pandas as pd dat = pd.DataFrame({'group':['a','a','b','b'], 'x':['1','2','1','2'], 'y':[3,4,1,2]}) (so.Plot(dat, x = 'x', y = 'y', color = 'group') .add(so.B...
This isn't ideal but can be worked around by assigning text only in the layer with the Text (or un-assigning it from the Bar layer) and restricting the variables used to compute the text dodge: ( so.Plot(dat, x='x', y='y', color='group') .add(so.Bar(), so.Dodge()) .add(so.Text({'va':'bottom'}), so.Dodge(by=["color"]), ...
4
4
75,262,933
2023-1-27
https://stackoverflow.com/questions/75262933/python-pandas-wide-data-identify-earliest-and-maximum-columns-in-time-series
I am working with a data frame that is written in wide format. Each book has a number of sales, but some quarters have null values because the book was not released before that quarter. import pandas as pd data = {'Book Title': ['A Court of Thorns and Roses', 'Where the Crawdads Sing', 'Bad Blood', 'Atomic Habits'], 'M...
Edit, updated approach making better use of groupby after melting #melt table to be long-form long_df1 = df1.melt( id_vars = ['Book Title','Metric'], value_name = 'Sales', var_name = 'Quarter', ) #remove rows that have 0 sales (could be dropna if null values used instead) long_df1 = long_df1[long_df1['Sales'].gt(0)] #g...
3
1
75,261,249
2023-1-27
https://stackoverflow.com/questions/75261249/how-to-assign-feature-weights-in-xgbclassifier
I am trying to assign a higher weight to one feature above others. Here is my code. ## Assign weight to High Net Worth feature cols = list(train_X.columns.values) # 0 - 1163 --Other Columns # 1164 --High Net Worth #Create an array of feature weights other_col_wt = [1]*1164 high_net_worth_wt = [5] feature_wt = other_col...
I think you need to remove feature_weights from the init of XGBClassifier. At least, this works when I try your example.
4
3
75,247,445
2023-1-26
https://stackoverflow.com/questions/75247445/error-when-making-a-dash-datatable-filterable-by-columns-values
Only when I add the property filter_action="native" in a dash.DataTable in order to make it possible for the user to filter rows by column values I get an error that varies with the browser I run the webapp on: Edge: Cannot read properties of undefined (reading 'placeholder_text') (This error originated from the built...
I found a possible solution: that is giving also the columns attribute during DataTable declaration (no, giving just data is not sufficient): columns=[{"name": i, 'id': i} for i in df.columns] The minimal code for making a DataTable with working filtering of rows based on column values is dash_table.DataTable( id='my_...
4
7
75,256,024
2023-1-27
https://stackoverflow.com/questions/75256024/calculating-timedeltas-across-daylight-saving
I'm facing a python timezones problem and am unsure of what is the right approach to deal with it. I have to calculate timedeltas from given start and end DateTime objects. It can happen that daylight saving time will change during the runtime of my events, so I have to take that into account. So far I've learned that ...
You just need to produce an aware (localised) datetime instance, then any calculation you do with it will take DST into account. Here as an example with pytz: >>> import pytz >>> from datetime import * >>> berlin = pytz.timezone('Europe/Berlin') >>> d1 = berlin.localize(datetime(2023, 3, 25, 12)) datetime.datetime(2023...
4
3
75,252,652
2023-1-26
https://stackoverflow.com/questions/75252652/python-sqlalchemy-postgresql-deprecated-api-features
I am using following code to create the function and trigger to update the created_at and updated_at fields. with upgrade of new module getting the deprecated API warning. How can I replace engine.execute(sa.text(create_refresh_updated_at_func.format(schema=my_schema))) line to remove the warning message? Code: mapper...
SQLAlchemy no longer supports autocommit at the library level. You need to run the execute within a transaction. This should work: with engine.begin() as conn: conn.execute(text(create_refresh_updated_at_func.format(schema=my_schema))) migration-core-connection-transaction You could also use the driver-level isolation...
4
4
75,242,731
2023-1-26
https://stackoverflow.com/questions/75242731/is-there-a-c-equivalent-for-pythons-self-documenting-expressions-in-f-strings
Since Python 3.8 it is possible to use self-documenting expressions in f-strings like this: >>> variable=5 >>> print(f'{variable=}') variable=5 is there an equivalent feature in C#?
Yes. int variable = 5; Console.WriteLine($"variable={variable}"); That outputs: variable=5 The key here is the $ that precedes the string literal. To do what you want with the name coming dynamically, I'd suggest a more explicit approach of using an extension method. Try this: public static class SelfDocExt { public...
4
5
75,248,944
2023-1-26
https://stackoverflow.com/questions/75248944/polymorphism-in-callablle-under-python-type-checking-pylance
For my code I have an aggregate class that needs a validation method defined for each of the subclasses of base class BaseC, in this case InheritC inherits from BaseC. The validation method is then passed into the aggregate class through a register method. See the following simple example from typing import Callable cl...
I'll be using the below sample code, where I've fixed a couple of bugs: from typing import Callable class BaseC: def __init__(self) -> None: pass class InheritC(BaseC): def __init__(self) -> None: super().__init__() @classmethod def validate(cls, c:'InheritC') ->bool: return False class AggrC: def register_validate_fn(...
4
4
75,240,766
2023-1-25
https://stackoverflow.com/questions/75240766/problem-converting-an-image-for-a-3-color-e-ink-display
I am trying to process an image file into something that can be displayed on a Black/White/Red e-ink display, but I am running into a problem with the output resolution. Based on the example code for the display, it expects two arrays of bytes (one for Black/White, one for Red), each 15,000 bytes. The resolution of the...
As requested, and in the event that it may be useful for future reader, I write a little bit more extensively what I've said in comments (and was verified to be indeed the reason of the problem). The e-ink display needs usually a black&white image. That is 1 bit per pixel image. Not a grayscale (1 channel byte per pixe...
4
4
75,244,419
2023-1-26
https://stackoverflow.com/questions/75244419/aws-ecs-environment-variable-not-available-python
I am using AWS ECS with a Python Framework and in my task definition i have the option to add environment variables that will be available to the service(cluster). Here is where i added the env variables: When i then try to print all the env variables in my service i do not get access to these variables and i am not s...
I had a similar problem and it seems to me that the full environment is passed only to the PID 1 (init process, which in a container should be CMD/ENTRYPOINT command). Cron is not that process so you cannot assume it sees the same environment. What I did may not be the best solution, it is rather a hack, but it works. ...
3
4
75,232,011
2023-1-25
https://stackoverflow.com/questions/75232011/why-does-exe-built-using-pyinstaller-isnt-working
here's the error: Traceback (most recent call last): File "main.py", line 5, in <module> File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "PyInstaller\load...
One of the libraries you are using is attempting to write to sys.stdout and sys.stderr, which are set to None when you run pyinstaller with the -w --windowed or --noconsole options. You need to explicitly set sys.stderr and sys.stdout in your programs code as early as possible to a writeable object like an open file or...
4
6
75,240,319
2023-1-25
https://stackoverflow.com/questions/75240319/conda-environment-using-incorrect-module-because-of-order-os-sys-path
I am using conda version 4.14.0. When I activate a conda environment I can see that the current numpy module is 1.22.3 conda list | grep -i numpy numpy 1.22.3 py39hc58783e_2 conda-forge When I run python in the conda environment and load numpy it shows version 1.19.1 Python 3.9.12 | packaged by conda-forge | (main, Ma...
The user site packages (at ~/.local) remaining available is the default behaviour of conda envs, and even issues requesting adding an option to disable that have been repeatedly closed by conda maintainers (example). It is an unfortunate decision from Conda that the user site is included by default. You can exclude it ...
4
5
75,229,250
2023-1-25
https://stackoverflow.com/questions/75229250/is-there-a-method-to-run-a-conda-environment-in-google-colab
I have a YML file for a Conda environment that runs with Python 3.8.15 (environment.yml). I am currently trying to load that file into my Google Colab, based on this answer: conda environment in google colab [google-colaboratory]. !wget -c https://repo.anaconda.com/archive/Anaconda3-2022.10-Windows-x86_64.exe !chmod +x...
You cannot run a Jupyter notebook (Colab session) with a new Conda environment, but you can use Conda to augment the packages in the existing Python installation. Installation is streamlined with condacolab. See the condacolab documentation. An quick example would go something like: First Cell !pip install -q condacola...
6
12
75,236,716
2023-1-25
https://stackoverflow.com/questions/75236716/anyway-to-get-rid-of-math-floor-for-positive-odd-integers-with-sympy-simplify
I'm trying to simplify some expressions of positive odd integers with sympy. But sympy refuses to expand floor, making the simplification hard to proceed. To be specific, x is a positive odd integer (actually in my particular use case, the constraint is even stricter. But sympy can only do odd and positive, which is fi...
I fail to see why sympy can't simplify that. But, on another hand, I've discovered the existence of odd parameter just now, with your question. What I would have done, without the knowledge of odd is k = Symbol('k', positive=True, integer=True) x = 2*k-1 expr = x // 2 - (x - 1) / 2 Then, expr is 0, without even the ne...
3
4
75,231,984
2023-1-25
https://stackoverflow.com/questions/75231984/read-sql-in-chunks-with-polars
I am trying to read a large database table with polars. Unfortunately, the data is too large to fit into memory and the code below eventually fails. Is there a way in polars how to define a chunksize, and also write these chunks to parquet, or use the lazy dataframe interface to keep the memory footprint low? import po...
Yes and no. There's not a predefined method to do it but you can certainly do it yourself. You'd do something like: rows_at_a_time=1000 curindx=0 while True: df = pl.read_sql(f"SELECT * from TABLENAME limit {curindx},{rows_at_a_time}", connection_string) if df.shape[0]==0: break df.write_parquet(f"output{curindx}.parqu...
5
2
75,232,363
2023-1-25
https://stackoverflow.com/questions/75232363/pandas-dataframe-aggregating-function-to-count-also-nan-values
I have the following dataframe print(A) Index 1or0 0 1 0 1 2 0 2 3 0 3 4 1 4 5 1 5 6 1 6 7 1 7 8 0 8 9 1 9 10 1 And I have the following Code (Pandas Dataframe count occurrences that only happen immediately), which counts the occurrences of values that happen immediately one after another. ser = A["1or0"].ne(A["1or0"]...
First fillna with a value this is not possible (here -1) before creating your grouper: group = A['1or0'].fillna(-1).diff().ne(0).cumsum() # or # s = A['1or0'].fillna(-1) # group = s.ne(s.shift()).cumsum() B = (A.groupby(group, as_index=False) .agg(**{'StartNum': ('Index', 'first'), 'EndNum': ('Index', 'last'), 'Size': ...
3
5
75,184,430
2023-1-20
https://stackoverflow.com/questions/75184430/how-to-redirect-the-user-to-another-page-after-login-using-javascript-fetch-api
Using the following JavaScript code, I make a request to obtain the firebase token, and then a POST request to my FastAPI backend, using the JavaScript fetch() method, in order to login the user. Then, in the backend, as can be seen below, I check whether or not the token is valid, and if so, return a redirect (i.e., R...
Option 1 - Returning RedirectResponse When using the fetch() function to make an HTTP request to a server that responds with a RedirectResponse, the redirect response will be automatically followed on client side (as explained here), as the redirect mode is set to follow, by default, in the fetch() function. This means...
5
8
75,211,934
2023-1-23
https://stackoverflow.com/questions/75211934/how-can-i-use-when-then-and-otherwise-with-multiple-conditions-in-polars
I have a data set with three columns. Column A is to be checked for strings. If the string matches foo or spam, the values in the same row for the other two columns L and G should be changed to XX. For this I have tried the following. df = pl.DataFrame( { "A": ["foo", "ham", "spam", "egg",], "L": ["A54", "A12", "B84", ...
For setting multiple columns to the same value you could use: df.with_columns( pl.when(pl.col("A").is_in(["foo", "spam"])) .then(pl.lit("XX")) .otherwise(pl.col("L", "G")) .name.keep() ) shape: (4, 3) ┌──────┬─────┬─────┐ │ A ┆ L ┆ G │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str │ ╞══════╪═════╪═════╡ │ foo ┆ XX ┆ XX │ │ ha...
9
10
75,188,523
2023-1-20
https://stackoverflow.com/questions/75188523/installing-requirements-txt-in-a-venv-inside-vscode
Apart from typing out commands - is there a good way to install requirements.txt inside VSCode. I have a workspace with 2 folders containing different Python projects added - each has it's own virtual environment. I would like to run a task to execute and install the requirements to each of these. I have tried adding a...
I've written a more detailed post before, but as Andez mentioned in comments, this is also a suitable post for the answer. This task can be ran in Windows, Linux and MacOS. { "version": "2.0.0", "tasks": [ { "label": "Build Python Env", "type": "shell", "group": { "kind": "build", "isDefault": true }, "options": { "cwd...
5
5
75,198,237
2023-1-22
https://stackoverflow.com/questions/75198237/stream-a-zst-compressed-file-line-by-line
I am trying to sift through a big database that is compressed in a .zst. I am aware that I can simply just decompress it and then work on the resulting file, but that uses up a lot of space on my ssd and takes 2+ hours so I would like to avoid that if possible. Often when I work with large files I would stream it line ...
Knowing which package to use and what the corresponding docs are can be a bit confusing, as there appears to be several Python bindings to the actual Zstandard library. Below, I am referring to the library by Gregory Szorc, that I installed from condas default channel with: conda install zstd # check: conda list zstd #...
7
5
75,204,255
2023-1-22
https://stackoverflow.com/questions/75204255/how-to-force-a-platform-wheel-using-build-and-pyproject-toml
I am trying to force a Python3 non-universal wheel I'm building to be a platform wheel, despite not having any native build steps that happen during the distribution-packaging process. The wheel will include an OS-specific shared library, but that library is built and copied into my package directory by a larger build ...
Update 2 Sept 2023: -C=--build-option=--plat {your-platform-tag} no longer works, so I added my preferred replacement to the end of the list. ========== OK, after some research and reading of code, I can present a bit of information and a few solutions that might meet other people's needs, summarized here: Firstly, pyp...
5
6
75,202,475
2023-1-22
https://stackoverflow.com/questions/75202475/joblib-persistence-across-sessions-machines
Is joblib (https://joblib.readthedocs.io/en/latest/index.html) expected to be reliable across different machines, or ways of running functions, even different sessions on the same machine over time? For concreteness if you run this code in a Jupyter notebook, or as a python script, or piped to the stdin a python interp...
The canonical way of using joblib's disk caching seems to require always having your function in a .py file, and not in a notebook cell (see e.g. this issue). I've found a workaround for using joblib in a jupyter notebook anyway, so that it hits the cache even if you re-run a cell or restart the notebook (which does no...
3
5
75,227,015
2023-1-24
https://stackoverflow.com/questions/75227015/error-mkdocstrings-generation-error-no-module-named
I was building a documentation site for my python project using mkdocstrings. For generating the code referece files I followed this instructions https://mkdocstrings.github.io/recipes/ I get these errors: INFO - Building documentation... INFO - Cleaning site directory INFO - The following pages exist in the docs dire...
Following the mkdocstrings documentation I also received that same error. After some tinkering, I was able to successfully serve the docs by adding paths: [src] (see below). mkdocs.yml plugins: - search - gen-files: scripts: - docs/gen_ref_pages.py - mkdocstrings: default_handler: python handlers: python: paths: [src]
7
3
75,157,428
2023-1-18
https://stackoverflow.com/questions/75157428/redis-exceptions-dataerror-invalid-input-of-type-dict-convert-to-a-bytes-s
Goal: store a dict() or {} as the value for a key-value pair, to set() onto Redis. Code import redis r = redis.Redis() value = 180 my_dict = dict(bar=value) r.set('foo', my_dict) redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
You cannot pass a dictionary object as a value in the set() operation to Redis. However, we can use either pickle or json to get the Bytes of an object. Whichever you already have imported would be optimal, imho. Pickle Serialize to pickle (with pickle.dumps) pre-set() import pickle my_dict = {'a': 1, 'b': 2} dict_byt...
8
17
75,215,780
2023-1-23
https://stackoverflow.com/questions/75215780/implement-qcut-functionality-using-polars
I have been using polars but it seems like it lacks qcut functionality as pandas do. I am not sure about the reason but is it possible to achieve the same effect as pandas qcut using current available polars functionalities? The following shows an example about what I can do with pandas qcut. import pandas as pd data =...
Update: Series.qcut was added in polars version 0.16.15 data = pl.Series([11, 1, 2, 2, 3, 4, 5, 1, 2, 3, 4, 5]) data.qcut([0.2, 0.4, 0.6, 0.8], labels=['q1', 'q2', 'q3', 'q4', 'q5'], maintain_order=True) shape: (12, 3) ┌──────┬─────────────┬──────────┐ │ ┆ break_point ┆ category │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ cat...
6
10
75,202,383
2023-1-22
https://stackoverflow.com/questions/75202383/raise-packaging-version-invalidversion-linux-pip
after updating pip and setuptools==66.0, pip stopped working and responds to all attempts to call it like this: Traceback (most recent call last): File "/usr/bin/pip", line 6, in <module> from pkg_resources import load_entry_point File "/usr/local/lib/python3.8/dist-packages/pkg_resources/__init__.py", line 3249, in <...
This turns out to be by design by the setuptools developers, please see some commentary on it at https://github.com/pypa/setuptools/issues/3772#issuecomment-1384342813. In short, it's by been removed to enforce strict semantic versioning of packages. If you can't upgrade the versioning to be semantic versioning compati...
5
8
75,179,679
2023-1-20
https://stackoverflow.com/questions/75179679/syntax-highlighting-for-python-docstrings-in-neovim-treesitter
I'm using Treesitter with Neovim v0.8.2 and Python. With a default configuration of those 3, python docstrings are highlighted as strings, and I'd like to highlight them as comments. I've tried creating a ~/.config/nvim/after/syntax/python.vim file with syn region Comment start=/"""/ end=/"""/ and I expected """<thing...
checkout https://github.com/nvim-treesitter/nvim-treesitter/issues/4392 it's quite the read, but you can override how treesitter parses the objects in the document/buffer, can't take credit for the below solution, but should get you where you need to be. after/queries/python/highlights.scm extends ; Module docstring ...
4
1
75,224,636
2023-1-24
https://stackoverflow.com/questions/75224636/importerror-cannot-import-name-int-from-numpy
I am trying to import sklearn library by writing code like from sklearn.preprocessing import MinMaxScaler but it kept showing same error. I tried uninstalling and reinstalling but no change. Command prompt is also giving same error. Recently I installed some python libraries but that never affected my enviroment. I als...
Run pip3 install --upgrade scipy OR upgrade whatever tool that tried to import np.int and failed np.int is same as normal int of python and scipy was outdated for me
6
13
75,209,217
2023-1-23
https://stackoverflow.com/questions/75209217/printing-a-list-within-a-list-as-a-string-on-new-lines
I'm really struggling with this issue, and can't seem to find an answer anywhere. I've got a text file which has name of the station and location, the task is to print out the names of the stations all underneath each other in order and same for the locations. In my text file the names of the stations are always made u...
This is a simple a straight forward approach using for-loop instead of while loop. What the code does: It splits your string into substrings, where every substring is separated by comma and space. After that it splits those substrings again by space then joins the first two elements of each substring to create station ...
3
2
75,180,598
2023-1-20
https://stackoverflow.com/questions/75180598/typeerror-object-of-type-type-is-not-json-serializable
The code works fine in Postman and provides a valid response but fails to generate the OpenAPI/Swagger UI automatic docs. class Role(str, Enum): Internal = "internal" External = "external" class Info(BaseModel): id: int role: Role class AppInfo(Info): info: str @app.post("/api/v1/create", status_code=status.HTTP_200_OK...
Issue The reason you get the following error in the console (Note that this error could also be raised by other causes—see here): TypeError: Object of type 'type' is not JSON serializable as well as the error below in the browser, when trying to load the OpenAPI/Swagger UI autodocs at /docs: Fetch error Internal Serve...
3
7
75,216,548
2023-1-24
https://stackoverflow.com/questions/75216548/aws-sam-cli-throws-error-error-building-docker-image
I am trying to use the SAM CLI on my M1 Mac. I followed the steps outlined in these docs: sam init cd sam-app sam build sam deploy --guided I did not modify the code or the yaml files. I can start the local Lambda function as expected: ➜ sam-app sam local start-api Mounting HelloWorldFunction at http://127.0.0.1:3000/...
In your template.yaml, change the following lines from Architectures: - x86_64 to Architectures: - arm64 The reason why this works is that sam init defaults to the x86_64 architecture. Since you have an M1 Mac, performance will be better with a Docker image for the arm64 architecture. You can tell this is the case ...
11
11
75,204,360
2023-1-22
https://stackoverflow.com/questions/75204360/how-to-call-an-async-function-during-debugging
I usually like to call some functions during debugging in the console just to see some quick results. However with async functions, this doesn't seem to be possible: import asyncio async def func1(): print('func1') def func2(): print('func2') async def main(): task = asyncio.create_task(func1()) await task # put a brea...
You can suspend the current_task and then run the event loop until the task is done. import asyncio from asyncio import tasks def wait(task_or_coro): task = asyncio.ensure_future(task_or_coro) loop, current_task = task.get_loop(), tasks.current_task() tasks._leave_task(loop, current_task) while not task.done(): loop._r...
3
5
75,159,675
2023-1-18
https://stackoverflow.com/questions/75159675/installing-open3d-ml-with-pytorch-on-macos
I created a virtualenv with python 3.10 and installed open3d and PyTorch according to the instructions on open3d-ml webpage: Open3d-ML but when I tested it with import open3d.ml.torch I get the error: Exception: Open3D was not built with PyTorch support! Steps to reproduce python3.10 -m venv .venv source .venv/bin/acti...
Finally, I decided to build Open3D from the source for Mac M1. I followed almost the official open3d page and thanks to this medium in one of the replies. Build Open3d-ml with Pytorch on Mac M1 For the OS environment see the main question. conda create --name open3d-ml-build python==3.10 conda activate open3d-ml-build ...
3
3