question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
61,552,469 | 2020-5-1 | https://stackoverflow.com/questions/61552469/google-cloud-functions-deploy-allow-unauthenticated-invocations | Whenever I have to deploy a new python function using the gcloud sdk I get this message Allow unauthenticated invocations of new function [function-name]? (y/N)? WARNING: Function created with limited-access IAM policy. To enable unauthorized access consider "gcloud alpha functions add-iam-policy-binding function-name... | From https://cloud.google.com/sdk/docs/scripting-gcloud#disabling_prompts: You can disable prompts from gcloud CLI commands by setting the disable_prompts property in your configuration to True or by using the global --quiet or -q flag. So for your example, you could run: gcloud functions deploy function-name --quiet... | 20 | 12 |
61,550,026 | 2020-5-1 | https://stackoverflow.com/questions/61550026/valueerror-shapes-none-1-and-none-3-are-incompatible | I have a 3 dimensional dataset of audio files where X.shape is (329,20,85). I want to have a simpl bare-bones model running, so please don't nitpick and address only the issue at hand. Here is the code: model = tf.keras.models.Sequential() model.add(tf.keras.layers.LSTM(32, return_sequences=True, stateful=False, input_... | The first problem is with the LSTM input_shape. input_shape = (20,85,1). From the doc: https://keras.io/layers/recurrent/ LSTM layer expects 3D tensor with shape (batch_size, timesteps, input_dim). model.add(tf.keras.layers.Dense(nb_classes, activation='softmax')) - this suggets you're doing a multi-class classificatio... | 33 | 44 |
61,543,768 | 2020-5-1 | https://stackoverflow.com/questions/61543768/super-in-a-typing-namedtuple-subclass-fails-in-python-3-8 | I have code which worked in Python 3.6 and fails in Python 3.8. It seems to boil down to calling super in subclass of typing.NamedTuple, as below: <ipython-input-2-fea20b0178f3> in <module> ----> 1 class Test(typing.NamedTuple): 2 a: int 3 b: float 4 def __repr__(self): 5 return super(object, self).__repr__() RuntimeEr... | I was slightly wrong in the other question (which I just updated). Apparently, this behavior manifests in both cases of super. In hindsight, I should have tested this. What's happening here is the metaclass NamedTupleMeta indeed doesn't pass __classcell__ over to type.__new__ because it creates a namedtuple on the fly ... | 14 | 5 |
61,540,156 | 2020-5-1 | https://stackoverflow.com/questions/61540156/python-unittest-setting-a-global-variable-correctly | I have a simple method that sets a global variable to either True or False depending on the method parameter. This global variable is called feedback and has a default value of False. When I call setFeedback('y') the global variable will be changed to be feedback = True. When I call setFeedback('n') the global variabl... | There are two problems with your test. First, you use input in your feedback function, that will stall the test until you enter a key. You probably should mock input. Also you may consider that the call to input does not belong in setFeedback (see comment by @chepner). Second, from main import * will not work here (apa... | 8 | 10 |
61,545,580 | 2020-5-1 | https://stackoverflow.com/questions/61545580/how-does-mypy-use-typing-type-checking-to-resolve-the-circular-import-annotation | I have the following structure for a package: /prog -- /ui ---- /menus ------ __init__.py ------ main_menu.py ------ file_menu.py -- __init__.py __init__.py prog.py These are my import/classes statements: prog.py: from prog.ui.menus import MainMenu /prog/ui/menus/__init__.py: from prog.ui.menus.file_menu import FileM... | Does the process of "type checking" mean code is not executed? Yes, exactly. The type checker never executes your code: instead, it analyzes it. Type checkers are implemented in pretty much the same way compilers are implemented, minus the "generate bytecode/assembly/machine code" step. This means your type checker h... | 31 | 33 |
61,514,121 | 2020-4-30 | https://stackoverflow.com/questions/61514121/serving-flask-app-with-waitress-on-windows-using-ssl-public-private-key | How do I run my Flask app which uses SSL keys using waitress. The SSL context is specified in my Flask's run() as in app.run(ssl_context=('cert.pem', 'key.pem')) But app.run() is not used when using waitress as in the code below. So, where do I specify the keys? Thanks for the help. from flask import Flask, request ap... | At the current version (1.4.3), Waitress does not natively support TLS. See TLS support in https://github.com/Pylons/waitress/blob/36240c88b1c292d293de25fecaae1f1d0ad9cc22/docs/reverse-proxy.rst You either need a reverse proxy in front to handle the tls/ssl part, or use another WSGI server (CherryPy, Tornado...). | 11 | 10 |
61,514,887 | 2020-4-30 | https://stackoverflow.com/questions/61514887/how-to-trigger-a-dag-on-the-success-of-a-another-dag-in-airflow-using-python | I have a python DAG Parent Job and DAG Child Job. The tasks in the Child Job should be triggered on the successful completion of the Parent Job tasks which are run daily. How can add external job trigger ? MY CODE from datetime import datetime, timedelta from airflow import DAG from airflow.operators.postgres_operator ... | Answer is in this thread already. Below is demo code: Parent dag: from datetime import datetime from airflow import DAG from airflow.operators.dummy_operator import DummyOperator default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2020, 4, 29), } dag = DAG('Parent_dag', default_args=de... | 28 | 40 |
61,528,500 | 2020-4-30 | https://stackoverflow.com/questions/61528500/installing-venv-for-python3-in-wsl-ubuntu | I am trying to configure venv on Windows Subsystem for Linux with Ubuntu. What I have tried: 1) Installing venv through pip (pip3, to be exact) pip3 install venv I get the following error ERROR: Could not find a version that satisfies the requirement venv (from versions: none) ERROR: No matching distribution found for... | Give this approach a shot: Install the pip: sudo apt-get install python-pip Install the virtual environment: sudo pip install virtualenv Store your virtual environments somewhere: mkdir ~/.storevirtualenvs Now you should be able to create a new virtualenv virtualenv -p python3 yourVenv To activate: source yourVenv/... | 49 | 50 |
61,513,681 | 2020-4-29 | https://stackoverflow.com/questions/61513681/bin-sh-1-python-not-found-when-run-via-cron-in-docker | I want to repeatedly call a script via cron in a docker container, but when I switch from one time execution to execution via cron the official python image suddenly can't seem to find python. Dockerfile: FROM python:3.7-slim COPY main.py /home/main.py #A: works CMD [ "python", "/home/main.py" ] #B: doesn't work #RUN a... | Cron doesn't set up the PATH environment variable the same as a normal login shell so python can't be found. It should work if you specify a complete path to the Python executable, e.g. replace python with /usr/bin/python (or whatever the path to your Python executable happens to be). Alternatively you can explicitly s... | 9 | 10 |
61,494,278 | 2020-4-29 | https://stackoverflow.com/questions/61494278/plotly-how-to-make-a-figure-with-multiple-lines-and-shaded-area-for-standard-de | How can I use Plotly to produce a line plot with a shaded standard deviation? I am trying to achieve something similar to seaborn.tsplot. Any help is appreciated. | The following approach is fully flexible with regards to the number of columns in a pandas dataframe and uses the default color cycle of plotly. If the number of lines exceed the number of colors, the colors will be re-used from the start. As of now px.colors.qualitative.Plotly can be replaced with any hex color sequen... | 14 | 9 |
61,516,930 | 2020-4-30 | https://stackoverflow.com/questions/61516930/does-shap-in-python-support-keras-or-tensorflow-models-while-using-deepexplainer | I am currently using SHAP Package to determine the feature contributions. I have used the approach for XGBoost and RandomForest and it worked really well. Since the data I am working on is a sequential data I tried using LSTM and CNN to train the model and then get the feature importance using the SHAP's DeepExplainer;... | The returned value of model.fit is not the model instance; rather, it's the history of training (i.e. stats like loss and metric values) as an instance of keras.callbacks.History class. That's why you get the mentioned error when you pass the returned History object to shap.DeepExplainer. Instead, you should pass the m... | 12 | 11 |
61,499,350 | 2020-4-29 | https://stackoverflow.com/questions/61499350/combine-audio-files-in-python | How can I combined multiple audio files (wav) to one file in Python? I found this: import wave infiles = ["sound_1.wav", "sound_2.wav"] outfile = "sounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, '... | You can use the pydub module. It's one of the easiest ways to cut, edit, merge audio files using Python. Here's an example of how to use it to combine audio files with volume control: from pydub import AudioSegment sound1 = AudioSegment.from_file("/path/to/sound.wav", format="wav") sound2 = AudioSegment.from_file("/pat... | 16 | 41 |
61,503,183 | 2020-4-29 | https://stackoverflow.com/questions/61503183/how-can-i-add-grid-lines-to-a-catplot-in-seaborn | How can I add grid lines (vertically and horizontally) to a seaborn catplot? I found a possibility to do that on a boxplot, but I have multiple facets and therefore need a catplot instead. And in contrast to this other answer, catplot does not allow an ax argument. This code is borrowed from here. import seaborn as sn... | You can set the grid over seaborn plots in two ways: 1. plt.grid() method: You need to use the grid method inside matplotlib.pyplot. You can do that like so: import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") exercise = sns.load_dataset("exercise") g = sns.catplot(x="time", y="pulse", hue="kin... | 23 | 41 |
61,500,121 | 2020-4-29 | https://stackoverflow.com/questions/61500121/opencv-python-reading-image-as-rgb | Is it possible to opencv (using python) as default read an image as order of RGB ? in the opencv documentation imread method return image as order of BGR but in code imread methods return the image as RGB order ? I am not doing any converting process. Just used imread methods and show on the screen. It shows as on wind... | OpenCV is entirely consistent within itself. It reads images into Numpy arrays with the channels in BGR order, keeps the images in BGR order and its cv2.imshow() and cv2.imwrite() also expect images in BGR order. All your JPEG/PNG/BMP/TIFF files remain in their normal RGB order on disk. Other libraries, such as PIL/Pil... | 13 | 23 |
61,497,292 | 2020-4-29 | https://stackoverflow.com/questions/61497292/getting-pep8-invalid-escape-sequence-warning-trying-to-escape-parentheses-in-a | I am trying to escape a string such as this: string = re.split(")(", other_string) Because not escaping those parentheses gives me an error. But if I do this: string = re.split("\)\(", other_string) I get a warning from PEP8 that it's an invalid escape sequence. Is there a way to do this properly? Putting 'r' in fron... | You probably are looking for this which would mean your string would be written as string = r")(" which would be escaped. Though that is from 2008 and in python 2 which is being phased out. What the r does is make it a "raw string" See: How to fix "<string> DeprecationWarning: invalid escape sequence" in Python? as wel... | 30 | 30 |
61,494,374 | 2020-4-29 | https://stackoverflow.com/questions/61494374/how-do-i-run-a-program-installed-with-pip-in-windows | I installed a program with pip (e.g. simple-plotter) in windows using the following command: py -m pip install simple-plotter How do I run the program I installed? In Linux, I can just type the command in a terminal, but if I type in windows, I get a "not recognized as an internal or external command" or if I run in P... | I think the error occurs because the Scripts folder is not on PATH in the environment variables, while in Linux it probably is (I don't know a lot of Linux so I don't know how environment variables work there, anyway): the best way to solve this is by adding the Scripts python folder to PATH: In my case it is C:\Users\... | 17 | 9 |
61,492,879 | 2020-4-29 | https://stackoverflow.com/questions/61492879/why-is-true-true-true-true-true-true-not-true-in-python | Code snippet 1: a = True, True, True b = (True, True, True) print(a == b) returns True. Code snippet 2: (True, True, True) == True, True, True returns (False, True, True). | Operator precedence. You're actually checking equality between (True, True, True) and True in your second code snippet, and then building a tuple with that result as the first item. Recall that in Python by specifying a comma-separated "list" of items without any brackets, it returns a tuple: >>> a = True, True, True >... | 16 | 29 |
61,487,041 | 2020-4-28 | https://stackoverflow.com/questions/61487041/more-perceptually-uniform-colormaps | I am an advocate of using perceptually uniform colormaps when plotting scientific data as grayscale images and applying false colorings. I don't know who invented these, but these colormaps are fantastic and I would not use anything else. Anyways to be honest, I've gotten a bit bored of the 5 colormaps (viridis, plasma... | If you follow this page: http://bids.github.io/colormap/, you will find all the details required to produce Viridis, Magma, Inferno and Plasma. All the details are too long to enumerate as an answer but using the aforementioned page and viscm, you can regenerate them and some more interactively. Alternatively, and usin... | 16 | 10 |
61,405,654 | 2020-4-24 | https://stackoverflow.com/questions/61405654/how-to-close-files-using-the-pathlib-module | Historically I have always used the following for reading files in python: with open("file", "r") as f: for line in f: # do thing to line Is this still the recommend approach? Are there any drawbacks to using the following: from pathlib import Path path = Path("file") for line in path.open(): # do thing to line Most ... | If all you wanted to do was read or write a small blob of text (or bytes), then you no longer need to use a with-statement when using pathlib: >>> import pathlib >>> path = pathlib.Path("/tmp/example.txt") >>> path.write_text("hello world") 11 >>> path.read_text() 'hello world' >>> path.read_bytes() b'hello world' The... | 25 | 33 |
61,368,851 | 2020-4-22 | https://stackoverflow.com/questions/61368851/how-to-rotate-seaborn-barplot-x-axis-tick-labels | I'm trying to get a barplot to rotate it's X Labels in 45° to make them readable (as is, there's overlap). len(genero) is 7, and len(filmes_por_genero) is 20 I'm using a MovieLens dataset and making a graph counting the number of movies in each individual genre. Here's my code as of now: import seaborn as sns import ma... | Data from MovieLens 25M Dataset at MovieLens The following code uses the explicit Axes interface with the seaborn axes-level functions. See How to rotate xticklabels in a seaborn catplot for the figure-level functions. If there's no need to change the xticklabels, the easiest option is ax.tick_params(axis='x', labe... | 13 | 30 |
61,414,947 | 2020-4-24 | https://stackoverflow.com/questions/61414947/why-dont-python-sets-preserve-insertion-order | I was surprised to discover recently that while dicts are guaranteed to preserve insertion order in Python 3.7+, sets are not: >>> d = {'a': 1, 'b': 2, 'c': 3} >>> d {'a': 1, 'b': 2, 'c': 3} >>> d['d'] = 4 >>> d {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> s = {'a', 'b', 'c'} >>> s {'b', 'a', 'c'} >>> s.add('d') >>> s {'d', '... | Sets and dicts are optimized for different use-cases. The primary use of a set is fast membership testing, which is order agnostic. For dicts, cost of the lookup is the most critical operation, and the key is more likely to be present. With sets, the presence or absence of an element is not known in advance, and so the... | 67 | 66 |
61,415,284 | 2020-4-24 | https://stackoverflow.com/questions/61415284/poetry-cant-find-version-of-dependency-even-though-it-exists | When bumping my python version from 3.7 to 3.8 in poetry, reinstalling all the dependencies fail with a version of the following: ERROR: No matching distribution found for... The distribution for that version is available at pypa, and is often the most recent version. Simply removing the offending package doesn't fix ... | There are two issues here which feed into each other. poetry seems to consistently botch the upgrade of a venv when you modify the python versions. According to finswimmer, the upgrade should create a new virtual env for the new python version, however this process can fail when poetry uses the wrong pip version or lo... | 22 | 17 |
61,468,548 | 2020-4-27 | https://stackoverflow.com/questions/61468548/check-if-list-is-not-empty-with-pydantic-in-an-elegant-way | Let's say I have some BaseModel, and I want to check that it's options list is not empty. I can perfectly do it with a validator: class Trait(BaseModel): name: str options: List[str] @validator("options") def options_non_empty(cls, v): assert len(v) > 0 return v Are there any other, more elegant, way to do this? | If you want to use a @validator: return v if v else doSomething Python assumes boolean-ess of an empty list as False If you don't want to use a @validator: In Pydantic, use conlist: from pydantic import BaseModel, conlist from typing import List class Trait(BaseModel): name: str options: conlist(str, min_length=1) | 27 | 53 |
61,427,583 | 2020-4-25 | https://stackoverflow.com/questions/61427583/how-do-i-plot-a-keras-tensorflow-subclassing-api-model | I made a model that runs correctly using the Keras Subclassing API. The model.summary() also works correctly. When trying to use tf.keras.utils.plot_model() to visualize my model's architecture, it will just output this image: This almost feels like a joke from the Keras development team. This is the full architecture... | I've found some workaround to plot with the model sub-classing API. For the obvious reason Sub-Classing API doesn't support Sequential or Functional API like model.summary() and nice visualization using plot_model. Here, I will demonstrate both. class my_model(keras.Model): def __init__(self, dim): super(my_model, self... | 16 | 26 |
61,392,258 | 2020-4-23 | https://stackoverflow.com/questions/61392258/most-efficient-method-to-concatenate-strings-in-python | At the time of asking this question, I'm using Python 3.8 When I say efficient, I'm only referring to the speed at which the strings are concatenated, or in more technical terms: I'm asking about the time complexity, not accounting the space complexity. The only methods I can think of at the moment are the following 3 ... | Let's try it out! We can use timeit.timeit() to run a statement many times and return the overall duration. Here, we use s to setup the variables a and b (not included in the overall time), and then run the various options 10 million times. >>> from timeit import timeit >>> >>> n = 10 * 1000 * 1000 >>> s = "a = 'start'... | 11 | 11 |
61,463,224 | 2020-4-27 | https://stackoverflow.com/questions/61463224/when-to-use-raise-for-status-vs-status-code-testing | I have always used: r = requests.get(url) if r.status_code == 200: # my passing code else: # anything else, if this even exists Now I was working on another issue and decided to allow for other errors and am instead now using: try: r = requests.get(url) r.raise_for_status() except requests.exceptions.ConnectionError a... | Response.raise_for_status() is just a built-in method for checking status codes and does essentially the same thing as your first example. There is no "better" here, just about personal preference with flow control. My preference is toward try/except blocks for catching errors in any call, as this informs the future pr... | 86 | 95 |
61,368,805 | 2020-4-22 | https://stackoverflow.com/questions/61368805/how-to-plot-shaded-error-bands-with-seaborn | I wish to create a plot like the following, where I show some values alongside standard deviations. I have two sets of values, containing the mean and standard deviation obtained by two different methods. I thought of doing this with seaborn, but I don't know exactly how to do it since the official example uses pandas... | Here is a minimal example to create such a plot with the given data. Thanks to vectorization and broadcasting, working with numpy simplifies the code. import matplotlib.pyplot as plt import numpy as np mean_1 = np.array([10, 20, 30, 25, 32, 43]) std_1 = np.array([2.2, 2.3, 1.2, 2.2, 1.8, 3.5]) mean_2 = np.array([12, 22... | 14 | 29 |
61,374,525 | 2020-4-22 | https://stackoverflow.com/questions/61374525/how-do-i-check-if-alembic-migrations-need-to-be-generated | I'm trying to improve CI pipeline to prevent situations where SQLAlchemy models are added or changed, but no Alembic migration is written or generated by the commit author from hitting the production branch. alembic --help doesn't seem to provide any helpful commands for this case, yet it already has all the metadata r... | Here's a solution that I use. It's a check that I have implemented as a test. from alembic.autogenerate import compare_metadata from alembic.command import upgrade from alembic.runtime.migration import MigrationContext from alembic.config import Config from models.base import Base def test_migrations_sane(): """ This t... | 14 | 6 |
61,366,664 | 2020-4-22 | https://stackoverflow.com/questions/61366664/how-to-upsert-pandas-dataframe-to-postgresql-table | I've scraped some data from web sources and stored it all in a pandas DataFrame. Now, in order harness the powerful db tools afforded by SQLAlchemy, I want to convert said DataFrame into a Table() object and eventually upsert all data into a PostgreSQL table. If this is practical, what is a workable method of going abo... | Update: You can save yourself some typing by using this method. If you are using PostgreSQL 9.5 or later you can perform the UPSERT using a temporary table and an INSERT ... ON CONFLICT statement: import sqlalchemy as sa # … with engine.begin() as conn: # step 0.0 - create test environment conn.exec_driver_sql("DROP T... | 17 | 24 |
61,430,552 | 2020-4-25 | https://stackoverflow.com/questions/61430552/dataclass-not-inheriting-eq-method-from-its-parent | I have a parent dataclass and a sub-dataclass inherits the first class. I've redefined __eq__() method in parent dataclass. But when I compare objects sub-dataclass, it doesn't use the __eq__() method defined in parent dataclass. Why is this happening? How can I fix this? MWE: from dataclasses import dataclass @datacla... | The @dataclass decorator adds a default __eq__ implementation. If you use @dataclass(eq=False) on class B, it will avoid doing that. See https://docs.python.org/3/library/dataclasses.html | 16 | 17 |
61,358,683 | 2020-4-22 | https://stackoverflow.com/questions/61358683/dependency-inversion-in-python | I've started to apply SOLID principles to my projects. All of them are clear for me, except dependency inversion, because in Python we have no change to define variable in type of some class inside another class (or maybe just I don't know). So I've realized Dependency Inversion principle in two forms, and want to know... | # define a common interface any food should have and implement class IFood: def bake(self): pass def eat(self): pass class Bread(IFood): def bake(self): print("Bread was baked") def eat(self): print("Bread was eaten") class Pastry(IFood): def bake(self): print("Pastry was baked") def eat(self): print("Pastry was eaten"... | 36 | 34 |
61,362,948 | 2020-4-22 | https://stackoverflow.com/questions/61362948/seaborn-pairplots-with-continuous-hues | How may I introduce a continuous hue to my seaborn pairplots? I am passing in a pandas data frame train_df in order to visualise the relationship between the multiple features. However I'd also like to add a hue which would use their corresponding target values, target_df. These target values are on a continuous scal... | You can just assign the target_df as a column in train_df and pass it as hue: sns.pairplot(data=train_df.assign(target=target_df, hue='target') However, this will be extremely slow if your target is continuous. Instead, you can do a double for loop: num_features = len(train_df.columns) fig,ax = plt.subplots(num_featur... | 9 | 4 |
61,400,225 | 2020-4-24 | https://stackoverflow.com/questions/61400225/expected-type-type-got-typetype-instead | My class has a project where we have to build a database. I keep running into this error where python asks expected a type of the same kind that I gave it (see image ) It says Expected type 'TableEntry', got 'Type[TableEntry]' instead TableEntry is a dataclass instance (as per my assignment). I am only calling it for i... | When you see an error like this: Expected type 'TableEntry', got 'Type[TableEntry]' instead it generally means that in the body of your code you said TableEntry (the name of the type) rather than TableEntry() (an expression that constructs an actual object of that type). | 8 | 17 |
61,430,166 | 2020-4-25 | https://stackoverflow.com/questions/61430166/python-3-7-on-ubuntu-20-04 | I am preparing a docker image for Ubuntu 20.04 and due to TensorFlow 2.0 requirement, I need Python 3.7. TensorFlow runs on Python 3.5 to 3.7. Running apt install python3 installs Python 3.8 by default and that breaks my TensorFlow installation. Is there any way I can get an apt package for Python 3.7 for Ubuntu 20.04?... | Do you need Ubuntu 20.04? Ubuntu 18.04 comes with Python 3.6, and 3.7 available. If you do, the deadsnakes PPA has Python 3.5-3.7 for Ubuntu 20.04 (Focal). To add it and install: sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get install python3.7 P.s. I'm not a dev and have no experience with Tensorflow so take ... | 60 | 117 |
61,386,477 | 2020-4-23 | https://stackoverflow.com/questions/61386477/type-hints-for-a-pandas-dataframe-with-mixed-dtypes | I've been looking for robust type hints for a pandas DataFrame, but cannot seem to find anything useful. This question barely scratches the surface Pythonic type hints with pandas? Normally if I want to hint the type of a function, that has a DataFrame as an input argument I would do: import pandas as pd def func(arg: ... | I have now found the pandera library that seems very promising: https://github.com/pandera-dev/pandera It allows users to create schemas and use those schemas to create verbose checks. From their docs: https://pandera.readthedocs.io/en/stable/schema_models.html import pandas as pd import pandera as pa from pandera.typi... | 11 | 8 |
61,370,108 | 2020-4-22 | https://stackoverflow.com/questions/61370108/tf-data-parallelize-loading-step | I have a data input pipeline that has: input datapoints of types that are not castable to a tf.Tensor (dicts and whatnot) preprocessing functions that could not understand tensorflow types and need to work with those datapoints; some of which do data augmentation on the fly I've been trying to fit this into a tf.data... | I came across the same problem and found a (relatively) easy solution. It turns out that the proper way to do so is indeed to first create a tf.data.Dataset object using the from_generator(gen) method, before applying your custom python processing function (wrapped within a py_function) with the map method. As you ment... | 11 | 4 |
61,419,449 | 2020-4-25 | https://stackoverflow.com/questions/61419449/unable-to-instantiate-python-dataclass-frozen-inside-a-pytest-function-that-us | I'm following along with Architecture Patterns in Python by Harry Percival and Bob Gregory. Around chapter three (3) they introduce testing the ORM of SQLAlchemy. A new test that requires a session fixture, it is throwing AttributeError, FrozenInstanceError due to cannot assign to field '_sa_instance_state' It may be i... | SqlAlchemy allows you to override some of the attribute instrumentation that is applied when using mapping classes and tables. In particular the following allows sqla to save the state on an instrumented frozen dataclass. This should be applied before calling the mapper function which associates the dataclass and the s... | 12 | 4 |
61,365,987 | 2020-4-22 | https://stackoverflow.com/questions/61365987/whats-new-in-python-2-7-18 | So the final Python 2 release is out. However, I can't find anywhere what has changed with this release. The corresponding news page on GitHub is also empty. Can anyone shed some light on this? | Nice question. You can find out for yourself by downloading and comparing the source code both for 2.7.17 and 2.7.18. Since 2.7 is my favorite flavor of Python I've decided to do it myself; here's a WinMerge screenshot: Looks like there are some differences. On the other hand, Misc\NEWS clearly states: What's New in ... | 17 | 9 |
61,359,162 | 2020-4-22 | https://stackoverflow.com/questions/61359162/convert-a-list-of-tensors-to-tensors-of-tensors-pytorch | I have this code: import torch list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)] tensor_of_tensors = torch.tensor(list_of_tensors) I am getting the error: ValueError: only one element tensors can be converted to Python scalars How can I convert the list of tensors to a tensor of tensors in pytorch? | Here is a solution: tensor_of_tensors = torch.stack((list_of_tensors)) print(tensor_of_tensors) #shape (3,3) | 9 | 12 |
61,419,086 | 2020-4-24 | https://stackoverflow.com/questions/61419086/fatal-error-in-launcher-unable-to-create-process-using-file-path1-file-path2 | I am trying to use different versions of Python on my Windows pc and I'm getting this error when using pip: Fatal error in launcher: Unable to create process using '"c:\users\mypc\appdata\local\programs\python\python38\python.exe" "C:\Python38\Scripts\pip.exe" ': The system cannot find the file specified. I understan... | it seems like python team may have implemented some security measures. The new method now is just to prefix python -m before your commands. Let's say you are trying to install pygame (any package) with pip. For that, you'll use python -m pip install pygame //Or any package name Also, upgrading pip and all other comman... | 7 | 24 |
61,379,554 | 2020-4-23 | https://stackoverflow.com/questions/61379554/how-to-bypass-google-recaptcha-while-scraping-with-requests | Python code to request the URL: agent = {"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'} #using agent to solve the blocking issue response = requests.get('https://www.naukri.com/jobs-in-andhra-pradesh', headers=agent) #making the request to t... | Using Google Cache along with a referer (in the header) will help you bypass the captcha. Things to note: Don't send more than 2 requests/sec. You may get blocked. The result you receive is a cache. This will not be effective if you are trying to scrape a real-time data. Example: header = { "user-agent": "Mozilla/5.0... | 13 | 25 |
61,399,162 | 2020-4-24 | https://stackoverflow.com/questions/61399162/is-there-a-way-to-splat-assign-as-tuple-instead-of-list-when-unpacking | I was recently surprised to find that the "splat" (unary *) operator always captures slices as a list during item unpacking, even when the sequence being unpacked has another type: >>> x, *y, z = tuple(range(5)) >>> y [1, 2, 3] # list, was expecting tuple Compare to how this assignment would be written without unpacki... | This is by design. Quoting the official docs about Assignment: ...The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assig... | 13 | 5 |
61,357,038 | 2020-4-22 | https://stackoverflow.com/questions/61357038/how-do-i-install-the-most-recent-tensorflow-here-2-2-on-windows-when-conda-do | I have conda 4.8.3 and Python 3.7.4 on Windows 8.1. I have tf 2.0.0 installed in a conda environment. How do I upgrade to 2.2.x? Or, how do I just install 2.2.x in a conda environment? Edit 1: pip install --upgrade tensorflow says: Requirement already up-to-date: tensorflow in d:\anaconda3\envs\tf2\lib\site-packages (2... | There are two methods 1. Install into virtual environment with pip TensorFlow virtualenv --system-site-packages -p python3 ./venv then you need to activate your new environment pip install --upgrade pip pip list # show packages installed within the virtual environment this command for quit deactivate # don't exit unti... | 12 | 4 |
61,381,620 | 2020-4-23 | https://stackoverflow.com/questions/61381620/pytest-windows-fatal-exception-access-violation | I'm using pytest to run some tests for my project. Sometimes (about 30 to 50%) I get an error after the test finished. But this is preventing the testengine to create the testreport, which is really a pain. Error: Windows fatal exception: access violation Current thread 0x000019e0 (most recent call first): File "C:\Pyt... | Downgrading pyserial from Version 3.4 to Version 2.7 fixed the problem | 8 | -1 |
61,457,122 | 2020-4-27 | https://stackoverflow.com/questions/61457122/python-assignment-operator-differs-from-non-assignment | I have face this weird behavior I can not find explications about. MWE: l = [1] l += {'a': 2} l [1, 'a'] l + {'B': 3} Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: can only concatenate list (not "dict") to list Basically, when I += python does not raise an error and append the key t... | l += ... is actually calling object.__iadd__(self, other) and modifies the object in-place when l is mutable The reason (as @DeepSpace explains in his comment) is that when you do l += {'a': 2} the operation updates l in place only and only if l is mutable. On the other hand, the operation l + {'a': 2} is not done in ... | 20 | 17 |
61,425,296 | 2020-4-25 | https://stackoverflow.com/questions/61425296/why-neural-network-predicts-wrong-on-its-own-training-data | I made a LSTM (RNN) neural network with supervised learning for data stock prediction. The problem is why it predicts wrong on its own training data? (note: reproducible example below) I created simple model to predict next 5 days stock price: model = Sequential() model.add(LSTM(32, activation='sigmoid', input_shape=(x... | The OP postulates an interesting finding. Let me simplify the original question as follows. If the model is trained on a particular time series, why can't the model reconstruct previous time series data, which it was already trained on? Well, the answer is embedded in the training progress itself. Since EarlyStopping ... | 27 | 15 |
61,479,772 | 2020-4-28 | https://stackoverflow.com/questions/61479772/remap-the-values-to-other-and-give-default-value-also | I have tabe i have to map with two values in NY,CAits Domestic, WT its OUTSIDE, and other than that its has to OVERSEAS di = {"NY": "Domestic","CA": "Domestic","WT":"OUTSIDE"} df.replace({'Territory': di}) How to give OVERSEAS in the above code. So by default it has(nothing in the dictionary) to OVERSEAS | Use Series.map which return missing values for no match values, so added Series.fillna for replace them to default value: df = pd.DataFrame({'Territory':['NY','CA','WT','SK','DE']}) di = {"NY": "Domestic","CA": "Domestic","WT":"OUTSIDE"} print (df) Territory 0 NY 1 CA 2 WT 3 SK 4 DE df['Territory'] = df['Territory'].ma... | 7 | 7 |
61,480,570 | 2020-4-28 | https://stackoverflow.com/questions/61480570/how-to-pass-a-parameterised-fixture-as-a-parameter-to-another-fixture | I am trying to avoid repeating too much boilerplate in my tests, and I want to rewrite them in a more structured way. Let's say that I have two different parsers that both can parse a text into a doc. That doc would then be used in other tests. The end goal is to expose a doc() fixture that can be used in other tests, ... | Not sure if this is exactly what you need, but you could just use functions instead of fixtures, and combine these in fixtures: import pytest class Parser: # dummy parser for testing def __init__(self, name): self.name = name def parse(self, text): return f'{self.name}({text})' class ParserFactory: # do not recreate ex... | 9 | 1 |
61,473,880 | 2020-4-28 | https://stackoverflow.com/questions/61473880/avro-deserialization-from-kafka-using-fastavro | I am building an application which receives data from Kafka. When using standard avro library provided by Apache ( https://pypi.org/project/avro-python3/ ) the results are correct, however, the deserialization process is terribly slow. class KafkaReceiver: data = {} def __init__(self, bootstrap='192.168.1.111:9092'): ... | The fastavro.reader expects the avro file format that includes the header. It looks like what you have is a serialized record without the header. I think you might be able to read this using the fastavro.schemaless_reader. So instead of: for record in reader(bytes_reader, schema): self.data = record You would do: self... | 7 | 10 |
61,461,520 | 2020-4-27 | https://stackoverflow.com/questions/61461520/does-anyone-know-the-meaning-of-the-output-of-image-to-data-and-image-to-osd-met | I'm trying to extract the data from an image using pytesseract. This module has image_to_data and image_to_osd methods. These two methods provide lots of info (TextLineOrder, WritingDirection, ScriptDetection, Orientation, etc...) as output. The image below is the output of the image_to_data method. What do the values ... | Column Level: Item with no block_num, paragraph_num, line_num, word_num Item with block_num and with no paragraph_num, line_num, word_num Item with block_num, paragraph_num and with no line_num, word_num Item with block_num, paragraph_num, line_num, and with no word_num Item with all those numbers Column block_num: B... | 10 | 8 |
61,479,059 | 2020-4-28 | https://stackoverflow.com/questions/61479059/it-there-any-default-asynchronious-null-context-manager-in-python3-7 | I would like to create optional asynchronious semaphore. In case of asyncio.Semaphore does not support None values, i decided to create asyncio.Semaphore, if connections limit is specified, else - some kind of dummy object There is a contextlib.nullcontext, but it supports only synchorious with I`ve created my own dumm... | It there any default asynchronious null context manager? You can use contextlib.AsyncExitStack(). ExitStack() was similarly the way to create a quick-and-dirty null context manager before the introduction of nullcontext. | 7 | 8 |
61,491,893 | 2020-4-28 | https://stackoverflow.com/questions/61491893/i-cannot-install-tensorflow-version-1-15-through-pip | I have checked my pip version and got the following output: Requirement already up-to-date: pip in ./anaconda3/envs/runlee_python3/lib/python3.8/site-packages (20.1) I have a specific situation in which I have to use version 1.15 of Tensorflow, but when I try to install it, it seems like it can‘t find this specific ve... | You are using python 3.8, which was not officially supported when tensorflow was at version 1.15. You can also check on pypi, there are no files available for cp38, even for 2.10 Onle the versions listed by your command have a cp38 whl file available, see here Since you have conda, simply create a virtual env with the ... | 63 | 86 |
61,490,351 | 2020-4-28 | https://stackoverflow.com/questions/61490351/scipy-cosine-similarity-vs-sklearn-cosine-similarity | I noticed that both scipy and sklearn have a cosine similarity/cosine distance functions. I wanted to test the speed for each on pairs of vectors: setup1 = "import numpy as np; arrs1 = [np.random.rand(400) for _ in range(60)];arrs2 = [np.random.rand(400) for _ in range(60)]" setup2 = "import numpy as np; arrs1 = [np.ra... | As mentioned in the comments section, I don't think the comparison is fair mainly because the sklearn.metrics.pairwise.cosine_similarity is designed to compare pairwise distance/similarity of the samples in the given input 2-D arrays. On the other hand, scipy.spatial.distance.cosine is designed to compute cosine distan... | 8 | 18 |
61,449,954 | 2020-4-27 | https://stackoverflow.com/questions/61449954/pyqt5-datepicker-popup | I am not able to make datepicker in pyqt5. I am using calendarWidget and it working fine now. But i want dropdown datepicker in my menu bar and want to show selected date in lineEdit. I have created a layout in QDesigner and adding 'DateEdit" widget. But i want same exactly as image shown. I searched for datepicker an... | The QDateEdit already provides a QCalendarWidget so you only need to enable the calendarPopup property: import sys from PyQt5 import QtCore, QtWidgets class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.dateedit = QtWidgets.QDateEdit(calendarPopup=True) self.menuBar()... | 7 | 17 |
61,468,705 | 2020-4-27 | https://stackoverflow.com/questions/61468705/pyspark-using-collect-list-over-window-with-condition | I have the following test data: import pandas as pd import datetime data = {'date': ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04', '2014-01-05', '2014-01-06'], 'customerid': [2, 2, 2, 3, 4, 3], 'names': ['Andrew', 'Pete', 'Sean', 'Steve', 'Ray', 'Stef'], 'PaymentType': ['OI', 'CC', 'CC', 'OI', 'OI', 'OI']} da... | You could put a when/otherwise clause in your collect_list to collect only when PaymentType is 'OI', otherwise collect None. spark_data.withColumn("names_array",\ F.collect_list(F.when(F.col("PaymentType")=='OI',F.col("names"))\ .otherwise(F.lit(None))).over(win)).sort(F.col("date").asc()).show() #+-------------------... | 8 | 13 |
61,457,120 | 2020-4-27 | https://stackoverflow.com/questions/61457120/how-to-use-libreoffice-api-uno-with-python-windows | This question is focused on Windows + LibreOffice + Python 3. I've installed LibreOffice (6.3.4.2), also pip install unoconv and pip install unotools (pip install uno is another unrelated library), but still I get this error after import uno: ModuleNotFoundError: No module named 'uno' More generally, and as an exampl... | In order to interact with LibreOffice, start an instance listening on a socket. I don't use COM much, but I think this is the equivalent of the COM interaction you asked about. This can be done most easily on the command line or using a shell script, but it can also work with a system call using a time delay and subpro... | 10 | 9 |
61,455,686 | 2020-4-27 | https://stackoverflow.com/questions/61455686/time-complexity-of-python-dictionary-len-method | Example: a = {a:'1', b:'2'} len(a) What is the time complexity of len(a) ? | Inspecting the c-source of dictobject.c shows that the structure contains a member responsible for maintaining an explicit count (dk_size) layout: +---------------+ | dk_refcnt | | dk_size | | dk_lookup | | dk_usable | | dk_nentries | +---------------+ ... Thus it will have order O(1) | 10 | 16 |
61,440,990 | 2020-4-26 | https://stackoverflow.com/questions/61440990/how-to-check-whether-user-is-logged-in-or-not | I am working on invoice management system in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page but whenever user logout and try to access home page but it is giving following error. TypeError at / 'AnonymousUser' object is not iterable i tried An... | Finally i got the solution that work for me here it is Django provides LoginRequiredMixin i used this in my invoicelistview function from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin class InvoiceListView(LoginRequiredMixin,ListView): model = Invoicelist template_name = 'invoicedata/home.ht... | 14 | 10 |
61,452,582 | 2020-4-27 | https://stackoverflow.com/questions/61452582/why-is-using-sudo-pip-a-bad-idea | In a post I was reviewing recently, I read that it's advised not to use 'sudo pip' to install certain items. Can someone clarify why this is and what the downsides/upsides are? Thanks! | Your OS has a Python interpreter to run Python software controlled by your package manager, be it apt, yum, or App Store. Any Python package installed to the system Python installation are dependencies of such software, or that software itself. By installing or updating packages in your system Python, you can break th... | 7 | 8 |
61,451,279 | 2020-4-27 | https://stackoverflow.com/questions/61451279/how-do-setcolumnstretch-and-setrowstretch-work | I have an application built using PySide2 which uses setColumnStretch for column stretching and setRowStretch for row stretching. It works well and good, but I am unable to understand how it is working. I am stuck on the two values inside those parentheses. For example: glay = QtWidgets.QGridLayout(right_container) gla... | Short Answer: Read the Qt docs: https://doc.qt.io/qt-5/qgridlayout.html as it is clear and precise. Long Answer: addWidget(): The addWidget method is overload (that concept exists natively in C++ but can be built in python but does not exist by default) which implies that a method (or function) has a different behavi... | 15 | 30 |
61,447,877 | 2020-4-26 | https://stackoverflow.com/questions/61447877/python-split-list-into-several-lines-of-code | I have a list in Python which includes up to 50 elements. In order for me to easily add/subtract elements, I'd prefer to either code it vertically (each list element on one Python code line) or alternatively, import a separate CSV file? list_of_elements = ['AA','BB','CC','DD','EE','FF', 'GG'] for i in list_of_elements:... | The first line should contain the first element, like this: list_of_elements = ['AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG'] or as Naufan Rusyda Faikar commented: Put backslash next to = Or put the left bracket next to =. list_of_elements = \ ['AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG'] list_of_elements = [ 'AA', 'BB', 'C... | 9 | 14 |
61,443,261 | 2020-4-26 | https://stackoverflow.com/questions/61443261/what-is-the-use-of-pd-plotting-register-matplotlib-converters-in-pandas | While learning from an online course on visualising data, I came across this line of code. import pandas as pd pd.plotting.register_matplotlib_converters() import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns Can someone please tell me what is the use of pd.plotting.register_matplotlib_converters(... | I found this in the documentation: This function modifies the global matplotlib.units.registry dictionary. Pandas adds custom converters for pd.Timestamp pd.Period np.datetime64 ... So I guess it makes sure that pandas datatypes like pd.Timestamp can be used in matplotlib plots without having to cast them to another ... | 14 | 6 |
61,439,815 | 2020-4-26 | https://stackoverflow.com/questions/61439815/how-to-display-an-svg-image-in-python | I was following this tutorial on how to write a chess program in Python. It uses the python-chess engine. The functions from that engine apparently return SVG data, that could be used to display a chessboard. Code from the tutorial: import chess import chess.svg from IPython.display import SVG board = chess.Board() ... | I think you are getting confused by the scripting nature of Python. You say, you have experience with Qt development under C++. Wouldn't you create a main window widget there first and add to it your SVG widget within which you would call or load SVG data? I would rewrite your code something like this. import chess im... | 12 | 8 |
61,437,320 | 2020-4-26 | https://stackoverflow.com/questions/61437320/pytest-finding-when-each-test-started-and-ended | I have a complex Django-Pytest test suite with lots of tests that are running in parallel processes. I'd like to see the exact timepoint at which each test started and ended. How can I get that information out of Pytest? | The start/stop timestamps for each call phase are stored in the CallInfo objects. However, accessing those for reporting is not very convenient, so it's best to store both timestamps in the report objects. Put the following code in a conftest.py file in your project/test root dir: import pytest @pytest.hookimpl(hookwra... | 8 | 6 |
61,437,756 | 2020-4-26 | https://stackoverflow.com/questions/61437756/no-python-3-8-installation-was-detected | Python installation screenshot 1.i Uninstall everything of python with advance uninstaller . ( register file and ...) 2.i download the last version of Python from python.org 3. i add the Include PATH file when start the installation of Python. BUT I don't KNOW WHY ITS NOT Installed ! | Error Code 0x80070643 I found it. if you are not administrator of the system , and change the location of installation , for example (c:\python) this error will be appear . so you must be install python on (c:\users\'your username'\App Data\Local\Programs\Python) and after installation python go to system environment a... | 11 | 5 |
61,408,795 | 2020-4-24 | https://stackoverflow.com/questions/61408795/using-sagemath-as-a-python-library | Is it possible to import the SageMath functions inside a python session? What I wish to do, from a user perspective is something like this: >>> import sage >>> sage.kronecker_symbol(3,5) # ...or any other sage root functions instead of accessing kronecker_symbol(3,5) from a sagemath session. If possible, it would be v... | Importing SageMath functions in a Python session There are several ways to achieve that. SageMath from the operating system's package manager Some operating systems have Sage packaged natively, for example Arch Linux, Debian, Fedora, Gentoo, NixOS, and their derivatives (Linux Mint, Manjaro, Ubuntu...). See the dedicat... | 12 | 10 |
61,428,816 | 2020-4-25 | https://stackoverflow.com/questions/61428816/why-does-unpacking-give-a-list-instead-of-a-tuple-in-python | This is really strange to me, because by default I thought unpacking gives tuples. In my case I want to use the prefix keys for caching, so a tuple is preferred. # The r.h.s is a tuple, equivalent to (True, True, 100) *prefix, seed = ml_logger.get_parameters("Args.attn", "Args.memory_gate", "Args.seed") assert type(pre... | This issue was mentioned in that PEP (PEP 3132): After a short discussion on the python-3000 list [1], the PEP was accepted by Guido in its current form. Possible changes discussed were: [...] Try to give the starred target the same type as the source iterable, for example, b in a, *b = 'hello' would be assigned the ... | 9 | 7 |
61,428,792 | 2020-4-25 | https://stackoverflow.com/questions/61428792/how-do-i-go-back-to-my-system-python-using-pyenv-in-ubuntu | i installed pyenv and switched to python 3.6.9 (using pyenv global 3.6.9). How do i go back to my system python? Running pyenv global system didnt work | Your system Python might be /usr/bin/python or /usr/bin/python3. You have a couple options: Execute that Python interpreter directly: /usr/bin/python --version If you want to run it from a script and you're on a *nix machine, put #!/usr/bin/python at the top of the file, then give it execute permissions (chmod +x m... | 11 | 8 |
61,426,232 | 2020-4-25 | https://stackoverflow.com/questions/61426232/update-dataclass-fields-from-a-dict-in-python | How can I update the fields of a dataclass using a dict? Example: @dataclass class Sample: field1: str field2: str field3: str field4: str sample = Sample('field1_value1', 'field2_value1', 'field3_value1', 'field4_value1') updated_values = {'field1': 'field1_value2', 'field3': 'field3_value2'} I want to do something l... | One way is to make a small class and inherit from it: class Updateable(object): def update(self, new): for key, value in new.items(): if hasattr(self, key): setattr(self, key, value) @dataclass class Sample(Updateable): field1: str field2: str field3: str field4: str You can read this if you want to learn more about g... | 11 | 10 |
61,417,426 | 2020-4-24 | https://stackoverflow.com/questions/61417426/is-if-name-main-required-in-a-main-py | In a project that has a __main__.py, rather than # __main__.py # def main... if __name__ == "__main__": main() ...is it OK to just do: # __main__.py # def main... main() Edit: @user2357112-supports-Monica's argument made a lot of sense to me, so I went back and tracked down the library that had been giving me issues,... | It's okay to skip the if __name__ == '__main__' guard in most regular scripts, not just __main__.py. The purpose of the guard is to make specific code not run if the file is imported as a module instead of run as the program's entry point, but importing a __main__.py as a module is usually using it wrong anyway. Even w... | 11 | 6 |
61,387,304 | 2020-4-23 | https://stackoverflow.com/questions/61387304/tabula-vs-camelot-for-table-extraction-from-pdf | I need to extract tables from pdf, these tables can be of any type, multiple headers, vertical headers, horizontal header etc. I have implemented the basic use cases for both and found tabula doing a bit better than camelot still not able to detect all tables perfectly, and I am not sure whether it will work for all ki... | Please read this: https://camelot-py.readthedocs.io/en/master/#why-camelot The main advantage of Camelot is that this library is rich in parameters, through which you can improve the extraction. Obviously, the application of these parameters requires some study and various attempts. Here you can find comparision of Cam... | 7 | 13 |
61,384,752 | 2020-4-23 | https://stackoverflow.com/questions/61384752/how-to-type-hint-with-an-optional-import | When using an optional import, i.e. the package is only imported inside a function as I want it to be an optional dependency of my package, is there a way to type hint the return type of the function as one of the classes belonging to this optional dependency? To give a simple example with pandas as an optional depende... | Try sticking your import inside of an if typing.TYPE_CHECKING statement at the top of your file. This variable is always false at runtime but is treated as always true for the purposes of type hinting. For example: # Lets us avoid needing to use forward references everywhere # for Python 3.7+ from __future__ import an... | 21 | 19 |
61,400,692 | 2020-4-24 | https://stackoverflow.com/questions/61400692/how-to-bypass-bot-detection-and-scrape-a-website-using-python | The problem I was new to web scraping and I was trying to create a scraper which looks at a playlist link and gets the list of the music and the author. But the site kept rejecting my connection because it thought that I was a bot, so I used UserAgent to create a fake useragent string to try and bypass the filter. It s... | You wanna check out this link to get the content you wish to grab. The following attempt should fetch you the artist names and their song names. import requests from bs4 import BeautifulSoup url = 'https://www.melon.com/mymusic/playlist/mymusicplaylistview_listSong.htm?plylstSeq=473505374' r = requests.get(url,headers=... | 7 | 5 |
61,394,826 | 2020-4-23 | https://stackoverflow.com/questions/61394826/how-do-i-get-to-show-gaussian-kernel-for-2d-opencv | I am using this: blur = cv2.GaussianBlur(dst,(5,5),0) And I wanted to show the kernel matrix by this: print(cv2.getGaussianKernel(ksize=(5,5),sigma=0)) But I am getting a type error: TypeError: an integer is required (got type tuple) If I only put 5, I get a 5x1 matrix. Isn't the blur kernel 5x5? Or am I missing on... | The Gaussian kernel is separable. Therefore, the kernel generated is 1D. The GaussianBlur function applies this 1D kernel along each image dimension in turn. The separability property means that this process yields exactly the same result as applying a 2D convolution (or 3D in case of a 3D image). But the amount of wor... | 7 | 12 |
61,392,431 | 2020-4-23 | https://stackoverflow.com/questions/61392431/how-to-create-a-permutation-in-c-using-stl-for-number-of-places-lower-than-the | I have a c++ vector with std::pair<unsigned long, unsigned long> objects. I am trying to generate permutations of the objects of the vector using std::next_permutation(). However, I want the permutations to be of a given size, you know, similar to the permutations function in python where the size of the expected retur... | You might use 2 loops: Take each n-tuple iterate over permutations of that n-tuple template <typename F, typename T> void permutation(F f, std::vector<T> v, std::size_t n) { std::vector<bool> bs(v.size() - n, false); bs.resize(v.size(), true); std::sort(v.begin(), v.end()); do { std::vector<T> sub; for (std::size_t i... | 19 | 6 |
61,383,179 | 2020-4-23 | https://stackoverflow.com/questions/61383179/fastapi-passing-json-in-get-request-via-testclient | I'm try to test the api I wrote with Fastapi. I have the following method in my router : @app.get('/webrecord/check_if_object_exist') async def check_if_object_exist(payload: WebRecord) -> bool: key = get_key_of_obj(payload.data) if payload.key is None else payload.key return await check_if_key_exist(key) and the foll... | In order to send data to the server via a GET request, you'll have to encode it in the url, as GET does not have any body. This is not advisable if you need a particular format (e.g. JSON), since you'll have to parse the url, decode the parameters and convert them into JSON. Alternatively, you may POST a search request... | 10 | 6 |
61,387,845 | 2020-4-23 | https://stackoverflow.com/questions/61387845/python-vs-julia-speed-comparison | I tried to compare these two snippets and see how many iterations could be done in one second. Turns out that Julia achieves 2.5 million iterations whereas Python 4 million. Isn't Julia supposed to be quicker. Or maybe these two snippets are not equivalent? Python: t1 = time.time() i = 0 while True: i += 1 if time.time... | This is kind of an odd performance comparison since typically one measures the time it takes to compute something of substance, rather than seeing how many trivial iterations one can do in a certain amount of time. I had trouble getting your Python and Julia codes to work, so I modified the Julia code to work and just ... | 13 | 13 |
61,367,382 | 2020-4-22 | https://stackoverflow.com/questions/61367382/plot-custom-data-with-tensorboard | I have a personal implementation of a RL algorithm that generates performance metrics every x time steps. That metric is simply a scalar, so I have an array of scalars that I want to display as a simple graph such as: I want to display it in real time in tensorboard like my above example. Thanks in advance | If you really want to use tensorboard you can start looking at tensorflow site and this datacamp tutorial on tensorboard. With tensorflow you can use summary.scalar to plot your custom data (as the example), no need for particular format, as the summary is taking care of that, the only condition is that data has to be ... | 13 | 8 |
61,372,172 | 2020-4-22 | https://stackoverflow.com/questions/61372172/lark-grammar-how-does-the-escaped-string-regex-work | The lark parser predefines some common terminals, including a string. It is defined as follows: _STRING_INNER: /.*?/ _STRING_ESC_INNER: _STRING_INNER /(?<!\\)(\\\\)*?/ ESCAPED_STRING : "\"" _STRING_ESC_INNER "\"" I do understand _STRING_INNER. I also understand how ESCAPED_STRING is composed. But what I don't really u... | Preliminaries: .*? Non-greedy match, meaning the shortest possible number of repetitions of . (any symbol). This only makes sense when followed by something else. So .*?X on input AAXAAX would match only the AAX part, instead of expanding all the way to the last X. (?<!...) is a "negative look-behind assertion" (link)... | 7 | 9 |
61,363,712 | 2020-4-22 | https://stackoverflow.com/questions/61363712/how-to-print-a-pandas-io-formats-style-styler-object | I have the following code which produces a pandas.io.formats.style.Styler object: import pandas as pd import numpy as np df = pd.DataFrame({'text': ['foo foo', 'bar bar'], 'number': [1, 2]}) df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])]) df2 = df1.set_properties(**{'text-align'... | I found the answer for this: import pandas as pd from IPython.display import display import numpy as np df = pd.DataFrame({'text': ['foo foo', 'bar bar'], 'number': [1, 2]}) df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])]) df2 = df1.set_properties(**{'text-align': 'center'}).hide... | 12 | 14 |
61,363,534 | 2020-4-22 | https://stackoverflow.com/questions/61363534/whats-the-recommended-way-of-renaming-a-project-in-pypi | I want people that know of the old name to be directed to the new name. For the pypi website, it's easy to upload a package with a README linking to the new package. I'm not sure what's the best way to handle people using pip to install it. I assume it might be possible to show an error on pip install old_name, looking... | Declare the new package a dependency of the old. See for example how scikit-learn does it: the old package sklearn declares in its setup.py: install_requires=['scikit-learn'], Thus everyone who does pip install sklearn automatically gets scikit-learn. | 12 | 8 |
61,238,502 | 2020-4-15 | https://stackoverflow.com/questions/61238502/how-to-require-predefined-string-values-in-python-pydantic-basemodels | Is there any in-built way in pydantic to specify options? For example, let's say I want a string value that must either have the value "foo" or "bar". I know I can use regex validation to do this, but since I use pydantic with FastAPI, the users will only see the required input as a string, but when they enter somethin... | Yes, you can either use an enum: class Choices(Enum): foo = 'foo' bar = 'bar' class Input(BaseModel): option: Choices see here Or you can use Literal: from typing import Literal class Input(BaseModel): option: Literal['foo', 'bar'] see here | 61 | 127 |
61,351,844 | 2020-4-21 | https://stackoverflow.com/questions/61351844/difference-between-multiprocessing-asyncio-threading-and-concurrency-futures-i | Being new to using concurrency, I am confused about when to use the different python concurrency libraries. To my understanding, multiprocessing, multithreading and asynchronous programming are part of concurrency, while multiprocessing is part of a subset of concurrency called parallelism. I searched around on the web... | Let's go through the major concurrency-related modules provided by the standard library: threading: interface to OS-level threads. Note that CPU-bound work is mostly serialized by the GIL, so don't expect threading to speed up calculations. Use it when you need to invoke blocking APIs in parallel, and when you require... | 61 | 135 |
61,321,503 | 2020-4-20 | https://stackoverflow.com/questions/61321503/is-there-a-pathlib-alternate-for-os-path-join | I am currently accessing the parent directory of my file using Pathlib as follows: Path(__file__).parent When I print it, and this gives me the following output: print('Parent: ', Path(__file__).parent) #output /home/user/EC/main-folder The main-folder has a .env file which I want to access and for that I want to joi... | Use pathlib.Path.joinpath: (Path(__file__).parent).joinpath('.env') | 150 | 84 |
61,274,967 | 2020-4-17 | https://stackoverflow.com/questions/61274967/why-cant-i-exclude-tests-directory-from-my-python-wheel-using-exclude | Consider the following package structure: With the following setup.py contents: from setuptools import setup, find_packages setup( name='dfl_client', packages=find_packages(exclude=['*tests*']), include_package_data=True, package_data={"": ['py.typed', '*.pyi']}, ) When I package it using python setup.py sdist bdist_... | (I spent so many time trying to understand this stupid issue that I answer my own question hoping that can save time to others facing the same problem) I finally found the culprit: it is a hidden interaction between setuptools_scm and the include_package_data=True flag. By itself, include_package_data=True does not mak... | 14 | 21 |
61,292,464 | 2020-4-18 | https://stackoverflow.com/questions/61292464/get-confidence-interval-from-sklearn-linear-regression-in-python | I want to get a confidence interval of the result of a linear regression. I'm working with the boston house price dataset. I've found this question: How to calculate the 99% confidence interval for the slope in a linear regression model in python? However, this doesn't quite answer my question. Here is my code: import ... | If you're looking to compute the confidence interval of the regression parameters, one way is to manually compute it using the results of LinearRegression from scikit-learn and numpy methods. The code below computes the 95%-confidence interval (alpha=0.05). alpha=0.01 would compute 99%-confidence interval etc. import n... | 18 | 14 |
61,226,910 | 2020-4-15 | https://stackoverflow.com/questions/61226910/how-to-programmatically-check-if-kafka-broker-is-up-and-running-in-python | I'm trying to consume messages from a Kafka topic. I'm using a wrapper around confluent_kafka consumer. I need to check if connection is established before I start consuming messages. I read that the consumer is lazy, so I need to perform some action for the connection to get established. But I want to check the connec... | I am afraid there is no direct approach for testing whether Kafka Brokers are up and running. Also note that if your consumer has already consumed the messages it doesn't mean that this is a bad behaviour and obviously it does not indicate that the Kafka broker is down. A possible workaround would be to perform some s... | 11 | 21 |
61,222,356 | 2020-4-15 | https://stackoverflow.com/questions/61222356/no-menu-for-adding-wsl-python-interpreter-in-pycharm | I was following this guide from official jetbrains page, until the step 2 comes in the existence. In the picture mentioned in that page, has so many options like ssh, wsl, vagrant, docker, etc. In my pycharm (latest 2019.3.4) it only shows 4 options - venv, conda, pipenv and system-interpreter. There is no WSL menu in... | I have solved this by Uninstalling pycharm with history and cache. Removing folders completely from C:\Users\%USERNAME%\AppData\Local and C:\Users\%USERNAME%\AppData\Roaming\JetBrains and Clean re-install of pycharm WSL interpreter option shows up as normal Ideavim is creating a conflict I guess. | 14 | 14 |
61,342,459 | 2020-4-21 | https://stackoverflow.com/questions/61342459/how-can-i-add-text-labels-to-a-plotly-scatter-plot-in-python | I'm trying to add text labels next to the data points in a Plotly scatter plot in Python but I get an error. How can I do that? Here is my dataframe: world_rank university_name country teaching international research citations income total_score num_students student_staff_ratio international_students female_male_rati... | You can include the text labels in the text attribute. To make sure that they are displayed on the scatter plot, set mode='lines+markers+text'. See the Plotly documentation on text and annotations. I included an example below based on your code. import plotly.graph_objects as go import pandas as pd df = pd.DataFrame({'... | 14 | 36 |
61,345,981 | 2020-4-21 | https://stackoverflow.com/questions/61345981/error-running-as-root-without-no-sandbox-is-not-supported | I try to implement scrapy-puppeteer library for my project (https://pypi.org/project/scrapy-puppeteer/) I implement PuppeteerMiddleware according to documentation from library Here is code which I run: import asyncio from twisted.internet import asyncioreactor asyncioreactor.install(asyncio.get_event_loop()) import scr... | How i can fix it? I would presume by not running as root It appears your dockerfile only needs root privileges for the apt-get process, since pip3 will cheerfully install either into a virtualenv (highly recommended) or into your dockerfile's user's home directory via --user FROM python:3.6 RUN set -e ;\ export DEBIA... | 9 | 3 |
61,341,119 | 2020-4-21 | https://stackoverflow.com/questions/61341119/write-a-text-inside-a-subplot | I'm working on this plot: I need to write something inside the first plot, between the red and the black lines, I tried with ax1.text() but it shows the text between the two plots and not inside the first one. How can I do that? The plot was set out as such: fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1, figsize = (1... | Without more code details, it's quite hard to guess what is wrong. The matplotlib.axes.Axes.text works well to show text box on subplots. I encourage you to have a look at the documentation (arguments...) and try by yourself. The text location is based on the 2 followings arguments: transform=ax.transAxes: indicates t... | 14 | 29 |
61,353,532 | 2020-4-21 | https://stackoverflow.com/questions/61353532/plotly-how-to-get-the-trace-color-attribute-in-order-to-plot-selected-marker-wi | I am trying to plot a selected marker for each of my traces in plotly. I would like to assign the same color to marker and line. Is there a way how to get the color attribute of my traces? fig = go.Figure() fig.add_trace(go.Scatter( x=[0, 1, 2, 3, 4, 5], y=[0, 3, 5, 7, 9, 11], name='trace01', mode='lines+markers', mark... | Updated answer for newer versions of plotly: For recent plotly versions, a larger number of the attributes of a plotly figure object are readable through fig.data. Now you can retrive the color for a line without defining it or following a color cycle through: fig.data[0].line.color To make things a bit more flexible ... | 14 | 22 |
61,277,709 | 2020-4-17 | https://stackoverflow.com/questions/61277709/unexpected-tokens-in-doctype-html-in-pycharm-community-edition | I am new in using PyCharm but I am loving it gradually. I am getting a red underline on <!DOCTYPE html> and the error is "Unexpected Token". Why PyCharm shows it? I can't understand. | It usually happens when you don't enable Django in Pycharm's settings. To resolve the problem: In Pycharm open Setting in File menu Select and expand Languages & Frameworks Select Django and enable it Select your Django project root Select your project setting.py file Select your project manage.py file Apply setting | 8 | 6 |
61,235,853 | 2020-4-15 | https://stackoverflow.com/questions/61235853/how-to-invoke-cloud-function-from-cloud-scheduler-with-authentication | I've looked everywhere and it seems people either use pubsub, app engine http or http with no auth. Not too many people out there showing their work for accessing functions via authentication w/ oidc tokens to access google functions. I checked out: Cannot invoke Google Cloud Function from GCP Scheduler but nothing se... | These are the exact steps you have to take. Be sure not to skip the second step, it sets invoker permissions on the service account so that the scheduler is able to invoke the HTTP Cloud Function with that service account's OIDC information. Note: for simplicity, I choose the default service account here, however, it w... | 23 | 12 |
61,302,822 | 2020-4-19 | https://stackoverflow.com/questions/61302822/can-you-change-code-in-a-gitlab-pipeline | Is it possible for a GitLab CI/CD pipeline to commit code changes? I would like to run a stage that uses black to format my code automatically whenever I push my work. gitlab-ci.yml image: python:3.6 stages: - test before_script: - python3 -m pip install -r requirements.txt test:linting: script: - black ./ I made sure... | Black won't automatically commit corrected python code unless you use pre-commit hook. Best way to run black in CI is to include something like : black . --check --verbose --diff --color This will fail the test if python code fail to adhere to code format and force user to fix formatting. please checkout black --help ... | 10 | 17 |
61,275,551 | 2020-4-17 | https://stackoverflow.com/questions/61275551/python-in-vs-code-can-i-run-cell-in-the-integrated-terminal | In VS Code with Python, we can run a "cell" (block that starts with #%%) in the "Python Interactive Window" Can we do the same thing on the Integrated Terminal? I know we can do this in Spyder, where the terminal is generally always an IPython terminal Matlab works in the same way with its terminal. Can we do this in V... | I've opened a issue in GitHub, @AdamAL also opened, but it seems they don't have intention to do this. Here is a workaround to other users. EDIT: I've answered before with a workaround that takes 2 VSCode extensions and not use the smart command jupyter.selectCellContents. @AdamAL shared a better solution using this co... | 8 | 9 |
61,350,804 | 2020-4-21 | https://stackoverflow.com/questions/61350804/tkinter-treeview-how-to-correctly-select-multiple-items-with-the-mouse | I'm trying to use the mouse to select and deselect multiple items. I have it working sort of but there is a problem when the user moves the mouse to fast. When the mouse is moved fast some items are skipped and are not selected at all. I must be going about this the wrong way. Update 1: I decided to use my own selectin... | Working Example: Tested and works in Windows and Linux UPDATE: I have updated the code and everything works in Windows and Linux, although in Windows the blue transparent window is jittery when sizing from right to left, left to right is fine. In Linux the jitters don't happen anyone know why? If someone could let me k... | 13 | 0 |
61,291,741 | 2020-4-18 | https://stackoverflow.com/questions/61291741/passing-list-likes-to-loc-or-with-any-missing-labels-is-no-longer-supported | I want to create a modified dataframe with the specified columns. I tried the following but throws the error "Passing list-likes to .loc or [] with any missing labels is no longer supported" # columns to keep filtered_columns = ['text', 'agreeCount', 'disagreeCount', 'id', 'user.firstName', 'user.lastName', 'user.gende... | It looks like Pandas has deprecated this method of indexing. According to their docs: This behavior is deprecated and will show a warning message pointing to this section. The recommended alternative is to use .reindex() Using the new recommended method, you can filter your columns using: tips_filtered = tips_df.rein... | 54 | 54 |
61,265,125 | 2020-4-17 | https://stackoverflow.com/questions/61265125/jupyter-notebook-module-not-found-even-after-pip-install | I have a module installed in my Juyter notebook !pip install gensim Requirement already satisfied: gensim in /home/m.gawinecki/virtualenv/la-recoms/lib/python3.7/site-packages (3.8.2) However, when I try to import it, it fails import gensim --------------------------------------------------------------------------- Mo... | Add your virtual environment as Python kernel in this way (Make sure it's activated): (venv) $ ipython kernel install --name "local-venv-kernel" --user Now, you can select the created kernel "local-venv-kernel" when you start Jupyter notebook or lab. You could check the installed libraries using this code in a noteboo... | 20 | 16 |
61,330,414 | 2020-4-20 | https://stackoverflow.com/questions/61330414/pandas-astype-with-date-or-datetime | This answer contains a very elegant way of setting all the types of your pandas columns in one line: # convert column "a" to int64 dtype and "b" to complex type df = df.astype({"a": int, "b": complex}) I am starting to think that that unfortunately has limited application and you will have to use various other methods... | This has been answered in the comments where it was noted that the following works: df.astype({'date': 'datetime64[ns]'}) In addition, you can set the dtype when reading in the data: pd.read_csv('path/to/file.csv', parse_dates=['date']) | 17 | 33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.