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,707,524
2023-12-23
https://stackoverflow.com/questions/77707524/how-to-remove-redundancy-when-computing-sums-for-many-rings
I have this code to compute the sum of the values in a matrix that are closer than some distance but further away than another. Here is the code with some example data: square = [[ 3, 0, 1, 3, -1, 1, 1, 3, -2, -1], [ 3, -1, -1, 1, 0, -1, 2, 1, -2, 0], [ 2, 2, -2, 0, 1, -3, 0, -2, 2, 1], [ 0, -3, -3, -1, -1, 3, -2, 0, 0...
Traverse the input square matrix just once to generate an array of pairs where calculated U parameter mapped to the respective value. Then apply a vectorized operation to sum up values filtered by U params matched the condition. def make_U_array(mtx): """Make an array of (U, value) pairs""" arr = np.array([(x * x + x ...
3
2
77,707,167
2023-12-23
https://stackoverflow.com/questions/77707167/pandas-create-new-column-that-contains-the-most-recent-index-where-a-condition
In the below example, I wish to return the last index ocurrance relative to the current row in which the "lower" was >= the "upper" column. I am able to do this with the results as expected but it is not truly vectorized and is very inefficient for larger dataframes. import pandas as pd # Sample DataFrame data = {'lowe...
I'm not sure if this can be vectorized (because you have variables that are dependent on past state). But you can try to speed up the computation using binary search, e.g.: from bisect import bisect_left def get_prev(lower, upper, _date): uniq_lower = sorted(set(lower)) last_seen = {} for l, u, d in zip(lower, upper, _...
3
2
77,705,057
2023-12-22
https://stackoverflow.com/questions/77705057/how-to-pass-a-pem-key-in-github-actions-via-environment-variable-without-charac
I have a GitHub environment secret {{ secrets.GITHUBAPP_KEY } that holds a .pem key, in a workflow step, I'm trying to pass the secret to an env variable GITHUBAPP_KEY - name: Do Certain Step run: Insert fancy command here env: GITHUBAPP_KEY: "${{ secrets.GITHUBAPP_KEY }}" Here is the error the GitHub actio workflow ...
As the SSH private key is spanned over multiple lines, you can assign it to an env var as a multiline string by using pipe | like this: env: GITHUBAPP_KEY: | ${{ secrets.GITHUBAPP_KEY }} See https://yaml-multiline.info/ for interactive examples.
2
5
77,704,406
2023-12-22
https://stackoverflow.com/questions/77704406/how-to-isolate-parts-of-a-venn-diagram
Here is a Venn Diagram I drew in Python: !pip install matplotlib_venn from matplotlib_venn import venn2 import matplotlib.pyplot as plt from matplotlib_venn import venn2 import matplotlib.pyplot as plt set1_size = 20 set2_size = 25 intersection_size = 5 venn2(subsets=(set1_size, set2_size, intersection_size)) plt.show(...
Possible arguments for .get_patch_by_id() include '10', '11', and '01'. See also this link. See the patch documentation for other patch parameters (e.g. color) that you can set. from matplotlib_venn import venn2 import matplotlib.pyplot as plt set1_size = 20 set2_size = 25 intersection_size = 5 fig, ax = plt.subplots()...
2
2
77,704,256
2023-12-22
https://stackoverflow.com/questions/77704256/create-filtered-value-using-pandas
I have a csv file in which the first line reads something like the following: Pyscip_V1.11 Ref: #001=XYZ_0[1234] #50=M3_0[112] #51=M3_1[154] #52=M3_2[254]... and so on. What I'd like to do is create filtered value such that the first column is Ref and it takes all the values after the # sign like 001,50,51,52... The s...
I would open the csv file, extract the first line and process it, only after read the rest of the CSV with pandas. For that, your original approach and regex are fine. import re import pandas as pd with open('my_csv.csv') as f: first_line = next(f) header_df = pd.DataFrame(re.findall(r'#(\d+)=(\w+_\d)\[([\d]+)\]', firs...
3
2
77,698,828
2023-12-21
https://stackoverflow.com/questions/77698828/difference-between-x-in-list-vs-x-in-dict-and-x-in-set-where-x-is-a-pol
This is mostly a question about python: How is x in [a, b, c] evaluated differently than x in {a, b, c}. The context I'm struggling with is like this: import polars as pl s = pl.Series(["a", "b"], dtype=pl.Categorical) s.dtype in [pl.Categorical, pl.Enum] # True s.dtype in {pl.Categorical, pl.Enum} # False s.dtype in {...
EDIT: polars dtypes do not follow the usual equals-contract in multiple ways, and this is considered by design: https://github.com/pola-rs/polars/issues/9564 (thanks @jqurious), specifically, they violate transitivity and hashcode-consistency. In polars, a specific datatype is considered equal to a more general datatyp...
2
5
77,701,771
2023-12-22
https://stackoverflow.com/questions/77701771/unable-to-connect-to-mysql-container-unable-to-create-tables-due-to-2003-hy000
I am trying to connect mysql container with my python flask app and I have this error when running docker-compose build --no-cache && docker-compose up: Creating network "hdbresalepricealert_sql_network" with the default driver Creating hdbresalepricealert_mysql_1 ... done Creating hdbresalepricealert_python_app_1 ... ...
You need to access MySQL with 3306 because it's the port that MySQL listens to inside the Docker container. If you try accessing mysql database with a python script running outside Docker, you'll need to use port 3307 because database is connected with this port on your local machine. "3307:3306" means you connect your...
2
3
77,702,504
2023-12-22
https://stackoverflow.com/questions/77702504/pydantic-exclude-computed-field-from-dump
In pydantic v2, the following code: from __future__ import annotations import pydantic from pprint import pprint class System(pydantic.BaseModel): id: int name: str subsystems: list[System] | None = None @pydantic.computed_field() @property def computed(self) -> str: return self.name.upper() systems = System( id=1, nam...
According to the documentation on computed_field: computed_field Decorator to include property and cached_property when serializing models or dataclasses. This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached. In other words, if don't want to i...
3
2
77,698,814
2023-12-21
https://stackoverflow.com/questions/77698814/mamba-error-while-creating-a-new-virtual-environment-could-not-open-lock-file
When I run the following command: mamba create --name eco-tech-h2gam-venv regionmask cartopy I get this error: Looking for: ['regionmask', 'cartopy'] error libmamba Could not open lockfile 'C:\ProgramData\anaconda3\pkgs\cache\cache.lock' Any idea how to overcome it? Additional Details OS: Windows 11 Anaconda 3 base ...
Lock files can be cleared using the mamba clean --locks command. See in the documentation (abridged): $ mamba clean -h # usage: mamba clean [-h] [-a] [-i] [-p] [-t] [-f] [-c [TEMPFILES ...]] [-l] [--json] [-v] # [-q] [-d] [-y] [--locks] # # Removal Targets: # --locks Remove lock files.
2
1
77,701,188
2023-12-22
https://stackoverflow.com/questions/77701188/how-to-get-features-selected-using-boruta-in-a-pandas-dataframe-with-headers
I have this boruta code, and I want to generate the results in pandas with columns included model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42) # let's initialize Boruta feat_selector = BorutaPy( verbose=2, estimator=model, n_estimators='auto', max_iter=10, # numero di iterazioni da fare rando...
Since support_ is a boolean mask, you can index the columns and create a new dataframe. X_filtered = pd.DataFrame( feat_selector.transform(X.values), columns=X.columns[feat_selector.support_] ) Then again, with the latest master version, you can pass a dataframe to transform() and flag return_df=True. So that would lo...
2
1
77,701,100
2023-12-21
https://stackoverflow.com/questions/77701100/github-self-hosted-runner-complains-of-python-version
I am trying to set a GitHub self-hosted runner for my project and I keep getting the following error: Run actions/setup-python@v3 Version 3.9 was not found in the local cache Error: Version 3.9 with arch x64 not found The list of all available versions can be found here: https://raw.githubusercontent.com/actions/pytho...
As documented, the setup-python action requires that you use a specific version of Ubuntu or Windows (same as the GitHub Actions environments) for the Action to work properly. As noted (emphasis added): Python distributions are only available for the same environments that GitHub Actions hosted environments are availa...
4
2
77,700,624
2023-12-21
https://stackoverflow.com/questions/77700624/weird-behavior-checking-if-np-nan-is-in-list-from-pandas-dataframe
It seems that checking if np.nan is in a list after pulling the list from a pandas dataframe does not correctly return True as expected. I have an example below to demonstrate: from numpy import nan import pandas as pd basic_list = [0.0, nan, 1.0, 2.0] nan_in_list = (nan in basic_list) print(f"Is nan in {basic_list}? {...
TL;DR pandas is using different nan object than np.nan and in operator for list checks if the object is the same. The in operator invokes __contains__ magic method of list, here is source code: static int list_contains(PyListObject *a, PyObject *el) { PyObject *item; Py_ssize_t i; int cmp; for (i = 0, cmp = 0 ; cmp ==...
3
2
77,693,813
2023-12-20
https://stackoverflow.com/questions/77693813/populate-nan-cells-in-dataframe-table-based-on-reference-table-based-on-specific
I have two tables. The first reference table is below: | Name | Target | Bonus | |------|--------:|------:| | Joe | 40 | 46 | | Phil | 38 | 42 | | Dean | 65 | 70 | The Python code to generate the table is: # Data for the table data = { 'Name': ['Joe', 'Phil', 'Dean'], 'Target': [40, 38, 65], 'Bonus': [46, 42, 70] } # ...
Only one block of NaN per column at most Another possible solution, which loops through the df columns corresponding to each person and, for each block of NaN (identified by loc), assigns the corresponding block of values in ref (also identified by loc): names = ['Joe', 'Dean'] d = ref.assign(Score = ref['Target']) for...
2
2
77,700,489
2023-12-21
https://stackoverflow.com/questions/77700489/how-to-perform-a-conditional-sort-in-polars
I'm performing a binary classification and I want to manually review cases where the model either made an incorrect guess or it was correct but with low confidence. I want the most confident incorrect predictions to appear first, followed by less confident predictions, followed by correct predictions sorted from least ...
You made your example with random numbers and then listed off the names as though they're fixed so therefore I don't have the same order as you're saying but from the description I believe this is right. df.sort([ (good_pred:=pl.col('truth').eq(pl.col('prediction'))), (good_pred-1)*pl.col('confidence'), pl.col('confide...
2
2
77,699,109
2023-12-21
https://stackoverflow.com/questions/77699109/replace-nan-values-in-a-column-with-values-from-a-different-column-from-the-same
I'm very new to polars and i'm trying to translate some pandas statements. The pandas line is as follows: df.loc[df['col_x'].isna(), 'col_y'] = df['col_z'] that is to say: replace the values of col_y corresponding to null values of col_x with values of col_z. In polars i'm trying with select, but to no avail.
Here you have the solution for Polars and Pandas: Polars: df = ( df .with_columns(pl.when(pl.col('col_x').is_nan()).then(pl.col('col_z')) .otherwise(pl.col('col_y')).alias('col_y')) ) Pandas: df["col_y"] = np.where(pd.isnull(df['col_x']), df['col_z'], df['col_y']) I hope this helps!
2
3
77,696,026
2023-12-21
https://stackoverflow.com/questions/77696026/cannot-close-browser-in-drissionpage
I have move from Selenium/SeleniumBase to DrissionPage for it's Undetectable Ability. Everything was easy to understand. Except the last part of it. That is Closing the Browser. The Docs says that page.quit() would close the browser. But When I run it in my local machine I get this error: Exception in thread Thread-1: ...
I am the author of DrissionPage, thank you for liking my work. Version 4.0 is fine. Now in beta, the latest is 4.0.0b26. pip install DrissionPage==4.0.0b26
2
4
77,692,905
2023-12-20
https://stackoverflow.com/questions/77692905/opencv-contour-width-measurement-at-intervals
I wrote a OpenCV python script to identify the contour of an object in a microscope image. Selected contour image example: I need to meassure the width of the object at N intervals, where width is the distance between the right side to the left side of the contour in that interval, the line meassured is always horison...
I had a little attempt at this as follows: #!/usr/bin/env python3 import cv2 as cv import numpy as np # Load image and extract width and height im = cv.imread('osjKP.jpg') h, w = im.shape[:2] # Convert to HSV to find all the green pixels HSV = cv.cvtColor(im, cv.COLOR_BGR2HSV) lo = np.array([50,200, 100]) # lower limit...
2
1
77,694,820
2023-12-20
https://stackoverflow.com/questions/77694820/how-can-i-implement-retry-policy-with-httpx-in-python
I need to communicate with other services in my Python and FastAPI application, therefore I use the httpx library to be able to communicate asynchronously. So, I have the following code for POST requests: from typing import Any, Dict, Optional, Tuple from fastapi import File from httpx._client import AsyncClient async ...
With the Async HTTPTransport class of httpx you can configure retry: from typing import Any, Dict, Optional, Tuple from fastapi import File from httpx import AsyncHTTPTransport from httpx._client import AsyncClient transport = AsyncHTTPTransport(retries=3) async def post( *, url: str, files: Optional[Dict[str, File]] =...
3
6
77,693,044
2023-12-20
https://stackoverflow.com/questions/77693044/transform-a-string-representing-a-list-in-each-cell-of-a-polars-dataframe-column
I am new to polars library and the title says it all regarding what I am trying to do. Doing this with the pandas library I would use apply() and the build in eval() function of Python. since eval("[1,2,3]") returns [1,2,3]. This can be done in polars as well - below I have an expected output example - but polars stron...
As long as your string column is valid JSON, you could use polars.Expr.str.json_decode as follows. df.with_columns( pl.col("col_string").str.json_decode().alias("col_list") ) Output. shape: (2, 2) ┌────────────┬───────────┐ │ col_string ┆ col_list │ │ --- ┆ --- │ │ str ┆ list[i64] │ ╞════════════╪═══════════╡ │ [1,2,3...
4
2
77,692,836
2023-12-20
https://stackoverflow.com/questions/77692836/how-to-promote-qpdfview-in-qt-designer
I am trying to upgrade my PDF viewer on a form from QWebEngineView to QPdfView (PyQt6). I originally promoted QWebEngineView in the QT Designer without an issue but as far as PDF functionality its a bit limited so upgrading to QPdfView. I promoted using QWidget as base: <?xml version="1.0" encoding="UTF-8"?> <ui versi...
This is a "bug" (quotes required) caused by the fact that, unlike any other widget, the parent argument of QPdfView is required. When child widgets are created by uic, they are always created with their parent in the constructor, using the parent=[parent widget] keyword. PyQt classes are a bit peculiar, and their const...
2
3
77,689,241
2023-12-20
https://stackoverflow.com/questions/77689241/how-can-literal-be-invoked-with-square-brackets-e-g-literaltest1
The following code snippet shows a function named Literal being invoked with square brackets: Literal['r', 'rb', 'w', 'wb'] The example is from the CPython GitHub repo Though we can use square brackets to call instances by using __getitem__ method in Python classes, it doesn't seem to be the case here.
In the source code there are these decorators @_TypedCacheSpecialForm # this is a class @_tp_cache(typed=True) # not relevant here def Literal(self, *parameters): ... _TypedCacheSpecialForm is a class, when using a class a decorator the function, here def Literal, is used to initialize an instance. Written differently...
2
2
77,690,364
2023-12-20
https://stackoverflow.com/questions/77690364/how-to-return-plain-text-in-fastapi
In this example, the entrypoint http://127.0.0.1:8000/ returns formatted text: "Hello \"World\"!" The quotes are masked by a slash, and quotes are added both at the beginning and at the end. How to return unformatted text, identical to my string Hello "World"!. import uvicorn from fastapi import FastAPI app = FastAPI()...
When you return a string from a FastAPI endpoint, FastAPI will automatically convert it to a JSON response, which is why the quotes are being escaped in your example. JSON strings must escape double quotes with a backslash. If you want to return unformatted text (plain text) and not JSON, you can do so by using FastAPI...
8
13
77,689,970
2023-12-20
https://stackoverflow.com/questions/77689970/python-not-working-on-a-bash-script-but-working-on-the-terminal-how-to-solve-it
I am trying to run a Python program through a Bash script. When I execute the python file by shell it works with no problem, but when I try to execute the script, the python keyword is not recognized. I have a fresh Ubuntu 23.10 installation and I added, on top of the ~/.bashrc file, the following line: alias python=py...
So, the issue is that your shebang isn't running bash as a login shell (which is pretty normal). You are aliasing python to python3 in your .bashrc, but that will only get run in a login shell. So try adding: #!/bin/bash -l to your shebang. Although, to be clear, I would consider this a hack. I would suggest that idea...
2
3
77,680,073
2023-12-18
https://stackoverflow.com/questions/77680073/ignore-specific-rules-in-specific-directory-with-ruff
I am using Ruff, a formatter or linter tool for Python code. I want to ignore some specific rules, and to write that config in pyproject.toml. My package structure is as follows. . ├── LICENSE ├── pyproject.toml ├── README.md ├── src │ └── mypackage/mymodule.py └── tests ├── doc.md └── test_mymodule.py And, I want to ...
You can use Ruff's per-file-ignores and specify individual files, or select a directory tree with a wildcard (star). You can ignore a "letter class" by specifying only the letter. Example: Ignore specific rule in a specific file To ignore line-length violations in your tests, add this to pyproject.toml: [tool.ruff.lint...
20
29
77,684,593
2023-12-19
https://stackoverflow.com/questions/77684593/is-there-a-way-to-retain-keys-in-polars-left-join
Is there a way to retain both the left and right join keys when performing a left join using the Python Polars library? Currently it seems that only the left join key is retained but the right join key gets dropped. Please see example code below: import polars as pl df = pl.DataFrame( { "foo": [1, 2, 3], "bar": [6.0, 7...
join now has a coalesce= parameter to control this behaviour. df.join(other_df, on="ham", how="left", coalesce=False) shape: (3, 5) ┌─────┬─────┬─────┬───────┬───────────┐ │ foo ┆ bar ┆ ham ┆ apple ┆ ham_right │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ str ┆ str ┆ str │ ╞═════╪═════╪═════╪═══════╪═══════════╡ │ 1...
3
1
77,676,556
2023-12-18
https://stackoverflow.com/questions/77676556/whats-the-correct-way-to-use-user-local-python-environment-under-pep668
I have tried to install any python packages on Ubuntu 24.04, but found I cannot do that as in 22.04, with --user PEP668 said it is for avoiding package conflict between system-wide package and user installed package. example: $ pip install setuptools --user error: externally-managed-environment × This environment is ex...
I finally found the best solution is use third-party tools (pyenv, conda, mini-forge). Pyenv use it's own python and pip independent with system's and use it by default. see $ where pip /home/john/.pyenv/shims/pip /home/john/.local/bin/pip /usr/local/bin/pip /usr/bin/pip /bin/pip So, system python and daily used pytho...
8
3
77,657,891
2023-12-14
https://stackoverflow.com/questions/77657891/in-polars-how-can-you-add-row-numbers-within-windows
How can I add row numbers within windows in a DataFrame? This example depicts what I want (in the counter column): >>> df = pl.DataFrame([{'groupings': 'a', 'target_count_over_windows': 1}, {'groupings': 'a', 'target_count_over_windows': 2}, {'groupings': 'a', 'target_count_over_windows': 3}, {'groupings': 'b', 'target...
You can generate an .int_range() over each group with a window function. df.with_columns(count = 1 + pl.int_range(pl.len()).over("groupings")) shape: (9, 3) ┌───────────┬───────────────────────────┬───────┐ │ groupings ┆ target_count_over_windows ┆ count │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞═══════════╪═════════...
2
4
77,683,711
2023-12-19
https://stackoverflow.com/questions/77683711/writing-nested-dictionary-to-excel-using-openpyxl-in-python
I want to write a nested dictionary to a sheet using openpyxl in which the keys should be used as header and values which are also a inner dictionary which has list values in it as well to be the records for header in which parent keys they are present. My code hasn't been able to achieve the complete the scenario but ...
Thanks for the expected result screen shot, I was close. Either way the easiest is probably just reading the dict and adding the values to the cells as they are read. Here is a quick option which I think is correct though may not be sorted the same way as your example; import openpyxl from openpyxl.utils.cell import g...
2
2
77,686,009
2023-12-19
https://stackoverflow.com/questions/77686009/when-i-want-to-logout-in-drf-api-browsable-it-shows-http-error-405
I'm new in DRF and now I have an Error in logout in DRF API browsable when I want to logout in API browsable it shows me Error 405 (method not Allowed) this is my setting.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', ), } this is my urls.py: urlpatterns...
It depends on Django version you are using. If you are using Version 5, try downgrading to 4.2.7.
2
2
77,688,251
2023-12-19
https://stackoverflow.com/questions/77688251/why-is-a-celery-task-not-consumed-by-a-worker-that-is-free
I have an application in Python with a microservices architecture and pipelines for which I use Celery along with RabbitMQ and Redis. In an application flow (machine learning training) 8 methodologies are needed, therefore a first worker called "Worker Training" sends 8 tasks to another worker called "Worker Training M...
This is most likely caused by the prefetching. Read the Prefetch Limits section, and the section after to find out how to make worker reserve as many tasks as they have (free) worker processes. In short (TLDR): task_acks_late = True worker_prefetch_multiplier = 1
2
0
77,686,348
2023-12-19
https://stackoverflow.com/questions/77686348/how-to-combine-different-styles-in-one-styler-map
I have a dataframe with 3 kind of data types - int64, float64 and object (string). How to apply format for two different data types in one function? Sample: def abc_style_format(cell_val): default = "" style_a = "background-color: green" style_b = "background-color: gold" style_c = "background-color: salmon" style_floa...
Here is one way to do it by defining as many helper functions as needed: import pandas as pd def _abc_style_format(s: pd.Series) -> list[str]: """Helper function to format 'abc' columns. Args: s: target column. Returns: list of styles to apply to each target column cell. """ background_colors = [] for v in s: match v: ...
2
0
77,662,046
2023-12-14
https://stackoverflow.com/questions/77662046/oserror-winerror-6-the-handle-is-invalid-python
Hey i am trying to make a application working in windows. It's basically adjusting your monitor brightness. There is a function provides minimize application. So i have issue about minimize. When clicking second time to minimize button getting error: Exception in Tkinter callback Traceback (most recent call last): File...
When icon.stop() is executed, you need to create a new instance of pystray.Icon in order to run icon.run(): class DesktopBrightnessApp: def __init__(self): ... # convert img to instance variable self.img self.img = ... ... # create the icon menu once self.menu = pystray.Menu( pystray.MenuItem("Open GUI", self.on_move_c...
2
3
77,651,663
2023-12-13
https://stackoverflow.com/questions/77651663/ffmpeg-transform-mulaw-8000khz-audio-buffer-data-into-valid-bytes-format
I'm trying to read a bytes variable using ffmpeg, but the audio stream I listen to, sends me buffer data in mulaw encoded buffer like this: https://github.com/boblp/mulaw_buffer_data/blob/main/buffer_data I'm having trouble running the ffmpeg_read function from the transformers library found here: def ffmpeg_read(bpayl...
This worked for me: import subprocess import numpy as np import io def ffmpeg_read_mulaw(bpayload: bytes, sampling_rate: int) -> np.array: ar = f"{sampling_rate}" ac = "1" format_for_conversion = "f32le" ffmpeg_command = [ "ffmpeg", "-f", "mulaw", "-ar", ar, "-ac", ac, "-i", "pipe:0", "-b:a",#change the bitrate "256k",...
3
2
77,654,869
2023-12-13
https://stackoverflow.com/questions/77654869/plumbum-fails-to-connect-via-jump-host-but-raw-command-succeeds
I'm trying to SSH into final_machine via the jump host portal_machine. Both remote machines are Linux, local is Windows. When I run the following command in a cmd, I can successfully connect ssh {username}@{final_machine} -oProxyCommand="ssh -W {final_machine}:22 {username}@{portal_machine}" And I can also successfull...
I would rather use ProxyJump than ProxyCommand, and move as many settings as possible into ~/.ssh/config. Sample configuration for the mentioned hosts: HOST portal HostName portal.machine.host.name.or.IP User username IdentityFile ~/.ssh/your.portal.key HOST final HostName final.machine.host.name.or.IP User username Id...
2
1
77,677,185
2023-12-18
https://stackoverflow.com/questions/77677185/how-can-i-reference-an-environment-variable-for-python-path-in-vscode-launch-con
I am using vscode on my desktop and laptop and each machine would generate a random folder name with a hash for the virtual environment path when creating the virtual environment using poetry. In order to use the same launch.json file in my project for both computers, I'd like to reference an environment variable inste...
As of vscode 1.85, specifying "python": "${env:PROJ_VENV}/bin/python" in launch.json will not work. As a workaround, you can remove "python" from launch.json and set "python.defaultInterpreterPath": "${env:PROJ_VENV}/bin/python" in settings.json. You can then select "Use Python from python.defaultInterpreterPath" when ...
3
1
77,686,427
2023-12-19
https://stackoverflow.com/questions/77686427/how-to-set-vscode-mypy-type-checker-args-argument-for-python
I am learning python , i use Vs code as my IDE, i am have some very strange and annoying errors. examples: when i import modules import telegram i get error "telegram" is not accessed Pylance invalid syntaxMypysyntax (module) telegram on my files, which is very annoying. I have write import telegram #type:ignore for th...
I enabled Copilot, ask it to explain the probem to me . it told me to do if update.effective_chat is not None: await context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, my name is MAS, i am your bot that provides movies to you for free.") instead of await context.bot.send_message(chat_id=update.e...
2
0
77,686,072
2023-12-19
https://stackoverflow.com/questions/77686072/issues-with-azure-identity-when-using-federated-credentials
I'm running a GH actions pipeline which is configured to login Azure cli using federated credentials (and this works fine): env: ARM_USE_OIDC: true steps: - name: az login uses: azure/login@v1 with: client-id: ${{ env.ARM_CLIENT_ID }} tenant-id: ${{ env.ARM_TENANT_ID }} subscription-id: ${{ env.ARM_SUBSCRIPTION_ID }} ...
the underlying OIDC token issued by Github has only 5 minutes of lifetime hence it doesnt matter if oAuth tokens have 1h lifetime. my workaround is to refresh Azure Cli auth everytime I need to use it until anything can be done about this (at least I dont see a way to extend token lifetime: https://docs.github.com/en/a...
2
0
77,657,592
2023-12-14
https://stackoverflow.com/questions/77657592/r-equivalent-of-python-add-volume-function
I am working with the R programming language. I found this tutorial/website over here that shows how to fill the volume under the surface in Python/Plotly (https://community.plotly.com/t/fill-volume-under-the-surface/64944/2): import numpy as np import plotly.express as px import plotly.graph_objects as go f = lambda x...
You can add a volume trace using add_trace(type = "volume"). The input is different from the surface plot though. You need a regular 3D grid of points given as vectors of x, y and z co-ordinates, such as you might create with expand.grid in R. Each of these points must also have a value. Only values above the isomin ar...
2
2
77,688,198
2023-12-19
https://stackoverflow.com/questions/77688198/how-to-decode-string-address-into-pubkey-address-on-solana
I am querying data from raydium using their SDK, but i am trying to do it in Python instead. So, I am obtaining an address: <BN: b870e12dd379891561d2e9fa8f26431834eb736f2f24fc2a2a4dff1fd5dca4df> And I know it correspond to : PublicKey(DQyrAcCrDXQ7NeoqGgDCZwBvWDcYmFCjSb9JtteuvPpz)] But anyone know how one could decode...
With Solana use base58 for encode address. In python, you can use module base58 to encode from hex string address. import base58 hex_sting="b870e12dd379891561d2e9fa8f26431834eb736f2f24fc2a2a4dff1fd5dca4df" byte_string = bytes.fromhex(hex_sting) encoded_string = base58.b58encode(byte_string).decode() # DQyrAcCrDXQ7NeoqG...
2
3
77,688,214
2023-12-19
https://stackoverflow.com/questions/77688214/indexing-a-python-dataframe
I am attempting to analyse high school attendance and behaviour data. I have a raw excel data sheet as shown in the image. I get lost with how to index it. Essentially the first three columns should be "Student Name, Class and Percent Attendance". Then all subsequent columns are a 2 level index, the first of which is ...
You can read_excel to load the spreadsheet as it is, then post-process it : raw = pd.read_excel("file.xlsx") idx_names = ["Student Name", "Class", "Percent Attendance"] left = raw.iloc[2:, :3].set_axis(idx_names, axis=1) col_mux = pd.MultiIndex.from_arrays(raw.iloc[:2, 3:].ffill(axis=1).to_numpy()) right = raw.iloc[2:,...
2
1
77,682,768
2023-12-19
https://stackoverflow.com/questions/77682768/python-streaming-from-webcam-through-an-ml-process-to-the-internet
I am trying to develop a program in Python that streams a webcam captured video, through an ML process, to "the internet". Are there particular packages for Python that are designed to handle the live webcam capture and streaming/receiving from the internet? The ML processes I understand fairly well but currently requi...
You can capture video from webcam using the opencv-python like the following: import cv2 cap = cv2.VideoCapture(0) # Open the default camera (0) while True: ret, frame = cap.read() # Read a frame from the webcam # Perform your ML processing here on 'frame' cv2.imshow('Webcam', frame) # Display the frame if cv2.waitKey(...
2
3
77,685,797
2023-12-19
https://stackoverflow.com/questions/77685797/create-a-dynamic-case-when-statement-based-on-pyspark-dataframe
I have a dataframe called df with features, col1, col2, col3. Their values should be combined and produce a result. What result each combination will produce is defined in mapping_table. However, mapping_table sometimes has the value '*'. This mean that this feature can have any value, it doesn't affect the result. Thi...
Transform map_data into a case statement: ressql = 'case ' for m in map_data: p = [f"{p[0]} = '{p[1]}'" for p in zip(columns, m[:3]) if p[1] != "*"] ressql = ressql + ' when ' + ' and '.join(p) + f" then '{m[3]}'" ressql = ressql + ' end' df.withColumn('result', F.expr(ressql)).show() ressql is now case when col1 = 'a...
2
2
77,660,162
2023-12-14
https://stackoverflow.com/questions/77660162/pygame-how-to-reset-alpha-layer-without-fill0-0-0-255-every-frame
I'm programming a 2D game with a background and a fog of war. Both are black pygame.Surface, one with an alpha chanel (fog of war) and one without (background). Their sizes are the same and are constants. The only thing that change is the alpha channel of some pixels in fog of war. Profiling my code, I observed that 15...
I found a solution for the second option from https://github.com/pygame/pygame/issues/1244, which explains how to modify the alpha layer. The key function goes like this: def reset_alpha(s): surface_alpha = np.array(s.get_view('A'), copy=False) surface_alpha[:,:] = 255 return s Though doing so requires to create a num...
3
1
77,686,302
2023-12-19
https://stackoverflow.com/questions/77686302/using-python-variable-in-sql-query
I would like to use python to do an SQL query that prompts the user for input to complete the query. Currently when I run my code it will tell me I have a TypeError (see below for full error message). My code will be posted below first. import pyodbc from datetime import datetime import pandas as pd def today(): return...
You have to pass query directly as a string without using conn.cursor() and pass the TOOL_OUT value into params as a tuple: query = """SELECT TOOL_OUT, TANK, STATION, FORMING_CURRENT, TIME, BUILDING_CURRENT, CYCLE_TIME FROM ELECTROFORMING WHERE PROCESS='ELECTROFORMING' AND (TOOL_OUT=?)""" tool_out = input("TOOL_OUT: ")...
2
2
77,686,120
2023-12-19
https://stackoverflow.com/questions/77686120/get-lowest-elementwise-values-from-multiple-numpy-arrays-which-may-be-different
I can get the lowest values from multiple arrays by using the following: first_arr = np.array([0,1,2]) second_arr = np.array([1,0,3]) third_arr = np.array([3,0,4]) fourth_arr = np.array([1,1,9]) print(np.minimum.reduce([first_arr, second_arr, third_arr, fourth_arr])) Result = [0 0 2] However if the arrays are differen...
If you don't mind the overhead, use pandas's DataFrame.min: l = [first_arr, second_arr, third_arr, fourth_arr] out = pd.DataFrame(l).min().to_numpy() Or with itertools.zip_longest and numpy.nanmin: from itertools import zip_longest l = [first_arr, second_arr, third_arr, fourth_arr] out = np.nanmin(np.c_[list(zip_longe...
3
2
77,655,853
2023-12-13
https://stackoverflow.com/questions/77655853/gekko-optimization-exit-invalid-number-in-nlp-function-or-derivative-detected
Hello I have the aim to optimize a currently simple set of equations in order to obtain the value of kd with a fit. Generate testing data (works fine) def solve_gekko_equations(H0input, D0input, Kinput): m = GEKKO(remote=False) d0 = m.Const(D0input) h0 = m.Const(H0input) hdLimit=min([D0input,H0input]) d = m.Var(1,0,D0i...
Thank you very much for your answer, and now the optimization finishes, but the result is wrong. we generated testing data for kd=0.5 but the fitting result is kd=1.0 in the suggested solution. It seemed that any initalValue in mFV(value=initialValue) was in the end the found solution. So I modified the code to only pr...
3
0
77,683,810
2023-12-19
https://stackoverflow.com/questions/77683810/fastest-way-to-use-cmaps-in-polars
I would like to create a column of color lists of type [r,g,b,a] from another float column using a matplotlib cmap. Is there a faster way then: data.with_columns( pl.col("floatCol")/100) .map_elements(cmap1) ) Minimal working example: import matplotlib as mpl import polars as pl cmap1 = mpl.colors.LinearSegmentedColor...
If you're using map_elements, then it can (nearly) always be faster ;) data.with_columns( pl.when(pl.col("boolCol").not_()) .then(mpl.colors.to_rgba("r")) .otherwise((pl.col("floatCol") / 100).map_batches(lambda x: pl.Series(cmap1(x)))) .alias("c1") ) Use map_batches to operate over the entire column
3
3
77,681,935
2023-12-18
https://stackoverflow.com/questions/77681935/can-this-simpler-case-of-the-2d-maximum-submatrix-problem-be-solved-more-quickly
Given an n by m matrix of integers, there is a well known problem of finding the submatrix with maximum sum. This can be solved with a 2d version of Kadane's algorithm. An explanation of an O(nm^2) time algorithm for the 2D version which is based on Kadane's algorithm can be found here. I am interested in a simpler ver...
Yes, you can do it in O(nm), for example by accumulating over the rows and then accumulating over the columns. That gives you all the sums, so just take the max. Example implementation to find the max sum: from itertools import accumulate max(max(accumulate(c)) for c in zip(*map(accumulate, A))) And to also find the b...
3
1
77,682,802
2023-12-19
https://stackoverflow.com/questions/77682802/is-there-a-way-for-selenium-to-connect-to-an-already-open-instance
I need to access a browser that is already open. I'm using Python, but if you have another language, I welcome help! I'm trying to access a website and when I break its captcha even manually (the browser is starting with Selenium) it simply reports that it's wrong even though it's right and I can't access the certifica...
you can run chrome with command: chrome.exe --remote-debugging-port=9222 --user-data-dir="D:/ChromeProfile" the user-data-dir is a new dir for user data. and in selenium, you should create driver like this: from selenium.webdriver.chrome.options import Options from selenium import webdriver chrome_options = Options() ...
2
3
77,680,831
2023-12-18
https://stackoverflow.com/questions/77680831/signalr-communication-between-python-and-aspnet
I COMMUNICATE BETWEEN ASP NET C# AND PYTHON using a websocket, or more specifically, I use a signalR library in both cases. I'm trying to get my server to respond in some way when a Python client sends a message. nothing helps for now. anyone had this problem? it is enough that after the client sends the message, the f...
# Send a message after connection # self.hub_connection.send("SendGemstoneDetailMessage", ["dwdw"]) self.hub_connection.send("SendGemstoneDetailMessage", [["dwdw"]]) You are missing [] in your frontend code, since you are using SendGemstoneDetailMessage(List<string> messag), you should use [["dwdw"]]. If you want send...
2
1
77,681,797
2023-12-18
https://stackoverflow.com/questions/77681797/how-to-mock-a-constant-value
I have a structure like so: mod1 ├── mod2 │ ├── __init__.py │ └── utils.py └── tests └── test_utils.py where __init__.py: CONST = -1 utils.py: from mod1.mod2 import CONST def mod_function(): print(CONST) test_utils.py: from mod1.mod2.utils import mod_function def test_mod_function(mocker): mock = mocker.patch(...
What patch("mod1.mod2.CONST") does is really to set the CONST attribute of the module object mod1.mod2 to a different object. It does not affect any existing names referencing the original mod1.mod2.CONST object. When utils.py does: from mod1.mod2 import CONST it creates a name CONST in the namespace of the mod1.mod2....
2
1
77,680,320
2023-12-18
https://stackoverflow.com/questions/77680320/getting-different-score-values-between-manual-cross-validation-and-cross-val-sco
I created a python for loop to split the training dataset into stratified KFolds and used a classifier inside the loop to train it. Then used the trained model to predict with the validation data. The metrics achieved using this process where quite different to that achieved with the cross_val_score function. I expecte...
TL;DR: The two ways of calculation are not equivalent due to the different way you handle the TF-IDF transformation; the first calculation is the correct one. In the first calculation you correctly apply fit_transform only to the training data of each fold, and transform to the validation data fold: X_tr_vec_tfidf = t...
2
3
77,676,879
2023-12-18
https://stackoverflow.com/questions/77676879/determining-and-filtering-out-low-frequent-component-from-a-real-dataset
I am trying to use FFT to filter out low frequency components from a signal and retain high frequency components in a real dataset (hourly electricity demand in California). I have tried this so far: X = fft(df['demand']) y_fft_shift = fftshift(X) n = 20 # number of low freq components to be removed (selected randomly)...
Don't use the complex versions of the FFT; use the real ones. import matplotlib import numpy as np from matplotlib import pyplot as plt sr = 2_000 # sampling rate ts = 1/sr # sampling interval t = np.arange(0, 1, ts) # generate a signal freq = 1 y = 3*np.sin(2*np.pi*freq*t) freq = 4 y += np.sin(2*np.pi*freq*t) freq = 7...
2
1
77,679,383
2023-12-18
https://stackoverflow.com/questions/77679383/validationerror-1-validation-error-for-structuredtool
I was getting an error when trying to use a Pydantic schema as an args_schema parameter value on a @tool decorator, following the DeepLearning.AI course. My code was: from pydantic import BaseModel, Field class SearchInput(BaseModel): query: str = Field(description="Thing to search for") @tool(args_schema=SearchInput) ...
Downgrading to pydantic 1.10.10 worked for me. Add pydantic==1.10.10 to your requirements.txt and install it with pip install -r requirements.txt or with the command pip install pydantic==1.10.10
3
3
77,678,603
2023-12-18
https://stackoverflow.com/questions/77678603/create-multiple-functions-in-one-azure-function-app
I want to create multiple python Azure Functions within one Azure Functions App using the azure cli/core tools. One http triggered function and one blob triggered function. I have the following folder structure: ├── azure-functions │ ├── az-func-blob │ │ ├── .python_packages │ │ ├── .vscode │ │ ├── .gitignore │ │ ├── f...
Can someone please explain in detail how to get set this up using only one Azure Function App instead of multiple function apps? I am able to deploy multiple functions to a Function App using func azure functionapp publish <function_APP_Name> command. Thanks @Thomas for the comment, you need to run func init --worker...
3
2
77,678,481
2023-12-18
https://stackoverflow.com/questions/77678481/using-libclang-python-bindings-how-do-you-retrieve-annotations-added-to-c-cla
Using the following C++ struct as an example: __attribute__((annotate("MyAttribute"))) struct TestComponent { __attribute__((annotate("MyAttribute"))) int32_t testInt; __attribute__((annotate("MyAttribute"))) bool testBool; __attribute__((annotate("MyAttribute"))) char testChar; }; Given a node (cursor) from clang usi...
tl;dr: attribute should be placed between struct and TestComponent struct __attribute__((annotate("MyAttribute"))) TestComponent If you print tu.diagnostics, clang does issue a -Wignored-attributes warning: test.cpp:2:17: warning: attribute 'annotate' is ignored, place it after "struct" to apply attribute to type decl...
2
3
77,676,117
2023-12-17
https://stackoverflow.com/questions/77676117/why-does-python-read3-seek-to-end-of-file
I am trying to understand file IO in Python, with the different modes for open, and reading and writing to the same file object (just self learning). I was surprised by the following code (which was just me exploring): with open('blah.txt', 'w') as f: # create a file with 13 characters f.write("hello, world!") with ope...
Consider this example: with open('test.txt', 'w') as f: f.write('HelloEmpty') with open('test.txt', 'r+') as f: print(f.read(5)) print(f.write('World')) f.flush() f.seek(0) print(f.read(10)) You might expect this to print: Hello 5 HelloWorld Instead, it prints: Hello 5 HelloEmpty And the file contains 'HelloEmptyWor...
3
2
77,672,842
2023-12-16
https://stackoverflow.com/questions/77672842/infer-type-hint-superclass-init-args-in-child
I'm trying to see whether it is possible to solve the following problem Suppose I have to classes: class A(): def __init__(self, param: str, **kwargs) -> None: ... class B(A): def __init__(self, **kwargs) -> None: ... super().__init__(**kwargs) When using pyright, I don't get any (type) checking on arguments to class ...
If you merely want to run some custom logic in the child class' __init__, a decorator approach will preserve the signature without the need to explicitly repeat it. from typing import Callable, Concatenate, ParamSpec, Protocol, TypeVar P = ParamSpec("P") SelfT = TypeVar("SelfT", contravariant=True) class Init(Protocol[...
4
3
77,674,469
2023-12-17
https://stackoverflow.com/questions/77674469/does-python-c-or-exec-create-temporary-files
Where are temporary files saved when running the commands or are there no temporary files created? python -c "print('Hello, World!')" and exec("print('Hello, World!')") Both Windows and macOS. Does Python run directly or is it compiled into a temporary file and then run? I use Google Translate.
No, neither of these operations creates any temporary file. Python creates .pyc files only as a performance optimization to speed future loading of the same code, and works perfectly well without them. This is typical behavior for interpreted languages as opposed to compiled ones. As Python is generally compiled only t...
2
1
77,672,765
2023-12-16
https://stackoverflow.com/questions/77672765/how-can-a-line-at-the-end-of-the-code-suddenly-cause-a-bug-in-an-earlier-line
Somehow I managed to create a program that gives an error in an earlier line by adding a line at the end. The code below runs without any error. However, if I uncomment the last line an error occurs in the line before that: Traceback (most recent call last): File "/path/to/code.py", line 233, in <module> print(current_...
The problem has to do with this line: current_step = list(start.connects_to)[0] start.connects_to is a set, which has no defined order, so if you convert it to a list and take the first element, the result can be arbitrary. Changing the structure of the code (e.g. adding or removing a statement at the end) changes the...
2
3
77,659,069
2023-12-14
https://stackoverflow.com/questions/77659069/how-to-understand-and-debug-memory-usage-with-jax
I am new to JAX and trying to learn use it for running some code on a GPU. In my example I want to search for regular grids in a point cloud (for indexing X-ray diffraction data). With test_mats[4_000_000,3,3] the memory usage seems to be 15 MB. But with test_mats[5_000_000,3,3] I get an error about it wanting to alloc...
The vmapped function is attempting to create an intermediate array of shape [N, 3, 3430]. For N=400_000, with float32 this amounts to 15GB, and for N=500_000 this amounts to 19GB. Your best option in this situation is probably to split your computation into sequentially-executed batches using lax.map or similar. Unfort...
2
2
77,668,149
2023-12-15
https://stackoverflow.com/questions/77668149/in-python-is-there-a-way-to-get-the-code-object-of-top-level-code
Is it possible to get the code object of top level code within a module? For example, if you have a python file like this: myvar = 1 print('hello from top level') def myfunction(): print('hello from function') and you want to access the code object for myfunction, then you can use myfunction.__code__. For example, myf...
The code that is executed at the top level of a module is not directly accessible as a code object in the same way that functions' code objects are, because the top-level code is executed immediately when the module is imported or run, and it doesn't exist as a separate entity like a function does. But when Python runs...
19
19
77,653,860
2023-12-13
https://stackoverflow.com/questions/77653860/how-to-insert-a-png-without-background-to-another-png-in-pyvips
I have two png images with transparent background example: and I'm trying to achieve something similar to the PIL paste() function in pyvips, where I can merge two images and 'remove the transparent background' using a mask. PIL example: image = Image.open(filepath, 'r') image_2 = Image.open(filepath, 'r') image.past...
You can do it like this, using the composite() function: import pyvips # Load background and foreground images bg = pyvips.Image.new_from_file('WA8rm.png', access='sequential') fg = pyvips.Image.new_from_file('Ny50t.png', access='sequential') # Composite foreground over background and save result bg.composite(fg, 'over...
2
1
77,664,047
2023-12-15
https://stackoverflow.com/questions/77664047/find-all-combinations-of-a-polars-dataframe-selecting-one-element-from-each-row
I have a Polars Dataframe, and I would like to contrust a new Dataframe that consists of all possible combinations choosing 1 element from each row. Visually like so: An input Dataframe | Column A | Column B | Column C | | -------- | -------- | -------- | | A1 | B1 | C1 | | A2 | B2 | C2 | | A3 | B3 | C3 | would give |...
There's no direct "combinations" functionality as far as I am aware. One possible approach is to .implode() then .explode() each column. df = pl.from_repr(""" ┌──────────┬──────────┬──────────┐ │ Column A ┆ Column B ┆ Column C │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str │ ╞══════════╪══════════╪══════════╡ │ A1 ┆ B1 ┆ C1 │...
2
2
77,664,095
2023-12-15
https://stackoverflow.com/questions/77664095/what-are-the-differences-between-pipx-and-pip-user
I have tried to install any python packages on Ubuntu:24.04, but found I cannot do that as in 22:04 PEP668 said it is for avoiding package conflict between system-wide package and user installed package. But what's the differences between using pipx and pip --user? And why the --user option not work, it also installs p...
pip --user is a function provided by pip, and pipx is a software package. Ubuntu can guarantee that the packages you install using pipx will not pollute the system environment, but pip does not have this guarantee. Additionally, you should install setuptools using apt install python3-setuptools.
6
3
77,663,828
2023-12-15
https://stackoverflow.com/questions/77663828/regex-difference-between-ruby-python
I just started Advent of Code 2023 and am trying to use it to learn a few new programming languages. I have (some) familiarity with python, and literally just installed ruby today. Day 1, part 2, I am using a Regex to search for digits as well as their spelled out versions. The regex in python (which yields the correct...
0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine The problem with this regex, in both Python and Ruby, is that you fail to account for overlapping matches. I made the exact same mistake doing this problem earlier this month. If the phrase eightwo, for instance, appears in your puzzle input, then b...
2
4
77,662,696
2023-12-14
https://stackoverflow.com/questions/77662696/speed-up-iterative-algorithm-in-python
I'm implementing the forward recursion for Hidden Markov Model: the necessary steps (a-b) are shown here Below is my implementation from scipy.stats import norm import numpy as np import random def gmmdensity(obs, w, mu, sd): # compute probability density function of gaussian mixture gauss_mixt = norm.pdf(obs, mu, sd)...
TL;DR: Numba can strongly speed up this code, especially with basic loops. This answer comes lately compared to the others, but it provides the fastest implementation so far. This is indeed typically a situation where Numba can strongly speed up the computation. Indeed, np.matmul takes more than 1 µs on my machine to ...
2
3
77,659,393
2023-12-14
https://stackoverflow.com/questions/77659393/subtracting-a-numpy-array-by-a-list-is-slow
Given a numpy array of shape 4000x4000x3, which is an image with 3 channels, subtract each channel by some values. I can do it as following: Implementation 1 values = [0.43, 0.44, 0.45] image -= values Or, Implementation 2 values = [0.43, 0.44, 0.45] for i in range(3): image[...,i] -= values[i] Surprisingly, the late...
TL;DR: the performance issue is caused by multiple factors : Numpy iterators introduce a big overhead on small broadcasted arrays values is implicitly converted to a np.float64 array causing a slow np.float64-based subtraction the memory layout is sub-optimal in all implementations Numpy internal iterators One issue...
2
2
77,661,139
2023-12-14
https://stackoverflow.com/questions/77661139/how-do-i-stop-the-ruff-linter-from-moving-imports-into-an-if-type-checking-state
I have a pydantic basemodel that looks something like: from pathlib import Path from pydantic import BaseModel class Model(BaseModel): log_file: Path And my ruff pre-commit hook is re-ordering it to: from typing import TYPE_CHECKING from pydantic import BaseModel if TYPE_CHECKING: from pathlib import Path class Model(...
Haven't reproduced this, but I think your list of select options is causing this. I know that this isn't the default behaviour of ruff. select = ["E", "F", "B", "C4", "DTZ", "PTH", "TCH", "I001"] Even though the official readme says TC* is the code for flake8-type-checking, this issue hints that TCH* is. From the READ...
4
3
77,661,003
2023-12-14
https://stackoverflow.com/questions/77661003/how-to-type-hint-a-method-that-returns-an-instance-of-a-class-passed-as-paramete
using Python 3.11 and Mypy 1.7. I am trying to properly type hint a method that takes a class as parameter, with a default value, and returns an instance of that class. The class passed as parameter must be a subclass of a specific base class. How should I do that? I tried to use a type variable with upper bound like t...
This is a known limitation of mypy. See the GitHub issues #8739 - mypy reporting error with default value for typevar and #3737 - Unable to specify a default value for a generic parameter for its discussion. You can make this work using typing.overload to separately annotate the case where the default value is used: fr...
3
4
77,660,815
2023-12-14
https://stackoverflow.com/questions/77660815/how-to-add-dfs-with-different-number-of-column-axis-levels-but-sharing-same-axi
I have two multi-level column dataframes: data = { 'A': { 'X': {'Value1': 2, 'Value2': 1}, 'Y': {'Value1': 2, 'Value2': 3} }, 'B': { 'X': {'Value1': 10, 'Value2': 11}, 'Y': {'Value1': 10, 'Value2': 11} } } df = pd.DataFrame(data) Which looks like this... Group A B Subgroup X Y X Y Metric Value1 Value2 Value1 Value2 Va...
I think the easiest might be to droplevel on df1, then add, finally recreate the DataFrame: pd.DataFrame(df1.droplevel('Subgroup', axis=1).add(df2).to_numpy(), index=df1.index, columns=df1.columns) Alternatively, reindex df2 and convert to numpy: df1 += df2.reindex_like(df1.droplevel('Subgroup', axis=1)).to_numpy() O...
2
1
77,659,552
2023-12-14
https://stackoverflow.com/questions/77659552/google-generative-ai-api-error-user-location-is-not-supported-for-the-api-use
I'm trying to use the Google Generative AI gemini-pro model with the following Python code using the Google Generative AI Python SDK: import google.generativeai as genai import os genai.configure(api_key=os.environ['GOOGLE_CLOUD_API_KEY']) model = genai.GenerativeModel('gemini-pro') response = model.generate_content('S...
I've looked at multiple sources and all signs point to the same issue: You're likely in a location where the generative AI isn't supported. While you're using the new Gemini Pro, the API is very similar to the previous iteration "PaLM", and they likely have the same regional limitations. https://www.googlecloudcommunit...
6
6
77,658,160
2023-12-14
https://stackoverflow.com/questions/77658160/how-to-delete-an-object-which-contains-a-list-of-its-bound-methods
At this code, an object of Foo() class is still alive after creating new one. I guess that reason is in the circular references on appending object's list property. So, how to let garbage collector free old object, withot manual calling gc.collect()? import gc class Foo(): def __init__(self): self.functions = [] print(...
You can use weakref.WeakMethod to avoid creating strong references to the self.print_func method in the list attribute. Note that to call a weakly referenced method you would have to dereference it first by calling the weakref before calling the actual method: from weakref import WeakMethod class Foo(): def __init__(se...
2
2
77,656,160
2023-12-13
https://stackoverflow.com/questions/77656160/pytorch-random-number-generators-and-devices
I always put on top of my Pytorch's notebooks a cell like this: device = ( "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" ) torch.set_default_device(device) In this convenient way, I can use the GPU, if the system has one, MPS on a Mac, or the cpu on a vanilla system. ED...
When defining the tensor "A", it is defaulting to creating the tensor on the CPU. This results in an error, because the generator you are passing in is on the CUDA device. You can solve this by passing in the "device" parameter into torch.randn() as follows: device = ("cuda" if torch.cuda.is_available() else "mps" if t...
2
4
77,656,117
2023-12-13
https://stackoverflow.com/questions/77656117/when-can-you-use-numpy-arrays-as-dict-values-in-numba
I am confused by the type rules for numba dicts. Here is an MWE that works: import numpy as np import numba as nb @nb.njit def foo(a, b, c): d = {} d[(1,2,3)] = a return d a = np.array([1, 2]) b = np.array([3, 4]) t = foo(a, b, c) But if I change the definition of foo as follows this fails: @nb.njit def foo(a, b, c):...
This doesn't have anything with how numba handles dictionaries. This piece of code fails with the same error: @nb.njit def foo2(a, b, c): x = np.array(a) return x When you look at the error message you see that numba doesn't know how to initialize np.array from other np.array: No implementation of function Function(<b...
2
2
77,655,440
2023-12-13
https://stackoverflow.com/questions/77655440/can-you-protect-a-python-variable-with-exec
This is kind of a hacky Python question. Consider the following Python code: def controlled_exec(code): x = 0 def increment_x(): nonlocal x x += 1 globals = {"__builtins__": {}} # remove every global (including all python builtins) locals = {"increment_x": increment_x} # expose only the increment function exec(code, gl...
Yes, x can be set to an arbitrary value by code executed by controlled_exec. Consider the following demo: def controlled_exec(code): x = 0 def increment_x(): nonlocal x x += 1 print(f"{x=}") globals = {"__builtins__": {}} # remove every global (including all python builtins) locals = {"increment_x": increment_x} # expo...
3
5
77,651,219
2023-12-13
https://stackoverflow.com/questions/77651219/finding-the-first-row-that-meets-conditions-of-a-mask-and-selecting-one-row-afte
This is my dataframe: import pandas as pd df = pd.DataFrame( { 'a': [100, 1123, 123, 100, 1, 0, 1], 'b': [1000, 11123, 1123, 0, 55, 0, 1], 'c': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], } ) And this is the output that I want. I want to create column x: a b c x 0 100 1000 a NaN 1 1123 11123 b NaN 2 123 1123 c NaN 3 100 0 d...
You can generate a mask that indicates one location past where the first value of a is greater than b: mask = (df.a > df.b).shift(fill_value=False) mask = mask & ~mask.cumsum().shift().astype(bool) You can then use that mask to set the value of x equal to c: df.loc[mask, 'x'] = df['c'] Output for each of your dfs: a...
4
5
77,652,094
2023-12-13
https://stackoverflow.com/questions/77652094/how-to-post-json-data-that-include-unicode-characters-to-fastapi-using-python-re
When a FastAPI endpoint expects a Pydantic model and one is passed with a string it works as expected unless that string contains unicode characters. First I create an example application for FastAPI with an example model. serv.py from pydantic import BaseModel class exClass(BaseModel): id: int = Field(example=1) text:...
This is not a problem of Pydantic and FastAPI. You should encode you request data like it's shown below: r = requests.post( f"http://127.0.0.1:8000/example", data=ex1.model_dump_json().encode('utf-8') ) print(r.text) r = requests.post( f"http://127.0.0.1:8000/example", data=ex2.model_dump_json().encode('utf-8') ) print...
3
4
77,646,307
2023-12-12
https://stackoverflow.com/questions/77646307/correlation-matrix-like-dataframe-in-polars
I have Polars dataframe data = { "col1": ["a", "b", "c", "d"], "col2": [[-0.06066, 0.072485, 0.548874, 0.158507], [-0.536674, 0.10478, 0.926022, -0.083722], [-0.21311, -0.030623, 0.300583, 0.261814], [-0.308025, 0.006694, 0.176335, 0.533835]], } df = pl.DataFrame(data) I want to calculate cosine similarity for each co...
Update: Polars 1.8.0 added native list arithmetic allowing us to write a much more efficient cosine similarity expression. Combinations We can add a row index and use .join_where() to generate the row "combinations". df = df.with_row_index().lazy() df.join_where(df, pl.col.index <= pl.col.index_right).collect() shape...
6
3
77,630,410
2023-12-9
https://stackoverflow.com/questions/77630410/fastapi-swagger-interface-showing-operation-level-options-override-server-option
I have been recently finding a popup that tells me some operation level options override the global server options: As per image: I do not understand whether this is a bug in my application or anything but normal. I would not like to show the user that message. EDIT: This is my main.py file: from fastapi import FastAP...
This option seem to appear for OAS 3.1 documents. This must be a bug in swagger-ui. Although servers are not overridden on operation level, swagger-ui defaults to '/' and always displays the override.
2
0
77,631,477
2023-12-9
https://stackoverflow.com/questions/77631477/runtimeerror-cant-create-new-thread-at-interpreter-shutdown-python-3-12
I am making a mouse jiggler and I can't get acces to the tray icon once the loop in the script is launched. I have asked another question but no one has answered yet, so I kept digging deeper into the topic in order to resolve my issue. So, I found a solution as I assumed it would be - threads. I kinda understand the c...
The solution is to use Python version under 3.12. Now I use 3.11.7. The code works perfectly fine.
4
0
77,630,013
2023-12-9
https://stackoverflow.com/questions/77630013/how-to-run-any-quantized-gguf-model-on-cpu-for-local-inference
In ctransformers library, I can only load around a dozen supported models. How can I run local inference on CPU (not just on GPU) from any open-source LLM quantized in the GGUF format (e.g. Llama 3, Mistral, Zephyr, i.e. ones unsupported in ctransformers)?
llama-cpp-python is my personal choice, because it is easy to use and it is usually one of the first to support quantized versions of new models. To install it for CPU, just run pip install llama-cpp-python. Compiling for GPU is a little more involved, so I'll refrain from posting those instructions here since you aske...
11
20
77,634,768
2023-12-10
https://stackoverflow.com/questions/77634768/sqlalchemy-cant-communicate-to-mysql-server-upon-app-start
I'm have troubles with SQLalchemy in Flask app first minute after the app start (or restart). It looks like logger exceptions of a sort: sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2006, 'MySQL server has gone away') <---- most often one sqlalchemy.exc.ResourceClosedError: This result ob...
Seems How to correctly setup Flask + uWSGI + SQLAlchemy to avoid database connection issues worked for them. This is a copy paste of the answer just to avoid "link only answers". I would still recommend anyone arriving at this question to refer the original answer linked above. The SQLAlchemy manual provides two examp...
2
3
77,633,160
2023-12-9
https://stackoverflow.com/questions/77633160/name-c-is-not-defined
I tried to import pytorch in Jupyter notebook: import torch When I run it I get this error message: NameError Traceback (most recent call last) <ipython-input-7-db4b44599dae> in <module> ----> 1 import torch 2 import numpy as np 3 from torch import nn 4 from tqdm.auto import tqdm 5 from torchvision import transforms /o...
I had this same error, I found the issue was an outdated package. I had to manually specify the latest typing_extensions: pip3 install typing_extensions==4.9.0
2
2
77,626,710
2023-12-8
https://stackoverflow.com/questions/77626710/data-is-normally-distributed-but-ks-test-return-a-statistic-of-1-0
I have an age variable. When I plotted it using the kde & qq-plot, the distribution seemed normal; however, when I performed the ks-test, the test statistics = 1.0, p = 0.0. Can someone please help me explain this observation? I use the ks-test on other variables, and the result was consistent with the visualization fo...
@Timur Shtatland is correct. Your code is: sps.kstest(age, 'norm') without specifying the parameters of the normal distribution, you are comparing your data to a standard normal distribution (with mean 0 and standard deviation 1). So it not surprising that the p-value for the test is effectively zero. Instead you shou...
3
0
77,636,721
2023-12-10
https://stackoverflow.com/questions/77636721/how-to-get-a-certain-value-from-enum
I have the following class: class YesOrNn(enum.Enum): YES = "Y" NO = "N" I am getting my inputs such as YesOrNo("true") or YesOrNo("false"), To make this work, I think I need to change the class to: class YesOrNn(enum.Enum): YES = "true" NO = "false" But, I also have a case where whenever a variable's value is saved ...
You want the _missing_ method: import enum class YesOrNo(enum.Enum): YES = "Y" NO = "N" @classmethod def _missing_(cls, value): if value.lower() in ('y', 'yes', 'true', 't'): return cls.YES elif value.lower() in ('n', 'no', 'false', 'f'): return cls.NO Disclosure: I am the author of the Python stdlib Enum, the enum34...
2
2
77,634,718
2023-12-10
https://stackoverflow.com/questions/77634718/server-for-saving-tcp-packets-from-routers
Asking for advice here. So I have a business that sells a specific kind of routers. One of the features is to monitor the activity of the router (i.e. making sure it's "live"). I asked the manufacturer of the routers to program them to send a TCP "ping" packet to my server IP address, to a specific port, every 15 minut...
Correct answer with TCP You can basically use https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example to accept tcp pings and write it to a database. Demo database using the standard library sqllite3 https://docs.python.org/3/library/sqlite3.html Demo server using standard library Httpserver ...
3
2
77,635,098
2023-12-10
https://stackoverflow.com/questions/77635098/pathlib-with-backlashes-within-input-string
I tried to check if a given path exists on Windows/Linux (using Path.exists()) A FileNotFoundError is raised on Linux only, obviously when looking at the POSIX path object it is not converted to POSIX. I would like to know why pathlib does not convert the Windows-style path to a POSIX path (currently running on Windows...
Found a solution: Path(PureWindowsPath(raw_string)) works on either platform. It’s useful if you’re developing on Windows and want to simply copy paste long Windows formatted file paths. raw_string = r'.\mydir\myfile' print(Path(PureWindowsPath(raw_string))) Output: mydir/myfile And you need the PureWindowsPath. If o...
2
1
77,642,254
2023-12-11
https://stackoverflow.com/questions/77642254/connect-to-dbus-signal-correct-syntax-pyside6
can you help me with the correct syntax to connect to a DBus signal? This is one of my many tries which at least runs and matches the signature in the docs: from PySide6 import QtDBus from PySide6.QtCore import Q from PySide6.QtWidgets import QMainWindow class MainWindow(QMainWindow): __slots__ = ["__mainwidget"] __mai...
This es the full solution to my initial post, I got this running with the QT/PySide support and they also acknowledged the hangig bug and a Python crash: import sys from PySide6.QtWidgets import QMainWindow from PySide6 import QtDBus, QtCore from PySide6.QtCore import QLibraryInfo, qVersion, Slot from PySide6.QtWidgets...
2
1
77,635,685
2023-12-10
https://stackoverflow.com/questions/77635685/getting-amplitude-value-of-mp3-file-played-in-python-on-raspberry-pi
I am playing an mp3 file with Python on a Raspberry Pi: output_file = "sound.mp3" pygame.mixer.init() pygame.mixer.music.load(output_file) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pass sleep(0.2) Now while the mp3 file is playing, I would like to get the current amplitude of the sound played. Is ...
There's a VU meter code on github working with microphone. You can easily change its input stream to wave file. If you want to work with .mp3 files, check this SO link for converting .mp3 to .wav on air without storing data on storage. import wave def main(): audio = pyaudio.PyAudio() try: # from wav file chunk = 1024 ...
5
3
77,645,141
2023-12-12
https://stackoverflow.com/questions/77645141/how-do-you-install-two-versions-of-python-on-a-docker-image-and-switch-them-on-b
I need to create a docker image that features two versions of Python, lets say, 3.9 & 3.10. The idea is to install both versions of Python and then install the pip/wheel/lib directories from Python 3.9 as it is the default version we want to use. I then created sys links to the pip/wheel/lib directories. Then using a ....
generic image that has both and we want to just swap the version on our CI/CD build when we build the Lambda, via Terraform passing in build args If you're already going to build the Lambda via Terraform, why don't you just build the Lambda with the correct version of Python? Say the Dockerfile for the Lambda is like...
2
1
77,627,725
2023-12-8
https://stackoverflow.com/questions/77627725/cannot-connect-to-my-couchbase-cluster-with-python-sdk
I can reach my couchbase cluster with a simple cURL: curl -u $CB_USERNAME:$CB_PASSWORD http://$CB_HOST/pools/default/buckets but I do not manage to connect using the Python SDK: from datetime import timedelta from couchbase.auth import PasswordAuthenticator from couchbase.cluster import Cluster from couchbase.options ...
Just to eliminate possible network/connectivity issues, I suggest running SDK Doctor. From the docs: SDK doctor is a tool to diagnose application-server-side connectivity issues with your Couchbase Cluster. It makes the same connections to the Couchbase Server cluster that Couchbase SDKs make during bootstrapping, and...
2
2
77,623,089
2023-12-7
https://stackoverflow.com/questions/77623089/pyvis-network-shows-html-which-is-not-100-percent-of-the-page
with this simple code the output is as expected but only in a 30% of the browser window. import networkx as nx from pyvis.network import Network G = nx.Graph() G.add_node(1) G.add_node(2) G.add_node(3) G.add_edge(1, 2) G.add_edge(1, 3) net = Network(height="100%", width="100%", directed=True, notebook=True) net.from_nx...
The reason why you cannot change the canvas size when you set it on 100% is that it is not 100% of browser window, it's 100% of its parent's height. If you change width and background color, you see the canvas is inside another frame. net = Network(height="500px", width="500px", directed=True, notebook=True, bgcolor="#...
3
1
77,645,110
2023-12-12
https://stackoverflow.com/questions/77645110/iterate-on-langchain-document-items
I loaded pdf files from a directory and I need to split them to smaller chunks to make a summary. The problem is that I can't iterate on documents object in a for loop and I get an error like this: AttributeError: 'tuple' object has no attribute 'page_content' How can I iterate on my document items to call the summary ...
And if you want to use a for loop, you can try: for file in os.listdir(pdf_folder_path): if file.endswith('.pdf'): pdf_path = os.path.join(pdf_folder_path, file) loader = PyPDFLoader(pdf_path) documents.extend(loader.load()) text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) chunked_docu...
2
2
77,648,771
2023-12-12
https://stackoverflow.com/questions/77648771/deserializtion-parsing-error-kafkaprotobuf-python
Serialization code (Go lang) 1. Producer func NewProducer(kafkaBrokerURL string, kafkaSchemaRegistryUrl string) { producerConfig := getKafkaProducerConfig(config.EnvConfig) producer, err := confluent_kafka.NewProducer(producerConfig) if err != nil { log.WithFields(log.Fields{"err": err}).Error("Failed to create Kafka P...
Your Go client is serializing with the Schema Registry meaning your Python code must do the same. The records are not "just Protobuf" since there's a schema ID also encoded in the bytes, therefore a regular Protobuf parser will fail. There's example code in the repo for consuming Protobuf with the Registry integration ...
2
1
77,641,455
2023-12-11
https://stackoverflow.com/questions/77641455/how-to-limit-memory-usage-while-scanning-parquet-from-s3-and-join-using-polars
As a follow-up question to this question, I would like to find a way to limit the memory usage when scanning, filtering and joining a large dataframe saved in S3 cloud, with a tiny local dataframe. Suppose my code looks like the following: import pyarrow.dataset as ds import polars as pl import s3fs # S3 credentials se...
polars doesn't (know how to) do predicate pushdown to the pa dataset. The development efforts are to bolster its own cloud hive reading so perhaps give that a try? The syntax for using it is a bit different than pyarrow. It should look roughly like this with possible nuance for how to enter your auth info. import polar...
2
2
77,642,547
2023-12-11
https://stackoverflow.com/questions/77642547/class-methods-are-not-at-the-same-address-for-both-parent-and-child-class
i try at the bellow code (for educational reasons) to implement this logic with class methods. What i observe is that, (a) the func1 inside the NO_CALCULATE list is not at the same address as func1 of the Parent class. (b) The type of the elements inside Calculate list, are class method objects and not methods as at CA...
What do you mean by "address"? In Python we don't use object addresses at all. There is, yes, an object ID, that as an implementation detail is the object pointer, (its address), but it is not usable as such from pure Python code. So, assuming you are seeing the ID's: both classmethods and ordinary instance methods are...
2
2
77,644,599
2023-12-12
https://stackoverflow.com/questions/77644599/why-does-adding-a-break-statement-significantly-slow-down-the-numba-function
I have the following Numba function: @numba.njit def count_in_range(arr, min_value, max_value): count = 0 for a in arr: if min_value < a < max_value: count += 1 return count It counts how many values are in the range in the array. However, I realized that I only needed to determine if they existed. So I modified it as...
TL;DR: Numba uses LLVM which not able to automatically vectorize the code when there is a break. One way to fix this is to compute the operation chunk by chunk. Numba is based on the LLVM compiler toolchain to compile the Python code to a native one. Numlba generates an LLVM intermediate representation (IR) from the P...
4
6
77,628,411
2023-12-8
https://stackoverflow.com/questions/77628411/how-to-convert-asynciterable-to-asyncio-task
I am using Python 3.11.5 with the below code: import asyncio from collections.abc import AsyncIterable # Leave this iterable be, the question is about # how to use many instances of this in parallel async def iterable() -> AsyncIterable[int]: yield 1 yield 2 yield 3 # How can one get multiple async iterables to work wi...
According your code snippet, you're trying to pass an async generator function (iterable) directly to asyncio.gather, however, it expects awaitables (coroutines, Tasks, or Futures). So, to fix the issue, one possible solution is, to create a new coroutine that consumes the async iterable()s and collects their items in ...
2
3
77,645,123
2023-12-12
https://stackoverflow.com/questions/77645123/export-pandas-io-excel-object-into-excel-file
I have reponse object that contain excel file, which i am decoding like this xl = pd.ExcelFile(io.BytesIO(response.content)) Now i want to export this into a .xlsx file. This object had pandas.io.excel._base.Excelfile type. Is there any way to export this. I have tried .to_excel but that didn't worked.
ExcelFile's purpose is to read and parse excel files into pandas objects. If your object is already an excel file, why pass it to ExcelFile at all? Directly save the response.content to a file: with open('outfile.xlsx', 'wb') as f: f.write(response.content) If you want to save the individual sheets, you can indeed use...
2
1