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 |
|---|---|---|---|---|---|---|
61,122,395 | 2020-4-9 | https://stackoverflow.com/questions/61122395/is-it-possible-to-test-a-while-true-loop-with-pytest-i-try-with-a-timeout | I have a python function foo with a while True loop inside. For background: It is expected do stream info from the web, do some writing and run indefinitely. The asserts test if the writing was done correctly. Clearly I need it to stop sometime, in order to test. What I did was to run via multirpocessing and introduce ... | Break out the functionality you want to test into a helper method. Test the helper method. def scrape_web_info(url): data = get_it(url) return data # In production: while True: scrape_web_info(...) # During test: def test_web_info(): assert scrape_web_info(...) == ... | 9 | 14 |
61,122,276 | 2020-4-9 | https://stackoverflow.com/questions/61122276/keras-not-training-on-entire-dataset | So I've been following Google's official tensorflow guide and trying to build a simple neural network using Keras. But when it comes to training the model, it does not use the entire dataset (with 60000 entries) and instead uses only 1875 entries for training. Any possible fix? import tensorflow as tf from tensorflow i... | The number 1875 shown during fitting the model is not the training samples; it is the number of batches. model.fit includes an optional argument batch_size, which, according to the documentation: If unspecified, batch_size will default to 32. So, what happens here is - you fit with the default batch size of 32 (since... | 16 | 25 |
61,114,822 | 2020-4-9 | https://stackoverflow.com/questions/61114822/invoking-google-cloud-function-from-python-using-service-account-for-authenticat | I have a cloud function with trigger type set to HTTP and also have a service account which is having permissions to Invoke the cloud function. I want to invoke the cloud function from a python script. I am using the following script to invoke the function: from google.oauth2 import service_account from google.auth.tra... | To be able to call your cloud function you need an ID Token against a Cloud Functions end point from google.oauth2 import service_account from google.auth.transport.requests import AuthorizedSession url = 'https://test-123456.cloudfunctions.net/my-cloud-function' creds = service_account.IDTokenCredentials.from_service_... | 8 | 12 |
61,114,520 | 2020-4-9 | https://stackoverflow.com/questions/61114520/how-to-fix-valueerror-multiclass-format-is-not-supported | This is my code and I try to calculate ROC score but I have a problem with ValueError: multiclass format is not supported. I'm already looking sci-kit learn but it doesn't help. In the end, I'm still have ValueError: multiclass format is not supported. This is my code from sklearn.tree import DecisionTreeClassifier fro... | From the docs, roc_curve: "Note: this implementation is restricted to the binary classification task." Are your label classes (y) either 1 or 0? If not, I think you have to add the pos_label parameter to your roc_curve call. fprate, tprate, thresholds = roc_curve(test_Y, pred_y, pos_label='your_label') Or: test_Y = yo... | 10 | 7 |
61,114,350 | 2020-4-9 | https://stackoverflow.com/questions/61114350/error-blahfile-is-not-utf-8-encoded-saving-disabled | So, I'm trying to write a gzip file, actually from the net, but to simplify I wrote some very basic test. import gzip LINES = [b'I am a test line' for _ in range(100_000)] f = gzip.open('./test.text.gz', 'wb') for line in LINES: f.write(line) f.close() It runs great, and I can see in Jupyter that it has created the te... | The very simple answer to this is none of the above. This is a very misleading error message, especially when the code you've written was designed to save a binary file with a weird extension. What this actually means is ... I HAVE NO IDEA HOW TO DISPLAY THIS DATA ! - Yours Jupyter So, go to your File Explorer, Finde... | 19 | 50 |
61,110,188 | 2020-4-8 | https://stackoverflow.com/questions/61110188/how-to-display-a-gif-in-jupyter-notebook-using-google-colab | I am using google colab and would like to embed a gif. Does anyone know how to do this? I am using the code below and it is not animating the gif in the notebook. I would like the notebook to be interactive so that one can see what the code animates without having to run it. I found many ways to do so that did not wor... | For external gif, you can use Jupyter's display as @knoop's answer. from IPython.display import Image Image(url='https://upload.wikimedia.org/wikipedia/commons/e/e3/Animhorse.gif') But for a local file, you need to read the bytes and display it. !wget https://upload.wikimedia.org/wikipedia/commons/e/e3/Animhorse.gif I... | 11 | 28 |
61,108,376 | 2020-4-8 | https://stackoverflow.com/questions/61108376/force-dask-to-parquet-to-write-single-file | When using dask.to_parquet(df, filename) a subfolder filename is created and several files are written to that folder, whereas pandas.to_parquet(df, filename) writes exactly one file. Can I use dask's to_parquet (without using compute() to create a pandas df) to just write a single file? | Writing to a single file is very hard within a parallelism system. Sorry, such an option is not offered by Dask (nor probably any other parallel processing library). You could in theory perform the operation with a non-trivial amount of work on your part: you would need to iterate through the partitions of your datafra... | 7 | 2 |
61,104,138 | 2020-4-8 | https://stackoverflow.com/questions/61104138/how-i-can-swap-3-dimensions-with-each-other-in-pytorch | I have a a= torch.randn(28, 28, 8) and I want to swap dimensions (0, 1, 2) to (2, 0, 1). I tried b = a.transpose(2, 0, 1) , but I received this error: TypeError: transpose() received an invalid combination of arguments - got (int, int, int), but expected one of: * (name dim0, name dim1) * (int dim0, int dim1) Is there... | You can use Pytorch's permute() function to swap all at once, >>>a = torch.randn(28, 28, 8) >>>b = a.permute(2, 0, 1) >>>b.shape torch.Size([8, 28, 28]) | 8 | 9 |
61,104,317 | 2020-4-8 | https://stackoverflow.com/questions/61104317/modulenotfounderror-no-module-named-tf | I'm having problem with tensorflow. I want to use ImageDataGenerator, but I'm receiving error ModuleNotFoundError: No module named 'tf'. Not sure what is the problem. I added this tf.version to test will it work, and it shows the version of tensorflow. import tensorflow as tf from tensorflow import keras print(tf.__ve... | The line import tensorflow as tf means you are importing tensorflow with an alias as tf to call it modules/functions. You cannot use the alias to import other modules. For your case, if you call directly tf.keras.preprocessing.image.ImageDataGenerator(...) then it will work. or you need to import the module wit... | 10 | 19 |
61,101,919 | 2020-4-8 | https://stackoverflow.com/questions/61101919/how-can-i-add-an-element-to-a-pytorch-tensor-along-a-certain-dimension | I have a tensor inps, which has a size of [64, 161, 1] and I have some new data d which has a size of [64, 161]. How can I add d to inps such that the new size is [64, 161, 2]? | There is a cleaner way by using .unsqueeze() and torch.cat(), which makes direct use of the PyTorch interface: import torch # create two sample vectors inps = torch.randn([64, 161, 1]) d = torch.randn([64, 161]) # bring d into the same format, and then concatenate tensors new_inps = torch.cat((inps, d.unsqueeze(2)), di... | 7 | 12 |
61,097,665 | 2020-4-8 | https://stackoverflow.com/questions/61097665/no-such-file-or-directory-but-file-exists | I'm writing a python script where I need to open a ".txt" folder and analyse the text in there. I have saved this ".txt" document in the same folder as my Python script. But, when I go to open the file; file = open("words.txt",'r') I get the error: No such file or directory: 'words.txt'. I don't understand why this i... | Maby it's because your current working directory is different from the directory your files are stored. Try giving the full path to the file file = open("<full_path>\words.txt",'r') | 10 | 12 |
61,096,522 | 2020-4-8 | https://stackoverflow.com/questions/61096522/pytorch-slice-matrix-with-vector | Say I have one matrix and one vector as follows: import torch x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) y = torch.tensor([0, 2, 1]) is there a way to slice it x[y] so the result is: res = [1, 6, 8] So basically I take the first element of y and take the element in x that corresponds to the first row and the... | You can specify the corresponding row index as: import torch x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) y = torch.tensor([0, 2, 1]) x[range(x.shape[0]), y] tensor([1, 6, 8]) | 15 | 15 |
61,037,557 | 2020-4-5 | https://stackoverflow.com/questions/61037557/should-i-commit-lock-file-changes-separately-what-should-i-write-for-the-commi | I'm using poetry for my Python package manager but I believe this would apply to any programming practices. I've been doing this without knowing exactly what I'm doing, or how I should be doing. When you use a package manager and install a new package, there's usually a .lock file change to keep your build determinis... | Disclaimer Please refer to this answer for the official stance and justification on the topic, which should be the top post in this thread. Below is my original answer, which I'll leave as it was. The official recommendation of the poetry maintainers is to commit the lockfile if you develop a deployable application (a... | 51 | 45 |
61,019,498 | 2020-4-3 | https://stackoverflow.com/questions/61019498/flake8-linting-for-databricks-python-code-in-github-using-workflows | I have my databricks python code in github. I setup a basic workflow to lint the python code using flake8. This fails because the names that are implicitly available to my script (like spark, sc, dbutils, getArgument etc) when it runs on databricks are not available when flake8 lints it outside databricks (in github ub... | TL;DR Don't use the built-in variable dbutils in code that would need to run locally (IDE, Unit tests, ...) and in Databricks (production). Create your own instance of DBUtils class instead. Here is what we ended up doing: Created a new dbk_utils.py from pyspark.sql import SparkSession def get_dbutils(spark: SparkSess... | 8 | 1 |
60,987,997 | 2020-4-2 | https://stackoverflow.com/questions/60987997/why-torch-cuda-is-available-returns-false-even-after-installing-pytorch-with | On a Windows 10 PC with an NVidia GeForce 820M I installed CUDA 9.2 and cudnn 7.1 successfully, and then installed PyTorch using the instructions at pytorch.org: pip install torch==1.4.0+cu92 torchvision==0.5.0+cu92 -f https://download.pytorch.org/whl/torch_stable.html But I get: >>> import torch >>> torch.cuda.is_ava... | Your graphics card does not support CUDA 9.0. Since I've seen a lot of questions that refer to issues like this I'm writing a broad answer on how to check if your system is compatible with CUDA, specifically targeted at using PyTorch with CUDA support. Various circumstance-dependent options for resolving issues are des... | 130 | 244 |
61,079,178 | 2020-4-7 | https://stackoverflow.com/questions/61079178/how-to-include-git-branch-in-installing-from-requirements-in-python | Hi I need to install from a branch of a git repo. I want to include it on the requirements.txt so that it would install using the command pip install -r requirements.txt What I know is how to install from master branch (See git ssh entry below): This is my requirements.txt networkx==2.4 numpy==1.18.1 opencv-python==4.2... | According to the document, you can add branch name or commit hash after @: git+ssh://git@gitlab.com/project/project-utils.git@1-fix-test | 9 | 12 |
61,038,373 | 2020-4-5 | https://stackoverflow.com/questions/61038373/should-i-use-python-magic-methods-directly | I heard from one guy that you should not use magic methods directly. and I think in some use cases I would have to use magic methods directly. So experienced devs, should I use python magic methods directly? | I intended to show some benefits of not using magic methods directly: 1- Readability: Using built-in functions like len() is much more readable than its relevant magic/special method __len__(). Imagine a source code full of only magic methods instead of built-in function... thousands of underscores... 2- Comparison op... | 9 | 12 |
60,969,987 | 2020-4-1 | https://stackoverflow.com/questions/60969987/how-can-i-save-the-original-index-after-sorting-a-list | Let's say I have the following array: a = [4,2,3,1,4] Then I sort it: b = sorted(A) = [1,2,3,4,4] How could I have a list that map where each number was, ex: position(b,a) = [3,1,2,0,4] to clarify this list contains the positions not values) (ps' also taking in account that first 4 was in position 0) | b = sorted(enumerate(a), key=lambda i: i[1]) This results is a list of tuples, the first item of which is the original index and second of which is the value: [(3, 1), (1, 2), (2, 3), (0, 4), (4, 4)] | 8 | 14 |
61,028,232 | 2020-4-4 | https://stackoverflow.com/questions/61028232/how-to-find-which-library-prevents-updating-a-package-in-conda | I have set up couple of environments with Data Science libraries like pandas, numpy, matplotlib, scikit-learn, tensorflow etc.. However I cannot update some packages to the latest version. E.g. conda update pandas will tell me I have the latest version available however I know for sure the latest version is 1.+ (mine ... | There is a way to do it using the drop-in replacement mamba. All you have to do is provide the version of the package you want to update to, and mamba will tell you what's preventing it from updating. E.g., in my case, I wanted to update snakemake to version > 7. But mamba update snakemake only gave me 6.15. So I ran: ... | 12 | 3 |
61,044,136 | 2020-4-5 | https://stackoverflow.com/questions/61044136/modulenotfounderror-when-trying-to-use-mock-patch-on-a-method | My pytest unit test keeps returning the error ModuleNotFoundError: No module name billing. Oddly enough the send_invoices method in the billing module is able to be called when I remove the patch statement. Why is mock.patch unable to find the billing module and patch the method if this is the case? billing.py import ... | Solution Since I had already imported the module of the method I needed to patch. I didn't need to use the full path including the package name. Changed patch('projectxapp.billing.Billing.create_invoice_pdf') to this patch('billing.Billing.create_invoice_pdf') From the unittest documentation: target should be a string... | 8 | 5 |
60,971,502 | 2020-4-1 | https://stackoverflow.com/questions/60971502/python-poetry-how-to-install-optional-dependencies | Python's poetry dependency manager allows specifying optional dependencies via command: $ poetry add --optional redis Which results in this configuration: [tool.poetry.dependencies] python = "^3.8" redis = {version="^3.4.1", optional=true} However how do you actually install them? Docs seem to hint to: $ poetry insta... | You need to add a tool.poetry.extras group to your pyproject.toml if you want to use the -E flag during install, as described in this section of the docs: [tool.poetry.extras] caching = ["redis"] The key refers to the word that you use with poetry install -E, and the value is a list of packages that were marked as --... | 59 | 61 |
61,003,308 | 2020-4-3 | https://stackoverflow.com/questions/61003308/conda-install-psycopg2-errors | New mackbookpro running Catalina. Installed anaconda using homebrew. Tried to install psycopg2 using the command conda install -c anaconda psycopg2 but failed due to package conflicts. Here's some of the output from the attempted install: $ conda install -c anaconda psycopg2 Collecting package metadata (current_repodat... | The reason might be there are too many conflicts between [anaconda==2020.02] and [70+ PACKAGES] Try the following worked for me: conda -V conda update -n base conda To ensure you are in version conda 4.8.2 Then conda update --all Then the following packages will be DOWNGRADED: anaconda 2020.02-py37_0 --> custom-py37_1 ... | 10 | 6 |
61,000,501 | 2020-4-2 | https://stackoverflow.com/questions/61000501/json-serialization-of-nested-dataclasses | I would need to take the question about json serialization of @dataclass from Make the Python json encoder support Python's new dataclasses a bit further: consider when they are in a nested structure. Consider: import json from attr import dataclass from dataclasses_json import dataclass_json @dataclass @dataclass_jso... | You can use a pydantic library. From the example in documentation from pydantic import BaseModel class BarModel(BaseModel): whatever: int class FooBarModel(BaseModel): banana: float foo: str bar: BarModel m = FooBarModel(banana=3.14, foo='hello', bar={'whatever': 123}) # returns a dictionary: print(m.dict()) """ { 'ban... | 14 | 12 |
61,075,295 | 2020-4-7 | https://stackoverflow.com/questions/61075295/shortcut-to-colllaspe-fold-all-methods-in-pycharm | I'm mainly working on PyCharm, and lot of times, I come into a situation where it would be much better if I can collapse/fold all method bodies, and leave their names only. The picture below is the the result I want, but I can't find the shortcut to do this thing. If you know any, let me know. | You can collapse the code as shown in the screenshot going to Code > Folding > Expand All to Level > 1 or using the keyboard shortcut Ctrl + Shift + NumPad *, 1. The level is absolute relative to the module level. If you have nested methods or classes you can select them individually an use the equivalent Expand to Lev... | 13 | 17 |
61,083,004 | 2020-4-7 | https://stackoverflow.com/questions/61083004/dense-object-has-no-attribute-op | I am trying to make a fully connected model using tensorflow.keras, here is my code from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Dense, Flatten def load_model(input_shape): input = Input(shape = input_shape) dense_shape = input_shape[0] x = Flatten()(input) x = Dense(dense_shape,... | You are missing (x) after your output layer. Try output = Dense(10 , activation = 'softmax')(x) | 25 | 47 |
60,997,189 | 2020-4-2 | https://stackoverflow.com/questions/60997189/how-can-i-make-faceted-plots-in-plotly-have-their-own-individual-yaxes-tick-labe | When I use Plotly express to plot different parameters with different ranges - in the example below, BloodPressureHigh, Height(cm), Weight(kg), and BloodPressureLow - using the facet_col argument, I am unable to get the resulting plot to display the unique YTicks for each of the faceted plots. Is there an easy method f... | Does this help you? fig = px.box(df_melted, x="Clinic", y="value", facet_col="variable", boxmode="overlay") fig.update_yaxes(matches=None) fig.for_each_yaxis(lambda yaxis: yaxis.update(showticklabels=True)) fig.show() | 25 | 43 |
61,025,973 | 2020-4-4 | https://stackoverflow.com/questions/61025973/how-to-avoid-arrow-key-values-in-python-input | I'm getting Arrow Key values in my Python Input using input(). This only happens during the time of execution of a Python Script. It doesn't happen if Input is taken from the Interpreter. The Arrow Key values I'm referring to: Why does the terminal show "^[[A" "^[[B" "^[[C" "^[[D" when pressing the arrow keys in Ubuntu... | Found a way to prevent this! You just have to import the readline module import readline This will make the standard input() method utilize some of its utilities, enabling normal arrow-key usage and more. | 12 | 19 |
61,041,707 | 2020-4-5 | https://stackoverflow.com/questions/61041707/plotly-log-scale-in-subplot-python | I have a 3 columns in my dataframe. I have charted them all in plotly, and the below code puts them side by side in a subplot. I would like to change the third chart 'c' to have a logarithmic scale. Is this possible? fig = make_subplots(rows=1, cols=3) fig.add_trace( go.Scatter(x = df.index,y = df['a'],mode = 'lines+ma... | See the section on "Customizing Subplot Axes" in the Plotly documentation. I included an example below for 2 subplots, but the logic is the same regardless of the number of subplots. import plotly.graph_objects as go from plotly.subplots import make_subplots fig = make_subplots(rows=1, cols=2, subplot_titles=("Default ... | 18 | 30 |
61,021,252 | 2020-4-3 | https://stackoverflow.com/questions/61021252/aws-cdk-s3-bucket-creation-error-bucket-name-already-exisits | I am new to using CloudFormation / CDK and am having trouble figuring out to deploy my stacks without error. Currently I am using the python CDK to create a bucket. This bucket will hold model files and I need to ensure that the bucket deployed in this stack retains data over time / new deployments. From my initial tes... | I ran into the same issue, and it was due to the reason that bucket was already created by me manually earlier for some testing, NOT by ECS stack initially. Deleting the bucket definitely makes ECS deployment to work fine, as it did for you and I tested this running the deployment multiple times. Ensure that no ECS res... | 8 | 3 |
60,992,109 | 2020-4-2 | https://stackoverflow.com/questions/60992109/valueerror-invalid-elements-received-for-the-data-property | I encounter an issue with plotly. I would like to display different figures but, somehow, I can't manage to achieve what I want. I created 2 sources of data: from plotly.graph_objs.scatter import Line import plotly.graph_objs as go trace11 = go.Scatter( x = [0, 1, 2], y = [0, 0, 0], line = Line({'color': 'rgb(0, 0, 128... | The reason why you are getting an error it is because the function append_trace() is expecting a single trace in the form you've declared them. However, the graph object Figure has the function add_traces() with which you can pass the data parameter as a list with more than one trace. Therefore, I suggest two simple so... | 12 | 6 |
61,063,676 | 2020-4-6 | https://stackoverflow.com/questions/61063676/command-errored-out-with-exit-status-1-python-setup-py-egg-info-check-the-logs | I am trying to download auto-py-to-exe on a different (windows) device than I usually use through pip. However when run I get the error (sorry it is so very very long): ERROR: Command errored out with exit status 1: command: 'c:\users\tom\appdata\local\programs\python\python38-32\python.exe' -c 'import sys, setuptools... | Edit Since this answer was posted, gevent has released several new versions, including prebuilt wheels for Python 3.8 on Windows, so the pip install gevent --pre shouldn't be necessary anymore - just run pip install auto-py-to-exe as usual and it should work. Original answer Allow prerelease gevent versions via $ pip i... | 45 | 27 |
61,010,431 | 2020-4-3 | https://stackoverflow.com/questions/61010431/how-to-start-with-the-instagramapi-in-python | i want to play with the InstagramAPI and write some code for like getting a list of my follower and something like that. I am really new to that topic. What is the best way to do this? Is there a Python-Lib for handle those json request or should I send them directly to the (new? graphAPI, displayAPI) InstagramAPI? A... | LevPasha's Instagram-API-python, instabot, and many other API's are no longer functional as of Oct 24, 2020 after Facebook deprecated the legacy API and now has a new, authentication-required, API. It now requires registering your app with Facebook to be able to get access to many of the API features (via oembed) that ... | 9 | 10 |
61,062,303 | 2020-4-6 | https://stackoverflow.com/questions/61062303/deploy-python-app-to-heroku-slug-size-too-large | I'm trying to deploy a Streamlit app written in python to Heroku. My whole directory is 4.73 MB, where 4.68 MB is my ML model. My requirements.txt looks like this: absl-py==0.9.0 altair==4.0.1 astor==0.8.1 attrs==19.3.0 backcall==0.1.0 base58==2.0.0 bleach==3.1.3 blinker==1.4 boto3==1.12.29 botocore==1.15.29 cachetools... | I have already answered this here. Turns out the Tensorflow 2.0 module is very large (more than 500MB, the limit for Heroku) because of its GPU support. Since Heroku doesn't support GPU, it doesn't make sense to install the module with GPU support. Solution: Simply replace tensorflow with tensorflow-cpu in your require... | 22 | 61 |
60,999,753 | 2020-4-2 | https://stackoverflow.com/questions/60999753/pandas-future-warning-indexing-with-multiple-keys | Pandas throws a Future Warning when I apply a function to multiple columns of a groupby object. It suggests to use a list as index instead of tuples. How would one go about this? >>> df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]]) >>> df.groupby([0,1])[1,2].apply(sum) <stdin>:1: FutureWarning: Indexing with multiple keys ... | This warning was introduced in pandas 1.0.0, following a discussion on GitHub. So best use what was suggested there: df.groupby([0, 1])[[1, 2]].apply(sum) It's also possible to move the slicing operation to the end, but that is not as efficient: df.groupby([0, 1]).apply(sum).loc[:, 1:] Thanks @ALollz and @cmosig for ... | 73 | 76 |
61,028,653 | 2020-4-4 | https://stackoverflow.com/questions/61028653/msys2-with-python-3-8-importerror-cannot-import-name-open-code-from-io | NOTE: There have been several EDITs to the question, as per comments. They are indicated below, and separated by lines. As of now, the only remaining issue seems to be that numpy cannot load, possibly (but not certainly) due to two alternative python 3.8 systems present. I have updated my msys2 system a couple of month... | The ImportError: cannot import name 'open_code' from 'io' (unknown location) comes from the fact that there are two different versions of Python conflicting with each other. python still points to the old version 3.7 but PYTHONPATH got updated to point to the new 3.8 version. As the documentation of PYTHONPATH states, ... | 13 | 14 |
61,072,873 | 2020-4-7 | https://stackoverflow.com/questions/61072873/hex-size-in-matplotlib-hexbins-based-on-density-of-nearby-points | I've got the following code which produces the following figure import numpy as np np.random.seed(3) import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame() df['X'] = list(np.random.randint(100, size=100)) + list(np.random.randint(30, size=100)) df['Y'] = list(np.random.randint(100, size=100)) + list(np... | You may want to spend sometime in understanding color mapping. import numpy as np np.random.seed(3) import pandas as pd import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.path import Path from matplotlib.patches import PathPatch df = pd.DataFrame() df['X'] = list(np.rand... | 9 | 3 |
61,042,524 | 2020-4-5 | https://stackoverflow.com/questions/61042524/create-a-nxn-matrix-from-one-column-pandas | i have dataframe with each row having a list value. id list_of_value 0 ['a','b','c'] 1 ['d','b','c'] 2 ['a','b','c'] 3 ['a','b','c'] i have to do a calculate a score with one row and against all the other rows For eg: Step 1: Take value of id 0: ['a','b','c'], Step 2: find the intersection between id 0 and id 1 , resu... | If you data is not too big, you can use get_dummies to encode the values and do a matrix multiplication: s = pd.get_dummies(df.list_of_value.explode()).sum(level=0) s.dot(s.T).div(s.sum(1)) Output: 0 1 2 3 0 1.000000 0.666667 1.000000 1.000000 1 0.666667 1.000000 0.666667 0.666667 2 1.000000 0.666667 1.000000 1.00000... | 12 | 7 |
61,071,022 | 2020-4-7 | https://stackoverflow.com/questions/61071022/pywintypes-com-error-2147221008-coinitialize-has-not-been-called-none-n | When I try to run this code as is I get this error "IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)" , however if I run stp_tracker alone it works fine and if I run notify stp's alone it works j... | Apologize for that, but searching the internet and I found something that helped. I came across the same post earlier and assumed it was deprecated info because my AutoComplete in pycharm was not picking anything up when typing pythoncom.CoInitialize() so it made me think it was outdated info. Also the same information... | 8 | 4 |
61,088,235 | 2020-4-7 | https://stackoverflow.com/questions/61088235/flat-file-nosql-solution | Is there a built-in way in SQLite (or similar) to keep the best of both worlds SQL / NoSQL, for small projects, i.e.: stored in a (flat) file like SQLite (no client/server scheme, no server to install; more precisely : nothing else to install except pip install <package>) possibility to store rows as dict, without hav... | It's possible via using the JSON1 extension to query JSON data stored in a column, yes: sqlite> CREATE TABLE test(data TEXT); sqlite> INSERT INTO test VALUES ('{"name":"john doe","balance":1000,"data":[1,73.23,18]}'); sqlite> INSERT INTO test VALUES ('{"name":"alice","balance":2000,"email":"a@b.com"}'); sqlite> SELECT ... | 14 | 8 |
60,974,077 | 2020-4-1 | https://stackoverflow.com/questions/60974077/how-to-save-keras-model-as-frozen-graph | I am working with Tensorflow 2.0 and want to store the following Keras model as frozen graph. import tensorflow as tf model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(64, input_shape=[100])) model.add(tf.keras.layers.Dense(32, activation='relu')) model.add(tf.keras.layers.Dense(16, activation='relu')) mod... | Freeze_Graph is now gone in Tensorflow 2.0. You can check it here Tensorflow 2.0 : frozen graph support. Except for the .save method that you have in your code. .save Method is already saving a .pb ready for inference. As an alternative, you can also use the below code. You can also use convert_variables_to_constants_v... | 9 | 14 |
61,074,714 | 2020-4-7 | https://stackoverflow.com/questions/61074714/open-cv-contour-area-miscalculation | I am just starting to play with OpenCV and I have found some very strange behaviour from the contourArea function. See this image. It has three non connected areas, the left is a grouping of long strokes and on the top center there is a single dot and finally a big square on the right. When I run my function, I get th... | The inner part of the contours the findContours finds is supposed to be of filled with white color. Don't use cv.Canny before findContours (cv.blur is also not required). Make sure the contours are white and not black. You may use cv.threshold with cv.THRESH_BINARY_INV option for inverting polarity. It is recommende... | 8 | 6 |
61,051,161 | 2020-4-6 | https://stackoverflow.com/questions/61051161/find-xarray-indices-where-conditions-are-satisfied | I want to get the indices of an xarray data array where some condition is satisfied. An answer provided in a related thread (here) for how to find the location for the maximum did not work for me either. In my case, I want to find out the locations for other types of conditions too, not just maximum. Here is what I tri... | I updated the linked example to show the indexes more clearly. Because xarray no longer adds default indexes, the previous example finds the max location but doesn't show the indexes. Copied below: In [17]: da = xr.DataArray( np.random.rand(2,3), dims=list('ab'), coords=dict(a=list('xy'), b=list('ijk')) ) In [18]: da.w... | 9 | 7 |
61,082,381 | 2020-4-7 | https://stackoverflow.com/questions/61082381/xgboost-produce-prediction-result-and-probability | I am probably looking right over it in the documentation, but I wanted to know if there is a way with XGBoost to generate both the prediction and probability for the results? In my case, I am trying to predict a multi-class classifier. it would be great if I could return Medium - 88%. Classifier = Medium Probability... | You can try pred_p = model.predict_proba(D_test) An example I had around (not multi-class though): import xgboost as xgb from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split X, y = make_moons(noise=0.3, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, te... | 19 | 25 |
61,076,688 | 2020-4-7 | https://stackoverflow.com/questions/61076688/django-form-dateinput-with-widget-in-update-loosing-the-initial-value | I need a DateInput field in a ModelForm with the default HTML datepicker (I'm not using 3rd party libraries). Since the DateInput is rendered with <input type = "text"> by default, the datepicker is missing (it comes for free with <input type = "date">) I've found some examples explaining how to change the input type... | I managed to make it work. Following the cause of the issue, I hope it can be useful to others. The HTML <input type='date'> element wants a date in the format YYYY-mm-dd; in fact an example of working HTML must be like this: <input type="date" name="date" value="2020-03-31" class="form-control dateinput form-control" ... | 19 | 32 |
61,058,798 | 2020-4-6 | https://stackoverflow.com/questions/61058798/python-relative-import-in-jupyter-notebook | Let's say I have the following structure: dir_1 ├── functions.py └── dir_2 └── code.ipynb In, code.ipynb, I simply want to access a function inside functions.py and tried this: from ..functions import some_function I get the error: attempted relative import with no known parent package I have checked a bunch of sim... | In your notebook do: import os, sys dir2 = os.path.abspath('') dir1 = os.path.dirname(dir2) if not dir1 in sys.path: sys.path.append(dir1) from functions import some_function | 14 | 10 |
61,052,890 | 2020-4-6 | https://stackoverflow.com/questions/61052890/import-could-not-be-resolved-reported-by-pyright | I've just started using Pyright. Running it on files that run perfectly well I get plenty of errors. This question is similar, but refers to one's own modules. For example Import "numpy" could not be resolved. What does it mean, and how do I resolve it? | On my computer I have 3 Pythons, a 3.6 from Anaconda, and a 2.7 & 3.7 that are regular python. Prompted by a nudge from this GH issue, I switched from the Anaconda 3.6 to the 3.7, and back again, and the problem went away. I think that this is the case because your .vscode/settings.json (the following is mine), doesn... | 35 | 68 |
61,077,802 | 2020-4-7 | https://stackoverflow.com/questions/61077802/how-to-use-a-datepicker-in-a-modelform-in-django | I am using django 3.0 and I am trying to display a datepicker widget in my ModelForm, but I can't figure out how (all I can get is text field). I have tried looking for some solutions, but couldn't find any. This is how my Model and my ModelForm look like: class Membership(models.Model): start_date = models.DateField(d... | This is the expected behavior. A DateInput widget [Django-doc] is just a <input type="text"> element with an optional format parameter. You can make use of a package, like for example django-bootstrap-datepicker-plus [pypi] , and then define a form with the DatePickerInput: from bootstrap_datepicker_plus import DatePic... | 7 | 0 |
61,041,214 | 2020-4-5 | https://stackoverflow.com/questions/61041214/making-a-tqdm-progress-bar-for-asyncio | Am attempting a tqdm progress bar with asyncio tasks gathered. Want the progress bar to be progressively updated upon completion of a task. Tried the code: import asyncio import tqdm import random async def factorial(name, number): f = 1 for i in range(2, number+1): await asyncio.sleep(random.random()) f *= i print(f"... | Made a couple of small changes to Dragos' code in pbar format and used tqdm.write() to get almost what I want, as follows: import asyncio import random import tqdm async def factorial(name, number): f = 1 for i in range(2, number + 1): await asyncio.sleep(random.random()) f *= i return f"Task {name}: factorial {number}... | 22 | 4 |
61,071,271 | 2020-4-7 | https://stackoverflow.com/questions/61071271/how-does-one-use-pytest-monkeypatch-to-patch-a-class | I would like to use pytest monkeypatch to mock a class which is imported into a separate module. Is this actually possible, and if so how does one do it? It seems like I have not seen an example for this exact situation. Suppose you have app with and imported class A in something.py from something import A #Class is im... | tested this, works for me: def test_thing(monkeypatch): def patched_g(self, value): return value * 2 monkeypatch.setattr(A, 'g', patched_g) b = B() assert b.f(2) == 4 | 13 | 8 |
61,061,435 | 2020-4-6 | https://stackoverflow.com/questions/61061435/modulenotfounderror-no-module-named-jose | I am using python-social-auth in my django project to use social platforms for authentication in my project. It all worked well but am getting this error ModuleNotFoundError: No module named 'jose' This is the whole error: [05/Apr/2020 14:01:00] "GET /accounts/login/ HTTP/1.1" 200 3058 Internal Server Error: /login/twi... | Install jose by running: pip install python-jose>=3.0.0 | 10 | 22 |
61,057,046 | 2020-4-6 | https://stackoverflow.com/questions/61057046/list-of-dicts-to-multilevel-dict-based-on-depth-info | I have some data, more or less like this: [ {"tag": "A", "level":0}, {"tag": "B", "level":1}, {"tag": "D", "level":2}, {"tag": "F", "level":3}, {"tag": "G", "level":4}, {"tag": "E", "level":2}, {"tag": "H", "level":3}, {"tag": "I", "level":3}, {"tag": "C", "level":1}, {"tag": "J", "level":2}, ] I want to turn it into ... | data = [ {"tag": "A", "level": 0}, {"tag": "B", "level": 1}, {"tag": "D", "level": 2}, {"tag": "F", "level": 3}, {"tag": "G", "level": 4}, {"tag": "E", "level": 2}, {"tag": "H", "level": 3}, {"tag": "I", "level": 3}, {"tag": "C", "level": 1}, {"tag": "J", "level": 2}, ] root = {'level': -1, 'children': {}} parents = {-... | 9 | 6 |
61,049,310 | 2020-4-5 | https://stackoverflow.com/questions/61049310/how-to-avoid-reloading-ml-model-every-time-when-i-call-python-script | I have two files, file1.py which have ML model size of 1GB and file2.py which calls get_vec() method from file1 and receives vectors in return. ML model is being loaded everytime when file1 get_vec() method is called. This is where it is taking lots of time (around 10s) to load the model from disk. I want to tell file1... | Heres how to do it Step 1) create a function in python and load your model in that function model=None def load_model(): global model model = ResNet50(weights="imagenet") if you carefully observe first I assigned variable model to None. Then inside load_model function I loaded a model. Also I made sure the variable m... | 10 | 11 |
61,054,415 | 2020-4-6 | https://stackoverflow.com/questions/61054415/find-least-common-denominator-for-a-list-of-fractions-in-python | I have a list of fractions that I need to transform. from fractions import Fraction fractions_list=[Fraction(3,14),Fraction(1,7),Fraction(9,14)] The output should be a list with the numerators for each fraction, followed by the least common denominator for all of them. For above example the result (3/14, 2/14, 9/14) w... | import numpy as np fractions_list=[Fraction(3,14),Fraction(1,7),Fraction(9,14)] lcm = np.lcm.reduce([fr.denominator for fr in fractions_list]) vals = [int(fr.numerator * lcm / fr.denominator) for fr in fractions_list] vals.append(lcm) | 8 | 11 |
61,049,744 | 2020-4-5 | https://stackoverflow.com/questions/61049744/import-dataset-into-google-colab-from-another-drive-account | lastly I'm working on google colab I get this dataset colled celeba and it is into a google drive accout and this account is not mine but I have the access to go through it now because the internet problems and drive capacity I can not dounload the dataset then upload it to my drive ... so the question is: is there any... | To download a file to Colab If you want to download the file directly into your Google Colab instance, then you can use gdown. Note that the file must be shared to the public. If the link to your dataset is https://drive.google.com/file/d/10vAwF6hFUjvw3pf6MmB_S0jZm9CLWbSx/view?usp=sharing, you can use: !gdown --id "10... | 12 | 18 |
61,050,767 | 2020-4-5 | https://stackoverflow.com/questions/61050767/how-to-force-zero-0-to-the-center-of-an-axis-in-matplotlib | I'm trying to plot percent change data and would like to plot it such that the y axis is symmetric about 0. i.e. 0 is in the center of the axis. import matplotlib.pyplot as plt import pandas as pd data = pd.DataFrame([1,2,3,4,3,6,7,8], columns=['Data']) data['PctChange'] = data['Data'].pct_change() data['PctChange'].pl... | After plotting the data find the maximum absolute value between the min and max axis values. Then set the min and max limits of the axis to the negative and positive (respectively) of that value. import matplotlib.pyplot as plt import pandas as pd data = pd.DataFrame([1,2,3,4,3,6,7,8], columns=['Data']) data['PctChange... | 11 | 16 |
61,047,555 | 2020-4-5 | https://stackoverflow.com/questions/61047555/indirect-fixture-error-using-pytest-what-is-wrong | def fatorial(n): if n <= 1: return 1 else: return n*fatorial(n - 1) import pytest @pytest.mark.parametrize("entrada","esperado",[ (0,1), (1,1), (2,2), (3,6), (4,24), (5,120) ]) def testa_fatorial(entrada,esperado): assert fatorial(entrada) == esperado The error: ERROR collecting Fatorial_pytest.py __________________... | TL;DR - The problem is with the line @pytest.mark.parametrize("entrada","esperado",[ ... ]) It should be written as a comma-separated string: @pytest.mark.parametrize("entrada, esperado",[ ... ]) You got the indirect fixture because pytest couldn't unpack the given argvalues since it got a wrong argnames parameter... | 62 | 164 |
60,962,274 | 2020-4-1 | https://stackoverflow.com/questions/60962274/plotly-how-to-change-the-colorscheme-of-a-plotly-express-scatterplot | I am trying to work with plotly, specifically ploty express, to build a few visualizations. One of the things I am building is a scatterplot I have some code below, that produces a nice scatterplot: import plotly.graph_objs as go, pandas as pd, plotly.express as px df = pd.read_csv('iris.csv') fig = px.scatter(df, x='s... | Generally, changing the color scheme for a plotly express figure is very straight-forward. What's causing the problems here is the fact that species is a categorical variable. Continuous or numerical values are actually easier, but we'll get to that in a bit. For categorical values, using color_discrete_map is a perfec... | 26 | 35 |
61,020,313 | 2020-4-3 | https://stackoverflow.com/questions/61020313/is-there-a-way-to-add-autofilter-to-all-columns-using-xlsxwriter-without-specify | I have a dataframe which I am writing to excel using xlsxwriter and I want there to be autofilter applied to all columns where the header is not blank in my spreadsheet without having to specify a range (e.g. A1:D1). Is there any way to do this? | You will need to specify the range in some way but you can do it programatically based on the shape() of the data frame. For example: import xlsxwriter import pandas as pd df = pd.DataFrame({'A' : [1, 2, 3, 4, 5, 6, 7, 8], 'B' : [1, 2, 3, 4, 5, 6, 7, 8], 'C' : [1, 2, 3, 4, 5, 6, 7, 8], 'D' : [1, 2, 3, 4, 5, 6, 7, 8]}) ... | 9 | 17 |
61,024,263 | 2020-4-4 | https://stackoverflow.com/questions/61024263/python-logging-does-not-log-pd-info | import logging import pandas as pd logger = logging.getLogger('train') logger.setLevel(logging.DEBUG) # Data data = {'Name': ['Tom', 'nick', 'krish', 'jack'], 'Age': [20, 21, 19, 18]} # Create DataFrame df = pd.DataFrame(data) logger.info(type(df)) logger.info(df.info()) . . . <other_processes> . The above code output... | Change buffer parameter in DataFrame.info to StringIO for text with .getvalue(): from io import StringIO buf = StringIO() df.info(buf=buf) logger.info(type(df)) logger.info(buf.getvalue()) | 9 | 11 |
61,022,248 | 2020-4-4 | https://stackoverflow.com/questions/61022248/i-can%c2%b4t-install-anaconda-on-linux | When I try to install Anaconda on Linux, I get to this point: Anaconda3 will now be installed into this location: /home/jorge/anaconda3 - Press ENTER to confirm the location - Press CTRL-C to abort the installation - Or specify a different location below [/home/jorge/anaconda3] >>> PREFIX=/home/jorge/anaconda3 Unpacki... | Did you verify the integrity of the installer's data? because it is a common error when downloading this corrupted or incomplete since it is the previous step you have to do to make sure that the file is ok before executing the script. This post helped me a lot for the first time I installed it. https://www.digitalocea... | 11 | 6 |
61,016,110 | 2020-4-3 | https://stackoverflow.com/questions/61016110/plot-multiple-confusion-matrices-with-plot-confusion-matrix | I am using plot_confusion_matrix from sklearn.metrics. I want to represent those confusion matrices next to each other like subplots, how could I do this? | Let's use the good'ol iris dataset to reproduce this, and fit several classifiers to plot their respective confusion matrices with plot_confusion_matrix: from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier from sklearn.svm import SVC from sklearn.model_selection import train_test_split from skle... | 7 | 26 |
60,983,836 | 2020-4-2 | https://stackoverflow.com/questions/60983836/complete-set-of-punctuation-marks-for-python-not-just-ascii | Is there a listing or library that has all punctuations that we might commonly come across? Normally I use string.punctuation, but some punctuation characters are not included in it, for example: >>> "'" in string.punctuation True >>> "’" in string.punctuation False | You might do better with this check: >>> import unicodedata >>> unicodedata.category("'").startswith("P") True >>> unicodedata.category("’").startswith("P") True The Unicode categories P* are specifically for Punctuation: connector (Pc), dash (Pd), initial quote (Pi), final quote (Pf), open (Ps), close (Pe), other (Po... | 41 | 63 |
61,008,937 | 2020-4-3 | https://stackoverflow.com/questions/61008937/python-round-to-next-highest-power-of-10 | How would I manage to perform math.ceil such that a number is assigned to the next highest power of 10? # 0.04 -> 0.1 # 0.7 -> 1 # 1.1 -> 10 # 90 -> 100 # ... My current solution is a dictionary that checks the range of the input number, but it's hardcoded and I would prefer a one-liner solution. Maybe I am missing a ... | You can use math.ceil with math.log10 to do this: >>> 10 ** math.ceil(math.log10(0.04)) 0.1 >>> 10 ** math.ceil(math.log10(0.7)) 1 >>> 10 ** math.ceil(math.log10(1.1)) 10 >>> 10 ** math.ceil(math.log10(90)) 100 log10(n) gives you the solution x that satisfies 10 ** x == n, so if you round up x it gives you the exponen... | 52 | 70 |
60,969,101 | 2020-4-1 | https://stackoverflow.com/questions/60969101/how-to-build-a-population-pyramid-with-python | I'm trying to build a population pyramid from a pandas df using seaborn. The problem is that some data isn't displayed. As you can see from the plot I created there's some missing data. The Y-axis ticks are 21 and the df's age classes are 21 so why don't they match? What am I missing? Here's the code I wrote: import ... | As explained by JohanC, the data is not missing, it's just very small compared to the other bars. Another factor is that you seem to have a white border around each of your bars, which hides the very small bars at the top. Try putting lw=0 in your call to barplot. This is what I am getting: bar_plot = sns.barplot(x='Ma... | 8 | 7 |
60,996,205 | 2020-4-2 | https://stackoverflow.com/questions/60996205/python-datetime-timezone-conversion-off-by-4-minutes | when I run this code: #!/usr/bin/env python3 from datetime import datetime, timedelta from dateutil import tz from pytz import timezone time = "2020-01-15 10:14:00" time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S") print("time1 = " + str(time)) time = time.replace(tzinfo=timezone('America/New_York')) print("time2 = "... | From pytz documentation: This library differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document. In addition, if you perform date arithmetic on local times that cross DST boundaries, the result may be... | 12 | 16 |
61,008,229 | 2020-4-3 | https://stackoverflow.com/questions/61008229/flatten-a-list-of-lists-containing-single-strings-to-a-list-of-ints | i have list with lists of strings looks like allyears #[['1916'], ['1919'], ['1922'], ['1912'], ['1924'], ['1920']] i need to have output like this: #[1916, 1919, 1922, 1912, 1924, 1920] have been try this: for i in range(0, len(allyears)): allyears[i] = int(allyears[i]) but i have error >>> TypeError: int() argumen... | You can simply do this: allyears = [int(i[0]) for i in allyears] Because all the elements in your allyears is a list which has ony one element, so I get it by i[0] The error is because ypu can't convert a list to an int | 11 | 9 |
61,006,189 | 2020-4-3 | https://stackoverflow.com/questions/61006189/can-i-define-functions-other-than-fixtures-in-conftest-py | Can I define functions other than fixtures in conftest.py. If I have a function add(), defined in conftest.py. Can I using the function inside test_add.py file just calling add()? | Two possible ways You could just import function add from conftest.py, or move it to something more appropriate. (for example utils.py) You could create fixture that returns function and use it in your tests. Something like this. conftest.py import pytest @pytest.fixture def add(): def inner_add(x, y): return x + y r... | 10 | 8 |
61,001,812 | 2020-4-2 | https://stackoverflow.com/questions/61001812/pip-cant-find-django-3-x-error-no-matching-distribution-found-for-django-3 | When I run: pip3 install django==3.0.5 I get the error ERROR: Could not find a version that satisfies the requirement django==3.0.5 (from versions: 1.1.3, ... 2.2.11, 2.2.12) ERROR: No matching distribution found for django==3.0.4 I need to update some references somewhere, but I am not sure how. Plz Help. | As noted in the comments, Django 3.x is only available for Python 3.6 or greater. If you attempt to install Django 3 while using an older version of Python (e.g. Python 3.5 in the case of the OP), pip will be unable to find a matching package. The solution is to simply upgrade to a more modern version of Python. | 11 | 10 |
60,996,892 | 2020-4-2 | https://stackoverflow.com/questions/60996892/how-to-replace-loss-function-during-training-tensorflow-keras | I want to replace the loss function related to my neural network during training, this is the network: model = tensorflow.keras.models.Sequential() model.add(tensorflow.keras.layers.Conv2D(32, kernel_size=(3, 3), activation="relu", input_shape=input_shape)) model.add(tensorflow.keras.layers.Conv2D(64, (3, 3), activatio... | So, a straightforward answer I would give is: switch to pytorch if you want to play this kind of games. Since in pytorch you define your training and evaluation functions, it takes just an if statement to switch from a loss function to another one. Also, I see in your code that you want to switch from cross_entropy to ... | 8 | 5 |
60,999,816 | 2020-4-2 | https://stackoverflow.com/questions/60999816/argparse-not-parsing-boolean-arguments | I am trying to make a build script like this: import glob import os import subprocess import re import argparse import shutil def create_parser(): parser = argparse.ArgumentParser(description='Build project') parser.add_argument('--clean_logs', type=bool, default=True, help='If true, old debug logs will be deleted.') p... | You are misunderstanding how the argparse understands the boolean arguments. Basically you should use action='store_true' or action='store_false' instead of the default value, with the understanding that not specifying the argument will give you the opposite of the action, e.g. parser.add_argument('-x', type=bool, acti... | 12 | 21 |
60,999,164 | 2020-4-2 | https://stackoverflow.com/questions/60999164/is-the-ordering-of-pathlibs-glob-method-consistent-between-runs | Will Path('.').glob('*.ext') produce consistent ordering of results (assuming the files being globbed don't change)? It seems the glob ordering is based on the file system order (at least, for the old glob package). Will pathlib's glob order be changed by adding files to the directory (which will not be included in the... | Checking the source code for the pathlib module, by chance, the latest commit points us directly to the relevant place: Use os.scandir() as context manager in Path.glob(). So under the hood Path.glob uses os.scandir to get the directory entries. The docs of this function report that the results are unordered: Return... | 11 | 10 |
60,995,830 | 2020-4-2 | https://stackoverflow.com/questions/60995830/debug-python-code-thats-in-a-pip-package-in-vs-code | My debugging is setup in VS code, I can hit break points in the file I'm running via the launch.json config, but I can't get breakpoints in packages that are installed with PIP. How do I get breakpoints in these package files? | If you know where you python installation is on your computer do this: Know where you python packets were installed. File -> add folder to workspace Add the breakpoints where necessary. As an alternative i would advise to create a virtual environment and do the same thing but with the safety of virtual environment. H... | 12 | 8 |
60,989,409 | 2020-4-2 | https://stackoverflow.com/questions/60989409/telethon-leads-to-runtimewarning-coroutine-messagemethods-send-message-was-n | I'm trying to run this first code snippet provided by the Telethon documentation. But, after multiple problems (here and here), I ended up with this modified version: import os import sys from telethon.sync import TelegramClient, events # import nest_asyncio # nest_asyncio.apply() session_name = "<session_name>" api_id... | Just add await the client.send_message('me', 'Hello, myself!') to solve that error and print afterdownload_profile_photo has done its work downloads an image to localhost so that may be why you don't see anything. You should read telethon documentation thoroughly and also how to use photo downloads correctly All the ca... | 9 | 7 |
60,989,914 | 2020-4-2 | https://stackoverflow.com/questions/60989914/add-id-found-in-list-to-new-column-in-pandas-dataframe | Say I have the following dataframe (a column of integers and a column with a list of integers)... ID Found_IDs 0 12345 [15443, 15533, 3433] 1 15533 [2234, 16608, 12002, 7654] 2 6789 [43322, 876544, 36789] And also a separate list of IDs... bad_ids = [15533, 876544, 36789, 11111] Given that, and ignoring the df['ID']... | Using np.intersect1d to get the intersect of the two lists: df['bad_id'] = df['Found_IDs'].apply(lambda x: np.intersect1d(x, bad_ids)) ID Found_IDs bad_id 0 12345 [15443, 15533, 3433] [15533] 1 15533 [2234, 16608, 12002, 7654] [] 2 6789 [43322, 876544, 36789] [876544] Or with just vanilla python using intersect of set... | 12 | 9 |
60,975,243 | 2020-4-1 | https://stackoverflow.com/questions/60975243/not-able-to-start-django-project-in-local-as-well-as-in-docker | I am using Docker to deploy Python2.7 application with Django1.8. I am facing some issue from last two days and I found error as below. Docker Image: python:2.7-slim-buster Error: root@64f8c580dd0a:/code# python manage.py runserver read completed! read completed! Traceback (most recent call last): File "manage.py", lin... | Django-appconf version 1.0.4 only supports Django 1.11 and up and Python 3.5 and up. (https://github.com/django-compressor/django-appconf/blob/v1.0.4/setup.py). You need to downgrade to at least version 1.0.2 (supports Python 2.6+, doesn't say which django version: https://github.com/django-compressor/django-appconf/bl... | 11 | 19 |
60,978,672 | 2020-4-1 | https://stackoverflow.com/questions/60978672/python-string-to-camelcase | This is a question from Codewars: Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). The input test cases ... | You may have a working implementation with slight errors as mentioned in your comments, but I propose that you: split by the delimiters apply a capitalization for all but the first of the tokens rejoin the tokens My implementation is: def to_camel_case(text): s = text.replace("-", " ").replace("_", " ") s = s.split()... | 9 | 19 |
60,976,758 | 2020-4-1 | https://stackoverflow.com/questions/60976758/how-can-i-get-the-mse-of-a-tensor-across-a-specific-dimension | I have 2 tensors with .size of torch.Size([2272, 161]). I want to get mean-squared-error between them. However, I want it along each of the 161 channels, so that my error tensor has a .size of torch.Size([161]). How can I accomplish this? It seems that torch.nn.MSELoss doesn't let me specify a dimension. | For the nn.MSELoss you can specify the option reduction='none'. This then gives you back the squared error for each entry position of both of your tensors. Then you can apply torch.sum/torch.mean. a = torch.randn(2272,161) b = torch.randn(2272,161) loss = nn.MSELoss(reduction='none') loss_result = torch.sum(loss(a,b),d... | 11 | 15 |
60,962,196 | 2020-4-1 | https://stackoverflow.com/questions/60962196/plotly-how-to-plot-rectangle-with-gradient-color-in-plotly | Can a shape such as a rectangle have a smooth color gradient in Plotly? I define the shape with a solid fill color as: shapes=[dict( type='rect', xref='x', yref='paper', x0=box_from, x1=box_to, y0=0, y1=1, fillcolor='Green', opacity=0.07, layer='below', line=dict(width=0), )] But I'd like the box not to have a solid c... | Someone will correct me if I'm wrong but I think that no, there is no straight implementation to fill with a gradient a shape. But to achieve a similar results you could plot several lines inside the rectangle specifying decreasing rgb values. For example I added this for loop after the first rectangle definition in th... | 8 | 8 |
60,925,137 | 2020-3-30 | https://stackoverflow.com/questions/60925137/using-mypy-with-with-lazy-initialization-of-instance-attributes | I'm trying to use mypy in my projects, but many of the instance attributes I use are only initialized after __init__, and not inside it. However, I do want to keep the good practice of declaring all instance attributes at __init__, so I need some complicated solutions to make this work. An example to how I want this to... | I have found this to work for me: class Foo: def __init__(self, x: int): self.x = x self.y: int # Give self.y a type but no value def fill_values(self): self.y = self.x ** 2 def do(self) -> int: return self.x + self.y Essentially all you are doing is telling mypy that self.y will be an integer when (and if) it is init... | 17 | 18 |
60,917,800 | 2020-3-29 | https://stackoverflow.com/questions/60917800/how-to-get-the-opencv-image-from-python-and-use-it-in-c-in-pybind11 | I'm trying to figure out how it is possible to receive an OpenCV image from a Python in C++. I'm trying to send a callback function, from C++ to my Python module, and then when I call a specific python method in my C++ app, I can access the needed image. Before I add more details, I need to add that there are already s... | I ultimately could successfully get this to work thanks to @DanMasek and this link: void cpp_callback1(py::array_t<uint8_t>& img) { py::buffer_info buf = img.request(); cv::Mat mat(buf.shape[0], buf.shape[1], CV_8UC3, (unsigned char*)buf.ptr); cv::imshow("test", mat); } note that the cast is necessary, or otherwise, y... | 12 | 7 |
60,897,536 | 2020-3-28 | https://stackoverflow.com/questions/60897536/python-count-and-replace-regular-expression-in-same-pass | I can globally replace a regular expression with re.sub(), and I can count matches with for match in re.finditer(): count++ Is there a way to combine these two, so that I can count my substitutions without making two passes through the source string? Note: I'm not interested in whether the substitution matched, I'm in... | You can use re.subn. re.subn(pattern, repl, string, count=0, flags=0) it returns (new_string, number_of_subs_made) For example purposes, I'm using the same example as @Shubham Sharma used. text = "Jack 10, Lana 11, Tom 12, Arthur, Mark" out_str, count = re.subn(r"(\d+)", repl='repl', string=text) # out_str--> 'Jack re... | 11 | 10 |
60,873,454 | 2020-3-26 | https://stackoverflow.com/questions/60873454/how-can-i-list-all-the-virtual-environments-created-with-venv | Someone's just asked me how to list all the virtual environments created with venv. I could only think of searching for pyvenv.cfg files to find them. Something like: from pathlib import Path venv_list = [str(p.parent) for p in Path.home().rglob('pyvenv.cfg')] This could potentially include some false positives. Is th... | On Linux/macOS this should get most of it find ~ -d -name "site-packages" 2>/dev/null Looking for directories under your home that are named "site-packages" which is where venv puts its pip-installed stuff. the /dev/null bit cuts down on the chattiness of things you don't have permission to look into. Or you can look a... | 16 | 13 |
60,902,650 | 2020-3-28 | https://stackoverflow.com/questions/60902650/how-does-the-quotechar-parameter-of-the-csv-reader-function-work | My current understanding of the quotechar parameter is that it surrounds the fields that are separated by a comma. I'm reading the csv documentation for python and have written a similar code to theirs as such: import csv with open("test.csv", newline="") as file: reader = csv.reader(file, delimiter=",", quotechar="|"... | The quotechar argument is A one-character string used to quote fields containing special characters, such as the delimiter or quotechar, or which contain new-line characters. It defaults to '"'. For example, If your csv file contains data of the form |Hello|,|My|,|name|,|is|,|"John"| |Hello|,|My|,|name|,|is|,|"Tom"| ... | 10 | 8 |
60,939,392 | 2020-3-30 | https://stackoverflow.com/questions/60939392/django-annotate-whether-exists-or-not | I have a query I'm using: people = Person.objects.all().annotate(num_pets=Count('pets')) for p in people: print(p.name, p.num_pets == 0) (Pet is ManyToOne with Person) But i'm actually not interested in the number of pets, but only on whether a person has any pets or not. How can this be done? | You can make use of an Exists expression [Django-doc] to determine if there exists a Pet for that Person. For example: from django.db.models import Exists, OuterRef Person.objects.annotate( has_pet=Exists(Pet.objects.filter(person=OuterRef('pk'))) ) Here the model is thus Pet that has a ForeignKey named person to Perso... | 15 | 26 |
60,921,001 | 2020-3-29 | https://stackoverflow.com/questions/60921001/internalerror-spectrum-scan-error-s3-to-redshift-copy-command | I am trying to copy some data from S3 bucket to redshift table by using the COPY command. The format of the file is PARQUET. When I run the execute the COPY command query, I get InternalError_: Spectrum Scan Error. This is the first time I tried copying from a parquet file. Please help me if there is a solution for t... | This generally happens for below reasons: If there is a mismatch in number of columns between table and file. If the Column type of your file schema is incompatible with your target table column type. Try going into the error logs. You might find partial log in cloud watch. From the screen shot you have uplaoded, you... | 10 | 29 |
60,847,083 | 2020-3-25 | https://stackoverflow.com/questions/60847083/attributeerror-torch-return-types-max-object-has-no-attribute-dim-maxpool | I'm trying to do maxpooling over channel dimension: class ChannelPool(nn.Module): def forward(self, input): return torch.max(input, dim=1) but I get the error AttributeError: 'torch.return_types.max' object has no attribute 'dim' | The torch.max function called with dim returns a tuple so: class ChannelPool(nn.Module): def forward(self, input): input_max, max_indices = torch.max(input, dim=1) return input_max From the documentation of torch.max: Returns a namedtuple (values, indices) where values is the maximum value of each row of the input te... | 17 | 28 |
60,927,188 | 2020-3-30 | https://stackoverflow.com/questions/60927188/django-3-x-error-mysql-connector-django-isnt-an-available-database-backend | Having recently upgraded a Django project from 2.x to 3.x, I noticed that the mysql.connector.django backend (from mysql-connector-python) no longer works. The last version of Django that it works with is 2.2.11. It breaks with 3.0. I am using mysql-connector-python==8.0.19. When running manage.py runserver, the follow... | For Django 3.0 and Django 3.1 I managed to have it working with mysql-connector-python 8.0.22. See this https://dev.mysql.com/doc/relnotes/connector-python/en/news-8-0-22.html. | 8 | 5 |
60,885,641 | 2020-3-27 | https://stackoverflow.com/questions/60885641/problem-while-installing-virtualenvwrapper-with-pyenv-pipx | I'm trying to install virtualenvwrapper (not pyenv-virtualenvwrapper) in my macOS (using zsh). I'm using pyenv to mange multiple python versions and pipx to install CLI stuff. I'm using Python 3.8.1 $ pyenv versions system 2.7.17 * 3.8.1 (set by /Users/my_user/.pyenv/version) I installed virtualenvwrapper with pipx $... | Fixed specifying a specific VIRTUALENVWRAPPER_PYTHON without pointing to the shim export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/Users/my_user/.local/pipx/venvs/virtualenvwrapper/bin/python3.8 source /Users/my_user/.local/pipx/venvs/virtualenvwrapper/bin/virtualenvwrapper.sh | 8 | 14 |
60,949,936 | 2020-3-31 | https://stackoverflow.com/questions/60949936/why-bilinear-scaling-of-images-with-pil-and-pytorch-produces-different-results | In order to feed an image to the pytorch network I first need to downscale it to some fixed size. At first I've done it using PIL.Image.resize() method, with interpolation mode set to BILINEAR. Then I though it would be more convenient to first convert a batch of images to pytorch tensor and then use torch.nn.functiona... | "Bilinear interpolation" is an interpolation method. But downscaling an image is not necessarily only accomplished using interpolation. It is possible to simply resample the image as a lower sampling rate, using an interpolation method to compute new samples that don't coincide with old samples. But this leads to alias... | 8 | 9 |
60,912,744 | 2020-3-29 | https://stackoverflow.com/questions/60912744/install-pytorch-from-requirements-txt | Torch documentation says use pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html to install the latest version of PyTorch. This works when I do it manually but when I add it to req.txt and do pip install -r req.txt, it fails and says ERROR: No matching distribution... | Add --find-links in requirements.txt before torch --find-links https://download.pytorch.org/whl/torch_stable.html torch==1.2.0+cpu Source: https://github.com/pytorch/pytorch/issues/29745#issuecomment-553588171 | 49 | 69 |
60,897,366 | 2020-3-28 | https://stackoverflow.com/questions/60897366/how-to-read-rtf-file-and-convert-into-python3-strings-and-can-be-stored-in-pyth | I am having a .rtf file and I want to read the file and store strings into list using python3 by using any package but it should be compatible with both Windows and Linux. I have tried striprtf but read_rtf is not working. from striprtf.striprtf import rtf_to_text from striprtf.striprtf import read_rtf rtf = read_rtf("... | Have you tried this? with open('yourfile.rtf', 'r') as file: text = file.read() print(text) For a super large file, try this: with open("yourfile.rtf") as infile: for line in infile: do_something_with(line) | 9 | 8 |
60,868,719 | 2020-3-26 | https://stackoverflow.com/questions/60868719/how-can-a-google-cloud-python-function-access-a-private-python-package | I am using Google Cloud Function using Python. Several other functions are in production. However, for this, I have additionally created a custom Python package that is available on github as a private repo. I need to install the package in the Google Function WHAT I HAVE DONE I run the Google Function in local usin... | You can not access the private repo from cloud function. According to the official documentation: " Using private dependencies Dependencies are installed in a Cloud Build environment that does not provide access to SSH keys. Packages hosted in repositories that require SSH-based authentication must be vendored and upl... | 11 | 4 |
60,894,682 | 2020-3-27 | https://stackoverflow.com/questions/60894682/jupyter-notebook-exported-html-dark-color | I am using JupyterLab with light theme and when I exported my notebook as HTML I saw this: What I am expecting to see is something like this: any ideas of the setting ? | I had the exact same issue. After a couple hours debugging I realized it had to do (for me at least) with the jupyter-theme library. I had a dark theme installed, and I think nbconverter uses whichever settings your jupyter is also using, so the dark settings were affecting the html conversion. Solution was simply to ... | 12 | 5 |
60,860,121 | 2020-3-26 | https://stackoverflow.com/questions/60860121/plotly-how-to-make-an-annotated-confusion-matrix-using-a-heatmap | I like to use Plotly to visualize everything, I'm trying to visualize a confusion matrix by Plotly, this is my code: def plot_confusion_matrix(y_true, y_pred, class_names): confusion_matrix = metrics.confusion_matrix(y_true, y_pred) confusion_matrix = confusion_matrix.astype(int) layout = { "title": "Confusion Matrix",... | You can use annotated heatmaps with ff.create_annotated_heatmap() to get this: Complete code: import plotly.figure_factory as ff z = [[0.1, 0.3, 0.5, 0.2], [1.0, 0.8, 0.6, 0.1], [0.1, 0.3, 0.6, 0.9], [0.6, 0.4, 0.2, 0.2]] x = ['healthy', 'multiple diseases', 'rust', 'scab'] y = ['healthy', 'multiple diseases', 'rust',... | 10 | 18 |
60,935,289 | 2020-3-30 | https://stackoverflow.com/questions/60935289/ego-graph-in-networkx | I have bipartite graph with nodes such as(a1,a2,...a100, m1,m2,...). I want to find the induced subgraph for certain nodes say(a1,a2 and a10). I can do this by using networkx.ego_graph, but it takes one vertex at one time and returns the induced graph. I want to know if there is any way to do this at once for all the n... | For the general case, the ego graph can be obtained using nx.ego_graph. Though in your specific case, it looks like you want to find the largest induced ego graph in the network. For that you can first find the node with a highest degree, and then obtain its ego graph. Let's create an example bipartite graph: import ... | 8 | 6 |
60,896,993 | 2020-3-28 | https://stackoverflow.com/questions/60896993/importerror-cannot-import-name-url-encode-from-werkzeug | I am currently running a conda environment with flask-wtf version 0.14.2 and wtforms version 2.21 and I have trouble solving this ImportError: cannot import name 'url_encode' from 'werkzeug' The following code is the complete traceback. Traceback (most recent call last): File "run.py", line 1, in <module> from flaskblo... | Setting werkzeug==0.16.1 in your requirements file fixes it. The issue is with the 1.0.0 version | 26 | 43 |
60,926,079 | 2020-3-30 | https://stackoverflow.com/questions/60926079/pipenv-install-runtimeerror-location-not-created-nor-specified | I am using Pipenv to manage project dependencies. It was working fine so far until now. Now I am trying to bootstrap an environment with pipenv install and I am getting the following error: ❯ pipenv install --dev --skip-lock Creating a virtualenv for this project… Pipfile: /Users/user/project/Pipfile Using /usr/bin/pyt... | So I manage to make it work. My default python system installation was 3.7.3. However, pipenv didn't like that one for some reason. I installed python 3.7.7 with homebrew and pipenv was able to locate that version properly and use it to create a virtual environment. In summary, to fix this issue try to install python a... | 9 | 9 |
60,879,701 | 2020-3-27 | https://stackoverflow.com/questions/60879701/socketio-flask-detect-disconnect | I had a different question here, but realized it simplifies to this: How do you detect when a client disconnects (closes their page or clicks a link) from a page (in other words, the socket connection closes)? I want to make a chat app with an updating user list, and I’m using Flask on Python. When the user connects, t... | Figured it out. socket.on('disconnect') did turn out to be right, however by default it pings each user only once a minute or so, meaning it took a long time to see the event. | 7 | 7 |
60,960,535 | 2020-3-31 | https://stackoverflow.com/questions/60960535/split-a-python-list-into-chunks-with-maximum-memory-size | Given a python list of bytes values: # actual str values un-important [ b'foo', b'bar', b'baz', ... ] How can the list be broken into chunks where each chunk has the maximum memory size below a certain ceiling? For example: if the ceiling were 7 bytes, then the original list would be broken up into a list of lists [ [... | This solution is with functools.reduce. l = [b'abc', b'def', b'ghi', b'jklm', b'nopqrstuv', b'wx', b'yz'] reduce(lambda a, b, size=7: a[-1].append(b) or a if a and sum(len(x) for x in a[-1]) + len(b) <= size else a.append([b]) or a, l, []) a is an empty list and b is an item from the original list. if a and sum(len(x)... | 7 | 2 |
60,886,568 | 2020-3-27 | https://stackoverflow.com/questions/60886568/google-colab-not-loading-image-files-while-using-tensorflow-2-0-batched-dataset | A little bit of background, I am loading about 60,000 images to colab to train a GAN. I have already uploaded them to Drive and the directory structure contains folders for different classes (about 7-8) inside root. I am loading them to colab as follows: root = "drive/My Drive/data/images" root = pathlib.Path(root) lis... | Here is how I load a 1.12GB zipped FLICKR image dataset from my personal Google Drive. First, I unzip the dataset in the colab environment. Some features that can speed up the performance is prefetch and autotune. Additionally, I use the local colab cache to store the processed images. This takes ~20 seconds to execute... | 8 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.