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
70,083,371
2021-11-23
https://stackoverflow.com/questions/70083371/can-i-use-experimental-types-from-typing-extensions
To be more specific: To solve questions like How do I type hint a method with the type of the enclosing class? PEP 673 introduces typing.Self. The PEP is a Draft, but it currently an experimental type in typing_extensions 4.0.0 I tried using this in python 3.8 @dataclasses.dataclass class MenuItem: url: str title: str ...
Yes you can, but be aware of the uses of the package: The typing_extensions module serves two related purposes: Enable use of new type system features on older Python versions. For example, typing.TypeGuard is new in Python 3.10, but typing_extensions allows users on previous Python versions to use it too. Enable exp...
5
3
70,088,232
2021-11-23
https://stackoverflow.com/questions/70088232/calculate-centroid-of-entire-geodataframe-of-points
I would like to import some waypoints/markers from a geojson file. Then determine the centroid of all of the points. My code calculates the centroid of each point not the centroid of all points in the series. How do I calculate the centroid of all points in the series? import geopandas filepath = r'Shiloh.json' gdf = g...
first dissolve the GeoDataFrame to get a single shapely.geometry.MultiPoint object, then find the centroid: In [8]: xyz.dissolve().centroid Out[8]: 0 POINT (2756876.613 248561.582) dtype: geometry From the geopandas docs: dissolve() can be thought of as doing three things: it dissolves all the geometries within a gi...
9
16
70,039,190
2021-11-19
https://stackoverflow.com/questions/70039190/how-to-read-the-values-of-iconlayouts-reg-binary-registry-file
I want to make a program that gets the positions of the icons on the screen. And with some research I found out that the values I needed were in a registry binary file called IconLayouts (Located in HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Shell\Bags\1\Desktop) I used python to get the positions using the winreg mo...
The following code snippet could help. It's very, very simplified code combined from Windows Shellbag Forensics article and shellbags.py script (the latter is written in Python 2.7 hence unserviceable for me). import struct from winreg import * aReg = ConnectRegistry(None, HKEY_CURRENT_USER) aKey = OpenKey(aReg, r"Soft...
4
4
70,041,819
2021-11-19
https://stackoverflow.com/questions/70041819/plotly-jupyterdash-is-not-removing-irrelevant-columns-when-applying-categoryorde
I'm trying to sort the axis of my chart based on the values in the "sales" column. Once I apply fig.update_layout(yaxis={'categoryorder':'total descending'}) to my figure, the chart no longer removes irrelevant rows when filtering the dataframe by selecting the "099" value for the RadioItems callback option. code to re...
I was able to work around this issue by computing the ranking independently of the graphing step and placing the rankings into a series, rankings. I then passed the ranked series to fig.update_layout(yaxis={'categoryorder':'array', 'categoryarray':rankings['team_rank']})
4
3
70,036,378
2021-11-19
https://stackoverflow.com/questions/70036378/pytest-full-cleanup-between-tests
In a module, I have two tests: @pytest.fixture def myfixture(request): prepare_stuff() yield 1 clean_stuff() # time.sleep(10) # in doubt, I tried that, did not help def test_1(myfixture): a = somecode() assert a==1 def test_2(myfixture): b = somecode() assert b==1 case 1 When these two tests are executed individually,...
Likely something is happening in your prepare_stuff and/or clean_stuff functions. When you run tests as: pytest ./test_module.py -k "test_1 or test_2" they are running in the same execution context, same process, etc. So, if, for example, clean_stuff doesn't do a proper clean up then execution of a next test can fail. ...
6
0
70,020,874
2021-11-18
https://stackoverflow.com/questions/70020874/ffmpegs-xstack-command-results-in-out-of-sync-sound-is-it-possible-to-mix-the
I wrote a python script that generates a xstack complex filter command. The video inputs is a mixture of several formats described here: I have 2 commands generated, one for the xstack filter, and one for the audio mixing. Here is the stack command: (sorry the text doesn't wrap!) 'c:/ydl/ffmpeg.exe', '-i', 'inputX.mp4'...
I'm a bit confused as how FFMPEG handles diverse framerates It doesn't, which would cause a misalignment in your case. The vast majority of filters (any which deal with multiple sources and make use of frames, essentially), including the Concatenate filter require that be the sources have the same framerate. For the...
10
3
70,081,399
2021-11-23
https://stackoverflow.com/questions/70081399/automatically-update-python-source-code-imports
We are refactoring our code base. Old: from a.b import foo_method New: from b.d import bar_method Both methods (foo_method() and bar_method()) are the same. It just changed the name an the package. Since above example is just one example of many ways a method can be imported, I don't think a simple regular expression...
Behind the scenes, IDEs are no much more than text editors with bunch of windows and attached binaries to make different kind of jobs, like compiling, debugging, tagging code, linting, etc. Eventually one of those libraries can be used to refactor code. One such library is Jedi, but there is one that was specifically m...
6
2
70,081,767
2021-11-23
https://stackoverflow.com/questions/70081767/how-do-i-cleanly-test-equality-of-objects-in-mypy-without-producing-errors
I have the following function: import pandas as pd def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool: return left == right I get the following error when I run it through Mypy: error: Returning Any from function declared to return "bool" I believe this is because Mypy doesn't know about pd.Timestamp so treats ...
you can cast it as a bool. import pandas as pd def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool: return bool(left == right) if mypy doesn't like that you can import cast from typing and use that to cast it to a bool. import pandas as pd from typing import cast def eq(left: pd.Timestamp, right: pd.Timestamp) -> ...
9
6
70,069,026
2021-11-22
https://stackoverflow.com/questions/70069026/how-to-use-files-in-the-answer-api-of-openai
As finally OpenAI opened the GPT-3 related API publicly, I am playing with it to explore and discover his potential. I am trying the Answer API, the simple example that is in the documentation: https://beta.openai.com/docs/guides/answers I upload the .jsonl file as indicated, and I can see it succesfully uploaded with ...
After a few hours (the day after) the file metadata status changed from uploaded to processed and the file could be used in the Answer API as stated in the documentation. I think this need to be better documented in the original OpenAI API reference.
4
3
70,079,504
2021-11-23
https://stackoverflow.com/questions/70079504/django-duplicated-queries-in-nested-models-querying-with-manytomanyfield
How do I get rid of the duplicated queries as in the screenshot? I have two models as following, class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return self.name cla...
From debug toolbar output I will asume that you have two level of nesting in your Genre model (root, Level 1). I do not know if the Level 1 has any children, i.e. there are Level 2 genres, since I can't view the query results (but this is not relevant for the current problem). The root level Genres are (1, 4, 7), the L...
4
2
70,008,909
2021-11-17
https://stackoverflow.com/questions/70008909/pem-certificate-tls-verification-against-rest-api
I have been provided with a pem certificate to authenticate with a third party. Authenticating using certificates is a new concept for me. Inside are two certificates and a private key. The issuer has advised they do not support SSL verification but use TLS(1.1/1.2). I have run a script as below: import requests as req...
The issuer is using an up to date version of HTTPS - SSL is the commonly used term but TLS is the more correct one. Sounds like their setup is correct - meaning you need to call it with a trusted client certificate, as part of an HTTPS request. I would recommend doing it with the curl tool first so that you can verify ...
5
8
70,017,034
2021-11-18
https://stackoverflow.com/questions/70017034/determine-whether-the-columns-of-a-dataset-are-invariant-under-any-given-scikit
Given an sklearn tranformer t, is there a way to determine whether t changes columns/column order of any given input dataset X, without applying it to the data? For example with t = sklearn.preprocessing.StandardScaler there is a 1-to-1 mapping between the columns of X and t.transform(X), namely X[:, i] -> t.transform(...
Not all your "transformers" would have the .get_feature_names_out method. Its implementation is discussed in the sklearn github. In the same link, you can see there is, to quote @thomasjpfan, a _OneToOneFeatureMixin class used by transformers with a simple one-to-one correspondence between input and output features Res...
5
2
70,087,344
2021-11-23
https://stackoverflow.com/questions/70087344/python-in-docker-runtimeerror-cant-start-new-thread
I'm unable to debug one error myself. I'm running python 3.8.12 inside docker image on Fedora release 35 (Thirty Five) and I'm unable to spawn threads from python. It's required for boto3 transfer to run in parallel and it uses concurrent.features to do so. The simplest example which replicates my issue without any dep...
Solution to this problem was to upgrade docker from version 18.06.1-ce to 20.10.7. Why? This is because the default seccomp profile of Docker 20.10.9 is not adjusted to support the clone() syscall wrapper of glibc 2.34 adopted in Ubuntu 21.10 and Fedora 35. Source: ubuntu:21.10 and fedora:35 do not work on the latest...
36
59
70,089,199
2021-11-23
https://stackoverflow.com/questions/70089199/how-to-set-a-different-linestyle-for-each-hue-group-in-a-kdeplot-displot
How can each hue group of a seaborn.kdeplot, or seaborn.displot with kind='kde' be given a different linestyle? Both axes-level and figure-level options will accept a str for linestyle/ls, which applies to all hue groups. import seaborn as sns import matplotlib.pyplot as plt # load sample data iris = sns.load_data...
With fill=True the object to update is in .collections With fill=False the object to update is in .lines Updating the legend is fairly simple: handles = p.legend_.legendHandles[::-1] extracts and reverses the legend handles. They're reversed to update because they're in the opposite order in which the plot linestyle ...
5
8
70,087,659
2021-11-23
https://stackoverflow.com/questions/70087659/how-to-convert-multiline-json-to-single-line
I am trying to convert a multiline json to a single line json. So the existing json file I have looks like this: { "a": [ "b", "bill", "clown", "circus" ], "vers": 1.0 } When I load the file, it comes in a dictionary and not sure how to strip blank spaces in the dictionary. f = open('test.json') data = json.load(f) ...
Using the standard library json you can get: import json with open('test.json') as handle: data = json.load(handle) text = json.dumps(data, separators=(',', ':')) print(text) Result: {"a":["b","bill","clown","circus"],"vers":1.0} Remark: 1.0 is not simplified to 1, probably, because this would change the type from f...
7
10
70,081,691
2021-11-23
https://stackoverflow.com/questions/70081691/how-to-close-other-windows-when-the-main-window-is-closed-in-pyqt5
I want to close all other windows opened by the main window when the main window is closed. Please find below the min. code that I was testing: from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget import sys class AnotherWindow(QWidget): """ This "window" is a QWidget. If it ...
Implement the closeEvent: class MainWindow(QMainWindow): w = None # ... def closeEvent(self, event): if self.w: self.w.close() Note that you can also use QApplication.closeAllWindows() to close any top level window, even without having any direct reference, but if any of those windows ignores the closeEvent() the func...
9
13
70,085,655
2021-11-23
https://stackoverflow.com/questions/70085655/django-how-to-over-ride-created-date
We have a base model that sets a created and modified field: class BaseModel(models.Model): created = models.DateTimeField(_('created'), auto_now_add=True) modified = models.DateTimeField(_('modified'), auto_now=True) ... other default properties class Meta: abstract = True We use this class to extend our models: clas...
You can override the created field for your Event model with: from django.utils.timezone import now class Event(BaseModel): created = models.DateTimeField(default=now) If you do not want this to show up for ModelForms and ModelAdmins by default, you can make use of editable=False [Django-doc]: from django.utils.timezon...
4
3
70,080,062
2021-11-23
https://stackoverflow.com/questions/70080062/how-to-correctly-use-imagedatagenerator-in-keras
I am playing with augmentation of data in Keras lately and I am using basic ImageDataGenerator. I learned the hard way it is actually a generator, not iterator (because type(train_aug_ds) gives <class 'keras.preprocessing.image.DirectoryIterator'> I thought it is an iterator). I also checked few blogs about using it, b...
I think the documentation can be quite confusing and I imagine the behavior is different depending on your Tensorflow and Keras version. For example, in this post, the user is describing the exact behavior you are expecting. Generally, the flow_from_directory() method allows you to read the images directly from a direc...
4
5
70,076,213
2021-11-23
https://stackoverflow.com/questions/70076213/how-to-add-95-confidence-interval-for-a-line-chart-in-plotly
I have Benford test results, test_show Expected Counts Found Dif AbsDif Z_score Sec_Dig 0 0.119679 4318 0.080052 -0.039627 0.039627 28.347781 1 0.113890 2323 0.043066 -0.070824 0.070824 51.771489 2 0.108821 1348 0.024991 -0.083831 0.083831 62.513122 3 0.104330 1298 0.024064 -0.080266 0.080266 60.975864 4 0.100308 3060...
As of Python 3.8 you can use NormalDist to calculate a confidence interval as explained in detail here. With a slight adjustment to that approach you can include it in your setup with fig.add_traces() using two go.Scatter() traces, and then set fill='tonexty', fillcolor = 'rgba(255, 0, 0, 0.2)') for the last one like t...
5
8
70,084,903
2021-11-23
https://stackoverflow.com/questions/70084903/redis-lpop-wrong-number-of-arguments-in-python
I have a simple Redis command that does the following: redis_conn.lpop(queue_name, batch_size) According to the Redis documentation and their Python SDK documentation, this should be a valid request. And, yet, I get the following error: redis.exceptions.ResponseError: wrong number of arguments for 'lpop' command May...
Well, I was being obtuse. The documentation I linked states that the count argument is available from version 6.2. However, since I'm running Windows I don't get the newest version, ergo the failure.
5
11
70,078,170
2021-11-23
https://stackoverflow.com/questions/70078170/find-the-indices-where-a-sorted-list-of-integer-changes
Assuming a sorted list of integers as below: data = [1] * 3 + [4] * 5 + [5] * 2 + [9] * 3 # [1, 1, 1, 4, 4, 4, 4, 4, 5, 5, 9, 9, 9] I want to find the indices where the values changes, i.e. [3, 8, 10, 13] One approach is to use itertools.groupby: cursor = 0 result = [] for key, group in groupby(data): cursor += sum(1...
When it comes to asymptotic complexity I think you can improve slightly on the binary search on average when you apply a more evenly spread divide-and-conquer approach: try to first pinpoint the value-change that occurs closer to the middle of the input list, thereby splitting the range in approximately two halves, whi...
6
5
70,046,832
2021-11-20
https://stackoverflow.com/questions/70046832/collapse-a-list-of-dictionary-of-list-to-a-single-dictionary-of-list
I have data arriving as dictionaries of lists. In fact, I read in a list of them... data = [ { 'key1': [101, 102, 103], 'key2': [201, 202, 203], 'key3': [301, 302, 303], }, { 'key2': [204], 'key3': [304, 305], 'key4': [404, 405, 406], }, { 'key1': [107, 108], 'key4': [407], }, ] Each dictionary can have different keys...
I have a solution that seems to achieve good results when the lists in your dictionaries are long. Although it is not the case in your situation I still mention it. The idea as mentioned in my comments is to use append instead of extend in a first loop and then concatenate all lists in the resulting dictionary using it...
4
1
70,073,711
2021-11-22
https://stackoverflow.com/questions/70073711/is-there-a-way-extension-to-exclude-certain-lines-from-format-on-save-in-vis
I am working on a Python project where the Formatting is set to Autopep8. Is there any extension or possible settings where can define to exclude a certain line(s) from formatting when VS is set to format modified code/file on save or with keyboard shortcuts?
Add the comment # noqa to the end of each line you want VS Code to leave alone. For instance, to prevent VS Code from changing RED = 0 YELLOW = 1 to RED = 0 YELLOW = 1 just do the following: RED = 0 # noqa YELLOW = 1 # noqa
5
5
70,073,310
2021-11-22
https://stackoverflow.com/questions/70073310/return-the-indices-of-false-values-in-a-boolean-array
I feel like this is a really simple question but I can't find the solution. Given a boolean array of true/false values, I need the output of all the indices with the value "false". I have a way to do this for true: test = [ True False True True] test1 = np.where(test)[0] This returns [0,2,3], in other words the corres...
Use np.where(~test) instead of np.where(test).
4
10
70,072,867
2021-11-22
https://stackoverflow.com/questions/70072867/how-to-remove-spyders-vertical-line-on-right-side-of-editor-pane
Spyder has a text wrap feature which includes a gray line at the end of the line. How do you remove it?
On Spyder 5.0.0, You can change the line limit and remove the vertical bar by going to Settings -> Completion and linting -> Code style and formatting -> Line length -> Show vertical line at that length
10
16
70,016,169
2021-11-18
https://stackoverflow.com/questions/70016169/how-can-i-copy-a-file-from-colab-to-github-repo-directly-it-is-possible-to-sav
How can I save a file generated by colab notebook directly to github repo? It can be assumed that the notebook was opened from the github repo and can be (the same notebook) saved to the same github repo.
Google Colaboratory's integrating with github tends to be lacking, however you can run bash commands from inside the notebook. These allow you to access and modify any data generated. You'll need to generate a token on github to allow access to the repository you want to save data to. See here for how to create a perso...
8
10
70,068,407
2021-11-22
https://stackoverflow.com/questions/70068407/modulenotfounderror-no-module-named-wtforms-fields-html5
I have a flask app that uses wtforms. I have a file which does: from wtforms.fields.html5 import DateField, EmailField, TelField # rest of the file I just wanted to rebuild my docker container and now I have this error: ModuleNotFoundError: No module named 'wtforms.fields.html5' I have in my requirements.txt: flask f...
Downgrading WTForms==2.3.3 solved the issue for me. Thread referenced here.
18
8
70,071,231
2021-11-22
https://stackoverflow.com/questions/70071231/how-does-one-check-if-all-rows-in-a-dataframe-match-another-dataframe
Say you have 2 dataframes with the same columns. But say dataframe A has 10 rows, and dataframe B has 100 rows, but the 10 rows in dataframe A are in dataframe B. The 10 rows may not be in the same row numbers as dataframe B. How do we determine that those 10 rows in df A are fully contained in df B? For example. Say w...
Is a Dataframe a subset of another: You can try solving this using merge and then comparison. The inner-join of the 2 dataframes would be the same as the smaller dataframe if the second one is a superset for the first. import pandas as pd # df1 - smaller dataframe, df2 - larger dataframe df1 = pd.DataFrame({'A ': [1]...
4
3
70,069,983
2021-11-22
https://stackoverflow.com/questions/70069983/how-can-i-use-value-counts-only-for-certain-values
I want to extract how many positive reviews by brand are in a dataset which includes reviews from thousands of products. I used this code and I got a table including percentaje of positive and non-positive reviews. How can I get only the percentage of positive reviews by brand? I only want the "True" results in positiv...
You can unstack the output and slice the True (df.groupby('brand') ['positive_review'].value_counts(normalize=True) .mul(100).round(2) .unstack(fill_value=0) [True] )
4
2
70,068,720
2021-11-22
https://stackoverflow.com/questions/70068720/jupyter-shell-commands-in-a-function
I'm attempting to create a function to load Sagemaker models within a jupyter notebook using shell commands. The problem arises when I try to store the function in a utilities.py file and source it for multiple notebooks. Here are the contents of the utilities.py file that I am sourcing in a jupyter lab notebook. def g...
You can use transform_cell method of IPython's shell to transform the IPython syntax into valid plain-Python: from IPython import get_ipython ipython = get_ipython() code = ipython.transform_cell('!ls') print(code) which will show: get_ipython().system('!ls') You can use that as input for exec: exec(code) Or direct...
4
5
70,064,901
2021-11-22
https://stackoverflow.com/questions/70064901/hydra-access-name-of-config-file-from-code
I have a config tree such as: config.yaml model/ model_a.yaml model_b.yaml model_c.yaml Where config.yaml contains: # @package _global_ defaults: - _self_ - model: model_a.yaml some_var: 42 I would like to access the name of the model config file used (either the default or overridden) from my python code or from the...
The a look at the hydra.runtime.choices variable mentioned in the Configuring Hydra - Introduction page of the Hydra docs. This variable stores a mapping that describes each of the choices that Hydra has made in composing the output config. Using your example from above with model: model_a.yaml in the defaults list: # ...
6
9
70,067,588
2021-11-22
https://stackoverflow.com/questions/70067588/valueerror-input-0-of-layer-sequential-is-incompatible-with-the-layer-expect
Here is the little project of Cancer detection, and it has already has the dataset and colab code, but I get an error when I execute model.fit(x_train, y_train, epochs=1000) The error is: ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 455, 30), found shape=(None, 30) W...
The Tensorflow model expects the first dimension of the input to be the batch size, in the model declaration however they set the input shape to be the same shape as the input. To fix this you can change the input shape of the model to be the number of feature in the dataset. model.add(tf.keras.layers.Dense(256, input_...
6
5
70,062,383
2021-11-22
https://stackoverflow.com/questions/70062383/cleaner-dockerfile-for-continuumio-miniconda3-environment
I have a Python3.9 / Quart / Hypercorn microservice which runs in a conda environment configured with an environment.yml file. The base image is continuumio/miniconda3. It took a lot of hacks to get this launching because of conda init issues etc. Is there a cleaner way to get a conda environment installed and activate...
An alternative approach is described here. Basically you can activate conda environment within bash script and run you commands there. entrypoint.sh: #!/bin/bash --login # The --login ensures the bash configuration is loaded, # Temporarily disable strict mode and activate conda: set +euo pipefail conda activate ms-amaz...
4
5
70,048,874
2021-11-20
https://stackoverflow.com/questions/70048874/twitter-api-v2-403-forbidden-using-tweepy
I'm not able to authenticate using my twitter developer account even though my account active import tweepy consumer_key= 'XX1' consumer_secret= 'XX2' access_token= 'XX3' access_token_secret= 'XX4' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = t...
I found out that Essential access can use only Twitter API v2 The code should be import tweepy consumer_key= 'x' consumer_secret= 'xx' access_token= 'xxx' access_token_secret= 'xxxx' client = tweepy.Client(consumer_key= consumer_key,consumer_secret= consumer_secret,access_token= access_token,access_token_secret= access...
4
5
70,060,263
2021-11-22
https://stackoverflow.com/questions/70060263/pytube-attributeerror-nonetype-object-has-no-attribute-span
I just downloaded pytube (version 11.0.1) and started with this code snippet from here: from pytube import YouTube YouTube('https://youtu.be/9bZkp7q19f0').streams.first().download() which gives this error: AttributeError Traceback (most recent call last) <ipython-input-29-0bfa08b87614> in <module> ----> 1 YouTube('htt...
Found this issue, pytube v11.0.1. It's a little late for me, but if no one has submitted a fix tomorrow I'll check it out. in C:\Python38\lib\site-packages\pytube\parser.py Change this line: 152: func_regex = re.compile(r"function\([^)]+\)") to this: 152: func_regex = re.compile(r"function\([^)]?\)") The issue is that ...
16
17
70,059,794
2021-11-22
https://stackoverflow.com/questions/70059794/get-function-name-when-contextdecorator-is-used-as-a-decorator
I have the following context manager and decorator to time any given function or code block: import time from contextlib import ContextDecorator class timer(ContextDecorator): def __init__(self, label: str): self.label = label def __enter__(self): self.start_time = time.perf_counter() return self def __exit__(self, *ex...
If you also override the __call__() method inherited from the ContextDecorator base class in your timer class, and add a unique default value to the initializer for the label argument, you can check for that and grab the function's __name__ when it's called: import time from contextlib import ContextDecorator class tim...
7
10
70,059,478
2021-11-21
https://stackoverflow.com/questions/70059478/no-module-named-web3-even-though-i-installed-web3-py-i-am-using-a-venv
pip freeze output: aiohttp==3.8.1 aiosignal==1.2.0 alembic==1.7.5 aniso8601==9.0.1 async-timeout==4.0.1 attrs==21.2.0 base58==2.1.1 bitarray==1.2.2 certifi==2021.10.8 charset-normalizer==2.0.7 click==8.0.3 cytoolz==0.11.2 eth-abi==2.1.1 eth-account==0.5.6 eth-hash==0.3.2 eth-keyfile==0.5.1 eth-keys==0.3.3 eth-rlp==0.2....
Are you sourcing your venv before running test.py? If so, then try this, source venv/bin/activate pip uninstall web3==5.25.0 pip install web3==5.25.0 python test.py (Since your pip freeze is correct), try this as well which python This should give you the python bin that is currently being used by your shell. (Check ...
4
4
70,058,288
2021-11-21
https://stackoverflow.com/questions/70058288/how-to-write-a-function-which-has-2-nested-functions-inside-and-let-computes-sum
I have to write a function which has 2 nested functions inside and computes only sum or difference of as many numbers as we want. Every equation end with "=". I wrote sth like this but it still doesn't work. What I am doing wrong? def calculator(x: int): def operation(operator: str): def calculation(y: int): while oper...
You can also use a dictionary to define your operations, and make a very readable and simple function with space for expansion: def calc(a: int): return lambda op: { '+': lambda b: calc(a+b), '-': lambda b: calc(a-b), '/': lambda b: calc(a/b), '*': lambda b: calc(a*b), }.get(op, a) print(calc(2)('+')(3)('-')(10)('/')(1...
4
4
70,057,975
2021-11-21
https://stackoverflow.com/questions/70057975/how-to-get-cosine-similarity-of-word-embedding-from-bert-model
I was interesting in how to get the similarity of word embedding in different sentences from BERT model (actually, that means words have different meanings in different scenarios). For example: sent1 = 'I like living in New York.' sent2 = 'New York is a prosperous city.' I want to get the cos(New York, New York)'s val...
Okay let's do this. First you need to understand that BERT has 13 layers. The first layer is basically just the embedding layer that BERT gets passed during the initial training. You can use it but probably don't want to since that's essentially a static embedding and you're after a dynamic embedding. For simplicity I'...
6
23
70,055,063
2021-11-21
https://stackoverflow.com/questions/70055063/how-is-memory-handled-once-touched-for-the-first-time-in-numpy-zeros
I recently saw that when creating a numpy array via np.empty or np.zeros, the memory of that numpy array is not actually allocated by the operating system as discussed in this answer (and this question), because numpy utilizes calloc to allocate the array's memory. In fact, the OS isn't even "really" allocating that m...
OS isn't even "really" allocating that memory until you try to access it This is dependent of the target platform (typically the OS and its configuration). Some platform directly allocates page in physical memory (eg. AFAIK the XBox does as well as some embedded platforms). However, mainstream platforms actually do t...
4
3
70,045,339
2021-11-20
https://stackoverflow.com/questions/70045339/what-is-analog-of-setwindowflags-in-pyqt6
While trying to migrate pyqt5 code to pyqt6, i have occured a problem with setWindowFlags: self.setWindowFlags(Qt.WindowStaysOnTopHint) returns an error: AttributeError: type object 'Qt' has no attribute 'WindowStaysOnTopHint'. So wat is the similar in PyQt6?
QtCore.Qt.WindowType.WindowStaysOnTopHint
5
12
70,044,476
2021-11-20
https://stackoverflow.com/questions/70044476/pandas-unique-values-per-row-variable-number-of-columns-with-data
Consider the below dataframe: import pandas as pd from numpy import nan data = [ (111, nan, nan, 111), (112, 112, nan, 115), (113, nan, nan, nan), (nan, nan, nan, nan), (118, 110, 117, nan), ] df = pd.DataFrame(data, columns=[f'num{i}' for i in range(len(data[0]))]) num0 num1 num2 num3 0 111.0 NaN NaN 111.0 1 112.0 112...
Another option, albeit longer: outcome = (df.melt(ignore_index= False) # keep the index as a tracker .reset_index() # get the unique rows .drop_duplicates(subset=['index','value']) .dropna() # use this to build the new column names .assign(counter = lambda df: df.groupby('index').cumcount() + 1) .pivot('index', 'counte...
4
2
70,002,709
2021-11-17
https://stackoverflow.com/questions/70002709/how-to-apply-transaction-logic-in-fastapi-realworld-example-app
I am using nsidnev/fastapi-realworld-example-app. I need to apply transaction logic to this project. In one API, I am calling a lot of methods from repositories and doing updating, inserting and deleting operations in many tables. If there is an exception in any of these operations, how can I roll back changes? (Or if ...
nsidnev/fastapi-realworld-example-app is using asyncpg. There are two ways to use Transactions. 1. async with statement async with conn.transaction(): await repo_one.update_one(...) await repo_two.insert_two(...) await repo_three.delete_three(...) # This automatically rolls back the transaction: raise Exception 2. sta...
9
4
70,041,386
2021-11-19
https://stackoverflow.com/questions/70041386/make-a-new-column-based-on-group-by-conditionally-in-python
I have a dataframe: id group x1 A x1 B x2 A x2 A x3 B I would like to create a new column new_group with the following conditions: If there are 2 unique group values within in the same id such as group A and B from rows 1 and 2, new_group should have "two" as its value. If there are only 1 unique group values within t...
Almost there. Change filter to transform and use a condition: df['new_group'] = df.groupby("id")["group"] \ .transform(lambda x: 'two' if (x.nunique() == 2) else x) print(df) # Output: id group new_group 0 x1 A two 1 x1 B two 2 x2 A A 3 x2 A A 4 x3 B B
4
4
70,039,745
2021-11-19
https://stackoverflow.com/questions/70039745/turning-a-dataframe-into-a-nested-dictionary
I have a dataframe like below. How can I get it into a nested dictionary like Guest GuestCode ProductName Quantity Invoice No 0 Maria NaN Pro Plus Cream 2 OBFL22511 1 Maria NaN Soothe Stress Cream 1 OBFL22511 2 Sanchez OBFLG3108 Pro Plus Cream 1 OBFL22524 3 Karen OBFLG1600 Soothe Stress Cream 1 OBFL22525 4 Karen OBFLG...
my_dict = {k[0]: {k[1]: {k[2]: {p: q for p, q in row[['ProductName', 'Quantity']].values}}} for k, row in df.fillna('<NA>').groupby(['Guest', 'GuestCode', 'Invoice No'])} Output: >>> my_dict {'Karen': {'OBFLG1600': {'OBFL22525': {'Soothe Stress Cream': 1, 'Pro Plus Cream': 1}}}, 'Maria': {'<NA>': {'OBFL22511': {'Pro P...
4
4
70,031,766
2021-11-19
https://stackoverflow.com/questions/70031766/receiving-stream-encountered-http-error-403-when-using-twitter-api-what-is-c
I am very new to using the Twitter API and was testing some Python code (below) from tweepy import OAuthHandler from tweepy import Stream import twitter_credentials class StdOutListener(Stream): def on_data(self, data): print(data) return True def on_error(self, status): print(status) twitter_stream = StdOutListener( t...
If you have Essential access, you won’t be able to access Twitter API v1.1. See the FAQ section about this in Tweepy's documentation for more information.
5
1
70,027,573
2021-11-18
https://stackoverflow.com/questions/70027573/error-bars-not-displaying-seaborn-relplot
Using this code I created a seaborn plot to visualize multiple variables in a long format dataset. import pandas as pd import seaborn as sns data = {'Patient ID': [11111, 11111, 11111, 11111, 22222, 22222, 22222, 22222, 33333, 33333, 33333, 33333, 44444, 44444, 44444, 44444, 55555, 55555, 55555, 55555], 'Lab Attribute'...
Each datapoint is separated by hue, so there are no error bars because no data is being combined. Remove hue='Patient ID' to only show the mean line and error bars. Alternatively, seaborn.lineplot can be mapped onto the seaborn.relplot. By not specifying hue the API will create the error bars linestyle='' is specifie...
4
3
70,024,746
2021-11-18
https://stackoverflow.com/questions/70024746/how-to-draw-custom-error-bars-with-plotly
I have a data frame with one column that describes y-axis values and two more columns that describe the upper and lower bounds of a confidence interval. I would like to use those values to draw error bars using plotly. Now I am aware that plotly offers the possibility to draw confidence intervals (using the error_y and...
used Plotly Express to create bar chart used https://plotly.com/python/error-bars/#asymmetric-error-bars for generation of error bars using appropriate subtractions with your required outcome import pandas as pd import plotly.express as px df = pd.DataFrame( {"x": [0, 1, 2], "y": [6, 10, 2], "ci_upper": [8, 11, 2.5],...
4
6
70,021,547
2021-11-18
https://stackoverflow.com/questions/70021547/using-pytorch-tensors-with-scikit-learn
Can I use PyTorch tensors instead of NumPy arrays while working with scikit-learn? I tried some methods from scikit-learn like train_test_split and StandardScalar, and it seems to work just fine, but is there anything I should know when I'm using PyTorch tensors instead of NumPy arrays? According to this question on ht...
I don't think PyTorch tensors are directly supported by scikit-learn. But you can always get the underlying numpy array from PyTorch tensors my_nparray = my_tensor.numpy() and then use it with scikit learn functions.
6
7
70,019,337
2021-11-18
https://stackoverflow.com/questions/70019337/how-do-i-group-a-pandas-column-to-create-a-new-percentage-column
I've got a pandas dataframe that looks like this: mydict ={ 'person': ['Jenny', 'Jenny', 'David', 'David', 'Max', 'Max'], 'fruit': ['Apple', 'Orange', 'Apple', 'Orange', 'Apple', 'Orange'], 'eaten': [25, 75, 15, 5, 10, 10] } df = pd.DataFrame(mydict) person fruit eaten Jenny Apple 25 Jenny Orange 75 David Apple 15 Davi...
Use DataFrame.pivot with division by sums: df = df.pivot('person','fruit','eaten').add_suffix('_percentage') df = df.div(df.sum(axis=1), axis=0) print (df) fruit Apple_percentage Orange_percentage person David 0.75 0.25 Jenny 0.25 0.75 Max 0.50 0.50
4
6
70,003,829
2021-11-17
https://stackoverflow.com/questions/70003829/poetry-installed-but-poetry-command-not-found
I've had a million and one issues with Poetry recently. I got it fully installed and working yesterday, but after a restart of my machine I'm back to having issues with it ;( Is there anyway to have Poetry consistently recognised in my Terminal, even after reboot? System Specs: Windows 10, Visual Studio Code, Bash - ...
When I run this, after shutdown of bash Terminal: export PATH="$HOME/.poetry/bin:$PATH" poetry command is then recognised. However, this isn't enough alone; as every time I shutdown the terminal I need to run the export. Possibly needs to be saved in a file.
88
48
70,015,750
2021-11-18
https://stackoverflow.com/questions/70015750/python-typing-issue-for-child-classes
This question is to clarify my doubts related to python typing from typing import Union class ParentClass: parent_prop = 1 class ChildA(ParentClass): child_a_prop = 2 class ChildB(ParentClass): child_b_prop = 3 def method_body(val) -> ParentClass: if val: return ChildA() else: return ChildB() def another_method() -> Ch...
mypy does not do runtime analysis so it cannot guess that calling method_body with argument True will always result in a ChildA object. So the error it produces does make sense. You have to guide mypy in some way to tell him that you know what you are doing and that another_method indeed produces a ChildA object when c...
4
6
70,015,993
2021-11-18
https://stackoverflow.com/questions/70015993/what-is-the-difference-between-concatenate-and-stack-in-numpy
I am bit confused between both the methods : concatenate and stack The concatenate and stack provides exactly same output , what is the difference between both of them ? Using : concatenate import numpy as np my_arr_1 = np.array([ [1,4] , [2,7] ]) my_arr_2 = np.array([ [0,5] , [3,8] ]) join_array=np.concatenate((my_arr...
In [160]: my_arr_1 = np.array([ [1,4] , [2,7] ]) ...: my_arr_2 = np.array([ [0,5] , [3,8] ]) ...: ...: join_array=np.concatenate((my_arr_1,my_arr_2),axis=0) In [161]: join_array Out[161]: array([[1, 4], [2, 7], [0, 5], [3, 8]]) In [162]: _.shape Out[162]: (4, 2) concatenate joined the 2 arrays on an existing axis, so ...
5
6
70,015,634
2021-11-18
https://stackoverflow.com/questions/70015634/how-to-test-async-function-using-pytest
@pytest.fixture def d_service(): c = DService() return c # @pytest.mark.asyncio # tried it too async def test_get_file_list(d_service): files = await d_service.get_file_list('') print(files) However, it got the following error? collected 0 items / 1 errors =================================== ERRORS ==================...
This works for me, please try: import asyncio import pytest pytest_plugins = ('pytest_asyncio',) @pytest.mark.asyncio async def test_simple(): await asyncio.sleep(0.5) Output of pytest -v confirms it passes: collected 1 item test_async.py::test_simple PASSED And I have installed: pytest 6.2.5 pytest-asyncio 0.16.0 # ...
49
62
70,013,345
2021-11-18
https://stackoverflow.com/questions/70013345/multiple-column-groupby-with-pandas-to-find-maximum-value-for-each-group
I have a dataframe like below: Feature value frequency label age_45_and_above No 2700 negative age_45_and_above No 1707 positive age_45_and_above No 83 other age_45_and_above Yes 222 negative age_45_and_above Yes 15 positive age_45_and_above Yes 8 other age_45_and_above [Null] 323 negative age_45_...
I would do it by using merge on the grouped data. Based on this data: df = pd.DataFrame({'Feature':['age']*9+['talk']*9, 'value':(['No']*3+['Yes']*3+['[Null]']*3)*2, 'frequency':[2700,1707,83,222,15,8,323,8,5,20,170,500,210,1500,809,234,43,85], 'label':['N','P','O']*6}) Using: df.groupby(['Feature','value'],as_index=F...
5
4
70,002,365
2021-11-17
https://stackoverflow.com/questions/70002365/fillna-if-all-the-values-of-a-column-are-null-in-pandas
I have to fill a column only if all the values of that column are null. For example c df = pd.DataFrame(data = {"col1":[3, np.nan, np.nan, 21, np.nan], "col2":[4, np.nan, 12, np.nan, np.nan], "col3":[33, np.nan, 55, np.nan, np.nan], "col4":[np.nan, np.nan, np.nan, np.nan, np.nan]}) >>> df col1 col2 col3 col4 0 3.0 4.0 ...
Use indexing: df.loc[:, df.isna().all()] = 100 print(df) # Output: col1 col2 col3 col4 0 3.0 4.0 33.0 100.0 1 NaN NaN NaN 100.0 2 NaN 12.0 55.0 100.0 3 21.0 NaN NaN 100.0 4 NaN NaN NaN 100.0
4
2
69,997,857
2021-11-17
https://stackoverflow.com/questions/69997857/implementation-of-the-max-function-in-python
Consider: def my_max(*a): n = len(a) max_v = a[0] for i in range (1,n): if a[i] > max_v: max_v = a[i] return max_v def my_min(*a): n = len(a) min_v = a[0] for i in range (1,n): if a[i] < min_v: min_v = a[i] return min_v test = [7, 4, 2, 6, 8] assert max(test) == my_max(test) and min(test) == my_min(test) assert max(7, ...
Short answer: Use a star to collect the arguments in a tuple and then add a special case for a tuple of length one to handle a single iterable argument. Source material: The C code that handles the logic can be found at: https://github.com/python/cpython/blob/da20d7401de97b425897d3069f71f77b039eb16f/Python/bltinmodule....
22
46
69,919,970
2021-11-10
https://stackoverflow.com/questions/69919970/no-module-named-distutils-util-but-distutils-is-installed
I was wanting to upgrade my Python version (to 3.10 in this case), so after installing Python 3.10, I proceeded to try adding some modules I use, e.g., opencv, which ran into: python3.10 -m pip install opencv-python Output: Traceback (most recent call last): File "/usr/lib/python3.10/runpy.py", line 196, in _run_modul...
It looks like distutils has versioning, so after the following, it seems to be able to proceed. sudo apt-get install python3.10-distutils Output: Reading package lists... Done Building dependency tree Reading state information... Done ... Setting up python3.10-lib2to3 (3.10.0-1+focal1) ... Setting up python3.10-distut...
180
53
69,918,818
2021-11-10
https://stackoverflow.com/questions/69918818/how-can-i-run-python-code-after-a-dbt-run-or-a-specific-model-is-completed
I would like to be able to run an ad-hoc python script that would access and run analytics on the model calculated by a dbt run, are there any best practices around this?
We recently built a tool that could that caters very much to this scenario. It leverages the ease of referencing tables from dbt in Python-land. It's called dbt-fal. The idea is that you would define the python scripts you would like to run after your dbt models are run: # schema.yml models: - name: iris meta: owner: "...
7
5
69,933,583
2021-11-11
https://stackoverflow.com/questions/69933583/how-to-customize-bar-annotations-to-not-show-selected-values
I have the following data set: data = [6.92, 1.78, 0.0, 0.0, 3.5, 8.82, 3.06, 0.0, 0.0, 5.54, -10.8, -6.03, 0.0, 0.0, -6.8, 13.69, 8.61, 9.98, 0.0, 9.42, 4.91, 3.54, 2.62, 5.65, 1.95, 8.91, 11.46, 5.31, 6.93, 6.42] Is there a way to remove the 0.0 labels from the bar plot? I tried df = df.replace(0, "") but then I ge...
labels passed to matplotlib.pyplot.bar_label must be customized Adjust the comparison (!= 0) value or range as needed. labels = [f'{v.get_height():0.0f}' if v.get_height() != 0 else '' for v in c ] without the assignment expression (:=). See this answer for additional details and examples using .bar_label. Tested i...
5
4
69,916,682
2021-11-10
https://stackoverflow.com/questions/69916682/python-httpx-how-does-httpx-clients-connection-pooling-work
Consider this function that makes a simple GET request to an API endpoint: import httpx def check_status_without_session(url : str) -> int: response = httpx.get(url) return response.status_code Running this function will open a new TCP connection every time the function check_status_without_session is called. Now, thi...
Is there any advantage in doing it like this or is there a better way? No, there is no advantage using httpx.Client in the way you've shown. In fact the httpx.<method> API, e.g. httpx.get, does exactly the same thing! The "pool" is a feature of the transport manager held by Client, which is HTTPTransport by default. ...
6
9
69,989,521
2021-11-16
https://stackoverflow.com/questions/69989521/unexpected-types-int-int-possible-types-supportsindex-none-slice-i
What's wrong with this code: split_list = [3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600, 45] split_list2 = [None, None, None, None, None, None, None, None, None, None, None, None] result = [3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600, 45, None, None, None] for i in range(len(split_list)): split_list2[i] = split_li...
This warning is solved by updating to PyCharm to 2021.2.2. It seems to be a bug in earlier versions of the IDE's static type checker. One user reported in the comments that this bug regressed in the PyCharm 2021.2.3 release. I just tested it again using PyCharm 2022.1 Professional Edition and the bug has again been sol...
8
7
69,912,264
2021-11-10
https://stackoverflow.com/questions/69912264/python-3-9-8-fails-using-black-and-importing-typed-ast-ast3
Since updating to Python 3.9.8, we get an error while using Black in our CI pipeline. black....................................................................Failed - hook id: black - exit code: 1 Traceback (most recent call last): File "../.cache/pre-commit/repol9drvp84/py_env-python3/bin/black", line 5, in <module> ...
The initial error was a failing Python Black pipeline. Black failed because it was pinned to an older version which now fails with Python 3.9.8. Updating Black to the latest version, 21.10b0, fixed the error for me. See also typed_ast issue #169: For others who may find this in a search, I ran into this problem via bl...
28
37
69,949,591
2021-11-12
https://stackoverflow.com/questions/69949591/modulenotfounderror-no-module-named-apt-pkg-installing-deadsnakes-repository
I want to install Python 3.10 on Ubuntu 18.04 (I'm currently on Python 3.8) from the deadsnakes repository with the following set of commands I found on the internet: sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update sudo apt install python3.10 But I got the error sudo: add-apt-repository: command not found. ...
This worked for me: sudo apt-get install python3-apt --reinstall cd /usr/lib/python3/dist-packages sudo cp apt_pkg.cpython-38-x86_64-linux-gnu.so apt_pkg.so The 38 in the filename above can be different for you.
9
33
69,938,570
2021-11-12
https://stackoverflow.com/questions/69938570/md4-hashlib-support-in-python-3-8
I am trying to implement a soap client for a server that uses NTLM authentication. The libraries that I use (requests-ntlm2 which relies on ntlm-auth) implement the MD4 algorithm that lies in the core of the NTLM protocol via the standard library's hashlib. Although hashlib seems to support MD4: >>> import hashlib >>> ...
Well, it seems that there was something corrupted in my conda environment. I created a new identical one, and it's been working ever since without having to change anything else.
11
2
69,913,781
2021-11-10
https://stackoverflow.com/questions/69913781/is-it-true-that-inplace-true-activations-in-pytorch-make-sense-only-for-infere
According to the discussions on PyTorch forum : What’s the difference between nn.ReLU() and nn.ReLU(inplace=True)? Guidelines for when and why one should set inplace = True? The purpose of inplace=True is to modify the input in place, without allocating memory for additional tensor with the result of this operation. ...
nn.ReLU(inplace=True) saves memory during both training and testing. However, there are some problems we may face when we use nn.ReLU(iplace=True) while calculating gradients. Sometimes, the original values are needed when calculating gradients. Because inplace destroys some of the original values, some usages may be p...
10
11
69,955,838
2021-11-13
https://stackoverflow.com/questions/69955838/saving-model-on-tensorflow-2-7-0-with-data-augmentation-layer
I am getting an error when trying to save a model with data augmentation layers with Tensorflow version 2.7.0. Here is the code of data augmentation: input_shape_rgb = (img_height, img_width, 3) data_augmentation_rgb = tf.keras.Sequential( [ layers.RandomFlip("horizontal"), layers.RandomFlip("vertical"), layers.RandomR...
This seems to be a bug in Tensorflow 2.7 when using model.save combined with the parameter save_format="tf", which is set by default. The layers RandomFlip, RandomRotation, RandomZoom, and RandomContrast are causing the problems, since they are not serializable. Interestingly, the Rescaling layer can be saved without a...
12
11
69,969,482
2021-11-15
https://stackoverflow.com/questions/69969482/why-arent-pandas-operations-in-place
Pandas operations usually create a copy of the original dataframe. As some answers on SO point out, even when using inplace=True, a lot of operations still create a copy to operate on. Now, I think I'd be called a madman if I told my colleagues that everytime I want to, for example, apply +2 to a list, I copy the whole...
As evidenced here in the pandas documentation, "... In general we like to favor immutability where sensible." The Pandas project is in the camp of preferring immutable (stateless) objects over mutable (objects with state) to guide programmers into creating more scalable / parallelizable data processing code. They are g...
34
9
69,965,600
2021-11-14
https://stackoverflow.com/questions/69965600/importerror-dll-load-failed-while-importing-defs
I'm trying to install sentence-transformers library. But when I import it, this error pops out: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-c9f0b8c65221> in <module> ----> 1 import h5py ~\Anaconda3\envs\custom_env\lib\site-pa...
I had the same problem after a CUDA/CUdnn update that probably messed some DLLs. I did: pip uninstall h5py, which indicated a successful uninstall along with some error messages. And immediately after pip install h5py Sometimes simple solutions work.
8
4
69,921,688
2021-11-11
https://stackoverflow.com/questions/69921688/how-to-handle-formatting-a-regular-string-which-could-be-a-f-string-c0209
For the following line: print("{0: <24}".format("==> core=") + str(my_dict["core"])) I am getting following warning message: [consider-using-f-string] Formatting a regular string which could be a f-string [C0209] Could I reformat it using f-string?
You could change the code to print(f"{'==> core=': <24}{my_dict['core']}"). The cast to string is implicit.
5
6
69,983,020
2021-11-16
https://stackoverflow.com/questions/69983020/modulenotfounderror-no-module-named-taming
ModuleNotFoundError Traceback (most recent call last) <ipython-input-14-2683ccd40dcb> in <module> 16 from omegaconf import OmegaConf 17 from PIL import Image ---> 18 from taming.models import cond_transformer, vqgan 19 import taming.modules 20 import torch ModuleNotFoundError: No module named 'taming' I've tried every...
Try the following command: pip install taming-transformers
17
25
69,992,818
2021-11-16
https://stackoverflow.com/questions/69992818/efficient-way-to-map-3d-function-to-a-meshgrid-with-numpy
I have a set of data values for a scalar 3D function, arranged as inputs x,y,z in an array of shape (n,3) and the function values f(x,y,z) in an array of shape (n,). EDIT: For instance, consider the following simple function data = np.array([np.arange(n)]*3).T F = np.linalg.norm(data,axis=1)**2 I would like to convolv...
For each item of data you're scanning pixels of cuboid to check if it's inside. There is an option to skip this scan. You could calculate corresponding indices of these pixels by yourself, for example: data = np.array([[1, 2, 3], #14 (corner1) [4, 5, 6], #77 (corner2) [2.5, 3.5, 4.5], #38.75 (duplicated pixel) [2.9, 3....
5
3
69,966,739
2021-11-14
https://stackoverflow.com/questions/69966739/is-there-a-way-to-make-python-showtraceback-in-jupyter-notebooks-scrollable
Or if there are scrolling functionalities built in, to edit the scrolling settings? I tried this but it didn't work -- def test_exception(self, etype, value, tb, tb_offset=None): try: announce = Announce(etype, value) if announce.print: announce.title() announce.tips() announce.resources() announce.feedback() announce....
Try going to cell > current outputs > toggle scrolling in the Jupyter UI to enable scrolling output for a cell.
6
2
69,935,815
2021-11-11
https://stackoverflow.com/questions/69935815/how-do-i-revert-an-pip-upgrade
I did the following command just now, pip install --upgrade ipykernel However, i got Requirement already satisfied: ipykernel in ./anaconda3/lib/python3.8/site-packages (5.3.4) Collecting ipykernel Downloading ipykernel-6.5.0-py3-none-any.whl (125 kB) |████████████████████████████████| 125 kB 4.3 MB/s Collecting ipyth...
I do not believe pip keeps a history of installed packages. If you have the text output from the terminal when you did the upgrade, pip does output a list of packages that will be installed, which version you had and which version you're replacing it with. You can manually revert each package by doing pip uninstall <pa...
7
9
69,986,869
2021-11-16
https://stackoverflow.com/questions/69986869/how-to-enable-and-disable-intel-mkl-in-numpy-python
I want to test and compare Numpy matrix multiplication and Eigen decomposition performance with Intel MKL and without Intel MKL. I have installed MKL using pip install mkl (Windows 10 (64-bit), Python 3.8). I then used examples from here for matmul and eigen decompositions. How do I now enable and disable MKL in order ...
You can use different environments for the comparison of Numpy with and without MKL. In each environment you can install the needed packages(numpy with MKL or without) using package installer. Then on that environments you can run your program to compare the performance of Numpy with and without MKL. NumPy doesn’t depe...
6
5
69,986,654
2021-11-16
https://stackoverflow.com/questions/69986654/how-to-send-file-from-nodejs-to-flask-python
Hope you are doing well. I'm trying to send pdfs file from Nodejs to Flask using Axios. I read files from a directory (in the form of buffer array) and add them into formData (an npm package) and send an Axios request. const existingFile = fs.readFileSync(path) console.log(existingFile) const formData = new nodeFormDa...
I solved this issue by updating my Nodejs code. We need to convert formData file into octet/stream format. so I did minor change in my formData code : before: formData.append("file", existingFile) after: formData.append("file", fs.createReadStream(existingFile) Note: fs.createReadStream only accepts string or uint8arr...
5
1
69,958,526
2021-11-13
https://stackoverflow.com/questions/69958526/oserror-winerror-127-the-specified-procedure-could-not-be-found
While importing torch (import torch) I'm facing the following error message: OSError: [WinError 127] The specified procedure could not be found. Error loading "C:\Users\myUserName\anaconda3\lib\site-packages\torch\lib\jitbackend_test.dll" or one of its dependencies. I tried the suggestion from this article but without ...
Fortunately, after extensive research, I found a solution. Someone suggested me to create a new conda environment. And that worked for me! Solution: create new conda env by: conda create --name new-env install python: conda install python=3.8.5 run: conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pyto...
5
5
69,982,275
2021-11-15
https://stackoverflow.com/questions/69982275/plot-bar-chart-in-multiple-subplot-rows
I have a simple long-form dataset I would like to generate bar charts from. The dataframe looks like this: data = {'Year':[2019,2019,2019,2020,2020,2020,2021,2021,2021], 'Month_diff':[0,1,2,0,1,2,0,1,2], 'data': [12,10,13,16,12,18,19,45,34]} df = pd.DataFrame(data) I would like to plot a bar chart that has 3 rows, eac...
1. seaborn.catplot The simplest option for a long-form dataframe is the seaborn.catplot wrapper, as Johan said: import seaborn as sns sns.catplot(data=df, x='Month_diff', y='data', row='Year', kind='bar', height=2, aspect=4) 2. pivot + DataFrame.plot Without seaborn: pivot from long-form to wide-form (1 year per co...
5
3
69,993,959
2021-11-16
https://stackoverflow.com/questions/69993959/python-threads-difference-for-3-10-and-others
For some, simple thread related code, i.e: import threading a = 0 threads = [] def x(): global a for i in range(1_000_000): a += 1 for _ in range(10): thread = threading.Thread(target=x) threads.append(thread) thread.start() for thread in threads: thread.join() print(a) assert a == 10_000_000 We got different behaviou...
An answer from a core developer: Unintended consequence of Mark Shannon's change that refactors fast opcode dispatching: https://github.com/python/cpython/commit/4958f5d69dd2bf86866c43491caf72f774ddec97 -- the INPLACE_ADD opcode no longer uses the "slow" dispatch path that checks for interrupts and such.
31
28
69,995,292
2021-11-16
https://stackoverflow.com/questions/69995292/algorithm-question-finding-the-cheapest-flight
I recently took an interview at a company (starting with M and ending in A) which asked me this question. Still practicing my algorithms, so I was hoping someone could help me understand how to solve this problem, and these types of problems. The problem: You are given 2 arrays. For example: D = [10,7,13,12,4] R = [5,1...
Create a mono queue/stack out of the return prices array R, then you can solve it in O(n) where n is the length of D. R = [5, 12, 9, 10, 12] => [5, 9, 9, 10, 12] As you can see at each step we have access to the cheapest return flight that is possible at index i and above. Now, iterate over elements of D and look at t...
5
3
69,984,897
2021-11-16
https://stackoverflow.com/questions/69984897/current-shortcut-to-run-python-in-vs-code
I use VS Code on a Mac laptop. If I'm using Python I can run the code by pressing the little arrow in the top right, However, I can't seem to find a keyboard shortcut for this. There is an old question, How to execute Python code from within Visual Studio Code, but all the answers there seem either to be obsolete or n...
I'm using Windows so i can't give you a specific answer. But Code > Preferences > Keyboard Shortcuts, search with keyword run python file, you will get related shortcuts.
6
6
69,983,472
2021-11-16
https://stackoverflow.com/questions/69983472/how-to-satisfy-flake8-w605-invalid-escape-sequence-and-string-format-in
I have an issue in python. My original regex expression is: f"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)" (method_name is a local variable) and I got a lint warning: "[FLAKE8 W605] invalid escape sequence '\.'Arc(W605)" Which looks like recommends me to use r as the reg...
Pass in the expression: r"regex(metrics_api_failure\.prod\.[\w_]+\." + method_name + r"\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)" Essentially, use Python string concatenation to accomplish the same thing that you were doing with the brackets. Then, r"" type string escaping should work. or use a raw format string: rf"regex(...
13
27
69,950,010
2021-11-12
https://stackoverflow.com/questions/69950010/why-is-python-list-slower-when-sorted
In the following code, I create two lists with the same values: one list unsorted (s_not), the other sorted (s_yes). The values are created by randint(). I run some loop for each list and time it. import random import time for x in range(1,9): r = 10**x # do different val for the bound in randint() m = int(r/2) print("...
Cache misses. When N int objects are allocated back-to-back, the memory reserved to hold them tends to be in a contiguous chunk. So crawling over the list in allocation order tends to access the memory holding the ints' values in sequential, contiguous, increasing order too. Shuffle it, and the access pattern when craw...
77
94
69,975,474
2021-11-15
https://stackoverflow.com/questions/69975474/python-typing-abstractmethod-with-default-arguments
I'm a little confuse how I'm supposed to type a base class abstract method? In this case my base class only requires that the inheriting class implements a method named 'learn' that returns None without mandating any arguments. class MyBaseClass(ABC): @abstractmethod def learn(self, *args, **kwargs) -> None: raise NotI...
First things first, I'd ask why you want a method without known arguments. That sounds like a design problem. One solution It's fine to add new parameters to subclasses if those parameters have default values (and the base class doesn't use **kwargs), like class MyBaseClass: @abstractmethod def learn(self) -> None: rai...
5
2
69,973,873
2021-11-15
https://stackoverflow.com/questions/69973873/symbol-not-found-in-flat-namespace-ft-done-face-from-reportlab-with-python3
I have a django project using easy-thumbnail as a dependency. Installing all packages with pip is working as expected, but when I try to run my app I get this error: Invalid template library specified. ImportError raised when trying to load 'backend.templatetags.get_thumbnail': dlopen(/opt/homebrew/lib/python3.9/site-p...
I reinstalled reportlab with this command: pip install reportlab --force-reinstall --no-cache-dir --global-option=build_ext This forced pip to actually build the package and now everythings works as intended!
9
14
69,959,195
2021-11-13
https://stackoverflow.com/questions/69959195/filling-missing-values-with-mean-in-pyspark
I am trying to fill NaN values with mean using PySpark. Below is my code that I am using and following is the error that occurred: from pyspark.sql.functions import avg def fill_with_mean(df_1, exclude=set()): stats = df_1.agg(*(avg(c).alias(c) for c in df_1.columns if c not in exclude)) return df_1.na.fill(stats.first...
Based on your input data, I create my dataframe : from pyspark.sql import functions as F, Window df = spark.read.csv("./weatherAUS.csv", header=True, inferSchema=True, nullValue="NA") Then, I process the whole dataframe, excluding the columns you mentionned + the columns that cannot be replaced (date and location) exc...
6
1
69,970,569
2021-11-15
https://stackoverflow.com/questions/69970569/valueerror-unexpected-result-of-predict-function-empty-batch-outputs-pleas
I have this model : # Set random seed tf.random.set_seed(42) # Create some regression data X_regression = np.expand_dims(np.arange(0, 1000, 5), axis=0) y_regression = np.expand_dims(np.arange(100, 1100, 5), axis=0) # Split it into training and test sets X_reg_train = X_regression[:150] X_reg_test = X_regression[150:] y...
Change the axis dimension in expand_dims to 1 and slice your data like this, since it is 2D: import tensorflow as tf import numpy as np tf.random.set_seed(42) # Create some regression data X_regression = np.expand_dims(np.arange(0, 1000, 5), axis=1) y_regression = np.expand_dims(np.arange(100, 1100, 5), axis=1) # Split...
6
4
69,950,418
2021-11-13
https://stackoverflow.com/questions/69950418/get-min-and-max-values-of-categorical-variable-in-a-dataframe
I have a dataframe that looks like this: D X Y Z A 22 16 23 A 21 16 22 A 20 17 21 B 33 50 11 B 34 53 12 B 34 55 13 C 44 34 11 C 45 33 11 C 45 33 10 D 55 35 60 D 57 34 61 E 66 36 13 E 67 38 14 E 67 37 13 I want to get the minimum and maximum values of the categorical variable D across all the column values and so the o...
I believe this is a nice way of doing it and in a single line of code. Making use of join doing the operation by index and the rsuffix and lsuffix to differentiate min and max. output = df.groupby('D').min().join(df.groupby('D').max(), lsuffix='min', rsuffix='max') Outputs: Xmin Xmax Ymin Ymax Zmin Zmax D A 20 22 16 ...
17
9
69,962,789
2021-11-14
https://stackoverflow.com/questions/69962789/how-to-find-the-number-of-neighbours-pixels-in-binary-array
I am looking for an easy way to count the number of the green pixels in the image below, where the original image is the same but the green pixels are black. I tried it with numpy.diff(), but then I am counting some pixels twice. I thought about numpy.gradient() – but here I am not sure if it is the right tool. I know ...
You can use the edge detection kernel for this problem. import numpy as np from scipy.ndimage import convolve a = np.array([[0, 0, 0, 0], [0, 1, 1, 1], [0, 1, 1, 1]]) kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]) Then, we will convolve the original array with the kernel. Notice that the edges are all ne...
6
6
69,957,212
2021-11-13
https://stackoverflow.com/questions/69957212/converting-timestamp-to-epoch-milliseconds-in-pyspark
I have a dataset like the below: epoch_seconds eq_time 1636663343887 2021-11-12 02:12:23 Now, I am trying to convert the eq_time to epoch seconds which should match the value of the first column but am unable to do so. Below is my code: df = spark.sql("select '1636663343887' as epoch_seconds") df1 = df.with...
Use to_timestamp instead of from_unixtime to preserve the milliseconds part when you convert epoch to spark timestamp type. Then, to go back to timestamp in milliseconds, you can use unix_timestamp function or by casting to long type, and concatenate the result with the fraction of seconds part of the timestamp that yo...
10
8
69,960,699
2021-11-14
https://stackoverflow.com/questions/69960699/any-simpler-way-to-assign-multiple-columns-in-python-like-r-data-table
I'm wondering if there's any simpler way to assign multiple columns in Python, just like the := in R data.table. For example, in Python I would have to write like this: df['Col_A'] = df.A/df.B df['Col_B'] = df.C/df.D df['Col_C'] = df.E/df.F * 1000000 df['Col_D'] = df.G/df.H * 1000000 However, it's just one line of cod...
You can use DataFrame.assign to assign multiple columns: df = df.assign(Col_A=df.A/df.B, Col_B=df.C/df.D, Col_C=df.E/df.F*1000000, Col_D=df.G/df.H*1000000) Example: df = pd.DataFrame(np.random.random((4, 8)), columns=list('ABCDEFGH')) # A B ... H # 0 0.771211 0.238201 ... 0.311904 # 1 0.197548 0.635218 ... 0.626639 # ...
5
3
69,958,768
2021-11-13
https://stackoverflow.com/questions/69958768/what-flags-to-use-for-configure-when-building-python-from-source
I am building Python 3.10 from source on Ubuntu 18.04, following instructions from several web links, primarily the Python website (https://devguide.python.org/setup) and RealPython (https://realpython.com/installing-python/#how-to-build-python-from-source-code). I extracted Python-3.10.0.tgz into /opt/Python3.10. I ha...
Welcome to the world of Python build configuration! I'll go through the command line options to ./configure one by one. --with-pydebug is for core Python developers, not developers (like you and me) just using Python. It creates debugging symbols and slows down execution. You don't need it. --enable-optimizations is go...
8
11
69,954,697
2021-11-13
https://stackoverflow.com/questions/69954697/why-does-loc-assignment-with-two-sets-of-brackets-result-in-nan-in-a-pandas-dat
I have a DataFrame: name age 0 Paul 25 1 John 27 2 Bill 23 I know that if I enter: df[['name']] = df[['age']] I'll get the following: name age 0 25 25 1 27 27 2 23 23 But I expect the same result from the command: df.loc[:, ['name']] = df.loc[:, ['age']] But instead, I get this: ...
That's because for the loc assignment all index axes are aligned, including the columns: Since age and name do not match, there is no data to assign, hence the NaNs. You can make it work by renaming the columns: df.loc[:, ["name"]] = df.loc[:, ["age"]].rename(columns={"age": "name"}) or by accessing the numpy array: d...
13
3
69,953,800
2021-11-13
https://stackoverflow.com/questions/69953800/pip-could-not-find-a-version-that-satisfies-the-requirement
I'm having problems with installing a package using pip. I tried: pip install jurigged Causing these errors: ERROR: Could not find a version that satisfies the requirement jurigged (from versions: none) ERROR: No matching distribution found for jurigged I checked if pip was up to date which was the case. I'm on Pytho...
From PyPI, jurigged is only supported as of Python >= 3.8 (see also here) pip doesn't find anything to install because you do not meet the requirements. Upgrade to Python >= 3.8 and do the same: pip install jurigged
35
24
69,921,629
2021-11-10
https://stackoverflow.com/questions/69921629/transformers-autotokenizer-tokenize-introducing-extra-characters
I am using HuggingFace transformers AutoTokenizer to tokenize small segments of text. However this tokenization is splitting incorrectly in the middle of words and introducing # characters to the tokens. I have tried several different models with the same results. Here is an example of a piece of text and the tokens th...
This is not an error but a feature. BERT and other transformers use WordPiece tokenization algorithm that tokenizes strings into either: (1) known words; or (2) "word pieces" for unknown words in the tokenizer vocabulary. In your examle, words "CTO", "TLR", and "Pty" are not in the tokenizer vocabulary, and thus WordPi...
6
4
69,948,897
2021-11-12
https://stackoverflow.com/questions/69948897/pandas-valueerror-worksheet-index-0-is-invalid-0-worksheets-found
Simple problem that has me completely dumbfounded. I am trying to read an Excel document with pandas but I am stuck with this error: ValueError: Worksheet index 0 is invalid, 0 worksheets found My code snippet works well for all but one Excel document linked below. Is this an issue with my Excel document (which defin...
It seems there indeed is a problem with my excel file. We have not been able to figure out what though. For now the path of least resistance is simply saving as a .csv in excel and using pd.read_csv to read this instead.
14
0
69,933,345
2021-11-11
https://stackoverflow.com/questions/69933345/expected-min-ndim-2-found-ndim-1-full-shape-received-none
In my model, I have a normalizing layer for a 1 column feature array. I assume this gives a 1 ndim output: single_feature_model = keras.models.Sequential([ single_feature_normalizer, layers.Dense(1) ]) Normailaztion step: single_feature_normalizer = preprocessing.Normalization(axis=None) single_feature_normalizer.adap...
I think you need to explicitly define an input layer with your input shape, since your output layer cannot infer the shape of the tensor coming from the normalization layer: import tensorflow as tf single_feature_normalizer = tf.keras.layers.Normalization(axis=None) feature = tf.random.normal((314, 1)) single_feature_n...
6
7
69,935,149
2021-11-11
https://stackoverflow.com/questions/69935149/how-to-extract-part-of-a-string-in-pandas-column-and-make-a-new-column
I have the below pandas dataframe. d = {'col1': [1, 2,3,4,5,60,0,0,6,3,2,4],'col3': [1, 22,33,44,55,60,1,5,6,3,2,4],'Name': ['2a df a1asd_V1', 'xcd a2asd_V3','23vg aabsd_V1','dfgdf_aabsd_V0','a3as d_V1','aa bsd_V3','aasd_V4','aabsd_V4','aa_adn sd_V15',np.nan,'aasd_V12','aasd120Abs'],'Date': ['2021-06-13', '2021-06-13',...
Use str.extract with a regex and str.replace to rename values: dff['Version_short'] = dff['Name'].str.extract('_(V\d+)$').fillna('') dff['Version_long'] = dff['Version_short'].str.replace('V', 'Version ') Output: >>> dff col1 col3 Name Date Version_short Version_long 0 1 1 2a df a1asd_V1 2021-06-13 V1 Version 1 1 2 22...
7
13
69,930,036
2021-11-11
https://stackoverflow.com/questions/69930036/deprecationwarning-desired-capabilities-has-been-deprecated-please-pass-in-a-s
maybe someone met the issue... I use a custom 'chrome driver' for PyTest with 'performance' log: cap = webdriver.DesiredCapabilities.CHROME.copy() cap['goog:loggingPrefs'] = {'performance': 'ALL'} services = Service(executable_path='/usr/local/bin/chromedriver') chrome_driver = webdriver.Chrome(desired_capabilities=cap...
See below from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService options = webdriver.ChromeOptions() options.set_capability("loggingPrefs", {'performance': 'ALL'}) service = ChromeService(executable_path'/usr/local/bin/chromedriver') driver = webdriver.Chrome(service=servi...
8
11
69,928,211
2021-11-11
https://stackoverflow.com/questions/69928211/plotly-px-scatter-3d-marker-size
I have a dataframe df: x y z ... colours marker_size marker_opacity test1 0.118709 0.219099 -0.024387 ... red 100 0.5 test2 -0.344873 -0.401508 0.169995 ... blue 100 0.5 test3 -0.226923 0.021078 0.400358 ... red 100 0.5 test4 0.085421 0.098442 -0.588749 ... purple 100 0.5 test5 0.367666 0.062889 0.042783 ... green 100...
If you're looking to increase the marker size of all traces, just use: fig.update_traces(marker_size = 12) Details: The size attribute of px.scatter_3d isn't there to let you specify the size of your markers directly. But rather to let you add a fourth dimension to your scatter plot representing the varying size of a...
8
16