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 |
|---|---|---|---|---|---|---|
60,054,076 | 2020-2-4 | https://stackoverflow.com/questions/60054076/is-dataclass-a-good-fit-to-replace-a-dictionary | I use dictionaries as data structure a lot in my code. Instead of returning several value as Tuple like Python permits it : def do_smth(): [...] return val1, val2, val3 I prefer to use a dictionary with the advantage to have named keys. But with complex nested dictionary it's hard to navigate inside it. When I was cod... | Dataclasses are more of a replacement for NamedTuples, then dictionaries. Whilst NamedTuples are designed to be immutable, dataclasses can offer that functionality by setting frozen=True in the decorator, but provide much more flexibility overall. If you are into type hints in your Python code, they really come into pl... | 15 | 24 |
60,018,578 | 2020-2-1 | https://stackoverflow.com/questions/60018578/what-does-model-eval-do-in-pytorch | When should I use .eval()? I understand it is supposed to allow me to "evaluate my model". How do I turn it back off for training? Example training code using .eval(). | model.eval() is a kind of switch for some specific layers/parts of the model that behave differently during training and inference (evaluating) time. For example, Dropouts Layers, BatchNorm Layers etc. You need to turn them off during model evaluation, and .eval() will do it for you. In addition, the common practice fo... | 292 | 399 |
59,986,413 | 2020-1-30 | https://stackoverflow.com/questions/59986413/achieving-multiple-inheritance-using-python-dataclasses | I'm trying to use the new python dataclasses to create some mix-in classes (already as I write this I think it sounds like a rash idea), and I'm having some issues. Behold the example below: from dataclasses import dataclass @dataclass class NamedObj: name: str def __post_init__(self): print("NamedObj __post_init__") s... | This: def __post_init__(self): super(NamedObj, self).__post_init__() super(NumberedObj, self).__post_init__() print("NamedAndNumbered __post_init__") doesn't do what you think it does. super(cls, obj) will return a proxy to the class after cls in type(obj).__mro__ - so, in your case, to object. And the whole point of ... | 21 | 27 |
60,050,586 | 2020-2-4 | https://stackoverflow.com/questions/60050586/pytorch-change-the-learning-rate-based-on-number-of-epochs | When I set the learning rate and find the accuracy cannot increase after training few epochs optimizer = optim.Adam(model.parameters(), lr = 1e-4) n_epochs = 10 for i in range(n_epochs): // some training here If I want to use a step decay: reduce the learning rate by a factor of 10 every 5 epochs, how can I do so? | You can use learning rate scheduler torch.optim.lr_scheduler.StepLR import torch.optim.lr_scheduler.StepLR scheduler = StepLR(optimizer, step_size=5, gamma=0.1) Decays the learning rate of each parameter group by gamma every step_size epochs see docs here Example from docs # Assuming optimizer uses lr = 0.05 for all g... | 28 | 53 |
59,985,035 | 2020-1-30 | https://stackoverflow.com/questions/59985035/does-there-exist-any-alternative-of-logspace-in-julia-v1-3-1 | Background and Existing Solutions I am porting some Python code into Julia (v1.3.1), and I have run into an issue with trying to reproduce the code into as easily readable code in Julia. In Python (using numpy), we have created a 101-element logarithmically spaced sequence from 0.001 to 1000: >>> X = numpy.logspace( -3... | You can just use range For Log-spaced values ∈ [1.0e-10, 1.0e10]: 10 .^ range(-10, stop=10, length=101) | 7 | 1 |
59,962,902 | 2020-1-29 | https://stackoverflow.com/questions/59962902/max-retries-exceeded-with-url-caused-by-proxyerror | i wanted to get some proxy list from this webPage; https://free-proxy-list.net/ but i stuck in this error and dont know how to fix it. requests.exceptions.ProxyError: HTTPSConnectionPool(host='free-proxy-list.net', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConnecti... | Your using https in the Json dict when your proxy is a http proxy Proxies should always be inside this format For a http proxy {'"http": "Http Proxy"} For a https proxy {"https":"Https Proxy"} And for the UserAgent {"User-Agent": "Opera/9.80 (X11; Linux x86_64; U; de) Presto/2.2.15 Version/10.00"} Example import req... | 10 | 5 |
59,979,467 | 2020-1-30 | https://stackoverflow.com/questions/59979467/accessing-microsoft-sharepoint-files-and-data-using-python | I am using Microsoft sharepoint. I have an url, by using that url I need to get total data like photos,videos,folders,subfolders,files,posts etc... and I need to store those data in database(Sql server). I am using python. So,Please anyone suggest me how to do this and I am beginner for accessing sharepoint and working... | Here's the starter code for connecting to share point through Python and accessing the list of files, folders and individual file contents of Sharepoint as well. You can build on top of this to suit your needs. Please note that this method works for public Sharepoint sites that are accessible through internet. For Orga... | 15 | 22 |
60,017,052 | 2020-2-1 | https://stackoverflow.com/questions/60017052/decompose-for-time-series-valueerror-you-must-specify-a-period-or-x-must-be | I have some problems executing an additive model right. I have the following data frame: And when I run this code: import statsmodels as sm import statsmodels.api as sm decomposition = sm.tsa.seasonal_decompose(df, model = 'additive') fig = decomposition.plot() matplotlib.rcParams['figure.figsize'] = [9.0,5.0] I got ... | Having the same ValueError, this is just the result of some testing and little research on my own, without the claim to be complete or professional about it. Please comment or answer whoever finds something wrong. Of course, your data should be in the right order of the index values, which you would assure with df.sort... | 34 | 48 |
60,024,262 | 2020-2-2 | https://stackoverflow.com/questions/60024262/error-converting-object-string-to-int32-typeerror-object-cannot-be-converted | I get following error while trying to convert object (string) column in Pandas to Int32 which is integer type that allows for NA values. df.column = df.column.astype('Int32') TypeError: object cannot be converted to an IntegerDtype I'm using pandas version: 0.25.3 | It's known bug, as explained here. Workaround is to convert column first to float and than to Int32. Make sure you strip your column from whitespaces before you do conversion: df.column = df.column.str.strip() Than do conversion: df.column = df.column.astype('float') # first convert to float before int df.column = df.... | 24 | 41 |
59,977,052 | 2020-1-29 | https://stackoverflow.com/questions/59977052/shooting-a-bullet-in-pygame-in-the-direction-of-mouse | I just cant figure out why my bullet is not working. I made a bullet class and here it is: class Bullet: def __init__(self): self.x = player.x self.y = player.y self.height = 7 self.width = 2 self.bullet = pygame.Surface((self.width, self.height)) self.bullet.fill((255, 255, 255)) Now I added several functions in my g... | First of all pygame.transform.rotate does not transform the object itself, but creates a new rotated surface and returns it. If you want to fire a bullet in a certain direction, the direction is defined the moment the bullet is fired, but it does not change continuously. When the bullet is fired, set the starting posit... | 7 | 14 |
60,003,444 | 2020-1-31 | https://stackoverflow.com/questions/60003444/typeddict-when-keys-have-invalid-names | If I have a key in a dictionary with an invalid identifier, such as A(2). How can I create a TypedDict with this field? E.g from typing import TypedDict class RandomAlphabet(TypedDict): A(2): str is not valid Python code, resulting in the error: SyntaxError: illegal target for annotation The same problem is with rese... | According to PEP 589 you can use alternative syntax to create a TypedDict as follows: Movie = TypedDict('Movie', {'name': str, 'year': int}) So, in your case, you could write: from typing import TypedDict RandomAlphabet = TypedDict('RandomAlphabet', {'A(2)': str}) or for the second example: RandomAlphabet = TypedDic... | 48 | 65 |
60,031,112 | 2020-2-2 | https://stackoverflow.com/questions/60031112/how-do-i-make-a-pdf-searchable-for-a-flask-search-application | I have been doing research for a very important personal project. I would like to create a Flask Search Application that allows me to search for content across 100 Plus PDF files. I have found Some information around A ElasticSearch Lib that works well with flask. #!/usr/bin/env python3 #-*- coding: utf-8 -*- # import ... | So now Amazon has a solution for my use case. It's called AWS Textract. If you create a free AWS account, and download the Cli and Python sdk, you can use the following code: import boto3 # Document documentName = "test2-28.png" # Read document content with open(documentName, 'rb') as document: imageBytes = document.re... | 8 | 0 |
60,058,588 | 2020-2-4 | https://stackoverflow.com/questions/60058588/tensorflow-2-0-tf-random-set-seed-not-working-since-i-am-getting-different-resul | I am using tf.random.set_seed to assure the reproducibility of my experiments but getting different results in terms of loss after training my model multiple times. I am monitoring the learning curve of each experiment using Tensorboard, but I am getting different values of loss and accuracy. | Providing the solution here (Answer Section), even though it is present in the Comment Section, for the benefit of the community. To reproduce same results, you can create function as below and pass seeds directly to the layers as mentioned Daniel in the comments. def reset_random_seeds(): os.environ['PYTHONHASHSEED']=... | 9 | 14 |
60,060,301 | 2020-2-4 | https://stackoverflow.com/questions/60060301/typeerror-cannot-cast-array-data-from-dtypeint64-to-dtypeint32-accordin | I'm trying to plot a regplot using seaborn and i'm not unable to plot it and facing TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe' . My data has 731 rows and 16 column - >>> bike_df.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 731 entries, 0 to 730 Data... | Update: this bug is solved in Seaborn version 0.10.1 (April 2020). I encountered the same problem. It is issue 1950 at Seaborn's github. Related to running a 32-bit version of numpy. It will be solved in the next release. To work around the problem, I changed line 84 of my local version of Seaborn's algorithm.py: resam... | 11 | 17 |
60,032,983 | 2020-2-3 | https://stackoverflow.com/questions/60032983/record-voice-with-recorder-js-and-upload-it-to-python-flask-server-but-wav-file | I would like to realize this. A user speaks to a web browser. A web browser (Google Chrome) record user's voice as WAV file(Recorder.js) and send it to a python-flask server. I realized this with the help of addpipe's simple recorder.js sample. https://github.com/addpipe/simple-recorderjs-demo This sample uses php se... | I have this problem and it takes me 2 days for finding the solution :)) . In flask server you can use request.files['audio_data'] to get wav audio file. You can pass and use it as an audio variable too. Hope this can help you | 10 | 12 |
60,022,388 | 2020-2-2 | https://stackoverflow.com/questions/60022388/pytorch-runtimeerror-reduce-failed-to-synchronize-cudaerrorassert-device-sid | I am running into the following error when trying to train this on this dataset. Since this is the configuration published in the paper, I am assuming I am doing something incredibly wrong. This error arrives on a different image every time I try to run training. C:/w/1/s/windows/pytorch/aten/src/THCUNN/ClassNLLCriteri... | This kind of error generally occurs when using NLLLoss or CrossEntropyLoss, and when your dataset has negative labels (or labels greater than the number of classes). That is also the exact error you are getting Assertion t >= 0 && t < n_classes failed. This won't occur for MSELoss, but OP mentions that there is a Cros... | 17 | 24 |
59,978,301 | 2020-1-30 | https://stackoverflow.com/questions/59978301/how-to-use-deep-learning-models-for-time-series-forecasting | I have signals recorded from machines (m1, m2, so on) for 28 days. (Note: each signal in each day is 360 length long). machine_num, day1, day2, ..., day28 m1, [12, 10, 5, 6, ...], [78, 85, 32, 12, ...], ..., [12, 12, 12, 12, ...] m2, [2, 0, 5, 6, ...], [8, 5, 32, 12, ...], ..., [1, 1, 12, 12, ...] ... m2000, [1, 1, 5, ... | Model and shapes Since these are sequences in sequences, you need to use your data in a different format. Although you could just go like (machines, days, 360) and simply treat the 360 as features (that could work up to some point), for a robust model (then maybe there is a speed problem) you'd need to treat both thin... | 7 | 4 |
60,042,568 | 2020-2-3 | https://stackoverflow.com/questions/60042568/this-application-failed-to-start-because-no-qt-platform-plugin-could-be-initiali | I am stuck trying to run a very simple Python script, getting this error: qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in "" This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. zsh: abort python3 mypuppy1.py The script ... | For me, it worked by using a opencv-python version prior to 4.2 version that just got released. The new version (4.2.0.32) released on Feb 2, 2020 seems to have caused this breaking change and probably expects to find Qt at a specific location (Users/ directory) as pointed by other answers. You can try either manually... | 56 | 21 |
60,023,381 | 2020-2-2 | https://stackoverflow.com/questions/60023381/securityerror-failed-to-establish-secure-connection-to-eof-occurred-in-violati | I am attempting to connect to Neo4j but I keep getting this error. I tried from neo4j.v1 import GraphDatabase driver = GraphDatabase.driver(uri="bolt://localhost:7687", auth=("neo4j", "12345")) but I get this error when I try to connect SecurityError: Failed to establish secure connection to 'EOF occurred in violati... | I had the same problem with the Object Graph Mapper Neomodel (connecting to neo4j v4). Adding the second line solved it: config.DATABASE_URL = 'bolt://neo4j:password123@localhost:7687' config.ENCRYPTED_CONNECTION = False | 9 | 6 |
60,022,462 | 2020-2-2 | https://stackoverflow.com/questions/60022462/how-to-suppress-specific-warning-in-tensorflow-python | I have a model that, based on certain conditions, has some unconnected gradients, and this is exactly what I want. But Tensorflow is printing out a Warning every time it encounters the unconnected gradient. WARNING:tensorflow:Gradients do not exist for variables Is there any way to only suppress this specific warning?... | Kinda hacky way: gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients([ (grad, var) for (grad, var) in zip(gradients, model.trainable_variables) if grad is not None ]) | 10 | 6 |
60,054,350 | 2020-2-4 | https://stackoverflow.com/questions/60054350/django-use-a-property-as-a-foreign-key | The database of my app is populated and kept syncd with external data sources. I have an abstract model from which all the models of my Django 2.2 app derives, defined as follow: class CommonModel(models.Model): # Auto-generated by Django, but included in this example for clarity. # id = models.AutoField(auto_created=T... | You mentioned in your comment in the other answer that object_id is not unique but it is unique in combination with object_type, so could you use a unique_together in the metaclass? i.e class CommonModel(models.Model): object_type = models.IntegerField() object_id = models.IntegerField() class Meta: unique_together = (... | 8 | 6 |
59,979,354 | 2020-1-30 | https://stackoverflow.com/questions/59979354/what-is-the-difference-between-numpy-fft-fft-and-numpy-fft-fftfreq | I am analysing time series data and would like to extract the 5 main frequency components and use them as features for training a machine learning model. My dataset is 921 x 10080. Each row is a time series and there are 921 of them in total. While exploring possible ways to do this, I came across various functions inc... | First one needs to understand that there are time domain and frequency domain representations of signals. The graphic below shows a few common fundamental signal types and their time domain and frequency domain representations. Pay close attention to the sine curve which I will use to illustrate the difference betwee... | 11 | 16 |
60,032,540 | 2020-2-3 | https://stackoverflow.com/questions/60032540/opencv-cv2-imshow-is-not-working-because-of-the-qt | I am having a problem that I can not use cv2.imshow() because of following error message qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in "" This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. Last Macbook I was using i... | I had the same issue after updating opencv - python to 4.2.0.32. Uninstall opencv-python and install the lower version (e.g pip install opencv-python==4.1.0.25) solves this issue. | 10 | 43 |
60,047,685 | 2020-2-3 | https://stackoverflow.com/questions/60047685/is-it-bad-practice-to-include-non-validating-methods-in-a-pydantic-model | I'm using pydantic 1.3 to validate models for an API I am writing. Is it common/good practice to include arbitrary methods in a class that inherits from pydantic.BaseModel? I need some helper methods associated with the objects and I am trying to decide whether I need a "handler" class. These models are being converted... | Yes, it's fine. We should probably document it. The only problem comes when you have a field name which conflicts with the method, but that's not a problem if you know what your data looks like. Also, it's possible to over object orient your code, but you're a long way from that. | 75 | 80 |
60,052,453 | 2020-2-4 | https://stackoverflow.com/questions/60052453/videowriter-outputs-corrupted-video-file | This is my code to save web_cam streaming. It is working but the problem with output video file. import numpy as np import cv2 cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter object #fourcc = cv2.cv.CV_FOURCC(*'DIVX') #out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) out = cv2.VideoWriter... | The output file is corrupted because of the wrong frame rate and frame resolution. Using this code : out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480)) We set the fps/frame rate per second 20. Which was not correct. Also, the frame width and height was wrong. I solved by getting fps, width, height from the capt... | 9 | 4 |
60,050,507 | 2020-2-4 | https://stackoverflow.com/questions/60050507/reading-prometheus-metric-using-python | I am trying to read Prometheus metrics (the cpu and memory values) of a POD in kubernetes. I have Prometheus install and everything is up using local host 'http://localhost:9090/. I used the following code to read the CPU and memory of a pod but I have an error results = response.json()['data']['result'] , No JSON obje... | The code looks true, However,the query in your response command is wrong . the true formate is : response =requests.get(PROMETHEUS + '/api/v1/query', params={'query': 'container_cpu_user_seconds_total'}) you can change "container_cpu_user_seconds_total" to any query that you want to read. .. good luck | 9 | 9 |
60,055,151 | 2020-2-4 | https://stackoverflow.com/questions/60055151/how-to-trigger-an-airflow-dag-run-from-within-a-python-script | Using apache airflow, I created some DAGS, some of which do not run on a schedule. I'm trying to find a way that I can trigger a run for a specific DAG from within a Python script. Is this possible? How can I do? EDIT --- The python script will be running from a different project from the project where all my DAGS are... | You have a variety of options when it comes to triggering Airflow DAG runs. Using Python The airflow python package provides a local client you can use for triggering a dag from within a python script. For example: from airflow.api.client.local_client import Client c = Client(None, None) c.trigger_dag(dag_id='test_dag_... | 10 | 20 |
60,058,762 | 2020-2-4 | https://stackoverflow.com/questions/60058762/fastest-way-for-boolean-matrix-computations | I have a boolean matrix with 1.5E6 rows and 20E3 columns, similar to this example: M = [[ True, True, False, True, ...], [False, True, True, True, ...], [False, False, False, False, ...], [False, True, False, False, ...], ... [ True, True, False, False, ...] ] Also, I have another matrix N ( 1.5E6 rows, 1 column): N ... | Simply use np.einsum to get all the counts - np.einsum('ij,ik,i->jk',M,M.astype(int),N.ravel()) Feel free to play around with optimize flag with np.einsum. Also, feel free to play around with different dtypes conversion. To leverage GPU, we can use tensorflow package that also supports einsum. Faster alternatives with... | 7 | 9 |
60,046,243 | 2020-2-3 | https://stackoverflow.com/questions/60046243/how-to-make-a-distplot-for-each-column-in-a-pandas-dataframe | I 'm using Seaborn in a Jupyter notebook to plot histograms like this: import numpy as np import pandas as pd from pandas import DataFrame import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline df = pd.read_csv('CTG.csv', sep=',') sns.distplot(df['LBE']) I have an array of columns with values that I ... | Insert plt.figure() before each call to sns.distplot() . Here's an example with plt.figure(): Here's an example without plt.figure(): Complete code: # imports import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [6, 2] %matplotlib inline # sampl... | 8 | 13 |
60,029,614 | 2020-2-2 | https://stackoverflow.com/questions/60029614/esp32-cam-stream-in-opencv-python | I am using AI Thinker ESP32-CAM with stream url http://192.168.8.100:81/stream. I have tried this and other techniques but nothing worked for me import numpy as np cap = cv2.VideoCapture("rtsp://192.168.8.100:81/stream") while(True): ret, frame = cap.read() cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q')... | I have used this arduino code #include <esp32cam.h> #include <WebServer.h> #include <WiFi.h> const char* WIFI_SSID = "ZONG MBB-E5573-AE26"; const char* WIFI_PASS = "58688303"; WebServer server(80); static auto loRes = esp32cam::Resolution::find(320, 240); static auto hiRes = esp32cam::Resolution::find(800, 600); void h... | 8 | 12 |
60,049,059 | 2020-2-4 | https://stackoverflow.com/questions/60049059/python-linear-regression-typeerror-invalid-type-promotion | i am trying to run linear regression and i am having issues with data type i think. I have tested line by line and everything works until i reach last line where i get the issue TypeError: invalid Type promotion. Based on my research i think it is due to date format. Here is my code: import pandas as pd import numpy as... | I think linear regression not work for date type data.You need to convert it to numerical data. for example import numpy as np import pandas as pd import datetime as dt X_test = pd.DataFrame(np.array([ ['2020-01-24T00:00:00.000000000'], ['2020-01-25T00:00:00.000000000'], ['2020-01-26T00:00:00.000000000'], ['2020-01-27T... | 18 | 31 |
60,032,087 | 2020-2-3 | https://stackoverflow.com/questions/60032087/why-my-package-cant-be-installed-with-pipx | I've got a Python project aws-ssm-tools that uses setup.py for packaging. It comes with 3 scripts: ssm-tunnel, ssm-session and ssm-copy. It can be installed with pip install aws-ssm-tools and puts the scripts to ~/.local/bin/. However when I try to install it with pipx it fails: ~ $ pipx install aws-ssm-tools No apps a... | As stated in the pipx documentation chapter "How pipx works", section "Developing for pix", the project requires setuptools entry_points. According to the content of your question, it seems that the target project uses scripts, they are similar in purpose to entry-points but pipx does not look for those and does not ex... | 11 | 8 |
60,048,149 | 2020-2-3 | https://stackoverflow.com/questions/60048149/how-to-convert-png-to-jpg-in-python | I'm trying to compare two images, one a .png and the other a .jpg. So I need to convert the .png file to a .jpg to get closer values for SSIM. Below is the code that I've tried, but I'm getting this error: AttributeError: 'tuple' object has no attribute 'dtype' image2 = imread(thisPath + caption) image2 = io.imsave("... | Before demonstrating how to convert an image from .png to .jpg format, I want to point out that you should be consistent on the library that you use. Currently, you're mixing scikit-image with opencv. It's best to choose one library and stick with it instead of reading in an image with scikit and then converting to gra... | 10 | 24 |
60,047,837 | 2020-2-3 | https://stackoverflow.com/questions/60047837/django-singleton-model-to-store-user-settings | I am building a web app with Django. I would like to be able to store final user settings for my app. For now I am using a model Settings that contains all what I need for the app. It seems ok but I don't think that's the right way to do it because I could have a second row in my database and I don't want it. I though... | If I understand your question correctly, you're interested in managing settings for your django app through an editable, easy to update interface. A popular existing approach to this is implemented by django-constance. It can use your database or redis to store the settings, and it makes them editable through the djang... | 7 | 9 |
60,044,157 | 2020-2-3 | https://stackoverflow.com/questions/60044157/python-ffmpeg-subprocess-broken-pipe | The following script reads a video with OpenCV, applies a transformation to each frame and attempts to write it with ffmpeg. My problem is, that I don't get ffmpeg working with the subprocess module. I always get the error BrokenPipeError: [Errno 32] Broken pipe in the line where I try to write to stdin. Why is that, w... | There is a missing comma after '-vcodec', 'rawvideo'!!! Took me about an hour to notice... You should also close stdin and wait before print('Done!'): pipe.stdin.close() pipe.wait() | 9 | 9 |
60,038,362 | 2020-2-3 | https://stackoverflow.com/questions/60038362/how-to-prevent-xss-attacks-in-django-rest-api-charfields | I'm currently working on an app using Django 2.2 with djangorestframework 3.9.2. I am aware that Django itself provides protection against SQL Injection or in in the context of displaying content in django templates (XSS), but I've noticed that while I use Django REST API, all the CharFields in my models are not saniti... | You can use escape() method inside serializer's validation: from django.utils.html import escape class MySerializer: def validate_myfield(self, value): return escape(value) | 7 | 16 |
60,033,397 | 2020-2-3 | https://stackoverflow.com/questions/60033397/moviewriter-ffmpeg-unavailable-trying-to-use-class-matplotlib-animation-pillo | Is there any way to use moving plot without ffmpeg? import matplotlib.animation as animation from IPython.display import HTML fig, ax = plt.subplots(figsize=(15, 8)) animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1968, 2019)) HTML(animator.to_jshtml()) animator.save('dynamic_images.mp4') My code i... | You can save animated plot as .gif with use of celluloid library: from matplotlib import pyplot as plt from celluloid import Camera import numpy as np # create figure object fig = plt.figure() # load axis box ax = plt.axes() # set axis limit ax.set_ylim(0, 1) ax.set_xlim(0, 10) camera = Camera(fig) for i in range(10): ... | 12 | 8 |
60,034,429 | 2020-2-3 | https://stackoverflow.com/questions/60034429/importerror-cannot-import-name-serial-from-serial-unknown-location | Whenever i execute the code below it gives me following Error: ImportError: cannot import name 'Serial' from 'serial' (unknown location) Code: from serial import Serial arduinodata = Serial('com4',9600) print("Enter n to ON LED and f to OFF LED") while 1: input_data = raw_input() print ("You Entered"+input_data) if (... | Most likely missing an __init__.py file or the module, or the file sub-directory for the module (Serial) is on a different layer than the file executable. Hope that helps :). | 11 | 1 |
60,029,873 | 2020-2-2 | https://stackoverflow.com/questions/60029873/pandas-to-json-redundant-backslashes | I have a '.csv' file containing data about movies and I'm trying to reformat it as a JSON file to use it in MongoDB. So I loaded that csv file to a pandas DataFrame and then used to_json method to write it back. here is how one row in DataFrame looks like: In [43]: result.iloc[0] Out[43]: title Avatar release_date 2009... | Pandas is escaping the " character because it thinks the values in the json columns are text. To get the desired behaviour, simply parse the values in the json column as json. let the file data.csv have the following content (with quotes escaped). # data.csv movie_id,title,cast 19995,Avatar,"[{""cast_id"": 242, ""char... | 8 | 6 |
60,018,903 | 2020-2-1 | https://stackoverflow.com/questions/60018903/how-to-replace-all-pixels-of-a-certain-rgb-value-with-another-rgb-value-in-openc | I need to be able to replace all pixels that have a certain RGB value with another color in OpenCV. I’ve tried some of the solutions but none of them worked for me. What is the best way to achieve this? | TLDR; Make all green pixels white with Numpy: import numpy as np pixels[np.all(pixels == (0, 255, 0), axis=-1)] = (255,255,255) I have made some examples of other ways of changing colours here. First I'll cover exact, specific RGB values like you asked in your question, using this image. It has three big blocks of ex... | 14 | 31 |
60,029,027 | 2020-2-2 | https://stackoverflow.com/questions/60029027/decay-parameter-of-adam-optimizer-in-keras | I think that Adam optimizer is designed such that it automtically adjusts the learning rate. But there is an option to explicitly mention the decay in the Adam parameter options in Keras. I want to clarify the effect of decay on Adam optimizer in Keras. If we compile the model using decay say 0.01 on lr = 0.001, and th... | From source code, decay adjusts lr per iterations according to lr = lr * (1. / (1. + decay * iterations)) # simplified see image below. This is epoch-independent. iterations is incremented by 1 on each batch fit (e.g. each time train_on_batch is called, or how many ever batches are in x for model.fit(x) - usually len(... | 10 | 10 |
60,019,006 | 2020-2-1 | https://stackoverflow.com/questions/60019006/can-we-plot-image-data-in-altair | I am trying to plot image data in altair, specifically trying to replicate face recognition example in this link from Jake VDP's book - https://jakevdp.github.io/PythonDataScienceHandbook/05.07-support-vector-machines.html. Any one had luck plotting image data in altair? | Altair features an image mark that can be used if you want to plot images that are available at a URL; for example: import altair as alt import pandas as pd source = pd.DataFrame.from_records([ {"x": 0.5, "y": 0.5, "img": "https://vega.github.io/vega-datasets/data/ffox.png"}, {"x": 1.5, "y": 1.5, "img": "https://vega.g... | 14 | 18 |
60,015,319 | 2020-2-1 | https://stackoverflow.com/questions/60015319/is-it-necessary-to-call-super-init-explicitly-in-python | I came from Java where we can avoid calling super class zero-argument constructor. The call to it is generated implicitly by the compiler. I read this post about super() and now in question about is it really necessary to do something like this explicitly: class A(object): def __init__(self): print("world") class B(A)... | If you override the __init__ method of the superclass, then the __init__ method of the subclass needs to explicitly call it if that is the intended behavior, yes. Your mental model of __init__ is incorrect; it is not the constructor method, it is a hook which the constructor method calls to let you customize object ini... | 13 | 21 |
60,012,168 | 2020-1-31 | https://stackoverflow.com/questions/60012168/how-to-change-the-time-of-a-pandas-datetime-column-to-midnight | Using Pandas 1.0.0, how can I change the time of a datetime dataframe column to midnight in one line of code? e.g.: from START_DATETIME 2017-02-13 09:13:33 2017-03-11 23:11:35 2017-03-12 00:44:32 ... to START_DATETIME 2017-02-13 00:00:00 2017-03-11 00:00:00 2017-03-12 00:00:00 ... My attempt: df['START_DATETIME'] = d... | Your method already converted datetime values correctly to midnight. I.e., their time are 00:00:00. Pandas just intelligently doesn't show the time part because it is redundant to show all same time of 00:00:00. After you assigning result back to START_DATETIME, print a cell will show print(df.loc[0, START_DATETIME]) ... | 7 | 13 |
60,013,721 | 2020-2-1 | https://stackoverflow.com/questions/60013721/how-to-see-complete-rows-in-google-colab | I am using Google Colab python 3.x and I have a Dataframe as below. I would like to see all cells on each row and column. How can I do this? I tried pd.set_option('display.max_columns', 3000) but it didn't work. # importing pandas as pd import pandas as pd # dictionary of lists dict = {'name':["a1", "b2", "c2", "d3"], ... | use pd.set_option('max_colwidth', <width>) for column width & pd.set_option('max_rows', <rows>) for number of rows. see https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html [] pd.set_option('max_rows', 99999) [] pd.set_option('max_colwidth', 400) [] pd.describe_option('max_colwidth') display.max_colwidt... | 7 | 17 |
60,008,773 | 2020-1-31 | https://stackoverflow.com/questions/60008773/what-is-the-numpy-equivalent-of-random-sample | I want to randomly choose 2 elements out of a list. >>> import random >>> random.sample(["foo", "bar", "baz", "quux"], 2) ['quux', 'bar'] But I want to use a numpy.random.Generator to do it, rather than using Python's global random number generator. Is there a built-in or easy way to do this? >>> import numpy as np >>... | If you really want to do it from the numpy.random.Generator: import numpy as np gen = np.random.default_rng() gen.choice(["foo", "bar", "baz", "quux"], 2, replace=False) Note that np.random.choice selects with replacement by default (i.e. each item can be sampled multiple times), so turn this off if you want an equiva... | 7 | 7 |
60,007,062 | 2020-1-31 | https://stackoverflow.com/questions/60007062/how-do-i-calculate-the-levenshtein-distance-between-two-pandas-dataframe-columns | I'm trying to calculate the Levenshtein distance between two Pandas columns but I'm getting stuck Here is the library I'm using. Here is a minimal, reproducible example: import pandas as pd from textdistance import levenshtein attempts = [['passw0rd', 'pasw0rd'], ['passwrd', 'psword'], ['psw0rd', 'passwor']] df=pd.Data... | Maybe I'm missing something, is there a reason you don't like the lambda expression? This works to me: import pandas as pd from textdistance import levenshtein attempts = [['passw0rd', 'pasw0rd'], ['passwrd', 'psword'], ['psw0rd', 'passwor'], ['helloworld', 'heloworl']] df=pd.DataFrame(attempts, columns=['password', 'a... | 10 | 12 |
60,000,802 | 2020-1-31 | https://stackoverflow.com/questions/60000802/how-can-i-see-all-installed-python-modules-in-jupyter-lab-like-pip-freeze-with | I'm looking for a way to get a list of all installed/importable python modules from a within a Jupyterlab notebook. From the command line, I can get the list by running py -3 -m pip freeze (or) pip freeze In the Jupyterlab console, running pip freeze returns The following command must be run outside of the IPython sh... | import pip._internal.operations.freeze _ = pip._internal.operations.freeze.get_installed_distributions() print(sorted(["%s==%s" % (i.key, i.version) for i in _])[:10]) ['absl-py==0.7.1', 'aiml==0.9.2', 'aio-utils==0.0.1', 'aiocache==0.10.1', 'aiocontextvars==0.2.2', 'aiocqhttp==0.6.7', 'aiodns==2.0.0', 'aiofiles==0.4.0... | 9 | 3 |
60,003,006 | 2020-1-31 | https://stackoverflow.com/questions/60003006/could-validation-data-be-a-generator-in-tensorflow-keras-2-0 | In official documents of tensorflow.keras, validation_data could be: tuple (x_val, y_val) of Numpy arrays or tensors tuple (x_val, y_val, val_sample_weights) of Numpy arrays dataset For the first two cases, batch_size must be provided. For the last case, validation_steps could be provided. It does not mention if gen... | Yes it can, that's strange that it is not in the doc but is it working exactly like the x argument, you can also use a keras.Sequence or a generator. In my project I often use keras.Sequence that acts like a generator Minimum working example that shows that it works : import numpy as np from tensorflow.keras import Se... | 13 | 15 |
59,996,493 | 2020-1-31 | https://stackoverflow.com/questions/59996493/does-await-always-give-other-tasks-a-chance-to-execute | I'd like to know what guarantees python gives around when a event loop will switch tasks. As I understand it async / await are significantly different from threads in that the event loop does not switch task based on time slicing, meaning that unless the task yields (await), it will carry on indefinitely. This can actu... | You are right to be wary. caller yields from callee, and yields to the event loop. Then the event loop decides which task to resume. Other tasks may (hopefully) be squeezed in between the calls to callee. callee needs to await an actual blocking Awaitable such as asyncio.Future or asyncio.sleep(), not a coroutine, othe... | 16 | 19 |
60,000,179 | 2020-1-31 | https://stackoverflow.com/questions/60000179/sphinx-insert-argument-documentation-from-parent-method | I have some classes that inherit from each other. All classes contain the same method (let us call it mymethod), whereby the children overwrite the base class method. I want to generate a documentation for mymethod in all classes using sphinx. Suppose mymethod takes an argument myargument. This argument has the same t... | Probably not ideal, but maybe you could use a decorator to extend the docstring. For example: class extend_docstring: def __init__(self, method): self.doc = method.__doc__ def __call__(self, function): if self.doc is not None: doc = function.__doc__ function.__doc__ = self.doc if doc is not None: function.__doc__ += do... | 8 | 2 |
59,975,604 | 2020-1-29 | https://stackoverflow.com/questions/59975604/how-to-inverse-a-dft-with-magnitude-with-opencv-python | I'm new to all of this, I would like to get a magnitude spectrum from an image and then rebuild the image from a modified magnitude spectrum.. But for now i'am getting a very dark reconstitution. import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('IMG.jpg',0) dft = cv2.dft(np.float32(i... | If you need to modify the magnitude by raising it to a power near 1 (called coefficient rooting or alpha rooting), then it is just a simple modification of my code above using Python/OpenCV. Simply add cv2.pow(mag, 1.1) before converting the magnitude and phase back to real and imaginary components. Input: import nump... | 7 | 8 |
59,979,760 | 2020-1-30 | https://stackoverflow.com/questions/59979760/how-to-detect-all-rectangular-boxes-python-opencv-without-missing-anything | I'm trying to detect all the rectangles from the relational database. But some of the boxes are not being detected by my script. Please help me to do that. Thank you. The Image: My Code: #!/usr/bin/python import cv2 import numpy as np im = cv2.imread("table.png") image = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) thresh = cv... | Here's an simple approach using thresholding + morphological operations. Obtain binary image. Load image, convert to grayscale, then adaptive threshold Fill rectangular contours. Find contours and fill the contours to create filled rectangular blocks. Perform morph open. We create a rectangular structuring element and... | 10 | 14 |
59,968,630 | 2020-1-29 | https://stackoverflow.com/questions/59968630/tensorflow-one-custom-metric-for-multioutput-models | I can't find the info in the documentation so I am asking here. I have a multioutput model with 3 different outputs: model = tf.keras.Model(inputs=[input], outputs=[output1, output2, output3]) The predicted labels for validation are constructed from these 3 outputs to form only one, it's a post-processing step. The da... | With your given model definition, this is a standard multi-output Model. model = tf.keras.Model(inputs=[input], outputs=[output_1, output_2, output_3]) In general, all (custom) Metrics as well as (custom) Losses will be called on every output separately (as y_pred)! Within the loss/metric function you will only see on... | 8 | 6 |
59,974,146 | 2020-1-29 | https://stackoverflow.com/questions/59974146/installing-an-old-version-of-scikit-learn | Problem Statment I'm trying to run some old python code that requires scikit-learn 18.0 but the current version I have installed is 0.22 and so I'm getting a warning/invalid data when I run the code. What I've Tried I tried installing the specific version both in the terminal: python -m pip install scikit-learn==0.18 ... | Tackling your issues one at a time: python -m pip install scikit-learn==0.18 fails This is probably due to the fact that scikit-learn==0.18, if you check on pypi only has whl files for python 3.5 and 2.7 for windows, therefore pip downloads the source distribution and then fails in compiling it, probably because it d... | 9 | 12 |
59,981,999 | 2020-1-30 | https://stackoverflow.com/questions/59981999/find-monday-of-current-week-in-python | I am trying to get the timestamp of monday at 00:00 of the current week in python. I know that for a specific date, the timestamp can be found using baseTime = int(datetime.datetime.timestamp(datetime.datetime(2020,1,1))) However, I want my program to automatically find out, based on the date, which date monday of th... | I am trying to get the timestamp of monday at 00:00 of the current week in python You could use timedelta method from datetime package. from datetime import datetime, timedelta now = datetime.now() monday = now - timedelta(days = now.weekday()) print(monday) Output 2020-01-27 08:47:01 | 16 | 50 |
59,978,162 | 2020-1-30 | https://stackoverflow.com/questions/59978162/how-to-run-gunicorn-while-still-using-websocket | So I am using a docker for this python chat app project. I originally had python manage.py runserver 0.0.0.0:8000 as my command in docker-compose. I found that I should switch to gunicorn if I want to deploy my app on web (like heroku). The tutorial I found say simply change the command in docker-compose to gunicorn ... | When using ASGI, for asynchronous servers (websockets), you should use an asynchronous server, like Daphne or Uvicorn, the Django documentation has examples on how to deploy for both of them. If you want to use uvicorn directly you could do something like: uvicorn myproject.asgi:application --host 0.0.0.0 --port 8000 ... | 9 | 13 |
59,977,900 | 2020-1-30 | https://stackoverflow.com/questions/59977900/how-to-plot-with-pyplot-from-a-script-file-in-google-colab | I am trying to show a plot to the notebook from a python script, but all I get is a text output showing me the type() output of the figure.I have something like this: This is my script (a very simplified version of my actual script, but same concept). import matplotlib.pyplot as plt x=[1,2,3,4,5,6,5,3,2,4,2,3,4,2] plt... | Instead of calling !python plot.py Use this instead %run plot.py It will show the plot normally. | 11 | 20 |
59,976,480 | 2020-1-29 | https://stackoverflow.com/questions/59976480/docker-errno-111-connect-call-failed-127-0-0-1-6379 | I am trying to follow the tutorial here https://channels.readthedocs.io/en/latest/tutorial/part_2.html and check if channel layer can communicate with Redis. The only different thing I'm doing is that I'm using docker-compose and running the entire thing on a docker container, and that seems to be messing up with every... | Try changing 127.0.0.1:6379 to redis:6379. Although Redis is running, your python container isn't able to communicate with it; this is because it's trying to connect to 127.0.0.1:6379, but from the container's perspective, there's nothing running there. This can be a bit frustrating to debug, but it's a bit easier if y... | 15 | 29 |
59,967,429 | 2020-1-29 | https://stackoverflow.com/questions/59967429/convert-all-columns-from-int64-to-int32 | We all now the question: Change data type of columns in Pandas where it is really nice explained how to change the data type of a column, but what if I have a dataframe df with the following df.dtypes: A object B int64 C int32 D object E int64 F float32 How could I change this without explicity mention the column name... | You can create dictionary by all columns with int64 dtype by DataFrame.select_dtypes and convert it to int32 by DataFrame.astype, but not sure if not fail if big integers numbers: df = pd.DataFrame({ 'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb') }) d ... | 11 | 17 |
59,882,884 | 2020-1-23 | https://stackoverflow.com/questions/59882884/vscode-doesnt-show-poetry-virtualenvs-in-select-interpreter-option | I need help. VSCode will NEVER find poetry virtualenv interpreter no matter what I try. Installed poetry Python package manager using a standard $ curl method as explained in the official documentation. Started a project by $ poetry new finance-essentials_37-64, installed poetry environment with $ poetry install. So... | You just need to type in your shell: poetry config virtualenvs.in-project true The virtualenv will be created inside the project path and vscode will recognize. Consider adding this to your .bashrc or .zshrc. If you already have created your project, you need to re-create the virtualenv to make it appear in the corre... | 193 | 482 |
59,874,373 | 2020-1-23 | https://stackoverflow.com/questions/59874373/type-hint-for-a-list-of-possible-values | I have a function which can take a fixed list of values: e.g. def func(mode="a"): if mode not in ["a", "b"]: raise AttributeError("not ok") is there a way to type hint it can only be one of these two values? | I think you want a literal type: def func(mode: Literal["a", "b"] = "a"): if mode not in ["a", "b"]: raise AttributeError("not ok") This was introduced in Python 3.8, via PEP 586. | 18 | 35 |
59,875,983 | 2020-1-23 | https://stackoverflow.com/questions/59875983/why-is-caplog-text-empty-even-though-the-function-im-testing-is-logging | I'm trying to use pytest to test if my function is logging the expected text, such as addressed this question (the pyunit equivalent would be assertLogs). Following the pytest logging documentation, I am passing the caplog fixture to the tester. The documentation states: Lastly all the logs sent to the logger during t... | The documentation is unclear here. From trial and error, and notwithstanding the "all the logs sent to the logger during the test run are made available" text, it still only captures logs with certain log levels. To actually capture all logs, one needs to set the log level for captured log messages using caplog.set_lev... | 34 | 33 |
59,955,854 | 2020-1-28 | https://stackoverflow.com/questions/59955854/what-is-md5-md5-and-why-is-hashlib-md5-so-much-slower | Found this undocumented _md5 when getting frustrated with the slow stdlib hashlib.md5 implementation. On a macbook: >>> timeit hashlib.md5(b"hello world") 597 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> timeit _md5.md5(b"hello world") 224 ns ± 3.18 ns per loop (mean ± std. dev. of 7 runs,... | Until Python 2.5, hashes and digests were implemented in their own modules (e.g. [Python 2.Docs]: md5 - MD5 message digest algorithm). Starting with v2.5, [Python 2.6.Docs]: hashlib - Secure hashes and message digests was added. Its purpose was to: Offer an unified access method to the hashes / digests (via their name... | 11 | 9 |
59,953,431 | 2020-1-28 | https://stackoverflow.com/questions/59953431/how-to-change-plotly-figure-size | I made the following scatter plot with Plotly: import plotly import plotly.plotly as py from plotly.graph_objs import Scatter import plotly.graph_objs as go trace1 = go.Scatter( x=x1_tsne, # x-coordinates of trace y=y1_tsne, # y-coordinates of trace mode="markers ", # scatter mode (more in UG section 1) text=label3, o... | Consider using: fig.update_layout( autosize=False, width=800, height=800, ) ...and then eventually reduce the size of your marker. Full code: import plotly.graph_objs as go trace1 = go.Scatter( x=x1_tsne, # x-coordinates of trace y=y1_tsne, # y-coordinates of trace mode="markers +text ", # scatter mode (more in UG sec... | 69 | 108 |
59,899,134 | 2020-1-24 | https://stackoverflow.com/questions/59899134/how-to-change-individual-entries-in-xarray-dataarray-with-sel | I have data inside an xarray.DataArray that I want to manipulate, however, it do not manage to change individual entries in the DataArray. Example: import numpy as np import xarray as xr data = np.random.rand(2,2) times = [1998,1999] locations = ['It','Be'] A = xr.DataArray(data, coords = [times, locations], dims = [... | Xarray's assignment does not allow you to assign values to arrays using sel or isel. This is described in the documentation here. For your application, you probably want to use the .loc property: A.loc[dict(time=1998, space='It')] = 5 It is also possible to use DataArray.where to replace values. | 6 | 12 |
59,893,782 | 2020-1-24 | https://stackoverflow.com/questions/59893782/how-to-exit-cleanly-from-flask-and-waitress-running-as-a-windows-pywin32-servi | I have managed to cobble together a working demo of a pywin32 Windows service running Flask inside the Pylons waitress WSGI server (below). A nice self contained solution is the idea... I have spent hours reviewing and testing ways of making waitress exit cleanly (like this and this), but the best I can do so far is a ... | I have found a solution using a sub-thread that seems to work. I am not quite sure if this may have possible unintended consequences yet... I believe the updated version below, "injecting" a SystemExit into the waitress thread is as good as it gets. I think thee original kills the thread hard, but this one prints "thre... | 13 | 10 |
59,854,439 | 2020-1-22 | https://stackoverflow.com/questions/59854439/how-to-create-requirement-txt-without-all-package-versions | Right now my requirement.txt contains following package list: asgiref==3.2.3 beautifulsoup4==4.8.2 certifi==2019.11.28 chardet==3.0.4 Click==7.0 Django==3.0.2 idna==2.8 pytz==2019.3 requests==2.22.0 six==1.14.0 soupsieve==1.9.5 sqlparse==0.3.0 urllib3==1.25.7 I just want the package name only, so that pip3 always ins... | Use sed to remove version info from your requirements.txt file. e.g. sed 's/==.*$//' requirements.txt will give output asgiref beautifulsoup4 certifi chardet Click Django idna pytz requests six soupsieve sqlparse urllib3 and this can be piped into pip to do the install sed 's/==.*$//' requirements.txt | xargs pip ins... | 11 | 9 |
59,890,977 | 2020-1-24 | https://stackoverflow.com/questions/59890977/f-string-multiple-format-specifiers | Is it possible to use multiple format specifiers in a Python f-string? For example, let's say we want to round up numbers to two decimal points and also specify a width for print. Individually it looks like this: In [1]: values = [12.1093, 13.95123] In [2]: for v in values: print(f'{v:.2}') 1.2e+01 1.4e+01 In [3]: for ... | Dependent on the result you want, you can combine them normally such as; for v in values: print(f"{v:<10.2} value") #1.2e+01 value #1.4e+01 value However, your result does not seem like the result you're looking for. To force the fixed notation of the 2 you need to add f: for v in values: print(f"{v:<10.2f} value") #1... | 15 | 9 |
59,953,611 | 2020-1-28 | https://stackoverflow.com/questions/59953611/how-can-i-get-a-tqdm-progress-apply-bar-in-pandas-operations-in-vs-code-notebook | I am trying to display a progress bar when I perform "vector" progress_apply operations on pandas dataframes, in MS Visual Studio Code. In VS Code with the Python extension enabled, I tried in a cell import pandas as pd from tqdm import tqdm_notebook, tqdm_pandas tqdm_notebook().pandas() df = pd.DataFrame({'a' : ['foo'... | Revisiting this in 2022 (VS Code 1.63.2), the code below will work fine in VS code, and may be more appealing visually than the other solution I previously had for this: import pandas as pd from tqdm.notebook import tqdm tqdm.pandas() df = pd.DataFrame({'a' : ['foo', 'bar'], 'b' : ['spam', 'eggs']}) df.progress_apply(l... | 11 | 7 |
59,930,590 | 2020-1-27 | https://stackoverflow.com/questions/59930590/prettier-vscode-extension-not-support-django-template-tags-tag | The Prettier Visual Studio Code extension does not support Django template tags {% %}. How can I fix this? Do I have to disable Prettier for HTML files, or is there another solution? See this GitHub issue too: No Django template tags support | February 2022 Based on @Al Mahdi's comment: Prettier does not support prettier.disableLanguages option anymore. Therefore, to ignore certain files you have to create a .prettierignore file akin a .gitignore file (for people who use Git). The file lives in the root folder of your project. Source of my examples below. To... | 16 | 19 |
59,938,578 | 2020-1-27 | https://stackoverflow.com/questions/59938578/pybind11-running-the-test-cases | I'm trying to learn pybind11 and the first Google result is this page, where you should be guided towards compiling and running some test cases. From this page, I have installed bybind11 by: pip3 install pybind11 and I have installed: sudo apt install python3-dev cmake as instructed in the original page. But I don't ... | You need to install pybind11 as instructed here by cloning the GitHub repository: python3 -m pip install pytest numpy scipy sudo apt install -y cmake python3-dev libeigen3-dev libboost-dev git git clone https://github.com/pybind/pybind11.git cd pybind11 cmake -DDOWNLOAD_CATCH=1 mkdir build cd build cmake .. sudo make i... | 8 | 6 |
59,882,714 | 2020-1-23 | https://stackoverflow.com/questions/59882714/python-generating-a-list-of-dates-between-two-dates | I want to generate a list of dates between two dates and store them in a list in string format. This list is useful to compare with other dates I have. My code is given below: from datetime import date, timedelta sdate = date(2019,3,22) # start date edate = date(2019,4,9) # end date def dates_bwn_twodates(start_date,... | You can use pandas.date_range() for this: import pandas pandas.date_range(sdate,edate-timedelta(days=1),freq='d') DatetimeIndex(['2019-03-22', '2019-03-23', '2019-03-24', '2019-03-25', '2019-03-26', '2019-03-27', '2019-03-28', '2019-03-29', '2019-03-30', '2019-03-31', '2019-04-01', '2019-04-02', '2019-04-03', '2019-0... | 97 | 146 |
59,870,193 | 2020-1-23 | https://stackoverflow.com/questions/59870193/is-there-a-function-in-pyspark-dataframe-that-is-similar-to-pandas-io-json-json | I would like to perform operation similar to pandas.io.json.json_normalize is pyspark dataframe. Is there an equivalent function in spark? https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.json.json_normalize.html | Spark has a similar function explode() but it is not entirely identical. Here is how explode works at a very high level. >>> from pyspark.sql.functions import explode, col >>> data = {'A': [1, 2]} >>> df = spark.createDataFrame(data) >>> df.show() +------+ | A| +------+ |[1, 2]| +------+ >>> df.select(explode(col('A'))... | 8 | 4 |
59,905,761 | 2020-1-25 | https://stackoverflow.com/questions/59905761/split-train-data-to-train-and-validation-by-using-tensorflow-datasets-load-tf-2 | I'm trying to run the following Colab project, but when I want to split the training data into validation and train parts I get this error: KeyError: "Invalid split train[:70%]. Available splits are: ['train']" I use the following code: (training_set, validation_set), dataset_info = tfds.load( 'tf_flowers', split=['t... | According to the Tensorflow Dataset docs the approach you presented is now supported. Splitting is possible by passing split parameter to tfds.load like so split="test[:70%]". (training_set, validation_set), dataset_info = tfds.load( 'tf_flowers', split=['train[:70%]', 'train[70%:]'], with_info=True, as_supervised=True... | 10 | 9 |
59,868,527 | 2020-1-22 | https://stackoverflow.com/questions/59868527/how-can-i-upload-a-pil-image-object-to-a-discord-chat-without-saving-the-image | I'm trying to send a PIL Image object to a discord chat (I don't want to save the file though) I have a function that gathers images from the internet, joins them together vertically and then return a PIL Image object. The code below creates a file image from the PIL Image object on my local machine and then sends it ... | Posting my solution as a separate answer. Thanks Ceres for the recommendation. @client.event async def on_message(message): if message.content.startswith('^index'): with BytesIO() as image_binary: create_image().save(image_binary, 'PNG') image_binary.seek(0) await message.channel.send(file=discord.File(fp=image_binary,... | 9 | 4 |
59,897,093 | 2020-1-24 | https://stackoverflow.com/questions/59897093/get-all-keys-and-its-hierarchy-in-h5-file-using-python-library-h5py | Is there any way I can recursively get all keys in h5 file using python library h5py? I tried using the code below import h5py h5_data = h5py.File(h5_file_location, 'r') print(h5_data.keys()) but it only print the top level keys of the h5 file. | Some of the keys returned by keys() on a Group may be Datasets some may be sub Groups. In order to find all keys you need to recurse the Groups. Here is a simple script to do that: import h5py def allkeys(obj): "Recursively find all keys in an h5py.Group." keys = (obj.name,) if isinstance(obj, h5py.Group): for key, val... | 10 | 10 |
59,868,987 | 2020-1-22 | https://stackoverflow.com/questions/59868987/saving-multiple-plots-into-a-single-html | I recently discovered plotly and find it really good for graphing, now I have a problem which I want to save multiple plot into a single html, how to do it please? *I want to save multiple plot, i.e fig, fig1, fig 2 and so on, NOT one subplot which has multiple plot in it, because I found that the plot within subplot i... | In the Plotly API there is a function to_html which returns HTML of the figure. Moreover, you can set option param full_html=False which will give you just DIV containing figure. You can just write multiple figures to one HTML by appending DIVs containing figures: with open('p_graph.html', 'a') as f: f.write(fig1.to_ht... | 43 | 101 |
59,893,850 | 2020-1-24 | https://stackoverflow.com/questions/59893850/how-to-accumulate-gradients-in-tensorflow-2-0 | I'm training a model with tensorflow 2.0. The images in my training set are of different resolutions. The Model I've built can handle variable resolutions (conv layers followed by global averaging). My training set is very small and I want to use full training set in a single batch. Since my images are of different re... | If I understand correctly from this statement: How can I accumulate the losses/gradients and then apply a single optimizer step? @Nagabhushan is trying to accumulate gradients and then apply the optimization on the (mean) accumulated gradient. The answer provided by @TensorflowSupport does not answers it. In order to... | 8 | 9 |
59,887,436 | 2020-1-23 | https://stackoverflow.com/questions/59887436/importerror-cannot-import-name-packagefinder | after updating everything in conda, pip can't install anything conda update -n base conda conda update --all when install or upgrade anything, this error is show $ pip install --upgrade HDF5 Traceback (most recent call last): File "C:\ProgramData\Anaconda3\Scripts\pip-script.py", line 10, in <module> sys.exit(main())... | It seems that this works. Reinstall the latest version of pip: $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py && python get-pip.py When you’re done, delete the installation script: $ rm get-pip.py | 26 | 41 |
59,920,760 | 2020-1-26 | https://stackoverflow.com/questions/59920760/python-graphql-gql-client-authentication | I´m having hard time to use GraphQL with Python since the suggested library: gql is completely undocumented. How ever I found out that to provide the api url I need to pass a RequestsHTTPTransport object to Client like this: client = Client(transport=RequestsHTTPTransport(url='https://some.api.com/v3/graphql')) but ho... | You can add it in the headers. reqHeaders = { 'x-api-key' : API_KEY, 'Authorization': 'Bearer ' + TOKEN_KEY // This is the key } _transport = RequestsHTTPTransport( url=API_ENDPOINT, headers = reqHeaders, use_json=True, ) client = Client( transport = _transport, fetch_schema_from_transport=True, ) | 8 | 7 |
59,938,619 | 2020-1-27 | https://stackoverflow.com/questions/59938619/does-the-django-address-module-provide-a-way-to-seed-the-initial-country-data | I'm using Django 2.0, Python 3.7, and MySql 5. I recently installed the django_address module. I noticed when I ran my initial migration based on my models.py file ... from django.db import models from address.models import AddressField from phonenumber_field.modelfields import PhoneNumberField class CoopType(models.Mo... | I'd suggest you write a simple management command that imports data from pycountry into your address models (approach borrowed from here). pycountry is a wrapper around the ISO standard list of countries - i.e., it's about as canonical a list of countries as you're going to get. A management command to populate all the... | 7 | 0 |
59,920,770 | 2020-1-26 | https://stackoverflow.com/questions/59920770/get-the-nearest-distance-with-two-geodataframe-in-pandas | Here is my first geodatframe : !pip install geopandas import pandas as pd import geopandas city1 = [{'City':"Buenos Aires","Country":"Argentina","Latitude":-34.58,"Longitude":-58.66}, {'City':"Brasilia","Country":"Brazil","Latitude":-15.78 ,"Longitude":-70.66}, {'City':"Santiago","Country":"Chile ","Latitude":-33.45 ,"... | Firstly, I merge two data frames by cross join. And then, I found distance between two points using map in python. I use map, because most of the time it is much faster than apply, itertuples, iterrows etc. (Reference: https://stackoverflow.com/a/52674448/8205554) Lastly, I group by data frame and fetch minimum values ... | 14 | 13 |
59,894,984 | 2020-1-24 | https://stackoverflow.com/questions/59894984/torch-installation-results-in-not-supported-wheel-on-this-platform | Tried running pip3 install torch===1.4.0 torchvision===0.5.0 -f https://download.pytorch.org/whl/torch_stable.html first, taken from PyTorch website which resulted in No matching distribution found for torch===1.4.0 and Could not find a version that satisfies the requirement torch===1.4.0 (from versions: 0.1.2, 0.1.2.... | using 64 Python 3.8 but you downloaded the cp37 whl which is for python 3.7. There is currently no whl file available for python 3.8. So either install from source (probably not recommended), install a different python version or create a virtual environment with python 3.7 Update There is now: https://download.pytor... | 6 | 8 |
59,856,694 | 2020-1-22 | https://stackoverflow.com/questions/59856694/how-to-get-around-slow-groupby-for-a-sparse-matrix | I have a large matrix (~200 million rows) describing a list of actions that occurred every day (there are ~10000 possible actions). My final goal is to create a co-occurrence matrix showing which actions happen during the same days. Here is an example dataset: data = {'date': ['01', '01', '01', '02','02','03'], 'actio... | I came up with an answer using only sparse matrices based on this post. The code is fast, taking about 10 seconds for 10 million rows (my previous code took 6 minutes for 5000 rows and was not scalable). The time and memory savings come from working with sparse matrices until the very last step when it is necessary to... | 7 | 3 |
59,956,479 | 2020-1-28 | https://stackoverflow.com/questions/59956479/python-warning-plotly-graph-objs-line-is-deprecated | Although everything works fine, I would like to know whether there is a way to fix what is provoking this warning: plotly.graph_objs.Line is deprecated. Please replace it with one of the following more specific types plotly.graph_objs.scatter.Line plotly.graph_objs.layout.shape.Line etc. | Fixing the warning regarding deprecated functions may variate, depending on the packages at use. In my particular case, I was using the "Line" function from "plotly" package. This function was being called from another package. In the latter package there was a .py file (I used "IDLE (Python 3.8 64-bit)" to edit it) th... | 8 | 2 |
59,937,482 | 2020-1-27 | https://stackoverflow.com/questions/59937482/100-classifier-accuracy-after-using-train-test-split | I'm working on the mushroom classification data set (found here: https://www.kaggle.com/uciml/mushroom-classification). I'm trying to split my data into training and testing sets for my models, however if i use the train_test_split method my models always achieve 100% accuracy. This is not the case when i split my data... | You got lucky there on your train_test_split. The split you are doing manually may be having the most unseen data, which is doing better validation than the train_test_split which internally shuffled the data to split it. For better validation use K-fold cross validation, which will allow to verify the model accuracy w... | 8 | 3 |
59,944,653 | 2020-1-28 | https://stackoverflow.com/questions/59944653/foreign-key-to-the-same-table-in-python-peewee | I am using ORM peewee for sqlite in Python. I would like to create table Item with field parent_id that will be foreign key to the Item: from peewee import * db = SqliteDatabase("data.db") class Item(Model): id = AutoField() parent_id = ForeignKeyField(Item, null = True) class Meta: database = db db.create_tables([Item... | This is documented very clearly: http://docs.peewee-orm.com/en/latest/peewee/models.html#self-referential-foreign-keys You just put 'self' as the identifier: class Item(Model): id = AutoField() parent = ForeignKeyField('self', backref='children', null=True) class Meta: database = db You do not need to mess with any de... | 7 | 10 |
59,957,089 | 2020-1-28 | https://stackoverflow.com/questions/59957089/how-to-send-one-gcode-command-over-usb | I am trying to write a simple python script that sends a gcode command to my wanhao D9 motherboard printer, running Marlin. I am running the python script on a raspberry pi that is connected to the printer via USB. import serial ser = serial.Serial("/dev/ttyUSB0", 115200) ser.write("G28\n") I have read over 20 forum p... | Adding an extra sleep period after my command fixed my issue. I can also now read back the initial set up feedback from the printer. My final code without this is: import serial import time ser = serial.Serial('/dev/ttyUSB0', 115200) time.sleep(2) ser.write("G28\r\n") time.sleep(1) ser.close() Thank you, to the users ... | 8 | 6 |
59,956,496 | 2020-1-28 | https://stackoverflow.com/questions/59956496/f-strings-formatter-including-for-loop-or-if-conditions | How can I insert for loops or if expressions inside an f-string? I thought initially of doing something like this for if expressions: f'{a:{"s" if CONDITION else "??"}}' What I would like to do though is something like: Example 1 f'{key: value\n for key, value in dict.items()}' result: if dict = {'a': 1, 'b': 2} a: 1... | Both ternaries ("if expressions") and comprehensions ("for expressions") are allowed inside f-strings. However, they must be part of expressions that evaluate to strings. For example, key: value is a dict pair, and f"{key}: {value}" is required to produce a string. >>> dct = {'a': 1, 'b': 2} >>> newline = "\n" # \escap... | 9 | 25 |
59,956,670 | 2020-1-28 | https://stackoverflow.com/questions/59956670/parsing-city-of-origin-destination-city-from-a-string | I have a pandas dataframe where one column is a bunch of strings with certain travel details. My goal is to parse each string to extract the city of origin and destination city (I would like to ultimately have two new columns titled 'origin' and 'destination'). The data: df_col = [ 'new york to venice, italy for usd271... | TL;DR Pretty much impossible at first glance, unless you have access to some API that contains pretty sophisticated components. In Long From first look, it seems like you're asking to solve a natural language problem magically. But lets break it down and scope it to a point where something is buildable. First, to ide... | 33 | 159 |
59,957,962 | 2020-1-28 | https://stackoverflow.com/questions/59957962/difference-between-conda-install-with-c-anaconda-and-without-it | I am new to python and I am trying to install new packages in Anaconda. I am using anaconda prompt and Windows 10. Can you please explain what is the difference between conda install with -c anaconda and without it? For example conda install -c anaconda mysqlclient and conda install mysqlclient. Which is better to use... | When you use the -c option, you are specifying the channel from which to get the package. The default is -c anaconda, so they are similar. To use packages built locally, you would use -c local. Here is a link for more info: Docs explaining usage of conda install | 6 | 4 |
59,957,171 | 2020-1-28 | https://stackoverflow.com/questions/59957171/removing-non-ascii-and-special-character-in-pyspark-dataframe-column | I am reading data from csv files which has about 50 columns, few of the columns(4 to 5) contain text data with non-ASCII characters and special characters. df = spark.read.csv(path, header=True, schema=availSchema) I am trying to remove all the non-Ascii and special characters and keep only English characters, and I t... | This should work. First creating a temporary example dataframe: df = spark.createDataFrame([ (0, "This is Spark"), (1, "I wish Java could use case classes"), (2, "Data science is cool"), (3, "This is aSA") ], ["id", "words"]) df.show() Output +---+--------------------+ | id| words| +---+--------------------+ | 0| T... | 6 | 11 |
59,907,079 | 2020-1-25 | https://stackoverflow.com/questions/59907079/visual-studio-codes-debugger-pipenv | I would like to use Visual Studio Code's debugger to debug my python code, but exception occurs. I use Windows 10, WSL, Debian, Python 3.7.6. Exception has occurred: ModuleNotFoundError No module named 'flask' File "/home/kazu/test/main.py", line 2, in <module> from flask import Flask This is python debugger console... | If you look in the bottom-left corner of your screen you will notice you are currently running against a pyenv install of Python and not a pipenv virtual environment. If you click on the interpreter name and select the appropriate environment where you installed flask it should fix your issue. | 18 | 31 |
59,955,751 | 2020-1-28 | https://stackoverflow.com/questions/59955751/abcmeta-object-is-not-subscriptable-when-trying-to-annotate-a-hash-variable | The following dataclass: from abc import ABC from collections.abc import Mapping from dataclasses import dataclass, field @dataclass(eq=True, order=True, frozen=True) class Expression(Node, ABC): def node(self): raise NotImplementedError is used as a base class for: @dataclass(eq=True, frozen=True) class HashLiteral(E... | You should use typing.Mapping instead of collections.abc.Mapping. typing contains many generic versions of various types, which are designed to be used in type hints. According to the mypy documentation, there are some differences between the typing classes and the collections.abc classes, but they're unclear on exactl... | 38 | 83 |
59,953,127 | 2020-1-28 | https://stackoverflow.com/questions/59953127/tensorflow-2-1-0-has-no-attribute-random-normal | I'm trying to get Uber's Ludwig to run. I get an error about there being no attribute 'random_normal'. I can reproduce the error in Python with these commands. >>> import tensorflow as tf >>> tf.reduce_sum(tf.random_normal([1000,1000])) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeErr... | It was moved to tf.random.normal (along with all the other tf.random_* functions) | 28 | 48 |
59,951,983 | 2020-1-28 | https://stackoverflow.com/questions/59951983/enum-missing-function-not-silencing-valueerror | I'm trying to set up an Enum that will return None if the value is not found. The documentation mentions a function _missing_, but does not explain any of the details regarding the function: _missing_ – a lookup function used when a value is not found; may be overridden After some looking around, it seems this is a c... | The 2 main things that the documentation is missing regarding the _missing_ function is the signature in the question, and the fact that the return type MUST be a member of the Enum. If None is returned, then the error simply isn't silenced. This behaviour is only seen through source inspection or a different error mes... | 9 | 9 |
59,903,051 | 2020-1-24 | https://stackoverflow.com/questions/59903051/sphinxs-autodocs-automodule-having-apparently-no-effect | I am running Sphinx on a rst file containing automodule but it does not seem to have any effect. Here are the details: I have a Python project with a file agent.py containing a class Agent in it. I also have a subdirectory apidoc with a file agent.rst in it (generated by sphinx-apidoc): agent module ============ .. aut... | I'll try answering by putting the "canonical" approach side-by-side with your case. The usual "getting started approach" follows these steps: create a doc directory in your project directory (it's from this directory the commands in the following steps are executed). sphinx-quickstart (choosing separate source from bu... | 7 | 17 |
59,944,182 | 2020-1-28 | https://stackoverflow.com/questions/59944182/how-to-create-a-visualization-for-events-along-a-timeline | I'm building a visualization with Python. There I'd like to visualize fuel stops and the fuel costs of my car. Furthermore, car washes and their costs should be visualized as well as repairs. The fuel costs and laundry costs should have a higher bar depending on the costs. I created the visualization below to describe ... | Yes, this kind of visualization is perfectly possible with matplotlib. To store the data, numpy arrays are usually very handy. Here is some code to get you started: import matplotlib.pyplot as plt import numpy as np refuel_km = np.array([0, 505.4, 1070, 1690]) refuel_cost = np.array([40.1, 50, 63, 55]) carwash_km = np.... | 7 | 16 |
59,920,126 | 2020-1-26 | https://stackoverflow.com/questions/59920126/rest-api-in-python-with-fastapi-and-pydantic-read-only-property-in-model | Assume a REST API which defines a POST method on a resource /foos to create a new Foo. When creating a Foo the name of the Foo is an input parameter (present in the request body). When the server creates a Foo it assigns it an ID. This ID is returned together with the name in the REST response. I am looking for somethi... | It is fine to have multiple models. You can use inheritance to reduce code repetition: from pydantic import BaseModel # Properties to receive via API create/update class Foo(BaseModel): name: str # Properties to return via API class FooDB(Foo): id: int The documentation which is excellent btw!, goes into this more in-... | 7 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.