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,442,172
2023-11-8
https://stackoverflow.com/questions/77442172/ssl-certificate-verify-failed-certificate-verify-failed-unable-to-get-local-is
Working on scripts to connect to AWS and recently started getting this error when I try to install a python module or execute a script I get the following error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129) It appears I have defined the certificate in ...
Try this in the command line: pip install pip-system-certs I've been struggling with the CERTIFICATE_VERIFY_FAILED error as well when using the requests module. I tried installing certifi but that didn't help. The only solution to my problem was to install pip-system-certs. For some reason that allowed requests to acc...
21
43
77,450,814
2023-11-9
https://stackoverflow.com/questions/77450814/how-to-dynamically-route-and-authenticate-upstream-proxies-in-mitmproxy-based-on
Hello Stack Overflow community, I am working on a project using mitmproxy and I'm facing a challenge where I need to dynamically route requests to different upstream proxies based on the URL, along with handling authentication for these proxies. I would appreciate any guidance or suggestions on how to implement this. R...
How about something like the below? This routes each request to an upstream proxy based on the value of a custom header called "X-Upstream-Proxy" or no upstream if the header does not exist (tested with mitmproxy v10.1.3). Regarding authentication with the upstream proxy server, I haven't tested this but I assume an up...
4
3
77,446,605
2023-11-8
https://stackoverflow.com/questions/77446605/running-python-poetry-unit-test-in-github-actions
I have my unittests in a top level tests/ folder for my Python project that uses poetry (link to code). When I run my tests locally, I simply run: poetry run python -m unittest discover -s tests/ Now, I want to run this as CI in Github Actions. I added the following workflow file: name: Tests on: push: branches: [ "ma...
You need to install the dependencies in your action in order for it to work. Adding poetry install after your pip statement is an immediate fix, but there are some further tweaks you should make. Your project needs to be tweaked for pytest to pick up your tests. pytest requires that your files be prefixed with test_, a...
5
3
77,455,300
2023-11-9
https://stackoverflow.com/questions/77455300/streamlit-how-to-add-proper-citation-with-source-content-to-chat-message
I'm currently building a RAG (Retrieval Augmented Generation) Chatbot in Streamlit that queries my own data from a Postgres database and provides it as context for GPT 3.5 to answer questions about my own data. I have got the basics working already (frontend and backend). Now I also want to display the sources used nic...
The simplest way is to serve the PDF via Flask/FastAPI and then use its link in your mention(label=f"{file_name}", url=url_name). The good news here is that most browsers will display the PDF on a specific page when it is provided. For example, if you go to https://arxiv.org/pdf/2401.00107.pdf#page=4, you will automati...
3
1
77,446,083
2023-11-8
https://stackoverflow.com/questions/77446083/pandas-statawriter-writing-an-iterator-for-large-queries-dta-file-corrupt
I'm trying to subclass the pandas StataWriter to allow passing a SQL query with chunksize to avoid running out of memory on very large result sets. I've gotten most of the way there, but am getting an error when I try to open up the file that is written by pandas in STATA: .dta file corrupt: The marker </data> was not ...
After diving deep into the internals of pandas to try to make this work, I decided to move in another direction. I ended up having PostgreSQL output a CSV file, then using the readstat C library's CSV to STATA conversion. This library keeps memory usage low by iterating over the CSV, rather than eagerly loading the ent...
3
2
77,453,594
2023-11-9
https://stackoverflow.com/questions/77453594/parallelising-functions-using-multiprocessing-in-jupyter-notebook
Edit: I updated the question with a trivial repeatable example for ipython, PyCharm and Visual Studio Code. They all fail in a different way. I am running CPU-intensive tasks in Jupyter Notebook. The task is trivial to parallelise and I am already able to do this in a notebook via threads. However, due to Python's GIL,...
You appear to be using macOS, and the problems you are running into are because of the lack of full support for forking a process in macOS. As such, multiprocessing on macOS starts subprocesses using the spawn method. The following paragraphs describes why the problem occurs. The simple solution is to define the functi...
3
4
77,481,604
2023-11-14
https://stackoverflow.com/questions/77481604/importing-polars-in-a-notebook-causes-kernel-to-crash
Importing Polars polars==0.19.7 makes my kernel crash logs : import polars The Kernel crashed while executing code in the the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click here for more info. View Jupyter log for further details. 15:51:25.818...
have you tried https://github.com/pola-rs/polars/issues/12292 Do you want Polars to run on an old CPU (e.g. dating from before 2011), or on an x86-64 build of Python on Apple Silicon under Rosetta? Install pip install polars-lts-cpu. This version of Polars is compiled without AVX target features. "Celeron" and "Pentium...
4
3
77,471,818
2023-11-13
https://stackoverflow.com/questions/77471818/exclude-subplots-without-any-data-and-left-align-the-rest-in-relplot
Related to this question: Use relplot to plot a pandas dataframe leading to error Data for reproducible example is here: import pandas as pd data = {'Index': ['TN10p', 'CSU', 'PRCPTOT', 'SDII', 'CWD', 'R99p', 'R99pTOT', 'TX', 'MIN', 'TN10p', 'CSU', 'PRCPTOT', 'SDII', 'CWD', 'R99p', 'R99pTOT', 'TX', 'MIN', 'TN10p', 'CSU...
Here is another solution that is based on @mwaskom's suggestion in the comments. The basic idea is to create an auxiliary column where for each Type, existing Index values are labeled 0,1,2,... which will act as the column index in the FacetGrid. Then after plotting the relplot, remove all Axes without data and fix the...
3
3
77,483,981
2023-11-14
https://stackoverflow.com/questions/77483981/80-second-delay-using-google-cloud-speechrecognition-with-python-3-9-on-rpi3b
I'm using the PyPi code ( https://pypi.org/project/SpeechRecognition/) cleaned up to use only Google Cloud SpeechRecognition. Google Json Credentials in shell's environment, and working. I've enabled the Cloud Speech-to-Text API, got the Json credentials, and the service calls ARE hitting the API. The Microphone is f...
Problem solved! It was the SSL certs; bouquets to @Dean Van Greune & @VonC My fibre router (Sagemcom) was blocking the Pi's SSL certs, or forcing it to a different port, creating massive delays. I remember solving the same problem for JavaMail TLS a while back, and wanting to take the bat to the router ("Office Space"-...
4
3
77,459,012
2023-11-10
https://stackoverflow.com/questions/77459012/when-mp4-files-encoded-with-h264-are-set-to-slices-n-where-can-i-find-out-how-m
I am doing an experiment on generating thumbnails for web videos. I plan to extract I-frames from the binary stream by simulating the working principle of the decoder, and add the PPS and SPS information of the original video to form the H264 raw information, which is then handed over to ffmpeg to generate images. I ha...
" I plan to extract I-frames" Make sure you go for IDR keyframes (not I-frame keyframes) since IDR bytes can decode into a complete image. Some I-frames can actually need other P/B frames to make a complete image. "I can't find any information about where there is an identifier when multiple NALUs form one frame" H...
2
2
77,481,878
2023-11-14
https://stackoverflow.com/questions/77481878/is-there-any-relation-between-classes-which-use-the-same-type-variable
The typing.TypeVar class allows one to specify reusable type variables. With Python 3.12 / PEP 695, one can define a class A/B with type variable T like this: class A[T]: ... class B[T]: ... Beforehand, with Python 3.11, you would do it like this: from typing import TypeVar, Generic T = TypeVar("T") class A(Generic[T]...
There is no such connection from the typechecker's POV. TypeVar is declared outside of class scope just because it's convenient to do so, it does not imply any relationships between its users. Type variable is bound in the following scopes: Class scope - if a class inherits from Generic (or parametrized Protocol, or o...
4
2
77,484,060
2023-11-14
https://stackoverflow.com/questions/77484060/efficient-iteration-application-of-a-function-in-pandas-polars-or-torch-is-l
Goal: Find an efficient/fastest way to iterate over a table by column and run a function on each column, in python or with a python library. Background: I have been exploring methods to improve the speed of my functions. This is because I have two models/algorithms that I want to run one small, one large (uses torch) a...
With regards to Polars, using .select() and .map_batches() in this type of situation is kind of an "anti-pattern". You are putting all of the data through Polars expression engine, to pass it back out to Python to run your external function, to pass it back into Polars again. You can bypass that and simply pass each Se...
2
2
77,470,588
2023-11-12
https://stackoverflow.com/questions/77470588/backtesting-py-backtest-statistics-only-shows-nans-and-0
I am trying to backtest a momentum strategy using Backtesting.py. I've gathered the data and computed indicator values using pandas_ta. I've defined short and long trading conditions. Now I just need Backtesting.py to run a backtest so that I can determine the performance of my strategy on historical data. I am expecti...
The backtester must use "self.data.foo" and not "self.foo" in order to use values inside any column. Please see the updated notebook with troubleshooting proof.
3
1
77,484,086
2023-11-14
https://stackoverflow.com/questions/77484086/why-is-my-nbody-simulator-not-printing-out-orbital-times-past-3-bodies
Here is my code for simulating planetary orbits. When I have the bodies list set up with only the Earth, Sun and Jupiter, my code works well and prints out a reasonably accurate time for Jupiter and Earth's orbit. However, when I add Saturn into the bodies list, I get a value of 43200 seconds for both Jupiter and Satur...
The reason for this behaviour is that the if distance_to_initial<min_distance condition for the time logging is not triggered correctly in this case. The specific cause of this is the "min_distance", which might get "hopped over" in certain circumstances (e.g. due to increasing step distance), and then only the first m...
2
1
77,483,917
2023-11-14
https://stackoverflow.com/questions/77483917/scopes-confusion-using-smtp-to-send-email-using-my-gmail-account-with-xoauth2
My application has an existing module I use for sending emails that accesses the SMTP server and authorizes using a user (email address) and password. Now I am trying to use Gmail to do the same using my Gmail account, which, for the sake of argument, we say is booboo@gmail.com (it's actually something different). Firs...
Okay first off as this is going to be a single user app. You the developer will be the only one using it, and your just sending emails programticlly lets clear a few things up to begin with. You do not need to verify this app. Yes you will need to just by pass that not a verified application screen as you have done. N...
2
3
77,484,264
2023-11-14
https://stackoverflow.com/questions/77484264/fields-not-initialized-when-post-init-called-using-ruamel-yaml
I have two dataclasses: Msg and Field. Msg has a field fields of type list[Field]. I want to assign something to a field of each Field after they have all been initialized which is more or less their relative index in the fields list. However, when I add a __post_init__(self) method to the Msg dataclass, the fields lis...
By default, object serializers such as YAML and pickle have no idea what to do with the attribute mapping for a user-defined object other than to assign the mapping directly to the object's attribute dictionary as-is. This is why you can define a __setstate__ method for your class, so that ruamel.yaml's object construc...
5
2
77,479,851
2023-11-14
https://stackoverflow.com/questions/77479851/torchaudio-cant-find-ffmpeg
Windows, vscode, Python 3.11.4-64bit import torch import torchaudio print(torch.__version__) print(torchaudio.__version__) print(torchaudio._extension._FFMPEG_INITIALIZED) 2.0.1+cu117 2.0.2+cu117 False and i try torchaudio._extension._init_ffmpeg() Traceback (most recent call last): File "C:\Users\USER\AppData\Local...
You need to install ffmpeg libraries, not CLI. What the error message means is that the dependencies of libtorchaudio_ffmpeg.pyd is not found. The dependencies here mean the libraries that consist FFmpeg, such as libavcodec and libavformat. Usually installing ffmpeg CLI also intall the libraries, but I often see people...
2
2
77,483,278
2023-11-14
https://stackoverflow.com/questions/77483278/adding-more-than-one-empty-row-between-pandas-groups
I want to add several empty rows between each groupby in my pandas dataframe. I know similar questions have been asked in the past but all of the answers I could find rely on the recently discontinued append function. I think I am close but I cannot get it to work. From what I've read, the idea is for the concat functi...
Following your 2nd approach : N = 5 grps = df.groupby("column3", sort=False) out = pd.concat( [ pd.concat([g, pd.DataFrame("", index=range(N), columns=df.columns)]) if i < len(grps)-1 else g for i, (_, g) in enumerate(grps) ] ) Output : print(out) column1 column2 column3 0 a 1 blue 1 b 2 blue 0 1 2 3 4 2 a 1 green 3 b...
2
1
77,475,314
2023-11-13
https://stackoverflow.com/questions/77475314/overlaying-images-on-python
I have these three pictures from a SEM Microscope. One is the actual picture whilst the other two just indicated the presence of specific elements (Aluminium and Silicon) on the sample. I'd like to overlay them using Numpy and matplotlib so that I can then see where exactly the elements are, however not sure how to app...
I would be inclined to paste Si and Al images using a mask so that they only affect the SEM image where they are coloured and not where they are black/grey - else you will tend to reduce the contrast of your base image: from PIL import Image # Load images sei = Image.open('sei.jpg') si = Image.open('si.jpg') al = Image...
5
2
77,479,584
2023-11-14
https://stackoverflow.com/questions/77479584/local-azure-function-customer-packages-not-in-sys-path-this-should-never-happe
I'm encountering a weird warning with azure functions locally. Whenever I func start my function, I get these error messages: Found Python version 3.10.12 (python3). Azure Functions Core Tools Core Tools Version: 4.0.5455 Commit hash: N/A (64-bit) Function Runtime Version: 4.27.5.21554 [2023-11-14T10:02:39.795Z] Custom...
This seems to be the issue with the latest version of Azure function Core tools (4.0.5455), which is published recently (6 days ago) as mentioned in the official doc. I have created a python Azure function to check the same: Python Version: 3.11.5 Azure Functions Core Tools Core Tools Version: 4.0.5348 Commit hash: N/...
7
5
77,479,119
2023-11-14
https://stackoverflow.com/questions/77479119/calculating-groupby-sum-of-values-on-column-based-on-string-in-pandas
data = {'SYMBOL': ['AAAA','AAAA','AAAA','AAAA','AAAA','AAAA','AAAA'] , 'EXPIRYDT': ['26-Oct-23','26-Oct-23','26-Oct-23','26-Oct-23','26-Oct-23','26-Oct-23','26-Oct-23'], 'STRIKE': [480, 500, 525, 425, 450, 480, 500], 'TYPE': ['CE', 'CE', 'CE', 'PE', 'PE', 'PE', 'PE'], 'CONTRACTS': [1, 31, 1, 0, 12, 2, 6], 'OPENINT': [4...
Code groupby & merge I chose to merge in too many ways because your original dataset may have multiple values in the EXPIRYDT column, and it is possible to assign different values depending on the EXPIRYDT. step1. aggregate by groupby tmp = df.groupby(['EXPIRYDT', 'TYPE']).agg(CONT=('CONTRACTS', 'sum'), OI=('OPENINT', ...
2
2
77,477,931
2023-11-14
https://stackoverflow.com/questions/77477931/compute-the-order-of-non-unique-array-elements
I'm looking for an efficient method to compute the "order" of each item in a numpy array, with "order" defined as the number of preceding elements equal to the element. Example: order([4, 2, 3, 2, 6, 4, 4, 6, 2, 4]) [0 0 0 1 0 1 2 1 2 3] Current solution loops in pure Python and is not fast enough: def order(A): cnt =...
Since what you're doing is essentially a Pandas cumcount, and Pandas uses NumPy internally, one idea would be to look at how they implemented cumcount, and do the same thing. If you read the Pandas code for cumcount, it is internally implemented in this way: Sort the array, keeping track of where each element came fro...
2
3
77,455,969
2023-11-9
https://stackoverflow.com/questions/77455969/finding-distinct-sublists-with-target-sums
I am currently working on a task that involves identifying distinct sublists from a given list such that each sublist adds up to one of the specified target numbers. Below is the Python code I've written to address this problem. The primary approach in this recursive function involves iteratively removing elements from...
In this section: for j in range(len(target_array)): # If using the new number would overshoot in that list, stop if (partial_sum[j] + n) > target_array[j]: return # Otherwise, use the new number and continue with the rest of the numbers else: next_total_partial = total_partial next_total_partial[j] = next_total_partia...
3
1
77,473,922
2023-11-13
https://stackoverflow.com/questions/77473922/polars-cast-pl-object-to-pl-string-polars-exceptions-computeerror-cannot-cast
Update: numpy.random.choice is no longer parsed as an Object type. The example produces a String column as expected without any casting needed. I got a pl.LazyFrame with a column of type Object that contains date representations, it also includes missing values (None). In a first step I would like to convert the colum...
When Polars assigns the pl.Object type it essentially means: "I do not understand what this is." By the time you end up with this type, it is generally too late to do anything useful with it. In this particular case, numpy.random.choice is creating a numpy array of dtype=object >>> rng.choice([None, "foo"], 3) array([N...
3
2
77,475,285
2023-11-13
https://stackoverflow.com/questions/77475285/pytorch-crossentropy-loss-getting-error-runtimeerror-boolean-value-of-tensor
I have a classification model, producing predictions for 4 classes in a tensor of shape (256, 1, 4)...256 is the batch size, while the "1" for the second dimension is due to some model internal logic and can be removed: preds.shape torch.Size([256, 1, 4]) The corresponding annotations are one-hot encoded, in a tensor ...
you can use direct call cross_entropy from torch.nn.functional import torch.nn.functional as F F.cross_entropy(predictions_squeezed, targets) or you can rewrite your code, because this's class not a function: loss = nn.CrossEntropyLoss() output = loss(input, target)
3
1
77,475,604
2023-11-13
https://stackoverflow.com/questions/77475604/how-to-separately-normalize-each-distribution-group
Lets say I have a dataframe such as: CATEGORY Value a v1 a v2 a v3 a v4 a v5 b v6 b v7 b v8 Now, if i want to plot this distributions by category, i could use something like: sns.histplot(data,"Value",hue="CATEGORY",stat="percent"). The problem with this is that category "a" represents 5/8 of the sample and "b" is 3/...
As per this answer of the duplicate, use common_norm=False. Also see seaborn histplot and displot output doesn't match. This is not specific to stat='percent'. Other options are 'frequency', 'probability', and 'density'. import seaborn as sns import matplotlib.pyplot as plt tips = sns.load_dataset('tips') fig, axes = p...
2
2
77,471,197
2023-11-13
https://stackoverflow.com/questions/77471197/is-there-a-way-to-add-a-column-of-numpy-random-values-to-a-polars-dataframe-whil
Let's say I have a dataframe that has a column named mean that I want to use as an input to a random number generator. Coming from R, this is relatively easy to do in a pipeline: library(dplyr) tibble(alpha = rnorm(1000), beta = rnorm(1000)) %>% mutate(mean = alpha + beta) %>% bind_cols(random_output = rnorm(n = nrow(....
There are four approaches (that I can think of), 2 of which were mentioned in comments, one that I use, and the last I know it exists but don't personally use it. First (get_column(col) or ['col']) reference Use df.get_column as a parameter of np.random.normal which you can do in a chain if you use pipe so for example ...
3
2
77,475,372
2023-11-13
https://stackoverflow.com/questions/77475372/pandas-subtraction-for-multiindex-pivot-table
I have a following data frame which I converted to pandas pivot table having two indexes "Date" and "Rating. The values are sorted in columns A, B and C. I would like to find a solution which will subtract the values for each column and rating for consecutive days. Say, the change in A from 03/01/2007 to 02/01/2007 fo...
If your dataframe is correctly sorted (or use df.sort_values('Date')), you can use groupby_diff: # Replace ['A'] with ['A', 'B', 'C'] df['A_diff'] = df.groupby('Rating')['A'].diff().fillna(0) Output: >>> df Date Rating A A_diff 0 02/01/2007 M 0.4256 0.0000 1 02/01/2007 MM 0.4358 0.0000 2 02/01/2007 MMM 0.4471 0.0000 3...
2
2
77,474,980
2023-11-13
https://stackoverflow.com/questions/77474980/discord-py-command-execution-truncates-the-json-file-then-applies-the-edits-l
I'm working on a more advanced leveling system. I want a user on any server as long as they are an administrator to be able to change the XP amount. I'm using a value in my server database to achieve that. Every time it makes an edit for that command, I've noticed that it truncates the entire file and applies the edits...
First of all, the code in the if statement on the line 10 is unreachable cause 0 is evaluated as false, so the if statement on the line 9 is only fulfilled when xp is not 0. Here is the code simplified: @levelmds.command(name="set_xp_addition", description="Choose how many XP you want to give to your members. Set 0 or ...
2
1
77,469,040
2023-11-12
https://stackoverflow.com/questions/77469040/python-dataclass-automate-id-incrementation-in-abstract-class
I want to create a unique ID incrementation for my Python subclasses using the abstract method, but I don't know how to separate each subclass's set of ID values. Here is my code: from dataclasses import dataclass, field from itertools import count @dataclass class Basic: identifier: int = field(default_factory=count()...
The dataclasses library does not fit for your use case. Think a data class as a mutable namedtuple with defaults. I recommend implementing concrete classes. However, if you insist, you can do like the following by defining another decorator which augments an input class before calling the dataclasses.dataclass(). (This...
2
1
77,472,952
2023-11-13
https://stackoverflow.com/questions/77472952/python-code-for-calculation-of-very-large-adjacency-matrix-crashes-using-network
I need to calculate the adjacency matrix (in flat format) of a very large graph. Number nodes is 54327 and number edges is 46 million. The input are 46 million edges, so input looks like 1 6 2 7 1 6 3 8 ... meaning node 1 connects to 6, node 2 to 7, with possible repeats. The adjacency matrix in this case would look l...
Maybe I miss something, buy you can use .groupby + .sum here: out = ( df.assign(count_intersections=1) .groupby(["nodeid_x", "nodeid_y"], as_index=False)["count_intersections"] .sum() ) out.sort_values( by=["count_intersections", "nodeid_x", "nodeid_y"], ascending=False, inplace=True ) print(out.head(10)) Prints (runn...
2
1
77,473,952
2023-11-13
https://stackoverflow.com/questions/77473952/using-lambda-function-how-to-iterate-over-the-columns-having-list-values-in-pan
import pandas as pd mydata = {"Key" : [567, 568, 569, 570, 571, 572] , "Sprint" : ["Max1;Max2", "Max2", "DI001 2", "DI001 25", "DAS 100" , "DI001 101"]} df = pd.DataFrame(mydata) df ["sprintlist"]= df["Sprint"].str.split(";") print (df) From this dataframe, I want to extract only the numbers that appears in the last p...
Use Series.explode with Series.str.extractall, converting to numeric and aggregate lists: df["Sprint Number"] = (df["sprintlist"].explode() .str.extractall(r"(\d+)$")[0] .astype(int) .groupby(level=0) .agg(list)) print (df) Key Sprint sprintlist Sprint Number 0 567 Max1;Max2 [Max1, Max2] [1, 2] 1 568 Max2 [Max2] [2] 2 ...
2
1
77,471,991
2023-11-13
https://stackoverflow.com/questions/77471991/how-to-decide-if-streamingresponse-was-closed-in-fastapi-starlette
When looping a generator in StreamingResponse() using FastAPI/starlette https://www.starlette.io/responses/#streamingresponse how can we tell if the connection was somehow disconnected, so a event could be fired and handled somewhere else? Scenario: writing an API with text/event-stream, need to know when client closed...
Consider using request.is_disconnected(). From Starlette's docs: In some cases such as long-polling, or streaming responses you might need to determine if the client has dropped the connection. You can determine this state with disconnected = await request.is_disconnected(). Unfortunately, there seems to be no other ...
2
4
77,472,748
2023-11-13
https://stackoverflow.com/questions/77472748/how-to-add-text-at-barchart-when-y-is-a-list-using-plotly-express
I have the following pandas dataframe import pandas as pd foo = pd.DataFrame({'country': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}, 'unweighted': {0: 18.0, 1: 16.9, 2: 13.3, 3: 11.3, 4: 13.1}, 'weighted_1': {0: 17.7, 1: 15.8, 2: 14.0, 3: 11.2, 4: 12.8}, 'weighted_2': {0: 17.8, 1: 15.8, 2: 14.0, 3: 11.2, 4: 12.8}}) count...
There are automatic annotations in the annotations. import plotly.express as px px.bar( foo, x='country', y=['unweighted', 'weighted_1', 'weighted_2'], text_auto=True, barmode='group', )
2
1
77,468,274
2023-11-12
https://stackoverflow.com/questions/77468274/how-to-make-mutation-which-is-inversion-of-one-of-the-solutions-genes-when-solu
That's what I have so far. As I see from the output, my parameters are not enough to constraint mutation to my needs. Sometimes no one gene is changed, sometimes more than one. import pygad import numpy as np def divider(ga_instance): return np.max(np.sum(ga_instance.population, axis=1)) def on_start(ga_instance): prin...
Inversion mutation inverts the order of subset of the genes. It does not invert the value of the genes from 0 to 1. That is if you have a chromosome like abcd, then inversion mutation inverts the genes to be dcba. To apply a mutation operator that flips the genes from 0 to 1 and from 1 to 0, use this code. It creates a...
2
1
77,470,205
2023-11-12
https://stackoverflow.com/questions/77470205/unexpected-behaviour-when-passing-none-as-a-parameter-value-to-sql-server
Given the following test3 table /****** Object: Table [dbo].[test3] Script Date: 11/12/2023 9:30:17 AM ******/ IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[test3]') AND type in (N'U')) DROP TABLE [dbo].[test3] GO /****** Object: Table [dbo].[test3] Script Date: 11/12/2023 9:30:17 AM ******/...
My gut is that the sp_prepexec statement is creating the positional parameter P1 as varchar(1) for some reason when the statement compares ? to a varchar column and sets P1 to and int when the statement comapres ? to a int column. Yes that is exactly what it does. It has no knowledge of how large to make the paramete...
2
3
77,469,168
2023-11-12
https://stackoverflow.com/questions/77469168/how-to-update-hoover-annotations-when-using-a-slider
My goal. I am using matplotlib slider to plot several series. I want to have hovering labels for each point. Each point corresponds to measurement. So I want to display measurement name to be on these hovering labels. Question. How do I update labels for new series (for slider positions)? If I create new cursor in upda...
I had to (!pip install mplcursors ipympl) before I could run your code. Here is my workaround to get the correct annotations/labels after the slider being updated : sliders = df["slide"].unique() fig, ax = plt.subplots() d = {} for sl in sliders: lbl, x, y = df.loc[ df["slide"].eq(sl), ["Name", "x", "y"]].T.to_numpy() ...
2
1
77,466,563
2023-11-11
https://stackoverflow.com/questions/77466563/how-to-implement-multi-band-pass-filter-with-scipy-signal-butter
Based on the band-pass filter here, I am trying to make a multi-band filter using the code bellow. However, the filtered signal is close to zero which affects the result when the spectrum is plotted. Should the coefficients of the filter of each band be normalized? Can you please someone suggest how I can fix the filte...
Easier and recommended method is what Warren wrote in comments. Just calculate sum of separately band-pass filtered signals. That being said, for someone who wants to create and apply single multi-band filter, he can try to achieve this by combining filters: lowpass (to cut everything above last pass-filter), highpass...
2
4
77,460,705
2023-11-10
https://stackoverflow.com/questions/77460705/how-to-detect-any-key-pressed-without-blocking-execution-in-python
I have an script that checks the position of the mouse every 60 seconds. If the mouse has not moved, it moves it, makes a right click, clicks esc, and sleeps. It is pretty handy to avoid the computer going to sleep. If the mouse has moved, does nothing, goes to sleep and checks again in 60 sec. Now I want to extend it ...
You can use method #3 of https://stackoverflow.com/a/57644349/9997212: Method #3: Using the function on_press_key: import keyboard keyboard.on_press_key("p", lambda _: print("You pressed p")) It needs a callback function. I used _ because the keyboard function returns the keyboard event to that function. Once execute...
2
3
77,460,094
2023-11-10
https://stackoverflow.com/questions/77460094/python-pyqt5-how-to-show-statustip-for-qmenu-and-submenu-actions
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'menu_example_statustip.ui' # # Created by: PyQt5 UI code generator 5.15.9 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import Q...
The issue here is that you're setting the status-tip on the wrong object. You need to set it on the item that represents the menu, rather than the menu itself. This can be done via the menu's associated action, like this: menu.menuAction().setStatusTip('Hello World') It's a little surprising that this doesn't happen a...
2
3
77,446,607
2023-11-8
https://stackoverflow.com/questions/77446607/why-does-cubic-spline-create-not-logical-shape
I am trying to draw an arch-like Cubic Spline using SciPy's Cubic Spline function but at some point is creating a non logical shape between two of the control points. The line in black is what the function is evaluating and in green is what I expect to happen (just as it does between points 4 and 8) This is how I creat...
Cubic splines are prone to overshooting like this due to the constraint of matching 2nd derivatives. Thus small variations in data may cause large variations in the curve itself, including what you seem to have here. There is no way to "fix" this with CubicSpline. What you could do is to clarify your requirements and s...
3
1
77,459,386
2023-11-10
https://stackoverflow.com/questions/77459386/how-to-implement-nested-for-loops-with-branches-efficiently-in-jax
I am wanting to reimplement a function in jax that loops over a 2d array and modifies the output array at an index that is not necessarily the same as the current iterating index based on conditions. Currently I am implementing this via repeated use of jnp.where for the conditions separately, but the function is ~4x sl...
The way you implemented it in JAX is pretty close to what I'd recommend. Yes, it's 3x slower than a custom Numba implementation on CPU, but I think for an operation like this, that is to be expected. The operation you defined applies specific logic to each individual entry of the array – that is precisely the computati...
3
1
77,459,155
2023-11-10
https://stackoverflow.com/questions/77459155/is-there-a-way-to-find-a-carmichael-number-having-n-prime-factors-in-a-given-ran
I'm trying to solve the problem. I need to find a Carmichael number which is a product of seven prime numbers, each between 10^7 and 10^9. Is there any way to do it? I tried to solve this task using Chernick's formula: M(m) = (6m+1)(12m+1)(18m+1)(36m+1)(72m+1)(144m+1)(288*m+1), on condition that all factors are prime a...
Lets first approach this problem by exploring Korselt's Criterion a bit. As you state, n is a Carmichael Number if and only if: n is square-free for all prime divisors p of n, it is true that p − 1 divides n − 1 We achieve (1) by making each of the 7 prime factors distinct. That leaves (2). This means n - 1 is a mult...
2
2
77,459,646
2023-11-10
https://stackoverflow.com/questions/77459646/how-to-pivot-a-pandas-dataframe-and-calculate-product-of-combinations
I have a pandas dataframe that looks like this: import pandas as pd pd.DataFrame({ 'variable': ['gender','gender', 'age_group', 'age_group'], 'category': ['F','M', 'Young', 'Old'], 'value': [0.6, 0.4, 0.7, 0.3], }) variable category value 0 gender F 0.6 1 gender M 0.4 2 age_group Young 0.7 3 age_group Old 0.3 which re...
You can split by variable using groupby and compute the combinations with a cross-merge: from functools import reduce group = df.groupby('variable', sort=False) out = reduce(lambda a,b: pd.merge(a, b, how='cross'), (g.rename(columns={'category': k}) .drop(columns='variable') for k, g in group) ) out['percentage'] = (x:...
2
3
77,458,463
2023-11-10
https://stackoverflow.com/questions/77458463/canot-slice-index-unicode-strings-with-underscores
I have this Unicode string: my_string = "₁ᴀa̲a̲̲" How can index and slice it to make other Unicode strings? If I run print([x for x in my_string]) ['₁', 'ᴀ', 'a', '̲', 'a', '̲', '̲'] when I expected ['₁', 'ᴀ', 'a̲', '̲a̲̲'] this prints my_string[3] '̲' when I expected a̲̲ I tried t define my_string = u"₁ᴀa̲a̲̲" bu...
You could use the \X regex and findall from the regex module: import regex out = regex.findall(r'\X', my_string) Output: ['₁', 'ᴀ', 'a̲', 'a̲̲']
2
3
77,455,738
2023-11-9
https://stackoverflow.com/questions/77455738/finding-the-nouns-in-a-sentence-given-the-context-in-python
How to find the nouns in a sentence regarding the context? I am using the nltk library as follows: text = 'I bought a vintage car.' text = nltk.word_tokenize(text) result = nltk.pos_tag(text) result = [i for i in result if i[1] == 'NN'] #result = [('vintage', 'NN'), ('car', 'NN')] The problem with this script is that ...
Using spacy might solve your task. Try this: import spacy nlp = spacy.load("en_core_web_lg") def analyze(text): doc = nlp(text) for token in doc: print(token.text, token.pos_) analyze("I bought a vintage car.") print() analyze("This old wine is a vintage.") Output I PRON bought VERB a DET vintage ADJ <- correctly iden...
3
2
77,455,334
2023-11-9
https://stackoverflow.com/questions/77455334/how-would-i-implement-idxmax-with-random-tiebreaking-on-a-dataframe
If I have a dataframe like this: id col1 col2 idxmax 1 3.0 4.0 col2 2 5.0 5.0 tiebreak 3 6.0 9.0 col 2 In the case of my example dataframe I'd like to return either col1 or col2 based on whichever name wins the tie. Not including the row ID. At the moment the df.idxmax(axis = 1) function just returns th...
I like @Timeless' approach with random sampling, the issue is that it will always use the same tie-breaker for different rows that have the same combination of equal maxes. An alternative would be to first stack the data: df['idxmax'] = (df .drop(columns=['id', 'idxmax'], errors='ignore') .stack() .sample(frac=1) .grou...
3
1
77,455,158
2023-11-9
https://stackoverflow.com/questions/77455158/how-do-i-label-features-in-an-array-by-their-size
I have a 2D boolean numpy array, mask: array([[False, False, False, True, True, False, False, False], [ True, True, True, False, True, False, False, False], [False, False, True, False, False, True, False, True], [ True, False, False, False, True, True, False, False]]) mask was generated by: np.random.seed(43210) mask ...
You could use numpy.unique: n, idx, cnt = np.unique(label, return_inverse=True, return_counts=True) n2, idx2 = np.unique(cnt, return_inverse=True) out = np.where(mask, n2[idx2][idx].reshape(mask.shape), 0) Output: array([[0, 0, 0, 3, 3, 0, 0, 0], [4, 4, 4, 0, 3, 0, 0, 0], [0, 0, 4, 0, 0, 3, 0, 1], [1, 0, 0, 0, 3, 3, 0...
2
4
77,454,771
2023-11-9
https://stackoverflow.com/questions/77454771/create-an-nxm-matrix-a-to-an-nxmxl-matrix-b-where-bi-j-kronecker-deltaai
Is there a way to convert a NxM matrix A where all values of A are positive integers to an NxMxL matrix B where L = 1 + max(A) B[i,j,k] = {1 if k==A[i,j] and 0 otherwise} using loops I have done the following: B = np.zeros((A.shape[0],A.shape[1],1+np.amax(A))) for i in range(A.shape[0]): for j in range(A.shape[1]):...
A sample A: In [231]: A = np.array([1,0,3,2,2,4]).reshape(2,3) In [232]: A Out[232]: array([[1, 0, 3], [2, 2, 4]]) Your code and B: In [233]: B = np.zeros((A.shape[0],A.shape[1],1+np.amax(A))) ...: for i in range(A.shape[0]): ...: for j in range(A.shape[1]): ...: B[i,j,A[i,j]] = 1 ...: In [234]: B Out[234]: array([[[0...
2
2
77,451,661
2023-11-9
https://stackoverflow.com/questions/77451661/how-can-i-add-the-x-or-y-value-from-a-line-above-to-the-line-that-is-missing
I have a .csv file that has this structure: X310.433,Y9.6 X310.54,Y10 X143.52 X144.77 when there is no "X" or "Y" value in a line, I want to take the value from the line above and copy it to the line after that, that is missing the value. For this example copy the Y10 into the next line, and seperate it with a comma. H...
Without any utility modules you could do this: Let's assume that the file content is: X310.433,Y9.6 Y999 X310.54,Y10 X143.52 X144.77 ...then... lines: list[tuple[str, str]] = [] with open("foo.csv") as foo: for line in map(str.strip, foo): if line: a, *b = line.split(",") if a[0] == "X": if b: lines.append((a, b[0])) ...
3
1
77,448,073
2023-11-8
https://stackoverflow.com/questions/77448073/how-can-i-check-if-all-given-points-in-space-lie-on-the-same-line
I need to implement a function that takes coordinates of any number of points as input data and return True or False depending on whether these points lie on the same line or not. I use Python to solve this problem and now I have the following implementation: def are_colinear(points, tolerance): # variable "points" is ...
Take any one of your coordinates, take it to be your new origin, translating all coordinates accordingly. Now, treat each coordinate as a position vector. Normalize each vector. Now, if any two vectors are parallel, their dot product is 1. In fact, they are the same vector. If two vectors are antiparallel, their dot pr...
2
3
77,447,360
2023-11-8
https://stackoverflow.com/questions/77447360/import-from-typing-within-type-checking-block
Does it make sense to import from typing inside a TYPE_CHECKING block? Is this good/bad or does it even matter? from __future__ import annotations from typing import TYPE_CHECKING, Protocol, runtime_checkable if TYPE_CHECKING: from typing import Any, Callable, Generator
Since typing is a built-in module and you are already importing it to use TYPE_CHECKING anyway, the answer is no, it does not make much sense. Also, it will only work if all of the usages of imported classes are within quotes (for lazy evaluation). Otherwise you will get a NameError when the code runs: from typing impo...
2
2
77,443,428
2023-11-8
https://stackoverflow.com/questions/77443428/how-can-i-check-if-an-instance-of-a-class-exists-in-a-list-in-python-3-according
In Python 3, I have a list (my_array) that contains an instance of the Demo class with a certain attribute set on that instance. In my case, the attribute is value: int = 4. Given an instance of the Demo class, how can I determine if that instance already exists in my_array with the same properties. Here's a MCRE of my...
You need to add an equality function to Demo: def __eq__(self, other): return isinstance(other, Demo) and self.value == other.value P.S, since Python 3.9 you don't need to import List and just use: my_array: list[Demo] = [Demo(4)]
2
2
77,401,730
2023-11-1
https://stackoverflow.com/questions/77401730/modulenotfounderror-no-module-named-imp
I need to install the eb command on windows. I would like to try to deploy an application on AWS using the elasticbeanstalk service, and through this command you can configure and deploy an environment directly with a configuration file. To do this I followed the guide. I first installed python via the site (Python ver...
I encountered this as well. As far as I understand its a deprecation issue. awsebcli will install with Python 3.12 but imp will not. If you type import imp into Python 3.11 you will get the following response DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12;...
24
26
77,418,896
2023-11-3
https://stackoverflow.com/questions/77418896/attributeerror-grouperview-object-has-no-attribute-join
I'm trying to reproduce this answer but getting the following error: AttributeError: 'GrouperView' object has no attribute 'join' --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[283], line 7 4 flights = flights.pivot("month", "year",...
As proposed in the 3.6 API changes, (and repeated in the 3.8 API changes), use Axes.sharey. ax2.sharey(ax1) ax3.sharey(ax1) Since an Axes can only sharey with one other Axes, I'm unaware of an alternative that lets ax1 share with both ax2 and ax3 in one step.
2
4
77,433,576
2023-11-6
https://stackoverflow.com/questions/77433576/how-to-apply-rolling-map-in-python-polars-for-a-function-that-uses-multiple-in
I have a function using Polars Expressions to calculate the standard deviation of the residuals from a linear regression (courtesy of this post). Now I would like to apply this function using a rolling window over a dataframe. My approaches below fail because I don't know how to pass two columns as arguments to the fun...
One thing to note about in rolling_map is that it is used for a custom function. While your expression is defined with a function, it isn't what they mean. What they mean is a python function which takes in values and outputs a value. This is also hinted at by the name having map which coincides to map_elements and map...
4
4
77,416,106
2023-11-3
https://stackoverflow.com/questions/77416106/how-do-i-wrap-a-byte-string-in-a-bytesio-object-using-python
I'm writing a script with the Pandas library that involves reading the contents of an excel file. The line currently looks like this: test = pd.read_excel(archive_contents['spreadsheet.xlsx']) The script works as intended with no issues, but I get a future warning depicting the following: FutureWarning: Passing bytes ...
As user459827 has commented, this will do the trick: from io import BytesIO test = pd.read_excel(BytesIO(archive_contents['spreadsheet.xlsx']))
3
3
77,404,746
2023-11-1
https://stackoverflow.com/questions/77404746/cors-policy-error-on-second-render-of-react-app-from-fastapi-backend
I am working on a React frontend to chart some data from a fastapi backend. I am using a couple of dropdown components to change the month and year for the requested data. With the initial render the fetch request works fine and returns the data and the charts display. Once I change the dropdowns, I get the following C...
CORS headers are not added when the request ends in an error, that is, when a response is returned with a status code such as 4xx or 5xx. As shown in the screenshot you provided, when calling the /dashboard_data API endpoint for the third time, the server responds with 500 Internal Server Error response code, indicatin...
4
5
77,410,600
2023-11-2
https://stackoverflow.com/questions/77410600/is-opentelemetry-in-python-safe-to-use-with-async
I want to use OpenTelemetry with an Async application, and I want to be 101% sure that it will work as intended. Specifically, I'm worried about what happens with the current_span when we switch back and forth between asynchronous functions. I have this fear that if I rely on tracer.start_as_current_span to set the spa...
OpenTelemetry for Python supports asynchronous code. Went through the code for version 1.24.0/0.45b0 of opentelemetry-python. The code contains abstract context class _RuntimeContext. _RuntimeContext has single implementation ContextVarsRuntimeContext that utilizes contextvars. ContextVarsRuntimeContext is used as a de...
5
3
77,406,316
2023-11-2
https://stackoverflow.com/questions/77406316/how-do-you-safely-pass-values-to-sqlite-pragma-statements-in-python
I'm currently writing an application in Python that stores its data in a SQLite database. I want the database file to be stored encrypted on disk, and I found the most common solution for doing this to be SQLCipher. I added sqlcipher3 to my project to provide the DB-API, and got started. With SQLCipher, the database en...
According to the accepted answer to “Python sqlite3 string variable in execute”, there are limitations on where DB-API substitutions can be used: Parameter markers can be used only for expressions, i.e., values. You cannot use them for identifiers like table and column names. Seeing this, I figured that arguments to ...
3
2
77,425,682
2023-11-5
https://stackoverflow.com/questions/77425682/what-is-the-point-of-usedforsecurity
The parameter usedforsecurity was added to every hash function in hashlib in Python 3.9. Changed in version 3.9: All hashlib constructors take a keyword-only argument usedforsecurity with default value True. A false value allows the use of insecure and blocked hashing algorithms in restricted environments. False indic...
TL;DR For almost everyone, ignore the flag, it has no effect whatsoever. The full story involves FIPS and how that gets exposed as a python API. For our purposes, FIPS is a standard that supposedly specifies a safe set of practices. In certain scenarios (e.g. writing software for US government agencies), you are force...
6
8
77,433,096
2023-11-6
https://stackoverflow.com/questions/77433096/notimplementederror-loading-a-dataset-cached-in-a-localfilesystem-is-not-suppor
I try to load a dataset using the datasets python module in my local Python Notebook. I am running a Python 3.10.13 kernel as I do for my virtual environment. I cannot load the datasets I am following from a tutorial. Here's the error: --------------------------------------------------------------------------- NotImple...
Try doing: pip install -U datasets This error stems from a breaking change in fsspec. It has been fixed in the latest datasets release (2.14.6). Updating the installation with pip install -U datasets should fix the issue. git link : https://github.com/huggingface/datasets/issues/6352 If you are using fsspec, then d...
24
58
77,418,738
2023-11-3
https://stackoverflow.com/questions/77418738/python-pystray-update-menu-use-variable-text-for-item
I want to change the text for an item variably. to do this, i tried to update the menu using update_menu(). unfortunately, this didn't work and i couldn't find anything more detailed in the pystray documentation. I hope you can help me. thank you. from pystray import Icon as icon, Menu as menu, MenuItem as item import ...
I've got to a similar problem earlier, I wanted to update the submenu while running. I made a version for what you wanted to adjust: def test(icon, this_item): global adapter adapter = 'after' global menu_items menu_items.pop() # remove last element, here containing 'adapter' # add new item with updated adapter value m...
3
6
77,433,139
2023-11-6
https://stackoverflow.com/questions/77433139/mask-r-cnn-load-weights-function-does-not-work-in-google-colab-with-tensorflow-c
I want to train a Mask R-CNN model in Google Colab using transfer learning. For that, I'm utilizing the coco.h5 dataset. I installed Mask R-CNN with !pip install mrcnn-colab. I noticed that the following code does not load the weights: model.load_weights(COCO_MODEL_PATH, by_name=True). The names are right and by_name=F...
You can use this implementation which is built on top of the original Mask R-CNN repo to support TF2. This repository allows to train and test the Mask R-CNN model with TensorFlow 2.14.0, and Python 3.10.12. You can also use it on Google Colab (current colab environment also uses Python 3.10.12 and TF 2.14.0) and it's ...
2
4
77,434,087
2023-11-6
https://stackoverflow.com/questions/77434087/execute-gcp-cloud-run-job-with-environment-variable-override-using-python-client
I am trying to trigger a GCP Cloud Run job from a python script following the run_job documentation (https://cloud.google.com/python/docs/reference/run/latest/google.cloud.run_v2.services.jobs.JobsClient#google_cloud_run_v2_services_jobs_JobsClient_run_job). However, I'm getting errors that I haven't been able to debug...
We recently started using the Cloud Run Jobs service in my workplace and I found myself needing to carry out the same task. A dictionary with the Override Specification is required. I've amended the Initialize request block as per your example. override_spec = { 'container_overrides': [ { 'env': [ {'name': 'VAR_1', 'va...
2
12
77,425,962
2023-11-5
https://stackoverflow.com/questions/77425962/how-to-compose-functions-through-purely-using-pythons-standard-library
Python's standard library is vast, and my intuition tells that there must be a way in it to accomplish this, but I just can't figure it out. This is purely for curiosity and learning purposes: I have two simple functions: def increment(x): return x + 1 def double(x): return x * 2 and I want to compose them into a new ...
As mentioned in the other answer of mine I don't agree that the test suite discovered by @AKX should be considered as part of the standard library per the OP's rules. As it turns out, while researching for an existing function to modify for my other answer, I found that there is this helper function _int_to_enum in the...
7
3
77,410,704
2023-11-2
https://stackoverflow.com/questions/77410704/pylance-not-working-autocomplete-for-dynamically-instantiated-classes
from typing import Literal, overload, TypeVar, Generic, Type import enum import abc import typing class Version(enum.Enum): Version1 = 1 Version2 = 2 Version3 = 3 import abc from typing import Type class Machine1BaseConfig: @abc.abstractmethod def __init__(self, *args, **kwargs) -> None: pass class Machine1Config_1(Mac...
Looking at the factory, there is no way to tell which of Type[typing.Union[Machine2Config_1, Machine2Config_2]] will be returned when calling Machine1FacadeConfig.get_version(self.version) in isolation. As the facade and the factory are extremely coupled anyways, I would suggest combining these into a single utility, w...
3
2
77,413,013
2023-11-2
https://stackoverflow.com/questions/77413013/how-to-staple-apple-notarization-tickets-manually-e-g-under-linux
Recently (as of 2023-11-01) Apple has changed their notarization process. I took the opportunity to drop Apple's own tools for this process (notarytool) and switch to a Python-based solution using their documented Web API for notarization This works great and has the additional bonus, that I can now notarize macOS apps...
How can I extract the code directory hash (CDhash) from a macOS application, without using macOS specific tools? The CDhash of an app is the CDhash of the main executable in Contents/MacOS as identified in Contents/Info.plist Each hash is stored at the end of the binary segment for each architecture in an XML stateme...
4
1
77,438,553
2023-11-7
https://stackoverflow.com/questions/77438553/pydantic-validation-error-input-should-be-a-valid-dictionary-or-instance
I am trying to validate the latitude and longitude: from pydantic import BaseModel, Field from pydantic.dataclasses import dataclass @dataclass(frozen=True) class Location(BaseModel): longitude: float = Field(None, ge=-180, le=180) latitude: float = Field(None, ge=-90, le=90) Location(longitude=1.0, latitude=1.0) When...
I guess you're using dataclass from pydantic.dataclasses. In that case, don't inherit from BaseModel from pydantic import Field from pydantic.dataclasses import dataclass @dataclass(frozen=True) class Location: longitude: float = Field(None, ge=-180, le=180) latitude: float = Field(None, ge=-90, le=90) Location(longitu...
3
4
77,433,205
2023-11-6
https://stackoverflow.com/questions/77433205/how-to-install-mysqlclient-in-a-python3-slim-docker-image-without-bloating-the
I'm using python:3-slim Docker image and want to use the mysqlclient package from Pypi but getting the following error from RUN pip install mysqlclient command: ... Collecting mysqlclient Downloading mysqlclient-2.2.0.tar.gz (89 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 89.5/89.5 kB 2.5 MB/s eta 0:00:00 Installing b...
Use a Multi-Stage build Dockerfile: FROM python:3.12 AS python-build RUN pip install mysqlclient FROM python:3.12-slim COPY --from=python-build /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages RUN apt-get update && apt-get install -y libmariadb3 This first 'stage' uses a full-fat python:...
4
6
77,436,620
2023-11-7
https://stackoverflow.com/questions/77436620/different-behaviour-of-re-search-function-in-python
I have come across a different behaviour of search function in regex which made me think that there is an implicit \b anchor in the pattern. Is this the case? text = "bowl" print(re.search(r"b|bowl", text)) # first alteration in this pattern works print(re.search(r"o|bowl", text)) # but first alteration won't work here...
I'm not a regex expert, so I'll use simple words to describe what happens internally. search works from left to right, and the | patterns too. Also search is different from match and moves forward to try to find the pattern across the string, not just at start. Take this: re.search(r"o|bowl", text) So if o pattern is ...
4
2
77,436,994
2023-11-7
https://stackoverflow.com/questions/77436994/what-is-the-effect-of-loc-in-a-dataframe
If I have this minimal reproducible example import pandas as pd df = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] df.index = index_ print(df) # Option 1 result = df[['A', 'D']] print(result) # Opt...
The difference is that df[['A', 'D']] is a weak reference to df (here on pandas 2.1.2). result1 = df[['A', 'D']] print(result1._is_copy) #<weakref at 0x7f34261b69d0; to 'DataFrame' at 0x7f34260e9590> result2 = df.loc[:, ['A', 'D']] print(result2._is_copy) # None In both cases, this is not a view: print(result1._is_vie...
2
7
77,435,651
2023-11-7
https://stackoverflow.com/questions/77435651/linear-programming-optimization-using-linprog
I am trying to solve this problem using linprog from scipy.optimize. A salad is any combination of the following ingredients: (1) tomato, (2) lettuce, (3) spinach, (4) carrot, and (5) oil. Each salad must contain: (A) at least 15 grams of protein, (B) at least 2 and at most 6 grams of fat, (C) at least 4 grams of carbo...
As you have few variables and constraints, we can write your constraints like this: # (A) protein, at least (*) 15 <= 0.85*x[tomato] + 1.62*x[lettuce] + 12.78*x[spinach] + 8.39*x[carrot] + 0.0*x[oil] # (B1) fat, at least (*) 2 <= 0.33*x[tomato] + 0.2*x[lettuce] + 1.58*x[spinach] + 1.39*x[carrot] + 100.0*x[oil] # (B2) f...
2
4
77,428,847
2023-11-6
https://stackoverflow.com/questions/77428847/is-there-a-way-to-use-a-conditional-kernel-in-opencv-that-only-changes-pixels-on
I want to use a kernel that performs a pixel operation based on a conditional expression. Let's say I have this grayscale image (6x6 resolution): and I use a 3x3 pixel kernel, how would I change the value of the centre kernel pixel (centre) IF AND ONLY IF the centre pixel is the local minimum or maximum within the 3x3...
You asked: [...] how would I change the value of the centre kernel pixel (centre) IF AND ONLY IF the centre pixel is the local minimum or maximum within the 3x3 kernel? For example, say I wanted to set the centre kernel pixel to the average value of the surrounding 8 pixels [...] I'll demonstrate a few things first. ...
2
3
77,434,196
2023-11-6
https://stackoverflow.com/questions/77434196/is-there-a-way-to-return-all-rows-where-only-one-column-is-not-null
I have a dataframe that I'd like to break up into logical sub-dataframes. The most logical way to do this, given how the data is, is to select rows from the original dataframe where only one of the columns is not null (i.e. df.column.notnull() is True). Is there a shorthand for this or do I need to check each other col...
Create a mask using .sum(axis=1) on the result of df.notnull() and checking if equal to 1: df[df.notnull().sum(axis=1).eq(1)] With some sample data: import numpy as np import pandas as pd df = pd.DataFrame( {'A': [1, np.nan, np.nan, np.nan], 'B': [np.nan, 2, np.nan, np.nan], 'C': [np.nan, np.nan, 3, np.nan], 'D': [np....
2
4
77,412,601
2023-11-2
https://stackoverflow.com/questions/77412601/how-to-configure-qdrant-data-persistence-and-reload
I'm trying to build an app with streamlit that uses Qdrant python client. to run the qdrant, im just using: docker run -p 6333:6333 qdrant/qdrant I have wrapped the client in something like this: class Vector_DB: def __init__(self) -> None: self.collection_name = "__TEST__" self.client = QdrantClient("localhost", port...
You mention using the Qdrant server, to which you'd like to connect with the Python client. There are two problems in your above question, let me go over both of them: 1. Persist data in Qdrant server: A Qdrant server stores its data inside the Docker container. Docker containers are immutable however, which means that...
2
4
77,432,905
2023-11-6
https://stackoverflow.com/questions/77432905/why-does-dataclass-favour-repr-over-str
Given the following code, I think output (A) makes sense since __str__ takes precedence over __repr__ however I am a bit confused about output (B) why does it favour __repr__ over __str__ and is there a way to make the class use the __str__ rather than the __repr__ of Foo without defining __str__ for Bar? @dataclass() ...
It is normal for the repr to be preferred to str when rendering a representation within a container of some sort, e.g.: >>> print(f) Foo::__str__ >>> print([f]) [Foo::__repr__] It is necessary for repr to be unambiguous, for example to see the difference between numbers and strings here: >>> from dataclasses import da...
2
4
77,432,108
2023-11-6
https://stackoverflow.com/questions/77432108/how-does-memory-management-in-python-work-for-integers
The result in the two following examples is different: EXAMPLE 1 a = 845 b = int("8"+"4"+"5") print(a == b) # True print(a is b) # False EXAMPLE 2 a = 845 b = 840+5 print(a == b) # True print(a is b) # True How can it be explained? Why in the first case the same integer is kept in two different memory slots in the pi...
Another question provides good context on this issue, but this is a bit different to the cases mentioned there (but it comes down to the same thing in the end). Even though only integers between -5 and 256 are cached and return True for is checks, the same happens for hardcoded integers, since they are compiled as cons...
3
3
77,431,520
2023-11-6
https://stackoverflow.com/questions/77431520/how-do-i-read-the-next-line-after-finding-a-variable-in-a-text-file-using-python
I am trying to make an app for electric vehicle drivers and i'm using a text file to store the data the way it works is i have the name of the electric vehicle and the the line under the name contains the miles it can get per 1%, i've got it so it can find the specific car but i can't find the range of the vehicle usin...
You can do the following: target_car = "Kia Niro EV" with open("temp.txt") as f: for line in f: if line.rstrip() == target_car: range_ = float(next(f)) break else: range_ = "Not Found" print(f"range is: {range_}") f is a consumable iterator. You iterate over it until you find your car, then the next item in that itera...
3
1
77,429,177
2023-11-6
https://stackoverflow.com/questions/77429177/pandas-group-or-pivot-table-by-a-column-horizonally-rather-than-vertically
I have got data that looks like this data = [['01/01/2000', 'aaa', 101, 102], ['01/02/2000', 'aaa', 201, 202], ['01/01/2000', 'bbb', 301, 302], ['01/02/2000', 'bbb', 401, 402],] df = pd.DataFrame(data, columns=['date', 'id', 'val1', 'val2']) df date id val1 val2 01/01/2000 aaa 101 102 01/02/2000 aaa 201 202 01/01/2000 ...
Add DataFrame.swaplevel with DataFrame.sort_index: out = (df.set_index(['date', 'id']) .unstack(level=1) .swaplevel(0,1, axis=1) .sort_index(axis=1)) print (out ) id aaa bbb val1 val2 val1 val2 date 01/01/2000 101 102 301 302 01/02/2000 201 202 401 402 Or use DataFrame.melt with DataFrame.pivot and DataFrame.sort_inde...
2
2
77,428,302
2023-11-6
https://stackoverflow.com/questions/77428302/is-there-any-cool-way-to-express-if-x-is-none-x-self-x-in-python-class
I'm just studying python OOP, and truly confused when to use self and not. especially when I want to make a method that defaultly get object instance input and also wanna make it work as a normal method that can get the input of custom parameters, I get somewhat bothersome to type if x is None: x = self.x for all the p...
A conditional expression is readable, fast, and intuitive- x = self.x if x is None else x Re: Is there any good way to use instance variables as default value of function parameter?? Regarding the setting of self.result- This should be avoided unless you need to access it as an instance variable later. As such you c...
2
1
77,427,048
2023-11-5
https://stackoverflow.com/questions/77427048/lazily-load-files-at-random-from-large-directory
I have about a million files in my directory, and their number is likely to grow. For machine learning, I would like to randomly sample from those files without replacement. How can I do this very quickly? os.listdir(path) is too slow for me.
I have about a million files in my directory ... os.listdir(path) is too slow for me. This is the core of your problem, and it's solved by a technique I've generally heard referred to as bucketing your files, though a web search for this doesn't seem particularly helpful. Bucketing is generally used by programs that ...
2
2
77,422,087
2023-11-4
https://stackoverflow.com/questions/77422087/error-when-trying-to-find-2nd-maximum-value-in-a-list
I am trying to write code for finding the second maximum value of a list. I tried it like this: arr = map(int, input().split()) lista = list(arr) max_value = lista[0] run = lista[0] for i in lista: if max_value < i: max_value = i for j in lista: if run < j and run < max_value: run = j print(run) And the second maximum...
The issue TLDR run = lista[0] ... if run < j and run < max_value: Should be v run = min(lista) ... v if run < j and j < max_value: How to find the Issue 1. Make the code simpler Comprehension instead of map - list constructor succession We can reduce the boilerplate of firsts lines by using a comprehension instead ...
4
7
77,425,573
2023-11-5
https://stackoverflow.com/questions/77425573/how-can-i-randomize-existing-byte-array
I create an array of bytes. array = bytearray(random.randint(1, 8192)) # Now, how can I randomize array's elements? Now how can I randomize each elements of the array? Just like, // with Java var array = new byte[ThreadLocalRandom.current().nextInt(1, 8192)]; ThreadLocalRandom.current().nextBytes(array);
def randomize(array): array[:] = random.randbytes(len(array)) Behaves like your answer's but is ~100 times faster. Time with an average-length array (4096 bytes): 23.0 ± 0.3 μs randomize_Kelly 2191.5 ± 11.6 μs randomize_Jin Python: 3.11.4 (main, Sep 9 2023, 15:09:21) [GCC 13.2.1 20230801] Attempt This Online!
2
2
77,418,891
2023-11-3
https://stackoverflow.com/questions/77418891/is-there-a-way-to-disable-a-nested-context-manager
I have a question on how to disable a nested context manager. I have an inside context manager: class cast: def __init__(self, enabled: bool = True, dtype) -> None: self.prev = False self.enabled = enabled self.dtype = dtype def __enter__(self) -> None: self.prev = is_cast_enabled() set_cast_enabled(self.enabled) set_c...
The no_cast context manager can redefine cast so it doesn't do anything while in this context. class no_cast: def __enter__(self): global cast self.cast = cast cast = no_cast.do_nothing return self def __exit__(self, *args): global cast cast = self.cast return True def do_nothing(*args): pass
2
3
77,424,888
2023-11-5
https://stackoverflow.com/questions/77424888/matplotlib-edgecolors-coloring-0-0-valued-data-points
I'm plotting a 3d bar plot for an array using matplotlib. I need to add an edgecolor to the bars. However, the edgecolor is coloring the 0.0 values data points in black. Is there a way to not color these data points? I'm trying to do edgecolors=none through a loop when values are 0.0. However this doesn't seem to help....
I feel that you've already tried the correct solution: not plot the unwanted bars. You need a mask. Btw, never ever compare floats with ==. mask = ~np.isclose(dz, 0.0) Then, plot data filtered by this mask ax.bar3d(xpos[mask],ypos[mask],zpos[mask], dx[mask], dy[mask],dz[mask],color=cs[:mask.sum()],zsort='average',alph...
3
2
77,424,774
2023-11-5
https://stackoverflow.com/questions/77424774/finding-the-last-row-that-meets-conditions-of-a-mask
This is my dataframe: df = pd.DataFrame({'a': [20, 21, 333, 444], 'b': [20, 20, 20, 20]}) I want to create column c by using this mask: mask = (df.a >= df.b) And I want to get the last row that meets this condition and create column c. The output that I want looks like this: a b c 0 20 20 NaN 1 21 20 NaN 2 333 20 Na...
For a mask to flag the last value satisfying a condition, use duplicated() by keeping last. We know that mask consists of at most 2 values (True/False). If we can create another mask that flags the last occurrences these values as True, then we can chain it with mask itself for the desired mask. This is accomplished by...
7
5
77,424,685
2023-11-5
https://stackoverflow.com/questions/77424685/how-do-i-change-a-variable-inside-a-function-ever-iteration-of-a-loop
I'm trying to have a boolean variable flip (True becomes False, False becomes True), and this variable is inside of a function. However, I have an issue where I either have to assign the variable inside the function (thus having the variable reset to what I assigned it to inside the function), or don't do that, which c...
python does not have pass by reference. it has mutable and immutable variables. so if your variable is mutable you need to return the value each time and reset it like this: def click(alternate): alternate = not alternate #flipping the variable return alternate and: alternate = True while True: alternate=click(alterna...
3
3
77,424,193
2023-11-4
https://stackoverflow.com/questions/77424193/output-of-function-using-np-reciprocal-changes-based-on-print-or-further-unrela
Whilst computing SVD I encountered strange behaviour in relation to np.reciprocal. Under certain conditions (i.e. additional steps on an unrelated variable or printing a variable) the output changes for some reason. The following is a simplified version of the code. import numpy as np from numpy.linalg import eig from ...
The line S_inv = np.reciprocal(S, where=(S != 0)) creates an uninitialized array and fills the entries where the condition S != 0 is True with reciprocals of the corresponding elements of S. All other elements are left unchanged, so they may be zeroes, but may also have some random values. In order to fix this, use t...
2
2
77,423,535
2023-11-4
https://stackoverflow.com/questions/77423535/fill-pandas-column-forward-iteratively-but-without-using-iteration
I have a pandas data frame with a column where a condition is met based on other elements in the data frame (not shown). Additionally, I have a column that extends the validness one row further with the following rule: If a valid row is followed directly by ExtendsValid, that row is also valid, even if the underlying v...
IIUC, you want to ffill the 1s only if there is an uninterrupted series of 1s starting on Valid and eventually continuing on ExtendsValid. For this you can use a groupby.cummin: df['FinalValid'] = ( (df['Valid']|df['ExtendsValid']) .groupby(df['Valid'].cumsum()) .cummin() ) Output: NB. I slightly modified the input on...
3
1
77,422,410
2023-11-4
https://stackoverflow.com/questions/77422410/manipulate-the-element-before-finding-sum-of-higher-elements-in-the-row
I have asked about finding sum of higher elements in the row/column and got really good answer. However this approach does not allow me to manipulate current element. My input dataframe is something like this: array([[-1, 7, -2, 1, 4], [ 6, 3, -3, 5, 1]]) Basically, I would like to have a output matrix which shows me ...
A possible solution, based on numba and numba prange to parallelize the for loop: from numba import jit, prange, njit, set_num_threads import numpy as np @njit(parallel=True) def get_horizontal(a): z = np.zeros((a.shape[0], a.shape[1]), dtype=np.int32) for i in prange(a.shape[0]): for j in range(a.shape[1]): aux = a[i,...
3
1
77,422,076
2023-11-4
https://stackoverflow.com/questions/77422076/putting-contributions-of-continuous-values-in-a-discrete-2d-grid-based-on-dista
I have a numpy array containing coordinates of points (in 3D, but I am have started off by trying the method in 1D and 2D first) that I would like to fit in a discrete grid. However, I do not want to just move the points to the grid pixel which they are closest to, but rather put on each pixel a weighted value which de...
So, if I get it correctly, you did "by hand" all the interpolation job (there are probably some code to do that somewhere, but can't think of any right now), and use bincount just to increase the output array (because output_array[indices] += weight wouldn't have worked, indeed, if indices contain repetitions) Then, yo...
3
1
77,422,457
2023-11-4
https://stackoverflow.com/questions/77422457/what-is-the-reason-that-child-class-does-not-inherit-doc-property-method
I am a bit confused about the difference in behavior between __doc__ and other methods: # python 3.10.13 class Parent: def __init__(self, doc): self._doc = doc def __doc__(self): return self._doc def __other__(self): return self._doc class Child(Parent): pass >>> print(Parent("test").__doc__()) test >>> print(Child("te...
As a first approximation1, when you write obj.a Python attempts to lookup a by checking whether obj has an attributed named a, then checking whether obj's class (obj.__class__) has an attribute a, then recursively checking each parent class (obj.__class__.__mro__) for an attribute a. If at any point, an attribute na...
3
4
77,415,312
2023-11-3
https://stackoverflow.com/questions/77415312/qcombobox-list-popup-display-in-fusion-style
I am using PyQt5. I want to know how to make my QComboBox open with ±10 items instead of the full screen. This only happens with the fusion style applied. Is there any way I can make this behave with a small drop down instead? I have tried to use setMaxVisibleItems(5), but it didn't make a difference. Here is what it i...
As pointed out in QTBUG-89037, there's an undocumented stylesheet property that can be used to change the behaviour of the popup: setStyleSheet('QComboBox {combobox-popup: 0}') A value of 0 will show the normal scrollable list-view with a maximum number of visible items, whilst a value of 1 shows the humungous menu. H...
2
2
77,421,030
2023-11-4
https://stackoverflow.com/questions/77421030/how-to-generate-the-uml-diagram-from-the-python-code
I have this code repo I created manual UML which look like this: I am trying to auto generate the UML via pyreverse: pyreverse -o png -p ShoppingCart ./mainService.py Format png is not supported natively. Pyreverse will try to generate it using Graphviz... Unfortunately, it gives me blank diagram. What can I do to g...
In short Assuming the installation of pyreverse and graphviz is correct, all you need to do is to package your project adding some emplty __init__py files in each folder. Alternatively, you'd hjhave to add all the modules manually in the command line. More details - step by step About the error message Assuming everyth...
4
7
77,420,330
2023-11-4
https://stackoverflow.com/questions/77420330/how-to-retain-sqlalchemy-model-after-adding-row-number
I'm try to filter rows in some method so I need the output model to be of the same type as input model to the sqlAlchemy query. I followed this answer https://stackoverflow.com/a/38160409/1374078 . However would it be possible to get the original model, so that I can access the model's methods by name? e.g. row.foo_fie...
Assuming that your code looks something like this*: with orm.Session(engine) as s: row_number_column = ( sa.func.row_number() .over(partition_by=User.name, order_by=sa.desc(User.id)) .label('row_number') ) q = sa.select(User) q = q.add_columns(row_number_column) for row in s.execute(q): print(row) Then the results loo...
2
2
77,420,886
2023-11-4
https://stackoverflow.com/questions/77420886/end-of-first-sequence-of-nans-in-numpy-array
I have a two dimensional numpy array where some rows may have nans. I want to select the occurrence or absence of nans in rows of these arrays as per the following prescription: If a row does not start with a nan, then the result for that array will be -1. If a row starts with a nan, then the result will be the index ...
You can add a column of non-nan with hstack, check which values are nan with isnan and get the position of the first non-nan with argmin: out = np.isnan(np.hstack([arr, np.ones((arr.shape[0], 1))])).argmin(axis=1)-1 Or without concatenation and using where to fix the case in which all values are nan: tmp = np.isnan(ar...
6
4
77,419,949
2023-11-3
https://stackoverflow.com/questions/77419949/adding-key-pair-values-into-a-dict-missing
I have been trying to add key values of a list into a dict whereas the key is the amount of times X is repeated in the list, and the value is X itself. my_list = ["apple", "cherry", "apple", "potato", "tomato", "apple"] my_grocery = {} while True: try: prompt = input().upper().strip() my_list.append(prompt) except EOFE...
you couldn't have duplicated keys in dict, in your case it's "1", you can use Counter for vise versa key-value savings occurrences of each product type from collections import Counter my_list = [] while True: try: prompt = input().strip() if not prompt: break my_list.append(prompt) except EOFError: break item_counts = ...
3
2
77,419,705
2023-11-3
https://stackoverflow.com/questions/77419705/all-combinations-of-elements-in-a-vector-in-a-larger-vector
I have the following input vector. ['a','b','c'] I want to list all possible combinations. There are three restrictions: The values have to be inserted into an output vector of six positions. One given value from the input vector can only occur once in the output vector. The order of the values has to be the same in ...
Choosing 3 out of the 6 indices and placing the elements there: from itertools import combinations v = ['a','b','c'] n = 6 for I in combinations(range(n), len(v)): out = [' '] * n for i, out[i] in zip(I, v): pass print(out)
3
3
77,412,120
2023-11-2
https://stackoverflow.com/questions/77412120/abstractmethod-returns-a-type-of-self
I'm having some problems with mypy. I have an abstract class and a class that inherits from it: from __future__ import annotations from abc import abstractmethod, ABC from typing import Union class Base(ABC): @abstractmethod def the_method(self, a_class: Union[Base, float, int]) -> None: ... @abstractmethod def other_m...
Base.the_method accepts Base, so subclasses need to accept at least Base too. If I have a class Foo(Base), that should be accepted. At the moment, it's not accepted by MyClass.the_method. Liskov substitution works in the opposite direction for method parameters and return types - superclasses are OK for parameters, sub...
3
5