question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
60,739,889 | 2020-3-18 | https://stackoverflow.com/questions/60739889/bypass-mypys-module-has-no-attribute-on-dynamic-attribute-setting | I have the following code on a.py: class Tags(enum.Flag): NONE = 0 A = enum.auto() B = enum.auto() C = enum.auto() # Allow using tags.A instead of tags.Tags.A globals().update(Tags.__members__) But when I use it on other files, mypy (rightfully) fails to identify the attributes: import tags print(tags.A) # Module has ... | Personally, what I would do is modify my imports to do: from tags import Tags ..which would let me refer to the enum items by doing just Tags.A everywhere with minimal fuss. But if you really want to continue referring to these items from the module namespace instead, one approach is to define a __getattr__ function ... | 8 | 2 |
60,742,389 | 2020-3-18 | https://stackoverflow.com/questions/60742389/split-item-to-rows-pandas | I have the data in dataframes like below. I want to split the item into same number of rows >>> df idx a 0 3 1 5 2 4 from above dataframe, I want the below as >>> df idx a 0 1 1 2 2 3 3 1 4 2 5 3 6 4 7 5 8 1 9 2 10 3 11 4 I tried several ways, but no success. | A Fun way df.a.map(range).explode()+1 # may add reset_index(), however, I think keep the original index is good, and help us convert back. Out[158]: idx 0 1 0 2 0 3 1 1 1 2 1 3 1 4 1 5 2 1 2 2 2 3 2 4 Name: a, dtype: object | 6 | 5 |
60,741,112 | 2020-3-18 | https://stackoverflow.com/questions/60741112/most-pythonic-way-to-provide-defaults-for-class-constructor | I am trying to stick to Google's styleguide to strive for consistency from the beginning. I am currently creating a module and within this module I have a class. I want to provide some sensible default values for different standard use cases. However, I want to give the user the flexibility to override any of the defa... | In general if there is more than one way to reasonably construct your object type, you can provide classmethods for alternate construction (dict.fromkeys is an excellent example of this). Note that this approach is more applicable if your use cases are finite and well defined statically. class MyClass: def __init__(sel... | 7 | 9 |
60,740,528 | 2020-3-18 | https://stackoverflow.com/questions/60740528/how-to-count-the-number-of-dashes-between-any-two-alphabetical-characters | If we have a string of alphabetical characters and some dashes, and we want to count the number of dashes between any two alphabetic characters in this string. what is the easiest way to do this? Example: Input: a--bc---d-k output: 2031 This means that there are 2 dashes between a and b, 0 dash between b and c, 3 dashe... | Solution with regex: import re x = 'a--bc---d-k' results = [ len(m) for m in re.findall('(?<=[a-z])-*(?=[a-z])', x) ] print(results) print(''.join(str(r) for r in results)) output: [2, 0, 3, 1] 2031 Solution with brute force loop logic: x = 'a--bc---d-k' count = 0 results = [] for c in x: if c == '-': count += 1 els... | 11 | 9 |
60,736,401 | 2020-3-18 | https://stackoverflow.com/questions/60736401/reticulate-doesnt-print-to-console-in-real-time | Using Python's print() (or to the best of my knowledge, any other console output generating) function in loop structures and running the code via reticulate in R, the output is only printed after the execution finished. For example, take the following loop which goes to sleep for 1.5 seconds after each iteration; the r... | Apparently, you need to force pyhton to export the standard output at times. You can do this by adding sys.stdout.flush() to your code: library(reticulate) py_run_string(" import time import sys for i in range(5): print(str(i)) time.sleep(1.5) # sleep for 1.5 sec sys.stdout.flush() ") see over here described with nohu... | 9 | 5 |
60,732,859 | 2020-3-18 | https://stackoverflow.com/questions/60732859/sudoku-puzzle-with-boxes-containing-square-numbers | Two days ago, I was given a sudoku problem that I tried to solve with Python 3. I've been informed that a solution does exist, but I'm not certain if there exists multiple solutions. The problem is as following: A 9x9 grid of sudoku is completely empty. It does however contain colored boxes, and inside these boxes, the... | This is where I would use a SMT solver. They are a lot more powerful than people give credit for. If the best algorithm you can think of is essentially bruteforce, try a solver instead. Simply listing your constraints and running it gives your unique answer in a couple seconds: 278195436 695743128 134628975 549812763 3... | 9 | 6 |
60,732,924 | 2020-3-18 | https://stackoverflow.com/questions/60732924/how-to-specify-that-a-python-object-must-be-two-types-at-once | I'm using the Python typing module throughout my project, and I was wondering if there was a way to specify that a given object must be of two different types, at once. This most obviously arises when you have specified two protocols, and expect a single object to fulfil both: class ReturnsNumbers(Protocol): def get_nu... | Create a new type that inherits from all types you wish to combine, as well as Protocol. class ReturnsNumbersAndLetters(ReturnsNumbers, ReturnsLetters, Protocol): pass def get_number_and_letter(x: ReturnsNumbersAndLetters) -> None: print(x.get_number(), x.get_letter()) | 15 | 13 |
60,669,969 | 2020-3-13 | https://stackoverflow.com/questions/60669969/why-is-mypy-complaining-about-list-comprehension-when-it-cant-be-annotated | Why does Mypy complain that it requires a type annotation for a list comprehension variable, when it is impossible to annotate such a variable using MyPy? Specifically, how can I resolve the following error: from enum import EnumMeta def spam( y: EnumMeta ): return [[x.value] for x in y] 🠜 Mypy: Need type annotation f... | In a list comprehension, the iterable must be cast instead of the elements. from typing import Iterable, cast from enum import EnumMeta, Enum def spam(y: EnumMeta): return [[x.value] for x in cast(Iterable[Enum], y)] This allows mypy to infer the type of x as well. In addition, at runtime it performs only 1 cast inste... | 16 | 25 |
60,645,256 | 2020-3-11 | https://stackoverflow.com/questions/60645256/how-do-you-get-batches-of-rows-from-spark-using-pyspark | I have a Spark RDD of over 6 billion rows of data that I want to use to train a deep learning model, using train_on_batch. I can't fit all the rows into memory so I would like to get 10K or so at a time to batch into chunks of 64 or 128 (depending on model size). I am currently using rdd.sample() but I don't think that... | I don't believe spark let's you offset or paginate your data. But you can add an index and then paginate over that, First: from pyspark.sql.functions import lit data_df = spark.read.parquet(PARQUET_FILE) count = data_df.count() chunk_size = 10000 # Just adding a column for the ids df_new_schema = data_df.withColumn('p... | 11 | 3 |
60,699,002 | 2020-3-16 | https://stackoverflow.com/questions/60699002/how-can-i-build-manually-c-extension-with-mingw-w64-python-and-pybind11 | My final goal is to compile Python C++ extension from my C++ code. Currently to get started I am following a simple example from the first steps of pybind11 documentation. My working environment is a Windows 7 Professional 64 bit, mingw-w64 (x86_64-8.1.0-posix-seh-rt_v6-rev0) and Anaconda3 with Python 3.7.4 64 bit. I h... | It is unbelievable! The problem was just the file extension of the compiled file. As soon as I changed .dll to .pyd, the Python example (example.py) is running without any issue! So the new command line is: C:/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin/g++.exe -shared -std=c++11 -DMS_WIN64 -fPIC -ID:\Users... | 6 | 9 |
60,669,256 | 2020-3-13 | https://stackoverflow.com/questions/60669256/how-do-you-create-a-logit-normal-distribution-in-python | Following this post, I tried to create a logit-normal distribution by creating the LogitNormal class: import numpy as np import matplotlib.pyplot as plt from scipy.special import logit from scipy.stats import norm, rv_continuous class LogitNormal(rv_continuous): def _pdf(self, x, **kwargs): return norm.pdf(logit(x), **... | Forewords I came across this problem this week and the only relevant issue I have found about it is this post. I have almost same requirement as the OP: Having a random variable for Logit Normal distribution. But I also need: To be able to perform statistical test as well; While being compliant with the scipy random... | 6 | 6 |
60,667,001 | 2020-3-13 | https://stackoverflow.com/questions/60667001/how-to-find-corner-x-y-coordinate-points-on-image-python-opencv | This is a truck container image but from the top view. First, I need to find the rectangle and know each corner position. The goal is to know the dimension of the container. | Here's a simple approach: Obtain binary image. Load image, convert to grayscale, Gaussian blur, then Otsu's threshold. Find distorted bounding rectangle contour and corners. We find contours then filter using contour area to isolate the rectangular contour. Next we find the distorted bounding rectangle with cv2.minAr... | 6 | 7 |
60,700,062 | 2020-3-16 | https://stackoverflow.com/questions/60700062/runtimeerror-occurs-in-pytorch-backward-function | I am trying to calculate the grad of a variable in PyTorch. However, there was a RuntimeError which tells me that the shape of output and grad must be the same. However, in my case, the shape of output and grad cannot be the same. Here is my code to reproduce: import numpy as np import torch from torch.autograd import ... | First of all you don't need to use numpy and then convert to Variable (which is deprecated by the way), you can just use G = torch.rand(m, n) etc. Second, when you write out.backward(z), you are passing z as the gradient of out, i.e. out.backward(gradient=z), probably due to the misconception that "out.backward(z) comp... | 6 | 5 |
60,716,016 | 2020-3-17 | https://stackoverflow.com/questions/60716016/how-to-get-the-latest-release-version-in-github-only-use-python-requests | Recently,I make an app and upload it to my GitHub release page.I want to make a function to check update to get the latest version(in the release pages). I try to use requests module to crawl my release page to get the latest version.Here it a minimal example of my code: import requests from lxml import etree response ... | A direct way is to use GitHub API, it is easy to do and don't need xpath. The URL should be: https://api.github.com/repos/{owner}/{repo}/releases/latest So if you want to get the latest release version of the repository. Here is an easy example only using the requests module: import requests response = requests.get("... | 14 | 33 |
60,685,749 | 2020-3-14 | https://stackoverflow.com/questions/60685749/python-plotly-how-to-add-an-image-to-a-3d-scatter-plot | I am trying to visualize multiple 2d trajectories (x, y) in a 3D scatter plot where the z axis is time. import numpy as np import pandas as pd import plotly.express as px # Sample data: 3 trajectories t = np.linspace(0, 10, 200) df = pd.concat([pd.DataFrame({'x': 900 * (1 + np.cos(t + 5 * i)), 'y': 400 * (1 + np.sin(t)... | I've ran into the same situation where I wanted to use an image as a bottom surface in a 3D scatterplot. With help from two posts here and here, I've been able to create the following 3d scatter plot: I've used plotly go in my example, so the result is a little bit different than the code from the OP. import numpy as ... | 7 | 4 |
60,699,202 | 2020-3-16 | https://stackoverflow.com/questions/60699202/python-frozen-dataclass-allow-changing-of-attribute-via-method | Suppose I have a dataclass: @dataclass(frozen=True) class Foo: id: str name: str I want this to be immutable (hence the frozen=True), such that foo.id = bar and foo.name = baz fail. But, I want to be able to strip the id, like so: foo = Foo(id=10, name="spam") foo.strip_id() foo -> Foo(id=None, name="spam") I have tr... | Well, you can do it by directly modifying the __dict__ member of the instance modifying the attribute using object.__setattr__(...)1, but why??? Asking specifically for immutable and then making it mutable is... indecisive. But if you must: from dataclasses import dataclass @dataclass(frozen=True) class Foo: id: str na... | 10 | 10 |
60,725,232 | 2020-3-17 | https://stackoverflow.com/questions/60725232/what-files-directories-should-i-add-to-gitignore-when-using-poetry-the-python | I'm using a very new Python package manager called Poetry. It creates several files/directories upon creating a new project (environment), but I'm not sure which one I should add to .gitignore for the best practice. Say I create a new poetry project by doing this: $ poetry new foo_project $ cd foo_project $ poetry a... | Also moved to poetry quite recently. I would say you should not add any of: tests/, foo_project/, poetry.lock or README.rst to your .gitignore. In other words, those files and folders should be in version control. My reasons are as follows: tests/ - your tests should not be machine dependent (unless this is a know limi... | 29 | 25 |
60,707,607 | 2020-3-16 | https://stackoverflow.com/questions/60707607/weird-mro-result-when-inheriting-directly-from-typing-namedtuple | I am confused why FooBar.__mro__ doesn't show <class '__main__.Parent'> like the above two. I still don't know why after some digging into the CPython source code. from typing import NamedTuple from collections import namedtuple A = namedtuple('A', ['test']) class B(NamedTuple): test: str class Parent: pass class Foo(P... | This is because typing.NamedTuple is not really a proper type. It is a class. But its singular purpose is to take advantage of meta-class magic to give you a convenient nice way to define named-tuple types. And named-tuples derive from tuple directly. Note, unlike most other classes, from typing import NamedTuple class... | 9 | 11 |
60,657,926 | 2020-3-12 | https://stackoverflow.com/questions/60657926/drawing-labels-that-follow-their-edges-in-a-networkx-graph | Working with Networkx, I have several edges that need to be displayed in different ways. For that I use the connectionstyle, some edges are straight lines, some others are Arc3. The problem is that every edge has a label and the label doesn't follow the edges in these styles. I borrowed a graph as example : #!/usr/bin... | Yes, it is possible to draw labeled edges of networkx directed graphs, by using GraphViz. An example using the Python package graphviz, the Python package networkx, and the GraphViz program dot: """How to draw a NetworkX graph using GraphViz. Requires: - The Python package `graphviz`: https://github.com/xflr6/graphviz ... | 7 | 4 |
60,719,286 | 2020-3-17 | https://stackoverflow.com/questions/60719286/actions-for-creating-venv-in-python-and-clone-a-git-repo | I'm relatively new in all that and I have a problem with the row of the actions. Say that you created a directory and you want a python virtual environment for some project and clone a few git repos (say, from GitHub). Then you cd in that directory and create a virtual environment using the venv module (for python3). T... | First of all, you need to understand what is virtual environments, when you understand what it is for, the order of actions will be more clear. Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library, beca... | 14 | 35 |
60,674,136 | 2020-3-13 | https://stackoverflow.com/questions/60674136/python-how-to-cancel-a-specific-task-spawned-by-a-nursery-in-python-trio | I have an async function that listens on a specific port. I want to run the function on a few ports at a time and when the user wants to stop listening on a specific port, stop the function listening on that port. Previously I was using the asyncio library for this task and I tackled this problem by creating tasks with... | Easy. You create a cancel scope, return that from the task, and cancel this scope when required: async def my_task(task_status=trio.TASK_STATUS_IGNORED): with trio.CancelScope() as scope: task_status.started(scope) pass # do whatever async def main(): async with trio.open_nursery() as n: scope = await n.start(my_task) ... | 6 | 5 |
60,658,375 | 2020-3-12 | https://stackoverflow.com/questions/60658375/vscode-python-extension-how-can-i-disable-autocompletion-from-inserting-import | In VS Code's Python extension I sometimes find that autocompletion can include options for things that are not yet imported in the file I'm editing. When selecting one of those options imports sometimes get inserted at the top of the module without notification. While I can see the utility in this feature I don't reall... | Using Pylance (as of v2020.8.0), you can disable this by setting "python.analysis.autoImportCompletions": false https://github.com/microsoft/pylance-release/blob/master/CHANGELOG.md#202080-5-august-2020 | 15 | 17 |
60,716,529 | 2020-3-17 | https://stackoverflow.com/questions/60716529/download-file-using-fastapi | I see the functions for uploading in an API, but I don't see how to download. Am I missing something? I want to create an API for a file download site. Is there a different API I should be using? from typing import List from fastapi import FastAPI, Query app = FastAPI() PATH "some/path" @app.get("/shows/") def get_item... | This worked For me from starlette.responses import FileResponse return FileResponse(file_location, media_type='application/octet-stream',filename=file_name) This will download the file with filename | 46 | 48 |
60,639,731 | 2020-3-11 | https://stackoverflow.com/questions/60639731/tensorboard-for-custom-training-loop-in-tensorflow-2 | I want to create a custom training loop in tensorflow 2 and use tensorboard for visualization. Here is an example I've created based on tensorflow documentation: import tensorflow as tf import datetime os.environ["CUDA_VISIBLE_DEVICES"] = "0" # which gpu to use mnist = tf.keras.datasets.mnist (x_train, y_train), (x_tes... | As answered here, I'm sure there's a better way, but a simple workaround is to just use the existing tensorboard callback logic: tb_callback = tf.keras.callbacks.TensorBoard(LOG_DIR) tb_callback.set_model(model) # Writes the graph to tensorboard summaries using an internal file writer | 11 | 6 |
60,646,028 | 2020-3-12 | https://stackoverflow.com/questions/60646028/numpy-point-cloud-to-image | I have a point cloud which looks something like this: The red dots are the points, the black dots are the red dots projected to the xy plane. Although it is not visible in the plot, each point also has a value, which is added to the given pixel when the point is moved to the xy plane. The points are represented by a n... | Courtesy of @Paul Panzer: def points_to_image(xs, ys, ps, img_size): coords = np.stack((ys, xs)) abs_coords = np.ravel_multi_index(coords, img_size) img = np.bincount(abs_coords, weights=ps, minlength=img_size[0]*img_size[1]) img = img.reshape(img_size) On my machine, the loop version takes 0.4432s vs 0.0368s using ve... | 6 | 7 |
60,638,344 | 2020-3-11 | https://stackoverflow.com/questions/60638344/quartiles-line-properties-in-seaborn-violinplot | trying to figure out how to modify the line properties (color, thickness, style etc) of the quartiles in a seaborn violinplot. Example code from their website: import seaborn as sns sns.set(style="whitegrid") tips = sns.load_dataset("tips") ax = sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, palette="Set... | You can access the lines from your ax variable using the following to set line type, color, and saturation: for l in ax.lines: l.set_linestyle('-') l.set_color('black') l.set_alpha(0.8) This creates a solid black line for all horizontal lines. If you can figure out which of the lines in ax correspond with your lines ... | 11 | 8 |
60,699,058 | 2020-3-16 | https://stackoverflow.com/questions/60699058/python-asyncio-queue-not-showing-any-exceptions | If i run this code, it will hang without throwing ZeroDivisionError. If i move await asyncio.gather(*tasks, return_exceptions=True) above await queue.join(), it will finally throw ZeroDivisionError and stop. If i then comment out 1 / 0 and run, it will execute everything, but will hang in the end. Now the question i... | There are several ways to approach this, but the central idea is that in asyncio, unlike in classic threading, it is straightforward to await multiple things at once. For example, you can await queue.join() and the worker tasks, whichever completes first. Since workers don't complete normally (you cancel them later), a... | 6 | 7 |
60,666,418 | 2020-3-13 | https://stackoverflow.com/questions/60666418/remove-authentication-and-permission-for-specific-url-path | I'm working with DRF and came across this issue. I have a third-party view which I'm importing in my urls.py file like this : from some_package import some_view urlpatterns = [ path('view/',some_view) ] but the issue I'm facing is since I have enabled default permission classes in my settings.py like this: REST_FRAMEW... | So, the most appropriate way for third-party views is to use decorators by defining them inside your urls.py: Case 1 I assume that some_view is a class inherited from rest_framework.views.APIView: urls.py from django.urls import path from rest_framework.decorators import permission_classes, authentication_classes from ... | 8 | 6 |
60,720,072 | 2020-3-17 | https://stackoverflow.com/questions/60720072/5x5-sliding-puzzle-fast-low-move-solution | I am trying to find a way to programmatically solve a 24-piece sliding puzzle in a reasonable amount of time and moves. Here is an example of the solved state in the puzzle I am describing: I have already found that the IDA* algorithm works fairly well to accomplish this for a 15-puzzle (4x4 grid). The IDA* algorithm... | It as been proved that finding the fewest number of moves of n-Puzzle is NP-Complete, see Daniel Ratner and Manfred Warmuth, The (n2-1)-Puzzle and Related Relocation Problems, Journal of Symbolic Computation (1990) 10, 111-137. Interesting facts reviewed in Graham Kendall, A Survey of NP-Complete Puzzles, 2008: The 8-... | 6 | 7 |
60,643,710 | 2020-3-11 | https://stackoverflow.com/questions/60643710/setuptools-know-in-advance-the-wheel-filename-of-a-native-library | Is there an easy way to know the filename of a Python wheel before running the setup script? I'm trying to generate a Bazel rule that builds a .whl for each Python version installed in the machine, the library contains native code so it needs to be compiled for each version separately. The thing with Bazel is that it r... | Update See also a more detailed answer here. You can get the name by querying the bdist_wheel command, for that you don't even need to build anything or writing a setup.py script (but you need the metadata you pass to the setup function). Example: from distutils.core import Extension from setuptools.dist import Distrib... | 7 | 4 |
60,719,220 | 2020-3-17 | https://stackoverflow.com/questions/60719220/airflow-running-python-files-fails-due-to-python-cant-open-file | I have a folder tree like this in my project project dags python_scripts libraries docker-compose.yml Dockerfile docker_resources I create an airflow service in a docker container with: dockerfile #Base image FROM puckel/docker-airflow:1.10.1 #Impersonate USER root #Los automatically thrown to the I/O strem and not... | Finally I solved the issue, I discard all previous work, and restart DOCKERFILE using an UBUNTU base image, and not puckel/docker-airflow image which is based in python:3.7-slim-buster. I don't use any other user that its not root know. | 7 | 0 |
60,704,532 | 2020-3-16 | https://stackoverflow.com/questions/60704532/python-telegram-bot-how-to-wait-for-user-answer-to-a-question-and-return-it | Context: I am using PyTelegramBotAPi or Python Telegram Bot I have a code I am running when a user starts the conversation. When the user starts the conversation I need to send him the first picture and a question if He saw something in the picture, the function needs to wait for the user input and return whether he sa... | You should save your user info in a database. Basic fields would be: (id, first_name, last_name, username, menu) What is menu? Menu keeps user's current state. When a user sends a message to your bot, you check the database to find out about user's current sate. So if the user doesn't exist, you add them to your users ... | 6 | 16 |
60,713,751 | 2020-3-16 | https://stackoverflow.com/questions/60713751/where-to-put-dockerignore | Consider the following typical python project structure: fooproject - main.py - src/ - test/ - logs/ - Dockerfile - .dockerignore - README.md The .dockerfile should prevent test/ and logs/ directories from being included in the docker image. test/ logs/ Contents of Dockerfile are FROM ubuntu16.04 COPY . /app/ WORKDIR... | The .dockerignore is used to control what files are included in the build context. This impacts the COPY and ADD commands in the Dockerfile, and ultimately the resulting image. When you run that image with a volume mount, e.g.: { "Type": "bind", "Source": "/home/adam/Desktop/Dev/ec2-data-analysis/grimlock", "Destinati... | 19 | 24 |
60,722,876 | 2020-3-17 | https://stackoverflow.com/questions/60722876/how-likely-is-token-collision-with-python-secrets-library | How likely is it for a collision to occur with tokens generated using Python's secrets library (https://docs.python.org/3/library/secrets.html)? There doesn't seem to be any mention of their uniqueness. | The purpose of the secrets module, is for sourcing secret data, i.e. information that cannot be predicted or reverse engineered The secrets module provides access to the most secure source of randomness that your operating system provides. Typically, the OS will use several entropy sources to generate bits. e.g. proc... | 6 | 9 |
60,716,482 | 2020-3-17 | https://stackoverflow.com/questions/60716482/error-skipping-analyzing-flask-mysqldb-found-module-but-no-type-hints-or-lib | I am using Python 3.6 and flask. I used flask-mysqldb to connect to MySQL, but whenever I try to run mypy on my program I get this error: Skipping analyzing 'flask_mysqldb': found module but no type hints or library stubs. I tried running mypy with the flags ignore-missing-imports or follow-imports=skip. Then I was n... | You are getting this error because mypy is not designed to try type checking every single module you try importing. This is mainly for three reasons: The module you're trying to import could be written in a way that it fails to type check. For example, if the module does something like my_list = [] in the global scope... | 56 | 59 |
60,727,103 | 2020-3-17 | https://stackoverflow.com/questions/60727103/what-are-the-caveats-of-inheriting-from-both-str-and-enum | What are the caveats (if any) of using a class that inherits from both str and Enum? This was listed as a possible way to solve the problem of Serialising an Enum member to JSON from enum import Enum class LogLevel(str, Enum): DEBUG = 'DEBUG' INFO = 'INFO' Of course the point is to use this class as an enum, with all ... | When inheriting from str, or any other type, the resulting enum members are also that type. This means: they have all the methods of that type they can be used as that type and, most importantly, they will compare with other instances of that type That last point is the most important: because LogLevel.DEBUG is a str... | 10 | 13 |
60,729,170 | 2020-3-17 | https://stackoverflow.com/questions/60729170/python-opencv-converting-planar-yuv-420-image-to-rgb-yuv-array-format | I am trying to use OpenCV, version 4.1.0 through python to convert a planar YUV 4:2:0 image to RGB and am struggling to understand how to format the array to pass to the cvtColor function. I have all 3 channels as separate arrays and am trying to merge them for use with cv2.cvtColor. I am using cv2.cvtColor(yuv_array, ... | In case the YUV standard matches the OpenCV COLOR_YUV2BGR_I420 conversion formula, you may read the frame as one chunk, and reshape it to height*1.5 rows apply conversion. The following code sample: Builds an input in YUV420 format, and write it to memory stream (instead of fifo). Read frame from stream and convert ... | 6 | 10 |
60,728,640 | 2020-3-17 | https://stackoverflow.com/questions/60728640/modify-global-variable-from-async-function-in-python | I'm making a Discord bot in Python using discord.py. I'd like to set/modify a global variable from an async thread. message = "" @bot.command() async def test(ctx, msg): message = msg However this doesn't work. How can I achieve something that does this? | As I said in the comment you have to use the keyword global in the functions wherever you are modifying the global variable. If you are just reading it in function than you don't need it. message = "" @bot.command() async def test(ctx, msg): global message message = msg | 11 | 24 |
60,722,360 | 2020-3-17 | https://stackoverflow.com/questions/60722360/python-how-to-split-and-re-join-first-and-last-item-in-series-of-strings | I have a Series of strings, the series looks like; Series "1, 2, 6, 7, 6" "1, 3, 7, 9, 9" "1, 1, 3, 5, 6" "1, 2, 7, 7, 8" "1, 4, 6, 8, 9" "1" I want to remove all elements apart from the first and last, so the output would look like; Series "1, 6" "1, 9" "1, 6" "1, 8" "1, 9" "1" To use Split(), do I need to loop over... | You can use split and rsplit to get the various parts: result = [f"{x.split(',', 1)[0]},{x.rsplit(',', 1)[1]}" if x.find(',') > 0 else x for x in strings] If strings is a pd.Series object then you can convert it back to a series: result = pd.Series(result, index=strings.index) | 6 | 5 |
60,708,680 | 2020-3-16 | https://stackoverflow.com/questions/60708680/how-to-change-the-marker-symbol-of-errorbar-limits-in-matplotlib | just a quick question, where I couldn't find anything helpful in the plt.errorbar documentation I want to plot values with error bars: import matplotlib.pyplot as plt plt.errorbar(1, 0.25, yerr=0.1, uplims=True, lolims=True, fmt='o') plt.show() But I would like to have error bars with a simple horizontal line instead... | Remove the uplims=True and lolims=True; both limits are plotted by default, without any ending arrows: import matplotlib.pyplot as plt plt.errorbar(1, 0.25, yerr=0.1, fmt='o') plt.show() EDIT: Increase the capsize to add caps to the end of the error bars, and increase the capthick to make the caps thicker: plt.errorb... | 6 | 13 |
60,650,325 | 2020-3-12 | https://stackoverflow.com/questions/60650325/install-python2-on-a-mac-after-python-2-support-has-ended-on-homebrew | I would like to install a few packages from a github project and one of the dependencies is python@2. Prior to Jan 1 2020, it was possible to install python@2 using Homebrew: $ brew install python@2 However, Python 2 support has ended from Homebrew. Is there anyway to install python@2 on a Mac now that Python 2 suppo... | I was able to find the exact same question -- Brew - reinstalling python@2. Unfortunately I can't raise the duplicate flag again so I'll duplicate the answer: brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/86a44a0a552c673a05f11018459c9f5faae3becc/Formula/python@2.rb | 10 | 10 |
60,721,826 | 2020-3-17 | https://stackoverflow.com/questions/60721826/how-can-i-generate-n-random-values-from-a-bimodal-distribution-in-python | I tried generating and combining two unimodal distributions but think there's something wrong in my code. N=400 mu, sigma = 100, 5 mu2, sigma2 = 10, 40 X1 = np.random.normal(mu, sigma, N) X2 = np.random.normal(mu2, sigma2, N) w = np.random.normal(0.5, 1, N) X = w*X1 + (1-w)*X2 X = X.reshape(-1,2) When I plot X I don't... | It's unclear where your problem is; it's also unclear what the purpose of the variable w is, and it's unclear how you judge you get an incorrect result, since we don't see the plot code, or any other code to confirm or reject a binomial distribution. That is, your example is too incomplete to exactly answer your questi... | 6 | 16 |
60,720,213 | 2020-3-17 | https://stackoverflow.com/questions/60720213/pandas-get-rows-by-comparing-two-columns-of-dataframe-to-list-of-tuples | Say I have a pandas DataFrame with four columns: A,B,C,D. my_df = pd.DataFrame({'A': [0,1,4,9], 'B': [1,7,5,7],'C':[1,1,1,1],'D':[2,2,2,2]}) I also have a list of tuples: my_tuples = [(0,1),(4,5),(9,9)] I want to keep only the rows of the dataframe where the value of (my_df['A'],my_df['B']) is equal to one of the tup... | Use DataFrame.merge with DataFrame created by tuples, there is no on parameter for default interecton of all columns in both DataFrames, here A and B: df = my_df.merge(pd.DataFrame(my_tuples, columns=['A','B'])) print (df) A B C D 0 0 1 1 2 1 4 5 1 2 Or: df = my_df[my_df.set_index(['A','B']).index.isin(my_tuples)] pri... | 11 | 10 |
60,698,056 | 2020-3-15 | https://stackoverflow.com/questions/60698056/parquet-int96-timestamp-conversion-to-datetime-date-via-python | TL;DR I'd like to convert an int96 value such as ACIE4NxJAAAKhSUA into a readable timestamp format like 2020-03-02 14:34:22 or whatever that could be normally interpreted...I mostly use python so I'm looking to build a function that does this conversion. If there's another function that can do the reverse -- even bette... | parquet-tools will not be able to change format type from INT96 to INT64. What you are observing in json output is a String representation of the timestamp stored in INT96 TimestampType. You will need spark to re-write this parquet with timestamp in INT64 TimestampType and then the json output will produce a timestamp ... | 6 | 6 |
60,708,789 | 2020-3-16 | https://stackoverflow.com/questions/60708789/exceptions-vs-errors-in-python | I come from Java where Exceptions and Errors are quite different things and they both derive from something called Throwable. In Java normally you should never try to catch an Error. In Python though it seems the distinction is blurred. So far after reading some docs and checking the hierarchy I have the following ques... | Yes. SyntaxError isn't catchable except in cases of dynamically executed code (via eval/exec), because it occurs before the code is actually running. "Fatal" means "program dies regardless of what the code says"; that doesn't happen with exceptions in Python, they're all catchable. os._exit can forcibly kill the proce... | 41 | 42 |
60,700,187 | 2020-3-16 | https://stackoverflow.com/questions/60700187/how-can-i-pass-a-callback-to-re-sub-but-still-inserting-match-captures | Consider: text = "abcdef" pattern = "(b|e)cd(b|e)" repl = [r"\1bla\2", r"\1blabla\2"] text = re.sub(pattern, lambda m: random.choice(repl), text) I want to replace matches randomly with entries of a list repl. But when using lambda m: random.choice(repl) as a callback, it doesn't replace \1, \2 etc. with its captures ... | If you pass a function you lose the automatic escaping of backreferences. You just get the match object and have to do the work. So you could: Pick a string in the regex rather than passing a function: text = "abcdef" pattern = "(b|e)cd(b|e)" repl = [r"\1bla\2", r"\1blabla\2"] re.sub(pattern, random.choice(repl), text)... | 7 | 8 |
60,705,542 | 2020-3-16 | https://stackoverflow.com/questions/60705542/python-typeerror-expected-str-bytes-or-os-pathlike-object-not-io-textiowrapp | I am trying to convert a pipe-delimited text file to a CSV file, and then iterate through and print the CSV file. Here is my code: with open("...somefile.txt", "r") as text_file: text_reader = csv.reader(text_file, delimiter='|') with open("...somefile.csv", 'w') as csv_file: csv_writer = csv.writer(csv_file, delimite... | You're passing open an already opened file, rather than the path of the file you created. Replace: with open (csv_file, 'r') as f: with with open ("...somefile.csv", 'r') as f: To change the extension in a function: import pathlib def txt_to_csv(fname): new_name = f'{Path(fname).stem}.csv' with open(fname, "r") as t... | 8 | 6 |
60,690,327 | 2020-3-15 | https://stackoverflow.com/questions/60690327/typeerror-keyword-argument-not-understood-inputs | The following code is for disease detection with a CNN model using Tensorflow and Keras. For some reason, I keep getting an error. This is a TypeError with parameter 'inputs'. I don't understand why this error is being raised. Here is my code: from __future__ import absolute_import, division, print_function, unicode_li... | The error you are asking about (TypeError: ('Keyword argument not understood:', 'inputs')) is caused because you are capitalizing the conv2d function in your first convolutional layer. Change the following: conv1 = tf.compat.v1.layers.Conv2D( inputs = input_layers , filters = 50 , kernel_size = [7 , 7], padding = 'same... | 11 | 7 |
60,691,363 | 2020-3-15 | https://stackoverflow.com/questions/60691363/runtimeerrorfreeze-support-on-mac | I'm new on python. I want to learn how to parallel processing in python. I saw the following example: import multiprocessing as mp np.random.RandomState(100) arr = np.random.randint(0, 10, size=[20, 5]) data = arr.tolist() def howmany_within_range_rowonly(row, minimum=4, maximum=8): count = 0 for n in row: if minimum ... | If you place everything in global scope inside this if __name__ == "__main__" block as follows, you should find that your program behaves as you expect: def howmany_within_range_rowonly(row, minimum=4, maximum=8): count = 0 for n in row: if minimum <= n <= maximum: count = count + 1 return count if __name__ == "__main_... | 15 | 19 |
60,681,437 | 2020-3-14 | https://stackoverflow.com/questions/60681437/plotly-express-bar-chart-colour-change | How can I change the colour of the plotly express bar-chart to green in the following code? import plotly.express as px import pandas as pd # prepare the dataframe df = pd.DataFrame(dict( x=[1, 2, 3], y=[1, 3, 2] )) # prepare the layout title = "A Bar Chart from Plotly Express" fig = px.bar(df, x='x', y='y', # data fro... | It can be done: - with color_discrete_sequence =['green']*3, or, - with fig.update_traces(marker_color='green') after the bar is instantiated. Ref: Community response | 18 | 21 |
60,677,843 | 2020-3-13 | https://stackoverflow.com/questions/60677843/python-check-if-all-elements-in-a-list-are-nan | My code sometimes produces a list of nan's op_list = [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan]. I want to know if all elements are nans. My code and present output: op_list = [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan] print(np.isnan(op_list)) array([ True, True, True, True, True, True, True, True, T... | You need all: np.isnan(op_list).all() # True For a solution using lists you can do: all(i != i for i in op_list) # True | 16 | 41 |
60,674,501 | 2020-3-13 | https://stackoverflow.com/questions/60674501/how-to-make-black-background-in-cv2-puttext-with-python-opencv | I have a project of opencv where on the frame I am displaying some text using cv2.putText(). Currently it looks like below: As you can see on the top left corner, the text is present but its not clearly visible. Is it possible to make background black so that the text will then appear good. Something like below image:... | There's no prebuilt method but a simple appraoch is to use cv2.rectangle + cv2.putText. All you need to do is to draw the black rectangle on the image followed by placing the text. You can adjust the x,y,w,h parameters depending on how large/small you want the rectangle. Here's an example: Input image: Result: import... | 24 | 11 |
60,675,832 | 2020-3-13 | https://stackoverflow.com/questions/60675832/how-to-see-current-cache-size-when-using-functools-lru-cache | I am doing performance/memory analysis on a certain method that is wrapped with the functools.lru_cache decorator. I want to see how to inspect the current size of my cache without doing some crazy inspect magic to get to the underlying cache. Does anyone know how to see the current cache size of method decorated with ... | Digging around in the docs showed the answer is calling .cache_info() on the method. To help measure the effectiveness of the cache and tune the maxsize parameter, the wrapped function is instrumented with a cache_info() function that returns a named tuple showing hits, misses, maxsize and currsize. In a multi-threade... | 10 | 16 |
60,674,039 | 2020-3-13 | https://stackoverflow.com/questions/60674039/how-to-test-assert-whether-two-lists-of-dictionaries-where-a-dict-item-contains | I'm creating my first test script (yay!) I'm have a list of dictionaries where one of the keys is a list. I'd like the test to past if the list (in the dictionary) is in any order. I know you can use assertCountEqual to check list equality regardless of order, but can you do that for a list that contains a dictinary of... | The assertCountEqual(first, second, msg=None): Test that sequence first contains the same elements as second, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated. Important: Calling assertCountEqual(first, second, msg=None) is equivalent to call... | 6 | 5 |
60,671,987 | 2020-3-13 | https://stackoverflow.com/questions/60671987/django-orm-equivalent-of-sql-not-in-exclude-and-q-objects-do-not-work | The Problem I'm trying to use the Django ORM to do the equivalent of a SQL NOT IN clause, providing a list of IDs in a subselect to bring back a set of records from the logging table. I can't figure out if this is possible. The Model class JobLog(models.Model): job_number = models.BigIntegerField(blank=True, null=True)... | I think the easiest way to do this would be to define a custom lookup, similar to this one or the in lookup from django.db.models.lookups import In as LookupIn class NotIn(LookupIn): lookup_name = "notin" def get_rhs_op(self, connection, rhs): return "NOT IN %s" % rhs Field.register_lookup(NotIn) or class NotIn(model... | 9 | 9 |
60,664,637 | 2020-3-13 | https://stackoverflow.com/questions/60664637/sslerror-using-boto | We are using a proxy + profile when using the aws s3 commands to browse our buckets in CLI. export HTTPS_PROXY=https://ourproxyhost.com:3128 aws s3 ls s3://our_bucket/.../ --profile dev And we can work with our buckets and objects fine. Because I need to write Python code for this, I translated this using boto3: # pyt... | botocore.vendored.requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590) The error above in most cases it's usually related to the CA bundle being used for S3 connections. Possible Resolution Steps: 1. Turn off SSL certification validation : s3 = boto3.client('s3', verif... | 9 | 13 |
60,667,865 | 2020-3-13 | https://stackoverflow.com/questions/60667865/get-column-names-with-distinct-value-greater-than-specified-values-python | Dataframe X: A B C D V1 V2 V3 V4 V1 V3 V4 V5 V1 V4 V5 V5 V1 V5 V9 V5 V1 V2 V3 V4 V1 V10 V11 V12 V1 V10 V6 V8 V1 V12 V7 V8 Here Col A has 1 unique value, Col B has 6 unique values, Col C has 7 unique values, Col D has 4 unique values. I need a list of all columns where unique values > 4 say. X.columns[(X.nunique() > 4)... | You are really close, only remove .any for boolean mask: c = X.columns[(X.nunique() > 4)] print (c) Index(['B', 'C'], dtype='object') If need select columns use DataFrame.loc: df = X.loc[:, (X.nunique() > 4)] print (df) B C 0 V2 V3 1 V3 V4 2 V4 V5 3 V5 V9 4 V2 V3 5 V10 V11 6 V10 V6 7 V12 V7 | 6 | 7 |
60,662,784 | 2020-3-12 | https://stackoverflow.com/questions/60662784/csv-standard-multiple-tables | I am working on a python project that does some analysis on csv files. I know there is no well-definedstandard for csv files, but as far as I understood the definition (https://www.rfc-editor.org/rfc/rfc4180#page-2), I think that a csv file should not contain more than one table. Is this thinking correct, or did I misu... | You are correct. There is no universal accepted standard. The definition is written to suggest that each file contains one table, and this is by far the most common practice. There's technically nothing stopping you from having more than one table, using a format you decide on and implement and keep consistent. For ins... | 10 | 9 |
60,657,399 | 2020-3-12 | https://stackoverflow.com/questions/60657399/what-does-abc-class-do | I wrote a class that inherits another class: class ValueSum(SubQuery): output = IntegerField() And pycharm is showing the following warning: Class ValueSum must implement all abstract methods Then I alt+enter to add ABC to superclass. And my warning is gone. I have several questions: Should I always do this when wr... | SubQuery is an abstract base class (per the abc module) with one or more abstract methods that you did not override. By adding ABC to the list of base classes, you defined ValueSum itself to be an abstract base class. That means you aren't forced to override the methods, but it also means you cannot instantiate ValueSu... | 11 | 10 |
60,655,270 | 2020-3-12 | https://stackoverflow.com/questions/60655270/mypy-fails-to-infer-enums-being-created-from-a-list-variable | Enums can be created by taking in a list of possible members, which I'm doing like so: # example_issue.py import enum yummy_foods = ["ham", "cheese"] foods = enum.Enum("Foods", yummy_foods) cheese = foods.cheese This looks OK, and runs fine, but mypy returns example_issue.py:4: error: Enum() expects a string, tuple, l... | Using a variable yummy_foods is too dynamic for mypy's static type checking, see this GitHub issue. If you change your code to generate the Enum as: foods = enum.Enum("Foods", ["ham", "cheese"]) mypy will then be able to figure out which attributes exist on the enumeration. | 7 | 6 |
60,654,781 | 2020-3-12 | https://stackoverflow.com/questions/60654781/typeerror-cannot-perform-rand-with-a-dtyped-float64-array-and-scalar-of-ty | I ran a command in python pandas as follows: q1_fisher_r[(q1_fisher_r['TP53']==1) & q1_fisher_r[(q1_fisher_r['TumorST'].str.contains(':1:'))]] I got following error: TypeError: Cannot perform 'rand_' with a dtyped [float64] array and scalar of type [bool] the solution i tried using this: error link. changed the code ... | For filtering by multiple conditions chain them by & and filter by boolean indexing: q1_fisher_r[(q1_fisher_r['TP53']==1) & q1_fisher_r['TumorST'].str.contains(':1:')] ^^^^ ^^^^ first condition second condition Problem is this code returned filtered data, so cannot chain by condition: q1_fisher_r[(q1_fisher_r['TumorST... | 52 | 41 |
60,635,118 | 2020-3-11 | https://stackoverflow.com/questions/60635118/drf-how-to-change-the-value-of-the-model-fields-before-saving-to-the-database | If I need to change some field values before saving to the database as I think models method clear() is suitable. But I can't call him despite all my efforts. For example fields email I need set to lowercase and fields nda I need set as null models.py class Vendors(models.Model): nda = models.DateField(blank=True, nul... | For DRF you can change your serializer before save as below... First of all, you should check that serializer is valid or not, and if it is valid then change the required object of the serializer and then save that serializer. if serializer.is_valid(): serializer.object.user_id = 15 # For example serializer.save() UPD... | 7 | 5 |
60,632,275 | 2020-3-11 | https://stackoverflow.com/questions/60632275/python-typing-is-there-a-way-to-avoid-importing-of-optional-type-if-its-none | Let's say we have a function definition like this: def f(*, model: Optional[Type[pydantic.BaseModel]] = None) So the function doesn't require pydantic to be installed until you pass something as a model. Now let's say we want to pack the function into pypi package. And my question is if there's a way to avoid bringing... | I tried to follow dspenser's advice, but I found mypy still giving me Name 'pydantic' is not defined error. Then I found this chapter in the docs and it seems to be working in my case too: from typing import TYPE_CHECKING if TYPE_CHECKING: import pydantic You can use normal clases (instead of string literals) with __f... | 6 | 9 |
60,646,431 | 2020-3-12 | https://stackoverflow.com/questions/60646431/how-to-use-multiprocessing-manager-value-to-store-a-sum | I want to accumulate a sum using multiprocessing.Pool. Here's how I tried: import multiprocessing def add_to_value(addend, value): value.value += addend with multiprocessing.Manager() as manager: value = manager.Value(float, 0.0) with multiprocessing.Pool(2) as pool: pool.starmap(add_to_value, [(float(i), value) for i ... | The multiprocessing documentation (under multiprocessing.Value) is quite explicit about this: Operations like += which involve a read and write are not atomic. So if, for instance, you want to atomically increment a shared value it is insufficient to just do counter.value += 1. In short, you need to grab a lock to be... | 6 | 7 |
60,650,432 | 2020-3-12 | https://stackoverflow.com/questions/60650432/merging-csv-files-with-different-headers-with-pandas-in-python | I'm trying to map a dataset to a blank CSV file with different headers, so I'm essentially trying to map data from one CSV file which has different headers to a new CSV with different amount of headers and called different things, the reason this question is different is since the column names aren't the same but there... | From your example, it looks like you need to do some column renaming in addition to the merge. This is easiest done before the merge itself. # Read the csv files dfA = pd.read_csv("a.csv") dfB = pd.read_csv("b.csv") # Rename the columns of b.csv that should match the ones in a.csv dfB = dfB.rename(columns={'MEASUREMEN... | 8 | 2 |
60,637,120 | 2020-3-11 | https://stackoverflow.com/questions/60637120/detect-circles-in-opencv | I have a problem with choosing right parameters for HoughCircles function. I try to detect circles from video. This circles are made by me, and has almost the same dimension. Problem is that camera is in move. When I change maxRadius it still detect bigger circles somehow (see the right picture). I also tried to chang... | The main problem in your code is 5th argument to HoughCircles function. According to documentation the argument list is: cv2.HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]]) → circles That means the 5th argument applies circles (it gives an option getting the output by... | 15 | 12 |
60,644,482 | 2020-3-11 | https://stackoverflow.com/questions/60644482/easy-way-to-copy-output-from-jupyter-to-paste-in-excel | I'm trying to find a simple way to change the standard output that I get in Jupyter in order to copy and paste tables ouputs in Excel. For example a simple value_counts() give this kind of output in Jupyter lab/notebook: 0 1030971 1 8766 Is there a simple way to mark, copy and paste keeping the format? Even better, cou... | Assuming your DataFrame is named "df", run this line and you'll save the data to your clipboard, letting you paste it where you need to. df.to_clipboard(excel=True) | 7 | 15 |
60,642,466 | 2020-3-11 | https://stackoverflow.com/questions/60642466/how-do-i-select-where-in-values-with-tuples-in-python-sqlite3 | I have an SQLite database with three columns, and I'm trying to use parameter substitution for tuples to SELECT rows. This is my table: conn = sqlite3.connect("SomeDb.sqlite3") conn.execute(""" CREATE TABLE RoadSegmentDistribution( Source INTEGER, Destination INTEGER, Distribution TEXT ) """) I know how to substitute ... | Using the str.join method is indeed a good way to achieve this, given the lack of native support for container-based placeholders in SQL engines: values = [(1, 2), (2, 3), (4, 5), (6, 7), (8, 9)] for e in conn.execute(f""" SELECT * FROM RoadSegmentDistribution WHERE ( Source, Destination ) IN (VALUES {','.join(f'({","... | 7 | 6 |
60,643,344 | 2020-3-11 | https://stackoverflow.com/questions/60643344/can-a-function-be-a-python-dataclass-member | I'm trying to keep some functions together and tried a Python dataclass for this. I could not come up with or find how to assign a type to a function within a dataclass. In example below I used a dummy type int, but what I should use correctly instead of int? from dataclasses import dataclass inc = lambda x : x+1 @dat... | You should use the Callable type from typing import Callable @dataclass class Holder: func: Callable[[int], int] | 13 | 17 |
60,641,215 | 2020-3-11 | https://stackoverflow.com/questions/60641215/one-to-many-relationship-django | I am coding up a dictionary using Django. I want a word to have multiple definitions, if necessary. This would be a one-to-many relationship, but Django does not seem to have a OneToManyField. This is a snippet of my code: class Definition(models.Model): definition = models.CharField(max_length=64) class Word(models.Mo... | You have to use ForeignKey in Definition class. Definition will have relation to Word: from django.db import models class Definition(models.Model): definition = models.CharField(max_length=64) word = models.ForeignKey(Word, on_delete=models.CASCADE) class Word(models.Model): word = models.CharField(max_length=64, uniqu... | 6 | 7 |
60,638,356 | 2020-3-11 | https://stackoverflow.com/questions/60638356/difference-between-pip-install-and-pip-install-e | I have created a package in python, and now I would like to install it as a regular package. What is the difference between just using pip3 install . and pip3 install -e . ? The reason why I asked, is because with pip3 install . the package, although installed was not seen by the system. While in the second way it was... | The -e flag tells pip to install in editable mode: -e,--editable <path/url> Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url. https://manpages.debian.org/stretch/python-pip/pip.1 So what is editable mode or setuptools "develop mode" ? This command allows you t... | 7 | 8 |
60,636,444 | 2020-3-11 | https://stackoverflow.com/questions/60636444/what-is-the-difference-between-x-test-x-train-y-test-y-train-in-sklearn | I'm learning sklearn and I didn't understand very good the difference and why use 4 outputs with the function train_test_split(). In the Documentation, I found some examples but it wasn't sufficient to end my doubts. Does the code use the X_train to predict the X_test or use the X_train to predict the y_test? What is t... | Below is a dummy pandas.DataFrame for example: import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, confusion_matrix, classification_report df = pd.DataFrame({'X1':[100,120,140,200,230,400,500,540,600,625... | 18 | 37 |
60,635,934 | 2020-3-11 | https://stackoverflow.com/questions/60635934/get-second-minimum-values-per-column-in-2d-array | How can I get the second minimum value from each column? I have this array: A = [[72 76 44 62 81 31] [54 36 82 71 40 45] [63 59 84 36 34 51] [58 53 59 22 77 64] [35 77 60 76 57 44]] I wish to have output like: A = [54 53 59 36 40 44] | Try this, in just one line: [sorted(i)[1] for i in zip(*A)] in action: In [12]: A = [[72, 76, 44, 62, 81, 31], ...: [54 ,36 ,82 ,71 ,40, 45], ...: [63 ,59, 84, 36, 34 ,51], ...: [58, 53, 59, 22, 77 ,64], ...: [35 ,77, 60, 76, 57, 44]] In [18]: [sorted(i)[1] for i in zip(*A)] Out[18]: [54, 53, 59, 36, 40, 44] zip(*A)... | 17 | 12 |
60,585,818 | 2020-3-8 | https://stackoverflow.com/questions/60585818/what-does-it-mean-to-inherit-global-site-packages-in-pycharm | When creating a new Python project, why would I want to select this option? If I don't select it, what functionality am I missing out on? Would I not be able to import certain Python modules? | It's just an option to pre-install some packages that you're using everytime, or if it doesn't bother you to have extra packages in your local python interpreted select it : all packages installed in the global python of your machine will be accessible for the interpreter you're going to create in the virtualenv. do n... | 22 | 11 |
60,618,346 | 2020-3-10 | https://stackoverflow.com/questions/60618346/pytorch-autograd-gives-different-gradients-when-using-clamp-instead-of-torch-re | I'm still working on my understanding of the PyTorch autograd system. One thing I'm struggling at is to understand why .clamp(min=0) and nn.functional.relu() seem to have different backward passes. It's especially confusing as .clamp is used equivalently to relu in PyTorch tutorials, such as https://pytorch.org/tutoria... | The reason is that relu and clamp produce different gradients at 0. For a scalar tensor x = 0: (relu(x) - 1.0).pow(2).backward() gives x.grad == 0 (x.clamp(min=0) - 1.0).pow(2).backward() gives x.grad == -2 This indicates that: relu chooses x == 0 --> grad = 0 clamp chooses x == 0 --> grad = 1 | 9 | 8 |
60,584,388 | 2020-3-8 | https://stackoverflow.com/questions/60584388/how-to-check-typevars-type-at-runtime | I have a generic class Graph(Generic[T]). Is there a function that returns the type arguments passed to the class Graph? >>> g = Graph[int]() >>> magic_func(g) <class 'int'> | Here is one way to achieve this which works from Python 3.6+ (tested it in 3.6, 3.7 and 3.8): from typing import TypeVar, Generic T = TypeVar('T') class Graph(Generic[T], object): def get_generic_type(self): print(self.__orig_class__.__args__[0]) if __name__=='__main__': g_int = Graph[int]() g_str = Graph[str]() g_int.... | 9 | 7 |
60,536,472 | 2020-3-5 | https://stackoverflow.com/questions/60536472/building-python-and-openssl-from-source-but-ssl-module-fails | I'm trying to build Python and OpenSSL from source in a container. Both seem to build correctly, but Python does not successfully create the _ssl module. I've found a few guides online that say to un-comment and lines from Python-3.X.X/Modules/Setup and add the --openssldir=/usr/local/ssl flag to the ./configure step f... | The following worked for me on Amazon's EC2, with the default CentOS 7 system. First, the openssl libraries on CentOS 7 are too old (Python 3.9+ wants openssl 1.1.1+ and the version available is 1.0.x). Install the newer ones: sudo yum install openssl11-devel Note: since writing this answer, Amazon has end-of-life'd t... | 7 | 15 |
60,567,732 | 2020-3-6 | https://stackoverflow.com/questions/60567732/poetry-force-install-when-versions-are-incompatible | Poetry has a very good version solver, too good sometimes :) I'm trying to use poetry in a project that uses two incompatible packages. However they are incompatible only by declaration as one of them is no longer developed, but otherwise they work together just fine. With pip I'm able to install these in one environme... | No. Alternative solutions might be: contacting the offending package's maintainers and asking for a fix + release forking the package and releasing a fix yourself vendoring the package in your source code - there is no need to install it if it's already there, and many of the usual downsides to vendoring disappear if... | 21 | 11 |
60,615,531 | 2020-3-10 | https://stackoverflow.com/questions/60615531/creating-dynamic-classes-in-sqlalchemy | We have 1 table with a large amount of data and DBA's partitioned it based on a particular parameter. This means I ended up with Employee_TX, Employee_NY kind of table names. Earlier the models.py was simple as in -- class Employee(Base): __tablename__ = 'Employee' name = Column... state = Column... Now, I don't want ... | Got it by creating a custom function like - def get_model(state): DynamicBase = declarative_base(class_registry=dict()) class MyModel(DynamicBase): __tablename__ = 'Employee_{}'.format(state) name = Column... state = Column... return MyModel And then from my services.py, I just call with get_model(TX) | 7 | 7 |
60,580,332 | 2020-3-7 | https://stackoverflow.com/questions/60580332/poetry-virtual-environment-already-activated | Running the following poetry shell returns the following error /home/harshagoli/.poetry/lib/poetry/_vendor/py2.7/subprocess32.py:149: RuntimeWarning: The _posixsubprocess module is not being used. Child process reliability may suffer if your program uses threads. "program uses threads.", RuntimeWarning) The currently ... | poetry shell is a really buggy command, and this is often talked about among the maintainers. A workaround for this specific issue is to activate the shell manually. It might be worth aliasing the following source $(poetry env info --path)/bin/activate so you need to paste this into your .bash_aliases or .bashrc alias... | 41 | 54 |
60,532,973 | 2020-3-4 | https://stackoverflow.com/questions/60532973/how-do-i-get-a-is-safe-url-function-to-use-with-flask-and-how-does-it-work | Flask-Login recommends having an is_safe_url() function after user login: Here is a link to the part of the documentation that discusses this: https://flask-login.readthedocs.io/en/latest/#login-example They link to this snippet but I don't understand how it implements is_safe_url(): https://palletsprojects.com/p/flask... | As mentioned in the comments, Flask-Login today had a dead link in the documentation (issue on GitHub). Please note the warning in the original flask snippets documentation: Snippets are unofficial and unmaintained. No Flask maintainer has curated or checked the snippets for security, correctness, or design. The snip... | 19 | 26 |
60,558,412 | 2020-3-6 | https://stackoverflow.com/questions/60558412/how-to-decode-a-video-memory-file-byte-string-and-step-through-it-frame-by-f | I am using python to do some basic image processing, and want to extend it to process a video frame by frame. I get the video as a blob from a server - .webm encoded - and have it in python as a byte string (b'\x1aE\xdf\xa3\xa3B\x86\x81\x01B\xf7\x81\x01B\xf2\x81\x04B\xf3\x81\x08B\x82\x88matroskaB\x87\x81\x04B\x85\x81\x... | Two years after Rotem wrote his answer there is now a cleaner / easier way to do this using ImageIO. Note: Assuming ffmpeg is in your path, you can generate a test video to try this example using: ffmpeg -f lavfi -i testsrc=duration=10:size=1280x720:rate=30 testsrc.webm import imageio.v3 as iio from pathlib import Path... | 7 | 6 |
60,599,149 | 2020-3-9 | https://stackoverflow.com/questions/60599149/what-is-the-difference-between-numpy-randoms-generator-class-and-np-random-meth | I have been using numpy's random functionality for a while, by calling methods such as np.random.choice() or np.random.randint() etc. I just now found about the ability to create a default_rng object, or other Generator objects: from numpy.random import default_rng gen = default_rng() random_number = gen.integers(10) ... | numpy.random.* functions (including numpy.random.binomial) make use of a global pseudorandom number generator (PRNG) object which is shared across the application. On the other hand, default_rng() is a self-contained Generator object that doesn't rely on global state. If you don't care about reproducible "randomness" i... | 8 | 13 |
60,593,604 | 2020-3-9 | https://stackoverflow.com/questions/60593604/importerror-attempted-relative-import-with-no-known-parent-package | I am learning to program with python and I am having issues with importing from a module in a package. I am usingvisual studio code with Python 3.8.2 64 bit. My Project Directory .vscode ├── ecommerce │ ├── __init__.py │ ├── database.py │ ├── products.py │ └── payments │ ├── __init__.py │ ├── authorizenet.py │ └── payp... | It seems, from Python docs and experimenting, that relative imports (involving ., .. etc) only work if the importing module has a __name__ other than __main__, and further, the __name__ of the importing module is pkg.module_name, i.e., it has to be imported from above in the directory hierarchy (to have a parent pkg a... | 139 | 37 |
60,599,812 | 2020-3-9 | https://stackoverflow.com/questions/60599812/how-can-i-customize-mplfinance-plot | I've made a python script to convert a csv file in a candlestick like this using mpl_finance, this is the script: import matplotlib.pyplot as plt from mpl_finance import candlestick_ohlc import pandas as pd import matplotlib.dates as mpl_dates plt.style.use('ggplot') # Extracting Data for plotting data = pd.read_csv('C... | The best way to do this is to define your own style using mpf.make_mpf_style() rather than using the default mpf styles. If using external axes method in mplfinance, you can plot multiple charts as below: # add your own style by passing in kwargs s = mpf.make_mpf_style(base_mpf_style='charles', rc={'font.size': 6}) fig... | 21 | 18 |
60,600,529 | 2020-3-9 | https://stackoverflow.com/questions/60600529/cannot-import-name-string-int-label-map-pb2 | My goal is to run tensorflow object detection API and followed the steps in the installation. I install the tensorflow object detection API and protobuf. I have also added the path to protobuf. But the following error shoots up: ImportError: cannot import name 'string_int_label_map_pb2' Installed protobuf : %%bash cd ... | Install protoc-3.11.4 from https://github.com/google/protobuf/releases and run protoc object_detection/protos/*.proto --python_out=. as mentioned in the installation instructions. And put this file in in object detection/protos | 8 | 13 |
60,616,430 | 2020-3-10 | https://stackoverflow.com/questions/60616430/mlflow-how-to-read-metrics-or-params-from-an-existing-run | I try to read metrics in this way: data, info = mlflow.get_run(run_id) print(data[1].metrics) # example of output: {'loss': 0.01} But it get only last value. It is possible to read manually all steps of a particular metric? | I ran into this same problem and was able to do get all of the values for the metric by using using mlflow.tracking.MlflowClient().get_metric_history. This will return every value you logged using mlflow.log_metric(key, value). Quick example (untested) import mlflow trackingDir = 'file:///....' registryDir = 'file:///.... | 7 | 12 |
60,607,824 | 2020-3-9 | https://stackoverflow.com/questions/60607824/pytorch-imagenet-dataset | I am unable to download the original ImageNet dataset from their official website. However, I found out that pytorch has ImageNet as one of it’s torch vision datasets. Q1. Is that the original ImageNet dataset? Q2. How do I get the classes for the dataset like it’s being done in Cifar-10 classes = [‘airplane’, ‘automob... | The torchvision.datasets.ImageNet is just a class which allows you to work with the ImageNet dataset. You have to download the dataset yourself (e.g. from http://image-net.org/download-images) and pass the path to it as the root argument to the ImageNet class object. Note that the option to download it directly by pass... | 11 | 17 |
60,532,678 | 2020-3-4 | https://stackoverflow.com/questions/60532678/what-is-the-difference-between-miniconda-and-miniforge | The miniforge installer is a relatively new, community-led, minimal conda installer that (as it says in its readme) "can be directly compared to Miniconda, with the added feature that conda-forge is the default channel". It is unclear what is different between miniforge and Miniconda, or what the miniforge use case is.... | miniforge is the community (conda-forge) driven minimalistic conda installer. Subsequent package installations come thus from conda-forge channel. miniconda is the Anaconda (company) driven minimalistic conda installer. Subsequent package installations come from the anaconda channels (default or otherwise). miniforge s... | 91 | 84 |
60,582,050 | 2020-3-7 | https://stackoverflow.com/questions/60582050/lightgbmerror-do-not-support-special-json-characters-in-feature-name-the-same | I have the following code: most_important = features_importance_chi(importance_score_tresh, df_user.drop(columns = 'CHURN'),churn) X = df_user.drop(columns = 'CHURN') churn[churn==2] = 1 y = churn # handle undersample problem X,y = handle_undersampe(X,y) # train the model X=X.loc[:,X.columns.isin(most_important)].valu... | You know what, this message is often found on LGBMClassifier () models, i.e. LGBM. Simply drop this line at the beginning as soon as you upload the data from the pandas and you have a problem with your head: import re df = df.rename(columns = lambda x:re.sub('[^A-Za-z0-9_]+', '', x)) | 12 | 41 |
60,580,113 | 2020-3-7 | https://stackoverflow.com/questions/60580113/change-python-version-to-3-x | According to poetry's docs, the proper way to setup a new project is with poetry new poetry-demo, however this creates a project based on the now deprecated python2.7 by creating the following toml file: [tool.poetry] name = "poetry-demo" version = "0.1.0" description = "" authors = ["Harsha Goli <harshagoli@gmail.com>... | Interestingly, poetry is silently failing due to a missing package the tool itself relies on and continues to install a broken venv. Here's how you fix it. sudo apt install python3-venv poetry env remove python3 poetry install I had to remove pytest, and then reinstall with poetry add pytest. EDIT: I ran into this iss... | 118 | 13 |
60,557,160 | 2020-3-6 | https://stackoverflow.com/questions/60557160/python3-8-fails-with-fatal-python-error-config-get-locale-encoding | OK, so somehow I have mangled my python3 installation under macOS Mojave and I'm not sure how. I've used macports for years to keep python up to date but when I installed python38 now I cannot run python3 at all. I always get this: $ python3.8 Fatal Python error: config_get_locale_encoding: failed to get the locale enc... | Try setting LANG with a locale: export LANG="en_US.UTF-8" | 22 | 58 |
60,624,139 | 2020-3-10 | https://stackoverflow.com/questions/60624139/when-i-do-flask-run-it-shows-error-modulenotfounderror-no-module-named-werk | the exact error I get is : flask.cli.NoAppException: While importing "application", an ImportError was raised:Traceback (most recent call last): File "/home/harshit/.local/lib/python3.6/site-packages/flask/cli.py", line 240, in locate_app __import__(module_name) File "/home/harshit/Documents/project1/application.py", l... | Werkzeug 1.0.0 has removed deprecated code, including all of werkzeug.contrib. You should use alternative libraries for new projects. werkzeug.contrib.session was extracted to secure-cookie. If an existing project you're using needs something from contrib, you'll need to downgrade to Werkzeug<1: pip3 install Werkzeug<... | 20 | 23 |
60,537,977 | 2020-3-5 | https://stackoverflow.com/questions/60537977/critical-worker-timeout-in-logs-when-running-hello-cloud-run-with-python-f | Following the tutorial here I have the following 2 files: app.py from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET']) def hello(): """Return a friendly HTTP greeting.""" who = request.args.get('who', 'World') return f'Hello {who}!\n' if __name__ == '__main__': # Used when running loca... | Cloud Run has scaled down one of your instances, and the gunicorn arbiter is considering it stalled. You should add --timeout 0 to your gunicorn invocation to disable the worker timeout entirely, it's unnecessary for Cloud Run. | 30 | 42 |
60,623,869 | 2020-3-10 | https://stackoverflow.com/questions/60623869/gradcam-with-guided-backprop-for-transfer-learning-in-tensorflow-2-0 | I get an error using gradient visualization with transfer learning in TF 2.0. The gradient visualization works on a model that does not use transfer learning. When I run my code I get the error: assert str(id(x)) in tensor_dict, 'Could not compute output ' + str(x) AssertionError: Could not compute output Tensor("blo... | I figured it out. If you set up the model extending the vgg16 base model with your own layers, rather than inserting the base model into a new model like a layer, then it works. First set up the model and be sure to declare the input_tensor. inp = layers.Input(shape=(imsize[0], imsize[1], imsize[2])) base_model = tf.k... | 8 | 6 |
60,625,834 | 2020-3-10 | https://stackoverflow.com/questions/60625834/create-interactive-hierarchy-diagram-from-pandas-dictionary | I have data that shows the relationship for each employee with their managers(Person:Manager) - data = {'PersonX':'Person1', 'PersonY':'Person1', 'PersonZ':'Person 2', 'Person1':'Person100','Person2':'Person100' } I am trying to show a hierarchy chart from the above data in a clean looking chart and if I can filter th... | I went with the following code to create a graph that was interactive, this is a work in progress but I wanted to post this so that people can use this in case needed. import pandas as pd import dash import dash_html_components as html import dash_cytoscape as cyto from matplotlib import colors as mcolors from itertool... | 8 | 4 |
60,562,759 | 2020-3-6 | https://stackoverflow.com/questions/60562759/incorrect-results-with-annotate-values-union-in-django | Jump to edit to see more real-life code example, that doesn't work after changing the query order Here are my models: class ModelA(models.Model): field_1a = models.CharField(max_length=32) field_2a = models.CharField(max_length=32) class ModelB(models.Model): field_1b = models.CharField(max_length=32) field_2b = models... | After some debugging and going through the source code, I have an idea why this is happening. What I am going to do is try to explain that why doing annotate + values results in displaying the id and what is the difference between the two cases above. To keep things simple, I will write also write the possible resultin... | 10 | 5 |
60,590,442 | 2020-3-8 | https://stackoverflow.com/questions/60590442/abstract-dataclass-without-abstract-methods-in-python-prohibit-instantiation | Even if a class is inherited from ABC, it can still be instantiated unless it contains abstract methods. Having the code below, what is the best way to prevent an Identifier object from being created: Identifier(['get', 'Name'])? from abc import ABC from typing import List from dataclasses import dataclass @dataclass c... | You can create a AbstractDataclass class which guarantees this behaviour, and you can use this every time you have a situation like the one you described. @dataclass class AbstractDataclass(ABC): def __new__(cls, *args, **kwargs): if cls == AbstractDataclass or cls.__bases__[0] == AbstractDataclass: raise TypeError("Ca... | 16 | 24 |
60,575,662 | 2020-3-7 | https://stackoverflow.com/questions/60575662/how-to-update-plotly-express-treemap-to-have-both-label-as-well-as-the-value-ins | Currently, plotly express treemap shows only label inside treemap. How to include the value alongside the label? | That's why I don't like express, there are too many limitations and to make these kinds of changes you have to access the trace either way. From my point of view it is better and more code-transparent to use plain plotly instead. That being said, you can access the textinfo attribute of the trace to do this. From the r... | 9 | 22 |
60,590,333 | 2020-3-8 | https://stackoverflow.com/questions/60590333/increasing-each-element-of-a-tensor-by-the-predecessor-in-tensorflow-2-0 | I'm new to tensorflow 2.0, and haven't done much except designing and training some artificial neural networks from boilerplate code. I'm trying to solve an exercise for newcomers into the new tensorflow. I created some code, but it doesn't work. Below is the problem definition: Assuming we have tensor M of rational n... | I'll give you a couple of different methods to implement that. I think the most obvious solution is to use tf.scan: import tensorflow as tf def apply_momentum_scan(m, p, axis=0): # Put axis first axis = tf.convert_to_tensor(axis, dtype=tf.int32) perm = tf.concat([[axis], tf.range(axis), tf.range(axis + 1, tf.rank(m))],... | 7 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.