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
62,106,028
2020-5-30
https://stackoverflow.com/questions/62106028/what-is-the-difference-between-np-linspace-and-np-arange
I have always used np.arange. I recently came across np.linspace. I am wondering what exactly is the difference between them... Looking at their documentation: np.arange: Return evenly spaced values within a given interval. np.linspace: Return evenly spaced numbers over a specified interval. The only difference I c...
np.linspace allows you to define how many values you get including the specified min and max value. It infers the stepsize: >>> np.linspace(0,1,11) array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) np.arange allows you to define the stepsize and infers the number of steps(the number of values you get). >>...
79
109
62,100,869
2020-5-30
https://stackoverflow.com/questions/62100869/ansible-error-the-python-2-bindings-for-rpm-are-needed-for-this-module
Im trying to pip install a requirements file in my python3 environment using the following task pip: python3: yes requirements: ./requirements/my_requirements.txt extra_args: -i http://mypypi/windows/simple I checked which version ansible is running on the controller node (RH7) and it's 3.6.8 ansible-playbook 2.9.9 co...
I had a similar problem with the "Amazon Linux 2" distribution that uses yum, but does not support dnf as of this writing. As mentioned in the comments above, my problem was in the ansible-managed nodes (AWS EC2 instances running Amazon Linux 2) and not in the controller. Solved it by imposing the use of python2, addin...
15
15
62,066,474
2020-5-28
https://stackoverflow.com/questions/62066474/python-flask-automatically-generated-swagger-openapi-3-0
Im trying to generate swagger document for my existing Flask app, I tried with Flask-RESTPlus initially and found out the project is abundant now and checked at the forked project flask-restx https://github.com/python-restx/flask-restx but still i dont think they support openapi 3.0 Im a bit confused to choose the pac...
I found a package to generate openapi 3.0 document https://apispec.readthedocs.io/en/latest/install.html This package serves the purpose neatly. Find the below code for detailed usage. from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from apispec_webframeworks.flask import FlaskPlugin f...
19
25
62,119,073
2020-5-31
https://stackoverflow.com/questions/62119073/why-are-migrations-files-often-excluded-from-code-formatting
We're applying Black code style to a django project. In all the tutorials / examples I find (such as in django cookiecutter and this blog), I keep seeing django's migrations files excluded from the linter. But to my mind, these are still python files. Sure, django may not autogenerate them to meet the Black spec. But i...
I bit the bullet and applied Black to my migrations files, progressively across half a dozen django projects. No problems at all, everything deployed in production for months now. So the answer is: No reason at all why not to do this, and I think migrations files should be included, so that reading them is a consistent...
14
8
62,158,734
2020-6-2
https://stackoverflow.com/questions/62158734/deprecationwarning-the-default-dtype-for-empty-series-will-be-object-instead
I appending a new row to an existing pandas dataframe as follows: df= df.append(pd.Series(), ignore_index=True) This is resulting in the subject DeprecationWarning. The existing df has a mix of string, float and dateime.date datatypes (8 columns totals). Is there a way to explicitly specify the columns types in the df...
You can try this Type_new = pd.Series([],dtype=pd.StringDtype()) This will create a blank data frame for us.
18
17
62,082,873
2020-5-29
https://stackoverflow.com/questions/62082873/conda-not-activated-in-power-shell
I have already install anaconda on my Windows 10 laptop. I'm trying to activate the Python environment named pyenv. First, I check the conda env list in my laptop, this is the output on the power shell: PS C:\Users\User> conda env list # conda environments: # base * C:\Users\User\Anaconda3 pyenv C:\Users\User\Anaconda3...
After a while, my Powershell appear this error when I open it. . : File C:\Users\User\Documents\WindowsPowerShell\profile.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 + . 'C:...
20
21
62,141,051
2020-6-1
https://stackoverflow.com/questions/62141051/flask-how-to-register-a-wrapper-to-all-methods
I've been moving from bottle to flask. I'm the type of person that prefers writing my own code instead of downloading packages from the internet if I the code needed is 20 lines or less. Take for example support for Basic authentication protocol. In bottle I could write: def allow_anonymous(): """assign a _allow_anonym...
You can definitely some of the functionality of flask-httpauth yourself, if you wish :-P I would think you will need to play some before_request games (not very beautiful), or alternatively call flask's add_url_rule with a decorated method for each api endpoint (or have a route decorator of your own that will do this)....
13
5
62,057,838
2020-5-28
https://stackoverflow.com/questions/62057838/how-to-retrieve-the-labels-used-in-a-segmentation-mask-in-aws-sagemaker
From a segmentation mask, I am trying to retrieve what labels are being represented in the mask. This is the image I am running through a semantic segmentation model in AWS Sagemaker. Code for making prediction and displaying mask. from sagemaker.predictor import json_serializer, json_deserializer, RealTimePredictor ...
Somewhere you should have a mapping from label integers to label classes, e.g. label_map = {0: 'background', 1: 'motorbike', 2: 'train', ...} If you are using the Pascal VOC dataset, that would be (1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle, 6=bus, 7=car , 8=cat, 9=chair, 10=cow, 11=diningtable, 12=dog, 13=horse...
8
1
62,148,564
2020-6-2
https://stackoverflow.com/questions/62148564/read-files-with-only-specific-names-from-amazon-s3
I have connected to Amazon S3 and am trying to retrieve data from the JSON content from multiple buckets using the below code. But I have to read only specific JSON files, but not all. How do I do it? Code: for i in bucket: try: result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/') con...
There are several ways to do this in Python. For example, checking if 'stringA' is in 'stringB': list1=['test-eob/PROCESSED_BY/FILE_JSON/222-Account.json', 'test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json', 'test-eob/PROCESSED_BY/FILE_JSON/122-multi.json', 'test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json', 'tes...
9
3
62,123,125
2020-5-31
https://stackoverflow.com/questions/62123125/how-to-join-strings-between-parentheses-in-a-list-of-strings
poke_list = [... 'Charizard', '(Mega', 'Charizard', 'X)', '78', '130', ...] #1000+ values Is it possible to merge strings that start with '(' and end with ')' and then reinsert it into the same list or a new list? My desired output poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]
Another way to do it, slightly shorter than other solution poke_list = ['Bulbasaur', 'Charizard', '(Mega', 'Charizard', 'X)', '78', 'Pikachu', '(Raichu)', '130'] fixed = [] acc = fixed for x in poke_list: if x[0] == '(': acc = [fixed.pop()] acc.append(x) if x[-1] == ')': fixed.append(' '.join(acc)) acc = fixed if not a...
7
2
62,092,147
2020-5-29
https://stackoverflow.com/questions/62092147/how-to-efficiently-assign-to-a-slice-of-a-tensor-in-tensorflow
I want to assign some values to slices of an input tensor in one of my model in TensorFlow 2.x (I am using 2.2 but ready to accept a solution for 2.1). A non-working template of what I am trying to do is: import tensorflow as tf from tensorflow.keras.models import Model class AddToEven(Model): def call(self, inputs): o...
Here is another solution based on binary mask. """Solution based on binary mask. - We just add this mask to inputs, instead of multiplying.""" class AddToEven(tf.keras.Model): def __init__(self): super(AddToEven, self).__init__() def build(self, inputshape): self.built = True # Actually nothing to build with, becuase ...
8
3
62,097,219
2020-5-30
https://stackoverflow.com/questions/62097219/getting-a-error-400-redirect-uri-mismatch-when-trying-to-use-oauth2-with-google
I am trying to connect to Google Sheets' API from a Django view. The bulk of the code I have taken from this link: https://developers.google.com/sheets/api/quickstart/python Anyway, here are the codes: sheets.py (Copy pasted from the link above, function renamed) from __future__ import print_function import pickle impo...
You shouldn't be using Flow.run_local_server() unless you don't have the intention of deploying the code. This is because run_local_server launches a browser on the server to complete the flow. This works just fine if you're developing the project locally for yourself. If you're intent on using the local server to nego...
7
5
62,095,767
2020-5-29
https://stackoverflow.com/questions/62095767/how-to-create-a-custom-preprocessinglayer-in-tf-2-2
I would like to create a custom preprocessing layer using the tf.keras.layers.experimental.preprocessing.PreprocessingLayer layer. In this custom layer, placed after the input layer, I would like to normalize my image using tf.cast(img, tf.float32) / 255. I tried to find some code or example showing how to create this ...
If you want to have a custom preprocessing layer, actually you don't need to use PreprocessingLayer. You can simply subclass Layer Take the simplest preprocessing layer Rescaling as an example, it is under the tf.keras.layers.experimental.preprocessing.Rescaling namespace. However, if you check the actual implementatio...
7
9
62,079,732
2020-5-29
https://stackoverflow.com/questions/62079732/did-i-o-become-slower-since-python-2-7
I'm currently having a small side project in which I want to sort a 20GB file on my machine as fast as possible. The idea is to chunk the file, sort the chunks, merge the chunks. I just used pyenv to time the radixsort code with different Python versions and saw that 2.7.18 is way faster than 3.6.10, 3.7.7, 3.8.3 and 3...
This is a combination of multiple effects, mostly the fact that Python 3 needs to perform unicode decoding/encoding when working in text mode and if working in binary mode it will send the data through dedicated buffered IO implementations. First of all, using time.time to measure execution time uses the wall time and ...
8
14
62,144,904
2020-6-2
https://stackoverflow.com/questions/62144904/python-how-to-retrieve-the-best-model-from-optuna-lightgbm-study
I would like to get the best model to use later in the notebook to predict using a different test batch. reproducible example (taken from Optuna Github) : import lightgbm as lgb import numpy as np import sklearn.datasets import sklearn.metrics from sklearn.model_selection import train_test_split import optuna # FYI: Ob...
I think you can use the callback argument of Study.optimize to save the best model. In the following code example, the callback checks if a given trial is corresponding to the best trial and saves the model as a global variable best_booster. best_booster = None gbm = None def objective(trial): global gbm # ... def call...
23
13
62,115,817
2020-5-31
https://stackoverflow.com/questions/62115817/tensorflow-keras-rmse-metric-returns-different-results-than-my-own-built-rmse-lo
This is a regression problem My custom RMSE loss: def root_mean_squared_error_loss(y_true, y_pred): return tf.keras.backend.sqrt(tf.keras.losses.MSE(y_true, y_pred)) Training code sample, where create_model returns a dense fully connected sequential model from tensorflow.keras.metrics import RootMeanSquaredError mode...
Two key differences, from source code: RMSE is a stateful metric (it keeps memory) - yours is stateless Square root is applied after taking a global mean, not before an axis=-1 mean like MSE does As a result of 1, 2 is more involved: mean of a running quantity, total, is taken, with respect to another running quantit...
8
8
62,152,885
2020-6-2
https://stackoverflow.com/questions/62152885/pydantic-basemodel-not-found-in-fastapi
I have python3 3.6.9 on Kubuntu 18.04. I have installed fastapi using pip3 install fastapi. I'm trying to test drive the framework through its official documentation and I'm in the relational database section of its guide. In schemas.py: from typing import List from pydantic import BaseModel class VerseBase(BaseModel):...
The problem of highlighting in VS code may be a problem due to the fact that you did not open the folder. It's quite annoying as it happens often to me as well (and I have basically your same config). Regarding the second problem you mention, it is probably due to the fact that the folder in which the script lays, does...
15
2
62,158,664
2020-6-2
https://stackoverflow.com/questions/62158664/search-in-each-of-the-s3-bucket-and-see-if-the-given-folder-exists
I'm trying to get the files from specific folders in s3 Buckets: I have 4 buckets in s3 with the following names: 1 - 'PDF' 2 - 'TXT' 3 - 'PNG' 4 - 'JPG' The folder structure for all s3 buckets looks like this: 1- PDF/analysis/pdf-to-img/processed/files 2- TXT/report/processed/files 3- PNG/analysis/reports/png-to-txt/...
This is maybe a lengthy process. buckets = ['PDF','TXT','PNG','JPG'] s3_client = getclient('s3') for i in buckets: result = s3_client.list_objects(Bucket= i, Prefix='', Delimiter ='') contents = result.get('Contents') for content in contents: if 'processed/files/' in content.get('Key'): print("Do the process") You ca...
7
5
62,155,465
2020-6-2
https://stackoverflow.com/questions/62155465/sessionnotcreatedexception-this-version-of-chromedriver-only-supports-chrome-ve
I am using python 3 on windows 7, selenium, chromedriver version 84 (latest) to automate my chrome browser. I am using this script: from selenium import webdriver #import chromedriver_binary # Adds chromedriver binary to path driver = webdriver.Chrome() driver.get("http://www.python.org") and I always get this error...
Your ChromeDriver version and your installed version of Chrome need to match up. You are using ChromeDriver for Chrome version 84, which at the time of this answer, is a beta (non-stable) build of Chrome; you're probably not using it. Likely you're on version 83. Check your Chrome version (Help -> About) and then find ...
13
10
62,152,591
2020-6-2
https://stackoverflow.com/questions/62152591/bug-in-numpy-ndarray-min-max-method
I'm assuming I'm doing something wrong here, but I'm working on a project in Pycharm, which notified me when using the ndarray.max() function that initial was undefined (parameter 'initial' unfilled). Looking at the documentation, it does show that there is no default value for initial argument. When ctrl-clicking the ...
it appears empty because it's not implemented in python, probably C/C++, as you can figure out from # real signature unknown; NOTE: unreliably restored from __doc__ - it's just a hint for you what parameter this function has. It's not even valid python ;) Basing on documentation of amax: initial scalar, optional The ...
12
2
62,102,912
2020-5-30
https://stackoverflow.com/questions/62102912/shape-mismatch-problem-in-tensorflow-2-2-training-using-yolo4-cfg
I recently added a new feature to my yolov3 implementation which is models are currently loaded directly from DarkNet cfg files for convenience, I tested the code with yolov3 configuration as well as yolov4 configuration they both work just fine except for v4 training. Shortly after I start training I get a shapes mism...
Adding this line in models.py solved the shapes problem and the training started as expected: if '4' in self.model_configuration: self.output_layers.reverse()
7
3
62,150,925
2020-6-2
https://stackoverflow.com/questions/62150925/how-do-i-update-values-without-refreshing-the-page-on-my-flask-project
I have a website that shows the prices of items in a video game. Currently, I have an "auto-refresh" script that refreshes the page every 5 seconds, but it is a bit annoying as every time you search for a product, it removes your search because the page refreshes. I would like to update the numbers in my table without ...
You have 3 options: AJAX - https://www.w3schools.com/js/js_ajax_intro.asp SSE - https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events Websocket - https://developer.mozilla.org/en-US/docs/Glossary/WebSockets I think the best option in your case is SSE since the server knows that ...
9
13
62,061,703
2020-5-28
https://stackoverflow.com/questions/62061703/runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modi
I am using pytorch-1.5 to do some gan test. My code is very simple gan code which just fit the sin(x) function: import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt # Hyper Parameters BATCH_SIZE = 64 LR_G = 0.0001 LR_D = 0.0001 N_IDEAS = 5 ART_COMPONENTS = 15 PAINT_POINTS = np.vstack([n...
This happens because the opt_D.step() modifies the parameters of your discriminator inplace. But these parameters are required to compute the gradient for the generator. You can fix this by changing your code to: for step in range(10000): artist_paintings = artist_works() # real painting from artist G_ideas = torch.ran...
11
11
62,139,040
2020-6-1
https://stackoverflow.com/questions/62139040/pythons-csv-module-vs-pandas
I am using Pandas to read CSV file data, but the CSV module is also there to manage the CSV file. What is the difference between these both? What are the cons of using Pandas over the CSV module?
Based upon benchmarks CSV is faster to load data for smaller datasets (< 1K rows) Pandas is several times faster for larger datasets Code to Generate Benchmarks Benchmarks
19
12
62,135,100
2020-6-1
https://stackoverflow.com/questions/62135100/how-to-define-a-pytest-fixture-to-be-used-by-all-tests-within-a-given-tests-subd
Given a directory tests with a few subdirectories each containing test modules, how can one create a pytest fixture to be run before each test found in a particular subdirectory only? tests ├── __init__.py ├── subdirXX │ ├── test_module1.py │ ├── test_module2.py │ ├── __init__.py ├── subdirYY │ ├── test_module3.py │ ├─...
Put your autouse fixture in a conftest.py file inside subdirYY. For more information, see the pytest docs about sharing fixtures and the docs on autouse fixtures which specifically mention conftest.py: if an autouse fixture is defined in a conftest.py file then all tests in all test modules belows its directory will i...
9
7
62,102,897
2020-5-30
https://stackoverflow.com/questions/62102897/certifacte-verify-failed-certificate-has-expired-ssl-c1108
When trying to run my Discord bot I get this error: raise ClientConnectorCertificateError( aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discordapp.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_s...
To fix this: Go to discord.com with Internet Explorer (Ran as Administrator) Click the lock on the top right Click view certificates Install one PS: If your antivirus is active for the web browser and this solution doesn't work, try disabling it and try again.
19
21
62,100,772
2020-5-30
https://stackoverflow.com/questions/62100772/can-you-make-python3-give-an-error-when-comparing-strings-to-bytes
When converting code from Python 2 to Python 3 one issue is that the behaviour when testing strings and bytes for equality has changed. For example: foo = b'foo' if foo == 'foo': print("They match!") prints nothing on Python 3 and "They match!" on Python 2. In this case it is easy to spot but in many cases the check i...
There is an option, -b, you can pass to the Python interpreter to cause it to emit a warning or error when comparing byte / str. > python --help usage: /bin/python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_ins...
7
6
62,121,832
2020-5-31
https://stackoverflow.com/questions/62121832/is-there-a-way-to-add-a-column-of-type-dictionary-to-a-spark-dataframe-in-pyspar
This is how I create a dataframe with primitive data types in pyspark: from pyspark.sql.types import StructType, StructField, DoubleType, StringType, IntegerType fields = [StructField('column1', IntegerType(), True), StructField('column2', IntegerType(), True)] schema = StructType(fields) df = spark.createDataFrame([],...
Example how to create: from pyspark.sql.types import MapType, IntegerType, DoubleType, StringType, StructType, StructField import pyspark.sql.functions as f schema = StructType([ StructField('column1', IntegerType()), StructField('column2', IntegerType()), StructField('column3', MapType(StringType(), DoubleType()))]) d...
8
5
62,110,746
2020-5-31
https://stackoverflow.com/questions/62110746/is-there-a-better-way-to-check-if-a-number-is-range-of-two-numbers
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this: def checkRange(number): if number in range(0, 5499): return 5000 elif number in range(5500, 9499): return 10000 elif number in range(9500...
Since you have continuous, sorted ranges, a quicker and less verbose way to do this, is to use the bisect module to find the index in a list of breakpoints and then use it to get the corresponding value from a list of values: import bisect break_points = [5499, 9499, 14499, 19499, 24499, 29499, 34499, 39499, 44499] val...
18
27
62,113,587
2020-5-31
https://stackoverflow.com/questions/62113587/adding-claims-to-drf-simple-jwt-payload
Using djangorestframework_simplejwt library, when POST to a custom view #urls.py path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'), #views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer I'm able to get a the following access token eyJ0eXAiOiJK...
As you already created a subclass for the desired view (MyTokenObtainPairView) and a subclass for its corresponding serializer (MyTokenObtainPairSerializer), add the following to the serializer class MyTokenObtainPairSerializer(TokenObtainPairSerializer): ... @classmethod def get_token(cls, user): token = super().get_t...
10
15
62,102,453
2020-5-30
https://stackoverflow.com/questions/62102453/how-to-define-callbacks-in-separate-files-plotly-dash
Background Dash web applications have a dash application instance, usually named app, and initiated like this: app = dash.Dash(__name__) Then, callbacks are added to the application using a callback decorator: @app.callback(...) def my_function(...): # do stuff. In most of the tutorials you find, the callbacks are de...
I don't think (but I might be wrong) that there's a correct way of doing it per se, but what you could do it have a central module (maindash.py) around your startup code app = dash.Dash(__name__), and have different callbacks simply import app from my_dash_app.maindash. This would set up the callbacks in their own sepa...
38
21
62,102,618
2020-5-30
https://stackoverflow.com/questions/62102618/sum-values-in-a-list-of-lists-of-dictionaries-using-common-key-value-pairs
How do I sum duplicate elements in a list of lists of dictionaries? Sample list: data = [ [ {'user': 1, 'rating': 0}, {'user': 2, 'rating': 10}, {'user': 1, 'rating': 20}, {'user': 3, 'rating': 10} ], [ {'user': 4, 'rating': 4}, {'user': 2, 'rating': 80}, {'user': 1, 'rating': 20}, {'user': 1, 'rating': 10} ], ] Expec...
You can try: from itertools import groupby result = [] for lst in data: sublist = sorted(lst, key=lambda d: d['user']) grouped = groupby(sublist, key=lambda d: d['user']) result.append([ {'user': name, 'rating': sum([d['rating'] for d in group])} for name, group in grouped]) # Sort the `result` `rating` wise: result = ...
10
4
62,100,550
2020-5-30
https://stackoverflow.com/questions/62100550/django-importerror-cannot-import-name-reporterprofile-from-partially-initiali
I have two apps: collection and accounts, with both having models defined. I'm importing a model ReporterProfile from accounts to collection. Similarly, I'm importing a model Report from collection to accounts. The Report model from collection is called in a model class method in accounts like this: from collection.mod...
For ForeignKey: Instead of using reporterprofile = models.ForeignKey(ReporterProfile, ...), you can use reporterprofile = models.ForeignKey("accounts.ReporterProfile", ...), so you don't have to import the model. For preventing circulor import error : Instead of using : from accounts.models import ReporterProfile [...]...
17
43
62,095,847
2020-5-29
https://stackoverflow.com/questions/62095847/pandas-groupby-concat-ungrouped-column-into-comma-separated-string
I have the following example df: col1 col2 col3 doc_no 0 a x f 0 1 a x f 1 2 b x g 2 3 b y g 3 4 c x t 3 5 c y t 4 6 a x f 5 7 d x t 5 8 d x t 6 I want to group by the first 3 columns (col1, col2, col3), concatenate the fourth column (doc_no) into a line of strings based on the groupings of the first 3 columns, as we...
Try groupby and agg like so: (df.groupby(['col1', 'col2', 'col3'])['doc_no'] .agg(['count', ('doc_no', lambda x: ','.join(map(str, x)))]) .sort_values('count', ascending=False) .reset_index()) col1 col2 col3 count doc_no 0 a x f 3 0,1,5 1 d x t 2 5,6 2 b x g 1 2 3 b y g 1 3 4 c x t 1 3 5 c y t 1 4 agg is simple to use...
7
10
62,090,541
2020-5-29
https://stackoverflow.com/questions/62090541/how-to-iterate-over-all-values-of-an-enum-including-any-nested-enums
Imagine one has two classes derived from Enum, e.g. class Color(Enum): blue = 'blue' red = 'red' class Properties(Enum): height = 'h' weight = 'w' colors = Color What is the best way to (probably recursively) iterate over all Enum-labels of a nested Enum like Properties, including the ones of Enum-members like Propert...
Here's a quick example that just prints them out. I'll leave it as an exercise to the reader to make this a generic generator or whatever applies to the actual use case. :) >>> from typing import Type >>> def print_enum(e: Type[Enum]) -> None: ... for p in e: ... try: ... assert(issubclass(p.value, Enum)) ... print_enu...
10
5
62,087,499
2020-5-29
https://stackoverflow.com/questions/62087499/failing-to-install-mysql-python
I am tying to install MySQL-python in a python 2.7 virtual environment but I am getting the following error: Installing collected packages: MySQL-python Running setup.py install for MySQL-python ... error ERROR: Command errored out with exit status 1: command: /home/jhylands/py2/bin/python -u -c 'import sys, setuptools...
So I managed to solve the issue with the following command: sudo wget https://raw.githubusercontent.com/paulfitz/mysql-connector-c/master/include/my_config.h -P /usr/include/mysql/ Which I found from a comment on this answer.
9
16
62,086,686
2020-5-29
https://stackoverflow.com/questions/62086686/how-to-extract-values-from-pandas-series-without-index
I have the following when I print my data structure: print(speed_tf) 44.0 -24.4 45.0 -12.2 46.0 -12.2 47.0 -12.2 48.0 -12.2 Name: Speed, dtype: float64 I believe this is a pandas Series but not sure I do not want the first column at all I just want -24.4 -12.2 -12.2 -12.2 -12.2 I tried speed_tf.reset_index() index ...
speed_tf.values Should do what you want.
23
33
62,078,016
2020-5-29
https://stackoverflow.com/questions/62078016/smooth-the-edges-of-binary-images-face-using-python-and-open-cv
I am looking for a perfect way to smooth edges of binary images. The problem is the binary image appears to be a staircase like borders which is very unpleasing for my further masking process. I am attaching a raw binary image that is to be converted into smooth edges and I am also providing the expected outcome. I am...
You can do that in Python/OpenCV with the help of Skimage by blurring the binary image. Then apply a one-sided clip. Input: import cv2 import numpy as np import skimage.exposure # load image img = cv2.imread('bw_image.png') # blur threshold image blur = cv2.GaussianBlur(img, (0,0), sigmaX=3, sigmaY=3, borderType = cv2...
9
8
62,074,633
2020-5-28
https://stackoverflow.com/questions/62074633/how-to-increase-the-memory-limits-in-google-cloud-run
I'm building a simple Flask based app using Cloud Run + Cloud Firestore. There is one method that brings a lot of data, and the logs are showing this error: `Memory limit of 244M exceeded with 248M used. Consider increasing the memory limit, see https://cloud.google.com/run/docs/configuring/memory-limits` How I can in...
In the args of the last step, add '--memory', '512Mi' The format for size is a fixed or floating point number followed by a unit: G, M, or K corresponding to gigabyte, megabyte, or kilobyte, respectively, or use the power-of-two equivalents: Gi, Mi, Ki corresponding to gibibyte, mebibyte or kibibyte respectively.
7
15
62,068,323
2020-5-28
https://stackoverflow.com/questions/62068323/iterating-over-tf-tensor-is-not-allowed-autograph-is-disabled-in-this-function
I am using tensorflow 2.1 along with python 3.7 The following snippet of code is being used to build a tensorflow graph. The code runs without errors when executed as a standalone python script. (Probably tensorflow is running in eager mode? I am not sure.) import tensorflow as tf patches = tf.random.uniform(shape=(1,...
List comprehensions are not yet supported in autograph. The error that's raised needs to be improved, too. Piling up on https://github.com/tensorflow/tensorflow/issues/32546 should help resolve it sooner. Until comprehensions are supported, you have to use map_fn, which in this case would look something like this: def ...
16
21
62,066,599
2020-5-28
https://stackoverflow.com/questions/62066599/how-to-get-the-pid-of-the-process-started-by-subprocess-run-and-kill-it
I'm using Windows 10 and Python 3.7. I ran the following command. import subprocess exeFilePath = "C:/Users/test/test.exe" subprocess.run(exeFilePath) The .exe file launched with this command, I want to force-quit when the button is clicked or when the function is executed. Looking at a past question, it has been indi...
Assign a variable to your subprocess import os import signal import subprocess exeFilePath = "C:/Users/test/test.exe" p = subprocess.Popen(exeFilePath) print(p.pid) # the pid os.kill(p.pid, signal.SIGTERM) #or signal.SIGKILL In same cases the process has children processes. You need to kill all processes to terminate ...
7
7
62,041,999
2020-5-27
https://stackoverflow.com/questions/62041999/where-to-set-n-job-estimator-or-gridsearchcv
I often use GridSearchCV for hyperparameter tuning. For example, for tuning regularization parameter C in Logistic Regression. Whenever an estimator I am using has its own n_jobs parameter I am confused where to set it, in estimator or in GridSearchCV, or in both? Same thing applies to cross_validate.
This is a very interesting question. I don't have a definitive answer, but some elements that are worth mentioning to understand the issue, and don't fir in a comment. Let's start with why you should or should not use multiprocessing : Multiprocessing is useful for independent tasks. This is the case in a GridSearch,...
9
7
62,059,196
2020-5-28
https://stackoverflow.com/questions/62059196/gensim-fasttext-why-load-facebook-vectors-doesnt-work
I've tried to load pre-trained FastText vectors from fastext - wiki word vectors. My code is below, and it works well. from gensim.models import FastText model = FastText.load_fasttext_format('./wiki.en/wiki.en.bin') but, the warning message is a little annoying. gensim_fasttext_pretrained_vector.py:13: DeprecationW...
You're almost there, you need to change two things: First of all, it's fasttext all lowercase letters, not Fasttext. Second of all, to use load_facebook_vectors, you need first to create a datapath object before using it. So, you should do like so: from gensim.models import fasttext from gensim.test.utils import data...
8
7
62,060,079
2020-5-28
https://stackoverflow.com/questions/62060079/how-to-solve-package-conflict-on-conda
I want to use Conda to create a virtual environment from a YAML file. However, many packages end up with a Conflict error. The best way to solve this is to install each package individually instead of creating a virtual environment from a YAML file, right? If anyone knows of a better way to do it, please let me know.
Use conda-forge which has a strong dependency resolution implementation. Newer conda versions (>=4.6) introduced a strict channel priority feature. Type conda config --describe channel_priority for more information. The solution is to add the conda-forge channel on top of defaults in your .condarc file when using cond...
8
3
62,042,172
2020-5-27
https://stackoverflow.com/questions/62042172/how-to-remove-noise-in-image-opencv-python
I have some cropped images and I need images that have black texts on white background. Firstly I apply adaptive thresholding and then I try to remove noise. Although I tried a lot of noise removal techniques but when the image changed, the techniques I used failed. The best method for converting image color to binary...
Before binarization, it is necessary to correct the nonuniform illumination of the background. For example, like this: import cv2 image = cv2.imread('9qBsB.jpg') image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) se=cv2.getStructuringElement(cv2.MORPH_RECT , (8,8)) bg=cv2.morphologyEx(image, cv2.MORPH_DILATE, se) out_gray=cv...
11
22
62,048,408
2020-5-27
https://stackoverflow.com/questions/62048408/how-to-remove-progressbar-in-tqdm-once-the-iteration-is-complete
How can I archive this? from tqdm import tqdm for link in tqdm(links): try: #Do Some Stff except: pass print("Done:") Result: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 111.5...
tqdm actually takes several arguments, one of them is leave, which according to the docs: If [default: True], keeps all traces of the progressbar upon termination of iteration. If None, will leave only if position is 0 So: >>> for _ in tqdm(range(2)): ... time.sleep(1) ... 100%|███████████████████████████████████████...
33
53
62,039,535
2020-5-27
https://stackoverflow.com/questions/62039535/extract-images-from-excel-file-with-python
I have an Excel sheet with 100 rows. Each one has various informations, including an id, and a cell containing a photo. I use pandas to load the data into dictionaries : import pandas as pd df = pd.read_excel('myfile.xlsx') data = [] for index,row in df.iterrows(): data.append({ 'id':row['id'], 'field2':row['field2'], ...
I found a solution using openpyxl and openpyxl-image-loader modules # installing the modules pip3 install openpyxl pip3 install openpyxl-image-loader Then, in the script : #Importing the modules import openpyxl from openpyxl_image_loader import SheetImageLoader #loading the Excel File and the sheet pxl_doc = openpyxl....
8
31
61,974,312
2020-5-23
https://stackoverflow.com/questions/61974312/is-python-memory-safe
With Deno being the new Node.js rival and all, the memory-safe nature of Rust has been mentioned in a lot of news articles, one particular piece stated Rust and Go are good for their memory-safe nature, as are Swift and Kotlin but the latter two are not used for systems programming that widely. Safe Rust is the true R...
Wikipedia lists the following examples of memory safety issues: Access errors: invalid read/write of a pointer Buffer overflow - out-of-bound writes can corrupt the content of adjacent objects, or internal data (like bookkeeping information for the heap) or return addresses. Buffer over-read - out-of-bound reads can ...
15
11
62,025,723
2020-5-26
https://stackoverflow.com/questions/62025723/how-to-validate-a-pydantic-object-after-editing-it
Is there any obvious way to validate a pydantic model after changing some attribute? Say I create a simple Model and object: from pydantic import BaseModel class A(BaseModel): b: int = 0 a=A() Then edit it, so that it is actually invalid: a.b = "foobar" Can I force a re-validation and expect a ValidationError to be r...
pydantic can do this for you, you just need validate_assignment: from pydantic import BaseModel class A(BaseModel): b: int = 0 class Config: validate_assignment = True
24
29
61,981,156
2020-5-24
https://stackoverflow.com/questions/61981156/unable-to-locate-package-python-pip-ubuntu-20-04
I am trying to install mininet-wifi. After downloading it, I have been using the following command to install it: sudo util/install.sh -Wlnfv However, I keep getting the error: E: Unable to locate package python-pip I have tried multiple times to download python-pip. I know mininet-wifi utilizes python 2 instead of...
Pip for Python 2 is not included in the Ubuntu 20.04 repositories. You need to install pip for Python 2 using the get-pip.py script. 1. Start by enabling the universe repository: sudo add-apt-repository universe 2. Update the packages index and install Python 2: sudo apt update sudo apt install python2 3. Use curl ...
33
69
61,948,723
2020-5-22
https://stackoverflow.com/questions/61948723/how-to-extend-a-pydantic-object-and-change-some-fields-type
There are two similar pydantic object like that. The only difference is some fields are optionally. How can I just define the fields in one object and extend into another one? class ProjectCreateObject(BaseModel): project_id: str project_name: str project_type: ProjectTypeEnum depot: str system: str ... class ProjectPa...
I find a good and easy way by __init__subclass__. The docs also can be generated successfully. class ProjectCreateObject(BaseModel): project_id: str project_name: str project_type: ProjectTypeEnum depot: str system: str ... def __init_subclass__(cls, optional_fields=(), **kwargs): """ allow some fields of subclass turn...
11
6
61,937,520
2020-5-21
https://stackoverflow.com/questions/61937520/proper-way-to-create-class-variable-in-data-class
I've just begun playing around with Python's Data Classes, and I would like confirm that I am declaring Class Variables in the proper way. Using regular python classes class Employee: raise_amount = .05 def __init__(self, fname, lname, pay): self.fname = fname self.lname = lname self.pay = pay Using python Data Class...
To create a class variable, annotate the field as a typing.ClassVar or not at all. from typing import ClassVar from dataclasses import dataclass @dataclass class Foo: ivar: float = 0.5 cvar: ClassVar[float] = 0.5 nvar = 0.5 foo = Foo() Foo.ivar, Foo.cvar, Foo.nvar = 1, 1, 1 print(Foo().ivar, Foo().cvar, Foo().nvar) # 0...
90
131
61,927,877
2020-5-21
https://stackoverflow.com/questions/61927877/how-to-crop-opencv-image-from-center
How can I crop an image using OpenCV from the center? I think it has something to do with this line, but if there is a better way please inform me. crop_img = img[y:y+h, x:x+w]
Just an additional comment for the Lenik's answer (It is the first time I want to contribute in StackOverflow and don't have enough reputation to comment the answer), you need to be sure x and y are integers. Probably in this case x and y would always be integers as most of resolutions are even, but is a good practice ...
10
14
61,913,632
2020-5-20
https://stackoverflow.com/questions/61913632/python-convert-string-type-to-datetime-type
I have a two variables that i want to compare. When printed, this is what they look like: 2020-05-20 13:01:30 2020-05-20 14:49:03 However, one is a string type, and the other a datetime type. If I want to convert the string one into date type so I can compare them, is the only way to use strptime? Because this seems a...
If you work with Python 3.7+, for ISO 8601 compatible strings, use datetime.fromisoformat() as this is considerably more efficient than strptime or dateutil's parser. Ex: from datetime import datetime dtobj = datetime.fromisoformat('2020-05-20 13:01:30') print(repr(dtobj)) # datetime.datetime(2020, 5, 20, 13, 1, 30) Y...
12
11
61,978,049
2020-5-23
https://stackoverflow.com/questions/61978049/reverse-search-an-image-in-yandex-images-using-python
I'm interested in automatizing reverse image search. Yandex in particular is great for busting catfishes, even better than Google Images. So, consider this Python code: import requests import webbrowser try: filePath = "C:\\path\\whateverThisIs.png" searchUrl = 'https://yandex.ru/images/' multipart = {'encoded_image': ...
You can get url with an image search by using this code. Tested on ubuntu 18.04, with python 3.7 and requests 2.23.0 import json import requests file_path = "C:\\path\\whateverThisIs.png" search_url = 'https://yandex.ru/images/search' files = {'upfile': ('blob', open(file_path, 'rb'), 'image/jpeg')} params = {'rpt': 'i...
11
17
61,976,560
2020-5-23
https://stackoverflow.com/questions/61976560/how-to-delete-queue-updates-in-telegram-api
I'm trying to delete messages from /getUpdates in telegram API but I didn't know how.. I tried to use /deleteMessage https://api.telegram.org/bot<TOKEN>/deleteMessage?chat_id=blahblah&message_id=BlahBlah But it didn't delete message from API database..
TL;DR: Call getUpdates() with the offset parameter set to the last message's id, incremented by 1 We'll need to let Telegram know which message's we've processed. To do this, set the offset parameter to the update_id + 1 of the last message your script has processed. Call getUpdates() to get the update_id of the late...
10
13
61,947,044
2020-5-22
https://stackoverflow.com/questions/61947044/keyring-warning-when-running-pip-list-o
I've been trying to run pip list -o and pip list --outdated to see if any packages need to be updated but it enters a loop of printing: WARNING: Keyring is skipped due to an exception: Failed to create the collection: Prompt dismissed.. I've upgraded keyring and the version was already up-to-date. I've seen this keyrin...
I searched the web about that topic and find that GitHub issue. If your pip version is any version before "21.1", you can try to upgrade pip to the latest version with pip install --upgrade pip command. Also, as a workaround, you can consider the following answer of jrd from the above link: Exporting PYTHON_KEYRING_BA...
18
11
61,924,233
2020-5-20
https://stackoverflow.com/questions/61924233/the-from-address-does-not-match-a-verified-sender-identity-mail-cannot-be-sent
I follow this link: https://sendgrid.com/docs/ui/sending-email/sender-verification In my sendgrid account the from_email is set as verifie Single sender authentication, but when i send email verifications in my localhost, i still receive the same message : The from address does not match a verified Sender Identity my c...
You need to add another line to your config containing the verified sender's address: DEFAULT_FROM_EMAIL = 'you@domain.com'
9
7
61,943,545
2020-5-21
https://stackoverflow.com/questions/61943545/python-get-keys-from-unbound-typeddict
I would like to get the keys from an unbound TypedDict subclass. What is the correct way to do so? Below I have a hacky method, and I'm wondering if there's a more standard way. Current Method I used inspect.getmembers on the TypedDict subclass, and saw the __annotations__ attribute houses a mapping of the keys + type...
The code documentation explicitly states (referring to a sample derived class Point2D): The type info can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. So if the modules code says this, there is no reason to look for another method. Note ...
16
21
61,951,026
2020-5-22
https://stackoverflow.com/questions/61951026/pygame-drawing-a-border-of-a-rectangle
I am creating a 3d pong game using pygame. I wanted to add a thick black border layer to the rectangle to make it more stylish. Here's what I tried: pygame.draw.rect(screen, (0,0,255), (x,y,150,150), 0) pygame.draw.rect(screen, (0,0,0), (x-1,y-1,155,155), 1) pygame.draw.rect(screen, (0,0,0), (x-2,y-2,155,155), 1) pygam...
You could also put it in a function, and make it more concise with for loops. First, you'll note that the four rectangles you drew were in a nice, easy pattern, so you could compact the drawing of the four rectangles like this: pygame.draw.rect(surface, (0,0,255), (x,y,150,150), 0) for i in range(4): pygame.draw.rect(s...
7
5
61,922,334
2020-5-20
https://stackoverflow.com/questions/61922334/how-to-solve-attributeerror-module-google-protobuf-descriptor-has-no-attribu
I encountered it while executing from object_detection.utils import label_map_util in jupyter notebook. It is actually the tensorflow object detection tutorial notebook(it comes with the tensorflow object detection api) The complete error log: AttributeError Traceback (most recent call last) <ipython-input-7-7035655b94...
The protoc version I got through pip show protobuf and protoc --version were different. The version in pip was a bit outdated. After I upgraded the pip version with pip install --upgrade protobuf the problem was solved.
104
199
61,908,834
2020-5-20
https://stackoverflow.com/questions/61908834/creating-virtual-environment-using-python-3-8-when-python-2-7-is-present
I am trying to create a virtual environment using mkvirtualenv with python 3 in Windows but the environment is created with python 2.7.My pip version is also from python 2.7 which i have avoided using py -m pip install virtualenvwrapper-win When i do mkvirtualenv test environment is created with python 2.7 Please he...
If you would like to create a virtualenv with python 3.X having the version 2.X You just have to pass a parameter argument for your virtual env. $ virtualenv venv -p $(which python3) This command will point to your current python3 install folder, and create a virtualenv copied from your current python3 binaries. If yo...
17
28
62,012,194
2020-5-25
https://stackoverflow.com/questions/62012194/how-to-make-a-line-plot-from-a-pandas-dataframe-with-a-long-or-wide-format
(This is a self-answered post to help others shorten their answers to plotly questions by not having to explain how plotly best handles data of long and wide format) I'd like to build a plotly figure based on a pandas dataframe in as few lines as possible. I know you can do that using plotly.express, but this fails fo...
Here you've tried to use a pandas dataframe of a wide format as a source for px.line. And plotly.express is designed to be used with dataframes of a long format, often referred to as tidy data (and please take a look at that. No one explains it better that Wickham). Many, particularly those injured by years of battling...
12
33
61,986,052
2020-5-24
https://stackoverflow.com/questions/61986052/visual-studio-code-terminal-doesnt-activate-conda-environment
I read this Stack Overflow post on a similar issue, but the suggestions there don't seem to be working. I installed Visual Studio Code on my Windows machine and added the Python extension. Then I changed the Python path for my project to C:\Users\username\.conda\envs\tom\python.exe. The .vscode/settings.json has this i...
First, open the Anaconda prompt (How to access Anaconda command prompt in Windows 10 (64-bit)), and type: conda activate tom To activate your virtual environment. Then to open Visual Studio Code in this active environment, type code And it should work.
57
52
61,913,882
2020-5-20
https://stackoverflow.com/questions/61913882/importerror-cannot-import-name-tablelist-from-camelot-core
i tried to extract the tables from a pdf using camelot but it is showing this error message! import camelot tables = camelot.read_pdf("C:/Users/shres/Desktop/PY/Arun District Council_ASR-2019.pdf", pages='all') tables tables.export("test.csv", f='csv') tables[0] tables[0].parsing_report { 'accuracy' : 99.02, 'whitespa...
you might want to reinstall it. Camelot and camelot-py are two different packages but they have the same import name. pip uninstall camelot pip uninstall camelot-py pip install camelot-py[cv]
15
29
62,008,457
2020-5-25
https://stackoverflow.com/questions/62008457/overlap-between-mask-and-fired-beams-in-pygame-ai-car-model-vision
I try to implement beam collision detection with a predefined track mask in Pygame. My final goal is to give an AI car model vision to see a track it's riding on: This is my current code where I fire beams to mask and try to find an overlap: import math import sys import pygame as pg RED = (255, 0, 0) GREEN = (0, 255,...
Your approach works fine, if the x and y component of the ray axis points in the positive direction, but it fails if it points in the negative direction. As you pointed out, that is caused by the way pygame.mask.Mask.overlap works: Starting at the top left corner it checks bits 0 to W - 1 of the first row ((0, 0) to (...
7
9
61,968,794
2020-5-23
https://stackoverflow.com/questions/61968794/what-is-the-best-practice-for-keeping-kafka-consumer-alive-in-python
Something is puzzling for me when it comes to keeping consumers alive. Let's say I have a topic to which data is constantly being written. But, in an hour in a day, there are no new messages. If I had set a timeout for my consumers, when there are no new messages, the consumer will get closed. Now, new messages arrive....
Why not just import time from confluent_kafka import Consumer consumer = Consumer({ 'bootstrap.servers': 'localhost:9092', 'group.id': 'my-consumer-1', 'auto.offset.reset': 'earliest' }) consumer.subscribe(['topicName']) while True: try: message = consumer.poll(10.0) if not message: time.sleep(120) # Sleep for 2 minute...
11
3
62,010,434
2020-5-25
https://stackoverflow.com/questions/62010434/how-do-i-get-the-snake-to-grow-and-chain-the-movement-of-the-snakes-body
I want to implement a snake game. The snake meanders through the playground. Every time when the snake eats some food, the length of the snake increase by one element. The elements of the snakes body follow its head like a chain. snake_x, snake_y = WIDTH//2, HEIGHT//2 body = [] move_x, move_y = (1, 0) food_x, food_y = ...
In general you have to distinguish between 2 different types of snake. In the first case, the snake moves in a grid and every time when the snake moves, it strides ahead one field in the grid. In the other type, the snakes position is not in a raster and not snapped on the fields of the grid, the position is free and t...
7
19
61,921,935
2020-5-20
https://stackoverflow.com/questions/61921935/aws-lambda-failed-to-find-libmagic
I'm using in my lambda function the magic library to determine the file`s type. I first deployed it to a local container to check that everything works. My DockerFile : FROM lambci/lambda:build-python3.8 WORKDIR /app RUN mkdir -p .aws COPY requirements.txt ./ COPY credentials /app/.aws/ RUN mv /app/.aws/ ~/.aws/ RUN p...
While using filetype as suggested by other answers is much simpler, that library does not detect as many file types as magic does. You can make python-magic work on aws lambda with python3.8 by doing the following: Add libmagic.so.1 to a lib folder at the root of the lambda package. This lib folder will be automatical...
8
11
61,986,490
2020-5-24
https://stackoverflow.com/questions/61986490/what-does-librosa-load-return
I'm working with the librosa library, and I would like to know what information is returned by the librosa.load function when I read a audio (.wav) file. Is it the instantaneous sound pressure in pa, or the just the instantaneous amplitude of the sound signal with no units?
To confirm the previous answer, librosa.load returns a time series that in librosa glossary is defined as: "time series: Typically an audio signal, denoted by y, and represented as a one-dimensional numpy.ndarray of floating-point values. y[t] corresponds to the amplitude of the waveform at sample t." The amplitude is ...
8
10
61,919,670
2020-5-20
https://stackoverflow.com/questions/61919670/how-nltk-tweettokenizer-different-from-nltk-word-tokenize
I am unable to understand the difference between the two. Though, I come to know that word_tokenize uses Penn-Treebank for tokenization purposes. But nothing on TweetTokenizer is available. For which sort of data should I be using TweetTokenizer over word_tokenize?
Well, both tokenizers almost work the same way, to split a given sentence into words. But you can think of TweetTokenizer as a subset of word_tokenize. TweetTokenizer keeps hashtags intact while word_tokenize doesn't. I hope the below example will clear all your doubts... from nltk.tokenize import TweetTokenizer from n...
11
23
62,010,704
2020-5-25
https://stackoverflow.com/questions/62010704/how-can-i-make-my-bullets-look-like-they-are-comming-out-of-my-guns-tip
I am having an issue where my bullets dont look like they are coming out of my gun they look like they are coming out of the players body VIDEO as you can see in the video it shoots somewhere else or its the gun its the same thing for the left side it shoots good going up but it shoots bad going down VIDEO I tried ang...
It looks to me as if your bullets are originating at the players coordinates and not at the edge of the gun. You probably need to apply the same offset you used for the gun, to the projectile origin. Or just extract the top right and bottom right coordinates of the gun after rotation and set the projectiles origin to e...
8
10
61,980,300
2020-5-24
https://stackoverflow.com/questions/61980300/changing-in-the-quantity-of-variants-reflecting-in-the-wrong-item-in-order-summa
I have a problem with the variations and the quantity related to it in the order summary page. It was working perfectly and all of a sudden (this is an example to simplify): when I add to the cart 2 items: Item X with a size small Item X with a size medium When I change the quantity of item X size medium, this change...
I checked your code. In your code, you are fetching items and then changing the quantity. Item X with larger size and Item X with a smaller size, I feel both are representing the same item. So changing in 1 item will reflect in same item with different sizes. Do you have any way to identify an item based on item_id as ...
7
5
62,026,559
2020-5-26
https://stackoverflow.com/questions/62026559/use-dictionary-data-to-append-data-to-pandas-dataframe
I have a dataframe and 2 separate dictionaries. Both dictionaries have the same keys but have different values. dict_1 has key-value pairs where the values are unique ids that correspond with the dataframe df. I want to be able to use the 2 dictionaries and the unique ids from the dict_1 to append the values of dict_2 ...
IIUC, the keys in your two dictionaries are aligned. One way is to create a dataframe with a column id containing the values in dict_1 and 2 (in this case but can be more) columns from the values in dict_2 aligned on the same key. Then use merge on id to get the result back in df # the two dictionaries. note in dict_2 ...
7
6
62,019,960
2020-5-26
https://stackoverflow.com/questions/62019960/difference-between-pass-statement-and-3-dots-in-python
What's the difference between the pass statement: def function(): pass and 3 dots: def function(): ... Which way is better and faster to execute(CPython)?
pass has been in the language for a very long time and is just a no-op. It is designed to explicitly do nothing. ... is a token having the singleton value Ellipsis, similar to how None is a singleton value. Putting ... as your method body has the same effect as for example: def foo(): 1 The ... can be interpreted as a...
71
64
61,977,830
2020-5-23
https://stackoverflow.com/questions/61977830/unsatisfiableerror-conda
I'm trying to create my own anaconda package and after many attempts I've finally managed to create a conda usable package out of my code. (It depends on a package from haasad channel, so it should be installed like this: conda install -c monomonedula sten -c haasad). The problem appear when I'm trying to install a pac...
Offhand i am not sure what the conflict you are seeing, or how to fix your environment, however I am able to install the stellargraph, sten and mono... packages from a fresh, base cloned environment. It may be more useful to build an environment from scratch, for others to use. Here are the commands I used: conda crea...
10
2
61,987,350
2020-5-24
https://stackoverflow.com/questions/61987350/is-finished-with-status-crash-normal-for-cloud-functions
I tried Google Cloud Functions with Python and there was a problem with running it. It said: Error: could not handle the request I checked the logs, but there was no error, just a log message: Function execution took 16 ms, finished with status: 'crash' When I simplified the function to a printout then it worked prope...
Quite rightly, as alluded to in the Comments, the crash seems buggy about Google Cloud Functions with Python. The issue was reported to the Internal Google Cloud Functions engineers and evaluation is still ongoing. You can monitor this link for fixes
13
5
62,019,358
2020-5-26
https://stackoverflow.com/questions/62019358/django-management-command-doesnt-flush-stdout
I'm trying to print to console before and after processing that takes a while in a Django management command, like this: import requests import xmltodict from django.core.management.base import BaseCommand def get_all_routes(): url = 'http://busopen.jeju.go.kr/OpenAPI/service/bis/Bus' r = requests.get(url) data = xmlto...
The thing to keep in mind is you're using self.stdout (as suggested in the Django docs), which is BaseCommand's override of Python's standard sys.stdout. There are two main differences between the 2 relevant to your problem: The default "ending" in BaseCommand's version of self.stdout.write() is a new-line, forcing yo...
8
8
61,997,937
2020-5-25
https://stackoverflow.com/questions/61997937/how-to-solve-type-is-partially-unknown-warning-from-pyright
I'm using strict type checks via pyright. When I have a method that returns a pytorch DataLoader, then pyright complains about my type definition: Declared return type, "DataLoader[Unknown]", is partially unknown Pyright (reportUnknownVariableType) Taking a look at the type stub from pytorch's DataLoader (reduced to ...
Since there was no reply on this question I was not sure if it is actually a bug in pyright. I therefore opened this issue on the github repository: https://github.com/microsoft/pyright/issues/698 Eric Traut explained in detail what the issue is and that pyright is working as designed. I try to give the gist of the mai...
18
20
61,982,672
2020-5-24
https://stackoverflow.com/questions/61982672/cuda-gpu-processing-typeerror-compile-kernel-got-an-unexpected-keyword-argum
Today I started working with CUDA and GPU processing. I found this tutorial: https://www.geeksforgeeks.org/running-python-script-on-gpu/ Unfortunately my first attempt to run gpu code failed: from numba import jit, cuda import numpy as np # to measure exec time from timeit import default_timer as timer # normal functio...
Adding an answer to get this off the unanswered queue. The code in that example is broken. It isn't anything wrong with your numba or CUDA installations. There is no way that the code in your question (or the blog you copied it from) can emit the result the blog post claims. There are many ways this could potentially b...
12
21
62,029,371
2020-5-26
https://stackoverflow.com/questions/62029371/python-poetry-error-setting-settings-virtualenvs-in-project-does-not-exist
I am setting poetry to create virtual environments in the project directory. I entered: poetry config settings.virtualenvs.in-project true and received error [ValueError] Setting settings.virtualenvs.in-project does not exist Also there is the text home/alex/.poetry/lib/poetry/_vendor/py2.7/subprocess32.py:149: R...
The config has changed with the release of poetry 1.0. The prefix settings is no longer needed. So just type poetry config virtualenvs.in-project true. Concerning the subprocess warning: This seems to be just a warning and has no influence on the correct working of poetry. Also have a look at my comment in poetry's iss...
27
50
62,012,775
2020-5-26
https://stackoverflow.com/questions/62012775/how-to-run-different-pytest-arguments-or-marks-from-vs-code-test-runner-interfac
I'm having trouble getting the VS Code PyTest code runner to work the way I'd like. It seems pytest options may be an all-or-nothing situation. Is there any way to run different sets of PyTest options easily in the VS Code interface? For example: By default, run all tests not marked with @pytest.mark.slow. This can b...
You're not missing anything. There currently isn't a way to provide per-execution arguments to get the integration you want with the Test Explorer.
8
7
62,032,115
2020-5-26
https://stackoverflow.com/questions/62032115/removing-python-3-8-entry-in-mac-os-path
PROBLEM DESCRIPTION I'm setting up a new MacBook and decided to jump too fast into downloading Python 3.8. I downloaded it from the website https://www.python.org/ before realizing it's better practice to do so with homebrew. GOAL - Remove Python 3.8 from my PATH to later install with Homebrew I cleared Python 3.8 fro...
Found the solution! Through running grep {subset of the path you're trying to remove} . (don't forget the period at the end), I found all places where that path was found on my computer. That brought me to seeing that the ./.zprofile file was exporting the Python 3.8 path. I removed it from that file, saved it and rest...
7
12
62,000,970
2020-5-25
https://stackoverflow.com/questions/62000970/celery-beat-keyerror-scheduler
I am trying to run a periodic celery task using celery beat and docker for my Flask application. However when I run the container I get the below error: Removing corrupted schedule file 'celerybeat-schedule': error(22, 'Invalid argument') Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/k...
This is weird, I haven't got the solution right now, but I found a way to circumnavigate this. Why we are getting the issue : Here are some thoughts on celery docs which explains what is happening here : Beat needs to store the last run times of the tasks in a local database file (named celerybeat-schedule by default...
7
5
61,974,206
2020-5-23
https://stackoverflow.com/questions/61974206/timeout-within-session-while-sending-requests
I'm trying to learn how I can use timeout within a session while sending requests. The way I've tried below can fetch the content of a webpage but I'm not sure this is the right way as I could not find the usage of timeout in this documentation. import requests link = "https://stackoverflow.com/questions/tagged/web-scr...
I'm not sure this is the right way as I could not find the usage of timeout in this documentation. Scroll to the bottom. It's definitely there. You can search for it in the page by pressing Ctrl+F and entering timeout. You're using timeout correctly in your code example. You can actually specify the timeout in a few ...
16
5
61,989,485
2020-5-24
https://stackoverflow.com/questions/61989485/pre-populate-current-value-of-wtforms-field-in-order-to-edit-it
I have a form inside a modal that I use to edit a review on an item (a perfume). A perfume can have multiple reviews, and the reviews live in an array of nested documents, each one with its own _id. I'm editing each particular review (in case an user wants to edit their review on the perfume once it's been submitted) b...
You can do this with jQuery as when you open the form, the form will automatically show the review content in there. It will be done by manipulating the dom. Also, add an id to your edit button, in this example, I have given it an id "editFormButton". Similarly, add an id to the div in which review content lies so that...
8
1
62,017,043
2020-5-26
https://stackoverflow.com/questions/62017043/automatic-download-of-appropriate-chromedriver-for-selenium-in-python
Unfortunately, Chromedriver always is version-specific to the Chrome version you have installed. So when you pack your python code AND a chromedriver via PyInstaller in a deployable .exe-file for Windows, it will not work in most cases as you won't be able to have all chromedriver versions in the .exe-file. Anyone know...
Here is the other solution, where webdriver_manager does not support. This script will get the latest chrome driver version downloaded. import requests import wget import zipfile import os # get the latest chrome driver version number url = 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE' response = request...
21
28
62,019,062
2020-5-26
https://stackoverflow.com/questions/62019062/pandas-dataframe-split-multiple-key-values-to-different-columns
I have a dataframe column with the following format: col1 col2 A [{'Id':42,'prices':['30',’78’]},{'Id': 44,'prices':['20','47',‘89’]}] B [{'Id':47,'prices':['30',’78’]},{'Id':94,'prices':['20']},{'Id':84,'prices':['20','98']}] How can I transform it to the following ? col1 Id price A 42 ['30',’78’] A 44 ['20','47',‘...
Solution if there are lists in column col2: print (type(df['col2'].iat[0])) <class 'list'> L = [{**{'col1': a}, **x} for a, b in df[['col1','col2']].to_numpy() for x in b] df = pd.DataFrame(L) print (df) col1 Id prices 0 A 42 [30, 78] 1 A 44 [20, 47, 89] 2 B 47 [30, 78] 3 B 94 [20] 4 B 84 [20, 98] If there are strings...
10
5
62,011,741
2020-5-25
https://stackoverflow.com/questions/62011741/pydantic-dataclass-vs-basemodel
What are the advantages and disadvantages of using Pydantic's dataclass vs BaseModel? Are there any performance issues or is it easier to Pydantic's dataclass in the other python module?
Your question is answered in Pydantic's documentation, specifically: Keep in mind that pydantic.dataclasses.dataclass is a drop-in replacement for dataclasses.dataclass with validation, not a replacement for pydantic.BaseModel (with a small difference in how initialization hooks work). There are cases where subclassin...
87
62
61,971,090
2020-5-23
https://stackoverflow.com/questions/61971090/how-can-i-add-images-to-bars-in-axes-matplotlib
I want to add flag images such as below to my bar chart: I have tried AnnotationBbox but that shows with a square outline. Can anyone tell how to achieve this exactly as above image? Edit: Below is my code ax.barh(y = y, width = values, color = r, height = 0.8) height = 0.8 for i, (value, url) in enumerate(zip(values,...
You need the images in a .png format with a transparent background. (Software such as Gimp or ImageMagick could help in case the images don't already have the desired background.) With such an image, plt.imshow() can place it in the plot. The location is given via extent=[x0, x1, y0, y1]. To prevent imshow to force an ...
7
6
61,917,910
2020-5-20
https://stackoverflow.com/questions/61917910/how-to-interpret-py-files-as-jupyter-notebooks
I am using an online jupyter notebook that is somehow configured to read all .py files as jupyter notebook files: I am a big fan of this setup and would like to use it everywhere. On my own jupyter installation however, .py files are just interpreted as test files and are not by default loaded into jupyter cells. How ...
What you're looking for is jupytext. You just need to install it into python env from which you're running your jupyter notebooks: pip install jupytext --upgrade And you get this:
7
5
61,997,378
2020-5-25
https://stackoverflow.com/questions/61997378/assertionerror-could-not-compute-output-tensor
I am trying to build a model that takes multiple inputs and multiple outputs using a functional API. I followed this to create the code. def create_model_multiple(): input1 = tf.keras.Input(shape=(13,), name = 'I1') input2 = tf.keras.Input(shape=(6,), name = 'I2') hidden1 = tf.keras.layers.Dense(units = 4, activation='...
you have to provide validation_data in the correct format (like your train). you have to pass 2 input data and 2 targets... you are passing only one this is a dummy example def create_model_multiple(): input1 = tf.keras.Input(shape=(13,), name = 'I1') input2 = tf.keras.Input(shape=(6,), name = 'I2') hidden1 = tf.keras....
15
15
61,990,363
2020-5-24
https://stackoverflow.com/questions/61990363/rmse-loss-for-multi-output-regression-problem-in-pytorch
I'm training a CNN architecture to solve a regression problem using PyTorch where my output is a tensor of 20 values. I planned to use RMSE as my loss function for the model and tried to use PyTorch's nn.MSELoss() and took the square root for it using torch.sqrt() for that but got confused after obtaining the results.I...
The MSE loss is the mean of the squares of the errors. You're taking the square-root after computing the MSE, so there is no way to compare your loss function's output to that of the PyTorch nn.MSELoss() function — they're computing different values. However, you could just use the nn.MSELoss() to create your own RMSE ...
9
6
61,988,327
2020-5-24
https://stackoverflow.com/questions/61988327/create-a-list-including-row-name-column-name-and-the-value-from-dataframe
I have the following dataframe: A B C A 1 3 0 B 3 2 5 C 0 5 4 All I want is shown below: my_list = [('A','A',1),('A','B',3),('A','C',0),('B','B',2),('B','C',5),('C','C',4)] Thanks in advance!
IIUC, you can do: df.stack().reset_index().agg(tuple,1).tolist() [('A', 'A', 1), ('A', 'B', 3), ('A', 'C', 0), ('B', 'A', 3), ('B', 'B', 2), ('B', 'C', 5), ('C', 'A', 0), ('C', 'B', 5), ('C', 'C', 4)]
14
5
61,952,845
2020-5-22
https://stackoverflow.com/questions/61952845/fastapi-single-parameter-body-cause-pydantic-validation-error
I have a POST FastAPI method. I do not want to construct a class nor query string. So, I decide to apply Body() method. @app.post("/test-single-int") async def test_single_int( t: int = Body(...) ): pass This is the request POST http://localhost:8000/test-single-int/ { "t": 10 } And this is the response HTTP/1.1 422 ...
It is not a bug, it is how Body behaves, it exists for "extending" request params how documentation outlines: class Item(BaseModel): name: str class User(BaseModel): username: str full_name: str = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Item, user: User, importance: int = Body(.....
10
15
61,983,158
2020-5-24
https://stackoverflow.com/questions/61983158/how-to-concat-multiple-pandas-dataframe-columns-with-different-token-separator
I am trying to concat multiple Pandas DataFrame columns with different tokens. For example, my dataset looks like this : dataframe = pd.DataFrame({'col_1' : ['aaa','bbb','ccc','ddd'], 'col_2' : ['name_aaa','name_bbb','name_ccc','name_ddd'], 'col_3' : ['job_aaa','job_bbb','job_ccc','job_ddd']}) I want to output somethi...
from itertools import chain dataframe['features'] = dataframe.apply(lambda x: ''.join([*chain.from_iterable((v, f' <{i}> ') for i, v in enumerate(x))][:-1]), axis=1) print(dataframe) Prints: col_1 col_2 col_3 features 0 aaa name_aaa job_aaa aaa <0> name_aaa <1> job_aaa 1 bbb name_bbb job_bbb bbb <0> name_bbb <1> job_...
19
8
61,980,349
2020-5-24
https://stackoverflow.com/questions/61980349/tensorflow-typeerror-cannot-unpack-non-iterable-float-object
I am using tensorflow V2.2 and run into TyepError when I do model.evaluate. Can someone advise what the issues may be? A screenshot of the execution and error message is shown below.
you need to define a metric when you compile the model model.compile('adam', 'binary_crossentropy', metrics='accuracy') in this way during evaluation, loss and accuracy are returned
7
12
61,972,717
2020-5-23
https://stackoverflow.com/questions/61972717/how-to-run-jupyter-notebook-with-a-different-version-of-python
I want to be able to run both Python 3.8 (currrent version) and Python 3.7 in my Jupyter Notebook. I understand creating different IPython kernels from virtual environments is the way. So I downloaded Python 3.7 and locally installed it in my home directory. Used this python binary file to create a virtual environment ...
Found it myself, the hard way. Let me share anyway, in case this helps anyone. I guess, the problem was that, jupyter notebook installed through pacman searches for python binary files in the PATH variable and not in the path specified by the virtual environment. Since I installed Python 3.7 locally in my home director...
7
8
61,979,855
2020-5-23
https://stackoverflow.com/questions/61979855/changing-colours-of-an-area-in-an-image-using-opencv-in-python
I have a picture were I want to change all white-ish pixels to grey, but only for a certain area of the image. Example picture, I just want to change the picture outside of the red rectangle, without changing the image within the red rectangle: I already have the general code, which was part of someone elses Stackover...
Here is one way to do that in Python/OpenCV. Read the input Convert to HSV color space Threshold on desired color to make a mask Use the mask to change the color of all corresponding pixels in the image Draw a new rectangular mask for the region where you do not want to change Invert the new mask for the region where ...
11
4
61,975,353
2020-5-23
https://stackoverflow.com/questions/61975353/what-is-the-difference-between-string-literals-and-string-values
See this answer. I think your confusion is that you're mixing up the concept of string literals in source code with actual string values. What is the difference between string literals and string values? I did not understand this.
A string literal is a piece of text you can write in your program's source code, beginning and ending with quotation marks, that tells Python to create a string with certain contents. It looks like 'asdf' or ''' multiline content ''' or 'the thing at the end of this one is a line break\n' In a string literal (except...
15
18