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,955,553
2024-2-7
https://stackoverflow.com/questions/77955553/dataframe-with-items-as-str-array-convert-to-multiindex
I've got some input data, which has a structure such that items can be a single entry, but also a str that is actually an array, but was not yet converted. A basic example would look like this: d = { 'col1': ['[5.02, 1, 3, 2]', '[2.002, 3.14, 4.5, 6.000153, 3]'], 'col2': ['[1.01, 1.02, 2, 4, 5, 10]', '[2, 3.05, 4.001, ...
One option taking advantage of the fact that str.extractall adds a second level: out = pd.concat({c: df[c].str.extractall('(\d+\.?\d*)')[0].astype(float) if df[c].dtype == object else df[c].set_axis( pd.MultiIndex.from_product([df[c].index, [0]]) ) for c in df}, axis=1 ).sort_index().rename_axis(['dataset', 'data point...
2
1
77,953,618
2024-2-7
https://stackoverflow.com/questions/77953618/how-to-change-the-root-directory-for-the-jupyter-notebook-in-windows
I can't «persuade» Jupyter to use another directory then the default one for storing its projects. I edited the following parameter of the jupyter_notebook_config.py file (I tried all three variants one-by-one, none worked): c.NotebookApp.notebook_dir = 'D:\\_Travail\\Python\\Jupyter_projects' c.NotebookApp.notebook_di...
You can launch the Jupyter in the directory you want. Open Anaconda Prompt and enter the following statement: jupyter notebook --notebook-dir "your-directory"
2
4
77,952,195
2024-2-7
https://stackoverflow.com/questions/77952195/streaming-function-in-microsoft-autogen
I want to know how to use the Streaming function in Autogen. The code below uses Autogen to enable the Agent to have streaming function. llm_config = { "config_list" : config_list, "timeout" : 120, "seed" : random.randint(1, 100), "stream" : True } user_proxy.initiate_chat( manager, message="hello, the weather is nice ...
Currently, there isn't a direct solution provided by AutoGen for the streaming issue you've described. This is evidenced by the lack of solutions in their open issues on GitHub, specifically related to streaming (https://github.com/microsoft/autogen/issues?q=is%3Aissue+is%3Aopen+streaming). However, a workaround exists...
2
2
77,935,269
2024-2-4
https://stackoverflow.com/questions/77935269/performance-results-differ-between-run-in-threadpool-and-run-in-executor-in
Here's a minimal reproducible example of my FastAPI app. I have a strange behavior and I'm not sure I understand the reason. I'm using ApacheBench (ab) to send multiple requests as follows: ab -n 1000 -c 50 -H 'accept: application/json' -H 'x-data-origin: source' 'http://localhost:8001/test/async' FastAPI app import t...
Using run_in_threadpool() FastAPI is fully compatible with (and based on) Starlette, and hence, with FastAPI you get all of Starlette's features, such as run_in_threadpool(). Starlette's run_in_threadpool(), which uses anyio.to_thread.run_sync() behind the scenes, "will run the sync blocking function in a separate thre...
9
29
77,919,632
2024-2-1
https://stackoverflow.com/questions/77919632/how-to-find-the-indexes-of-the-first-n-maximum-values-of-a-tensor
I know that torch.argmax(x, dim = 0) returns the index of the first maximum value in x along dimension 0. But is there an efficient way to return the indexes of the first n maximum values? If there are duplicate values I also want the index of those among the n indexes. As a concrete example, say x=torch.tensor([2, 1, ...
To acquire all you need you have to go over the whole tensor. The most efficient should therefore be to use argsort afterwards limited to n entries. >>> x=torch.tensor([2, 1, 4, 1, 4, 2, 1, 1]) >>> x.argsort(dim=0, descending=True)[:n] [2, 4, 0, 5] Sort it again to get [0, 2, 4, 5] if you need the ascending order of i...
2
4
77,927,215
2024-2-2
https://stackoverflow.com/questions/77927215/understanding-scikit-learn-import-variants
Scikit learn import statements in their tutorials are on the form from sklearn.decomposition import PCA Another versions that works is import sklearn.decomposition pca = sklearn.decomposition.PCA(n_components = 2) However import sklearn pca = sklearn.decomposition.PCA(n_components = 2) does not, and complains Attrib...
sklearn doesn't automatically import its submodules. If you want to use sklearn.<SUBMODULE>, then you will need to import it explicitly e.g. import sklearn.<SUBMODULE>. Then you can use it without any further imports like result = sklearn.<SUBMODULE>.function(...). Large packages often behave this way where they don't ...
2
4
77,914,856
2024-1-31
https://stackoverflow.com/questions/77914856/sphinx-raises-warnings-for-class-derived-from-intenum-can-i-do-something-about
As the title says. The warnings are: docstring of liesel.goose.EpochType.from_bytes:9: WARNING: Inline interpreted text or phrase reference start-string without end-string. docstring of liesel.goose.EpochType.to_bytes:8: WARNING: Inline interpreted text or phrase reference start-string without end-string. I am using S...
I ran into this problem too, and @mzjn's explanation seems to be right. A fix to use apostrophes for the opening quotes got merged and will be in the upcoming Python 3.13. release: https://github.com/python/cpython/pull/117847 I also tried to fix a handful other similar cases of this in the standard library in https://...
2
2
77,949,419
2024-2-6
https://stackoverflow.com/questions/77949419/how-to-force-an-async-context-manager-to-exit
I've been getting into Structured Concurrency recently and this is a pattern that keeps cropping up: It's nice to use async context managers to access resource - say a some websocket. That's all great if the websocket stays open, but what about if it closes? well we expect our context to be forcefully exited - normally...
Before we get started, let's replace manual __aenter__() and __aexit__() implementations with contextlib.asynccontextmanager. This takes care of handling exceptions properly and is especially useful when you have nested context managers, as we're going to have in this answer. Here's your snippet rewritten in this way. ...
3
3
77,946,746
2024-2-6
https://stackoverflow.com/questions/77946746/connect-docker-container-with-sql-server
I'm trying to run code that writes on a SQL Server database. The code is working fine on my machine (Microsoft). dockerfile: # syntax=docker/dockerfile:1 FROM ubuntu:22.04 WORKDIR /app RUN apt-get update RUN apt-get install -y apt-utils \ && echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections...
If you must have mssql-tools inside the container then you have to follow : the Microsoft instructions (note different Ubuntu version) or get an existing Docker container with mssql-tools in it. The basic commands (Ubuntu 22.04 version) are: curl https://packages.microsoft.com/keys/microsoft.asc | sudo tee /etc/apt/tru...
2
2
77,939,941
2024-2-5
https://stackoverflow.com/questions/77939941/unable-to-start-mlflow-ui
Problem: Following a quicksart guide in official docs (https://mlflow.org/docs/latest/tracking/autolog.html), every time I try running mlflow ui --port 8080 inside parent directory with particular conda env activated same error keeps popping up: C:\Users\user\miniconda3\envs\regular\Lib\site-packages\pydantic\_internal...
Obviously the error was in cli.py. However the appropriate fix was needed, which, thanks to Gabomfim, has been discovered: just substitute .get("mlflow.app", []) by .select(group="mlflow.app")
2
2
77,938,155
2024-2-5
https://stackoverflow.com/questions/77938155/acknowledged-kombu-message-is-not-removed-from-rabbitmq-queue
I am trying to create a Python script that waits for a message on a RabbitMQ queue to start a task in a subprocess. During task execution, the script continues to consume another queue for a cancel order that would stop the task. I use kombu package to handle interactions with RabbitMQ. I call message.ack() when the ta...
I finally found the cause of my problem. Actually there were two causes: I did not set channels when creating the Consumers, so they were both using the same channel. Since I had set noAck=True for the "stop" consumer, calling message.ack() had no effect. The strange thing is that noAck=True should have caused the ACK...
2
1
77,940,460
2024-2-5
https://stackoverflow.com/questions/77940460/psycopg3-pool-all-connections-getting-lost-instantly-after-long-idle-time
If it's a standalone persistant connection, I have no problem, connection lasts for hours. If I use psycopg(3) Connection pool, I make make requests, first requests are ok and my pool size stays at 5, at one point pool size decreases and I get a Pool Timeout when client makes a new request. Then I tried: start pool, do...
connection logs from postgresql gave a hint: SSL error before all connection going dust: 2024-02-09 10:38:05.627 CET [297036] LOG: checkpoint starting: time 2024-02-09 10:38:05.739 CET [297036] LOG: checkpoint complete: wrote 2 buffers (0.0%); 0 WAL file(s) added, 0 removed, 0 recycled; write=0. 103 s, sync=0.002 s, to...
2
2
77,929,999
2024-2-2
https://stackoverflow.com/questions/77929999/how-to-generate-name-combinations-with-initials
Given a string of a person's name: "Richard David" I'd like to create a list of all combinations of this name where up to all but one of the individual names are replaced with initials: [ "Richard David", "R David", "Richard D", ] An example with three individual names: "Richard Anthony David" Would output: [ # repl...
Using the fact that the order of the elements returned by itertools.product is predictable, as guaranteed in its documentation. from itertools import product def all_names(fullname): pool = [(word, word[0]) for word in fullname.split()] return [' '.join(name) for name in product(*pool)][:-1] print(*all_names("Richard A...
2
3
77,922,817
2024-2-1
https://stackoverflow.com/questions/77922817/importerror-cannot-import-name-iterator-from-typing-extensions
When I try to install openai on my Google Colab, I get this error: from openai import OpenAI --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-6-5ee9a4e68b89> in <cell line: 1>() ----> 1 from openai import OpenAI 5 frames /usr/local/...
I found a related issue on OpenAI forum: https://community.openai.com/t/error-while-importing-openai-from-open-import-openai/578166/26 Solution 1: Credit to @Aymane_oub pip install --force-reinstall typing-extensions==4.5 pip install --force-reinstall openai==1.8 Solution 2: Credit to @Shannon-21 After navigating thr...
2
4
77,941,127
2024-2-5
https://stackoverflow.com/questions/77941127/how-can-i-get-the-fully-qualified-names-of-return-types-and-argument-types-using
Consider the following example. I use python clang_example.py to parse the header my_source.hpp for function and method declarations. my_source.hpp #pragma once namespace ns { struct Foo { struct Bar {}; Bar fun1(void*); }; using Baz = Foo::Bar; void fun2(Foo, Baz const&); } clang_example.py I use the following code t...
Unfortunately, there does not appear to be a simple way to print a type using fully-qualified names. Even in the C++ API, QualType::getAsString(PrintingPolicy&) ignores the SuppressScope flag due to the intervention of the ElaboratedTypePolicyRAII class (I don't know why, and the git commit history offers no clues that...
2
1
77,951,155
2024-2-6
https://stackoverflow.com/questions/77951155/does-offset-have-a-default-value
In the code below, if the upload_file_2_sp function is called, I'm unsure of how the offset argument is being assigned a value. The code will run successfully as is, but I'm trying to add a second argument to the print_upload_progress function to pass each file in my file list loop to the print_upload_progress function...
The arguments are passed automatically by create_upload_session(), you can't change what it passes. You could use a lambda to pass additional arguments to your function. for file in report_list: uploaded_file = target_folder.files.create_upload_session( file, size_chunk, lambda offset, file=file: print_upload_progress...
2
3
77,950,773
2024-2-6
https://stackoverflow.com/questions/77950773/resampling-and-interpolation-of-pandas-dataframe-with-multiple-columns
I have a dataframe that looks roughly like this: timestamp mmsi departures_count calc_speed coursechange 2012-01-31 07:11:59 1.252340e+12 1 4.041755 0.000000 2012-01-31 07:22:20 1.252340e+12 1 5.209561 30.000000 2012-01-31 07:35:34 1.252340e+12 2 5.766184 1.000000 2012-01-31 07:45:35 1.252340e+12 2 5.9326...
You can try: def fn(g): rng = pd.date_range( g.index[0].floor("10min"), g.index[-1].ceil("10min"), freq="10min" ) g = ( g.reindex(g.index.union(rng)) .interpolate(method="linear", limit_direction="both") .reindex(rng) ) return g df["timestamp"] = pd.to_datetime(df["timestamp"]) df = df.set_index("timestamp") out = df.g...
2
2
77,950,619
2024-2-6
https://stackoverflow.com/questions/77950619/how-to-suppress-line-too-long-warning-pyright-extended-in-replit-python
When coding in Python using Replit, I get the annoying warning "Line too long" (pyright-extended). How can I get Replit to always ignore displaying this type of warnings?
Just add 'E501' to the "[tool.ruff]" section of the "pyproject.toml"-file, to disable the warning in the default python template. https://ask.replit.com/t/python-88-characters-maximum-in-a-line/74941
2
2
77,950,122
2024-2-6
https://stackoverflow.com/questions/77950122/handle-exceptions-in-python-functions-signature
I wonder if I have designed my script correctly (it works so far) because of a loop of warnings from which I cannot get out. I am trying to define a function that either is able to parse a JSON response from a website or it simply terminates the program. Here my code: from requests import get, Response, JSONDecodeError...
typing.NoReturn is used for functions that never return. For example: from typing import NoReturn def stop() -> NoReturn: raise RuntimeError('no way') So you should type hint the return value of logout() with NoReturn: from typing import NoReturn def logout() -> NoReturn: exit()
2
3
77,948,903
2024-2-6
https://stackoverflow.com/questions/77948903/no-matching-distribution-found-for-setuptools-while-building-my-own-pip-packag
I am building a Python package using setuptools. This is the basic structure: /path/to/project/ ├── myproj/ │ ├── __init__.py │ └── my_module.py ├── pyproject.toml ├── setup.cfg └── ## other stuff This is the content of pyproject.toml [build-system] requires = [ "setuptools", "setuptools-scm"] build-backend = "setupto...
However, if I upload it to test.pypi and then I pip install it from test.pypi I assume this means you're using --index-url https://test.pypi.org/simple/, which is confirmed by the build output Looking in indexes: https://test.pypi.org/simple/. That tells pip to use TestPyPI exclusively as the package index. You will ...
2
3
77,945,663
2024-2-6
https://stackoverflow.com/questions/77945663/polars-alternative-solution-to-using-map-groups-with-with-columns
I think after the recent update of Polars (version 0.20.7), it stopped supporting the use of map_groups with with_columns I got a Type Error stating TypeError: cannot call `map_groups` when grouping by an expression I am trying to Group By a column called Product Number and fill the null values using backward strategy...
Instead, you can use pl.Expr.over to compute expressions over certain groups. ( df1 .with_columns( pl.col("New Date") .fill_null(strategy="backward") .over("'Product Number'") .alias("New Date1") ) )
3
0
77,947,027
2024-2-6
https://stackoverflow.com/questions/77947027/how-can-i-use-a-classvar-literal-as-a-discriminator-for-pydantic-fields
I'd like to have Pydantic fields that are discriminated based on a class variable. For example: from pydantic import BaseModel, Field from typing import Literal, ClassVar class Cat(BaseModel): animal_type: ClassVar[Literal['cat']] = 'cat' class Dog(BaseModel): animal_type: ClassVar[Literal['dog']] = 'dog' class PetCarr...
This is a very interesting question. Broadly it seems to me that Pydantic does not support discriminated unions for ClassVar literals, but that asks the question, why not? An important thing to note about ClassVar's, is they don't become regular fields in pydantic (https://docs.pydantic.dev/2.3/usage/models/#class-vars...
4
2
77,945,267
2024-2-6
https://stackoverflow.com/questions/77945267/vscode-settings-json-error-incorrect-type-expected-string
how do i fix the error shown in the pic, i was trying to edit my VSCode settings.json, installed the extension Ruff and tried to edit the settings based on an article I've read here: https://medium.com/@ordinaryindustries/the-ultimate-vs-code-setup-for-python-538026b34d94 but i get the error shown in the pic below
Smart Tips(Ctrl+Space) displays these two settings with five values, which are: "always": Triggers Code Actions on explicit saves and auto saves triggered by window or focus changes. "explicit": Triggers Code Actions only when explicitly saved "never": Never triggers Code Actions on save "false": Never triggers Code A...
3
4
77,942,843
2024-2-5
https://stackoverflow.com/questions/77942843/how-to-install-a-namespace-package-with-hatch
in The context of the sphinxcontrib organisation the package are supposed to all live in a sphinxcontrib namespace package like "sphinxcontrib.icon" or "sphinxcontrib.badge". The file have the following structure: sphinxcontrib-icon/ ├── sphinxcontrib/ │ └── icon/ │ └── __init__.py └── pytproject.toml In a setuptools ...
copying here the answer given by the hatchling repository maintainers: The packages option is for the case where your code lives under a directory like src/ and will collapse until the last path component. So if your namespace package lived under such a directory then you could set that to src/sphinxcontrib but since ...
4
2
77,942,463
2024-2-5
https://stackoverflow.com/questions/77942463/numba-implementation-for-monte-carlo-simulation
I'm actually writing a Monte-Carlo code for simple fluid simulation. The code was predicting good results for energy and pressure before Numba implementation, and after its implementation it doesn't predicts good result at all. Since I'm not very familiar with Numba, I don't really know where the error is comming from....
Don't use global variables. I changed the jitted function to accept positions as first argument: import numpy as np from numba import njit # Constants N = 100 density = 0.8 T = 2.0 beta = 1 / T L = (N / density) ** (1.0 / 3.0) cutoff = 2.5 boxVolume = N / density numEqSteps = 100000 numSampSteps = 100000 numTotalSteps ...
2
2
77,943,395
2024-2-5
https://stackoverflow.com/questions/77943395/openai-embeddings-api-how-to-extract-the-embedding-vector
I use nearly the same code as here in this GitHub repo to get embeddings from OpenAI: oai = OpenAI( # This is the default and can be omitted api_key="sk-.....", ) def get_embedding(text_to_embed, openai): response = openai.embeddings.create( model= "text-embedding-ada-002", input=[text_to_embed] ) return response embed...
Simply return just the embedding vector as follows: def get_embedding(text_to_embed, openai): response = openai.embeddings.create( model= "text-embedding-ada-002", input=[text_to_embed] ) return response.data[0].embedding # Change this embedding_raw = get_embedding(text,oai)
3
2
77,943,054
2024-2-5
https://stackoverflow.com/questions/77943054/how-do-i-make-a-custom-class-thats-serializable-with-dataclasses-asdict
I'm trying to use a dataclass as a (more strongly typed) dictionary in my application, and found this strange behavior when using a custom type subclassing list within the dataclass. I'm using Python 3.11.3 on Windows. from dataclasses import dataclass, asdict class CustomFloatList(list): def __init__(self, args): for ...
If you look at the source code of asdict, you'll see that passes a generator expression that recursively calls itself on the elements of a list when it encounters a list: elif isinstance(obj, (list, tuple)): # Assume we can create an object of this type by passing in a # generator (which is not true for namedtuples, h...
2
3
77,939,542
2024-2-5
https://stackoverflow.com/questions/77939542/how-to-slice-data-in-pytorch-tensor
I've put my data to the pytorch tensor and now i want to split into the batches size 64. I got the following code: batch = 0 BATCH_SIZE = 64 X_train = x_scaled.to(device) y_train = y_scaled.to(device) for batch in range(0,len(X_train[0]),BATCH_SIZE): ### Training model.train() # train mode is on by default after constr...
You should read how indexing works in pytorch/numpy and other similar libraries. You have a tensor of shape (2, 11938). When you index with X_train[0:2], you get a tensor of size (2, 11938). You don't need to index if you want all the rows. When you index with X_train[0:2][batch:batch+BATCH_SIZE], you're indexing the r...
2
2
77,943,148
2024-2-5
https://stackoverflow.com/questions/77943148/how-to-add-numeric-value-from-one-column-to-other-list-column-elements-in-polars
Suppose I have the following Polars DataFame: import polars as pl df = pl.DataFrame({ 'lst': [[0, 1], [9, 8]], 'val': [3, 4] }) And I want to add the number in the val column, to every element in the corresponding list in the lst column, to get the following result: ┌───────────┬─────┐ │ lst ┆ val │ │ --- ┆ --- │ │ li...
If lst has a fixed number of items for the whole column AND you know how many in advance then you can do this: df.with_columns( pl.concat_list(pl.col('lst').list.get(x) + pl.col('val') for x in range(2)) ) If not, then you can still do this: df.with_columns( pl.concat_list( pl.col('lst').list.get(x) + pl.col('val') fo...
4
2
77,942,425
2024-2-5
https://stackoverflow.com/questions/77942425/how-to-serialize-list-of-list-items-to-pydantic-model
I have response from server: { "date": "2024-02-05 15:34:44", "status": True, "data": [ [1, "red"], [2, "blue"], [3, "yellow"] ] } And i want to serialize this response to pydantic model, but i don't know how parse list (example [1, "red"]) in pydantic model class Item(BaseModel): # how convert list from data to this ...
You can work for example with a model_validator to parse the list into the Item model: from pydantic import BaseModel, model_validator data = { "date": "2024-02-05 15:34:44", "status": True, "data": [ [1, "red"], [2, "blue"], [3, "yellow"] ] } class Item(BaseModel): id: int color: str @model_validator(mode="before") @c...
2
3
77,941,994
2024-2-5
https://stackoverflow.com/questions/77941994/what-is-setuptools-alternative-to-the-deprecated-distutils-strtobool
I am migrating to Python 3.12, and finally have to remove the last distutils dependency. I am using from distutils.util import strtobool to enforce that command-line arguments via argparse are in fact bool, properly taking care of NaN vs. False vs. True, like so: arg_parser = argparse.ArgumentParser() arg_parser.add_ar...
What about using argparse's BooleanOptionalAction? This is documented in the argparse docs, but not in a way that provides me with a useful link. That would look like: arg_parser = argparse.ArgumentParser() arg_parser.add_argument("-r", "--rebuild-all", action=argparse.BooleanOptionalAction, default=True) And it would...
3
3
77,940,596
2024-2-5
https://stackoverflow.com/questions/77940596/azure-devops-and-uploading-a-python-package-to-artifacts-using-pipeline-authen
I am trying to use the Azure pipeline to publish a Python package to Artifact's feed. I could do it from my local machine and upload the package using Twine, but I have an authentication issue in the pipeline. trigger: - main pool: vmImage: ubuntu-22.04 variables: pip_cache_dir: '$(Pipeline.Workspace)/.pip_cache' steps...
Go the Azure Artifacts feed you want to publish the Python package to, then navigate to Feed Settings > Permissions page to check and ensure the following identities have been assigned with Contributor role at least. Project Collection Build Service ({OrgName}) {ProjectName} Build Service ({OrgName}) For more detail...
2
1
77,920,479
2024-2-1
https://stackoverflow.com/questions/77920479/how-to-specify-bounds-and-variable-length-in-python-union-types
I have a type that has subclasses. E.g., Event, with classes Event1(Event), Event2(Event), etc. I want to specify a type annotation for the argument to a function that accepts any union of subclasses of Event. Concretely, I want all of the following to type check: listen_for_events(Event1) listen_for_events(Event1 | Ev...
So to answer this question, firstly let's look at how union types work. The syntax you're describing generates a types.UnionType, and you can't specify any more detail about this type. e.g. Something like the below passes for all of your examples, including the one you didn't want: def listen_for_events(event: type[Eve...
2
2
77,939,544
2024-2-5
https://stackoverflow.com/questions/77939544/python-h5py-warning-getlimits-py511-userwarning-signature-class-numpy-float
I get following warning on RedHat 8.8 for H5PY Package: Is there any way to fix this? I dont want to use warnings.filterwarnings("ignore") bash-4.4$ python3 Python 3.11.6 (main, Oct 16 2023, 03:41:34) [GCC 8.5.0 20210514 (Red Hat 8.5.0-18)] on linux Type "help", "copyright", "credits" or "license" for more information....
A similar issue posted on git : https://github.com/h5py/h5py/issues/2357 moving to numpy version older than 1.24 may fix the warning. Looks like a broken support for long double/numpy.float128 data type from the OS. You can try other methods to ignore warnings as well.
2
3
77,922,917
2024-2-1
https://stackoverflow.com/questions/77922917/find-maximum-radius-circle-everywhere-between-two-lines
I have two sine waves, as pictured below. Sometimes they are identical waves, just shifted in the y-axis. Other times the sine waves have different period / amplitude etc. I need to find the maximum radius circle that can fit between the two lines everywhere along the lines (discretized by the resolution that I genera...
I'm not sure if this a the complete answer, but it may contain a few useful ideas. (There is some math, but I think the code is also important, so I think SO is a reasonable place for this question.) There may be multiple solutions to the last equation, but in practice scipy.optimize.newton seems to converge to the c...
2
3
77,932,050
2024-2-3
https://stackoverflow.com/questions/77932050/chromedriver-is-suddenly-displaying-a-strange-warning-about-blocking-third-party
Here's my python code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from flask import Flask, render_template from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service APP = Flask(__na...
I just came across this error too. Try adding the following: chrome_options.add_argument('log-level=3')
3
3
77,930,475
2024-2-3
https://stackoverflow.com/questions/77930475/replicating-columns-in-dataframe-based-on-the-column-names
I have a following dataframe called ol_axle: Single Tridem Tandem Tridem 700 1500 1200 2700 The code to create the dataframe is as follows: weight=[700,1500,1200,2700] name=['Single','Tridem','Tandem','Tridem'] ol_axle=pd.DataFrame([weight],columns=[name]) My apologies as the query doesn't appear to be tha...
Using numpy.repeat with map: n = {'Single': 1, 'Tandem': 2, 'Tridem': 3} rep = ol_axle.columns.map(n) out = (pd.DataFrame(np.repeat(ol_axle.div(rep, axis=1), rep, axis=1), columns=np.repeat(ol_axle.columns, rep), index=ol_axle.index) ) print(out) Variant of @Timeless' approach using iloc: n = {'Single': 1, 'Tandem': 2...
2
2
77,928,132
2024-2-2
https://stackoverflow.com/questions/77928132/how-to-install-conda-file-downloaded-from-anaconda-package-site
For example, I want to install fish shell using conda. But the server has no internet connection. On https://anaconda.org/conda-forge/fish/files , many versions are provided. But almost the latest few versions are always in .conda format. I downloaded linux-64/fish-3.7.0-hdab1d28_0.conda and install it using conda inst...
Bug with Anaconda Cloud downloads There is an outstanding bug with the Anaconda Cloud website that prepends the subdirectory (e.g., a linux-64_ prefix) to file names when downloading from a browser (i.e., clicking file links). This is fine for .tar.gz files, but for .conda the file name is coupled(!) to being able to c...
4
3
77,930,086
2024-2-2
https://stackoverflow.com/questions/77930086/how-to-alter-pythons-json-encoder-to-convert-nan-to-none
Say I have this (all this is Python 3.11 in case that matters): not_a_number = float("NaN") # this actually comes from somewhere else json.encode([not_a_number]) The output is an (invalid) JSON literal NaN. I've been trying to create an JSONEncoder subclass that would use math.isnan() to determine if the value is a Na...
I don't know about easy solution to replace NaN with custom values (other than replace NaNs in original object). On top of that, json module doesn't make it easy to monkeypatch the inner workings: https://github.com/python/cpython/blob/034bb70aaad5622bd53bad21595b18b8f4407984/Lib/json/encoder.py#L224 But you can try: i...
3
0
77,930,211
2024-2-2
https://stackoverflow.com/questions/77930211/removing-duplicates-in-a-pandas-dataframe-for-only-a-specified-value
Let's say I have a dataframe: df = pd.DataFrame({ 'ID': [1, 2, 3, 1, 2, 3], 'Value': ['A', 'B', 'A', 'B', 'C', 'A'] }) If I wanted to only remove duplicates on ID when ID is a specified value (let's say 1), how would I do that? In other words, the resulting dataframe would look like: |ID|Value| |--|-----| |1 |A | |2 |...
Create a boolean mask with DataFrame.duplicated: mask = df.ID.eq(1) & df.duplicated(subset=["ID"]) print(df[~mask]) Prints: ID Value 0 1 A 1 2 B 2 3 A 4 2 C 5 3 A Steps: print(df.ID.eq(1)) 0 True 1 False 2 False 3 True 4 False 5 False Name: ID, dtype: bool print(df.duplicated(subset=["ID"])) 0 False 1 False 2 False...
2
3
77,928,740
2024-2-2
https://stackoverflow.com/questions/77928740/python-sockets-in-a-multithreaded-program-with-classes-objects-interfere-with-ea
As an aid to my work, I am developing a communication simulator between devices, based on TCP sockets, in Python 3.12 (with an object oriented approach). Basically, the difference between a SERVER type communication channel rather than a CLIENT type is merely based on the way by which the sockets are instantiated: resp...
Then I read that inheritance in Python is not the same as in Java Thanks, that was a good tip to find the issue! While not an inheritance issue, I think you're seeing problems caused by this Java-ism: class ChannelClientManager(): establishedConn = None receivedData = None eventMainThread = None #set this event when ...
2
4
77,928,596
2024-2-2
https://stackoverflow.com/questions/77928596/finding-all-combinations-of-two-sets-with-k-elements-being-exchanged
Lets say I have two list ['a', 'b', 'c', 'd'] and ['x', 'y', 'z', 'w']. I want to create a set of two other list where k elements are being exchanged between the two lists: Example for a single element: ['x', 'b', 'c', 'd'] ['a', 'y', 'z', 'w'] ['a', 'x', 'c', 'd'] ['b', 'y', 'z', 'w'] ['a', 'b', 'x', 'd'] ['c', 'y', '...
I think the nested loops is as efficient as it gets, because you're basically generating a list of [source_index, target_index] pairs. Though re-creating the lists on every iteration is indeed wasteful. Here's a more straightforward solution for k=1, using itertools.product: import itertools list_0 = ['a', 'b', 'c', 'd...
2
2
77,920,123
2024-2-1
https://stackoverflow.com/questions/77920123/using-starlette-testclient-causes-an-attributeerror-unixselectoreventloop-o
Using FastAPI : 0.101.1 I run this test_read_aynsc and it pass. # app.py from fastapi import FastAPI app = FastAPI() app.get("/") def read_root(): return {"Hello": "World"} # conftest.py import pytest from typing import Generator from fastapi.testclient import TestClient from server import app @pytest.fixture(scope="se...
To support async debugging, PyCharm patches a bunch of asyncio APIs with custom wrapped functions. Notably, it patches asyncio.new_event_loop() in ~/Applications/PyCharm Professional Edition.app/Contents/plugins/python/helpers-pro/pydevd_asyncio/pydevd_nest_asyncio.py:169. Starlette uses anyio, with the asyncio backend...
9
11
77,924,775
2024-2-2
https://stackoverflow.com/questions/77924775/how-to-get-correct-date-with-gspread
How can I get the spreadsheet values with Python's gspread? Suppose there is a cell that looks like 1/1 because m/d is specified as the cell display format, but actually contains 2024/1/1. Retrieving this cell using get_all_values() returns "1/1". I want the actual value "2024/1/1", not the value displayed on the sheet...
Issue and workaround: From your showing image, script, and current value, I understood that you put a value of 2024/01/01 into a cell "A2" as a date object. And, the cell value is shown as 1/1 with the number format. In the current stage, when this cell value is retrieved by Sheets API, 1/1 is retrieved as the default ...
2
2
77,922,861
2024-2-1
https://stackoverflow.com/questions/77922861/why-does-sympy-solve-produce-empty-array-for-certain-inequalities
sympy's solve seems to generally work for inequalities. For example: from sympy import symbols, solve; x = symbols('x'); print(solve('x^2 > 4', x)); # ((-oo < x) & (x < -2)) | ((2 < x) & (x < oo)) In some cases where all values of x or no values of x are valid solutions, solve() returns True or False to indicate that....
Remember that expressions are not WYSIWYG: your expressions did not have x in them: print(solve('x - x > 0', x)); # [] <-- solve(0>0, x) => solve(False, x) print(solve('x - x >= 0', x)); # [] <-- solve(0>=0, x) => solve(True, x) Since x does not appear in either expression, there are no values of x to report in the fi...
2
2
77,915,146
2024-1-31
https://stackoverflow.com/questions/77915146/binding-an-event-when-a-shape-is-clicked-in-turtle
I generate random figures on the screen. I want the screen to clear when I click on any circle shape. How to bind an event when a circle is clicked? I tried onclick() with clearscreen(), but it doens't work. My code: # -*- coding: utf-8 -*- import random import turtle class Figure: def __init__(self): __colors = ['red'...
onclick doesn't register a click listener on drawings the turtle has made, only on the turtle itself. But these turtles are hidden and only a few pixels large even if visible, so there's nothing to click. There are two main options: Keep the turtle drawing the same and add a screen click listener. In the click handler...
2
2
77,917,904
2024-2-1
https://stackoverflow.com/questions/77917904/pycharm-debugger-console-not-autocompleting-variables-created-in-the-debugger-co
I have just upgraded to PyCharm 2023.3.3 community edition and am experiencing a weird issue that hasn't occurred before. System is Windows 10 64 bit, and this has worked fine on this machine before. When I debug a script and hit a breakpoint and the program is suspended and the debugger window is opened, autocomplete ...
Open Settings | Build, Execution, Deployment | Console and switch Code Completion to Runtime. Relevant ticket in PyCharm's issue tracker - PY-64055.
4
7
77,915,725
2024-1-31
https://stackoverflow.com/questions/77915725/pass-fail-result-for-paramiko-sftpclient-get-and-put-functions
I'm writing an Ansible module using Paramiko's SFTPClient class. I have the following code snippets import paramiko from ansible.module_utils.basic import * def get_sftp_client(host, port, user, password): # Open a transport transport = paramiko.Transport((host,port)) # Auth transport.connect(None,user,password) # Get ...
The Paramiko SFTPClient.put and .get throw an exception on error. If they do not throw, then the transfer succeeded.
2
2
77,915,868
2024-1-31
https://stackoverflow.com/questions/77915868/module-os-has-no-attribute-add-dll-directory-in-aws-lambda-function
I'm facing an issue that os does not have an add_dll_directory attribute in the AWS lambda function on the trigger. I have written code for creating a thumbnail of a video and I have tried it locally that's working fine but when I upload this function with the required libraries then I get this issue and still, I'm una...
Lambda runtime doesn't provide Pillow or openCV, and you seem to have packaged Windows binary distributions of your dependencies with your Lambda code. You need to package the distributions compatible with Amazon Linux and the architecture of your Lambda function (x86_64 or arm). The easiest way to do this is create a ...
6
5
77,920,704
2024-2-1
https://stackoverflow.com/questions/77920704/how-to-access-values-of-two-keys-in-the-map-lambda-function
I have a list of dictionary like below : sample = [{'By': {'email': 'xyz@stackoverflow.com', 'name': 'xyzzy', 'id': '5859'}},{'By': {'email': 'abc@stackoverflow.com', 'name': 'abccb', 'id': '9843'}}, {'By': {'email': 'xyz@stackoverflow.com', 'name': 'xyzzy', 'id': '5859'}}] From this, I am trying to access keys 'name...
You want a dict, not a set. You can get all the values in the lambda and pack them in a tuple print(dict(map(lambda x: (x['By']['id'], x['By']['name']), sample))) You should also consider a simpler solution, you don't really need map and lambda here, dict-comprehensions will do just fine print({x['By']['id']: x['By'][...
2
2
77,920,093
2024-2-1
https://stackoverflow.com/questions/77920093/python-3-12-correct-typing-for-listlistint-str-listliststr
I have a list of users, that I would like to type correctly, but I'm not able to find an answer explaining how to do this. The list looks like this: listofusers = [[167, 'john', 'John Fresno', [[538, 'Privileged'], [529, 'User']]]] I tried doing like this: def test(listofusers: list[list[str,list[list[str]]]]) -> None...
As already mentioned in comments and in this answer, having such complicated structures look like code smell. You can think of re-organising your code a bit and do some more explicit semantics: import dataclasses @dataclasses.dataclass class Data: data_id: int attribute: str @dataclasses.dataclass class User: user_id: ...
4
4
77,915,010
2024-1-31
https://stackoverflow.com/questions/77915010/how-to-faster-find-x-value-that-minimizes-result-for-function-involving-multip
I have a LazyFrame with multiple columns of hourly data for a few periods. For each period, I want to find the x value for a function involving mathematical operations of multiple columns that minimizes the result. I used scipy.optimize.minimize to accomplish this, and I actually obtain the desired result. The problem ...
Avoid working with entire dataframe. As a start, you can cut the runtime by a factor of ~2 by only using the current group in the optimization target instead of filtering the entire dataframe first. This can be achieved as follows. import functools def minimization_target(x, group: pl.DataFrame): numerator_expr = pl.co...
3
5
77,919,397
2024-2-1
https://stackoverflow.com/questions/77919397/polars-create-an-integer-column-from-another-one-by-computing-the-difference-wi
I have a polars dataframe like this one: shape: (10, 2) ┌────────┬───────┐ │ foo ┆ bar │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞════════╪═══════╡ │ 86 ┆ 11592 │ │ 109 ┆ 2765 │ │ 109 ┆ 4228 │ │ 153 ┆ 4214 │ │ 153 ┆ 7217 │ │ 153 ┆ 11095 │ │ 160 ┆ 1134 │ │ 222 ┆ 5509 │ │ 225 ┆ 10150 │ │ 239 ┆ 4151 │ └────────┴───────┘ And a sorted...
You can have a solution which fully relies on polars expressions, by using join_asof. First, create DataFrame out of the list and then join (I'm assuming that points list is pre-sorted) Here, we leave strategy argument of the join empty, so default backward strategy is going to be used. A backward search selects the l...
2
4
77,918,063
2024-2-1
https://stackoverflow.com/questions/77918063/how-to-get-numeric-data-from-the-object-data-type-and-make-it-int-in-a-dataf
When loading securities quote data, the price values ​​look like this: Where units is the integer part, nano is the fractional part. | close | volume | time | {'units': 270, 'nano': 190000000} | 51642 | 2023-12-29 07:30:00+00:00 | {'units': 270, 'nano': 930000000} | 47910 | 2023-12-29 08:00:00+00:00 | {'units': 271, '...
Convert dictionaries to DataFrame by json_normalize and then create new column: v = pd.json_normalize(df['close']) df['close'] = v.units + v.nano / 1e9 But if there are strings repr of dictionaries first convert them: import ast v = pd.json_normalize(df['close'].apply(ast.literal_eval)) df['close'] = v.units + v.nano ...
2
4
77,917,091
2024-2-1
https://stackoverflow.com/questions/77917091/unique-melt-and-pivot-crosstab-format-with-a-groupby-using-pandas
I have a dataset where I would like for some values to become column headers, as well as a crosstab format. data year qtr ID type growth re nondd_re se_re or 2024 2024Q1 NY aa 3.18 1.14 0 0 0 2024 2024Q2 NY aa 2.1 1.14 0 0 0 2024 2024Q1 NY dd 6.26 3.07 3.07 0 0 2024 2024Q2 NY dd 4.13 3.07 3.07 0 0 2024 2024Q1 CA aa 0 0...
You can try to set_index() + stack()/unstack(): out = ( df.set_index(["year", "qtr", "ID", "type"]) .stack() .unstack("qtr") .reset_index() .rename(columns={"level_3": "type2"}) .rename_axis(columns=None, index=None) ) print(out) Prints: year ID type type2 2024Q1 2024Q2 0 2024 CA aa growth 0.00 0.03 1 2024 CA aa re 0...
2
1
77,912,637
2024-1-31
https://stackoverflow.com/questions/77912637/what-is-in-python-function-definition
I know what a single asterisk (*) means in a function definition. See, for example, this question. However, the documentation of warnings.warn contains the entry \*. What does this symbol combination mean in a function definition?
A typo, up to 3.11 it's not there warnings.warn(message, category=None, stacklevel=1, source=None): warnings.warn(message, category=None, stacklevel=1, source=None) Issue a warning, or maybe ignore it or raise an exception. The category argument, if given, must be a warning category class; it defaults to UserWarning. A...
3
2
77,914,684
2024-1-31
https://stackoverflow.com/questions/77914684/how-do-you-write-a-statically-typed-python-function-that-converts-a-string-to-a
I would like to write a statically typed Python function that accepts a general type and a string and that returns a value of the given type, derived from the given string. For example: >>> parse(int | None, "5") 5 >>> parse(int | None, "") is None True Here's a Python 3.12 attempt (which has a problem in the type sig...
In short, this is a problem of parametricity. Your function is not the same for every possible type A. With the signature def parse[A](x: type[A], v: str) -> A: ... the type checker has no idea what A is, only that a value of type A is required. As such, the only way to get such a value is to call x. The following tri...
2
1
77,914,583
2024-1-31
https://stackoverflow.com/questions/77914583/gammainc-difference-in-python-and-matlab
I am transfering code between Matlab and Python. However when I use scipy.special.gammainc I get different values than when I use gammainc in Matlab. My Python code is: from scipy.special import gammainc gammainc([1, 2, 3, 4], 5) array([0.99326205, 0.95957232, 0.87534798, 0.73497408]) However in Matlab I have: gammain...
There are two issues with your code: Matlab's gammainc function expects the input arguments in reverse order compared to the usual mathematical notation. So it expects the integral limit first, then the exponent. Scipy's gammaincc is the upper incomplete Gamma function, not the lower. For the lower version you need to...
4
3
77,914,497
2024-1-31
https://stackoverflow.com/questions/77914497/keep-all-rows-before-first-occurrence-of-a-value
I have a pandas dataframe and the opposite question to Drop all rows before first occurrence of a value Instead of drop all rows before the first occurence of a value, I want to keep the rows before the first occurence of a value. so for example, i want to keep all the rows before the occurence 1 in the column count: Y...
Use cummax and negate its output (~) to form a boolean Series for boolean indexing: out = df[~df['Count'].eq(1).cummax()] Output: Year ID Count 0 1997 1 0 1 1998 2 0 Intermediates: Year ID Count eq(1) cummax ~ 0 1997 1 0 False False True 1 1998 2 0 False False True 2 1999 3 1 True True False 3 2000 4 0 False True F...
2
3
77,914,135
2024-1-31
https://stackoverflow.com/questions/77914135/weird-behavior-of-new
I have encountered a peculiar behavior with the __new__ method in Python and would like some clarification on its functionality in different scenarios. Let me illustrate with two unrelated classes, A and B, and provide the initial code: class A: def __new__(cls, *args, **kwargs): return super().__new__(B) def __init__(...
TL;DR super().__new__(B) is not the same as B(). As @jonsharpe pointed out in a comment, __init__ is only called when an instance of cls is returned. But this implicit call to __init__ is handled* by type.__call__, not the call to __new__ itself before it returns. For example, you can imagine type.__call__ is implemen...
3
4
77,914,136
2024-1-31
https://stackoverflow.com/questions/77914136/dictionary-comparison-conditional-check-in-python
I have two list of dictionaries in the format: list1 = [ {"time": "2024-01-29T18:32:24.000Z", "value": "abc"}, {"time": "2024-01-30T19:47:48.000Z", "value": "def"}, {"time": "2024-01-30T19:24:20.000Z", "value": "ghi"} ] list2 = [ {"time": "2024-01-30T18:34:44.000Z", "value": "xyz"}, {"time": "2024-01-30T19:47:48.000Z",...
dict comprehension has an if clause (at the end), to also filter out elements, like this: output = {x['value']: y['value'] for x, y in itertools.product(list1, list2) if x['time'] == y['time']} Output: {'def': 'pqr', 'ghi': 'jkl'}
6
4
77,911,173
2024-1-31
https://stackoverflow.com/questions/77911173/discrepancy-between-opencv-python-and-c-implementations-of-imreconstruct
I'm implementing MATLAB's imreconstruct in both Python and C++. However, for my test case, the Python implementation matches the MATLAB's output, the C++ one doesn't. This is the Python implementation: def imReconstruct(marker: np.array, mask: np.array) -> np.array: """ Naive implementation of MatLAB's imReconstruct fu...
There are minor, but significant differences between the Python and C++ implementation of the while loop body you presented. Those, coupled with some nuances of how cv::Mat and many OpenCV functions work came together to bite you. The variant of Python code that accurately matches the C++ implementation would look some...
2
3
77,913,154
2024-1-31
https://stackoverflow.com/questions/77913154/vectorizing-power-of-jax-grad
I'm trying to vectorize the following "power-of-grad" function so that it accepts multiple orders: (see here) def grad_pow(f, order, argnum): for i in jnp.arange(order): f = grad(f, argnums=argnum) return f This function produces the following error after applying vmap on the argument order: jax.errors.ConcretizationT...
The fundamental issue with your question is that a vmapped function cannot return a function, it can only return arrays. All other details aside, that precludes any possibility of writing a valid function that does what you intend. There are alternatives: for example, rather than attempting to create a function that wi...
2
2
77,913,473
2024-1-31
https://stackoverflow.com/questions/77913473/why-pandas-value-counts-generates-tuples-as-index
I have the following pandas dataframe: import pandas as pd df = pd.DataFrame({'a': ["Q1", "Q2", "Q1", "P1"]}) That is: a 0 Q1 1 Q2 2 Q1 3 P1 When I count the values with counts = df.value_counts(normalize=True), indexes change to tuple. That is, counts.index is now: MultiIndex([('Q1',), ('P1',), ('Q2',)], names=['a'...
You have a MultiIndex because you're starting from a DataFrame, not a Series. This is actually not very well described in the DataFrame.value_counts documentation: The returned Series will have a MultiIndex with one level per input column but an Index (non-multi) for a single label. What this actually means, is that ...
2
2
77,913,003
2024-1-31
https://stackoverflow.com/questions/77913003/how-does-autocommit-work-with-multiple-queries
I have a psycopg connection with autocommit turned on. Say, I run a query that is a combination of multiple queries, e.g.: query = ";".join([create_table, insert_data, analyze_table]) conn.execute(query) Is this batch executed in a single transaction or multiple transactions? What happens if a query in the middle fail...
From Chain multiple statements within Psycopg2 In SQL chaining refers to the process of linking multiple SQL statements together into a single string, separated by semicolons. This allows you to execute multiple SQL statements at once, without having to execute them individually. For example, you might chain together ...
3
2
77,911,884
2024-1-31
https://stackoverflow.com/questions/77911884/python-azure-function-works-in-local-emulator-but-no-http-triggers-found-when-de
I have 5 Azure Functions I'm developing, and 4 of them deploy and work fine, just having this trouble with one of them. I have the Azure Functions Core Tools installed and Azurite running as a VSCode plugin, and am able to run my function with no errors by calling func start --python --verbose from CLI. I can call the ...
Turns out this was due to a custom environment variable missing from production which was present in development. I worked that one out on my own, I never found a useful error message to point to the fact that that is what was happening. If anyone knows how I'd be supposed to get a meaningful error message out of Azure...
2
3
77,911,172
2024-1-31
https://stackoverflow.com/questions/77911172/if-you-specify-a-background-color-in-pandas-in-python-number-formatting-is-disa
After sorting the data in pandas, I am saving it in Excel. At this time, we are trying to improve readability by changing the format. I specified the number format and background color at the same time, but there is an error where only one of the two is specified. I'm pretty sure this isn't an error, it's just 'I'm not...
I think you can use only pandas styles solution, but if check Styler.format: Styler.format is ignored when using the output format Styler.to_excel, since Excel and Python have inherrently different formatting structures. However, it is possible to use the number-format pseudo CSS attribute to force Excel permissible f...
3
3
77,910,262
2024-1-31
https://stackoverflow.com/questions/77910262/how-do-i-properly-type-hint-a-decorated-getitem-and-setitem
For example: T = TypeVar("T", bound="CustomDict") class CustomDict(dict): def __init__(self) -> None: super().__init__() class dict_operator: def __init__(self, method: Callable[..., Any]) -> None: self.method = method def __get__(self, instance: T, owner: Type[T]) -> Callable[..., Any]: def wrapper(key: Any, *args: An...
The issue isn't the type annotations on __getitem__ and __setitem__. For better or for worse, mypy (currently) doesn't recognise that a __get__ which returns a Callable is, for the majority of cases, a safe override in lieu of a real Callable. The fastest fix is to add a __call__ to your dict_operator class body (mypy ...
3
2
77,888,735
2024-1-26
https://stackoverflow.com/questions/77888735/insert-many-to-many-relationship-objects-using-sqlmodel-when-one-side-of-the-rel
I am trying to insert records in a database using SQLModel where the data looks like the following. A House object, which has a color and many locations. Locations will also be associated with many houses. The input is: [ { "color": "red", "locations": [ {"type": "country", "name": "Netherlands"}, {"type": "municipalit...
I am writing this solution because you mentioned you are open to using SQLAlchemy. As you mentioned, you need association proxy but you also need "Unique Objects". I have adapted it to function with asynchronous queries (instead of synchronous), aligning with my individual preferences, all without altering the logic si...
2
2
77,903,321
2024-1-30
https://stackoverflow.com/questions/77903321/importerror-cannot-import-name-mock-s3-from-moto
import pytest from moto import mock_s3 @pytest.fixture(scope='module') def s3(): with mock_s3(): os.environ['AWS_ACCESS_KEY_ID'] = 'test' os.environ['AWS_SECRET_ACCESS_KEY'] = 'test' os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' s3 = boto3.resource('s3') s3.create_bucket(Bucket='test_bucket') yield s3 This code was w...
Simply replace your import of mock_s3 with from moto import mock_aws and use with mock_aws(): instead. Moto was recently bumped to version 5.0, and you were probably running 4.x before. https://github.com/getmoto/moto/blob/master/CHANGELOG.md If you check the change log, you will see that an important breaking change w...
27
57
77,877,288
2024-1-25
https://stackoverflow.com/questions/77877288/how-to-cache-playwright-python-contexts-for-testing
I am doing some web scraping using playwright-python>=1.41, and have to launch the browser in a headed mode (e.g. launch(headless=False). For CI testing, I would like to somehow cache the headed interactions with Chromium, to enable offline testing: First invocation: uses Chromium to make real-world HTTP transactions ...
It might solve your problem using HAR-file recording: Run the first test while recording a HAR-file Storing the HAR-file as an artifact, in your repo or similar in your CI environment Running test again with recorded HAR-file Here is how to do that with playwright==1.41.1 and pytest-playwright==0.3.3: import pathlib ...
3
3
77,907,578
2024-1-30
https://stackoverflow.com/questions/77907578/how-to-add-a-general-title-with-a-seaborn-objects-plot-facet-plot
I am currently using the seaborn library in Python to create a facetted stacked barplot from a pandas dataframe named averages with columns ['Name', 'Period', 'Value', 'Solver']. Here is the code I use to create the plot I want. p = so.Plot(data = averages, x = 'Period', y = 'Value', color = 'Name').add(so.Bar(), so.St...
You can provide an existing Matplotlib figure or axes for drawing the plot using so.Plot.on. This gives you access to the underlying matplotlib.figure.Figure object to which the suptitle can be added. import matplotlib.pyplot as plt import seaborn.objects as so import pandas as pd df = pd.DataFrame({ "x": [1, 2, 3, 4, ...
2
2
77,871,364
2024-1-24
https://stackoverflow.com/questions/77871364/vectorize-a-convex-hull-and-interpolation-loop-on-a-specific-axis-of-an-ndarray
I'm struggling to find an efficient way to implement this interpolated convex hull data treatment. I have a 2D ndarray, call it arr, with shape (2000000,19), containing floats. I have a 1D ndarray, call it w, with shape (19,), also containing floats. What I achieved (and works perfectly except that it's excruciatingly ...
What about using numba in your code? This gives me a speed improvement on my machine by a factor of: loop_hulls_numba: ~70 (single core) or 70s to 0.973s loop_hulls_numba_parallel: ~350 (multiple cores) or 70s to 0.223s (depends strongly on the number of CPUs) based on a 2'000'000 by 16 array! Speed tests are perform...
2
3
77,878,901
2024-1-25
https://stackoverflow.com/questions/77878901/image-reconstruction-from-predicted-array-padding-same-shows-grid-tiles-in-rec
I have two images, E1 and E3, and I am training a CNN model. In order to train the model, I use E1 as train and E3 as y_train. I extract tiles from these images in order to train the model on tiles. The model, does not have an activation layer, so the output can take any value. So, the predictions for example, preds , ...
Now that I understood this: My problem is not the small black box. This is some bad pixel. My problem is the square tile border lines. This is a stitching problem in my opinion. The border lines, come from your approach to crop the full image into tiles and then stitch them back together later. Due to the padding of ...
3
4
77,900,822
2024-1-29
https://stackoverflow.com/questions/77900822/distribution-plot-with-gradient-fill-in-python
I'm trying to create a density plot with a gradient fill in python like this: I've attempted to do so using this code: plt.figure(figsize=(6, 1)) sns.kdeplot(data=df, x='Overall Rating', fill=True, palette='viridis') ...and sns.kdeplot(data=df, x='Overall Rating', fill=True, cmap='viridis') Neither work, both outputt...
You just need to grab the ax: ax = sns.kdeplot(...) and then execute the inner part of the for loop in @Diziet Asahi's solution with that ax. import matplotlib import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_theme(style='white') iris = sns.load_dataset('iris') ax = sns.kdeplot(data=iris...
3
3
77,904,458
2024-1-30
https://stackoverflow.com/questions/77904458/what-does-the-mode-reduced-in-numpy-linalg-qr-do
In the numpy documentation for the qr factorization (https://numpy.org/doc/stable/reference/generated/numpy.linalg.qr.html), the default mode is 'reduced'. I know the theory of the 'complete' mode and expected it to be the default. What does the mode 'reduced' mean mathematically? I could not find any information about...
Let's summarize the answer given by @stéphane-laurent, so people can find the results more easily: Let , the QR-decomposition is defined as . If , the values of can be dropped, because the last rows of are zero. I.e. we multiply the last columns of with zeros. Therefore, we can just drop these columns to get the s...
3
1
77,910,049
2024-1-30
https://stackoverflow.com/questions/77910049/how-do-i-get-a-mean-inlcuding-nan-values-in-python
Apparently I have the opposite of everyone else's problem... I would like to take the mean of a pandas dataframe, and I would like to have the result return NaN if there are ANY NaNs in the frame. However, it seems like neither np.mean nor np.nanmean do this. Example code: b = pd.DataFrame([[1,2],[math.nan,4]]) print(b...
It can be done using pandas DataFrame.mean() function : b.mean(axis=None,skipna=False) According to the documentation of numpy, the reason that you don't get nan from mean function is that when numpy sees the input of mean() is not multiarray.ndarray, it tries to use mean function from that data type if possible. if t...
3
3
77,909,551
2024-1-30
https://stackoverflow.com/questions/77909551/how-to-merge-two-columns-by-the-intersection-of-the-elements-in-each-col
Imagine I have a dataframe like this: With lists of elements in a single string. data = {'Col1': ["apple, banana, orange", "dog, cat", "python, java, c++"], 'Col2': ["banana, lemon, blueberry", "bird, cat", "R, fortran"] } df = pd.DataFrame(data) df How can I create a Col3 with the intersection of elements in Col1 and...
Using a list comprehension and set intersection: df['Col3'] = [', '.join(set(a.split(', ')) & set(b.split(', '))) for a,b in zip(df['Col1'], df['Col2'])] Output: Col1 Col2 Col3 0 apple, banana, orange banana, lemon, blueberry banana 1 dog, cat bird, cat cat 2 python, java, c++ R, fortran If you want NAs on empty int...
2
2
77,904,890
2024-1-30
https://stackoverflow.com/questions/77904890/how-to-edit-telegram-messages-with-monospace-or-html-text-using-telethon
When utilizing Telethon to send Telegram messages with monospace or HTML text in Python, the parse_mode option (for example parse_mode='markdown' or parse_mode='html') works well during initial message sending. However, when attempting to edit a previously sent message, the parse_mode option does not appear to be avail...
client(EditMessageRequest( is a old, not preferred way of editing a message. You should use client.edit_message method, in your example: client.edit_message(tst_id, first.id, 'Oeps, the code is `1234789`') This way, you don't even need to specify parse_mode it's the same as the message your editing. Full code to tes...
2
2
77,902,366
2024-1-29
https://stackoverflow.com/questions/77902366/plotting-weighted-histograms-with-weighted-kde-kernel-density-estimate
I want to plot two distributions of data as weighted histograms with weighted kernel density estimate (KDE) plots, side by side. The data (length of DNA fragments, split by categorical variable regions) are integers in (0, 1e8) interval. I can plot the default, unweighted, histograms and KDE without a problem, using th...
Histograms and kde plots with a very small sample size often aren't a good indicator for how things behave with more suitable sample sizes. In this case, the default bandwidth seems too wide for this particular dataset. The bandwidth can be scaled via the bw_adjust parameter of the kdeplot. When creating a histplot, pa...
4
2
77,908,410
2024-1-30
https://stackoverflow.com/questions/77908410/how-can-i-drop-columns-with-zero-variance-from-a-numpy-array
So using the following example: import numpy as np X = np.array([[1,10,np.nan,0],[2,10,np.nan,0],[3,10,np.nan,0]]) I can drop the all-NaN or all-0 columns like so: X = X[:,~np.all(np.isnan(X), axis=0)] X = X[:,~np.all(X==0, axis=0)] I would also like to drop the zero variance columns, is there a good way to do so us...
You can. import numpy as np X[:, np.var(X, axis=0) != 0] array([[ 1., nan], [ 2., nan], [ 3., nan]]) This calculates the variance of each column (axis=0) and then returns the ones not equal to 0.
2
2
77,888,944
2024-1-26
https://stackoverflow.com/questions/77888944/how-do-you-pull-aruba-reports-using-api-calls-via-python
I need to login to aruba appliance and get report data using the following api at aruba-airwave endpoint. I have this code so far: import xml.etree.ElementTree as ET # libxml2 and libxslt import requests # HTTP requests import csv import sys # --------------------------------------------------------------------------- ...
The problem you are running into is because your open_session() function returns a dict and a dicts args are typically for accessing a key within the dict. since your session parameter is a dict in this case, if you want to use the elements in session, you need to access them by their key that you defined in open_sessi...
2
2
77,901,985
2024-1-29
https://stackoverflow.com/questions/77901985/how-do-i-add-a-message-back-onto-the-queue-from-a-service-bus-triggered-python-a
I want my Service Bus triggered Python Azure Function to make the message it has retrieved from the queue available on the queue again to be retried. I want this to happen without having to raise an exception in the function. However as per the documentation: In non-C# functions, exceptions in the function results in ...
The short version is - this can't be done from the Python language worker at this time. Currently, only the .NET Function workers (both in-proc and isolated) are able to bind to the ServiceBusMessageActions parameter needed to explicitly complete messages. The only way for other language workers to complete a message i...
3
1
77,906,150
2024-1-30
https://stackoverflow.com/questions/77906150/how-to-modify-a-pass-in-value-as-a-not-nonlocal-variable
I am learning to use a python bytecode preprocessing mechanism. However it complains when processing these lines of code: def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into...
Because there is a nested function(the lambda) which has access to a variable(the x_start) from the outer function(the q_sample())'s namespace. To solve that you can make the x_start local to the lambda by passing it as the default parameter of the lambda like: def q_sample(self, x_start, t, noise=None): noise = defaul...
3
2
77,890,446
2024-1-27
https://stackoverflow.com/questions/77890446/how-to-call-via-google-places-apinew-text-search-id-only-in-python
According to documentation here if I ask, just for place_id, the call should be for free. I tried various versions of call, but all of them either did not work or gave me not just id, but also other basic info such as address, location, rating, etc. Bard told me that it is ok and as I asked just for id, the calls will ...
Finally I found out how to do that properly. Now the response is only the needed field(s): def find_place(query, api_key): # Define the API endpoint url = 'https://places.googleapis.com/v1/places:searchText' # Define the headers headers = { 'Content-Type': 'application/json', 'X-Goog-Api-Key': api_key, # Replace 'API_K...
2
3
77,906,670
2024-1-30
https://stackoverflow.com/questions/77906670/remove-duplicates-in-df-and-convert-into-a-json-obj-in-python
I have a df something like below Name Series ============================= A A1 B B1 A A2 A A1 B B2 I need to convert the series to a list which should be assigned to each Name like a dict or json obj as something like below { "A": ["A1", "A2"], "B": ["B1", "B2"] } So far I have tried using groupby, but it just group...
First drop_duplicates to ensure having , then groupby.agg as list: out = df.drop_duplicates().groupby('Name')['Series'].agg(list).to_dict() Or with unique: out = df.groupby('Name')['Series'].agg(lambda x: x.unique().tolist()).to_dict() Output: {'A': ['A1', 'A2'], 'B': ['B1', 'B2']} If you have other columns, ensure t...
2
1
77,906,193
2024-1-30
https://stackoverflow.com/questions/77906193/the-behavior-of-numpy-fromfunction
I was trying to create different arrays using Numpy's fromfunction(). It was working fine until I faced this issue. I tried to make an array of ones using fromfunction()(I know I can create it using ones() and full()) and here is the issue : array = np.fromfunction(lambda i, j: 1, shape=(2, 2), dtype=float) print(array...
The callable function is passed two arrays, not repeatedly called with two numbers: i=[ [ 0.0, 0.0 ], [ 1.0, 1.0 ] ] j=[ [ 0.0, 1.0 ], [ 0.0, 1.0 ] ] It returns what it is asked to provide ... just ONCE ... to be the ultimate result of np.fromfunction. So an input of 1 returns just 1 whereas an input of i*0+1 returns ...
3
1
77,896,596
2024-1-28
https://stackoverflow.com/questions/77896596/why-arent-the-environment-variables-working-inside-my-django-docker-container
I'm encountering an issue where Django doesn't seem to be reading environment variables when running in a Docker-compose environment. Strangely, the environment variables work fine for PostgreSQL but not for Django. I've tried both the env_file and environment options in my Docker-compose file, and I've also experiment...
I believe I've identified the root cause of the issue in my Dockerfile. The problem lies in the sequence of commands during the Docker image build process. Specifically, I observed that the Dockerfile attempts to run python manage.py collectstatic --noinput and python manage.py migrate before Docker Compose copies the ...
3
2
77,905,231
2024-1-30
https://stackoverflow.com/questions/77905231/calculating-head-to-head-records-in-a-dataframe-based-on-target-values-in-python
I have a Python script that processes tennis match data stored in a Pandas DataFrame (tennis_data_processed). Each row represents a single match from 2010 to 2023, including details about the tournament, match, and the two players involved. There's also a target variable that indicates whether Player1 won (1) or Player...
Code Of course, since it is a dataset with mixed data from multiple players, I created a function to make it possible to use groupby. Of course, there may be better ways to do this. import pandas as pd import numpy as np def get_h2h(df): cond = df['target'].eq(1) players = pd.concat([df['player1_id'], df['player2_id']]...
3
2
77,903,414
2024-1-30
https://stackoverflow.com/questions/77903414/pip-install-mysqlclient-fails-with-call-to-undeclared-function-error
I am currently on macOS 14.3 on Apple silicon. I am trying to install mysqlclient using pip. I already have mysql package installed using brew install mysql pkg-config but my mysqlclient installation is failing due to the errors mentioned below: I am trying to run pip install mysqlclient I am getting the following erro...
You can download the source code,and make some modifications, then build & install. Here are the details: https://github.com/PyMySQL/mysqlclient/issues/688
2
5
77,872,454
2024-1-24
https://stackoverflow.com/questions/77872454/running-python-script-in-pycharm-debugger-with-proxychains
I am working with PyCharm IDE and have encountered an issue where I need to run my Python script within both the PyCharm internal debugger and under proxychains. The reason for using proxychains is that the modules I'm working with do not support working via a SOCKS5 proxy, which is necessary for internet access. Runni...
This can be accomplished by creating a shell script which would run your script through ProxyChains and then using this script as an interpreter in PyCharm. First, create a shell script named python in your project directory (let's say it's located at ~/MyProject): #!/bin/sh proxychains4 /usr/bin/python3 "$@" $@ is us...
2
3
77,889,518
2024-1-26
https://stackoverflow.com/questions/77889518/how-to-fusion-cells-of-a-dataframe-by-summation
I want to transform my dataframe by merging it cells and summing them into other larger cells given the indices of those, as an example, given the indices [0,2] & [2,4] on the X and Y axis and go from the following dataframe : +----+----+----+----+ | 1 | 2 | 3 | 4 | +----+----+----+----+ | 5 | 6 | 7 | 8 | +----+----+--...
Assuming you have homogenous blocks (e.g, 2x2), the most efficient would be to reshape the underlying numpy array and sum: N = 2 out = pd.DataFrame(df.to_numpy() # convert the 2D array to 4D .reshape(len(df)//N, N, -1, N) # sum along dimensions 1 and 3 to go back to 2D .sum((1, 3)) ) If you want non-square blocks (RxC...
2
2
77,902,775
2024-1-29
https://stackoverflow.com/questions/77902775/how-to-forward-generic-argument-types-to-a-callable-in-python
I want to annotate a generic function which takes as arguments another function and its parameters. def forward(func, **kwargs): func(**kwargs) So, if I have a function which takes two integers: def sum_int(a: int, b: int): ... in my editor I want help if I pass the wrong object types: forward(sum_int, 1.5, 2.6) # wa...
You can use typing.ParamSpec to associate the arguments expected by func with the arguments expected by forward, though you do apparently need to use both positional and keyword arguments in the definition of forward: RV = TypeVar('RV') P = ParamSpec('P') def forward(func: Callable[P, RV], *args: P.args, **kwargs: P.kw...
3
3
77,901,277
2024-1-29
https://stackoverflow.com/questions/77901277/building-python-from-source-sqlite3-built-but-not-imported
I have a Rocky Linux 9.0 server and we use modules on it. I'm trying to compile different versions of python from source and to pack them into modules that can be loaded by the user as needed. But, unfortunately, I've been struggling to build them from source. First off, if anybody has a good alternative on how to buil...
You need to define LD_LIBRARY_PATH: # install python cd "../Python-${PYTHON_VERSION}" export LD_LIBRARY_PATH=${INSTALL_BASE_PATH}/lib export PKG_CONFIG_PATH="${INSTALL_BASE_PATH}/lib/pkgconfig" After you've built Python, you need to put in ~/.bashrc : export LD_LIBRARY_PATH=/modules/shared/apps/python/3.11.7/lib
2
2
77,902,595
2024-1-29
https://stackoverflow.com/questions/77902595/polars-groupby-ignore-nans-when-calculating-mean
What is the best way to ignore NaNs when calculating the mean in Polars? As of polars v0.19.19, the default pl.Expr.mean does not ignore NaNs. Example: test_data = pl.DataFrame( { "group": ["A", "A", "B", "B"], "values": [1, np.nan, 2, 3] } ) test_data.group_by("group").agg(pl.col("values").mean()) results in group va...
TLDR. You can simply drop the NaNs before computing the mean. df.group_by("group").agg(pl.col("values").drop_nans().mean()) Output. shape: (2, 2) ┌───────┬────────┐ │ group ┆ values │ │ --- ┆ --- │ │ str ┆ f64 │ ╞═══════╪════════╡ │ A ┆ 1.0 │ │ B ┆ 2.5 │ └───────┴────────┘ Performance comparison against pl.Expr.fill...
4
6
77,877,556
2024-1-25
https://stackoverflow.com/questions/77877556/does-the-order-of-modeling-affect-computational-speed-in-pulp-for-integer-progra
I am currently solving an integer programming problem using Pulp. I am aware that the order of statements in Pulp modeling can affect the outcome of the computations. However, I am curious to know if a specific order of modeling can also lead to improvements in computational speed. Is the practice of finding a particul...
Does the Order of Modeling Affect Computational Speed in Pulp for Integer Programming Problems? Yes. But that's something bad and solvers try hard to decrease this effect. It's also not limited to pulp but applies to discrete-optimization in general. See resource below (focusing on Integer-Programming)! Is the pract...
2
3
77,901,835
2024-1-29
https://stackoverflow.com/questions/77901835/subs-is-not-defined-error-when-trying-to-graph-the-tangent-line-of-the-derivat
I've graphed my original function and I want to graph the tangent line at the point of interest. import numpy as np from sympy import lambdify, symbols, diff, Abs point_of_interest = 8 graphRange = [1,15] # define the variable and the function xsym = symbols('x') # With a chord length of 60, plot the circle diameters o...
At the moment, you are using a complex symbol, xsym: it doesn't have any assumptions, hence it is as general as it gets. Your function contains Abs(xsym): because xsym is complex, its derivative will be quite convoluted: print(Abs(xsym).diff(xsym)) # (re(x)*Derivative(re(x), x) + im(x)*Derivative(im(x), x))*sign(x)/x ...
2
2
77,900,818
2024-1-29
https://stackoverflow.com/questions/77900818/why-does-running-a-plot-in-a-secondary-thread-works-the-first-time-with-warning
For some quick tests (this code will evolve later anyway, so a temporary solution is ok), I need to use Matplotlib in a thread, and not the main thread. Usually we have this warning but it works anyway: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail. Here it is indeed the case. How...
I just noticed that adding plt.close() at the end of the visualization thread solves the problem. Again, this is a temporary solution, since matplotlib is not threadsafe anyway.
2
2
77,900,646
2024-1-29
https://stackoverflow.com/questions/77900646/post-request-error-400-when-trying-to-search-a-website
I am trying to search for movie titles here: https://classindportal.mj.gov.br/consulta-filmes and scrape the resulting page. I know this involves an intermediary step of sending a certain request to the site with my search term, which I currently cannot get to work. When using Google DevTools, the network tab shows me ...
Iv'e inspected the page, and seems like you need to provide a token - which can be obtained by sending a POST request to: https://sso.mj.gov.br/auth/realms/PRD/protocol/openid-connect/token So, get the token, and then send another request to the API with the token to search for your desired movie import requests SEARC...
2
2
77,899,281
2024-1-29
https://stackoverflow.com/questions/77899281/how-to-create-an-file-dialog-box-in-customtkinter
Please review this code where I have used CustomTkinter (alias as "ctk") to create a button. The "command" field contains a function "selectfile". I want to implement this "selectfile" function. button_to_select = ctk.CTkButton(app, text = "Choose file", fg_color = "blue", command = selectfile) button_to_select.pack(pa...
You can use filedialog. Use this function to open the windows file selector from customtkinter import filedialog def selectfile(): filename = filedialog.askopenfilename() print(filename) Edit : Customtkinter got this function
2
4