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,314,440 | 2020-4-20 | https://stackoverflow.com/questions/61314440/certbort-commands-return-modulenotfounderror-no-module-named-cffi-backend | I followed a guide to get my python flask app running and I am at the last step where I change http into https with certbot. But when I run my certbot command sudo certbot --nginx -d domainname -d www.domainname I get ModuleNotFoundError: No module named '_cffi_backend' The whole error is: Traceback (most recent call ... | This fixes the problem: pip install -U cffi | 9 | 21 |
61,241,374 | 2020-4-16 | https://stackoverflow.com/questions/61241374/attributeerror-module-os-has-no-attribute-uname | When I do: >>> import os >>> os.uname() I get an attribute error which looks like this: Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> os.uname() AttributeError: module 'os' has no attribute 'uname' How can I fix this is my python broken or something else because in the docs. | I've run your code the exact same way in IDLE on Windows 10 and got the same result. >>> print(os.uname()) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print(os.uname()) AttributeError: module 'os' has no attribute 'uname' And as @Joran Beasley pointed out, this function is only available... | 15 | 11 |
61,241,172 | 2020-4-16 | https://stackoverflow.com/questions/61241172/plotly-how-to-create-sunburst-subplot-using-graph-objects | my dataframe looks something like this: user age gender 0 23 12 male 1 24 13 male 2 25 15 female 3 26 20 male 4 27 21 male and using px.sunburst(df, path=["gender", "age"]) gives me correct sunburst plot where gender is in middle part of pie chart and for each gender it has associated ages. I want to do this using g... | The answer: Just build one figure using px, and "steal" all your figure elements from there and use it in a graph_objects figure to get what you need! The details: If px does in fact give you the desired sunburst chart like this: Plot 1: Code 1: # imports import pandas as pd import plotly.graph_objects as go import p... | 8 | 17 |
61,330,427 | 2020-4-20 | https://stackoverflow.com/questions/61330427/set-y-axis-in-millions | I have a problem with this plot: The y-axis is in unit but I need them to be in millions as such: Do you know a method to achieve this? Thanks in advance. | You can use a custom FuncFormatter like this: from matplotlib.ticker import FuncFormatter import matplotlib.pyplot as plt def millions(x, pos): 'The two args are the value and tick position' return '%1.1fM' % (x * 1e-6) formatter = FuncFormatter(millions) fig, ax = plt.subplots() ax.yaxis.set_major_formatter(formatter)... | 12 | 21 |
61,321,143 | 2020-4-20 | https://stackoverflow.com/questions/61321143/12296266720420-163936-459errorbrowser-switcher-service-cc238-xxx-init-er | I am using Version 81.0.4044.113 (Official Build) (64-bit). It was not happening before and the code was working completely fine. But after few days I ran it again and this error came. I am using these modules-> from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.u... | This error message... ERROR:browser_switcher_service.cc(238)] XXX Init() ...implies that call to on_init_ raised an error. Analysis This error is defined in bluetooth_adapter_winrt.cc and was the direct impact of the changes incorporated within google-chrome as per the details available within the discussion Chrome n... | 14 | 1 |
61,226,587 | 2020-4-15 | https://stackoverflow.com/questions/61226587/pycharm-does-not-recognize-logging-basicconfig-handlers-argument | I have a python application that uses the python logging library for some time now for printing messages both on the screen and on time rotating files and works fine. The logging configuration is as follows: import logging from logging.handlers import TimedRotatingFileHandler logging.basicConfig(level=logging.INFO if d... | This issue is reported on PyCharm bug tracker at https://youtrack.jetbrains.com/issue/PY-39762 . In short: the new keyword arguments of basicConfig in Python 3, like handler, are not recognized. That issue also mentions a workaround: Put a caret on basicConfig - Right Click - Go to - Declaration or Usages - Click on a... | 9 | 6 |
61,346,100 | 2020-4-21 | https://stackoverflow.com/questions/61346100/plotly-how-to-style-a-plotly-figure-so-that-it-doesnt-display-gaps-for-missing | I have a plotly graph of the EUR/JPY exchange rate across a few months in 15 minute time intervals, so as a result, there is no data from friday evenings to sunday evenings. Here is a portion of the data, note the skip in the index (type: DatetimeIndex) over the weekend: Plotting this data in plotly results in a gap o... | Even if some dates are missing in your dataset, plotly interprets your dates as date values, and shows even missing dates on your timeline. One solution is to grab the first and last dates, build a complete timeline, find out which dates are missing in your original dataset, and include those dates in: fig.update_xaxes... | 14 | 15 |
61,238,162 | 2020-4-15 | https://stackoverflow.com/questions/61238162/why-cant-i-import-candlestick-ohlc-from-mplfinance | So I have been able to successfully install mplfinance with pip and when I import it alone I receive no error. Though when I do: from mplfinance import candlestick_ohlc I get the error ImportError: cannot import name 'candlestick_ohlc' from 'mplfinance' I have checked command prompt again, and it says it has successful... | So from what I understand the Matplotlib for finance has changed so that: To access the old API with the new mplfinance package installed, change statments from: from mpl_finance import to: from mplfinance.original_flavor import candlestick_ohlc and then it should work fine. | 17 | 36 |
61,296,763 | 2020-4-18 | https://stackoverflow.com/questions/61296763/why-cnn-running-in-python-is-extremely-slow-in-comparison-to-matlab | I have trained a CNN in Matlab 2019b that classifies images between three classes. When this CNN was tested in Matlab it was functioning fine and only took 10-15 seconds to classify an image. I used the exportONNXNetwork function in Maltab so that I can implement my CNN in Tensorflow. This is the code I am using to use... | In this case, it appears that the Grapper optimization suite has encountered some kind of infinite loop or memory leak. I would recommend filing an issue against the Github repo. It's challenging to debug why constant folding is taking so long, but you may have better performance using the ONNX TensorRT backend as comp... | 8 | 1 |
61,333,273 | 2020-4-20 | https://stackoverflow.com/questions/61333273/how-to-use-edge-bundling-with-networkx-and-matplotlib-in-python | I've created a toy graph with the iris dataset. My layout is from PCA ordination which separates out the nodes nicely. I've recently discovered edge bundling. Does anybody know of a way to do this with matplotlib and networkx? from sklearn.decomposition import PCA import pandas as pd import networkx as nx import matp... | This can be done fairly easily for matplotlib using hammer_bundle from datashader. Datashader is a python library which uses a lot of pandas DataFrames, so getting the data into a format for matplotlib is fairly easy. (I assume the main goal is to plot this easily in matplotlib, but if one really doesn't want to instal... | 15 | 10 |
61,331,079 | 2020-4-20 | https://stackoverflow.com/questions/61331079/how-to-configure-celery-worker-and-beat-for-email-reporting-in-apache-superset-r | I am running Superset via Docker. I enabled the Email Report feature and tried it: However, I only receive the test email report. I don't receive any emails after. This is my CeleryConfig in superset_config.py: class CeleryConfig(object): BROKER_URL = 'sqla+postgresql://superset:superset@db:5432/superset' CELERY_IMPOR... | I managed to solve it by altering the CeleryConfig implementation, and adding a beat service to 'docker-compose.yml' New CeleryConfig class in 'superset_config.py': REDIS_HOST = get_env_variable("REDIS_HOST") REDIS_PORT = get_env_variable("REDIS_PORT") class CeleryConfig(object): BROKER_URL = "redis://%s:%s/0" % (REDIS... | 8 | 3 |
61,299,553 | 2020-4-19 | https://stackoverflow.com/questions/61299553/subclassing-is-it-possible-to-override-a-property-with-a-conventional-attribute | Let's assume we want to create a family of classes which are different implementations or specializations of an overarching concept. Let's assume there is a plausible default implementation for some derived properties. We'd want to put this into a base class class Math_Set_Base: @property def size(self): return len(sel... | A property is a data descriptor which takes precedence over an instance attribute with the same name. You could define a non-data descriptor with a unique __get__() method: an instance attribute takes precedence over the non-data descriptor with the same name, see the docs. The problem here is that the non_data_propert... | 24 | 13 |
61,238,840 | 2020-4-15 | https://stackoverflow.com/questions/61238840/xarray-reverse-interpolation-on-coordinate-not-on-data | I have a the following DataArray arr = xr.DataArray([[0.33, 0.25],[0.55, 0.60],[0.85, 0.71],[0.92,0.85],[1.50,0.96],[2.5,1.1]],[('x',[0.25,0.5,0.75,1.0,1.25,1.5]),('y',[1,2])]) This gives the following output <xarray.DataArray (x: 6, y: 2)> array([[0.33, 0.25], [0.55, 0.6 ], [0.85, 0.71], [0.92, 0.85], [1.5 , 0.96], [... | The problem I had with jojo's answer is that it is difficult to expand it in many dimensions and to keep the xarray structure. Hence, I decided to look further into this. I used some ideas from jojo's code to make below answer. I make two arrays, one with the condition that the values are smaller than what I look for,... | 9 | 1 |
61,348,795 | 2020-4-21 | https://stackoverflow.com/questions/61348795/generate-list-of-numbers-and-their-negative-counterparts-in-python | Is there a convenient one-liner to generate a list of numbers and their negative counterparts in Python? For example, say I want to generate a list with the numbers 6 to 9 and -6 to -9. My current approach is: l = [x for x in range(6,10)] l += [-x for x in l] A simple "one-liner" would be: l = [x for x in range(6,10)]... | I am unsure if order matters, but you could create a tuple and unpack it in a list comprehension. nums = [y for x in range(6,10) for y in (x,-x)] print(nums) [6, -6, 7, -7, 8, -8, 9, -9] | 63 | 71 |
61,346,009 | 2020-4-21 | https://stackoverflow.com/questions/61346009/why-is-pil-used-so-often-with-pytorch | I noticed that a lot of dataloaders use PIL to load and transform images, e.g. the dataset builders in torchvision.datasets.folder. My question is: why use PIL? You would need to do an np.asarray operation before turning it into a tensor. OpenCV seems to load it directly as a numpy array, and is faster too. One reason ... | There is a discussion about adding OpenCV as one of possible backends in torchvision PR. In summary, some reasons provided: OpenCV2 loads images in BGR format which would require wrapper class to handle changing to RGB internally or format of loaded images backend dependent This in turn would lead to code duplication ... | 9 | 15 |
61,249,708 | 2020-4-16 | https://stackoverflow.com/questions/61249708/valueerror-no-gradients-provided-for-any-variable-tensorflow-2-0-keras | I am trying to implement a simple sequence-to-sequence model using Keras. However, I keep seeing the following ValueError: ValueError: No gradients provided for any variable: ['simple_model/time_distributed/kernel:0', 'simple_model/time_distributed/bias:0', 'simple_model/embedding/embeddings:0', 'simple_model/conv2d/ke... | There are two different sets of problems in your code, which could be categorized as syntactical and architectural problems. The error raised (i.e. No gradients provided for any variable) is related to the syntactical problems which I would mostly address below, but I would try to give you some pointers about the archi... | 8 | 24 |
61,336,238 | 2020-4-21 | https://stackoverflow.com/questions/61336238/getting-attributeerror-module-pandas-has-no-attribute-json-normalize-while | I am exploring the Jupiter notebook for Python. While calling this method "Access OutbreakLocation data" I get this exception in Python 3.6: getting AttributeError: module 'pandas' has no attribute 'json_normalize' Any ideas how can we fix this issue? | Make sure to update to Pandas 1.0.3. Pandas prior to version 1 doesn't have json_normalize. | 18 | 16 |
61,253,928 | 2020-4-16 | https://stackoverflow.com/questions/61253928/writing-pandas-dataframe-to-s3-bucket-aws | I have an AWS Lambda function which queries API and creates a dataframe, I want to write this file to an S3 bucket, I am using: import pandas as pd import s3fs df.to_csv('s3.console.aws.amazon.com/s3/buckets/info/test.csv', index=False) I am getting an error: No such file or directory: 's3.console.aws.amazon.com/s3/b... | You can use boto3 package also for storing data to S3: from io import StringIO # python3 (or BytesIO for python2) import boto3 bucket = 'info' # already created on S3 csv_buffer = StringIO() df.to_csv(csv_buffer) s3_resource = boto3.resource('s3') s3_resource.Object(bucket, 'df.csv').put(Body=csv_buffer.getvalue()) | 14 | 35 |
61,341,712 | 2020-4-21 | https://stackoverflow.com/questions/61341712/calculate-projected-point-location-x-y-on-given-line-startx-y-endx-y | If i have three points P1, P2, P3 with their coordinates(x,y) P1(x,y) and P3(x,y) are coordinate of line(start, end) and P3 is a point need to be projected. how can i find the coordinate of point r(x,y) which is projection of P3 over P1 and P2 | This solution extends to points with any geometric dimensions (2D, 3D, 4D, ...). It assumes all points are one dimensional numpy arrays (or two dimensional with one dimension shape 1). I am not sure if you require the projection to fall onto line segment or the extension of segment so I include both. You can pick which... | 10 | 13 |
61,338,539 | 2020-4-21 | https://stackoverflow.com/questions/61338539/how-to-use-enum-value-in-asdict-function-from-dataclasses-module | I have a dataclass with a field template of type Enum. When using the asdict function it converts my dataclass to a dictionary. Is it possible to use the value attribute of FoobarEnum to return the string value instead of the Enum object? My initial idea was to use the dict_factory=dict parameter of the asdict function... | This can't be done with standard library except maybe by some metaclass enum hack I'm not aware of. Enum.name and Enum.value are builtin and not supposed to be changed. The approach of using the dataclass default_factory isn't going to work either. Because default_factory is called to produce default values for the dat... | 38 | 7 |
61,339,594 | 2020-4-21 | https://stackoverflow.com/questions/61339594/how-to-convert-a-dictionary-to-dataframe-in-pyspark | I am trying to convert a dictionary: data_dict = {'t1': '1', 't2': '2', 't3': '3'} into a dataframe: key | value| ---------------- t1 1 t2 2 t3 3 To do that, I tried: schema = StructType([StructField("key", StringType(), True), StructField("value", StringType(), True)]) ddf = spark.createDataFrame(data_dict, schema) ... | You can use data_dict.items() to list key/value pairs: spark.createDataFrame(data_dict.items()).show() Which prints +---+---+ | _1| _2| +---+---+ | t1| 1| | t2| 2| | t3| 3| +---+---+ Of course, you can specify your schema: spark.createDataFrame(data_dict.items(), schema=StructType(fields=[ StructField("key", StringTy... | 9 | 11 |
61,234,609 | 2020-4-15 | https://stackoverflow.com/questions/61234609/how-to-import-python-package-from-another-directory | I have a project that is structured as follows: project ├── api │ ├── __init__.py │ └── api.py ├── instance │ ├── __init__.py │ └── config.py ├── package │ ├── __init__.py │ └── app.py ├── requirements.txt └── tests └── __init__.py I am trying to call the config.py file from the package/app.py as shown below: # packa... | You can add the parent directory to PYTHONPATH, in order to achieve that, you can use OS depending path in the "module search path" which is listed in sys.path. So you can easily add the parent directory like following: import sys sys.path.insert(0, '..') from instance import config Note that the previous code uses a ... | 33 | 29 |
61,337,373 | 2020-4-21 | https://stackoverflow.com/questions/61337373/split-on-train-and-test-separating-by-group | I have a sample data as follows: import pandas as pd df = pd.DataFrame({"x": [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120], "id": [1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5], "label": ["a", "a", "a", "b", "a", "b", "b", "b", "a", "b", "a", "b"]}) So my data look like this x id label 10 1 a 20 1 a 30 1 a 40 1 b 50 2 a ... | sklearn.model_selection has several other options other than train_test_split. One of them, aims at solving what you're after. In this case you could use GroupShuffleSplit, which as mentioned inthe docs it provides randomized train/test indices to split data according to a third-party provided group. You also have Grou... | 10 | 10 |
61,337,007 | 2020-4-21 | https://stackoverflow.com/questions/61337007/pysftp-library-not-working-in-aws-lambda-layer | I want to upload files to EC2 instance using pysftp library (Python script). So I have created small Python script which is using below line to connect pysftp.Connection( host=Constants.MY_HOST_NAME, username=Constants.MY_EC2_INSTANCE_USERNAME, private_key="./mypemfilelocation.pem", ) some code here ..... pysftp.put(fi... | I build pysftp layer and tested it on my lambda with python 3.8. Just to see import and basic print: import json import pysftp def lambda_handler(event, context): # TODO implement print(dir(pysftp)) return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } I used the following docker tool to build the pys... | 8 | 8 |
61,334,085 | 2020-4-21 | https://stackoverflow.com/questions/61334085/breaking-change-for-google-api-python-client-1-8-1-attributeerror-module-goo | After upgrading to the new google-api-python-client 1.8.1 I'm receiving this error. Do we know if python 3.8 breaks the latest google-api-core? And whether there's a solution Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_proc... | I had the same error and changing the import fixed it for me. The developers recommend importing from googleapiclient instead of apiclient. So you will need to change from apiclient import errors to from googleapiclient import errors | 8 | 9 |
61,328,571 | 2020-4-20 | https://stackoverflow.com/questions/61328571/standard-init-linux-go211-exec-user-process-caused-no-such-file-or-directory | Dockerfile FROM python:3.7.4-alpine ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV LANG C.UTF-8 MAINTAINER "mail@gmail.com" RUN apk update && apk add postgresql-dev gcc musl-dev RUN apk --update add build-base jpeg-dev zlib-dev RUN pip install --upgrade setuptools pip RUN mkdir /code WORKDIR /code COPY requir... | The "shebang" line at the start of a script says what interpreter to use to run it. In your case, your script has specified #!/bin/bash, but Alpine-based Docker images don't typically include GNU bash; instead, they have a more minimal /bin/sh that includes just the functionality in the POSIX shell specification. Your ... | 10 | 18 |
61,325,817 | 2020-4-20 | https://stackoverflow.com/questions/61325817/differences-between-matplotlib-and-matplotlib-base | While updating my packages I've noticed that there is a package named "matplotlib-base". I couldn't figure out what the difference to "matplotlib" is, neither on the official website nor here on Stack Overflow, and I also couldn't find any repository to compare the code. Any ideas? | The packages are similar, but differ in their dependencies: matplotlib depends on matplotlib-base and pyqt. Therefore installing matplotlib will also pull in the qt stack, while installing matplotlib-base does not. Users that do not need qt backends and prefer a slim installation will prefer matplotlib-base over matplo... | 16 | 19 |
61,327,917 | 2020-4-20 | https://stackoverflow.com/questions/61327917/why-does-using-return-a-series-instead-of-bool-in-pandas | I just can't figure out what "==" means at the second line: - It is not a test, there is no if statement... - It is not a variable declaration... I've never seen this before, the thing is data.ctage==cat is a pandas Series and not a test... for cat in data["categ"].unique(): subset = data[data.categ == cat] # Création ... | It is testing each element of data.categ for equality with cat. That produces a vector of True/False values. This is passed as in indexer to data[], which returns the rows from data that correspond to the True values in the vector. To summarize, the whole expression returns the subset of rows from data where the value ... | 13 | 13 |
61,327,385 | 2020-4-20 | https://stackoverflow.com/questions/61327385/trying-to-use-on-path-object-python | The program takes an optional command line argument (which is meant to be a directory path) I am using python pathlib and shutil to move files. Here's the code: from pathlib import Path path = Path(sys.argv[1]) shutil.move(path / file, path / e.upper()) Where e is just a string representing certain file extension; Inp... | Use the rename function of Path to move a file, if you're using the pathlib module. ie. (path / file).rename(path / e.upper()) Otherwise, if you wish to use the shutil module, then you must convert your paths to strings before passing them to shutil.move() ie. shutil.move(str(path / file), str(path / e.upper())) | 9 | 16 |
61,319,140 | 2020-4-20 | https://stackoverflow.com/questions/61319140/difference-between-numpy-and-tensorflow | Are NumPy and TensorFlow the same thing? I just started learning programming; I was learning AI and found TensorFlow. I started to look at videos and I saw the code snippets below: import tensorflow as tf tf.ones([1,2,3]) tf.zeros([2,3,2]) import numpy as np np.zeros([2,3,2]) np.ones([1,2,3]) | Although the method names and parameters look identical, they are not the same thing. This becomes clear in the debugger. Just assign the results to variables and inspect them: As you can see, Tensorflow gives you an EagerTensor and NumPy gives you an NDArray. Tensorflow is a library for artificial intelligence, espec... | 9 | 2 |
61,313,365 | 2020-4-20 | https://stackoverflow.com/questions/61313365/pandas-futurewarning-columnar-iteration-over-characters-will-be-deprecated-in-f | I have an existing solution to split a dataframe with one column into 2 columns. df['A'], df['B'] = df['AB'].str.split(' ', 1).str Recently, I got the following warning FutureWarning: Columnar iteration over characters will be deprecated in future releases. How to fix this warning? I'm using python 3.7 | That's not entirely correct, plus the trailing .str does not make sense. Since split with expand returns a DataFrame, this is easier: df[['A', 'B']] = df['AB'].str.split(' ', n=1, expand=True) Your existing method without expand returns a single Series with a list of columns. I'm not sure what version of pandas used ... | 14 | 23 |
61,305,921 | 2020-4-19 | https://stackoverflow.com/questions/61305921/pandas-select-columns-using-list-but-ignore-missing-column-names | I have a dataframe 'A' 'B' 'C' 'X' ,'Y' , 'Z' 0 1 2 3 4 5 and a list l=[A,B,C,D,E,F] I want to use that that list to select columns that are in the list but ignore the ones that don't appear. So the expected output is 'A' 'B' 'C' 0 1 2 3 4 5 | Use DataFrame.loc for select all rows by : and columns by mask created by Index.isin : df = df.loc[:, df.columns.isin(l)] Or get columns names by Index.intersection: df = df[df.columns.intersection(l)] print (df) A B C 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 NaN NaN NaN 4 NaN NaN NaN 5 NaN NaN NaN | 7 | 22 |
61,292,759 | 2020-4-18 | https://stackoverflow.com/questions/61292759/how-to-fill-elements-between-intervals-of-a-list | I have a list like this: list_1 = [np.NaN, np.NaN, 1, np.NaN, np.NaN, np.NaN, 0, np.NaN, 1, np.NaN, 0, 1, np.NaN, 0, np.NaN, 1, np.NaN] So there are intervals that begin with 1 and end with 0. How can I replace the values in those intervals, say with 1? The outcome will look like this: list_2 = [np.NaN, np.NaN, 1, 1, ... | Pandas solution: s = pd.Series(list_1) s1 = s.eq(1) s0 = s.eq(0) m = (s1 | s0).where(s1.cumsum().ge(1),False).cumsum().mod(2).eq(1) s.loc[m & s.isna()] = 1 print(s.tolist()) #[nan, nan, 1.0, 1.0, 1.0, 1.0, 0.0, nan, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, nan, 1.0, 1.0] but if there is only 1, 0 or NaN you can do: s = pd.Serie... | 9 | 5 |
61,257,658 | 2020-4-16 | https://stackoverflow.com/questions/61257658/python-dataclasses-mocking-the-default-factory-in-a-frozen-dataclass | I'm attempting to use freezegun in my unit tests to patch a field in a dataclass that is set to the current date when the object is initialised. I would imagine the question is relevant to any attempt to patch a function being used as a default_factory outside of just freezegun. The dataclass is frozen so its immutable... | You're right, the dataclass creation process does something strange here which leads to your current problem. It binds the factory function during class creation, which means that it holds a reference of the code before freezegun had a chance to patch it. Here is an example without dataclasses that runs into the same i... | 8 | 11 |
61,273,244 | 2020-4-17 | https://stackoverflow.com/questions/61273244/how-to-downgrade-torch-version-for-google-colab | I would like to downgrade the Torch version used in my Google Colab notebooks. How could I do that? | Run from your cell: !pip install torch==version Where version could be, for example, 1.3.0 (default is 1.4.0). You may have to downgrade torchvision appropriately as well so you would go with: !pip install torch==1.3.0 torchvision==0.4.1 On the other hand PyTorch provides backward compatibility between major versions... | 10 | 7 |
61,269,796 | 2020-4-17 | https://stackoverflow.com/questions/61269796/aws-lambda-returning-json-data-as-string | I am using AWS Lambda to create my APIs and want to return an array's data in JSON format. However, when I call the lambda, it is able to return the required JSON data but it is coming as a string in double quotes. I tried running the same code in my Python IDE and everything works fine but when I try to return it in L... | I'm not sure if this is what you want, but you can just do 'body': json_data. I tested this now in my λ function: Lambda function import json def lambda_handler(event, context): json_data = [{"Dp_Record_Id": 2, "DP_TYPE": "NSDL", "DP_ID": "40877589", "CLIENT_ID": "1232", "Default_flag": "Y"}] return {'statusCode': 200,... | 10 | 9 |
61,261,907 | 2020-4-16 | https://stackoverflow.com/questions/61261907/on-colab-class-weight-is-causing-a-valueerror-the-truth-value-of-an-array-wit | i'm running a CNN with keras sequential on google colab. i'm getting the following error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() when i remove the class_weight argument from the model.fit function, the error is gone and the network is trained succesfully.... | The problem is that the sklearn API returns a numpy array but the keras requires a dictionary as an input for class_weight (see here). You can resolve the error using below method: from sklearn.utils import class_weight weight = class_weight.compute_class_weight('balanced', np.unique(y_train), y_train) weight = {i : we... | 14 | 27 |
61,266,275 | 2020-4-17 | https://stackoverflow.com/questions/61266275/epoch-1-2-103-unknown-8s-80ms-step-loss-0-0175-model-fit-keeps-running-f | I am developing autoencoder on the dataset https://www.kaggle.com/jessicali9530/celeba-dataset. import tensorflow tensorflow.__version__ Output: '2.2.0-rc3' from tensorflow.keras.preprocessing import image data_gen = image.ImageDataGenerator(rescale=1.0/255) batch_size = 20 train_data_gen = data_gen.flow_from_direc... | When executing model.fit with a generator as input you have to set the steps_per_epoch argument. For generators you can't know the number of images they output (and in this case they go on forever), so set it to the number of images in your dataset divided by your batch size. | 9 | 16 |
61,249,612 | 2020-4-16 | https://stackoverflow.com/questions/61249612/error-unable-to-download-video-data-http-error-403-forbidden-while-using-yout | I am trying to download songs from youtube using python 3.8 and youtube_dl 2020.3.24. But the weird thing is that most songs I try to download don't get downloaded. I'm talking 99% of them. The ones that do get downloaded get the following Error from youtube_dl: ERROR: unable to download video data: HTTP Error 403: For... | Same problem many times .. solution: youtube-dl --rm-cache-dir Cause of the problem: Sometimes I download playlists of large videos and I force it to stop downloading, the next time I run the command to resume the download, the 403 problem arises At the moment, the cache directory is used only to store youtube players ... | 25 | 40 |
61,250,311 | 2020-4-16 | https://stackoverflow.com/questions/61250311/error-importing-bert-module-tensorflow-api-v2-train-has-no-attribute-optimi | I tried to use bert-tensorflow in Google Colab, but I got the following error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () 1 import bert ----> 2 from bert import run_classifier_with_tfhub # run_classifier 3 from bert import optimiza... | I did some experimentation in my own colab notebook (please provide a link next time) and I found that in the error message, there was class AdamWeightDecayOptimizer(tf.train.Optimizer): this being the header of the class. But there is nothing like tf.train.optimizer instead it should be : class AdamWeightDecayOptimi... | 10 | 9 |
61,251,473 | 2020-4-16 | https://stackoverflow.com/questions/61251473/compare-lists-in-the-same-dictionary-of-lists | In resume, I have two keys in the same dictionary where each one has their corresponding lists. I try to compare both list to check common and differential elements. It means that the output I will count how many elements are identical or present in only one key's list. from the beginning I am inserting the elements us... | A solution with list comprehension would be: dictionary = {'a':[1,2,3,4,5], 'b':[2,3,4,6]} only_in_a = [x for x in dictionary['a'] if not x in dictionary['b']] only_in_b = [x for x in dictionary['b'] if not x in dictionary['a']] in_both = [x for x in dictionary['a'] if x in dictionary['b']] Note that this is not espec... | 7 | 4 |
61,234,309 | 2020-4-15 | https://stackoverflow.com/questions/61234309/how-to-give-space-between-two-dcc-components-in-python-dash | What is the HTML equivalent for   (space) in Dash? html.Div( [ dcc.Input(), <add horizontal space here> dcc.Input() ] ) | If you want to add some space between components you can simply use CSS-properties for this: html.Div( [ dcc.Input(), dcc.Input(style={"margin-left": "15px"}) ] ) This adds a margin to the left of your second Input. Have a look at the layout-section in the Plotly Dash documentation and CSS documentation about margin: ... | 19 | 30 |
61,242,966 | 2020-4-16 | https://stackoverflow.com/questions/61242966/pytorch-attributeerror-function-object-has-no-attribute-copy | I am trying to load a model state_dict I trained on Google Colab GPU, here is my code to load the model: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = models.resnet50() num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, n_classes) model.load_state_dict(copy.deepcopy(torch.l... | I am guessing this is what you did by mistake. You saved the function torch.save(model.state_dict, 'model_state.pth') instead of the state_dict() torch.save(model.state_dict(), 'model_state.pth') Otherwise, everything should work as expected. (I tested the following code on Colab) Replace model.state_dict() with model... | 16 | 32 |
61,147,405 | 2020-4-10 | https://stackoverflow.com/questions/61147405/how-do-i-setup-my-own-time-zone-in-django | I live in Chittagong, Bangladesh and my time zone is GMT+6. How can i change to this time zone in Django settings? | You can specify the timezone as 'Asia/Dhaka' in the TIME_ZONE setting [Django-doc]: # settings.py TIME_ZONE = 'Asia/Dhaka' # … Note that if USE_TZ setting [Django-doc] is set to True, then: When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret dateti... | 11 | 16 |
61,153,546 | 2020-4-11 | https://stackoverflow.com/questions/61153546/addition-subtraction-of-integers-and-integer-arrays-with-timestamp-is-no-longer | I am using pytrends library to extract google trends and i am getting the following error: Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting n, use n * obj.freq timeframes = [] datelist = pd.date_range('2004-01-01', '2018-01-01', freq="AS") date =... | You can't sum a date and a number like date+4 because who knows which unit this is, 4h, 4d,... ? You may use datetime.timedelta, here's an example if you meant days from datetime import timedelta end_date = (date + timedelta(days=4)).strftime("%Y-%m-%d") # ... date = date + timedelta(days=3) | 28 | 30 |
61,149,803 | 2020-4-10 | https://stackoverflow.com/questions/61149803/threads-is-not-executing-in-parallel-python-with-threadpoolexecutor | I'm new in python threading and I'm experimenting this: When I run something in threads (whenever I print outputs), it never seems to be running in parallel. Also, my functions take the same time that before using the library concurrent.futures (ThreadPoolExecutor). I have to calculate the gains of some attributes over... | I had this same trouble and fixed by moving the iteration to within the context of the ThreadPoolExecutor, or else, you'll have to wait for the context to finish and start another one. Here is a probably fix for your code: def calculate_gains(self): splited_attributes = np.array_split(self.attributes, 10) result = {} w... | 11 | 1 |
61,140,398 | 2020-4-10 | https://stackoverflow.com/questions/61140398/fastapi-return-a-file-response-with-the-output-of-a-sql-query | I'm using FastAPI and currently I return a csv which I read from SQL server with pandas. (pd.read_sql()) However the csv is quite big for the browser and I want to return it with a File response: https://fastapi.tiangolo.com/advanced/custom-response/ (end of the page). I cannot seem to do this without first writing it ... | Based HEAVILY off this https://github.com/tiangolo/fastapi/issues/1277 Turn your dataframe into a stream use a streaming response Modify headers so it's a download (optional) from fastapi import FastAPI from fastapi.responses import StreamingResponse import io import pandas as pd app = FastAPI() @app.get("/get_csv") ... | 31 | 64 |
61,150,835 | 2020-4-11 | https://stackoverflow.com/questions/61150835/check-if-string-is-in-string-literal-type | We use static type checking extensively, but we also need some simple runtime type checking. I'd love to use our static types for that runtime type checking. I've seen typeguard and the other libraries, but I'd prefer to have something simpler. I've tried below, but assert value in expected_type doesn't make sense. How... | Python 3.8 introduced typing.get_args(tp), making this possible: assert value in get_args(expected_type) | 12 | 15 |
61,092,523 | 2020-4-8 | https://stackoverflow.com/questions/61092523/what-is-running-loss-in-pytorch-and-how-is-it-calculated | I had a look at this tutorial in the PyTorch docs for understanding Transfer Learning. There was one line that I failed to understand. After the loss is calculated using loss = criterion(outputs, labels), the running loss is calculated using running_loss += loss.item() * inputs.size(0) and finally, the epoch loss is c... | It's because the loss given by CrossEntropy or other loss functions is divided by the number of elements i.e. the reduction parameter is mean by default. torch.nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean') Hence, loss.item() contains the loss of entire mini-batch... | 22 | 33 |
61,116,190 | 2020-4-9 | https://stackoverflow.com/questions/61116190/what-are-all-the-formats-to-save-machine-learning-model-in-scikit-learn-keras | There are many ways to save a model and its weights. It is confusing when there are so many ways and not any source where we can read and compare their properties. Some of the formats I know are: 1. YAML File - Structure only 2. JSON File - Structure only 3. H5 Complete Model - Keras 4. H5 Weights only - Keras 5. Prot... | There are also formats like onnx which basically supports most of the frameworks and helps in removing the confusion of using different formats for different frameworks. | 14 | 3 |
61,156,894 | 2020-4-11 | https://stackoverflow.com/questions/61156894/pytorch-torch-max-over-multiple-dimensions | Have tensor like :x.shape = [3, 2, 2]. import torch x = torch.tensor([ [[-0.3000, -0.2926],[-0.2705, -0.2632]], [[-0.1821, -0.1747],[-0.1526, -0.1453]], [[-0.0642, -0.0568],[-0.0347, -0.0274]] ]) I need to take .max() over the 2nd and 3rd dimensions. I expect some like this [-0.2632, -0.1453, -0.0274] as output. I tri... | Now, you can do this. The PR was merged (Aug 28 2020) and it is now available in the nightly release. Simply use torch.amax(): import torch x = torch.tensor([ [[-0.3000, -0.2926],[-0.2705, -0.2632]], [[-0.1821, -0.1747],[-0.1526, -0.1453]], [[-0.0642, -0.0568],[-0.0347, -0.0274]] ]) print(torch.amax(x, dim=(1, 2))) # O... | 32 | 44 |
61,151,832 | 2020-4-11 | https://stackoverflow.com/questions/61151832/how-can-i-set-marker-size-based-on-column-value | I am trying to use plotly (version 4.6.0) to create plots, but having trouble with the markers/size attribute. I am using the Boston housing price dataset in my example. I want to use the value in one of the columns of my dataframe to set a variable size for the marker, but I get an error when I use a direct reference ... | import chart_studio.plotly as py import plotly.graph_objs as go from plotly.offline import iplot, init_notebook_mode import cufflinks cufflinks.go_offline(connected=True) init_notebook_mode(connected=True) import pandas as pd from sklearn.datasets import load_boston boston = load_boston() df = pd.DataFrame(boston.data,... | 9 | 5 |
61,152,889 | 2020-4-11 | https://stackoverflow.com/questions/61152889/plotly-how-to-set-node-positions-in-a-sankey-diagram | The sample data is as follows: unique_list = ['home0', 'page_a0', 'page_b0', 'page_a1', 'page_b1', 'page_c1', 'page_b2', 'page_a2', 'page_c2', 'page_c3'] sources = [0, 0, 1, 2, 2, 3, 3, 4, 4, 7, 6] targets = [3, 4, 4, 3, 5, 6, 8, 7, 8, 9, 9] values = [2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2] Using the sample code from the doc... | In go.Sankey() set arrangement='snap' and adjust x and y positions in x=<list> and y=<list>. The following setup will place your nodes as requested. Plot: Please note that the y-values are not explicitly set in this example. As soon as there are more than one node for a common x-value, the y-values will be adjusted au... | 11 | 15 |
61,184,906 | 2020-4-13 | https://stackoverflow.com/questions/61184906/difference-between-predict-vs-predict-proba-in-scikit-learn | Suppose I have created a model, and my target variable is either 0, 1 or 2. It seems that if I use predict, the answer is either of 0, or 1 or 2. But if I use predict_proba, I get a row with 3 cols for each row as follows, for example model = ... Classifier # It could be any classifier m1 = model.predict(mytest) m2= m... | predict() is used to predict the actual class (in your case one of 0, 1, or 2). predict_proba() is used to predict the class probabilities From the example output that you shared, predict() would output class 0 since the class probability for 0 is 0.6. [0.6, 0.2, 0.2] is the output of predict_proba that simply deno... | 25 | 30 |
61,218,237 | 2020-4-14 | https://stackoverflow.com/questions/61218237/how-can-i-install-tkinter-for-python-on-mac | So I posted this error on a Facebook group, they said I should get pip. I installed pip, when I am wanting to install tkinter it's giving me error: I used this command first : sudo pip install tkinter . . . error: ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none) ERROR: No mat... | After a day of headache, this worked for me: $ brew install python-tk | 19 | 46 |
61,165,055 | 2020-4-11 | https://stackoverflow.com/questions/61165055/storing-factory-boy-relatedfactory-object-on-parent-factory | I have two Django models (Customer and CustomerAddress) that both contain ForeignKeys to each other. I am using factory-boy to manage creation of these models, and cannot save a child factory instance onto the parent factory (using relationships defined using the RelatedFactory class). My two models: class ExampleCusto... | First, a simple rule of thumb: when you're following a ForeignKey, always prefer a SubFactory; RelatedFactory is intended to follow a reverse relationship. Let's take each factory in turn. ExampleCustomerAddressFactory When we call this factory without a customer, we'll want to get an address, linked to a customer, and... | 8 | 12 |
61,154,741 | 2020-4-11 | https://stackoverflow.com/questions/61154741/how-to-display-a-pandas-dataframe-within-a-vbox-using-ipywidgets | i would like to display a pandas dataframe in a interactive way using ipywidgets. So far the code gets some selections and then does some calculation. For this exmaple case, its not really using the input labels. However, my problem is when I would like to display the pandas dataframe, it's not treated as widget. But h... | from IPython.display import display import ipywidgets as widgets def setup_ui(df): out = widgets.Output() with out: display(df) return out If you change your setup_ui function to this, you can return an Output widget with your dataframe. BUT, in your button_run_on_click function it appears selection is not defined. Sh... | 12 | 14 |
61,149,073 | 2020-4-10 | https://stackoverflow.com/questions/61149073/null-identity-key-error-using-sqlalchemys-base-automap-to-reflect-a-postgres | I have a postgres database that I'm trying to reflect that uses the now standard "Identity" column for primary keys. Here's my table definition: create table class_label ( class_label_id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY, class_name varchar not null, default_color varchar, created_dttm timestamp default ... | A fix was added in SQLAlchemy 1.4 | 8 | 2 |
61,154,740 | 2020-4-11 | https://stackoverflow.com/questions/61154740/attributeerror-module-networkx-has-no-attribute-connected-component-subgraph | B = nx.Graph() B.add_nodes_from(data['movie'].unique(), bipartite=0, label='movie') B.add_nodes_from(data['actor'].unique(), bipartite=1, label='actor') B.add_edges_from(edges, label='acted') A = list(nx.connected_component_subgraphs(B))[0] I am getting the below given error when am trying to use nx.connected_componen... | This was deprecated with version 2.1, and finally removed with version 2.4. See these instructions Use (G.subgraph(c) for c in connected_components(G)) Or (G.subgraph(c).copy() for c in connected_components(G)) | 23 | 32 |
61,206,437 | 2020-4-14 | https://stackoverflow.com/questions/61206437/importerror-cannot-import-name-literal-from-typing | I have recently started using PEP 484 and PEP 586 to make my code clearer and more accessible. So far everything was ok, but when I wanted to use Literal from the package typing it appears it couldn't be imported. What is the most surprising is that PyCharm isn't complaining at all for importing it or using it. The cod... | Using Literal in Python 3.8 and later from typing import Literal Using Literal in all Python versions (1) Literal was added to typing.py in 3.8, but you can use Literal in older versions anyway. First install typing_extensions (pip install typing_extensions) and then from typing_extensions import Literal This approac... | 43 | 53 |
61,198,658 | 2020-4-13 | https://stackoverflow.com/questions/61198658/how-to-flip-numpy-array-along-the-diagonal-efficiently | Lets say that i have the following array (note that there is a 1 in the [2,0] position and a 2 in the [3,4] position): [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [1, 0, 0, 0, 0] [0, 0, 0, 0, 2] [0, 0, 0, 0, 0] and I want to flip it along the diagonal efficiently such that: [0, 0, 1, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0... | Both np.rot90(np.fliplr(x)) and transposing the array solves this. a = np.random.uniform(size=(5,5)) a.T == np.rot90(np.fliplr(a)) | 9 | 16 |
61,176,552 | 2020-4-12 | https://stackoverflow.com/questions/61176552/how-to-hide-file-paths-when-running-python-scripts-in-vs-code | Every time I run my code, the terminal at the bottom is displaying this long name (I think the file location) as well as whatever output it's supposed to display. Is there a way to get that to go away? This is what it looks like: administrator@Machintosh-2 Exercise Files Python % /user/bin/python3... Hello world! ... | AFAIK, there is no way to hide the paths, because the VS Code Integrated Terminal is basically using your OS/system's underlying terminal. And running Python scripts on a terminal requires the following form: <path/to/python/interpreter> <path/to/python/file> If you want a "cleaner" console output, you could create a ... | 8 | 2 |
61,112,322 | 2020-4-9 | https://stackoverflow.com/questions/61112322/get-userid-cant-find-user-returns-none-self-bot-discord-py | I am trying to DM myself using a self bot. I am trying to use the get_user() function in my code. bot = commands.Bot(command_prefix='', self_bot=True) counter = 0 userID = 695724603406024726 @bot.event async def dm(userID): print('Running Function') global counter if counter <= 0: print('Finding user.') counter += 1 us... | You could always use the coroutine client.fetch_user(id) to get it done. get_user() takes it from cache so when fresh, doesn't work most of the times. In your case: bot = commands.Bot(command_prefix='', self_bot=True) counter = 0 userID = 695724603406024726 async def dm(userID): print('Running Function') global counter... | 8 | 9 |
61,204,189 | 2020-4-14 | https://stackoverflow.com/questions/61204189/vs-code-pylintimport-error-unable-to-import-subsub-module-from-custom-direct | I have organized my self-written Python scripts within a tree of several sub-directories, starting from the parent directory "Scripts" which is already included in "python.autoComplete.extraPaths" within the settings-json: "python.autoComplete.extraPaths": ["/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Program... | I found a great workaround for my problem with this answer. It points towards the message control part of the pylint-docs. Practically, I just had to add the comment # pylint: disable=import-error behind my custom imports like so: import General.Plotting.auxiliary_plotting_functions as aux_plot # pylint: disable=import... | 11 | 7 |
61,124,950 | 2020-4-9 | https://stackoverflow.com/questions/61124950/received-incompatible-instance-in-graphql-query | When i hit insomnia with this request bellow then it shows this response. How can i solve this issue? Request: query{ datewiseCoronaCasesList{ updatedAt, affected, death, recovered } } Response: { "errors": [ { "message": "Received incompatible instance \"{'updated_at': datetime.date(2020, 4, 8), 'affected': 137, 'dea... | Under CoronaQuery class, since you are returning a list of objects (instances), graphene.Field should be changed to graphene.List. I mean: class CoronaQuery(graphene.ObjectType): datewise_corona_cases_list = graphene.List(CoronaCaseType) | 10 | 10 |
61,155,366 | 2020-4-11 | https://stackoverflow.com/questions/61155366/type-hint-for-finite-iterable | My function foo accepts an argument things which is turned into a list internally. def foo(things): things = list(things) # more code The list constructor accepts any iterable. However, annotating things with typing.Iterable does not give the user a clue that the iterable must be finite, not something like itertools.c... | I am not aware of any possible way to achieve this in Python as you cannot provide such constraints in type hints. However, probably the Collection type might be useful in your context as a workaround: class collections.abc.Collection ABC for sized iterable container classes. This requires objects to have a __len__,... | 18 | 20 |
61,186,708 | 2020-4-13 | https://stackoverflow.com/questions/61186708/pandas-read-excel-doesnt-parse-dates-correctly-returns-a-constant-date-instea | I've read a .xlsb file and parsed date columns using a code below: dateparser = lambda x: pd.to_datetime(x) data = pd.read_excel(r"test.xlsb", engine="pyxlsb", parse_dates=["start_date","end_date"], date_parser=dateparser ) My input columns in the .xlsb file have format DD/MM/YYYY (e.g. 26/01/2008). As an output of t... | I am not sure if you were able to figure out the answer to this problem. But, below is how I resolved it: from pyxlsb import convert_date self.data: pd.DataFrame = pd.read_excel(self.file, sheet_name=self.sheet, engine='pyxlsb', header=0) self.data["test"] = self.data.apply(lambda x: convert_date(x.SomeStupidDate), axi... | 7 | 9 |
61,166,864 | 2020-4-12 | https://stackoverflow.com/questions/61166864/tensorflow-python-framework-ops-eagertensor-object-has-no-attribute-in-graph | I am trying to visualize CNN filters by optimizing a random 'image' so that it produces a high mean activation on that filter which is somehow similar to the neural style transfer algorithm. For that purpose, I am using TensorFlow==2.2.0-rc. But during the optimization process, an error occurs saying 'tensorflow.python... | The reason for the bug is that the tf.keras optimizers apply gradients to variable objects (of type tf.Variable), while you are trying to apply gradients to tensors (of type tf.Tensor). Tensor objects are not mutable in TensorFlow, thus the optimizer cannot apply gradients to it. You should initialize the variable img ... | 11 | 14 |
61,128,637 | 2020-4-9 | https://stackoverflow.com/questions/61128637/discord-errors-forbidden-403-forbidden-error-code-50013-missing-permissions | I am trying to setup roles for my discord bot but keep getting this error: discord.errors.Forbidden: 403 Forbidden (error code: 50013) My Code: @client.event async def on_member_join(member): guild = client.get_guild(688568885968109756) role = discord.utils.get(member.guild.roles, id=689916456871133311) await member.... | If your bot have enough permission, Then it's coming due to the hierarchy of roles. Check-in server settings for the hierarchy. For changing the hierarchy, you can move the roles up down in the settings. | 7 | 19 |
61,218,501 | 2020-4-14 | https://stackoverflow.com/questions/61218501/plotly-how-to-show-legend-in-single-trace-scatterplot-with-plotly-express | Sorry beforehand for the long post. I'm new to python and to plotly, so please bear with me. I'm trying to make a scatterplot with a trendline to show me the legend of the plot including the regression parameters but for some reason I can't understand why px.scatter doesn't show me the legend of my trace. Here is my co... | You must specify that you'd like to display a legend and provide a legend name like this: fig['data'][0]['showlegend']=True fig['data'][0]['name']='Sepal length' Plot: Complete code: import plotly.express as px df = px.data.iris() # iris is a pandas DataFrame fig = px.scatter(df, x="sepal_width", y="sepal_length", tr... | 11 | 18 |
61,165,574 | 2020-4-12 | https://stackoverflow.com/questions/61165574/cast-and-type-env-variables-using-file | For all my projects, I load all env variables at the start and check that all the expected keys exist as described by an .env.example file following the dotenv-safe approach. However, the env variables are strings, which have to be manually cast whenever they're used inside the Python code. This is annoying and error-p... | I will suggest using pydantic. From StackOverflow pydantic tag info Pydantic is a library for data validation and settings management based on Python type hinting (PEP484) and variable annotations (PEP526). It allows for defining schemas in Python for complex structures. let's assume that you have a file with your SS... | 9 | 18 |
61,213,866 | 2020-4-14 | https://stackoverflow.com/questions/61213866/why-do-i-get-this-many-iterations-when-adding-to-and-removing-from-a-set-while-i | Trying to understand the Python for-loop, I thought this would give the result {1} for one iteration, or just get stuck in an infinite loop, depending on if it does the iteration like in C or other languages. But actually it did neither. >>> s = {0} >>> for i in s: ... s.add(i + 1) ... s.remove(i) ... >>> print(s) {16}... | Python makes no promises about when (if ever) this loop will end. Modifying a set during iteration can lead to skipped elements, repeated elements, and other weirdness. Never rely on such behavior. Everything I am about to say is implementation details, subject to change without notice. If you write a program that reli... | 69 | 97 |
61,212,514 | 2020-4-14 | https://stackoverflow.com/questions/61212514/django-model-objects-became-not-hashable-after-upgrading-to-django-2-2 | I'm testing the update of an application from Django 2.1.7 to 2.2.12. I got an error when running my unit tests, which boils down to a model object not being hashable : Station.objects.all().delete() py37\lib\site-packages\django\db\models\query.py:710: in delete collector.collect(del_query) py37\lib\site-packages\dja... | As pointed out by @Alasdair, the issue was a change of behaviour brought in Django 2.2 to comply with how a model class should behave when __eq__() is overriden but not __hash__(). As per the python docs for __hash__(): A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly ... | 7 | 19 |
61,217,834 | 2020-4-14 | https://stackoverflow.com/questions/61217834/how-to-use-extra-files-for-aws-glue-job | I have an ETL job written in python, which consist of multiple scripts with following directory structure; my_etl_job | |--services | | | |-- __init__.py | |-- dynamoDB_service.py | |-- __init__.py |-- main.py |-- logger.py main.py is the entrypoint script that imports other scripts from above directories. The above c... | You'll have to pass the zip file as extra python lib , or build a wheel package for the code package and upload the zip or wheel to s3, provide the same path as extra python lib option Note: Have your main function written in the glue console it self , referencing the required function from the zipped/wheel dependency,... | 20 | 13 |
61,217,923 | 2020-4-14 | https://stackoverflow.com/questions/61217923/merge-rows-based-on-value-pandas-to-excel-xlsxwriter | I'm trying to output a Pandas dataframe into an excel file using xlsxwriter. However I'm trying to apply some rule-based formatting; specifically trying to merge cells that have the same value, but having trouble coming up with how to write the loop. (New to Python here!) See below for output vs output expected: (As ... | Your logic is almost correct, however i approached your problem through a slightly different approach: 1) Sort the column, make sure that all the values are grouped together. 2) Reset the index (using reset_index() and maybe pass the arg drop=True). 3) Then we have to capture the rows where the value is new. For that p... | 19 | 15 |
61,213,745 | 2020-4-14 | https://stackoverflow.com/questions/61213745/typechecking-dynamically-added-attributes | When writing project-specific pytest plugins, I often find the Config object useful to attach my own properties. Example: from _pytest.config import Config def pytest_configure(config: Config) -> None: config.fizz = "buzz" def pytest_unconfigure(config: Config) -> None: print(config.fizz) Obviously, there's no fizz at... | One way of doing this would be to contrive to have your Config object define __getattr__ and __setattr__ methods. If those methods are defined in a class, mypy will use those to type check places where you're accessing or setting some undefined attribute. For example: from typing import Any class Config: def __init__(s... | 14 | 7 |
61,125,925 | 2020-4-9 | https://stackoverflow.com/questions/61125925/optimization-help-involving-matrix-operations-and-constraints | I'm so far out of my league on this one, so I'm hoping someone can point me in the right direction. I think this is an optimization problem, but I have been confused by scipy.optimize and how it fits with pulp. Also, matrix math boggles my mind. Therefore this problem has really been slowing me down without to ask. Pro... | You can use scipy.optimize.linprog to solve this linear optimization problem. It requires to setup the boundary conditions as matrix products, as outlined in the docs. There are two types of boundary conditions, inequalities of the form A @ x <= b and equality A @ x == b. The problem can be modeled as follows: The res... | 7 | 5 |
61,104,747 | 2020-4-8 | https://stackoverflow.com/questions/61104747/jupyter-notebook-to-html-notebook-json-is-invalid-outputprepend | I am trying to convert my Jupyter Notebook file (.ipynb) into an HTML file for easier reading. Every time I try to save the notebook I get a "Notebook validation failed" error: Notebook validation failed: ['outputPrepend', 'outputPrepend', 'outputPrepend', 'outputPrepend', 'outputPrepend', 'outputPrepend', 'outputPrepe... | I recently experienced this from using the VSCode Notebook editor. I solved it by opening the notebook in a regular text editor and deleting all the extra outputPrepend-items, leaving only a single one in each array. | 8 | 14 |
61,190,321 | 2020-4-13 | https://stackoverflow.com/questions/61190321/calling-invoking-a-javascript-function-from-python-a-flask-function-within-html | I was creating a flask application and tried to call a python function in which I wanted to invoke some javascript function/code regarding the HTML template that I returned on the initial app.route('/') If the user did something, then I called another function that should invoke or call a js function I have tried looki... | You could execute a JavaScript function on load and have the function check for the condition. You can influence the outcome of this check by changing the condition with Python. If you use the render_template function of Flask, you do not have to write your HTML code within your Python file. For better readability I am... | 8 | 9 |
61,126,284 | 2020-4-9 | https://stackoverflow.com/questions/61126284/zipped-python-generators-with-2nd-one-being-shorter-how-to-retrieve-element-tha | I want to parse 2 generators of (potentially) different length with zip: for el1, el2 in zip(gen1, gen2): print(el1, el2) However, if gen2 has less elements, one extra element of gen1 is "consumed". For example, def my_gen(n:int): for i in range(n): yield i gen1 = my_gen(10) gen2 = my_gen(8) list(zip(gen1, gen2)) # La... | If you want to reuse code, the easiest solution is: from more_itertools import peekable a = peekable(a) b = peekable(b) while True: try: a.peek() b.peek() except StopIteration: break x = next(a) y = next(b) print(x, y) print(list(a), list(b)) # Misses nothing. You can test this code out using your setup: def my_gen(n:... | 66 | 2 |
61,194,028 | 2020-4-13 | https://stackoverflow.com/questions/61194028/adding-labels-at-end-of-line-chart-in-altair | So I have been trying to get it so there is a label at the end of each line giving the name of the country, then I can remove the legend. Have tried playing with transform_filter but no luck. I used data from here https://ourworldindata.org/coronavirus-source-data I cleaned and reshaped the data so it looks like this:-... | You can do this by aggregating the x and y encodings. You want the text to be at the maximum x value, so you can use a 'max' aggregate in x. For the y-value, you want the y value associated with the max x-value, so you can use an {"argmax": "x"} aggregate. With a bit of adjustment of text alignment, the result looks li... | 7 | 12 |
61,194,881 | 2020-4-13 | https://stackoverflow.com/questions/61194881/docker-container-run-locally-didnt-send-any-data | I am trying to run a basic flask app inside a docker container. The docker build works fine but when i try to test locally i get 127.0.0.1 didn't send any data error. Dockerfile FROM tiangolo/uwsgi-nginx-flask:python3.6-alpine3.7 ENV LISTEN_PORT=5000 EXPOSE 5000 RUN pip install --upgrade pip WORKDIR /app ADD . /app... | The issue is that you are passing --host parameter while not using the flask binary to bring up the application. Thus, you need to just take the parameter out of CMD in Dockerfile to your code. Working setup: Dockerfile: FROM tiangolo/uwsgi-nginx-flask:python3.6-alpine3.7 ENV LISTEN_PORT=5000 EXPOSE 5000 RUN pip instal... | 7 | 9 |
61,159,469 | 2020-4-11 | https://stackoverflow.com/questions/61159469/importerror-cannot-import-name-dnn-superres-for-python-example-of-super-resol | I am trying to run an example for upscaling images from the following website: https://towardsdatascience.com/deep-learning-based-super-resolution-with-opencv-4fd736678066 This is the code I am using: import cv2 from cv2 import dnn_superres # Create an SR object sr = dnn_superres.DnnSuperResImpl_create() # Read image i... | I had the same problem with Python 3.6.9 and opencv 4.2.0, but after the upgrade to 4.3.0, the problem disappeared. If you have no problem upgrading the version, try 4.3.0. | 18 | 4 |
61,172,400 | 2020-4-12 | https://stackoverflow.com/questions/61172400/what-does-padding-idx-do-in-nn-embeddings | I'm learning pytorch and I'm wondering what does the padding_idx attribute do in torch.nn.Embedding(n1, d1, padding_idx=0)? I have looked everywhere and couldn't find something I can get. Can you show example to illustrate this? | As per the docs, padding_idx pads the output with the embedding vector at padding_idx (initialized to zeros) whenever it encounters the index. What this means is that wherever you have an item equal to padding_idx, the output of the embedding layer at that index will be all zeros. Here is an example: Let us say you ha... | 18 | 16 |
61,168,140 | 2020-4-12 | https://stackoverflow.com/questions/61168140/opencv-removing-the-background-with-a-mask-image | Given two input i. original image & ii. mask image, what's the best way to remove to the background from the original image. Original Image Mask Image The final output would contain just the dog without the background and look transparent. I have seen the mask images are also created with OpenCV. Is there a way to j... | You can create a transparent image by creating a 4-channel BGRA image and copying the first 3 channels from the original image and setting the alpha channel using the mask image. transparent = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.uint8) transparent[:,:,0:3] = img transparent[:, :, 3] = mask | 8 | 7 |
61,163,024 | 2020-4-11 | https://stackoverflow.com/questions/61163024/return-multiple-files-from-fastapi | Using fastapi, I can't figure out how to send multiple files as a response. For example, to send a single file, I'll use something like this from fastapi import FastAPI, Response app = FastAPI() @app.get("/image_from_id/") async def image_from_id(image_id: int): # Get image from the database img = ... return Response(c... | Zipping is the best option that will have same results on all browsers. you can zip files dynamically. import os import zipfile import StringIO def zipfiles(filenames): zip_subdir = "archive" zip_filename = "%s.zip" % zip_subdir # Open StringIO to grab in-memory ZIP contents s = StringIO.StringIO() # The zip compressor... | 11 | 10 |
61,159,437 | 2020-4-11 | https://stackoverflow.com/questions/61159437/what-is-the-equivalent-of-decorators-with-arguments-without-the-syntactical-suga | I'm learning about decorators and came across an example where the decorator took an argument. This was a little confusing for me though, because I learned that (note: the examples from this question are mostly from this article): def my_decorator(func): def inner(*args, **kwargs): print('Before function runs') func(*a... | That article is the same one that tought me everthing I know about decorators! It's brilliant. In regards to what the non @ symbol syntax looks like: You can imagine the actual decorator function is decorator_repeat(func), the function within repeat(num_times=4). @repeat(num_times=4) returns a decorator which is essent... | 8 | 3 |
61,153,872 | 2020-4-11 | https://stackoverflow.com/questions/61153872/renumbering-line-by-line | I have an input text which looks like this: word77 text text bla66 word78 text bla67 text bla68 word79 text bla69 word80 text bla77 word81 text bla78 word92 text bla79 word99 I have to renumber word and bla from 1, in each line. I can renumber the whole input which looks like this: word1 text text bla1 word2 text bla2... | You operate on the whole file at once (fp.read()) - you need to do it line-wise: with open("input.txt","w") as f: f.write("""word77 text text bla66 word78 text bla67 text bla68 word79 text bla69 word80 text bla77 word81 text bla78 word92 text bla79 word99""") import re i = 0 def replace(m): global i i+=1 return str(i) ... | 7 | 8 |
61,144,232 | 2020-4-10 | https://stackoverflow.com/questions/61144232/updated-to-python-3-8-terminal-wont-open | I updated my system (Ubuntu 18.04) from Python 3.6 to Python 3.8, and reset the defaults so that python3 now points to Python 3.8 (and not 3.6). However, since then, the terminal has refused to open using Ctrl + Alt + T, and other obvious methods such as clicking on the icon itself. When I run gnome-terminal - I get t... | You shouldn't change the symlink /usr/bin/python3 since a bunch of Ubuntu components depend on it, and Ubuntu-specific Python libraries like gi are built only for the Python build shipped with Ubuntu, which is version 3.6 on 18.04. See Gnome terminal will not start on Ask Ubuntu (though note that it's about Ubuntu 16.0... | 12 | 14 |
61,143,812 | 2020-4-10 | https://stackoverflow.com/questions/61143812/unable-to-install-metatrader5 | I could not install MetaTrader5 by: pip install MetaTrader5 I got the following error: ERROR: Could not find a version that satisfies the requirement MetaTrader5 (from versions: none) ERROR: No matching distribution found for MetaTrader5 Knowing that I am on MAC laptop and I have Python 3.7.6 Thanks in advance to provi... | MetaTrader5 provides a lot of binary wheels but only for w32 and w64. No Linux, no MacOS and no source code. It seems the software is Windows-only. Their site recommends to use one of the w32/w64 emulators on MacOS. | 15 | 10 |
61,141,025 | 2020-4-10 | https://stackoverflow.com/questions/61141025/not-understanding-a-trick-on-get-method-in-python | While learning python I came across a line of code which will figure out the numbers of letters. dummy='lorem ipsum dolor emet...' letternum={} for each_letter in dummy: letternum[each_letter.lower()]=letternum.get(each_letter,0)+1 print(letternum) Now, My question is -in the 4th line of code inletternum.get(each_let... | The get method on a dictionary is documented here: https://docs.python.org/3/library/stdtypes.html#dict.get get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. So this explains the 0 - it's a... | 8 | 9 |
61,132,574 | 2020-4-10 | https://stackoverflow.com/questions/61132574/can-i-convert-spectrograms-generated-with-librosa-back-to-audio | I converted some audio files to spectrograms and saved them to files using the following code: import os from matplotlib import pyplot as plt import librosa import librosa.display import IPython.display as ipd audio_fpath = "./audios/" spectrograms_path = "./spectrograms/" audio_clips = os.listdir(audio_fpath) def gene... | Yes, it is possible to recover most of the signal and estimate the phase with e.g. Griffin-Lim Algorithm (GLA). Its "fast" implementation for Python can be found in librosa. Here's how you can use it: import numpy as np import librosa y, sr = librosa.load(librosa.util.example_audio_file(), duration=10) S = np.abs(libro... | 7 | 13 |
61,116,006 | 2020-4-9 | https://stackoverflow.com/questions/61116006/how-can-i-get-the-current-userid-in-flask-jwt-extended | I am new to python/flask and I am working on one to many relationships. I tried some solutions but didn't work. My problem here is in the "/add_about" route I want to get the user_id that created this post and be able to see that reflected in the database. Here is my code: from flask import Blueprint, jsonify, request ... | When you register your jwt token on login, you register the token with the users email. user route test = User.query.filter_by(email=email, password=password).first() if test: access_token = create_access_token(identity=email) # identity = email return jsonify(message="Login succeeded!", access_token=access_token), 200... | 9 | 13 |
61,133,916 | 2020-4-10 | https://stackoverflow.com/questions/61133916/is-there-in-python-a-single-function-that-shows-the-full-structure-of-a-hdf5-fi | When opening a .hdf5 file, one can explore the levels, keys and names of the file in different ways. I wonder if there is a way or a function that displays all the available paths to explore in the .hdf5. Ultimately showing the whole tree. | Try using nexuformat package to list the structure of the hdf5 file. Install by pip install nexusformat Code import nexusformat.nexus as nx f = nx.nxload(‘myhdf5file.hdf5’) print(f.tree) This should print the entire structure of the file. For more on that see this thread. Examples can be found here | 7 | 4 |
61,132,936 | 2020-4-10 | https://stackoverflow.com/questions/61132936/drawing-plotting-a-circle-with-some-radius-around-a-point-matplotlib | I use scatter to plot some points. For example: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() ax.scatter([1,2, 1.5], [2, 1, 1.5]) plt.show() Now I also want a circle with radius 0.5 around point [1.5, 1.5] in the plot. How do I do that? I know that... | To make a circle around point, you can use plt.Circle as shown below: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() ax.scatter([1,2, 1.5], [2, 1, 1.5]) cir = plt.Circle((1.5, 1.5), 0.07, color='r',fill=False) ax.set_aspect('equal', adjustable='datal... | 7 | 6 |
61,131,768 | 2020-4-9 | https://stackoverflow.com/questions/61131768/how-to-count-consecutive-repetitions-of-a-substring-in-a-string | I need to find consecutive (non-overlapping) repetitions of a substring in a string. I can count them but not consecutive. For instance: string = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA" substring = "AA" here, "AA" is repeated one time at the beginning of the string, then 4 times, then 2 times, etc. I should select... | Regular expressions shine when searching through strings. Here you can find all groups of one or more AA with (?:AA)+ the (?: simply tells the engine to interpret the parentheses for grouping only. Once you have the groups you can use max() to find the longest based on length (len()). import re s = "AASDASDDAAAAAAAAER... | 8 | 16 |
61,130,890 | 2020-4-9 | https://stackoverflow.com/questions/61130890/best-way-to-overwrite-azure-blob-in-python | If I try to overwrite an existing blob: blob_client = BlobClient.from_connection_string(connection_string, container_name, blob_name) blob_client.upload_blob('Some text') I get a ResourceExistsError. I can check if the blob exists, delete it, and then upload it: try: blob_client.get_blob_properties() blob_client.delet... | From this issue it seems that you can add overwrite=True to upload_blob and it will work. | 16 | 37 |
61,128,143 | 2020-4-9 | https://stackoverflow.com/questions/61128143/plots-not-showing-in-jupyter-notebook | I am trying to create a 2x2 plots for Anscombe data-set Loading Data-set and separating each class in data-set import seaborn as sns import matplotlib.pyplot as plt anscombe = sns.load_dataset('anscombe') dataset_1 = anscombe[anscombe['dataset'] == 'I'] dataset_2 = anscombe[anscombe['dataset'] == 'II'] dataset_3 = ansc... | If you are working with a Jupyter Notebook then you can add the following line to the top cell where you call all your imports. The following command will render your graph %matplotlib inline | 11 | 19 |
61,128,227 | 2020-4-9 | https://stackoverflow.com/questions/61128227/what-is-the-proper-way-to-override-threading-excepthook-in-python | I am trying to handle uncaught exceptions that occur when I run a thread. The python documentation at docs.python.org states that "threading.excepthook() can be overridden to control how uncaught exceptions raised by Thread.run() are handled." However, I can't seem to do it properly. It doesn't appear that my excepthoo... | threading.excepthook is a function that belongs to the threading module, not a method of the threading.Thread class, so you should override threading.excepthook instead with your own function: import threading import time def excepthook(args): print("In excepthook") threading.excepthook = excepthook class MyThread(thre... | 13 | 13 |
61,123,685 | 2020-4-9 | https://stackoverflow.com/questions/61123685/receiving-failed-to-query-code-13-access-is-denied-when-using-virtualenv-p-o | I have two versions of Python installed on my Windows system. 3.7 is installed in C:\Python37 and 3.8 installed in Python 3.8. My PATH variables include the Python 3.7 executable. When I try to run 'virtualenv -p C:\Python38 ProjectFolder' I get the following error: RuntimeError: failed to query C:\Python38 with code 1... | virtualenv -p C:\Python38\python.exe ProjectFolder I.e. point -p to python executable, not to a directory. | 25 | 47 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.