question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
77,269,751
2023-10-11
https://stackoverflow.com/questions/77269751/make-efficient-python-generator-with-condition
I tried to make python str generator with condition, but it is not easy to me. condition is simple. I have 3 letters, "A", "B", and "C" each letters must be used at least 4 times. total sentence length is 19. I need to test all combinations. so i tried below code for i in combinations_with_replacement('ABC', 7): for ...
To implement the rule that "each letters must be used at least 4 times" you can create a base pool of 12 characters with 'ABC' repeated 4 times, and that leaves 19 - 3 x 4 = 7 characters that need to be filled in with any of the letters in 'ABC', which can be done with itertools.combinations_with_replacement. Chain the...
2
2
77,270,062
2023-10-11
https://stackoverflow.com/questions/77270062/python-pandas-filter-rows-by-days-of-difference-in-two-columns-with-weekend-and
I have a dataframe with two dates, among other things. I need to filter out rows that have more than two working days difference between these two dates. I must take into consideration weekends and holidays. *Assuming 10/17/2023 is a holiday... Example df: NAME DATE1 DATE2 CASE1 10/12/2023 10/13/2023 <--- one day diffe...
Code Define a list of holidays holidays = np.array([pd.to_datetime("10/17/2023", format="%m/%d/%Y")], dtype='datetime64[D]') Parse the strings in date columns to datetime type df['DATE1'] = pd.to_datetime(df['DATE1'], format="%m/%d/%Y") df['DATE2'] = pd.to_datetime(df['DATE2'], format="%m/%d/%Y") # NAME DATE1 DATE2 # ...
4
2
77,237,818
2023-10-5
https://stackoverflow.com/questions/77237818/how-to-load-a-huggingface-pretrained-transformer-model-directly-to-gpu
I want to load a huggingface pretrained transformer model directly to GPU (not enough CPU space) e.g. loading BERT from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("bert-base-uncased") would be loaded to CPU until executing model.to('cuda') now the model is loaded into GPU I ...
I'm answering my own question. Hugging Face accelerate (add via pip install accelerate) could be helpful in moving the model to GPU before it's fully loaded in CPU. It's useful when: GPU memory > model size > CPU memory Also specify device_map="cuda": from transformers import AutoModelForCausalLM model = AutoModelForCa...
17
28
77,260,102
2023-10-9
https://stackoverflow.com/questions/77260102/python-typing-cast-method-vs-colon-type-hints
What the difference between using the Python typing.cast method x = cast(str, x) compared with using type hints/colon notation/left hand side type annotation? x: str I've seen the use of the cast method in codebases but don't have an apparent reason to use it instead of type hint notation, which is more concise.
I will answer you through a well-written example: def get_name(can_return_name: bool) -> str | None: in_name = input('Enter your name: ') return in_name if can_return_name else None def do_something_with_name() -> None: name: str = get_name(True) print(name.capitalize()) Here, you'd expect Pyright or mypy to say that ...
4
7
77,241,390
2023-10-6
https://stackoverflow.com/questions/77241390/querying-html-content-in-common-crawl-dataset-using-amazon-athena
I am currently exploring the massive Common Crawl dataset hosted on Amazon S3 and am attempting to use Amazon Athena to query this dataset. My objective is to search within the HTML content of the web pages to identify those that contain specific strings within their tags. Essentially, I am looking to filter out websit...
This is not easily possible, because the html content is not in the schema of the index that you are querying. Please see the Common Crawl Columnar Index blog post for further details. The most common use of this index is to select a small subset of the crawl (things like "all webpages with a Swiss domain name (*.ch) c...
3
1
77,254,777
2023-10-8
https://stackoverflow.com/questions/77254777/alternative-to-concat-of-empty-dataframe-now-that-it-is-being-deprecated
I have two dataframes that can both be empty, and I want to concat them. Before I could just do : output_df= pd.concat([df1, df2]) But now I run into FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA colu...
To be precise, concat is not deprecated (and won't be IMHO) but I can trigger this FutureWarning in 2.1.1 with the following example, while df2 being an empty DataFrame with a different dtypes than df1 : df1 = pd.DataFrame({"A": [.1, .2, .3]}) df2 = pd.DataFrame(columns=["A"], dtype="object") out = pd.concat([df1, df2]...
43
26
77,227,895
2023-10-4
https://stackoverflow.com/questions/77227895/polars-sql-context-filter-by-date-or-datetime
I'm trying to write a query against parquet using Polars SQL Context. It's working great if I pre-filter my arrow table by date. I cannot figure out how to use date in the SQL query. works: filters = define_filters(event.get("filters", None)) table = pq.read_table( f"s3://my_s3_path{partition_path}", partitioning="hive...
Update: Implicit string → temporal conversion in SQL comparisons was added in Polars 0.20.26 https://github.com/pola-rs/polars/pull/15958 The original query now runs as expected. import polars as pl df = pl.DataFrame({ "a": ["2023-06-01", "2023-06-01", "2023-06-02"], "b": [None, None, None], "c": [4, 5, 6], "d": [Non...
4
3
77,259,434
2023-10-9
https://stackoverflow.com/questions/77259434/python-testing-assertions-unittest-playwright
so im new to testing and have been learning python/playwright testing for a couple of weeks now. I've got to assertions and have found multiple ways to write them, so this might sound like a stupid question but which of these 3 types of assertions would be best to use, or is there one that i don't know about that is be...
When using Playwright, almost always use the Playwright assertion, which waits for the predicate to be true. Consider the following simple example: from playwright.sync_api import expect, sync_playwright html = r"""<!DOCTYPE html><html><body> <h1>NO!</h1> <script> setTimeout(() => { document.querySelector("h1").textCon...
2
6
77,238,856
2023-10-5
https://stackoverflow.com/questions/77238856/problems-installing-libraries-via-pip-after-installing-python-3-12
Today I installed the new Python 3.12 on my Ubuntu 22.04 from the ppa repository ppa:deadsnakes/ppa. Everything works, but when I try to install some library with the command python3.12 -m pip install somelibrary, I get the following error ERROR: Exception: Traceback (most recent call last): File "/usr/lib/python3/dist...
python3.12 -m ensurepip --upgrade fixed my problem! solution
15
17
77,227,048
2023-10-4
https://stackoverflow.com/questions/77227048/django-testing-views-getting-error-discoverrunner-run-tests-takes-2-positi
I use Django framework to create basic web application. I started to write tests for my views. I followed the django documentation and fixed some issues along the way. But now I am stuck - I don't know why I get this error even after 30 minutes of searching for answer. C:\Osobni\realityAuctionClient\venv\Scripts\pytho...
Django removed the parameter extra_tests in Django 5.0 and PyCharm's test runner is still providing it. See django's release notes: The extra_tests argument for DiscoverRunner.build_suite() and DiscoverRunner.run_tests() is removed. You could downgrade to django 4.2 until this is fixed by Jetbrains. A Pycharm issue r...
5
11
77,267,346
2023-10-10
https://stackoverflow.com/questions/77267346/error-while-installing-python-package-llama-cpp-python
I am using Llama to create an application. Previously I used openai but am looking for a free alternative. Based on my limited research, this library provides openai-like api access making it quite easy to add into my prexisting code. However this library has errors while downloading. I tried installing cmake which did...
You need to install the desktop c++ block with visual studio to get cmake properly installed.Open the Visual Studio Installer and click Modify, then check Desktop development with C++ and click Modify to start the install. I also recommend the Windows 10 SDK. https://learn.microsoft.com/en-us/cpp/build/cmake-projects-i...
15
15
77,266,318
2023-10-10
https://stackoverflow.com/questions/77266318/defining-an-annotatedstr-with-constraints-in-pydantic-v2
Suppose I want a validator for checksums that I can reuse throughout an application. The Python type-hint system has changed a lot in 3.9+ and that is adding to my confusion. In pydantic v1, I subclassed str and implement __get_pydantic_core_schema__ and __get_validators__ class methods. v2 has changed some of this and...
For pydantic you need to annotate your fields, but you're assigning them. The following code should do the trick for you from typing import Annotated from pydantic import BaseModel, StringConstraints ChecksumString = Annotated[str, StringConstraints(pattern="^[a-fA-F0-9]{64}$")] class GeneralThing(BaseModel): special_s...
8
8
77,233,855
2023-10-5
https://stackoverflow.com/questions/77233855/why-did-i-get-an-error-modulenotfounderror-no-module-named-distutils
I've installed scikit-fuzzy but when I import skfuzzy as fuzz I get an error ModuleNotFoundError: No module named 'distutils'" I already tried to pip uninstall distutils and got this output Note: you may need to restart the kernel to use updated packages. WARNING: Skipping distutils as it is not installed. Then I tri...
Python 3.12 does not come with a stdlib distutils module (changelog), because distutils was deprecated in 3.10 and removed in 3.12. See PEP 632 – Deprecate distutils module. You can still use distutils on Python 3.12+ by installing setuptools. When that doesn't work, you may need stay on Python < 3.12 until the 3rd-par...
52
83
77,260,536
2023-10-9
https://stackoverflow.com/questions/77260536/run-adb-shell-and-then-interact-with-console-app-in-python
I have a situation where I need to run the adb shell command which takes me to the root access of my device. Then I run the interactive console app against my device using this command: /oem/console --no-logging. The command returns this output: Console Process: connecting to application... Console Process: connected ...
So, after a couple of days of research, I found a solution from this post https://stackoverflow.com/a/56051270/4911426. I had to use an asynchronous subprocess for chaining different commands together.
3
5
77,267,596
2023-10-10
https://stackoverflow.com/questions/77267596/mypy-type-stubs-for-aws-lambda-function
Are there maintained mypy types published for AWS Lambda functions? I'm talking here about defining a function to handle an HTTP request (from a lambda URL or API Gateway). I'm not talking about other AWS Lambda-related APIs such as are exposed for example by boto3. Here's a example of the kind of function I would like...
Check out Powertools for AWS Lambda. It includes typings for LambdaContext as well as dataclasses for event sources such as ALBEvent. from aws_lambda_powertools.utilities.data_classes import ALBEvent from aws_lambda_powertools.utilities.typing import LambdaContext @event_source(data_class=ALBEvent) def lambda_handler(l...
3
3
77,262,501
2023-10-10
https://stackoverflow.com/questions/77262501/how-to-alter-cipher-suite-used-with-python-requests
This is part of a larger program I'm working on, but I've got it pinpointed down to the exact problem. When I use Python requests module in some environments it works but not others and it seems to be related to the cipher suite being used by SSL. When I run the following command in Python, it gives an error or success...
So indeed the problem is the server is using an outdated cipher. And the issue is that Windows 11 and Ubuntu 22 will not use that outdated cipher by default. The issue also is that in the version of requests that I was using (2.31.0), you can no longer change the cipher suite with requests.packages.urllib3.util.ssl_.DE...
3
6
77,269,234
2023-10-10
https://stackoverflow.com/questions/77269234/turtle-nameerror-after-defining-a-variable-in-a-separate-function
I want to create a turtle game. When I click the turtle shape in the game, it should give score +1 point so that I can count the points. But when I execute the command and click on the turtle shape it is giving me a name error which is NameError: name 'score_turtle' is not defined even though it is defined in the upper...
Variables are scoped to the function by default. That means that when the function returns, all variables in the function scope are destroyed. Luckily, functions let you return values, so you can do something like: def score_turtle_setup(): score_turtle = turtle.Turtle() # ... return score_turtle # ... score_turtle = s...
3
2
77,269,011
2023-10-10
https://stackoverflow.com/questions/77269011/how-to-get-the-callable-function-defined-by-exec-in-python
Say I want to have a function exec_myfunc that can execute any user-defined function with an input value of 10. The user is supposed to define the function by a string as shown below: func1_str = """ def myfunc1(x): return x """ func2_str = """ def myfunc2(x): return x**2 """ Right now I am using a very hacky way, by ...
You could directly use exec: def exec_myfunc(func_str: str): fun = {} # to hold your function exec(func_str,fun) fun_name = list(fun.keys())[1] fn = fun[fun_name] print(f"The function {fun_name} evaluated at 10 = {fn(10)}") exec_myfunc(func1_str) The function myfunc1 evaluated at 10 = 10
2
1
77,268,771
2023-10-10
https://stackoverflow.com/questions/77268771/how-to-make-a-cluster-of-items-based-on-membership
I need like a magnet effect to form a cluster within a list of unique items. My input is this : lst1 = ['ah', 'ab', 'c', None, 'xo', 'i', 'b', 'lji', 'z', 'bel', 'oyb'] So based on a given item (a string that could be of any length), we need to move from left and right (towards this item) every string that contains it...
One possible solution is to use list slicing + sorting: letter = "b" lst1 = ["ah", "ab", "c", None, "xo", "i", "b", "lji", "z", "bel", "oyb"] index = lst1.index(letter) out = ( sorted(lst1[:index], key=lambda v: letter in v if isinstance(v, str) else False) + [letter] + sorted(lst1[index + 1 :], key=lambda v: letter no...
2
1
77,268,673
2023-10-10
https://stackoverflow.com/questions/77268673/cannot-install-matplotlib-in-python-3-12
When i try to install matplotlib 3.8.0 in my conda environment with miniconda package manager i get the following error : Solving environment: / warning libmamba Added empty dependency for problem type SOLVER_RULE_UPDATE failed LibMambaUnsatisfiableError: Encountered problems while solving: - cannot install both pin-1-...
As of the writing of the question, python 3.12 is just a few days old. Days! You don't have to downgrade your python to 3.9. It's conda. You just use another enviroronment for a python 3.9 and install whatever is needed. That's what Conda is made for. Matplotlib already works pretty fine with Python 3.11. No need to g...
2
5
77,266,671
2023-10-10
https://stackoverflow.com/questions/77266671/polars-drop-duplicate-row-based-on-column-subset-but-keep-first
Given the following table, I'd like to remove the duplicates based on the column subset col1,col2. I'd like to keep the first row of the duplicates though: data = { 'col1': [1, 2, 3, 1, 1], 'col2': [7, 8, 9, 7, 7], 'col3': [3, 4, 5, 6, 8] } tmp = pl.DataFrame(data) ┌──────┬──────┬──────┐ │ col1 ┆ col2 ┆ col3 │ │ --- ┆...
You can use DataFrame.unique; the flexible keep keyword argument is here in Polars. tmp.unique(('col1', 'col2'), keep='first', maintain_order=True)
2
6
77,251,236
2023-10-7
https://stackoverflow.com/questions/77251236/cloudbuild-failing-on-flask-app-due-to-incopatibility-of-functions-framework-and
I'm trying to build my code using CloudBuild, but it's failing with the following message: Error: Error while updating cloudfunction configuration: Error waiting for Updating CloudFunctions Function: Error code 3, message: Build failed: found incompatible dependencies: "functions-framework 3.0.0 has requirement flask<3...
Solved by setting fixed (latest) version of functions-framework, which is 3.4.0 at the time of writing this comment in my requirements.txt. Why GCP doesn't use latest version of their own libary is beyond me.
3
5
77,228,915
2023-10-4
https://stackoverflow.com/questions/77228915/window-all-throwing-an-error-with-pyflink-kafka-connector
I am trying to print the datastream by applying the tumbling process window for every 5 seconds. Since I couldn't implement the custom deserializer for now, I created the process function which returns the result as tuple, and as per this documentation link I could link the process function with the windowing operation...
The problem is for windowing you need to use ProcessWindowFunction and not ProcessFunction. Ideally, your code should look like this: class ExtractingRecordAttributes(ProcessWindowFunction): def __init__(self): pass def process(self, key: str, context: 'ProcessWindowFunction.Context', elements: Iterable[Tuple[str, str]...
3
1
77,258,692
2023-10-9
https://stackoverflow.com/questions/77258692/how-can-i-efficiently-get-multiple-slices-out-of-a-large-dataset
I want to get multiple small slices out of a large time-series dataset (~ 25GB, ~800M rows). At the moment, this looks something like this: from polars import pl sample = pl.scan_csv(FILENAME, new_columns=["time", "force"]).slice(660_000_000, 3000).collect() This code takes about 0-5 minutes, depending on the position...
You should be able to run them all in parallel with .collect_all() lf = pl.scan_csv(FILENAME, new_columns=["time", "force"]) samples = [ lf.slice(660_000_000, 3000), lf.slice(890_000_000, 5000), ... ] samples = pl.collect_all(samples)
2
3
77,257,750
2023-10-9
https://stackoverflow.com/questions/77257750/how-to-move-up-values-in-specific-columns-as-long-as-possible
My input is this dataframe : df = pd.DataFrame({'class': ['class_a', 'class_a', 'class_a', 'class_a', 'class_b', 'class_b', 'class_c', 'class_c', 'class_d'], 'id': ['id1', 'id2', 'id3', '', '', 'id4', 'id5', '', 'id6'], 'name': ['abc1', '', '', 'abc2', 'abc3', '', '', 'abc4', 'abc5']}) print(df) class id name 0 class_a...
Use DataFrame.melt with sorting by key parameter for correct ordering, then reshape by DataFrame.pivot with GroupBy.cumcount and last remove empty rows if exist at least one value: out = (df.melt('class').sort_values('value', key=lambda x: x.eq('')) .assign(g = lambda x: x.groupby(['class','variable']).cumcount()) .piv...
2
2
77,257,822
2023-10-9
https://stackoverflow.com/questions/77257822/melting-only-one-level-of-a-multi-index-dataframe
I am working with a MultiIndex DataFrame and would like to melt out one of the column levels, I have found a way to do this but it involves a two step process (detailed below). I am wondering if there is a way in which I can use df.melt() to achieve the intended result in one step Here is a simplified example of the df...
You just need to stack: df_desired = df.stack(0) With name: df_desired = df.rename_axis(['location', None], axis=1).stack('location') Output: temp_avg temp_predicted date location 2013-01-01 A 0.018696 -1.135884 B 0.064724 0.790992 2013-01-02 A -1.572779 -0.365371 B -0.572017 0.742684 2013-01-03 A -3.018399 1.081398...
2
3
77,255,758
2023-10-9
https://stackoverflow.com/questions/77255758/how-can-i-mock-my-environment-variables-for-my-pytest
I've looked at some examples to mock environment variables. Here In my case, I have to mock a variable in my config.py file that is setup as follows: class ServiceConfig(BaseSettings): ... API_AUDIENCE: str = os.environ.get("API_AUDIENCE") ... ... I have that called here: class Config(BaseSettings): auth: ClassVar[Ser...
To update the environment, and restore it after the test: import os from unittest import mock @pytest.fixture() def setenvvar(monkeypatch): with mock.patch.dict(os.environ, clear=True): envvars = { "API_AUDIENCE": "https://mock.com", } for k, v in envvars.items(): monkeypatch.setenv(k, v) yield # This is the magical bi...
4
8
77,245,595
2023-10-6
https://stackoverflow.com/questions/77245595/fastapi-testclient-overriding-lifespan-function
In a more complicated setup using the python dependency injector framework I use the lifespan function for the FastAPI app object to correctly wire everything. When testing I'd like to replace some of the objects with different versions (fakes), and the natural way to accomplish that seems to me like I should override ...
I found a solution to my problem that didn't include overriding the lifespan function, so not a general solution to my questions above. As I mentioned my specific problem in the real application was using the python dependency injector framework, and it provides and override method for it's containers. So the solution ...
6
1
77,234,199
2023-10-5
https://stackoverflow.com/questions/77234199/msys2-and-embedding-python-no-module-named-encodings
I'm trying to use embedded python in my C++ dll library. The library is built and compiled in MSYS2 using GCC compiler, CMake and Ninja. Python 3.10 is also installed on MSYS2 using pacman. Windows 10 env contains C:\msys64\mingw64\bin in Path (python is also located there). Python doesn't installed on Windows, only on...
I set PYTHONHOME=C:\msys64\mingw64\bin and more important PYTHONPATH=C:\msys64\mingw64\lib\python3.10;C:\msys64\mingw64\lib\python3.10\site-packages;C:\msys64\mingw64\lib\lib-dynload and it solved my problem
3
2
77,253,713
2023-10-8
https://stackoverflow.com/questions/77253713/calling-loc-with-a-boolean-array-containing-na
The pandas doc on loc states that it can be used with boolean arrays, more specifically it states the following: "Allowed inputs are: ... A boolean array (any NA values will be treated as False)." My question: How can u create a boolean array containing NA-values? I mean: A numpy bool array can't contain Nans and if we...
I think they mean a BooleanArray (which can be created with pd.array) : Array of boolean (True/False) data with missing values. t1 = [True,False,False,np.nan] out = d_test.loc[pd.array(t1, dtype="boolean")] So, since np.nan is treated as False, only the first row is being selected by the mask. Output : print(out) id...
3
3
77,249,095
2023-10-7
https://stackoverflow.com/questions/77249095/python-select-linter-option-is-missing
VS Code is missing "Python: Select Linter" option when trying to run a command (F1 or Ctrl/CMD+Shift+P). Previously, (2 days ago) this option was available. Is there a way to restore this option or is there a new alternative? I have tried creating new VS Code profile and installing just Python extension - still no ment...
Rolling back Python extension to previous version (v2023.16.0) restores the option.
4
0
77,252,117
2023-10-8
https://stackoverflow.com/questions/77252117/what-is-the-difference-between-built-in-sum-and-math-fsum-in-python-3-12
In the What's New document for 3.12 there is a point: sum() now uses Neumaier summation to improve accuracy and commutativity when summing floats or mixed ints and floats. (Contributed by Raymond Hettinger in gh-100425.) But also there is a math.fsum function that is intended to be used for exact floating-point numbe...
Here is the GitHub issue from your question: https://github.com/python/cpython/issues/100425 According to the detailed discussion there, sum has been about 10x faster that fsum. This new optimisation is supposed to run in parallel to the summation, making it essentially free. sum is now more accurate than before. fsum ...
5
5
77,251,673
2023-10-7
https://stackoverflow.com/questions/77251673/futurewarning-dataframe-groupby-with-axis-1-is-deprecated-do-frame-t-groupby
I have been using these two lines to get stock data: df = yf.download(tickers, group_by="ticker") d = {idx: gp.xs(idx, level=0, axis=1) for idx, gp in df.groupby(level=0, axis=1)} from https://stackoverflow.com/a/66989947/21955590. While it works fine, I can't figure out how to avoid getting the warning in the title. ...
Edit: In fact, you don't need groupby: d = {ticker: df[ticker] for ticker in df.columns.levels[0]} There is a discussion about groupby(axis=1) on github. Another solution is to stack the ticker level: d = {idx: gp.xs(idx, level=1) for idx, gp in df.stack(level=0).groupby(level=1)} Output: >>> d {'AAPL': Open High Lo...
6
4
77,251,464
2023-10-7
https://stackoverflow.com/questions/77251464/how-to-merge-rows-with-nearest-values-in-dataframe
I have a DataFrame like this: index B 0 1 1 2 2 5 3 6 4 7 5 10 And i need to merge rows where the difference is less than or equal 2, select the line with the smaller value and set count merges The result should be like this : index B count 0 1 2 1 5 3 2 10 1 How can this be solved using pandas?
Very similar to @AndrejKesely, just shorter syntax, using named aggregations: df.groupby(df["B"].diff().gt(2).cumsum(), as_index=False).agg(B=("B", "first"), count=("B", "count")) Output: B count 0 1 2 1 5 3 2 10 1
3
7
77,250,919
2023-10-7
https://stackoverflow.com/questions/77250919/matrix-multiplication-of-numpy-ndarrays
I have a two numpy arrays a, B like this. >> a [1 2 3] >> type(a) <class 'numpy.ndarray'> >> B [[1 2 3] [2 2 7] [3 4 6]] >> type(B) <class 'numpy.ndarray'> I want to do the matrix multiplication like a * B * a_transpose which is (1*3)*(3*3)*(3*1) type matrix multiplication which should result in (1*1). How do I do thi...
a.T is the transpose of matrix a temp = np.dot(a, B) # a * B final= np.dot(temp, a.T) #(a * B) * a_transpose Answer for your example is 155
2
1
77,248,861
2023-10-7
https://stackoverflow.com/questions/77248861/failing-to-run-turtle-graphics-program-on-macos
I'm a Python newbie working on my first Turtle Graphics program. This is what I have at the moment import turtle def draw_square(): window = turtle.Screen() window.bgcolor("red") brad = turtle.Turtle() brad.forward(100) window.exitonclick() draw_square() This code works perfectly on my friend's Windows laptop: Howeve...
This is a known issue that arises due to an incompatibility between MacOS and Tkinter, on which Turtle is based. In the terminal, use the following code: brew install tcl-tk env \ PATH="$(brew --prefix tcl-tk)/bin:$PATH" \ LDFLAGS="-L$(brew --prefix tcl-tk)/lib" \ CPPFLAGS="-I$(brew --prefix tcl-tk)/include" \ PKG_CONF...
3
2
77,248,988
2023-10-7
https://stackoverflow.com/questions/77248988/how-importing-from-a-script-works-differently-than-importing-from-a-module
I have a structure of files and folders like this: package1/ p1.py package2/ p2.py Contents of package1/p1.py: def p1fun(): print("p1fun") Contents of package1/package2/p2.py: import package1.p1 if __name__ == '__main__': package1.p1.p1fun() Now, when I do python -m package1.package2.p2, I get the correct result = p...
You just have to add the directory containing package1 to sys.path. A simple way is to set the PYTHONPATH environment variable to .: export PYTHONPATH='.' # on Linux or other Unix-like set PYTHONPATH=. # on Windows Underlying cause: As explained by @KlausD. , python automatically adds the path of the script passed on ...
2
3
77,240,105
2023-10-5
https://stackoverflow.com/questions/77240105/python-typing-generic-type-that-has-the-same-interface-as-the-wrapper-type
I would like to define a sort of "wrapper" Generic Type, say MyType[T], so that it has the same type interface as the wrapped type. from typing import Generic, TypeVar T = TypeVar("T") class MyType(Generic): pass # what to write here? So, as an example, when I have a type MyType[int], the type-checker should treat it ...
To confirm, you're looking at wanting the expression MyType[T] to mean to a static type checker "A subclass of MyType and T", such that a declaration class MyType: attr: object will result in the following (e.g. using mypy and int.conjugate as an example): >>> reveal_type(MyType[int].conjugate) # def (self: builtins.i...
5
3
77,235,342
2023-10-5
https://stackoverflow.com/questions/77235342/run-external-program-inside-a-conda-environment-in-r
I am trying to run stitchr in R. For programs that run in Python, I use reticulate. I create a conda environment named r-reticulate, where I want to install stitchr and run it. I try the following: if (!('r-reticulate' %in% reticulate::conda_list()[,1])){ reticulate::conda_create(envname = 'r-reticulate', packages = 'p...
Here is maybe what you expect. shell: conda create --name=testenv python # or conda create --name=testenv python==3.10.13 if you want a specific version for jupyter for example conda activate testenv # to be sure which pip is: whereis pip ~/anaconda3/envs/testenv/bin/pip shell stitchr part, read from the doc of stit...
4
0
77,240,340
2023-10-5
https://stackoverflow.com/questions/77240340/python-pandas-select-and-drop-rows-grouped-by-multiple-columns-based-on-conditi
Suppose I have a pandas DataFrame with the following columns and data: user time session time_diff 0 21.0 2022-12-16 14:03:08 5 NaN 1 21.0 2022-12-16 14:03:10 5 2.0 2 21.0 2022-12-16 14:03:12 6 2.0 3 21.0 2022-12-16 14:03:13 6 1.0 4 21.0 2022-12-28 14:49:54 16 1039601.0 5 30.0 2022-12-16 14:03:16 5 1039598.0 6 30.0 20...
Option 1 Group by ["user", "session"] (df.groupby) and check .diff for column "time". For the resulting Series check < 10 seconds using Series.lt. Finally, use the resulting Series (populated with True & False) for boolean indexing to retrieve the desired subset. out = df[df.groupby(["user", "session"])['time'].diff(...
3
3
77,242,993
2023-10-6
https://stackoverflow.com/questions/77242993/how-to-reshape-pandas-dataframe-into-a-symmetric-matrix-corr-like-square-matrix
I have a df like below: name1 name2 value 0 A B 1300 1 A C 150 2 A D 300 3 B C 450 4 B D 200 5 C D 300 I tried to pivot the table to plot a corr-like heatmap based on the value column: table = df.pivot(columns='name1', index='name2', values='value') table The result is: name1 A B C name2 B 1300.0 NaN NaN C 150.0 450...
You can combine_first the transpose after pivoting: # table = df.pivot(columns='name1', index='name2', values='value') out = table.combine_first(table.T) Output: A B C D A NaN 1300.0 150.0 300.0 B 1300.0 NaN 450.0 200.0 C 150.0 450.0 NaN 300.0 D 300.0 200.0 300.0 NaN Alternatively, but less elegant, swap the columns...
2
6
77,235,006
2023-10-5
https://stackoverflow.com/questions/77235006/importerror-cannot-import-name-docstring-from-matplotlib
Recently, my code involving matplotlib.pyplot suddenly stopped working on all my machines (Ubuntu 22.04 LTS). I tried a simple import and got the following error: $ python Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import...
As pointed out in comments by @Imsteffan, and the linked bug reports here and here, the issue happens because: ... docstring was removed after a deprecation cycle of 2 releases and changed to be private (_docstring) However, the line that is erroring in mplot3d/axes3d.py was updated #22148, indicating that you have a ...
6
12
77,235,156
2023-10-5
https://stackoverflow.com/questions/77235156/check-if-a-columns-integer-is-in-another-columns-string-of-integers
A dataframe has two columns. One has a single integer per row. The other has a string of multiple integers, separated by ',', per row: import pandas as pd duck_ids = ["1, 4, 5, 7", "3, 11, 14, 27"] ducks_of_interest = [4,15] duck_df = pd.DataFrame( { "DucksOfInterests": ducks_of_interest, "DuckIDs": duck_ids } ) print(...
You were almost there but unnecessarily used a list and swapped the names: duck_df['DoIinDIDs'] = duck_df.apply(lambda x: str(x['DucksOfInterests']) in x['DuckIDs'], axis=1) Output: DucksOfInterests DuckIDs DoIinDIDs 0 4 1, 4, 5, 7 True 1 15 3, 11, 14, 27 False Note, however, that this approach might fail as you rel...
2
3
77,234,523
2023-10-5
https://stackoverflow.com/questions/77234523/python-is-writing-empty-lists-from-cvs-file-dictreader-data-in-python-3-10
So I have written this piece of code which is meant to read a csv file and write the data to a dictionary with keys "key1" "key2" "key3" "key4" with values given as a list comprised of data from columns of the csv file but with some modifications: import numpy as np import csv #code ... #code with open(file,'r') as fl:...
This looks like it's to do with how your csv.DictReader object is being iterated over. When you do a list comprehension over the csv_file object for key1, you exhaust the iterator. This means that when you try to do the list comprehension for key2, there's no data left in csv_file to iterate over, and so on for the sub...
3
1
77,233,769
2023-10-5
https://stackoverflow.com/questions/77233769/if-a-module-is-an-object-from-the-class-module-why-arent-regular-functions-co
Begginer here trying to understand how python works and i came up with this doubt. Shouldn't all functions be methods? Here's the code i used to verify this my_module.py: def func(): pass Main.py: import inspect import my_module print(inspect.ismethod(my_module.func)) Output: False
Because methods are defined on the class. Any given module is an instance of the class module, not the definition of a new class. Compare to: class Foo: pass f = Foo() f.stuff = lambda: print('stuff') f.stuff is an instance attribute of that particular instance of Foo, not of Foos in general. The descriptor protocol (...
3
4
77,230,983
2023-10-4
https://stackoverflow.com/questions/77230983/why-does-it-take-longer-to-execute-a-simple-for-loop-in-python-3-12-than-in-pyth
Python 3.12 was released two days ago with several new features and improvements. It claims that it's faster than ever, so I decided to give it a try. I ran a few of my scripts with the new version, but it was slower than before. I tried various approaches, simplifying my code each time in an attempt to identify the bo...
I am able to reproduce the observed behavior between CPython 3.11.2 and CPython 3.12.0rc2 on Debian Linux 6.1.0-6 using an Intel i5-9600KF CPU. I tried to use a low-level profiling approach so to find the differences. Put it shortly: your benchmark is very specific and CPython 3.12 is less optimized for this specific c...
11
16
77,232,950
2023-10-4
https://stackoverflow.com/questions/77232950/python-pandas-data-frame-time-difference-between-specific-alternating-values
I have a dataframe of app usage in 4 columns that looks like this: Id Timestamp App_Name Event_Type 1 2018/01/16 06:01:05 Instagram Opened 2 2018/01/16 06:01:06 Instagram Closed 3 2018/01/16 06:01:07 Instagram Opened 4 2018/01/16 06:01:08 Instagram Interaction 5 2018/01/16 06:01:09 Instagram Interaction 6 2018/01/16 06...
Try: out, state = [], None for i, e in zip(df["Id"], df["Event_Type"]): if e == "Opened": state = i elif e == "Closed" and state is not None: out.append([state, i]) state = None print(out) Prints: [[1, 2], [3, 6], [9, 10], [11, 12]] To get time differences: df["Timestamp"] = pd.to_datetime(df["Timestamp"]) out, stat...
3
1
77,232,741
2023-10-4
https://stackoverflow.com/questions/77232741/how-to-block-progression-in-asyncio
So I understand that using async ... await python can prevent blocking and accomplish xyz to follow. But what about the opposite, where I want python to block xyz until an process has completed? For example, suppose I have three functions, A,B & C where A should not block B and vice versa. But C should be blocked by bo...
If I understand you correctly, you want to run A, B in parallel and if they both finish, call C(). You can create tasks from A(), B(), use asyncio.gather() to wait for them to finish and then call C(): import asyncio async def A(): await asyncio.sleep(1) print("A finished") async def B(): await asyncio.sleep(2) print("...
2
4
77,231,765
2023-10-4
https://stackoverflow.com/questions/77231765/how-to-create-a-menu-separator-in-pystray
I am trying to create a pystray menu separator, but I am having a hard time doing so. I have searched here on SO and in its documentation, which I find super confusing and unhelpful and I even tried to read the Menu class: class Menu(object): """A description of a menu. A menu description is immutable. It is created wi...
You have correctly identified the point at which the use of the separator is indicated. However, you should specifically use the SEPARATOR attribute instead of its assigned value because someone might actually want to create a menu item with four hyphens, and it wouldn't be appropriate for pystray to automatically conv...
6
11
77,228,269
2023-10-4
https://stackoverflow.com/questions/77228269/remove-white-area-around-3d-plot
I created a surface plot of a gaussian using matplotlib: num_pts = 1000 σ = 1.5 x = np.linspace(-5, 5, num_pts) kernel1d = np.exp(-np.square(x) / (2 * σ * σ)) kernel2d = np.outer(kernel1d, kernel1d) X, Y = np.meshgrid(x, x) fig, ax = plt.subplots(figsize=(6,6), subplot_kw={"projection":"3d"}) ax.plot_surface(X, Y, kern...
You can play around with the pad_inches value: fig.savefig("test.svg", format="svg", transparent=True, bbox_inches='tight', pad_inches=-0.4) Otherwise, perhaps you can try getting the bounding box containing the paths, and set the axes limits based on that: https://stackoverflow.com/a/76076555/7750891
2
2
77,227,241
2023-10-4
https://stackoverflow.com/questions/77227241/is-there-a-lint-rule-for-python-that-automatically-detects-list-operator-concat
For me the following extras = ["extra0", "extra1"] func_with_list_arg([ "base0", "base1", ] + extras) is nicer to read with a spread operator like the following extras = ["extra0", "extra1"] func_with_list_arg([ "base0", "base1", *extras, ]) Is there a lint rule in ruff or pylint that would detect this situation?
Yes, there is! c = [3] b = [1, 2] + c print(b) When I run (my configured) ruff on this, I get: RUF005 [*] Consider [1, 2, *c] instead of concatenation This is part of the ruff specific ruleset: https://docs.astral.sh/ruff/rules/#ruff-specific-rules-ruf and is a rule which is actually automatically fixable.
2
3
77,226,367
2023-10-4
https://stackoverflow.com/questions/77226367/whats-the-best-way-to-calculate-tp-q-r-sp-q-sp-r-in-numpy
I'm trying to turn a series of m input sequences with n items each (sm,n) into a tensor where tp,q,r = sp,qsp,r While my code does work, I feel there must be a better solution. Here's what I got. # nseqs is the number of sequences # seq_length is the sequence length # seq is a list of sequences output = np.empty((nseqs...
You can achieve the desired result with broadcasting. The first dimensions line up, and the others can be coerced into the right shape using unit dimensions introduced with None: t = s[:, :, None] * s[:, None, :] You can implement your original approach without loops by assigning the elements of output with broadcasti...
3
5
77,225,812
2023-10-3
https://stackoverflow.com/questions/77225812/is-there-a-way-to-install-pytorch-on-python-3-12-0
I'm making an app using gpt-neo and I'm trying to install torch, but it won't install. The error message is as follows: C:\Users\Ben>pip install torch ERROR: Could not find a version that satisfies the requirement torch (from versions: none) ERROR: No matching distribution found for torch Is there any way to install t...
There are now released versions of pytorch available for python 3.12, starting with pytorch 2.2 There should be no need to use the pre-release nightly build for cuda 11.8 and python 3.12, at least there seems to be installation candidates in https://download.pytorch.org/whl/cu118 for python 3.12: torch-2.2.0+cu118-cp31...
11
2
77,202,074
2023-9-29
https://stackoverflow.com/questions/77202074/how-do-i-transcribe-a-multi-language-audio-file-using-whisper-without-translati
I am attempting to transcribe an audio file using the Whisper library which contains alternating English and Indonesian speech. Some of the Indonesian speech is correctly transcribed into Indonesian text, but some of it is translated into English and transcribed. This behaviour seems to be random, different passes with...
You could use WhisperX and leverage its speaker diarization. Make two (or more) transcription passes, one for each language. Merge both results based on speaker and time stamps.
5
5
77,217,220
2023-10-2
https://stackoverflow.com/questions/77217220/pydantic-2-validator-to-add-all-extra-fields-to-unique-dict-field
Both validators and extra columns have different ways of configuration in pydantic 2.*, I would like to know if I can still do a validation to take all the extra fields and put them in a single dictionary field The expected behavior is: class A(BaseModel): name: str extra_columns: Optional[Dict] a = A(name="john", age=...
This can be solved with model_validator: from typing import Any from pydantic import BaseModel, model_validator class A(BaseModel): name: str extra_columns: dict | None = None @model_validator(mode="before") @classmethod def set_extra_columns(cls, data: Any): if isinstance(data, dict): extra_fields = data.keys() - cls....
2
2
77,210,441
2023-10-1
https://stackoverflow.com/questions/77210441/pydantic-typeerror-validate-takes-2-positional-arguments-but-3-were-given
This is my JsonFeedOptions class. class JsonFeedOptions(BaseModel): address: Optional[AddressType] = None signer: Optional[Union[AccountAPI, str]] = None Type: Optional[FeedType] = None And I'm trying to validate the data like this. opts = {"signer": "abcd"} options = JsonFeedOptions.model_validate(opts) But got this...
Which Pydantic version do you use? You can check this by pip list and review the library version (do not forget to activate virtual environment if you have one) The error TypeError: BaseModel.validate() takes 2 positional arguments, but 3 were given is relevant to the difference between Pydantic versions 1 and 2. In Py...
3
9
77,215,107
2023-10-2
https://stackoverflow.com/questions/77215107/importerror-cannot-import-name-url-decode-from-werkzeug-urls
I am building a webapp using Flask. I imported the flask-login library to handle user login. But it shows an ImportError. Below is my folder structure: >flask_blog1 >flaskblog >static >templates >__init__.py >forms.py >models.py >routes.py >instance >site.db >venv >requirements.txt >run.py My run.py: from flaskblog im...
I can only assume you got the Werkzeug 3.0 update (as flask-login didn't up-bound their werkzeug dependency). In their ongoing quest to remove all the non-core public APIs of werkzeug, the developers deprecated most of werkzeug.urls in Werkzeug 2.3 (released April 25th 2023), and removed it in Werkzeug 3.0 (released Se...
15
28
77,219,901
2023-10-3
https://stackoverflow.com/questions/77219901/can-not-change-media-using-setsource-in-pyside6
I have some video clips named 0.mp4, 1.mp4, 2.mp4... and I am using QMediaPlayer in PySide6. I want to write a media player which can play videos one by one. At the end of each video clip, I use the 'setSource()' function to transition to the next clip. But the mainwindow stuck every time I execute setSource() in slot ...
Check the status, play when media is loaded, set source when end of media is reached. class MainWindow(QMainWindow): def __init__(self): super().__init__() self._audio_output = QAudioOutput() self._player = QMediaPlayer() self._player.setAudioOutput(self._audio_output) self._video_widget = QVideoWidget() self.setCentra...
4
0
77,189,542
2023-9-27
https://stackoverflow.com/questions/77189542/how-to-read-corrupted-pickle-file
I have a binary file written using pickle.dump containing logs from an app (a set of tuples of floats and strings), it worked great for 24h but now when trying to read it using import pickle path = "/path/to/file.pkl" with open(path, 'rb') as f: score_board = pickle.load(f) I get UnpicklingError: invalid load key, '\x...
TL;DR Add the right opcodes to the end of your pickle file. Mine should end in 'bsbuu.' but instead ends with 'bsbj' (the opcodes between items). Editing the binary file to put 'bsbuu.' at the end instead of 'bsbj' fixed it. Now my file opens perfectly. Eat it, pickle devs. Your opcodes are probably different since it ...
4
3
77,197,398
2023-9-28
https://stackoverflow.com/questions/77197398/error-running-pyttsx3-code-on-os-x-nameerror-name-objc-is-not-defined
I am trying to run this program using Python 3.11.5 on macOS Ventura 13.6: import pyttsx3 engine = pyttsx3.init() engine.say("Hello, how are you today?") engine.runAndWait() But I am getting this error and I don't know where to start looking: Traceback (most recent call last): File "/Library/Frameworks/Python.framewor...
I checked pypi and I found py3-tts: https://pypi.org/project/py3-tts/ I followed the installation for py3-tts and it works now without the dummy parameter!
2
8
77,204,822
2023-9-29
https://stackoverflow.com/questions/77204822/gekko-ipopt-trajectory-propagation
I am trying to propagate a spacecraft to optimize the time of flight using IPOPT in GEKKO/Python. Here is the code for my GEKKO model: m = GEKKO() #manipulating variables and initial guesses al_a = m.MV(value = -1, lb = -2, ub = 2) al_a.STATUS = 1 l_e = m.MV(value = 0.001, lb = 0, ub = 10**6) l_e.STATUS = 1 l_i = m.MV(...
Conditional statements can't be used to define the equations of the model such as: while t <= tf: deltas, Tp = propagate(a, e, i, Om, om, nu, mass) m.Equation(Tp * a.dt() == (deltas[0] * delta_t * deltas[7])) m.Equation(Tp * e.dt() == (deltas[1] * delta_t * deltas[7])) m.Equation(Tp * i.dt() == (deltas[2] * delta_t * d...
3
1
77,213,053
2023-10-2
https://stackoverflow.com/questions/77213053/why-did-flask-start-failing-with-importerror-cannot-import-name-url-quote-fr
Environment: Python 3.10.11 Flask==2.2.2 I run my Flask backend code in docker container, with BASE Image: FROM pytorch/pytorch:2.0.1-cuda11.7-cudnn8-runtime But when I run the pytest with version pytest 7.4.2, pip install pytest pytest it raised an Error, with logs: ==================================== ERRORS ======...
I had the same problem. It is because Werkzeug 3.0.0 was released and Flask doesn't specify the dependency correctly (requirements says Werkzeug>=2.2.0). This is why, Werkzeug 3.0.0 is still installed and Flask 2.2.2 isn't made for Werkzeug 3.0.0. Solution: Just set a fix version for Werkzeug such as Werkzeug==2.2.2 in...
196
329
77,202,743
2023-9-29
https://stackoverflow.com/questions/77202743/how-to-efficiently-implement-forward-fill-in-pytorch
How can I efficiently implement the fill forward logic (inspired for pandas ffill) for a vector shaped NxLxC (batch, sequence dimension, channel). Because each channel sequence is independent this can be equivalent to working with a tensor shaped (N*C)xL. The computation should keep the torch variable so that the actua...
Here is an approach to this problem, without creating TxT matrix: import torch def forward_fill(t: torch.Tensor) -> torch.Tensor: n_dim, t_dim = t.shape # Generate indices range rng = torch.arange(t_dim) rng_2d = rng.unsqueeze(0).repeat(n_dim, 1) # Replace indices to zero for elements that equal zero rng_2d[t == 0] = 0...
5
1
77,221,564
2023-10-3
https://stackoverflow.com/questions/77221564/add-mypy-options-enable-incomplete-feature-unpack-in-pyproject-toml
I would like to use the experimental typing.Unpack in my project. In the CLI command, it works when adding --enable-incomplete-feature=Unpack. However, I have mypy issues reported by pyright (in neovim), therefore I would like to add this option in the section mypy of pyproject.toml. How can I achieve it?
It should be like this [tool.mypy] enable_incomplete_feature = ["Unpack"]
5
7
77,200,817
2023-9-29
https://stackoverflow.com/questions/77200817/generalized-goertzel-algorithm-for-better-peaks-detection-than-fft-shifted-freq
I have translated the algorithm of the Generalized Goertzel technique in Python from the Matlab code that can be found here. I have trouble using it on real data and only on real data: generating a testing "synthetic" signal with 5 sin components the Goertzel returns correct frequencies, obviously with better accuracy ...
I finally found the point. The Goertzel transform basically counts how many times each harmonic stays inside the sampling period returning, in addition, its amplitude and phase. To get the frequency it is necessary to divide by the number of samples, something that probably is implicitly done by the standard FFT librar...
4
0
77,196,410
2023-9-28
https://stackoverflow.com/questions/77196410/how-can-i-set-authentication-options-for-an-azure-container-app-via-python-sdk
We're using the Python ContainerAppsAPIClient library to deploy a container app to our azure estate, and it works great however I can't find any documentation on how to set the authentication on the container app either during or after it's been created. In the portal it's super easy to do, and there are some models I'...
When I ran your code in my environment, I too got same error in Portal as below: In my case, adding Microsoft as identity provider worked when I included existing application clientId and secret in Python code. For that, you can register one Azure AD application with Redirect URI as <container-app-url>/.auth/login/a...
3
4
77,220,442
2023-10-3
https://stackoverflow.com/questions/77220442/multiprocessing-pool-in-a-python-class-without-name-main-guard
I am attempting to run a multiprocessed job within a larger Python class. In a simple form, the class looks as following: class Thing: def test(self): with mp.Pool() as p: yield from p.map(str, range(20)) When I import this class to a script such as: from x import Thing t = Thing() for item in t.test(): print(item) I...
Since the value of __name__ in the main module of a spawned child process is '__mp_main__' as discussed here, you can place a guard in the function that spawns child processes by checking if any of the ancestors' frames has a __name__ in the global namespace with a value of '__mp_main__', in which case the current proc...
3
3
77,224,368
2023-10-3
https://stackoverflow.com/questions/77224368/init-called-twice
Here is a simplified Python code: class Base: __possible_types__ = {} def __new__(cls, *args, **kwargs) -> type: # pop the `__type__` argument because it # should be passed to the class `__init__` type_ = kwargs.pop("__type__", None) if type_ is not None: possible_type = cls.__possible_types__.get(type_) if possible_t...
The problem. Two distinct calls. Two disctinct calls for Child are made. One as result of the call to Parent(), and the other when you call possible_type(*args, **kwargs) inside Base's constructor. As possible_type e.g. Child does not override __new__, it inherits the first one available from its parents. That ultimate...
2
2
77,224,148
2023-10-3
https://stackoverflow.com/questions/77224148/matching-the-second-ip-address-in-a-range-only-when-its-following-a-specific-te
I have the following patterns (each example is in a different file): example one ----------- alpha: 192.168.50.0 - 192.168.50.24 delta: 192.168.50.100 - 192.168.50.124 other fields: more stuff .... example two ------------- gamma: 200.0.0.0 - 200.0.0.64 lamda: 200.0.0.124 - 200.0.0.255 other fields: more stuff .... I'...
I'd always lean on the excellent ipaddress library whenever dealing with IP addresses because of its easy validity checking (use a simpler regex and just try it), comparison methods (ip in network?), support for IPv4 and IPv6, and understanding of special ranges (global, link_local, multicast..) - additionally, you may...
3
4
77,223,323
2023-10-3
https://stackoverflow.com/questions/77223323/plotting-each-tickline-with-individually-specified-color
I am trying to change the color of the ticklines in my plot, where I would like to assign the colors based on a list of strings with color codes. I am following the following approach, but I cannot see why that does not work: import numpy as np import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = np.sin(x) y2 = n...
As noted in comments, tick._color/tick.set_color(tickcolor) isn't working due to a bug: Using tick.set_markeredgecolor is the workaround, but it doesn't seem to be the only issue. ax1.get_xticklines() yields the actual ticks lines on every two items, you should thus only zip those: for tick, tickcolor in zip(ax1.get_xt...
4
2
77,220,728
2023-10-3
https://stackoverflow.com/questions/77220728/pydantic-accept-integer-as-string-input
For a FastAPI Pydantic interface I want to be as tolerable as possible, such as receiving an integer for a string parameter and parse that integer to string: from pydantic import BaseModel class FooBar(BaseModel): whatever: str FooBar(whatever=12) Gives: ValidationError: 1 validation error for FooBar whatever Input sh...
This functionality was just reintroduced in version 2.4.0. You need to add the coerce_numbers_to_str configuration: from pydantic import BaseModel, ConfigDict class FooBar(BaseModel): model_config = ConfigDict(coerce_numbers_to_str=True) whatever: str
3
8
77,221,619
2023-10-3
https://stackoverflow.com/questions/77221619/how-can-i-find-pseudo-element-using-playwright
In my webpage I have some pseudo elements. For example: How can I find the ::after element using Playwright?
You can't get the pseudo-element because the browser doesn't expose it. But you can get the CSS properties using JavaScript. const someCSSPropertyValue = await page.locator('<selector>').first() .evaluate(el => window.getComputedStyle(el, ':after').someCSSProperty); I bet that will be helpful if you need to test that ...
2
2
77,221,968
2023-10-3
https://stackoverflow.com/questions/77221968/how-to-convert-numpy-array-into-pydub-audiosegment
I have a TTS model and I want to combine audio. I need a way to convert the model output(numpy array) for pydub.AudioSegment to be able to combine audio This is the model output - audio[0].data.cpu().numpy() = array([ 1.90522405e-04, 3.96589050e-04, 4.41852462e-04, ..., 1.13033675e-05, -1.63643017e-05, -2.01268449e-05...
You can rely on audiosegment (a wrapper of a pydub.AudioSegment) and its audiosegment.from_numpy_array method or borrow its underlying method implementation from https://github.com/MaxStrange/AudioSegment/blob/master/docs/api/audiosegment.py#L1145
2
2
77,222,038
2023-10-3
https://stackoverflow.com/questions/77222038/numpy-calculate-values-in-middle
I have numpy array which represents my x-axis, ex. x = [1, 2, 3, 4, 5] I want to get values in the middle of two adjacent element, so my example array should turn into x_interp = [1.5, 2.5, 3.5, 4.5] Is there a fast and convinient way to do this using python/numpy
If you have a numpy array, just slice with a shift: x = np.array([1, 2, 3, 4, 5]) x_interp = (x[1:]+x[:-1])/2 Output: array([1.5, 2.5, 3.5, 4.5]) An alternative (and also more generic approach to get the mean of every N items) would be to use sliding_window_view: from numpy.lib.stride_tricks import sliding_window_view...
2
2
77,221,910
2023-10-3
https://stackoverflow.com/questions/77221910/python-pandas-delete-rows-in-the-past-if-there-is-a-row-on-the-1st-of-january-2
I try to force all users to have a date that starts at the earliest on the 1st of january 2023 with 3 use cases: if there is already data on the 01/01/2023, I want to keep it and delete previous rows If there is no data on the 01/01/2023 but older rows, I want to update the date to 01/01/2023 if the 1st row of a user ...
If I understand correctly, you could force a minimal date with clip, then drop_duplicates keeping the latest row: # ensure datetime df['Date'] = pd.to_datetime(df['Date']) out = (df.assign(Date=df['Date'].clip(lower=pd.Timestamp('2023-01-01'))) .drop_duplicates(subset=['USER', 'Date'], keep='last') ) NB. I am assuming...
2
1
77,221,352
2023-10-3
https://stackoverflow.com/questions/77221352/how-to-freeze-package-version-in-requirements
I have installed the a Python Package with pip install pyjwt[crypto] and pip freeze shows me different packages that was installed by that action. What do I need to put in my requirements.txt to correctly freeze the versions I am developing with? I dont want to put to much in the requirements.txt, only what is needed f...
You can keep your requirements.txt flexible enough, and use a constraint files. This constraint file is basically the output of pip freeze, and pins all versions, including their dependencies. If you need to add a dependency or upgrade, just do this in requirements.txt and regenerate the constraint file. That way, you ...
2
2
77,219,187
2023-10-3
https://stackoverflow.com/questions/77219187/most-optimal-solution-o1-to-question-given-a-single-word-return-a-list-of-an
I received this question in an interview, and coded out a solution, but it was not optimal. Given a stream of words such as: army, ramy, cat, eat, tea.... How can you store these words to support the following query: Given a word return list of anagrams present in the stream Implement Methods: public void storeWords(S...
To detect anagrams, using ascii values to compute a hash is not a strong way to get unique hashes and would require separate handling for collisions. For example, below 2 strings will have the same ascii sum: abd -> 295 bcb -> 295 Instead, you can sort the characters of the string and use this sorted state as the dic...
2
1
77,220,345
2023-10-3
https://stackoverflow.com/questions/77220345/pandas-adding-data-from-a-column-to-another-dataframe-until-a-specific-time-end
df1 is like below, A time 0 32 2023-09-30 08:00:00 1 18 2023-09-30 08:01:00 2 61 2023-09-30 08:02:00 3 87 2023-09-30 08:03:00 4 46 2023-09-30 08:04:00 5 18 2023-09-30 08:05:00 6 65 2023-09-30 08:06:00 7 18 2023-09-30 08:07:00 8 10 2023-09-30 08:08:00 9 93 2023-09-30 08:09:00 and df2 is like below, AA BB Timestamp 0 ...
If I understand correctly, you could define a cumsum delta from your reference (or first value of df2) and use this as a key for merge_asof: start = pd.Timestamp('2023-09-30 08:02:00') out = pd.merge_asof(df2.assign(delta=df2['Timestamp'].sub(df2['Timestamp'].iloc[0]).cumsum()), df1.assign(delta=df1['time'].sub(start)....
2
2
77,218,039
2023-10-2
https://stackoverflow.com/questions/77218039/ways-to-speed-up-rolling-weighted-mean-on-a-pandas-dataframe
I have a large DataFrame, on which I need to calculate the rolling row-wise weighted average. I know I can do the following: import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(20000, 50)) weights = [1/9, 2/9, 1/3, 2/9, 1/9] rolling_mean = df.rolling(5, axis=1).apply(lambda seq: np.average(seq, weig...
Code Creating a new dataframe of multiplying df by weights[0], then shifting df by one and multiplying by weights[1], then shifting df by two and multiplying by weights[2], and repeating this process, then adding all of the created dataframes together, will speed up the process. sum([df.shift(num, axis=1) * w for num, ...
4
5
77,218,116
2023-10-2
https://stackoverflow.com/questions/77218116/i-want-to-make-a-new-grouped-dataframe-that-has-only-the-dates-with-holidays-in
I have a dataframe: dateRep day month year cases deaths country_name Land.area..sq..km. 0 2021-09-21 21 9 2021 1162 7 Austria 82520.0 1 2021-09-20 20 9 2021 1708 7 Austria 82520.0 2 2021-09-19 19 9 2021 2072 5 Austria 82520.0 3 2021-09-18 18 9 2021 2235 9 Austria 82520.0 4 2021-09-17 17 9 2021 2283 8 Austria 82520.0 .....
Convert the dateRep to datetime Series and use .dt. accessor: df["dateRep"] = pd.to_datetime(df["dateRep"]) print(df.loc[(df["dateRep"].dt.weekday == 5) | (df["dateRep"].dt.weekday == 6)]) Prints: dateRep day month year cases deaths country_name Land.area..sq..km. 2 2021-09-19 19 9 2021 2072 5 Austria 82520.0 3 2021-...
2
3
77,217,974
2023-10-2
https://stackoverflow.com/questions/77217974/drop-a-single-column-from-a-pandas-dataframe-index-without-reset-index
I am dealing with a very large DataFrame with many index columns and I wish to convert a few columns from the index to regular columns. Below is a simplified example: df = pd.DataFrame( { 'col_a': [1,2,3], 'col_b': [4,5,6], 'index_1': ['a','b','c'], 'index_2': ['f','g','h'], 'index_to_column': [True,False,False], }, )....
Just specify a level(s) to be reset: df.reset_index(2) index_to_column col_a col_b index_1 index_2 a f True 1 4 b g False 2 5 c h False 3 6 To reset multiple selective indices pass a list of levels positions to df.reset_index like: df.reset_index(level=[0, 2]) or a list of level names: df.reset_index(level=['inde...
2
3
77,196,102
2023-9-28
https://stackoverflow.com/questions/77196102/check-if-table-exists-in-unity-meta-catalog
So I am trying to build a weekly Data import to Unity Catalog in Databricks. I use python. There is no problem overwriting the table in case it exists: %sql Use catalog some_catalog dfTarget #some pandas dataframe df_sparkTarget=spark.createDataFrame(dfTarget) df_sparkTarget.write.format("delta").mode("overwrite").save...
Yes I have found much the same for now until there is documented ways to do this I am using this. Catalog functionality only seems to work for the hivemetastore def schema_exists(catalog:str, schema_name:str): query = spark.sql(f""" SELECT 1 FROM {catalog}.information_schema.schemata WHERE schema_name = '{schema_name}'...
3
5
77,204,189
2023-9-29
https://stackoverflow.com/questions/77204189/how-to-work-with-topics-through-telethon
I need to receive messages from a specific topic, and send them to my channel. there are no problems with sending, but when I try to receive a message from a group, I cannot understand which topic the message is from. (it is not necessary to use telethon) import asyncio import telethon from telethon import TelegramClie...
In v1, the topic is inside the MessageReplyHeader: msg = event.message if msg.reply_to and msg.reply_to.forum_topic: topic_id = msg.reply_to.reply_to_top_id
2
0
77,217,521
2023-10-2
https://stackoverflow.com/questions/77217521/is-psycopg3-a-fork-of-psycopg2-or-a-replacement-upgrade
I see references to both psycopg2 and psycopg3, but no clear guidance wrt a roadmap for transitioning between the two. I see that over time there is a large body of SO questions regarding psycopg2. Is psycopg3 intended to be a replacement for psycopg2? Has there been a significant uptake of this version? Will there be ...
From the documentation of psycopg3: Psycopg 3 is a newly designed PostgreSQL database adapter for the Python programming language. Psycopg 3 presents a familiar interface for everyone who has used Psycopg 2 or any other DB-API 2.0 database adapter, but allows to use more modern PostgreSQL and Python features, such as:...
15
12
77,216,542
2023-10-2
https://stackoverflow.com/questions/77216542/how-to-merge-the-multiple-dataframes-sequentially
Although I thought this question should be duplicated, I couldn't find the proper answer. I have some problems merging multiple dataframes sequentially. For example, I have four dataframes as below: df1 = pd.DataFrame({'source': ['A', 'A', 'A', 'B', 'B', 'C', 'C'], 'target': ['1', '2', '3', '4', '5', '6', '7']}) df2 = ...
This is not a simple merge. You want to concat the df2,df3,df4, then merge with df1: df1.merge(pd.concat([df2,df3,df4]).drop_duplicates(), on='source') Output: source target temp 0 A 1 a 1 A 1 b 2 A 2 a 3 A 2 b 4 A 3 a 5 A 3 b 6 B 4 c 7 B 4 d 8 B 5 c 9 B 5 d 10 C 6 e 11 C 7 e
2
3
77,216,151
2023-10-2
https://stackoverflow.com/questions/77216151/extract-words-from-list-after-specific-character
I have two lists: list_1 = ['08667\nST 403', '08667\nST 403', '08667\nST 403'] list_2 = ['12233\nFION', '12233\nFION', '12233\nFION', '12233\nFION', '31147\nARAB\nP1454'] I want to be able to extract the names after the '\n' keyword. I am using this code: def parse_string(string): string = string.rsplit('\n', 1)[1] re...
You can use list comprehension. It will work for both the lists. list_1 = ['08667\nST 403', '08667\nST 403', '08667\nST 403'] list_2 = ['12233\nFION', '12233\nFION', '12233\nFION', '12233\nFION', '31147\nARAB\nP1454'] [x.split('\n')[1] for x in list_1] #['ST 403', 'ST 403', 'ST 403'] [x.split('\n')[1] for x in list_2] ...
2
1
77,202,124
2023-9-29
https://stackoverflow.com/questions/77202124/pycharm-unable-to-debug-the-python-flask-project
I have a simple Flask based project in Pycharm. I am trying to debug this by right clicking and selecting debug option. But keeps getting below error: Connected to pydev debugger (build 232.9559.58) * Serving Flask app 'app' * Debug mode: on WARNING: This is a development server. Do not use it in a production deploymen...
This appears to be a bug in Pycharm. Multiple issues have been raised for the same in the JetBrains bug tracker. FLASK_DEBUG=1 breaks debugger when Python/PyCharm installation path has spaces Flask Debug session cannot be started in PyCharm Flask debugger is not working on Windows because of white space in installatio...
2
3
77,214,515
2023-10-2
https://stackoverflow.com/questions/77214515/how-to-split-a-numpy-array-to-2d-array-based-on-postive-neagtive-changes
I have a numpy 1D array: import numpy as np arr = np.array([1, 1, 3, -2, -1, 2, 0, 2, 1, 1, -3, -1, 2]) I want split it into another two-dimensional array, based on changes in positive and negative values of array's elements(0 is placed in the range of positive values). But the original order of elements should be mai...
You could use array_split, diff, nonzero: np.array_split(arr, np.nonzero(np.diff(arr>=0))[0]+1) Ouptut: [array([1, 1, 3]), array([-2, -1]), array([2, 0, 2, 1, 1]), array([-3, -1]), array([2])] Intermediates: # arr>0 [ True True True False False True False True True True False False True] # np.diff(arr>=0) [False Fals...
4
4
77,194,570
2023-9-28
https://stackoverflow.com/questions/77194570/warm-start-in-combination-with-new-data-leads-to-broadcasting-error-when-predi
I am trying to train a random forest model with sklearn. I have some original data (x, y) that I use to train the RF initially with. from sklearn.ensemble import RandomForestClassifier import numpy as np x = np.random.rand(30,20) y = np.round(np.random.rand(30)) rf = RandomForestClassifier() rf.fit(x,y) Now I get some...
This runs fine for me in colab, with the same sklearn version 1.2.2 mentioned. I suspect the issue is similar to what was indicated by the now-deleted answer, as well as Scikit-learn Randomforest with warm_start results (non-broadcastable output ...): one of your datasets (in this case, the y_new) doesn't have the same...
3
1
77,208,951
2023-10-1
https://stackoverflow.com/questions/77208951/detect-page-change-in-dash
I am developing a dash web application which is a multi page app. Below is my structure - project/ - pages/ - home.py - contact.py - graph.py - app.py - index.py In app.py, I have a component dcc.Location(id="url", refresh=True), to load different pages to a html.Div(id="page-content") using a callback. The pages are ...
You will probably need a dash callback and the custom script : If navigating to a page within your app via one of the Location links doesn't trigger the visibilitychange event, you can still update the store using a dash callback (defined in app.py, as well as the Location and Store components), eg. @app.callback( Out...
2
2
77,210,131
2023-10-1
https://stackoverflow.com/questions/77210131/can-i-force-pip-to-install-dependencies-for-x86-64-architecture-in-powershell-to
I'm trying to create a lambda layer that includes pydantic/pydantic_core (Lambda python 3.11, x86_64) but getting the following error: "Unable to import module 'reddit_lambda': No module named 'pydantic_core._pydantic_core'" For context, I'm installing this on a windows x64 machine. From reading up about it here, here ...
It is possible as part of the options provided by the pip CLI. For example given a requirements.txt file containing the necessary dependencies, you can run: # Create layer based on requirements.txt in python/ directory pip install -r requirements.txt --platform manylinux2014_x86_64 --target ./python --only-binary=:all:...
4
10
77,209,153
2023-10-1
https://stackoverflow.com/questions/77209153/how-to-dynamically-create-dataframes-with-a-for-loop
My code currently looks like this: df_1 = portfolio_all[0].rename(columns={'Close': 'Close_1'} ) df_2 = portfolio_all[1].rename(columns={'Close': 'Close_2'} ) df_3 = portfolio_all[2].rename(columns={'Close': 'Close_3'} ) df_4 = portfolio_all[3].rename(columns={'Close': 'Close_4'} ) df_5 = portfolio_all[4].rename(column...
You can create using a simple python for-loop and enumerate throught he list import pandas as pd portfolio_all = [df1, df2, df3, df4, df5] for i, df in enumerate(portfolio_all): column_name = f'Close_{i+1}' df.rename(columns={'Close': column_name}, inplace=True) df[f'daily_return_{i+1}'] = df[column_name].pct_change(1)...
2
3
77,208,733
2023-9-30
https://stackoverflow.com/questions/77208733/import-widgets-into-a-function-from-a-class-in-another-file-nameerror-name-te
In the function1 function of the main.py file, i would like to import textbox1 and textbox2 from the Page1(tk.Frame) class of the page1.py file. I get the error NameError: name 'textbox1' is not defined, because textbox1 and textbox2 are not imported correctly. This is the code I'm using. What am I doing wrong? How to ...
As per my knowledge, to access textbox1 and textbox2 in the function1 function in main.py, you should make them instance variables by using self.textbox1 and self.textbox2. import tkinter as tk from tkinter import ttk class Page1(tk.Frame): def __init__(self, master, **kw): super().__init__(master, **kw) self.textbox1 ...
2
3
77,205,133
2023-9-29
https://stackoverflow.com/questions/77205133/implementing-montgomery-ladder-methods-for-modular-exponentiation-in-python
I'm trying to implement the mongomery-ladder method for modular exponentiation for RSA (so N=p•q, p,q are primes) in python, as followed in this paper: My code looks like this: x stands for base, k for exp, and N for modulus # uses montgomery-ladder method for modular exponentiation def montgomery_ladder(x, k, N): x...
Remove the k %= N at the start.
3
4
77,197,885
2023-9-28
https://stackoverflow.com/questions/77197885/is-there-a-way-to-avoid-boilerplate-property-getters-in-python-subclasses-using
I am trying to create subclasses of some superclass that has properties (delineated by the property decorator) and a properties() method that returns the properties and their values as a dict. I want the subclasses to be able to make use of the inherited properties() method with minimal boilerplate code needing to be c...
You can try to use inspect.getmro to get all base classes: from inspect import getmro class BaseClass(object): def __init__(self, A, B): self._A = A self._B = B @property def A(self): return self._A @A.setter def A(self, new_value): self._A = new_value @property def B(self): return self._B @B.setter def B(self, new_val...
3
1
77,200,529
2023-9-29
https://stackoverflow.com/questions/77200529/pandas-select-three-rows-per-id-amongst-varying-number-of-rows
I have a dataset of 100s of people who have been followed up over varying amounts of time (up to 8 observations per person) and have completed a bunch of tests. The time values are always in an integer sequence for each ID. The goal of my project is to examine these changes in individuals, while sampling each person's ...
Using aggregation per group (groupby.agg) with first/median/last, then filtering the IDs with groupby.size, and reshaping with stack: g = df_test.groupby('ID') s = g.size() out = (g.agg(['first', 'median', 'last']) .loc[lambda d: s[s>2].index] # remove groups with < 2 values .stack().reset_index() #.drop(columns=['leve...
2
4
77,200,419
2023-9-29
https://stackoverflow.com/questions/77200419/bulk-create-many-to-many-objects-to-self
Having model class MyTable(Model): close = ManyToManyField("MyTable") How to bulk create objects to this relation? With tables not related to itself, one could use db_payload =[MyTable.close.throught(tablea_id=x, tableb_id=y) for x,y in some_obj_list] MyTable.close.through.objects.bulk_create(db_payload) What would t...
In that case it uses as fields from_model and to_model. Indeed, we can see this in the source code [GitHub]: to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = "to_%s" % to from_ = "from_%s" % from_ So you can work with: MyTable.close.through.objects.bulk_create( [ MyTable.close.t...
3
1
77,198,291
2023-9-28
https://stackoverflow.com/questions/77198291/how-do-i-concatenate-columns-values-all-but-one-to-a-list-and-add-it-as-a-colu
I have the input in this format: import polars as pl data = {"Name": ['Name_A', 'Name_B','Name_C'], "val_1": ['a',None, 'a'],"val_2": [None,None, 'b'],"val_3": [None,'c', None],"val_4": ['c',None, 'g'],"val_5": [None,None, 'i']} df = pl.DataFrame(data) print(df) shape: (3, 6) ┌────────┬───────┬───────┬───────┬───────┬─...
For the main answer in the question you can do df.with_columns(combined = pl.concat_list(pl.exclude('Name'))) pl.exclude is how to get all columns BUT the ones given. To get rid of the nulls in the final list, version 0.19.4 just introduced list.drop_nulls. df.with_columns(combined = pl.concat_list(pl.exclude('Name'))...
2
3
77,197,671
2023-9-28
https://stackoverflow.com/questions/77197671/splitting-a-column-with-delimiter-and-place-a-value-in-the-right-column
I have a data frame with a column that potentially can be filled with 3 options (a,b, and/or c) with a comma delimiter. import pandas as pd df = pd.DataFrame({'col1':['a,b,c', 'b', 'a,c', 'b,c', 'a,b']}) I want to split this column based on ',' df['col1'].str.split(',', expand=True) A problem with this is that new co...
Using str.get_dummies: tmp = df['col1'].str.get_dummies(',') out = tmp.mul(tmp.columns) Output: a b c 0 a b c 1 b 2 a c 3 b c 4 a b With NaNs and custom headers: tmp = df['col1'].str.get_dummies(',') out = (tmp.mul(tmp.columns).where(tmp>0) .rename(columns={'a': 'X', 'b': 'Y', 'c': 'Z'}) ) Output: X Y Z 0 a b c 1 ...
3
3
77,197,748
2023-9-28
https://stackoverflow.com/questions/77197748/arent-the-values-supposed-to-sum-up-for-each-bar
I was expecting for example the F bar to have 8+9=17 and not only 9 (the last value for F). import matplotlib.pyplot as plt x = ['A', 'B', 'C', 'D', 'D', 'D', 'D', 'E', 'F', 'F'] y = [ 5 , 8 , 7, 9, 9, 2, 7, 8, 8, 9 ] fig, ax = plt.subplots() ax.bar(x, y) plt.show(); Can someone explain the logic please ?
No, it's normal, the bars are superimposed. See for example changing the opacity: ax.bar(x, y, alpha=0.1) You can use pandas to group the values: pd.Series(y).groupby(x).sum().plot.bar() Output: Or in pure python: out = {} for X, Y in zip(x, y): out[X] = out.get(X, 0) + Y fig, ax = plt.subplots() ax.bar(*zip(*out.i...
2
3