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
64,799,422
2020-11-12
https://stackoverflow.com/questions/64799422/python-with-sparql-client-importerror-cannot-import-name-encodestring-from
I am Python newbie. Trying to use this module https://pypi.org/project/sparql-client/ module.py from sparql import Service class MyModule: def my_method(self): s = Service('https://my-endpoint:8182/sparql', "utf-8", "GET") statement = """ MOVE uri:temp_graph TO uri:user_graph ADD uri:temp_graph TO uri:user_graph """.fo...
The problem is caused by the version of base64 module you are running while the version of sparql you have installed is dependent on a lower version of the base64 module. The sparql is dependent on base64 version built for python3.1. encodestring() and decodestring() have since been deprecated. Option 1 - Your best be...
7
13
64,846,222
2020-11-15
https://stackoverflow.com/questions/64846222/store-networkx-graph-object
I have a huge graph with about 5000 nodes that I made it with networkX. It takes about 30 seconds to create this graph each time I execute my script. After this relatively long time I can run my analysis like shortest_path and so on. My question is, is there any way to store the object of this graph in file or somethin...
As of version 2.6, methods write_gpickle and read_gpickle are deprecated. Try this instead: import pickle # save graph object to file pickle.dump(G, open('filename.pickle', 'wb')) # load graph object from file G = pickle.load(open('filename.pickle', 'rb')) Note the options 'wb' to dump and 'rb' to load in open().
13
18
64,780,251
2020-11-11
https://stackoverflow.com/questions/64780251/how-to-annotate-a-seaborn-barplot-with-the-aggregated-value
How can the following code be modified to show the mean as well as the different error bars on each bar of the bar plot? import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") a,b,c,d = [],[],[],[] for i in range(1,5): np.random.seed(i) a.append(np.random.uni...
Given the example data, for a seaborn.barplot with capped error bars, data_df must be converted from a wide format, to a tidy (long) format, which can be accomplished with pandas.DataFrame.stack or pandas.DataFrame.melt It is also important to keep in mind that a bar plot shows only the mean (or other estimator) valu...
7
16
64,837,376
2020-11-14
https://stackoverflow.com/questions/64837376/how-to-efficiently-run-multiple-pytorch-processes-models-at-once-traceback
Background I have a very small network which I want to test with different random seeds. The network barely uses 1% of my GPUs compute power so i could in theory run 50 processes at once to try many different seeds at once. Problem Unfortunately i can't even import pytorch in multiple processes. When the nr of processe...
I've looked a bit into this tonight. I don't have a solution (edit: I have a mitigation, see the edit at end), but I have a bit more information. It seems the issue is caused by NVidia fatbins (.nv_fatb) being loaded into memory. Several DLLs, such as cusolver64_xx.dll, torcha_cuda_cu.dll, and a few others, have .nv_fa...
26
30
64,781,191
2020-11-11
https://stackoverflow.com/questions/64781191/asyncio-gather-on-list-of-dict-which-has-a-field-of-coroutine
I have the following two async function from tornado.httpclient import AsyncHTTPClient async def get_categories(): # return a list of str # .... http = AsyncHTTPClient() resp = await http.fetch(....) return [....] async def get_details(category): # return a list of dict # .... http = AsyncHTTPClient() resp = await http...
gather accepts coroutine (or other awaitable) arguments and returns a tuple of their results in the same order. You are passing it a sequence of dicts some of whose values are coroutines. gather doesn't know what to do with that and attempts to treat the dicts as awaitable objects, which fails soon enough. The correct ...
6
11
64,792,295
2020-11-11
https://stackoverflow.com/questions/64792295/how-to-get-self-instance-in-mock-mock-call-args
I observe an inconsistent behavior when patching a dummy class: class A: def f(self, *args, **kwargs): pass If I patch manually the function: call_args_list = [] def mock_fn(*args, **kwargs): call_args_list.append(mock.call(*args, **kwargs)) with mock.patch.object(A, 'f', mock_fn): A().f(1, 2) print(call_args_list) # ...
with mock.patch.object(A, 'f', autospec=True) as mock_obj: A().f(1, 2) print(mock_obj.call_args_list) # [call(<__main__.A object at 0x7fb2908fc880>, 1, 2)] From the documentation: If you pass autospec=True [...] the mocked function will be turned into a bound method if it is fetched from an instance. It will have sel...
10
15
64,797,838
2020-11-12
https://stackoverflow.com/questions/64797838/libgcc-s-so-1-must-be-installed-for-pthread-cancel-to-work
I'm on python; I am trying to shut down a function running through a ThreadPoolExecutor, but the shutdown is crashing with the error: libgcc_s.so.1 must be installed for pthread_cancel to work The function is submitted with: record_future = self.executor.submit(next,primitive) primitive is an iterator that usually re...
I found a potential workaround in the Python mailing list to explicitly load libgcc_.so.1 via ctypes as follows: import ctypes libgcc_s = ctypes.CDLL('libgcc_s.so.1') One has to make sure that this is loaded before any threads are created and that the variable libgcc_s lasts until all of the threads are closed (i.e. p...
7
15
64,792,041
2020-11-11
https://stackoverflow.com/questions/64792041/white-gap-between-python-folium-map-and-jupyter-notebook-cell
How can I remove the undesired gap between the Python folium map and the next cell inside my jupyter notebook. Here the naive code to reproduce my problem : import folium m = folium.Map(width=600, height=400, location=[12, 12], zoom_start=2) m
Here the solution need to use Figure : from branca.element import Figure fig = Figure(width=600, height=400) m = folium.Map(location=[12, 12], zoom_start=2) fig.add_child(m)
12
16
64,795,881
2020-11-11
https://stackoverflow.com/questions/64795881/collapse-output-in-vs-code-jupyter-notebook-into-scrollable-window
Is there a way to show the output such as a very long data-frame in a scrollable window in VS Code Jupyter Notebook? I am aware that pressing letter "o" allows you to collapse all output. But having the scrollable window is still preferable as it allows you to check the output while referring to other windows. I also c...
Per the comments, a workaround to trigger the scrollable window is to add a print statement to the cell output. For example print("foo") at the beginning or end of a cell.
13
7
64,856,195
2020-11-16
https://stackoverflow.com/questions/64856195/what-is-tape-based-autograd-in-pytorch
I understand autograd is used to imply automatic differentiation. But what exactly is tape-based autograd in Pytorch and why there are so many discussions that affirm or deny it. For example: this In pytorch, there is no traditional sense of tape and this We don’t really build gradient tapes per se. But graphs. but...
There are different types of automatic differentiation e.g. forward-mode, reverse-mode, hybrids; (more explanation). The tape-based autograd in Pytorch simply refers to the uses of reverse-mode automatic differentiation, source. The reverse-mode auto diff is simply a technique used to compute gradients efficiently and ...
21
25
64,789,217
2020-11-11
https://stackoverflow.com/questions/64789217/how-can-i-do-a-seq2seq-task-with-pytorch-transformers-if-i-am-not-trying-to-be-a
I may be mistaken, but it seems that PyTorch Transformers are autoregressive, which is what masking is for. However, I've seen some implementations where people use just the Encoder and output that directly to a Linear layer. In my case, I'm trying to convert a spectrogram (rows are frequencies and columns are timestep...
Most of the models in Huggingface Transformers are some version of BERT and thus not autoregressive, the only exceptions are decoder-only models (GPT and similar) and sequence-to-sequence model. There are two conceptually different types of masks: one is the input mask that is specific to the input batch and the purpos...
10
2
64,876,788
2020-11-17
https://stackoverflow.com/questions/64876788/how-to-use-the-pytorch-transformer-with-multi-dimensional-sequence-to-seqence
I'm trying to go seq2seq with a Transformer model. My input and output are the same shape (torch.Size([499, 128]) where 499 is the sequence length and 128 is the number of features. My input looks like: My output looks like: My training loop is: for batch in tqdm(dataset): optimizer.zero_grad() x, y = batch x = x.to...
There are several points to be checked. As you have same output to the different inputs, I suspect that some layer zeros out all it's inputs. So check the outputs of the PositionalEncoding and also Encoder block of the Transformer, to make sure they are not constant. But before that, make sure your inputs differ (try t...
9
4
64,791,380
2020-11-11
https://stackoverflow.com/questions/64791380/can-homebrew-run-on-apple-arm-processors
I ordered a MacBook Pro equipped with an M1 ARM processor. Will I be able to run Homebrew and install dev tools like Python, Node etc..?
Yes. Now Homebrew fully supports Apple Silicon https://brew.sh/2021/02/05/homebrew-3.0.0/
6
3
64,788,656
2020-11-11
https://stackoverflow.com/questions/64788656/exe-file-made-with-pyinstaller-being-reported-as-a-virus-threat-by-windows-defen
I'm trying to create an exe using pyinstaller for a school project but, windows defender seems to report a virus threat and blocks the file. I want to send this exe to some other people but i wouldn't be able to do that unless I fix this. So these are my queries- Why does the exe file get reported as a virus? A quick s...
METHOD 1 A possible solution for this would be to encrypt your code. There are several ways of encrypting your code. But the easiest one is to use base64 or basically converting text-to-binary encoding. and you need to make sure that there is no special character because base64 only have this charachter set. You can ch...
19
19
64,833,782
2020-11-14
https://stackoverflow.com/questions/64833782/aws-lambda-keeps-returning-hello-from-lambda
I'm having some issues with AWS Lambda for Python 3.8. No matter what code I try running, AWS Lambda keeps returning the same response. I am trying to retrieve a information from a DynamoDB instance with the code below: import json import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('planets') def...
Usually this is due to one of the following reasons: You are not deploying your code changes. In the new UI, you have to explicitly Deploy your function using Orange button. You are invoking old lambda version, rather then your latest version, if you are versioning your functions. You must explicitly choose the correc...
16
36
64,878,908
2020-11-17
https://stackoverflow.com/questions/64878908/low-parallelism-when-running-apache-beam-wordcount-pipeline-on-spark-with-python
I am quite experienced with Spark cluster configuration and running Pyspark pipelines, but I'm just starting with Beam. So, I am trying to do an apple-to-apple comparison between Pyspark and the Beam python SDK on a Spark PortableRunner (running on top of the same small Spark cluster, 4 workers each with 4 cores and 8G...
It took a while, but I figured out what's the issue and a workaround. The underlying problem is in Beam's portable runner, specifically where the Beam job is translated into a Spark job. The translation code (executed by the job server) splits stages into tasks based on calls to sparkContext().defaultParallelism(). The...
6
1
64,807,850
2020-11-12
https://stackoverflow.com/questions/64807850/sqlalchemy-multiple-one-to-one-and-one-to-many-relationships
I've got two models: Game and Player. I want to have a list of all players in the Game Model, as well as one of these players in a different field. It's a flask server and a sqlite database. Here is my Player Model: class Player(db.Model): id = db.Column(db.Integer, primary_key=True) # other fields... game_id = db.Colu...
So I tried to learn SQLAlchemy a bit deeper, and found a solution. First you set the use_alter Flag to True in the one-to-one relationship: current_president_id = db.Column(db.Integer, db.ForeignKey('player.id', use_alter=True)) This makes the Warning go away. But you still need to be careful now. Because the Player m...
11
10
64,856,328
2020-11-16
https://stackoverflow.com/questions/64856328/selenium-works-on-aws-ec2-but-not-on-aws-lambda
I've looked at and tried nearly every other post on this topic with no luck. EC2 I'm using python 3.6 so I'm using the following AMI amzn-ami-hvm-2018.03.0.20181129-x86_64-gp2 (see here). Once I SSH into my EC2, I download Chrome with: sudo curl https://intoli.com/install-google-chrome.sh | bash cp -r /opt/google/chrom...
I was finally able to get it to work Python 3.7 selenium==3.14.0 headless-chromium v1.0.0-55 chromedriver 2.43 Headless-Chromium https://github.com/adieuadieu/serverless-chrome/releases/download/v1.0.0-55/stable-headless-chromium-amazonlinux-2017-03.zip Chromedriver https://chromedriver.storage.googleapis.com/2.43/chr...
8
2
64,838,803
2020-11-14
https://stackoverflow.com/questions/64838803/is-there-any-way-to-use-sagemath-on-macos-big-sur
I downloaded SageMath-9.2 on my mac, but every time I try to use the notebook by running "sage -n jupyter" on my terminal I get the following massage: Please wait while the Sage Jupyter Notebook server starts... Traceback (most recent call last): File "/Applications/SageMath-9.2.app/Contents/Resources/sage/local/lib/py...
On macOS Big Sur, there are several ways to install SageMath using Conda: https://doc.sagemath.org/html/en/installation/conda.html building from source, using as many Homebrew packages as you can: https://doc.sagemath.org/html/en/installation/source.html using CoCalc-Docker: https://github.com/sagemathinc/cocalc-docke...
6
5
64,821,850
2020-11-13
https://stackoverflow.com/questions/64821850/error-when-importing-geopandas-oserror-could-not-find-lib-c-or-load-any-of-its
I'm using Spyder with Anaconda and since MacOS last update (Big Sur 11.0.1), when doing import geopandas, I get the following error: OSError: Could not find lib c or load any of its variants []. There are several subjects on the matter (particularly this one and this one), that mainly recommends to reset the environme...
For references: I ended up reinstalling a new environment on Anaconda an it works but I wasn't able to fix the original problem.
7
0
64,871,329
2020-11-17
https://stackoverflow.com/questions/64871329/does-string-slicing-perform-copy-in-memory
I'm wondering if : a = "abcdef" b = "def" if a[3:] == b: print("something") does actually perform a copy of the "def" part of a somewhere in memory, or if the letters checking is done in-place ? Note : I'm speaking about a string, not a list (for which I know the answer)
String slicing makes a copy in CPython. Looking in the source, this operation is handled in unicodeobject.c:unicode_subscript. There is evidently a special-case to re-use memory when the step is 1, start is 0, and the entire content of the string is sliced - this goes into unicode_result_unchanged and there will not be...
44
41
64,871,133
2020-11-17
https://stackoverflow.com/questions/64871133/reportlab-installation-failed-after-upgrading-to-macos-big-sur
I'm trying to reinstall my virtual env after upgrade to MacOS Big Sur. But error appears: 4 warnings generated. clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk -I/Library/Developer/CommandLine...
this worked for me CFLAGS="-Wno-error=implicit-function-declaration" pip install reportlab
14
41
64,794,378
2020-11-11
https://stackoverflow.com/questions/64794378/correct-pb-file-to-move-tensorflow-model-into-ml-net
I have a TensorFlow model that I built (a 1D CNN) that I would now like to implement into .NET. In order to do so I need to know the Input and Output nodes. When I uploaded the model on Netron I get a different graph depending on my save method and the only one that looks correct comes from an h5 upload. Here is the mo...
This answer is made of 3 parts: going through other programs NOT going through other programs Difference between op-level graph and conceptual graph (and why Netron show you different graphs) 1. Going through other programs: ML.net needs an ONNX model, not a pb file. There is several ways to convert your model from T...
8
4
64,811,022
2020-11-12
https://stackoverflow.com/questions/64811022/how-to-import-a-python-py-file-in-jupyter-notebook
I have a Jupyter Notebook and I would like to use some credentials I have put into a config.py file. This file is in the same folder as the Jupyter Notebook. I use the line import config The problem is Jupyter replies with this message: ModuleNotFoundError: No module named 'config.py'; 'config' is not a package Thank...
After some research, I have found a way to solve my need using Dotenv Python Package: pypi.org/project/python-dotenv What needs to be done? Insert the following lines: !pip install python-dotenv # Credentials file %load_ext dotenv %dotenv import os Then place a hidden file named .env where the credentials are places. ...
8
1
64,872,560
2020-11-17
https://stackoverflow.com/questions/64872560/elementwise-maximum-of-sparse-scipy-matrix-vector-with-broadcasting
I need a fast element-wise maximum that compares each row of an n-by-m scipy sparse matrix element-wise to a sparse 1-by-m matrix. This works perfectly in Numpy using np.maximum(mat, vec) via Numpy's broadcasting. However, Scipy's .maximum() does not have broadcasting. My matrix is large, so I cannot cast it to a numpy...
A low level approach As always you can think on how a proper sparse matrix format for this operation is built up, for csr-matrices the main components are shape, data_arr,indices and ind_ptr. With these parts of the scipy.sparse.csr object it is quite straight forward but maybe a bit time consuming to implement an effi...
7
6
64,792,460
2020-11-11
https://stackoverflow.com/questions/64792460/how-to-code-a-residual-block-using-two-layers-of-a-basic-cnn-algorithm-built-wit
I have a basic CNN model's code built with tensorflow.keras library: model = Sequential() # First Layer model.add(Conv2D(64, (3,3), input_shape = (IMG_SIZE,IMG_SIZE,1))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (3,3))) # Second Layer model.add(Conv2D(64, (3,3))) model.add(Activation("relu")) mod...
Residual Block from ResNet Architecture is the following : You need to use the Keras functionnal API because Sequential models are too limited. Its implementation in Keras is : from tensorflow.keras import layers def resblock(x, kernelsize, filters): fx = layers.Conv2D(filters, kernelsize, activation='relu', padding='...
6
16
64,863,147
2020-11-16
https://stackoverflow.com/questions/64863147/python3-reload-project-that-use-python-c-api
I have a project that I built for it a Class in C (python c-api) which I extended more in the python project. The project's purpose is to provide a test framework for a C library. The test is mainly executed for each pull request of the C library. The project needs to download form a Nexus server the relevant build of ...
Finally, I found the solution by trial and error. for this example code id did the following: from utils.my_custom_py import MyCustomExtended from importlib.util import find_spec from importlib import reload from sys import modules from os import system def setup(): if system('./setup.py clean build install') > 0: rais...
6
3
64,825,967
2020-11-13
https://stackoverflow.com/questions/64825967/pygame-tic-tak-toe-logic-how-would-i-do-it
I am trying to make a tic tak toe game with pygame and I was wondering how would I do the logic here is what I have so far. VIDEO < I only have it when I click on the middle button it will display the player 2 x on the screen and then the image that is hovering over my mouse will turn into O for player 1 turn to go BUT...
Class names should normally use the CapWords convention. The name of the class should be Button rather than button. Instance Variables should be lowercase. Hence the name of an object of the typ Button should be button. Furthermore use a pygame.Rect object and collidepoint. See How do I detect if the mouse is hovering ...
8
10
64,874,129
2020-11-17
https://stackoverflow.com/questions/64874129/alpha-blending-two-images-with-opencv-and-or-numpy
I would like to add a semi-transparent rectangle filled with a solid colour to an already loaded semi-transparent PNG. Here's an example input image I am using: That image is loaded with a standard cv2.IMREAD_UNCHANGED flag so that alpha channel is perfectly preserved. That input image is stored in the image variable....
As unlut pointed out this is indeed a duplicate. Just in case someone stumbles on it, Mark Setchell's answer works pretty well: # get image dimensions imgHeight, imgWidth = image.shape[:2] # create empty overlay layer with 4 channels overlay = np.zeros((imgHeight, imgWidth, 4), dtype = "uint8") # draw semi-transparent ...
12
10
64,837,917
2020-11-14
https://stackoverflow.com/questions/64837917/build-a-basic-cube-with-numpy
I was wondering if numpy could be used to build the most basic cube model where all cross-combinations and their computed value are stored. Let's take the following example of data: AUTHOR BOOK YEAR SALES Shakespeare Hamlet 2000 104.2 Shakespeare Hamlet 2001 99.0 Shakespeare Romeo 2000 27.0 Shakespeare Romeo 2001 19.0 ...
I think numpy record arrays can be used for this task, below is my solution based on record arrays. class rec_array(): def __init__(self,author=None,book=None,year=None,sales=None): self.dtype = [('author','<U20'), ('book','<U20'),('year','<U20'),('sales',float)] self.rec_array = np.rec.fromarrays((author,book,year,sal...
18
9
64,834,321
2020-11-14
https://stackoverflow.com/questions/64834321/how-can-i-arbitarily-rotate-rearrange-etc-pdf-pages-in-python
I have an input.pdf which is "normal" (a number of pages all the same orientation and direction) and I want to create a new pdf which can arbitrarily rearrange the input pages For example: I only need rotation and scaling. Each input page will be present in its entirety as some component of the output. I don't need to...
With PyPDF2, you can write a script to accomplish this task that looks very similar to your pseudocode. Here’s some sample code, using a nightly build of the Homotopy Type Theory textbook as input: #!/usr/bin/env python3 from PyPDF2 import PdfFileReader, PdfFileWriter # matrix helper class class AfMatrix: """ A matrix ...
11
8
64,867,031
2020-11-16
https://stackoverflow.com/questions/64867031/tensorflow-error-tensorflow-core-framework-op-kernel-cc1767-op-requires-faile
I am trying to train an object detection algorithm with samples that I have labeled using Label-img. My images have dimensions of 1100 x 1100 pixels. The algorithm I am using is the Faster R-CNN Inception ResNet V2 1024x1024, found on the TensorFlow 2 Detection Model Zoo. The specs of my operation are as follows: Tens...
Take a look on this thread ( By your post I think you are read it): Resource exhausted: OOM when allocating tensor only on gpu The two possible solutions are to change config.gpu_options.per_process_gpu_memory_fraction to a greater number. The other solutions were to reinstall cuda. You can use nvidia docker. Then you ...
6
2
64,881,855
2020-11-17
https://stackoverflow.com/questions/64881855/kernel-and-recurrent-kernel-in-keras-lstms
I'm trying to draw in my mind the structure of the LSTMs and I don't understand what are the Kernel and Recurrent Kernel. According to this post in LSTMs section, the Kernel it's the four matrices that are multiplied by the inputs and Recurrent Kernel it's the four matrices that are multiplied by the hidden state, but,...
The kernels are basically the weights handled by the LSTM cell units = neurons, like the classic multilayer perceptron It is not shown in your diagram, but the input is a vector X with 1 or more values, and each value is sent in a neuron with its own weight w (the which we are going to learn with backpropagation) The f...
6
3
64,883,998
2020-11-17
https://stackoverflow.com/questions/64883998/pytorch-dataloader-shows-odd-behavior-with-string-dataset
I'm working on an NLP problem and am using PyTorch. For some reason, my dataloader is returning malformed batches. I have input data that comprises sentences and integer labels. The sentences can either a list of sentences or a list of list of tokens. I will later convert the tokens to integers in a downstream componen...
This behavior is because the default collate_fn does the following when it has to collate lists (which is the case for ['sentences']): # [...] elif isinstance(elem, container_abcs.Sequence): # check to make sure that the elements in batch have consistent size it = iter(batch) elem_size = len(next(it)) if not all(len(el...
7
5
64,882,432
2020-11-17
https://stackoverflow.com/questions/64882432/sklearn-preprocessing-standardscaler-valueerror-expected-2d-array-got-1d-array
I'm trying to work through a tutorial at http://www.semspirit.com/artificial-intelligence/machine-learning/regression/support-vector-regression/support-vector-regression-in-python/ but there's no csv file included, so I'm using my own data. Here's the code so far: import numpy as np import pandas as pd from matplotlib ...
I am guessing you have a dataframe, so you need to reassign the variable t = t.reshape(-1,1): import pandas as pd dataset = pd.DataFrame(np.random.normal(2,1,(100,4)),columns=['z','x1','x2','x3']) mags = ['x1','x2','x3'] S = np.asarray(dataset[mags]) t = np.asarray(dataset['z']) t = t.reshape(-1,1) from sklearn.preproc...
6
5
64,861,610
2020-11-16
https://stackoverflow.com/questions/64861610/easily-check-if-table-exists-with-python-sqlalchemy-on-an-sql-database
Hello I am using sqlalchemy and pandas to process some data and then save everything to a table in an sql database. I am trying to find a quick easy and standardized way to check if a table exists in a database based on a table name. I have found the has_table() function but no working examples. Does anyone has somethi...
With SQLAlchemy 1.4+ you can call has_table by using an inspect object, like so: import sqlalchemy as sa # … engine = sa.create_engine(connection_uri) insp = sa.inspect(engine) print(insp.has_table("team", schema="dbo")) # True (or False, as the case may be) For earlier versions of SQLAlchemy, see the other answer her...
12
26
64,866,338
2020-11-16
https://stackoverflow.com/questions/64866338/is-it-right-that-i-need-to-deploy-my-lambda-in-order-to-test-it
I'm writing some Python code on AWS Lambda. I haven't used AWS for a few months and I noticed that when I hit the TEST button the test no longer runs on the latest code that I've entered into the Lambda editor, even when I save the code. After some playing around I've found I need to press the DEPLOY button first, then...
Yes, The Deploy button is updating the code, The Test button just Invoke your lambda with a test Event (That can be configured)
13
11
64,873,588
2020-11-17
https://stackoverflow.com/questions/64873588/typevar-in-class-init-type-hinting
I am trying to use a TypeVar to indicate an init parameter as a certain type. But I am doing it wrong, or it might not even be possible. from typing import TypeVar T=TypeVar("T") class TestClass: def __init__(self,value:T): self._value=value a = TestClass(value=10) b = TestClass(value="abc") reveal_type(a._value) revea...
By default, using a TypeVar restricts its scope only to the method/function in which it is used as an annotation. In order to scope a TypeVar to the instance and all methods/attributes, declare the class as Generic. from typing import TypeVar, Generic T=TypeVar("T") class BaseClass(Generic[T]): # Scope of `T` is the cl...
6
9
64,823,332
2020-11-13
https://stackoverflow.com/questions/64823332/gradients-returning-none-in-huggingface-module
I want to get the gradient of an embedding layer from a pytorch/huggingface model. Here's a minimal working example: from transformers import pipeline nlp = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") responses = ["I'm having a great day!!"] hypothesis_template = 'This person feels {}' candid...
I was also very surprised of this issue. Although I have never used the library I went down and did some debugging and found out that the issue is coming from the library transformers. The problem is comming from from this line : encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states) I...
6
6
64,863,439
2020-11-16
https://stackoverflow.com/questions/64863439/tensorflow-with-gpu-how-to-see-tensorflow-is-using-the-gpu
Trying to install tensorflow to work with the GPU. Some documentation I see says tensorflow comes out of box with gpu support when detected. If so, what command can I use to see tensorflow is using my GPU? I have seen other documentation saying you need tensorflow-gpu installed. I have tried both but do not see how my ...
Go to command line and run Python The following example lists the number of visible GPUs on the host. Docs import tensorflow as tf devices = tf.config.list_physical_devices('GPU') print(len(devices)) For CUDA Docs import tensorflow as tf tf.test.is_built_with_cuda() Returns whether TensorFlow was built with CUDA (G...
6
8
64,838,511
2020-11-14
https://stackoverflow.com/questions/64838511/opencv-imshow-crashes-python-launcher-on-macos-11-0-1-big-sur
I'm trying to run some old code from gaussian filter when I find out that python launcher gets stuck trying to do the imshow function. I tried: Used Matplotlib to display a graph to see if the python launcher was the problem but no, graph showed up fine. Remove process in between just to have the image read and displ...
I resolved the issue with below steps: Install the anaconda. Install the libraries needed. Run the script, there is an error appeared as below: You might be loading two sets of Qt binaries into the same process. Check that all plugins are compiled against the right Qt binaries. Export DYLD_PRINT_LIBRARIES=1 and chec...
10
10
64,853,113
2020-11-16
https://stackoverflow.com/questions/64853113/how-to-integrate-flutter-app-with-python-code
I want to make a Flutter app that uses a Python module. What are the options to integrate Python code, how can I marshal data between the 2 runtimes, can I make a standalone app that includes Python module that doesn't depend on local Python installation? My context: I have written Python code that can mark attendance ...
I suggest you to use or convert your Python code as a Back-end code and Flutter code as Front End code. After that, your Flutter application can call the API via HTTP Requests and get data that it wants. Further reading about my suggestion: Build a REST API with Python HTTP Requests Front-End Back-End : Introduction
10
14
64,851,261
2020-11-16
https://stackoverflow.com/questions/64851261/why-is-this-memoized-euler14-implementation-so-much-slower-in-raku-than-python
I was recently playing with problem 14 of the Euler project: which number in the range 1..1_000_000 produces the longest Collatz sequence? I'm aware of the issue of having to memoize to get reasonable times, and the following piece of Python code returns an answer relatively quickly using that technique (memoize to a d...
I think the majority of the extra time is because Raku has type checks, and they aren't getting removed by the runtime type specializer. Or if they are getting removed it is after a significant amount of time. Generally the way to optimize Raku code is first to run it with the profiler: $ raku --profile test.raku Of c...
10
7
64,850,321
2020-11-15
https://stackoverflow.com/questions/64850321/windows-keeps-crashing-when-trying-to-install-pytorch-via-pip
I am currently trying to install PyTorch (using the installation commands posted on PyTorch.org for pip) and when I run the command, my computer completely freezes. I tried this multiple times with the same result. I had to restart the computer a few times as well. On my current try, I put "-v" when trying to install a...
After troubling shooting and a lot of restart, it seems like the issue came from when pip was trying to load a pre-downloaded file. Essentially, the first time I ran the installation command, pip downloaded files for pytorch but did not install pytorch due to some user privilege issue. The fix is to add --no-cache-dir ...
13
25
64,841,082
2020-11-15
https://stackoverflow.com/questions/64841082/segmentation-fault-11-python-after-upgrading-to-os-big-sur
Yesterday, my program was working perfectly fine. However, today it stopped working. I think that it may have something to do with the latest Mac OS update, as I had just installed it today. My testing code is shown below import matplotlib.pyplot as plt import numpy as np print("ehllow") zeroes = np.zeros((10,10)) plt....
Ok. Just for anyone wondering Just uninstalling and reinstalling the packages that were giving the error worked for me pip uninstall matplotlib pip install matplotlib
15
35
64,837,148
2020-11-14
https://stackoverflow.com/questions/64837148/how-to-create-a-co-occurence-matrix-of-product-orders-in-python
Let's assume we have the following dataframe that includes customer orders (order_id) and the products that the individual order contained (product_id): import pandas as pd df = pd.DataFrame({'order_id' : [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], 'product_id' : [365, 48750, 3333, 9877, 48750, 32001, 3333, 3333, 365, 11202, 36...
We start by grouping the df by order_id, and within each group calculate all possible pairs. Note we sort first by product_id so the same pairs in different groups are always in the same order import itertools all_pairs = [] for _, group in df.sort_values('product_id').groupby('order_id'): all_pairs += list(itertools.c...
9
5
64,833,580
2020-11-14
https://stackoverflow.com/questions/64833580/django-annotate-whether-field-is-null
I want to annotate a datetime field to know whether it is null. Something like: Table.objects.all().annotate(date_is_null=XXX(YYY)).values(date_is_null, .....) What do I need to replace XXX(YYY) to check if the field is null? (I'm using .values().annotate() later for a Group By, so it must be in annotate first)
You can use an ExpressionWrapper to convert a Q object to an annotated BooleanField: from django.db.models import BooleanField, ExpressionWrapper, Q Table.objects.annotate( date_is_null=ExpressionWrapper( Q(date=None), output_field=BooleanField() ) ) Here Q(date=None) is thus the condition. If the DateTimeField has a d...
12
25
64,831,017
2020-11-14
https://stackoverflow.com/questions/64831017/how-do-i-get-the-discord-py-intents-to-work
I am trying to make a bot that welcomes people to the server that it's in and all of the code works except for the on_member_join event because it utilizes the new intents. I googled on how to work with the intents and tried everything but it still isn't working. intents = discord.Intents.default() intents.members = Tr...
intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix=',', intents=intents) You also have to enable privileged intents in the developer portal A Primer Gateway to Intents
14
19
64,826,735
2020-11-13
https://stackoverflow.com/questions/64826735/pandas-write-dataframe-in-fixed-width-formatted-lines-to-a-file
Have a huge pandas dataframe (df) like this: id date a b c 0 0023 201110132120 -30 -45 7 1 0023 201110132130 -30 11 9111 2 0023 201110132140 -24 44 345 3 0023 201110132150 -19 223 11 4 0023 201110132200 -23 -3456 -1250 I need to write this dataframe to a file with special fixed-width for each field. For this i used n...
One option is to abuse header option in savetxt: formats = '%+4s %+12s %+5s %+5s %+6s' headers = [format(str(x),y.replace('%+','>')) for x, y in zip(df.columns,formats.split())] np.savetxt('out.txt', df.values, fmt=formats, header=' '.join(headers), comments='')
6
2
64,821,441
2020-11-13
https://stackoverflow.com/questions/64821441/collecting-package-metadata-repodata-json-killed
I have a fresh EC2 Ubuntu 18.04 I have installed anaconda as it it in the official guide https://docs.anaconda.com/anaconda/install/linux/ apt-get install libgl1-mesa-glx libegl1-mesa libxrandr2 libxrandr2 libxss1 libxcursor1 libxcomposite1 libasound2 libxi6 libxtst6 64 bit installation But then I have YML files that ...
Adding more RAM helps I switched from 0.5 GB to 8GB RAM than the problem disappears
10
13
64,784,834
2020-11-11
https://stackoverflow.com/questions/64784834/draw-grid-line-on-secondaryaxis-matplotlib
The question I am trying to draw grid lines from the ticks of my SecondaryAxis with ax2.grid(color=color,linestyle='--') nothing shows up on the figure, I believe I am in the same situation as for Format SecondaryAxis ticklabels Matplotlib, aren't I ? However, does anybody have a workaround for the issue without rever...
I did some digging on this topic, and opened an issue on GitHub. Here's what I found out: The SecondaryAxis is "quite new thing", added in matplotlib 3.1.0. (May 2019). Even the v.3.3.3 docs say that the secondary_xaxis() method is experimental. The SecondaryAxis inherits from _AxesBase, which is an "implementation de...
6
6
64,811,350
2020-11-12
https://stackoverflow.com/questions/64811350/is-setuptools-always-installed-in-python-by-default
Is setuptools always installed with Python? I would like to invoke setuptools at runtime outside of a setup.py script. In other words, should I include setuptools inside my package's requirements.txt and setup.py's install_requires list? Background I have noticed when creating a new virtual environment (with Python 3....
TL;DR Formally, No. Usually, Yes. the setuptools is not part of the python vanilla codebase, hence not a vanilla modules. python.org installers or mac homebrew will install it for you, but if someone compile the python by himself or install it on some linux distribution he may not get it and will need to install it by ...
8
6
64,803,895
2020-11-12
https://stackoverflow.com/questions/64803895/how-can-i-count-the-number-of-cases-in-recursive-functions
def calcPath(trace_map, x, y): n = len(trace_map) count = 0 if x > n - 1 or y > n - 1: pass elif x < n and y < n: if x + trace_map[x][y] == (n - 1) and y == (n - 1): count += 1 elif x == (n - 1) and y + trace_map[x][y] == (n - 1): count += 1 else: calcPath(trace_map, x + trace_map[x][y], y) calcPath(trace_map, x, y + t...
One of the ways to solve this is by adding the count you get from each recursive function's return. When you call the recursive function, take the count that is returned and add it to the count variable in the current scope. For example: def calcPath(trace_map, x, y): n = len(trace_map) count = 0 if x > n - 1 or y > n ...
7
6
64,800,003
2020-11-12
https://stackoverflow.com/questions/64800003/seaborn-confusion-matrix-heatmap-2-color-schemes-correct-diagonal-vs-wrong-re
Background In a confusion matrix, the diagonal represents the cases that the predicted label matches the correct label. So the diagonal is good, while all other cells are bad. To clarify what is good and what is bad in a CM for non-experts, I want to give the diagonal a different color than the rest. I want to achieve ...
You can use mask= in the call to heatmap() to choose which cells to show. Using two different masks for the diagonal and the off_diagonal cells, you can get the desired output: import numpy as np import seaborn as sns cf_matrix = np.array([[50, 2, 38], [7, 43, 32], [9, 4, 76]]) vmin = np.min(cf_matrix) vmax = np.max(cf...
10
16
64,797,192
2020-11-12
https://stackoverflow.com/questions/64797192/how-to-do-multiple-queries
I want to do a multiple queries. Here is my data frame: data = {'Name':['Penny','Ben','Benny','Mark','Ben1','Ben2','Ben3'], 'Eng':[5,1,4,3,1,2,3], 'Math':[1,5,3,2,2,2,3], 'Physics':[2,5,3,1,1,2,3], 'Sports':[4,5,2,3,1,2,3], 'Total':[12,16,12,9,5,8,12], 'Group':['A','A','A','A','A','B','B']} df1=pd.DataFrame(data, colum...
The long way to solve this – and the one with the most transparency, so best for beginners – is to create a boolean column for each filter. Then sum those columns as one final filter: df1['filter_1'] = df1['Group'].isin(['A','B']) df1['filter_2'] = df1['Math'] > df1['Eng'] df1['filter_3'] = df1['Name'].str.startswith('...
8
8
64,793,581
2020-11-11
https://stackoverflow.com/questions/64793581/python-selenium-get-page-title
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.firefox.options import Options options = Options() options.headless = True driver = webdriver.Firefo...
You need to take care of a couple of things as follows: To retrieve the Page Title instead of using a xpath you need to use driver.title The hapondo website contains JavaScript enabled elements. Solution To extract the Page Title you need to induce WebDriverWait for the title_contains() and you can use either of the...
10
8
64,782,008
2020-11-11
https://stackoverflow.com/questions/64782008/how-to-use-fastapi-depends-for-endpoint-route-in-separate-file
I have an Websocket endpoint defined in separate file, like: from starlette.endpoints import WebSocketEndpoint from connection_service import ConnectionService class WSEndpoint(WebSocketEndpoint): """Handles Websocket connections""" async def on_connect(self, websocket: WebSocket, connectionService: ConnectionService =...
TL;DR The documents seem to hint that you can only use Depends for request functions. Explanation I found a related issue #2057 in the FastAPI repo and it seems the Depends(...) only works with the requests and not anything else. I confirmed this by, from fastapi import Depends, FastAPI app = FastAPI() async def foo_fu...
6
5
64,780,009
2020-11-11
https://stackoverflow.com/questions/64780009/typeerror-cannot-index-by-location-index-with-a-non-integer-key
I am trying to re-write this code, which was written a while ago. It has multiple chuncks, hence, I separated it into smaller pieces and re-write step by step. For instance, converting .ix to iloc, etc. This chunk gives me an error: #Loop through all rows, skip the user column, and fill with similarity scores for i in ...
I'm not exactly sure what that piece of code is supposed to do (though it seems like there may be a more efficient way of doing it). Also, it looks like you are referencing j outside the j loop. However, the specific error you're getting is mostly likely related to: product_top_names = data_neighbours.iloc[product][1:1...
8
4
64,685,527
2020-11-4
https://stackoverflow.com/questions/64685527/pip-install-with-all-extras
How does one pip install with all extras? I'm aware that doing something like: pip install -e .[docs,tests,others] is an option. But, is it possible to do something like: pip install -e .[all] This question is similar to setup.py/setup.cfg install all extras. However, the answer there requires that the setup.cfg file...
pip has a --report= option which we can use: --report <file> Generate a JSON file describing what pip did to install the provided requirements. Can be used in combination with --dry-run and --ignore-installed to 'resolve' the requirements. When - is used as file name it writes to stdout. When writing to stdout, please ...
15
3
64,734,118
2020-11-8
https://stackoverflow.com/questions/64734118/environment-variable-not-loading-with-load-dotenv-in-linux
I'm trying to make a discord bot, and when I try to load a .env with load_dotenv() it doesn't work because it says Traceback (most recent call last): File "/home/fanjin/Documents/Python Projects/Discord Bot/bot.py", line 15, in <module> client.run(TOKEN) File "/home/fanjin/.local/lib/python3.8/site-packages/discord/cli...
TL:DR You need to put the full path. Use either os.path.expanduser('~/Documents/MY_PROJECT/.env') or: load_dotenv('/home/MY_USER/Documents/MY_PROJECT/.env') and it will work. Or you change your current working directory in your code editor to where the ".env" file is (which should be the project folder). Or you ope...
14
12
64,761,870
2020-11-10
https://stackoverflow.com/questions/64761870/python-subprocess-doesnt-inherit-virtual-environment
When operating with a venv on Windoes 10 if I invoke a subprocess from a file in the directory, the subprocess does not seem to have access to the venv. Is there a way to make it work? Ideally I would like the approach to be portable to Linux but I'll take whatever gets the project running. Here is my test: main.py us...
Use sys.executable in place of 'python'. sys.executable refers to the executable you're running with. This will preserve access to the virtualenv in subprocesses.
14
19
64,710,616
2020-11-6
https://stackoverflow.com/questions/64710616/whats-the-difference-between-the-write-and-typewrite-functions-in-pyautogui
I've seen the use of pyautogui.typewrite() but I can't find the documentation for it in the pyautogui docs. I did find the pyautogui.write() function in the docs and I wanted to know if they are the same thing, because from what I can see, they seem very similar.
As of version 1.0 there is no difference between write and typewrite. The write function has been chosen as the preferred invocation but currently write is just an alias for typewrite: write = typewrite # In PyAutoGUI 1.0, write() replaces typewrite().
6
10
64,766,354
2020-11-10
https://stackoverflow.com/questions/64766354/unittest-and-mocks-how-to-reset-them
I am testing a class that needs a mock in the constructor, so I usually do this: class TestActionManager(unittest.TestCase): @patch('actionlib.SimpleActionClient', return_value=create_autospec(actionlib.SimpleActionClient)) def setUp(self, mock1): self.action_manager = ActionManager() Then in this class I add all the ...
I believe what you're looking for is reset_mock Here's, in general, how it works: def test_1(self): f = MagicMock() # or whatever you're mocking f() f.assert_called_once() f.reset_mock() f() f.assert_called_once() The result will be PASSED If you want to automate, then you store the mocked thing inside setUp, and in t...
16
29
64,690,820
2020-11-5
https://stackoverflow.com/questions/64690820/does-pytest-cache-fixture-data-when-called-by-multiple-test-functions
I have unit tests that require test data. This test data is downloaded and has decently large filesize. @pytest.fixture def large_data_file(): large_data = download_some_data('some_token') return large_data # Perform tests with input data def test_foo(large_data_file): pass def test_bar(large_data_file): pass def test_...
Does pytest call on large_data_file once and use it for every unit test that uses that fixture, or does it call the large_data_file each time? It depends on the fixture scope. The default scope is function, so in your example large_data_file will be evaluated three times. If you broaden the scope, e.g. @pytest.fixtur...
29
31
64,729,944
2020-11-7
https://stackoverflow.com/questions/64729944/runtimeerror-the-current-numpy-installation-fails-to-pass-a-sanity-check-due-to
I am using Python 3.9 on Windows 10 version 2004 x64. PowerShell as Administrator. Python version: Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Install matplotlib error. pip install virtualenv virtualenv foo cd .\foo .\Scripts\active pip install numpy pip install matplo...
The temporary solution is to use NumPy 1.19.3. pip install numpy==1.19.3 From a Microsoft thread, a fix was promised to be available around January 2021. It was fixed in the KB4598291 update.
85
242
64,741,015
2020-11-8
https://stackoverflow.com/questions/64741015/plotly-how-to-color-the-fill-between-two-lines-based-on-a-condition
I want to add a fill colour between the black and blue line on my Plotly chart. I am aware this can be accomplished already with Plotly but I am not sure how to fill the chart with two colours based on conditions. The chart with the blue background is my Plotly chart. I want to make it look like the chart with the whit...
For a number of reasons (that I'm willing to explain further if you're interested) the best approach seems to be to add two traces to a go.Figure() object for each time your averages cross eachother, and then define the fill using fill='tonexty' for the second trace using: for df in dfs: fig.add_traces(go.Scatter(x=df....
16
22
64,717,302
2020-11-6
https://stackoverflow.com/questions/64717302/deprecationwarning-executable-path-has-been-deprecated-selenium-python
I am using sublime to code python scripts. The following code is for selenium in python to install the driver automatically by using the webdriver_manager package # pip install webdriver-manager from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import Chr...
This error message... DeprecationWarning: executable_path has been deprecated, please pass in a Service object ...implies that the key executable_path will be deprecated in the upcoming releases. This change is inline with the Selenium 4.0 Beta 1 changelog which mentions: Deprecate all but Options and Service argumen...
203
269
64,712,375
2020-11-6
https://stackoverflow.com/questions/64712375/fine-tune-bert-for-specific-domain-unsupervised
I want to fine-tune BERT on texts that are related to a specific domain (in my case related to engineering). The training should be unsupervised since I don't have any labels or anything. Is this possible?
What you in fact want to is continue pre-training BERT on text from your specific domain. What you do in this case is to continue training the model as masked language model, but on your domain-specific data. You can use the run_mlm.py script from the Huggingface's Transformers.
7
9
64,711,663
2020-11-6
https://stackoverflow.com/questions/64711663/setting-up-hydrogen-and-atom-with-anaconda-on-windows
I would like to run python interactively in ATOM using the Hydrogen package. I am on Windows 10. I would like to be able to initiate an ATOM session by double-clicking the ATOM icon in my toolbar or double-clicking a .py file and not have to resort to initiating ATOM via the command line. I have installed Python 3.8 vi...
I use Atom + Hydrogen extensively. And it is works which whatever python version and if it uses Anaconda, Miniconda, or simply python. Please do not mess with the system environment PATH. Maybe you are confused about which python executable is which. Or, is Atom.exe and Hydrogen using the same version, same path, of py...
9
1
64,687,757
2020-11-4
https://stackoverflow.com/questions/64687757/authorization-architecture-in-microservice-cluster
I have a project with microservice architecture (on Docker and Kubernetes), and 2 main apps are written in Python using AIOHTTP and Django (also there are and Ingress proxy, static files server, a couple more made with NginX). I'd like to split these Python apps into separate smaller microservices, but to accomplish th...
Theory Well, I found a lot of info after digging on the Internet and one and a half of consultations. There is an architectural pattern named API Gateway, which describes an entry point in a cluster, and this is just what Kubernetes Ingress does, and what I imagined in my question. In a general case, it is proxy server...
6
6
64,763,770
2020-11-10
https://stackoverflow.com/questions/64763770/why-we-use-yield-to-get-sessionlocal-in-fastapi-with-sqlalchemy
def get_db(): db = SessionLocal() try: return db finally: db.close() I got this code snipped to get Sessionlocal in fastapi with Sqlalchemy. Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield. Can someone help me?
Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield. It's a great question, the answer is, yes there's a reason to use yield instead of return. SQLAlchemy has a Connection Pooling mechanism by default. That means with yield you are creating a single sess...
23
24
64,769,205
2020-11-10
https://stackoverflow.com/questions/64769205/seaborn-lineplot-logarithmic-scale
I'm having a problem with adding a logarithmic X-axis to my plot. I want to show results based on the sample size with methods A, B and C. My dataframe result: A B C 15 0.733333 0.613333 0.733333 30 0.716667 0.693333 0.766667 59 0.733684 0.678485 0.745763 118 0.796667 0.726087 0.779661 236 0.817862 0.788333 0.838983 4...
First set the scale for the x-axis to logarithmic and then set xticks and labels as you want. sns.set_style('whitegrid') g_results=sns.lineplot(data=results,dashes=0,markers=['o','o','o']) g_results.set(xscale='log') g_results.set(xticks=sample_count) g_results.set(xticklabels=sample_count) This gives you this result:...
17
19
64,763,274
2020-11-10
https://stackoverflow.com/questions/64763274/module-cv2-cv2-has-no-attribute-dnn-superres
I am trying to upscale image (performing super resolution) using OpenCV, but I am getting this error that module 'cv2.cv2' has no attribute 'dnn_superres'. Any help would be greatly appreciated. I am using 4.4.0.44 OpenCV version. Here is the code section. import cv2 sr = cv2.dnn_superres.DnnSuperResImpl_create() sr.re...
In case you are using python3, you need to download opencv with pip3 First uninstall opencv: pip uninstall opencv-python pip uninstall opencv-contrib-python Then install latest version of opencv with pip3: pip3 install opencv-contrib-python
12
15
64,718,655
2020-11-6
https://stackoverflow.com/questions/64718655/plotly-fails-to-show-text-in-latex-labels-in-python
I am using plotly to do some plots. I need to use math symbols in the labels of the axes. Plotly shows the latex parts but not the text parts: import plotly.graph_objects as go import numpy as np x = np.array([1,2,3,4,5,6,7,8,9]) fig = go.Figure() fig.add_trace( go.Scatter( x = x, y = x**2, ) ) fig.update_layout( title...
I came across to the same problem too. The temporary solution is to quote the text in \textrm. i.e. fig.update_layout( title = 'My figure', xaxis_title = r'$\Delta t\textrm{(s)}$', yaxis_title = r'This text is not displayed/$\sqrt{2}\textrm{(ps)}$', ) The result looks like this below. <html> <head><meta charset="utf...
6
3
64,718,274
2020-11-6
https://stackoverflow.com/questions/64718274/how-to-update-python-in-raspberry-pi
I need python newest version in raspberry pi. I tried apt install python3 3.8 apt install python3 but this didnot work. And I also needed to update my raspberry pi python IDLE
First update the Raspbian. sudo apt-get update Then install the prerequisites that will make any further installation of Python and/or packages much smoother. sudo apt-get install -y build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev l...
22
60
64,680,361
2020-11-4
https://stackoverflow.com/questions/64680361/vscode-autocompletion-doesnt-work-for-jupyter-notebook
I recently started using Jupyter Notebooks on vscode but i've notices that code autocompletion doesn't work properly. If i create a regular .py file everything works correctly as you can see. It shows function signature and docstring. In both core python language and extern modules. But if i try the same in a .ipynb ...
According to your description, the reason for this situation is that different language services provide different functions such as automatic completion and prompts. For the "print()" and "np.concatenate()" you mentioned, it is recommended that you use the "Pylance" extension, which provides excellent language service...
30
33
64,760,817
2020-11-9
https://stackoverflow.com/questions/64760817/after-upgrade-raw-sql-queries-return-json-fields-as-strings-on-postgres
I am upgrading a Django app from 2.2.7 to 3.1.3. The app uses Postgres 12 & psycopg2 2.8.6. I followed the instructions and changed all my django.contrib.postgres.fields.JSONField references to django.db.models.JSONField, and made and ran the migrations. This produced no changes to my schema (which is good.) However, w...
To add to @Andrew Backer's helpful answer, this is apparently intentional. From the 3.1.1 release notes: Fixed a QuerySet.order_by() crash on PostgreSQL when ordering and grouping by JSONField with a custom decoder (#31956). As a consequence, fetching a JSONField with raw SQL now returns a string instead of pre-loaded...
8
5
64,680,438
2020-11-4
https://stackoverflow.com/questions/64680438/how-does-joblib-parallel-deal-with-global-variables
My code looks something like this: from joblib import Parallel, delayed # prediction model - 10s of megabytes on disk LARGE_MODEL = load_model('path/to/model') file_paths = glob('path/to/files/*') def do_thing(file_path): pred = LARGE_MODEL.predict(load_image(file_path)) return pred Parallel(n_jobs=2)(delayed(do_thing)...
TLDR The parent process pickles large model once. That can be made more performant by ensuring large model is a numpy array backed to a memfile. Workers can load_temporary_memmap much faster than from disk. Your job is parallelized and likely to be using joblibs._parallel_backends.LokyBackend. In joblib.parallel.Para...
6
5
64,761,911
2020-11-10
https://stackoverflow.com/questions/64761911/sqlalchemy-accessing-column-types-from-query-results
I am connecting to a SQL Server database using SQLAlchemy (with the pymssql driver). import sqlalchemy conn_string = f'mssql+pymssql://{uid}:{pwd}@{instance}/?database={db};charset=utf8' sql = 'SELECT * FROM FAKETABLE;' engine = sqlalchemy.create_engine(conn_string) connection = engine.connect() result = connection.exe...
If no, is it possible to get the SQL data types? SQL Server function sys.dm_exec_describe_first_result_set could be used to get SQL column's data type directly for provided query: SELECT column_ordinal, name, system_type_name, * FROM sys.dm_exec_describe_first_result_set('here goes query', NULL, 0) ; In your exampl...
10
3
64,760,423
2020-11-9
https://stackoverflow.com/questions/64760423/pipfile-hash-creation
I am having issues with Pipenv. I run pipenv install --dev in order to install some dependencies from a Pipfile within my project. Upon running this command, Pipenv generates an MD5 hash for a certain dependency. The error is saying that MD5 is not supported yet still generates it. I have not set any configurations on ...
Try clearing your pipenv cache: Make sure your dependencies actually do resolve. If you’re confident they are, you may need to clear your resolver cache. Run the following command: pipenv lock --clear and try again. If this does not work, try manually deleting the whole cache directory. It is usually one of the follo...
10
4
64,777,931
2020-11-10
https://stackoverflow.com/questions/64777931/what-is-the-recommended-way-to-include-properties-in-dataclasses-in-asdict-or-se
Note this is similar to How to get @property methods in asdict?. I have a (frozen) nested data structure like the following. A few properties that are (purely) dependent on the fields are defined. import copy import dataclasses import json from dataclasses import dataclass @dataclass(frozen=True) class Bar: x: int y: i...
There's no "recommended" way to include them that I know of. Here's something that seems to work and I think meets your numerous requirements. It defines a custom encoder that calls its own _asdict() method when the object is a dataclass instead of monkey-patching the (private) dataclasses._asdict_inner() function and ...
21
3
64,681,232
2020-11-4
https://stackoverflow.com/questions/64681232/why-is-it-that-input-shape-does-not-include-the-batch-dimension-when-passed-as
In Keras, why is it that input_shape does not include the batch dimension when passed as an argument to layers like Dense but DOES include the batch dimension when input_shape is passed to the build method of a model? import tensorflow as tf from tensorflow.keras.layers import Dense if __name__ == "__main__": model1 = ...
You can specify the input shape of your model in several different ways. For example by providing one of the following arguments to the first layer of your model: batch_input_shape: A tuple where the first dimension is the batch size. input_shape: A tuple that does not include the batch size, e.g., the batch size is a...
13
7
64,731,890
2020-11-7
https://stackoverflow.com/questions/64731890/fastapi-supporting-multiple-authentication-dependencies
Problem I currently have JWT dependency named jwt which makes sure it passes JWT authentication stage before hitting the endpoint like this: sample_endpoint.py: from fastapi import APIRouter, Depends, Request from JWTBearer import JWTBearer from jwt import jwks router = APIRouter() jwt = JWTBearer(jwks) @router.get("/t...
Sorry, got lost with things to do The endpoint has a unique dependency, call it check from the file check_auth ENDPOINT from fastapi import APIRouter, Depends, Request from check_auth import check from JWTBearer import JWTBearer from jwt import jwks router = APIRouter() jwt = JWTBearer(jwks) @router.get("/test_jwt", de...
15
12
64,777,820
2020-11-10
https://stackoverflow.com/questions/64777820/do-i-need-to-keep-track-of-the-asyncio-event-loop-or-can-i-just-call-asyncio-ge
I am writing a REST API using aiohttp. Some of the coroutines need to call the database using the aiomysql library. The documentation for aiomysql has the following example: import asyncio import aiomysql loop = asyncio.get_event_loop() async def test_example(): conn = await aiomysql.connect(host='127.0.0.1', port=3306...
loop argument should go. aiomysql should be updated to don't accept the loop. You can just skip loop=... in your code right now because aiomysql.connect() has the default loop=None value for the argument. In general, asyncio.get_event_loop() will be deprecated; asyncio.get_running_loop() is recommended for the usage fr...
6
2
64,775,717
2020-11-10
https://stackoverflow.com/questions/64775717/calling-generated-init-in-custom-init-override-on-dataclass
Currently I have something like this: @dataclass(frozen=True) class MyClass: a: str b: str c: str d: Dict[str, str] ...which is all well and good except dicts are mutable, so I can't use my class to key another dictionary. Instead, I'd like field d to be something like a FrozenSet[Tuple[str, str]], but I'd still like ...
You can use an InitVar and assign to d in __post_init__: @dataclass(frozen=True) class MyClass: a: str b: str c: str d: FrozenSet[Tuple[str, str]] = field(init=False) d_init: InitVar[Dict[str, str]] def __post_init__(self, d_init): object.__setattr__(self, 'd', frozenset(d_init.items()))
7
9
64,771,988
2020-11-10
https://stackoverflow.com/questions/64771988/python-selenium-click-on-button-based-on-text-inside-span-tag
I want to click on this button when <Span text is "OK": <button type="button" class="ant-btn ant-btn-primary" style="float: right;"><span>OK</span></button> The soluton would be something like that (this code don´t work because it´s not clickable): driver.find_element_by_xpath('//span[text()="OK"]').click() I found a...
So, based on your button HTML <button type="button" class="ant-btn ant-btn-primary" style="float: right;"><span>OK</span></button> I think that the following xapth would help you. //button[contains(@class, 'ant-btn-primary')]//*[contains(., 'OK')]/.. The /.. helps you traverse back 1 level; sending you to the main bu...
7
11
64,770,298
2020-11-10
https://stackoverflow.com/questions/64770298/how-to-repeat-the-body-of-a-with-statement-in-python
I want to implement a way to repeat a section of code as many times as it's needed using a context manager only, because of its pretty syntax. Like this: with try_until_success(attempts=10): command1() command2() command3() The commands must be executed once if no errors happen. And they should be executed again if an...
The problem is that the body of the with statement does not run within the call to try_until_success. That function returns an object with a __enter__ method; that __enter__ method calls and returns, then the body of the with statement is executed. There is no provision for wrapping the body in any kind of loop that wo...
7
2
64,753,347
2020-11-9
https://stackoverflow.com/questions/64753347/should-domain-model-classes-always-depend-on-primitives
Halfway through Architecture Patterns with Python, I have two questions about how should the Domain Model Classes be structured and instantiated. Assume on my Domain Model I have the class DepthMap: class DepthMap: def __init__(self, map: np.ndarray): self.map = map According to what I understood from the book, this c...
I wrote the book, so I can at least have a go at answering your question. You can use things other than primitives (str, int, boolean etc) in your domain model. Generally, although we couldn't show it in the book, your model classes will contain whole hierarchies of objects. What you want to avoid is your technical imp...
19
16
64,760,484
2020-11-9
https://stackoverflow.com/questions/64760484/plotly-how-to-display-different-color-segments-on-a-line-chart-for-specified-th
I have a multi-line graph that displays percent increase over time. I'd like to set a threshold in my code to have an upper and lower bound. If the line falls outside these bounds, I'd like that specific part of the line graph to be a different color than its parent. This is what I am doing: import plotly.express as px...
I've put together a suggestion that should do exactly what you're asking for. The following figure is produced by the code sample below. The code uses a dictionary that contains the different upper and lower limits for your different PODs along with a possibility to set different colors for different pods: lim = {'IAD'...
10
3
64,712,172
2020-11-6
https://stackoverflow.com/questions/64712172/deprecationwarning-please-use-dns-resolver-resolver-resolve
When using dns.resolver.Resolver() it returns a warning that I should use dns.resolver.Resolver.resolve () When I changed it, it further gives error: TypeError: resolve() missing 2 required positional arguments: 'self' and 'qname' This is the code: # my_resolver = dns.resolver.Resolver() my_resolver = dns.resolver.Re...
faced the same problem You should remove .resolve from my_resolver = dns.resolver.Resolver.resolve() and replace my_resolver.query() with my_resolver.resolve() Example: my_resolver = dns.resolver.Resolver() answers = my_resolver.resolve(host, "A") answer_txt = my_resolver.resolve(host, "TXT")
6
6
64,761,547
2020-11-10
https://stackoverflow.com/questions/64761547/using-python-f-string-in-a-json-list-of-data
I need to push data to a website through their API and I'm trying to find a way to use F-string to pass the variable in the data list but couldn't find a way. Here's what I've tried so far: today = datetime.date.today() tomorrow = today + datetime.timedelta(days = 1) #trying to pass *tomorrow* value with f-string below...
I would personally do something like this: import json import datetime today = datetime.date.today() tomorrow = today + datetime.timedelta(days = 1) data = [{ "date": str(tomorrow), "price": { "amount": 15100 } }] print(json.dumps(data)) Of course, after this, you can do anything you want with json.dumps(data): in you...
7
12
64,754,025
2020-11-9
https://stackoverflow.com/questions/64754025/calculate-all-distances-between-two-geodataframe-of-points-in-geopandas
This is quite simple case, but I did not find any easy way to do it so far. The idea is to get a set of distances between all the points defined in a GeoDataFrame and the ones defined in another GeoDataFrame. import geopandas as gpd import pandas as pd # random coordinates gdf_1 = gpd.GeoDataFrame(geometry=gpd.points_f...
You have to apply over each geometry in first gdf to get distance to all geometric in second gdf. import geopandas as gpd import pandas as pd # random coordinates gdf_1 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0, 0, 0], [0, 90, 120])) gdf_2 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0, 0], [0, -90])) gdf_1....
9
14
64,744,849
2020-11-9
https://stackoverflow.com/questions/64744849/how-do-i-use-scale-color-manual-in-python
I've been using ggplot for a long time now and am very comfortable using it in R. I am working in Python right now for school and I am having the toughest time understanding this error. When I try to use scale_color_manual to manually assign colors to my variable called "CellTypeOther" which has unique values 0/1, I ke...
You should use [] rather than c() in python:
6
8
64,716,495
2020-11-6
https://stackoverflow.com/questions/64716495/how-to-delete-the-file-after-a-return-fileresponsefile-path
I'm using FastAPI to receive an image, process it and then return the image as a FileResponse. But the returned file is a temporary one that need to be deleted after the endpoint return it. @app.post("/send") async def send(imagem_base64: str = Form(...)): # Convert to a Pillow image image = base64_to_image(imagem_base...
You can delete a file in a background task, as it will run after the response is sent. import os import tempfile from fastapi import FastAPI from fastapi.responses import FileResponse from starlette.background import BackgroundTasks app = FastAPI() def remove_file(path: str) -> None: os.unlink(path) @app.post("/send") ...
31
33
64,737,143
2020-11-8
https://stackoverflow.com/questions/64737143/is-there-a-networkx-algorithm-to-find-the-longest-path-from-a-source-to-a-target
I need to find a longest path in an unweighted graph from s to t. I am using NetworkX, which has an algorithm for finding a longest path in a directed, acyclic graph, but I am not able to specify the source and the target nodes. I have not been able to find any info online, but it seems like such an obvious algorithm t...
"[T]he longest path problem is the problem of finding a simple path of maximum length in a given graph."[1] NetworkX has a simple_paths module, that contains the function all_simple_paths. Below is one solution for finding the longest simple paths between two nodes. from typing import List import networkx as nx def lon...
6
4
64,733,556
2020-11-7
https://stackoverflow.com/questions/64733556/error-command-errored-out-with-exit-status-1-python-setup-py-egg-info-check-th
I'm trying to install dotenv for my discord bot with pip3 install dotenv but it keeps giving me this error: ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xmobtpdk/dotenv/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xm...
Oh it's because the package is called python-dotenv not dotenv.
26
92
64,727,187
2020-11-7
https://stackoverflow.com/questions/64727187/tqdm-multiple-progress-bars-with-nested-for-loops-in-pycharm
The below question is for people who use PyCharm. There are nested for loops and tqdm is used for progress bars corresponding to each for loop. The code is shown below. from tqdm import tqdm import time for i in tqdm(range(5), desc="i", colour='green'): for j in tqdm(range(10), desc="j", colour='red'): time.sleep(0.5) ...
The solution is two fold. Go to "Edit configurations". Click on the run/debug configuration that is being used. There should be an option "Emulate terminal in output console". Check that. Image added for reference. Along with the position argument also set the leave argument. The code should look like this. I have a...
25
37
64,723,478
2020-11-7
https://stackoverflow.com/questions/64723478/do-full-outer-join-with-pandas-merge-asof
Hi I need to align some time series data with nearest timestamps, so I think pandas.merge_asof could be a good candidate. However, it does not have an option to set how='outer' like in the standard merge method. An example can be: df1: Value1 Time 2020-07-17 14:25:03.535906075 108 2020-07-17 14:25:05.457247019 110 202...
This seems simple enough yet no direct solution. There's an option to merge again to bring in the missing rows: # enumerate the rows of `df2` to later identify which are missing df2 = df2.reset_index().assign(idx=np.arange(df2.shape[0])) (pd.merge_asof(df1.reset_index(), df2[['Time','idx']], on='Time', direction='neare...
7
2
64,697,755
2020-11-5
https://stackoverflow.com/questions/64697755/exporting-forecast-data-from-darts
I am trying to export the forecasts I made with Pytorch models in darts library to some exchangeable format like XLS or CSV. Is it somehow possible to export the predictions from the Timeseries class? How can I specify output format?
Forecasts in Darts are nothing but regular TimeSeries objects and a TimeSeries is internally represented as a pandas.DataFrame. You can access this DataFrame using series.pd_dataframe() (to get a copy of the DataFrame) or series._df directly if you want to avoid copying the DataFrame to save it. Be careful in the latte...
6
11
64,716,790
2020-11-6
https://stackoverflow.com/questions/64716790/save-pytorch-4d-tensor-as-image
I have a 4-d Pytorch tensor that I would like to save to disk as a .jpg My tensor is the following size: print(image_tensor.size()) >>>torch.Size([1, 3, 400, 711]) I can view the entire tensor as one image within my IDE: ax1.imshow(im_convert(image_tensor)) Since I am able to view the entire tensor as one image, I am...
In PyTorch this snippet is working and saving the image: from torchvision.utils import save_image import torch import torchvision tensor= torch.rand(2, 3, 400, 711) img1 = tensor[0] save_image(img1, 'img1.png') Before saving the image can you check the shape of the img1 in any case something happened.
6
15