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
69,132,981
2021-9-10
https://stackoverflow.com/questions/69132981/how-to-make-jupyter-notebook-python-help-function-output-colorful
I am new to Jupyter notebook and trying to see the some help about the functions. For example, when I print the help of statsmodels.OLS I got the following plain black and white help. Are there any python modules that colorize/beautify the help outputs? For example: hightlight parameters names highlight the code examp...
You can try to beautify the help using rich library (in jupyter, you can install it, using the command !pip install rich). In particular, you could study the inspect method. For example, with the following code: from rich import inspect inspect(sm.OLS, help=True) I get this output:
7
4
69,159,775
2021-9-13
https://stackoverflow.com/questions/69159775/gtk-python-window-symbolic-icon-color-problem
I have a GTK3 GUI called by a simple Python 3 code. Icon is located in the /usr/share/icons/hicolor/scalable/actions/ directory. My current theme color is dark and icons look white. When I switch to white system theme GUI icons turn into black. But in my code icon looks as black instead of white when dark theme is acti...
I have found a solution for automatically changing icon color on the window title bar. I have used Gtk.HeaderBar instead of default window title bar and added an Gtk.Image (its name is image_headerbar) to the left of the headerbar. Finally I have set image icon by using the following code and it worked: image_headerbar...
6
2
69,154,359
2021-9-12
https://stackoverflow.com/questions/69154359/guvectorize-not-resolving-types-in-nopython-mode
I'm struggling with a numba error Untyped global name 'is_a_subset': Cannot determine Numba type of <class 'numba.np.ufunc.gufunc.GUFunc'> This usually means I have fumbled and used a method that isn't supported by numba. The following code fails. @guvectorize("(n),(n)->(n)",nopython=True) def is_a_subset(x,y,out): out...
I am using Numba 0.53.1 and can replicate this error. This blog on the dynamic dispatch update to guvectorize in Numba 0.53 mentions this at the end (emphasis added): In the future we would like to bring the @guvectorize capabilities closer to the @vectorize ones. For instance, currently it is not possible to call a g...
9
4
69,115,825
2021-9-9
https://stackoverflow.com/questions/69115825/remove-white-borders-from-segmented-images
I am trying to segment lung CT images using Kmeans by using code below: def process_mask(mask): convex_mask = np.copy(mask) for i_layer in range(convex_mask.shape[0]): mask1 = np.ascontiguousarray(mask[i_layer]) if np.sum(mask1)>0: mask2 = convex_hull_image(mask1) if np.sum(mask2)>2*np.sum(mask1): mask2 = mask1 else: m...
For this problem, I don't recommend using Kmeans color quantization since this technique is usually reserved for a situation where there are various colors and you want to segment them into dominant color blocks. Take a look at this previous answer for a typical use case. Since your CT scan images are grayscale, Kmeans...
17
11
69,125,666
2021-9-9
https://stackoverflow.com/questions/69125666/merge-two-pandas-dataframe-based-on-partial-match
Two DataFrames have city names that are not formatted the same way. I'd like to do a Left-outer join and pull geo field for all partial string matches between the field City in both DataFrames. import pandas as pd df1 = pd.DataFrame({ 'City': ['San Francisco, CA','Oakland, CA'], 'Val': [1,2] }) df2 = pd.DataFrame({ 'Ci...
Update: the fuzzywuzzy project has been renamed to thefuzz and moved here You can use thefuzz package and the function extractOne: # Python env: pip install thefuzz # Anaconda env: pip install thefuzz # -> thefuzz is not yet available on Anaconda (2021-09-18) # -> you can use the old package: conda install -c conda-for...
16
17
69,181,078
2021-9-14
https://stackoverflow.com/questions/69181078/spacy-how-do-you-add-custom-ner-labels-to-a-pre-trained-model
I am new to SpaCy and NLP. I am using SpaCy v 3.1 and Python 3.9.7 64-bit. My objective: to use a pre-trained SpaCy model (en_core_web_sm) and add a set of custom labels to the existing NER labels (GPE, PERSON, MONEY, etc.) so that the model can recognize both the default AND the custom entities. I've looked at the Spa...
For Spacy 3.2 I did it this way: import spacy import random from spacy import util from spacy.tokens import Doc from spacy.training import Example from spacy.language import Language def print_doc_entities(_doc: Doc): if _doc.ents: for _ent in _doc.ents: print(f" {_ent.text} {_ent.label_}") else: print(" NONE") def cus...
12
12
69,175,352
2021-9-14
https://stackoverflow.com/questions/69175352/why-does-my-jupyterlab-cell-turn-orange-with-every-new-edit-or-when-i-type-in-it
I recently installed Cron via jupyterlab_scheduler in the anaconda extensions in a conda environment I usually work in. This was to schedule my jupyterlab notebooks. However, there was a problem with the application and so I deleted it. Though it seems to have left some of its features like turning the cell orange and ...
As explained in the JupyterLab 3.1 changelog, specifically the user-facing changes section, a new new visual indicator was introduced to highlight cells in which the code changed in the editor since last execution: The indicator is currently implemented by changing the cell collapser and the cell execution counter col...
7
8
69,125,173
2021-9-9
https://stackoverflow.com/questions/69125173/accuracy-in-calculating-fourth-derivative-using-finite-differences-in-tensorflow
I am writing a small code to calculate the fourth derivative using the method of finite differences in tensorflow. This is as follows: def action(y,x): #spacing between points. h = (x[-1] - x[0]) / (int(x.shape[0]) - 1) #fourth derivative dy4 = (y[4:] - 4*y[3:-1] + 6*y[2:-2] - 4*y[1:-3] + y[:-4])/(h*h*h*h) return dy4 x...
The issue is related to the choice of floating-point types. tf.linspace automatically selects tf.float32 as its type, while np.linspace creates a float64 array, which has much more precision. Making the following modification: start = tf.constant(0.0, dtype = tf.float64) end = tf.constant(30.0, dtype = tf.float64) x ...
10
10
69,184,212
2021-9-14
https://stackoverflow.com/questions/69184212/how-to-enumerate-combinations-filtering-repeats
I have a list of possible choices: [[1], [2, 4], [4], [5, 6, 2], [5, 3]]. I want to list all combinations, taking maximum one element from each sublist, without repeating elements. So [1, 2, 4, 5, 3] is a valid option. But [1, 4, 4, 5, 3] is not. I allow not making a choice in any sublist, so [1,4, None,5,3] is valid, ...
Another way to generate all valid outputs with minimal memory usage is to iterate over the elements rather than over the lists. Use a Depth-First search so that you only generate valid outputs from the start. This means that we need to track three things in each level of our DFS: the current element to maybe add, the l...
5
6
69,148,495
2021-9-12
https://stackoverflow.com/questions/69148495/typeerror-import-optional-dependency-got-an-unexpected-keyword-argument-erro
I am trying to work with Featuretools to develop an automated feature engineering workflow for the customer churn dataset. The end outcome is a function that takes in a dataset and label times for customers and builds a feature matrix that can be used to train a machine learning model. As part of this exercise I am try...
Try to upgrade pandas: pip install pandas --upgrade
9
9
69,172,994
2021-9-14
https://stackoverflow.com/questions/69172994/spark-submit-options-for-gcs-connector-to-access-google-storage
I am using spark-job on a self-managed cluster (like local environment) while accessing buckets on google storage. ❯ spark-submit --version Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /___/ .__/\_,_/_/ /_/\_\ version 3.1.2 /_/ Using Scala version 2.12.10, OpenJDK 64-Bit Server VM, 1.8.0_292 Branch...
As mentioned in the comments, this stems from a Guava version incompatibility between the GCS connector's dependency vs what you have bundled in your Spark distro. Specifically, the GCS connector hadoop3-2.2.2 depends on Guava 30.1-jre whereas Spark 3.1.2 brings Guava 14.0.1 as a "provided" dependency. In the two diffe...
6
5
69,152,016
2021-9-12
https://stackoverflow.com/questions/69152016/cant-send-requests-through-socks5-proxy-with-python
I was trying to send http/https requests via proxy (socks5), but I can't understand if the problem is in my code or in the proxy. I tried using this code and it gives me an error: requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by ...
Create a local server/mock to handle the request using pytest or some other testing framework with responses library to eliminate variables external to your application/script. I’m quite sure Google will reject requests with empty headers. Also, ensure you installed the correct dependencies to enable SOCKS proxy suppor...
4
6
69,177,148
2021-9-14
https://stackoverflow.com/questions/69177148/numpyic-way-to-sort-a-matrix-based-on-another-similar-matrix
Say I have a matrix Y of random float numbers from 0 to 10 with shape (10, 3): import numpy as np np.random.seed(99) Y = np.random.uniform(0, 10, (10, 3)) print(Y) Output: [[6.72278559 4.88078399 8.25495174] [0.31446388 8.08049963 5.6561742 ] [2.97622499 0.46695721 9.90627399] [0.06825733 7.69793028 7.46767101] [3.774...
This is a vectorized version of your algorithm. It runs ~26.5x faster than your implementation for 1000 samples. But an additional boolean array with shape (1000,1000,3) is created. There is a chance that rows will have similar values within the tolerance and a wrong row is selected. tol = .5 X[(np.abs(Y[:, np.newaxis]...
5
2
69,175,990
2021-9-14
https://stackoverflow.com/questions/69175990/how-does-password-checking-in-bcrypt-work
So, I found the following example in bcrypt docs: password = b"super secret password" hashed = bcrypt.hashpw(password, bcrypt.gensalt()) if bcrypt.checkpw(password, hashed): print("It Matches!") else: print("It Does not Match :(") And it seems to work. But I don't understand how. Shouldn't we use salt to generate a ha...
The generated "hash" also contains the salt. It is in the Modular Crypt Format, documented here (thanks @Masklinn) $2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy |<--- salt --->||<---- confirmation hash ---->| The "2a" part gives information on the modular hash being used, "10" is the logarithmic cost pa...
7
10
69,166,262
2021-9-13
https://stackoverflow.com/questions/69166262/fastapi-adding-route-prefix-to-testclient
I have a FastAPI app with a route prefix as /api/v1. When I run the test it throws 404. I see this is because the TestClient is not able to find the route at /ping, and works perfectly when the route in the test case is changed to /api/v1/ping. Is there a way in which I can avoid changing all the routes in all the test...
Figured out a workaround for this. The TestClient has an option to accept a base_url, which is then urljoined with the route path. So I appended the route prefix to this base_url. source: url = urljoin(self.base_url, url) However, there is a catch to this - urljoin concatenates as expected only when the base_url ends...
12
5
69,173,608
2021-9-14
https://stackoverflow.com/questions/69173608/why-do-i-get-an-http-error-404-when-using-textblob
I am experiencing some problems using the TextBlob library. I'm trying to run a very simple piece of code like this: from textblob import TextBlob text = 'this is just a test' blob = TextBlob(text) blob.detect_language() And it continually gives me this error: /usr/lib/python3.7/urllib/request.py in http_error_default...
Function dectect_language() sends a request to google translate service: http://translate.google.com/translate_a/t?client=webapp&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&ssel=0&tsel=0&kc=1&sl=auto&tk=276174.132528 and this url returns 404. From documentation on detect_language...
8
11
69,172,802
2021-9-14
https://stackoverflow.com/questions/69172802/clean-boto3-pagination
I am trying to find a very nice python idiom to use aws boto3 paginators in the most "pythonic" way. Below is the best I have been able to come up with and I'm still not happy with it. Any ideas on how to make pagination simpler, possibly not using while True:? import boto3 client = boto3.client('acm', region_name='ap-...
Woudn't the following form work?: client = boto3.client('acm', region_name='ap-southeast-2') paginator = client.get_paginator('list_certificates') for page in paginator.paginate(): print(page)
7
5
69,167,795
2021-9-13
https://stackoverflow.com/questions/69167795/order-of-evaluation-of-assignment-expressions-walrus-operator
I have the following expression: >>> a = 3 >>> b = 2 >>> a == (a := b) False Now, a == 2 after the operation, as expected. And the result is what I would want, i.e., comparison of a to RHS of assignment before assignment. Reversing the order of the equality operator reverses the result: >>> a = 3 >>> b = 2 >>> (a := b...
Neither of those PEP sections have to do with this. You just have a == comparison, and the general Evaluation order applies: "Python evaluates expressions from left to right." So your (a := b) == a simply first evaluates the left side (a := b), assigning something to a and evaluating to the same value. And then evaluat...
8
9
69,169,295
2021-9-13
https://stackoverflow.com/questions/69169295/automatically-activating-conda-environment-in-integrated-terminal
I have an anaconda virtual environment that I wish to use. I am able to use Select Interpreter, which finds and allows me to accurately select said virtual environment. I am also able to use this with jupyter notebooks. What I am not able to do is have the integrated terminal automatically activate this environment. Ev...
Open Powershell and run as Administrator, execute the following command conda config --set auto_activate_base true Then restart VS Code, add the following in User Settings.json: "python.defaultInterpreterPath": "\\path\\to\\conda\\python.exe", "Python.terminal.activateEnvironment": true, "Python.terminal.activateEnvIn...
4
8
69,164,379
2021-9-13
https://stackoverflow.com/questions/69164379/how-to-find-the-index-of-the-point-closest-to-k-means-cluster-centers-using-skle
I have used python's sklearn package for K-means clustering. So far I am able to get the coordinates of the cluster centers using the following code. import numpy as np from sklearn.cluster import KMeans p50 = np.load('tsnep400.npy') kmeans = KMeans(n_clusters=50).fit(p50) np.savetxt('kmeans_50clusters_centers_tsnep400...
According to the scikit-learn documentation, the attribute .labels_ contains the labels of each point, by their index. Thus, you can use this to group each of your points into a cluster and then calculate the distance to each cluster center. You can use the following code for this: from scipy.spatial.distance import eu...
5
3
69,108,649
2021-9-8
https://stackoverflow.com/questions/69108649/change-a-matplotlib-3d-figures-frames-into-x-y-and-z-arrows
Can one can change the arrows of a figure into an arrow by superimposing arrows on top of the x, y and z axes to create the illusion of the axes being arrows or perhaps directly change the settings of the frames as Matplot lib framing in order to get the same outcome on a 3D plot, showing (x,y,z) with arrows? Turning t...
I don't usually use 3D graphs, and I did a lot of research to answer your question. Here's a great approach I found. I created a new Arrow 3D class and implemented it. In your code, I added the class and added arrows to the x-, y-, and z-axes. I manually shifted their positions to align them on the axes. import numpy a...
8
6
69,160,152
2021-9-13
https://stackoverflow.com/questions/69160152/pymupdf-attributeerror-module-fitz-has-no-attribute-open
pip3 install PyMuPDF Collecting PyMuPDF Using cached PyMuPDF-1.18.17-cp37-cp37m-win_amd64.whl (5.4 MB) Installing collected packages: PyMuPDF Successfully installed PyMuPDF-1.18.17 import fitz doc = fitz.open("my_pdf.pdf") When I look for def open on the fitz.py file, I find nothing. So I understand the error But I d...
This is likely to be an installation issue and looks like there already exists a package fitz installed on your environment and is unrelated to PyMuPDF. So when PyMuPDF calls fitz it might actually be calling the wrong fitz package. You can consider doing a clean install of all dependencies or create a virtual environm...
20
7
69,134,512
2021-9-10
https://stackoverflow.com/questions/69134512/where-can-i-find-python-print-statements-in-cloud-run-docker-instances
If I am running a container within Cloud Run and do a print statement in my python code. Where can I view it? Cloud logs seem to show logs for the contain itself(build, etc)? to debug my code often I do write statements that help me figure what's going on. Where would that print output be located?
1] You can find all the logs including your print statement output in Cloud Logging as mentioned in this link. So when you write a print statement from your service they will be automatically picked up by Cloud Logging. 2] Steps to view logs in Cloud Logging: Logs Explorer -> Cloud Run Revision. 3] You may wanna check ...
4
7
69,157,587
2021-9-13
https://stackoverflow.com/questions/69157587/how-to-install-the-dependencies-of-the-submodule-using-poetry
I have a project my-project that uses a submodule my-submodule. The submodule has dependencies different from my-project in poetry.lock & pyproject.toml files. I have installed the dependencies required for my-project using poetry add. These deps are installed and poetry.lock & pyproject.toml files are created in the r...
You can declare the submodule as a path dependency in the pyproject.toml of the parent project. It will then treat the submodule as a package and include it in dependency install/resolution. Be sure to also include the develop attribute when declaring the dependency, as follows: [tool.poetry.dependencies] my-package = ...
9
12
69,155,594
2021-9-12
https://stackoverflow.com/questions/69155594/cannot-reset-index-inplace-on-a-series-to-create-a-dataframe
When I am trying to reset the index of my dataFrame, it is not working. new = pd.DataFrame(columns=['a','b','Amount1']) new['Amount1'] = [0,1,6,7,8,9] new['a'] = ['sarim',1,2,3,4,'sarim'] df_tf = new[new['a']=='sarim']['Amount1'] df_tf.reset_index(inplace=True) ret_df['Amount1'] = df_tf
you can try, df_tf.reset_index(drop = True, inplace=True) ret_df['Amount1'] = df_tf or ret_df['Amount1'] = list(df_tf)
8
6
69,155,789
2021-9-12
https://stackoverflow.com/questions/69155789/importerror-cannot-import-name-parsemode-from-telegram
I am trying to create a telegram bot. The code i am trying to execute is : from telegram import ParseMode But it is throwing up this error: ImportError: cannot import name 'ParseMode' from 'telegram' (C:\ProgramData\Anaconda3\lib\site-packages\telegram\__init__.py) Could you please advise how to fix this error?
you have to import with this way: from telegram.ext import ParseMode if problem not solved: install the package like this: pip install python_telegram_bot or pip install "python_telegram_bot==12.4.2"
11
2
69,132,009
2021-9-10
https://stackoverflow.com/questions/69132009/django-forms-that-choice-is-not-one-of-the-available-choices
I have a form to update user, the error is on the role field. I am filtering the role based on customer. I am getting the right values for role but anyways the error pops up. Select a valid choice. That choice is not one of the available choices views.py class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, Upd...
I have removed the role feature, it was redundant in my project.
5
0
69,152,401
2021-9-12
https://stackoverflow.com/questions/69152401/print-and-evaluate-in-python3
Currently for my scientific experiments I use dbg = print # def dbg(*args): pass So I have a lot of dbg(x, y, f(x)) in code, all of which I can "turn off" my commenting one line and uncommenting another. However, the output looks brief, e.g. 0 15 32. Is there a way to make it look like x = 0, y = 15, f(x) = 32? I trie...
Try using the = operator on f-strings: dbg(f"{x=}, {y=}, {f(x)=}") This was introduced in Python3.8 f-strings support = for self-documenting expressions and debugging Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of ...
5
13
69,148,116
2021-9-12
https://stackoverflow.com/questions/69148116/convert-long-form-dataframe-of-pairwise-distances-to-distance-matrix-in-python
I have a pandas dataframe of pairwise distances in the form of: SampleA SampleB Num_Differences 0 sample_1 sample_2 1 1 sample_1 sample_3 4 2 sample_2 sample_3 8 Note that there are no self-self comparisons (e.g., sample_1 vs sample_1 won't be represented). I would like to convert this table into a squareform distanc...
You can reshape to square, and then make symmetrical by adding the transposed values: # make unique, sorted, common index idx = sorted(set(df['SampleA']).union(df['SampleB'])) # reshape (df.pivot(index='SampleA', columns='SampleB', values='Num_Differences') .reindex(index=idx, columns=idx) .fillna(0, downcast='infer') ...
10
6
69,107,860
2021-9-8
https://stackoverflow.com/questions/69107860/celery-what-is-the-reason-to-have-acks-late-true-without-setting-task-reject-on
After playing with some "defect" scenarios with celery (Redis being a broker for whatever it worth) we came to understanding that there is effectively no sense in setting acks_late=true without simultaneous setting of task_reject_on_worker_lost=true because the task won't be rescheduled (again, in our tests) -- task st...
Reboot, power outage, hardware failure. n.b., all of your examples assume that the prefetch multiplier is 1.
14
1
69,146,994
2021-9-11
https://stackoverflow.com/questions/69146994/how-to-set-specific-color-to-some-bars-in-a-plotly-bar-graph
I'm trying to set different colors for some bars in a plotly express bar graph: import plotly.express as px import pandas as pd data = {'Name':['2020/01', '2020/02', '2020/03', '2020/04', '2020/05', '2020/07', '2020/08'], 'Value':[34,56,66,78,99,55,22]} df = pd.DataFrame(data) color_discrete_sequence = ['#ec7c34']*len(...
This happens because color in px.bar is used to name a category to illustrate traits or dimensions of a dataset using a colorscale. Or in you your case, rather a color cycle since you're dealing with a categorical / discrete case. color_discrete_sequence is then used to specify which color sequence to follow. One way t...
7
9
69,146,380
2021-9-11
https://stackoverflow.com/questions/69146380/how-to-parse-datetime-that-is-coming-in-arabic-text-%d9%a0%d9%a4-%d9%a2%d9%a5-%d9%a2%d9%a0%d9%a2%d9%a1-to-english-date
I am reading JSON file that has some date columns. The issue is some of the date columns contain dates in Arabic/urdu text : ٠٤-٢٥-٢٠٢١ I want to convert it to English date in yyyy-mm-dd format. How to achieve this in Pyspark?
You can convert arabic number to english by casting type to decimal. df = spark.createDataFrame([('٠٤-٢٥-٢٠٢١',)],['arabic']) df.withColumn('split', split('arabic', '-')) \ .withColumn('date', concat_ws('-', col('split')[2].cast('decimal'), col('split')[0].cast('decimal'), col('split')[1].cast('decimal'))) \ .drop('spl...
5
5
69,139,030
2021-9-11
https://stackoverflow.com/questions/69139030/why-and-when-should-use-a-stack-and-unstack-methods
I'm very confused about these two methods which are: stack() and unstack() I know that I should use them in the case of multi-Indexes however, I need to know the following: 1- I don't know where I should use stack or unstack 2- why I should use them when I use "pivot" what I understand is that the pivot converts Datafr...
Here is an attempt at a canonical answer on the differences between pivot and unstack. For a complete guide on reshaping, pandas's official documentation on reshaping and pivot tables is a must read. pivot and unstack perform roughly the same operation, but they operate on different logical levels: columns and index le...
6
11
69,133,906
2021-9-10
https://stackoverflow.com/questions/69133906/taking-gradients-when-using-tf-function
I am puzzled by the behavior I observe in the following example: import tensorflow as tf @tf.function def f(a): c = a * 2 b = tf.reduce_sum(c ** 2 + 2 * c) return b, c def fplain(a): c = a * 2 b = tf.reduce_sum(c ** 2 + 2 * c) return b, c a = tf.Variable([[0., 1.], [1., 0.]]) with tf.GradientTape() as tape: b, c = f(a)...
Gradient tape does not record the operations inside the tf.Graph generated by @tf.function treating the function as a whole. Roughly, f is applied to a, and gradient tape has recorded the gradients of the outputs of f with respect to input a (it is the only watched variable, tape.watched_variables()). In the second cas...
7
9
69,127,120
2021-9-10
https://stackoverflow.com/questions/69127120/gensim-fasttext-cannot-get-latest-training-loss
Problem description It seems that the get_latest_training_loss function in fasttext returns only 0. Both gensim 4.1.0 and 4.0.0 do not work. from gensim.models.callbacks import CallbackAny2Vec from pprint import pprint as print from gensim.models.fasttext import FastText from gensim.test.utils import datapath class cal...
Indeed, loss-tracking hasn't ever been implemented in Gensim's FastText model, at least through release 4.1.0 (August 2021). The docs for that method appear in error, due to the inherited method from the Word2Vec superclass not being overriden to prevent the default assumption that superclass methods work. There is a l...
5
5
69,106,483
2021-9-8
https://stackoverflow.com/questions/69106483/python-project-with-poetry-how-to-debug-it-in-visual-studio-code
I have a Python project which I created according to basic Poetry instructions. The project folder is something like this: my-project +----my_project | +-- my_project.py | +-- File1.py | +-- File2.py | +----pyproject.toml Example of how I import stuff from one file to another: in my_project.py I have the code from . i...
For Visual Studio Code, you could try this: add an __init__.py file in the sub-directory my_project in the .vscode directory, add a lauch.json file with the following content: { "version": "0.1.0", "configurations": [ { "name": "my-project", "type": "python", "request": "launch", "cwd": "${workspaceFolder}", "module"...
25
15
69,118,694
2021-9-9
https://stackoverflow.com/questions/69118694/pandas-transpose-rows-to-columns-based-on-first-column
I have the below dataframe. Column_1 Column_2 Name Xxxx Age 28 Gender M Name yyyy Age 26 Gender F My expected output is Name Age Gender Xxxx 28 M yyyy 26 F I tried df.T(), but it's writing each name, age and gender to separate columns. How to achieve the above output in python/pandas.
Try with groupby and pivot: df["idx"] = df.groupby("Column_1").cumcount() >>> df.pivot("idx", "Column_1", "Column_2").reset_index(drop=True).rename_axis(columns=None) Age Gender Name 0 28 M Xxxx 1 26 F Yyyy
4
2
69,118,377
2021-9-9
https://stackoverflow.com/questions/69118377/what-is-the-point-of-having-to-put-await-in-front-of-each-async-function-in-pyth
In Python, we need an await keyword before each coroutine object to have it called by the event loop. But when we put await, it makes the call blocking. It follows that we end up doing the same thing as we do in the blocking fashion. What is the point of having such a use? https://www.aeracode.org/2018/02/19/python-asy...
await makes the call locally blocking, but the "wait" is transmitted through the async function (which is itself awaited), such that when it reaches the reactor the entire task can be moved to a waitlist and an other can be run instead. Furthermore you do not need an await, you could also spawn the coroutine (to a sepa...
13
4
69,117,594
2021-9-9
https://stackoverflow.com/questions/69117594/problem-with-curve-fitting-overflow-encountered-in-exp
I want to fit a curve with the following data, but I get the error: ipython-input>:2: RuntimeWarning: overflow encountered in exp Does anyone know what is the reason for this problem? I fitted this curve with a different datatype for Matlab and it worked fine. I used the initial condition from my Matlab code. Both cur...
If you set the dtypes of array_R1_fit and tau_array to np.longdouble ornp.float64 should fix the RuntimeWarning: overflow encountered in exp that is: array_R1_fit = np.asarray(list_R1_fit, dtype=np.longdouble) tau_array =np.asarray(tau_list, dtype=np.longdouble) Note that if you are on a Windows 64-bit computer np.lon...
5
1
69,110,065
2021-9-8
https://stackoverflow.com/questions/69110065/plotly-how-to-add-a-text-box-under-legend
I use this example code given in plotly website. import plotly.express as px df = px.data.medals_long() fig = px.bar(df, x="medal", y="count", color="nation", pattern_shape="nation", pattern_shape_sequence=[".", "x", "+"]) fig.show() This gives a plot like below. How can I add a text box under the legend in the plot ...
From what I could find, adding an annotation is the only way to get the expected output natively in plotly. An implemntation of the annotation will look like: fig.add_annotation(text='South Korea: Asia <br>China: Asia <br>Canada: North America', align='left', showarrow=False, xref='paper', yref='paper', x=1.1, y=0.8, b...
4
6
69,109,730
2021-9-8
https://stackoverflow.com/questions/69109730/apache-airflow-dag-with-single-task
I'm newbie in Apache Airflow. There are a lot of examples of basic DAGs in the Internet. Unfortunately, I didn't find any examples of single-task DAG's. Most of DAG's examples contain bitshift operator in the end of the .py script, which defines tasks order. For example: # ...our DAG's code... task1 >> task2 >> task3 ...
The answer is NO, you don't need to include the last line. You could also avoid the asignment of the variable t1, leaving the DAG like this: with DAG( 'tutorial', default_args=default_args, description='A simple tutorial DAG', schedule_interval=timedelta(days=1), start_date=days_ago(2), tags=['example'], ) as dag: Bash...
9
11
69,109,316
2021-9-8
https://stackoverflow.com/questions/69109316/how-can-i-see-the-creation-dates-for-my-conda-environments
I created four different versions of conda virtual environments (envs) for image processing tasks. Each env includes GDAL and OpenCV, and some subset of related libs and dependencies. I want to cull my list of image processing envs down to the most recently created one, which will have the most complete set of the libs...
Conda history files Aside from file/folder dates, Conda also records the history of all environment changes in the conda-meta/history file relative to each environment folder, so that could also be consulted. All entries begin with a date stamp (==> YYYY-MM-DD HH:MM:SS <==), so assuming the first entry corresponds with...
4
3
69,107,300
2021-9-8
https://stackoverflow.com/questions/69107300/get-access-token-from-google-oauth2-credentials
Currently, I am building the async frontend to my TF2 model. Now it works as two services, 1st service is a twisted service, and 2nd service is a TensorFlow serving. The async web client is being used to query the model asynchronously. For practical reasons, I've deployed the model into the GCP AI Platform, and I can g...
The following code sets up the data structures for managing credentials (OAuth tokens) from a service account. No tokens are requested at this point. credentials = service_account.Credentials.from_service_account_file( '/path/to/key.json', scopes=['https://www.googleapis.com/auth/cloud-platform']) Tokens are not reque...
5
14
69,100,302
2021-9-8
https://stackoverflow.com/questions/69100302/setting-results-of-torch-gather-calls
I have a 2D pytorch tensor of shape n by m. I want to index the second dimension using a list of indices (which could be done with torch.gather) then then also set new values to the result of the indexing. Example: data = torch.tensor([[0,1,2], [3,4,5], [6,7,8]]) # shape (3,3) indices = torch.tensor([1,2,1], dtype=torc...
What you are looking for is torch.scatter_ with the value option. Tensor.scatter_(dim, index, src, reduce=None) → Tensor Writes all values from the tensor src into self at the indices specified in the index tensor. For each value in src, its output index is specified by its index in src for dimension != dim and by the...
6
4
69,101,233
2021-9-8
https://stackoverflow.com/questions/69101233/using-dateformatter-resets-starting-date-to-1970
I have a dataframe where the index is the first date of each month and the size column is the frequency for that month, e.g. Using .index on the dataframe confirms the type of the index is DatetimeIndex: DatetimeIndex(['2006-12-01', ...], dtype='datetime64[ns]', name='created_at_month', length=175, freq=None) Using ....
As reported here, for some reason pandas's plot shows this issue. You can overcome this issue by replacing pandas' plot with matplotlib.pyplot.plot. You can take this answer as a reference for 2 datetime ticks on x axis (month and year, or month and day, or day and hour, as you need), using two different axis in palce ...
5
5
69,099,250
2021-9-8
https://stackoverflow.com/questions/69099250/how-does-threadpoolexecutor-utilise-32-cpu-cores-for-cpu-bound-tasks
From ThreadPoolExecutor Changed in version 3.8: Default value of max_workers is changed to min(32, os.cpu_count() + 4). This default value preserves at least 5 workers for I/O bound tasks. It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL. And it avoids using very large resources implicitly on...
Yes, exactly. Since the GIL protects python interpreter state, a library can release the lock if it has a significant amount of work to do that doesn't involve accessing Python variables or calling Python functions. NumPy is one such library that can frequently do this.
5
4
69,096,752
2021-9-8
https://stackoverflow.com/questions/69096752/how-can-i-run-python-on-my-hp-prime-graphing-calculator
According to this firmware post, the HP Prime graphing calculator supports Python. However, I cannot find any guide as to how to run python files in the calculator (even within HP's own 700 page long user manual). Does anyone know how to execute these files? For reference, I have HP Prime's connectivity kit (CK) insta...
I couldn't really find a good source to read about Python support in this particular brand, but in general, graphing calculators have much more limited memory than personal computers, so they do not choose CPython or any of the heftier implementations of the Python language. They will instead use lightweight implementa...
4
1
69,096,931
2021-9-8
https://stackoverflow.com/questions/69096931/how-do-i-combine-two-plots-into-one-figure-using-plotly
I have 2 csv files, my codes are as below. df = pd.read_csv("test.csv", sep='\t',skiprows=range(9),names=['A', 'B', 'C','D']) df2 = pd.read_csv("LoadMatch_Limit.csv",skiprows=range(1),names=['X','Y']) fig = px.line([df,df2], x=['A','X'] , y=['D','Y']) I would like my line chart, x-axis to take from (columns 'A' and 'X...
You could create the two plots and combine them with plotly graph objects import plotly.express as px import plotly.graph_objects as go fig1 = px.line(df, x='A', y='D') fig2 = px.line(df2, x='X', y='Y') fig = go.Figure(data = fig1.data + fig2.data) fig.show()
6
20
69,087,044
2021-9-7
https://stackoverflow.com/questions/69087044/early-stopping-in-bert-trainer-instances
I am fine-tuning a BERT model for a multiclass classification task. My problem is that I don't know how to add "early stopping" to those Trainer instances. Any ideas?
There are a couple of modifications you need to perform, prior to correctly using the EarlyStoppingCallback(). from transformers import EarlyStoppingCallback, IntervalStrategy ... ... # Defining the TrainingArguments() arguments args = TrainingArguments( output_dir = "training_with_callbacks", evaluation_strategy = Int...
31
68
69,023,252
2021-9-2
https://stackoverflow.com/questions/69023252/conda-init-polluting-environment
I have a project set up in Pycharm, with an existing conda environment. My scripts work when run from within the console. I would like to be able to run python -m path_to_my_script/script.py from any location, but I need conda activated. Conda recommends I do conda init but I'm worried it may change settings someplace ...
Strategy for Answering Exactly what the conda init command does and its consequences are shell-specific. Instead of trying to cover all cases, let's walk through a case, noting along the way that one can replicate this analysis by substituting their shell of interest. Case Study: conda init zsh Let's look at zsh as th...
10
18
69,074,128
2021-9-6
https://stackoverflow.com/questions/69074128/how-to-package-a-python-project-into-msix-package
I currently work on a Python project, which I'd like to upload to the Microsoft Store in the future. As far as I am aware, in order to upload applications to the Microsoft Store, it is necessary that the application will be packed into the MSIX format. Now the question is - is it possible to pack a Python project into ...
Use PyInstaller or a similar tool to package your Python application. You can find more information on how to do this in the PyInstaller documentation. Once you have the output from PyInstaller (either a single .exe file or the "dist" folder), you can use a program like AdvancedInstaller to create .msix files. Note:...
8
1
69,049,818
2021-9-3
https://stackoverflow.com/questions/69049818/how-to-export-jupyter-notebook-by-vscode-in-pdf-format-windows-10
When I try to export my Jupyter Notebook in pdf format in VSCode like this: then I got this error: Export failed. Please check the 'Jupyter' output panel for further details. and jupyter output panel says: [error] If you have not installed xelatex (TeX), you will need to do so before you can export to PDF. For fur...
Since I'm using conda venvs, I did these steps: Activate conda venv using: conda activate <NAME_OF_VENV> in Anaconda prompt. Install nbconvert using conda install -c anaconda nbconvert Now it's all okay, and I can export Jupyter notebooks in HTML and PDF format both. Update 11/17/2023 nbconvert is compatible with Pyt...
25
17
69,083,256
2021-9-7
https://stackoverflow.com/questions/69083256/the-naming-rules-for-your-virtual-environments-in-python
I'm looking for some sort of naming scheme for my virtual environments. How do you usually name them? Is there naming convention for python virtual environments?
If you are storing your environment inside the project folder some common names are env, venv, .env, .venv, but besides that, I don't think there are any common conventions. The official docs.python.org's tutorial on venv also suggests using .venv as the name. A common directory location for a virtual environment is ....
8
22
69,024,302
2021-9-2
https://stackoverflow.com/questions/69024302/matplotlib-pie-chart-label-does-not-match-value
I am working on this https://www.kaggle.com/edqian/twitter-climate-change-sentiment-dataset. I already convert the sentiment from numeric to its character description (i.e. 0 will be Neutral, 1 will be Pro, -1 will be Anti) import pandas as pd import seaborn as sns import matplotlib.pyplot as plt tweets_df = pd.read_cs...
labels = list(tweets_df["twt_sentiment"].unique()) does not put the labels in the same order as the index of tweets_df.twt_sentiment.value_counts(). The index determines the slice order. Therefore, it's best to use the .value_counts() index as the labels. Labels can easily be added to the bar plot, then the pie chart ...
5
3
69,040,420
2021-9-3
https://stackoverflow.com/questions/69040420/assertionerror-tried-to-export-a-function-which-references-untracked-resource
I wrote a unit-test in order to safe a model after noticing that I am not able to do so (anymore) during training. @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_save_model(speech_model: Tuple[TransducerBase, SpeechFeaturesConfig]): model, speech_features_config = speech_model speech_features_config: ...
Using tensorflow v2.5.0 Python: 3.9 It appears that the problem occurs when we declare/define a layer as class-variable. I can only assume that the problem has to do with the internal Keras logic, which probably makes sense, but imo it's not obvious to the user and I don't think I have ever seen a hint pointing out t...
9
4
69,071,684
2021-9-6
https://stackoverflow.com/questions/69071684/how-to-optimize-for-multiple-metrics-in-optuna
How do I optimize for multiple metrics simultaneously inside the objective function of Optuna. For example, I am training an LGBM classifier and want to find the best hyperparameter set for all common classification metrics like F1, precision, recall, accuracy, AUC, etc. def objective(trial): # Train gbm = lgb.train(pa...
After defining the grid and fitting the model with these params and generate predictions, calculate all metrics you want to optimize for: def objective(trial): param_grid = {"n_estimators": trial.suggest_int("n_estimators", 2000, 10000, step=200)} clf = lgbm.LGBMClassifier(objective='binary', **param_grid) clf.fit(X_tr...
11
24
69,019,206
2021-9-1
https://stackoverflow.com/questions/69019206/what-it-means-register-anaconda-as-my-default-python
During installation process (Windows OS) I have 2 options: Add Miniconda to my PATH environment variable Register Miniconda as my default Python The first option is pretty obvious. I understand it completely. But what about the second? What is meant by the word "register"? It creates the file with the string "Ok I ha...
I've investigated this issue today and revealed the secret within. You mean the following Anaconda installer UI, right? I give my conclusion first. What he says is: Register Anaconda3 as my default Python 3.9 NOT Register Anaconda3 as my default Python That means, he can NOT determine what Python version, 3.5, 3....
12
8
69,062,195
2021-9-5
https://stackoverflow.com/questions/69062195/scikit-learn-column-transformer-does-not-return-back-feature-names
I'm trying to use Column Transformer with OneHotEncoder to transform my categorical data : A quick look at my data : I want to do one-hot-encoding for 3 features : 'sex' , 'smoker' , 'region', so I use Column Transformer by scikit-learn. ( I don't want to want to seperate numerical one and categorical one than transfo...
User will have to write custom Transformer which does passthrough and supports get_feature_names Steps: Custom Transformer which will return pass through columns names via get_feature_names Dont use remainder = 'passthrough' but rather use our custom Transformer Use enc.get_feature_names() to get the feature list. S...
6
6
69,084,646
2021-9-7
https://stackoverflow.com/questions/69084646/np-random-rand-or-random-random
While analyzing a code, I've stumbled upon the following snippet: msk = np.random.rand(len(df)) < 0.8 Variables "msk" and "df" are irrelevant for my question. After doing some research I think this usage is also related to "random" class as well. It gives True with 80% chance and False with 20% chance on random elemen...
np.random.rand(len(df)) returns an array of uniform random numbers between 0 and 1, np.random.rand(len(df)) < 0.8 will transform it into an array of booleans based on the condition. As there is a 80% chance to be below 0.8, there is 80% of True values. A more explicit approach would be to use numpy.random.choice: np.ra...
5
14
69,046,990
2021-9-3
https://stackoverflow.com/questions/69046990/how-to-pass-dependency-files-to-sagemaker-sklearnprocessor-and-use-it-in-pipelin
I need to import function from different python scripts, which will used inside preprocessing.py file. I was not able to find a way to pass the dependent files to SKLearnProcessor Object, due to which I am getting ModuleNotFoundError. Code: from sagemaker.sklearn.processing import SKLearnProcessor from sagemaker.proces...
There are a couple of options for you to accomplish that. One that is really simple is adding all additional files to a folder, example: . ├── my_package │ ├── file1.py │ ├── file2.py │ └── requirements.txt └── preprocessing.py Then send this entire folder as another input under the same /opt/ml/processing/input/code/...
17
26
69,025,133
2021-9-2
https://stackoverflow.com/questions/69025133/filtering-list-of-tuples-based-on-condition
For a given list of tuples, if multiple tuples in the list have the first element of tuple the same - among them select only the tuple with the maximum last element. For example: sample_list = [(5,16,2),(5,10,3),(5,8,1),(21,24,1)] In the sample_list above since the first 3 tuples has the similar first element 5 in thi...
TL;DR Use collections.defaultdict is the fastest alternative and arguably the most pythonic: from collections import defaultdict sample_list = [(5, 16, 2), (5, 10, 3), (5, 8, 1), (21, 24, 1)] d = defaultdict(lambda: (0, 0, float("-inf"))) for e in sample_list: first, _, last = e if d[first][2] < last: d[first] = e res ...
21
24
69,057,820
2021-9-4
https://stackoverflow.com/questions/69057820/how-to-structure-a-mixed-python-rust-package-with-pyo3
I'm looking for Info on how to structure a Python package that wraps an extension module written in Rust, where both languages are mixed. I'm using pyO3 for FFI but can't seem to find an example on how to do this. To be specific: my rust library exposes a type that is later wrapped by a python class. Only the python cl...
I found a way to do this using Maturin. So, in case anyone else is trying to find out how to do this, here's one way. The project needs to have the following structure: my_project ├── Cargo.toml ├── my_project │ ├── __init__.py │ └── sum.py └── src └── lib.rs Cargo.toml can be: [package] name = "my_project" version = ...
9
7
69,082,602
2021-9-7
https://stackoverflow.com/questions/69082602/the-websocket-transport-is-not-available-you-must-install-a-websocket-server-th
When I development some socket.io service in python environment by using python-socketio and gunicorn, I meet an issue here. I am using Mac OS X and I am using python 3.7. Environment setting $ pip install python-socketio $ pip install gunicorn server-side code app.py import socketio sio = socketio.Server() app = socke...
It just needs to install more packages here. $ pip install gevent-websocket $ pip install eventlet And then $ gunicorn --thread 50 app:app Update 1: If the server-side need to active emit to client side, it will need this environment. Because this command $ gunicorn --thread 50 app:app cannot support this situation. T...
13
11
69,038,398
2021-9-3
https://stackoverflow.com/questions/69038398/python-module-distutilis-hack
I was looking through my pip list and cleaning all my third party modules when I came across a module named 'distutils_hack'. I don't remember installing this, is this something I should be concerned about? The version I was using was Python 3.9. Thanks
It's used by setuptools to replace the stdlib distutils with setuptools' bundled distutils library. Quoting ncoghlan from pypa/setuptools#417 on why this is necessary: While CPython as a whole has many contributors, we don't have many folks contributing to distutils any more - folks need build tools that let them targ...
6
3
69,090,545
2021-9-7
https://stackoverflow.com/questions/69090545/typehint-importing-module-dynamically-using-importlib
Give something as follows: import importlib module_path = "mod" mod = importlib.import_module(module_path, package=None) print(mod.Foo.Bar.x) where mod.py is: class Foo: class Bar: x = 1 mypy file.py --strict raises the following error: file.py:7: error: Module has no attribute "Foo" [attr-defined] I'm wondering how...
As was alluded to by @MisterMiyagi in the comments, I think the solution here is to use structural, rather than nominal, subtyping. Nominal subtyping is where we use direct class inheritance to define type relationships. For example, collections.Counter is a subtype of dict because it directly inherits from dict. Struc...
6
4
69,091,760
2021-9-7
https://stackoverflow.com/questions/69091760/how-can-i-import-a-testclass-properly-to-inherit-from-without-it-being-run-as-a
Context I have a test class where all my tests inherit from. It cant run by itself as it really doesnt contain any setup info I wanted to add a test which is executed by ALL tests (adding it to the baseclass seems logical) But now I notice the basetestclass( => Foo) which I import is being detected as a test itself and...
The key to the answer seems to be that each test has an attribute __test__ which is set to True when it is a test. Setting it to False when the class should not be a test will then let the test collector ignore this class. The answer assumes I can only do changes in the base.py In python 3.9 classmethod and property de...
5
6
69,092,874
2021-9-7
https://stackoverflow.com/questions/69092874/check-if-list-is-valid-sequence-of-chunks
I want to check whether a list is a valid sequence of chunks, where each chunk begins with some value and ends with the next occurrence of the same value. For example, this is a valid sequence of three chunks: lst = [2, 7, 1, 8, 2, 8, 1, 8, 2, 8, 4, 5, 9, 0, 4, 5, 2] \___________/ \_____/ \_______________________/ And...
How about this, creating an iter from the list and searching forward on that iter until the next matching element is found. Note that this might fail is None can be an element of the list; then you should rather define and compare against a sentinel obj = object(). def is_valid(lst): it = iter(lst) for x in it: if next...
8
10
69,085,037
2021-9-7
https://stackoverflow.com/questions/69085037/get-type-argument-of-arbitrarily-high-generic-parent-class-at-runtime
Given this: from typing import Generic, TypeVar T = TypeVar('T') class Parent(Generic[T]): pass I can get int from Parent[int] using typing.get_args(Parent[int])[0]. The problem becomes a bit more complicated with the following: class Child1(Parent[int]): pass class Child2(Child1): pass To support an arbitrarily long...
The following approach is based on __class_getitem__ and __init_subclass__. It might serve your use case, but it has some severe limitations (see below), so use at your own judgement. from __future__ import annotations from typing import Generic, Sequence, TypeVar T = TypeVar('T') NO_ARG = object() class Parent(Generic...
7
6
69,024,209
2021-9-2
https://stackoverflow.com/questions/69024209/chromedriver-executable-path-not-found-in-docker-container
I have created a docker image with the Docker file below. It installs the latest versions of Google Chrome and the chrome driver. As well as the other pip packages. Dockerfile FROM python:3.9 # Install Chrome WebDriver RUN CHROMEDRIVER_VERSION=`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE` && \ mkdir -p ...
I have found the problem, you need to add the all the python files into the Dockerfile. Please find the Dockerfile to install the Chromedriver and Chrome onto the image and the default path for the chromedriver within the container. Dockerfile FROM python:3.9 ADD /app/main.py . ADD /app/connectdriver.py . # Install Chr...
11
7
69,079,181
2021-9-6
https://stackoverflow.com/questions/69079181/how-is-the-s-sc-string-concat-optimization-decided
Short version: If s is a string, then s = s + 'c' might modify the string in place, while t = s + 'c' can't. But how does the operation s + 'c' know which scenario it's in? Long version: t = s + 'c' needs to create a separate string because the program afterwards wants both the old string as s and the new string as t. ...
Here's the code in question, from the Python 3.10 branch (in ceval.c, and called from the same file's implementation of the BINARY_ADD opcode). As @jasonharper noted in a comment, it peeks ahead to see whether the result of the BINARY_ADD will next be bound to the same name from which the left-hand addend came. In fast...
18
16
69,065,682
2021-9-5
https://stackoverflow.com/questions/69065682/randomizedsearchcv-all-estimators-failed-to-fit
I am currently working on the "French Motor Claims Datasets freMTPL2freq" Kaggle competition (https://www.kaggle.com/floser/french-motor-claims-datasets-fremtpl2freq). Unfortunately I get a "NotFittedError: All estimators failed to fit" error whenever I am using RandomizedSearchCV and I cannot figure out why that is. A...
Wow, that was a mess of a traceback, but I think I've finally found it. You set scoring=mean_squared_error, and should instead use scoring="neg_mean_squared_error". The metric function mean_squared_error has signature (y_true, y_pred, *, <kwargs>), whereas the scorer obtained by using the string "neg_mean_squared_error...
4
6
69,090,253
2021-9-7
https://stackoverflow.com/questions/69090253/how-to-iterate-over-attributes-of-dataclass-in-python
Is it possible to iterate over attributes of a instance of dataclass in python? For example, I would like in the __post_init__ double the integer attributes: from dataclasses import dataclass, fields @dataclass class Foo: a: int b: int def __post_init__(self): self.double_attributes() def double_attributes(self): for f...
You are very close, but dataclasses.fields actually returns a tuple of Field objects. At least in my case, it looks like the return type is not properly annotatted, but that's easy enough to fix. from dataclasses import dataclass, fields, Field from typing import Tuple @dataclass class Foo: a: int b: int def __post_ini...
13
16
69,071,531
2021-9-6
https://stackoverflow.com/questions/69071531/how-to-use-django-serializer-to-update-an-instance
in Django PUT method, I want to update an instance: sv= SV.objects.get(pk=pk) serializer = SVSerializer(sv, data=request.data) if serializer.is_valid(): Here, in request.data, I just want to pass some of the variable of SV. But as some fields missing, the is_vaild will be false. What I want is, just update the fields ...
Perform a partial update by setting partial=True: sv= SV.objects.get(pk=pk) serializer = SVSerializer(sv, data=request.data, partial=True) if serializer.is_valid(): serializer.save() else: # Do something else This allows a PATCH request. Edit If you want a default field during partial update (as requested in a comment...
7
10
69,036,579
2021-9-2
https://stackoverflow.com/questions/69036579/how-to-display-buttons-in-pyvis-visualization-of-networkx-graph
I am trying to modify this function in order to correctly display the interactive buttons. I am using pyvis to visualize a graph created on Networkx. Despite including N.show_buttons(filter_=True), the buttons do not appear in the corresponding html file. Also, how can I add a title to the html page that is produced? d...
The problem is you've set the height and width both to '100%' when instantiating the visualization: N = Network(height='100%', width='100%', bgcolor='#ffffff', font_color='black',notebook = True, directed=False) Since the network is set to take up all of the space in the browser window, the buttons simply aren't rende...
5
6
69,091,017
2021-9-7
https://stackoverflow.com/questions/69091017/python-type-hint-for-has-method
For example, we have a class: class A: def send(msg: bytes) -> None: # implementation... pass def recv(n: int) -> bytes: # implementation pass and a function: def a(obj, n: int) -> None: received = obj.recv(n) obj.send(received) It's fairly obvious, that not only instances of class A can be passed as the obj argument...
What you exactly need is duck-typing (structural subtyping) via typing.Protocol. Some examples are in this list. Protocol classes are defined like this: class Proto(Protocol): def meth(self) -> int: ... Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing),...
9
8
69,085,675
2021-9-7
https://stackoverflow.com/questions/69085675/pyspark-dataframe-with-multiple-array-columns-into-multiple-rows-with-one-valu
We have a pyspark dataframe with several columns containing arrays with multiple values. Our goal is to have each of this values of these columns in several rows, keeping the initial different columns. So, starting with something like this: data = [ ("A", ["a", "c"], ["1", "5"]), ("B", ["a", "b"], None), ("C", [], ["1"...
In case both columns list_a and list_b could be empty, I would add a 4th case in the dataset data = [ ("A", ["a", "c"], ["1", "5"]), ("B", ["a", "b"], None), ("C", [], ["1"]), ("D", None, None), ] df = spark.createDataFrame(data,["id","list_a","list_b"]) I would then split the original df in 3 (both nulls, list_a expl...
5
2
69,087,228
2021-9-7
https://stackoverflow.com/questions/69087228/python-multiprocessing-making-same-object-instance-for-every-process
I have written a simple example to illustrate what exactly I'm banging my head onto. Probably there is some very simple explanaition that I just miss. import time import multiprocessing as mp import os class SomeOtherClass: def __init__(self): self.a = 'b' class SomeProcessor(mp.Process): def __init__(self, queue): sup...
To expand on the comments and discussion: On Linux, multiprocessing defaults to the fork start method. Forking a process means child processes will share a copy-on-write version of the parent process's data. This is why the globally created objects have the same address in the subprocesses. On macOS and Windows, the ...
5
8
69,087,572
2021-9-7
https://stackoverflow.com/questions/69087572/how-to-create-mongodb-time-series-collection-using-pymongo
The documentation shows how to do it with mongosh, but how do you create Time Series Collection using pymongo from within a python script? import pymongo import time from datetime import datetime client = pymongo.MongoClient() db = client['time-series-db'] col = db['time-series-col'] # ... do something here to make it ...
You can try this: conn = pymongo.MongoClient('mongodb://localhost') db = conn.testDB db.create_collection('testColl', timeseries={ 'timeField': 'timestamp' }) # - OR - db.command('create', 'testColl', timeseries={ 'timeField': 'timestamp', 'metaField': 'data', 'granularity': 'hours' }) General Reference: Time Series C...
8
11
69,087,045
2021-9-7
https://stackoverflow.com/questions/69087045/datetime-formatting-in-pandas-to-markdown
I have a pandas DataFrame which has a column of dtype datetime: import pandas as pd # Mock-up data df = pd.DataFrame({'year': [2015, 2016], 'month': [2, 3], 'day': [4, 5]}) df = pd.to_datetime(df) print(df) # 0 2015-02-04 # 1 2016-03-05 # dtype: datetime64[ns] I would like to use the .to_markdown() method to display t...
Under the hood the .to_markdown() method uses the tabulate package. The floatfmt named argument can be used to control the formatting of floats, but I cannot see how this could be useful here. The best solution I can currently find is simply to format the datetime column as a column of strings before calling the .to_ma...
7
8
69,083,878
2021-9-7
https://stackoverflow.com/questions/69083878/fastapi-how-to-define-a-global-variable-once
I want to define a dict variable once, generated from a text file, and use it to answer to API requests. This variable should be always available till the end of server run. In an example below: from fastapi import FastAPI import uvicorn app = FastAPI() def init_data(path): print("init call") data = {} data[1] = "123" ...
One approach would be to use the FastAPI startup event to define the variable data once on app startup. An example similar to what you provided in your question: from fastapi import FastAPI import uvicorn app = FastAPI() data = {} @app.on_event('startup') def init_data(): print("init call") path='/an/example/path' data...
8
7
69,084,242
2021-9-7
https://stackoverflow.com/questions/69084242/valueerror-the-truth-value-of-a-dataframe-is-ambiguous-use-a-empty-a-bool
I have a list of data frames but in a few cases, the list can also contain a string. df = pd.DataFrame({"df_column":["df_value"]}) a = ['skip',df] if "skip" in a: print("yes") The above gives output as yes because the list contains a string. But in case if the list doesn't contain a string for eg df = pd.DataFrame({"d...
You need to avoid checking pandas all together see e.g. [df , 'skip'] would fail - it's just a matter of order. For starters you can only filter strings in a: if "skip" in filter(lambda x: isinstance(x, str), a): print("yes")
5
4
69,073,058
2021-9-6
https://stackoverflow.com/questions/69073058/mapping-aij-array-to-ai-j-matrix
I have an array a, and want to create a new matrix A for which A[i,j] = a[i+j]. Example: import numpy as np a = np.random.rand(3) A = np.zeros((2,2)); for i in range(2): for j in range(2): A[i,j] = a[i+j] Is there a way of doing this without a for loop? (with numpy)
Using stride_tricks.as_strided This would be a perfect use case for stride_tricks: from np.lib.stride_tricks import as_strided Set the strides as (8, 8) (i.e. (1, 1) in terms of slots). This way we essentially map the resulting array A as i, j -> k = i + j. A more detailed description would be: we map every i, j pair ...
5
3
69,073,516
2021-9-6
https://stackoverflow.com/questions/69073516/pandas-grouping-and-transform-ignoring-nan
I'm facing an issue with grouping and transforming on non-NA values in my dataframe. So my dataframe is something like this: Name Value A 1 A 2 A NaN B 3 B 7 B 9 B NaN Final output I want: Name Value Weight 1 Weight 2 A 1 0.33 0.5 A 2 0.33 0.5 A NaN 0.33 NaN B 3 0.25 0.33 B 7 0.2...
You can use GroupBy.count to count Non-NaN values in each group. Then use pd.Series.map with pd.Series.mask mapping = (1 / df.groupby('Name')['Value'].count()).squeeze() df['Weight 2'] = df['Name'].map(mapping).mask(df['Value'].isna()) Name Value Weight 2 0 A 1.0 0.500000 1 A 2.0 0.500000 2 A NaN NaN 3 B 3.0 0.333333 4...
5
5
69,057,272
2021-9-4
https://stackoverflow.com/questions/69057272/passing-arguments-in-dataclass-representation
I have a below NormalClass that I want to structure as a dataclass. However I was not sure how I can pass the date_str param without __init__ in the dataclass. Any thoughts? class FieldDateTime(): def __init__(self, data, d_format='%m/%d/%y %I:%M %p'): try: self.data = datetime.strptime(data, d_format) except ValueErro...
Your question has to be more detailed, but I think this is what you're looking for: from __future__ import annotations from datetime import datetime from dataclasses import dataclass, InitVar, field class FieldDateTime: def __init__(self, data, d_format='%m/%d/%y %I:%M %p'): try: self.data = datetime.strptime(data, d_f...
9
10
69,024,982
2021-9-2
https://stackoverflow.com/questions/69024982/fastest-way-to-find-a-pandas-index-column-value-pair
I have a largish DataFrame with a date index ['Date'] and several columns. One column is a string identifier ['Type'], with related data in the remaining columns. I need to add newData to the DataFrame, but only if the date-type pair (i.e. index-ColumnValue pair) is not already present in the DataFrame. Checking for th...
Index value lookup is faster than column value lookup. I don't know the implementation details (it looks like lookup depends on number of rows). Here is a performance comparison: def test_value_matches(df, v1, v2): # return True if v1, v2 found in df columns, else return False if any(df[(df.c1 == v1) & (df.c2 == v2)]):...
5
2
69,066,012
2021-9-5
https://stackoverflow.com/questions/69066012/numpy-function-to-get-the-quantile-that-corresponds-to-a-given-value
I see a lot of questions like this one for R, but I couldn't find one specifically for Python, preferably using numpy. Let's say I have an array of observations stored in x. I can get the value that accumulates q * 100 per cent of the population. # Import numpy import numpy as np # Get 75th percentile np.quantile(a=x, ...
Not a ready-made function but a compact and reasonably fast snippet: (a<value).mean() You can (at least on my machine) squeeze out a few percent better performance by using np.count_nonzero np.count_nonzero(a<value) / a.size but tbh I wouldn't even bother.
15
22
69,068,803
2021-9-6
https://stackoverflow.com/questions/69068803/python-assert-all-elements-in-list-is-not-none
I was wondering if we could assert all elements in a list is not None, therefore while a = None will raise an error. The sample list is [a, b, c] I have tried assert [a, b, c] is not None, it will return True if any one of the elements is not None but not verifying all. Could you help figure it out? Thanks!!
Unless you have a weird element that claims it equals None: assert None not in [a, b, c]
7
9
69,059,121
2021-9-4
https://stackoverflow.com/questions/69059121/how-to-draw-a-normal-curve-on-seaborn-displot
distplot was deprecated in favour of displot. The previous function had the option to draw a normal curve. import seaborn as sns import matplotlib.pyplot as plt from scipy import stats ax = sns.distplot(df.extracted, bins=40, kde=False, fit=stats.norm) the fit=stats.norm doesn't work with displot anymore. In the answe...
seaborn.displot is a figure-level plot where the kind parameter specifies the approach. When kind='hist' the parameters for seaborn.histplot are available. For axes-level plots see How to add a standard normal pdf over a seaborn histogram seaborn.axisgrid.FacetGrid.map expects dataframe column names, as such, to ma...
6
4
69,064,948
2021-9-5
https://stackoverflow.com/questions/69064948/how-to-import-gensim-summarize
I got gensim to work in Google Collab by following this process: !pip install gensim from gensim.summarization import summarize Then I was able to call summarize(some_text) Now I'm trying to run the same thing in VS code: I've installed gensim: pip3 install gensim but when I run from gensim.summarization import summar...
The summarization code was removed from Gensim 4.0. See: https://github.com/RaRe-Technologies/gensim/wiki/Migrating-from-Gensim-3.x-to-4#12-removed-gensimsummarization 12. Removed gensim.summarization Despite its general-sounding name, the module will not satisfy the majority of use cases in production and is likely t...
9
11
69,062,015
2021-9-5
https://stackoverflow.com/questions/69062015/fastest-method-to-update-all-list-entries-with-union-of-all-intersecting-entries
I am looking for a fast method to traverse a list of sets, and to expand each set by finding its union with any other element of the list with which it shares at least one element. For example, suppose that I have four rows of data, where each row corresponds to a set of unique elements 0, 5, 101 8, 9, 19, 21 78, 79 5,...
This problem is about creating disjoint sets and so I would use union-find methods. Now Python is not particularly known for being fast, but for the sake of showing the algorithm, here is an implementation of a DisjointSet class without libraries: class DisjointSet: class Element: def __init__(self): self.parent = self...
5
5
69,064,372
2021-9-5
https://stackoverflow.com/questions/69064372/check-if-the-type-of-a-variable-is-dictstr-any-in-python
I want to check if the type of a variable is: dict[str, Any]. (in python) What I have tried (unsuccessfully) is this: myvar = { 'att1' : 'some value', 'att2' : 1 } if not isinstance(myvar, dict[str, Any]): raise Exception('Input has the wrong type') I get the following error message: TypeError: isinstance() argument ...
Try the below - make sure you have a dict and the keys of the dict are strings. data1 = { 'att1': 'some value', 'att2': 1 } data2 = { 'att1': 'some value', 13: 1 } def check_if_dict_with_str_keys(data): return isinstance(data, dict) and all(isinstance(x, str) for x in data.keys()) print(check_if_dict_with_str_keys(data...
6
7
69,050,355
2021-9-3
https://stackoverflow.com/questions/69050355/get-all-possible-order-combinations-in-python
I have a list of 1 and 2, e.g. [2, 1, 1, 1] I need to get all possible combinations: [[2, 1, 1, 1], [1, 2, 1, 1], [1, 1, 2, 1], [1, 1, 1, 2]] I tried to use itertools' product, however, it return the same result (e.g. [2, 1, 1, 1]) multiple times, and it is inefficient when input is bigger. Is there some build in func...
What you are looking for is permutations: >>> import itertools >>> a = [2, 1, 1, 1] >>> list(set(itertools.permutations(a))) [(1, 1, 1, 2), (1, 1, 2, 1), (2, 1, 1, 1), (1, 2, 1, 1)]
4
7
69,048,016
2021-9-3
https://stackoverflow.com/questions/69048016/make-a-list-from-multiple-list
I have three lists: list_01 = ['DOG','CAT','BEAR'] list_02 = ['V','W','X','Y','Z'] list_03 = ['A','B','C','D','E','F','G','H'] What I hope to get is a list like the following: list_04 = ['DOG','V','A','CAT','W','B','BEAR','X','C','Y','D','Z','E','F','G','H'] This list is supposed to contain one item from list 1, then...
It seems like you want to do this in order, not randomly. If so, you can use zip_longest() from itertools and make a nested list comprehension: from itertools import zip_longest list_01 = ['DOG','CAT','BEAR'] list_02 = ['V','W','X','Y','Z'] list_03 = ['A','B','C','D','E','F','G','H'] list_04 = [n for group in zip_longe...
6
6
69,045,499
2021-9-3
https://stackoverflow.com/questions/69045499/how-to-get-rid-of-scientific-notation-on-bar-labels-in-matplotlib
How could I format the bar labels to remove the scientific notation? highest_enrollment = course_data.groupby( "course_organization")["course_students_enrolled"].sum().nlargest(10) ax = sns.barplot(x=highest_enrollment.index, y=highest_enrollment.values, ci=None, palette="ch: s=.5, r=-.5") ax.ticklabel_format(style='pl...
As already suggested by BigBen in the comment, you can pass fmt parameter to matplotlib.axes.Axes.bar_label; you can use %d for integers: import matplotlib.pyplot as plt import seaborn as sns import pandas as pd highest_enrollment = pd.DataFrame({'class': ['A', 'B', 'C'], 'values': [30000000, 20000000, 10000000]}) ax =...
5
12
69,031,604
2021-9-2
https://stackoverflow.com/questions/69031604/tensorflow-running-out-of-gpu-memory-allocator-gpu-0-bfc-ran-out-of-memory-tr
I am fairly new to Tensorflow and I am having trouble with Dataset. I work on Windows 10, and the Tensorflow version is 2.6.0 used with CUDA. I have 2 numpy arrays that are X_train and X_test (already split). The train is 5Gb and the test is 1.5Gb. The shapes are: X_train: (259018, 30, 30, 3), <class 'numpy.ndarray'> Y...
That's working as designed. from_tensor_slices is really only useful for small amounts of data. Dataset is designed for large datasets that need to be streamed from disk. The hard way but ideal way to do this would be to write your numpy array data to TFRecords then read them in as a dataset via TFRecordDataset. Here's...
5
6
69,038,533
2021-9-3
https://stackoverflow.com/questions/69038533/getting-a-powerset-of-a-list-of-lists
I'm given a list of lists s: s = [["a1", "A"], ["b4", "B"], ["a3", "A"], ["d6", "D"], ["c4", "C"]] (note that the elements in a list do not necessarily begin with a same letter. I modified the data here for convenience.) My goal is to sort each list to a category by its second element, and get all possible combination...
@don'ttalkjustcode's answer works but unnecessarily incurs the overhead of adding dummy values, and also produces an empty set, which is not required by the question. A more direct approach would be to use itertools.combinations to pick lists from the dict of lists to pass to itertools.product to produce the desired co...
4
5
69,036,090
2021-9-2
https://stackoverflow.com/questions/69036090/python-dataframe-yes-no-checker
I would like to make a table that evaluates whether a user is in a group or not. How can I get my dictionary sorted like in the example I have down below? I would like the index and columns populated automatically by the key and value. d = { 'user1': ['group1', 'group2', 'group3'], 'user2': ['group1', 'group2'], 'user3...
Try: d = { "user1": ["group1", "group2", "group3"], "user2": ["group1", "group2"], "user3": ["group2"], } df = pd.DataFrame.from_dict(d, orient="index") x = df.stack().droplevel(level=1) x = pd.crosstab(x.index, x).replace({1: "Y", 0: "N"}) x.index.name, x.columns.name = None, None print(x) Prints: group1 group2 grou...
4
4
69,034,186
2021-9-2
https://stackoverflow.com/questions/69034186/diffrence-between-np-int16-and-int16-matlab
I am converting a matlab code to Python. In matlab there is a line which converting the complex number to the int16: real = int16(real(-3.406578165491512e+04 + 9.054663292273188e+03i)); imag= int16(imag(-3.406578165491512e+04 + 9.054663292273188e+03i)); real= -32768 imag=9055 In python I have tried this: real = np.int...
Wolfie gets at the difference, this is about how to solve it. If you're OK with clipping, then you can use iinfo to get the min and max values of an integer type (or hard-code it, if you know you won't be changing it from int16 ever) and then use clip to constrain the float to be within those bounds before casting it. ...
5
5
69,034,478
2021-9-2
https://stackoverflow.com/questions/69034478/how-can-i-find-the-k-th-largest-element-in-an-exponentially-large-list
Suppose there are n sets of real numbers: S[1], S[2], ..., S[n]. We know two things about these sets: Each set S[i] has exactly 3 elements. All elements in each of the sets S[i] are real numbers in the [0, 1] range. (I don't know if this detail can be helpful for the solution, though). Let's consider a set T of all...
Well, you know that the largest product is the one that uses the largest factor from each set. Furthermore, every other product can be formed by starting with a larger one, and then decreasing the factor chosen in exactly one set. That leads to a simple search: Put the largest product in a max-first priority queue. R...
7
13
69,031,699
2021-9-2
https://stackoverflow.com/questions/69031699/calculation-on-my-for-loop-and-want-to-do-it-without-for-loop-using-some-functio
dec = 0.1 data = np.array([100,200,300,400,500]) I have a for loop like this y = np.zeros(len(data)) for i in range(len(data)): if i == 0: y[i] = (1.0 - dec) * data[i] else: y[i] = (1.0 - dec) * data[i] + (dec * y[i - 1]) Output y is: array([ 90. , 189. , 288.9 , 388.89 , 488.889]) And now I want to do the above cal...
We can do this with scipy.linalg.toeplitz to make a matrix of shifts of the data and then multiplying that by powers of dec and summing columns: import numpy as np from scipy.linalg import toeplitz dec = 0.1 data = np.array([100,200,300,400,500]) decs = np.power(dec, np.arange(len(data))) r = np.zeros_like(data) r[0] =...
5
2