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 |
|---|---|---|---|---|---|---|
69,462,888 | 2021-10-6 | https://stackoverflow.com/questions/69462888/converting-spherical-coordinates-into-cartesian-and-then-converting-back-into-ca | I'm trying to write two functions for converting Cartesian coordinates to spherical coordinates and vice-versa. Here are the equations that I've used for the conversions (also could be found on this Wikipedia page): And Here is my spherical_to_cartesian function: def spherical_to_cartesian(theta, phi): x = math.cos(p... | You seem to be giving your angles in degrees, while all trigonometric functions expect radians. Multiply degrees with math.pi/180 to get radians, and multiply radians with 180/math.pi to get degrees. | 6 | 5 |
69,462,119 | 2021-10-6 | https://stackoverflow.com/questions/69462119/determine-the-range-of-a-value-using-a-look-up-table | I have a df with numbers: numbers = pd.DataFrame(columns=['number'], data=[ 50, 65, 75, 85, 90 ]) and a df with ranges (look up table): ranges = pd.DataFrame( columns=['range','range_min','range_max'], data=[ ['A',90,100], ['B',85,95], ['C',70,80] ] ) I want to determine what range (in second table) a value (in the f... | You can use a bit of numpy vectorial operations to generate masks, and use them to select your labels: import numpy as np a = numbers['number'].values # numpy array of numbers r = ranges.set_index('range') # dataframe of min/max with labels as index m1 = (a>=r['range_min'].values[:,None]).T # is number above each min m... | 8 | 7 |
69,396,320 | 2021-9-30 | https://stackoverflow.com/questions/69396320/could-not-install-packages-due-to-an-environmenterror-winerror-5-access-is-de | ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\Users\Sampath\anaconda3\Lib\site-packages\~5py\defs.cp38-win_amd64.pyd' Consider using the --user option or check the permissions. I tried pip install mediapipe | EnvironmentError: Access is denied errors usually stem from one of three reasons: You do not have the proper permissions to install these files, and you should try running the same commands in an Administrator Command Prompt. 90% of the time, this should solve the problem. You don't have permission to install the pack... | 10 | 23 |
69,446,189 | 2021-10-5 | https://stackoverflow.com/questions/69446189/python-equivalent-for-typedef | What is the python way to define a (non-class) type like: typedef Dict[Union[int, str], Set[str]] RecordType | This would simply do it? from typing import Dict, Union, Set RecordType = Dict[Union[int, str], Set[str]] def my_func(rec: RecordType): pass my_func({1: {'2'}}) my_func({1: {2}}) This code will generate a warning from your IDE on the second call to my_func, but not on the first. As @sahasrara62 indicated, more here ht... | 27 | 31 |
69,388,833 | 2021-9-30 | https://stackoverflow.com/questions/69388833/triggering-a-function-on-creation-of-an-pydantic-object | is there a clean way of triggering a function call whenever I create/ instantiate a pydantic object? Currently I am "misusing" the root_validator for this: from pydantic import BaseModel class PydanticClass(BaseModel): name: str @root_validator() def on_create(cls, values): print("Put your logic here!") return values ... | Your intentions are not fully clear. But I can suggest overriding the __init__ model method. In this case, your code will be executed once at object instantiation: from pydantic import BaseModel class PydanticClass(BaseModel): name: str def __init__(self, **data) -> None: super().__init__(**data) print("Put your logic ... | 7 | 11 |
69,433,904 | 2021-10-4 | https://stackoverflow.com/questions/69433904/assigning-pydantic-fields-not-by-alias | How can I create a pydantic object, without useing alias names? from pydantic import BaseModel, Field class Params(BaseModel): var_name: int = Field(alias='var_alias') Params(var_alias=5) # works Params(var_name=5) # does not work | As of the pydantic 2.0 release, this behaviour has been updated to use model_config populate_by_name option which is False by default. from pydantic import BaseModel, Field, ConfigDict class Params(BaseModel): var_name: int = Field(alias='var_alias') model_config = ConfigDict( populate_by_name=True, ) Params(var_alias=... | 45 | 65 |
69,381,312 | 2021-9-29 | https://stackoverflow.com/questions/69381312/importerror-cannot-import-name-from-collections-using-python-3-10 | I am trying to run my program which uses various dependencies, but since upgrading to Python 3.10 this does not work anymore. When I run "python3" in the terminal and from there import my dependencies I get an error: ImportError: cannot import name 'Mapping' from 'collections' (/Library/Frameworks/Python.framework/Vers... | Change: from collections import Mapping to from collections.abc import Mapping | 80 | 96 |
69,435,073 | 2021-10-4 | https://stackoverflow.com/questions/69435073/what-is-the-correct-way-of-using-typing-literal | My code looks something like this, which runs fine BDW without any errors from typing import Literal def verify(word: str) -> Literal['Hello XY']: a = 'Hello ' + word return a a = verify('XY') Although, when I'm trying to do the type-checking using mypy, it throws an error error: Incompatible return value type (got "s... | word can be any string, so this seems like a good thing that mypy complains because it cannot guess that you will always call it with the appropriate argument. In other words, for mypy, if you concatenate 'Hello ' with some str, it can give any str and not only 'Hello XY'. What you could do to check if the function is ... | 12 | 14 |
69,445,500 | 2021-10-5 | https://stackoverflow.com/questions/69445500/setuptools-distribute-package-composed-of-a-single-module | I'm learning how to distribute python packages using setuptools and I have a problem. setuptools is setting the name of the folder containing a single python file as the name of my package. Below is the structure of my repository: gerador_endereco/ -- setup.py -- my_package/ -- __init__.py -- gerador_endereco.py My se... | setuptools is related to the distribution of packages, period. To install a module restructure you project: gerador_endereco/ -- setup.py -- gerador_endereco.py and change setup.py; remove packages=find_packages(), and add py_modules = ['gerador_endereco'] instead. See the docs at https://docs.python.org/3/distutils... | 4 | 7 |
69,403,103 | 2021-10-1 | https://stackoverflow.com/questions/69403103/functionally-is-torch-multinomial-the-same-as-torch-distributions-categorical-ca | For example, if I provide a probability array of [0.5, 0.5], both functions will sample the index [0,1] with equal probability? | Yes: [torch.distributions.categorical.Categorical()] is equivalent to the distribution that torch.multinomial() samples from. https://pytorch.org/docs/stable/distributions.html#categorical | 7 | 7 |
69,381,928 | 2021-9-29 | https://stackoverflow.com/questions/69381928/why-arent-augmented-assignment-expressions-allowed | I was recently reading over PEP 572 on assignment expressions and stumbled upon an interesting use case: # Compute partial sums in a list comprehension total = 0 partial_sums = [total := total + v for v in values] print("Total:", total) I began exploring the snippet on my own and soon discovered that :+= wasn't valid ... | The short version: The addition of the walrus operator was incredibly controversial, and they wanted to discourage overuse, so they limited it to only those cases for which a strong motivating use case was put forward, leaving = the convenient tool for all other cases. There's a lot of things the walrus operator won't ... | 11 | 8 |
69,396,816 | 2021-9-30 | https://stackoverflow.com/questions/69396816/django-merge-queryset-while-keeping-the-order | i'm trying to join together 2 QuerySets. Right now, I'm using the | operator, but doing it this way won't function as an "append". My current code is: df = RegForm((querysetA.all() | querysetB.all()).distinct()) I need the elements from querysetA to be before querysetB. Is it even possible to accomplish while keeping ... | This can be solved by using annotate to add a custom field for ordering on the querysets, and use that in a union like this: from django.db.models import Value a = querysetA.annotate(custom_order=Value(1)) b = querysetB.annotate(custom_order=Value(2)) a.union(b).order_by('custom_order') Prior to django-3.2, you need t... | 5 | 8 |
69,371,882 | 2021-9-29 | https://stackoverflow.com/questions/69371882/sending-entire-ethereum-address-balance-in-post-eip-1559-world | I'm trying to figure out how to send an entire address balance in a post EIP-1559 transaction (essentially emptying the wallet). Before the London fork, I could get the actual value as Total balance - (gasPrice * gas), but now it's impossible to know the exact remaining balance after the transaction fees because the ba... | This can be done by setting the 'Max Fee' and the 'Max Priority Fee' to the same value. This will then use a deterministic amount of gas. Just be sure to set it high enough - comfortably well over and above the estimated 'Base Fee' to ensure it does not get stuck. | 5 | 2 |
69,422,116 | 2021-10-3 | https://stackoverflow.com/questions/69422116/what-is-the-best-way-to-get-accurate-text-similarity-in-python-for-comparing-sin | I've got similar product data in both the products_a array and products_b array: products_a = [{color: "White", size: "2' 3\""}, {color: "Blue", size: "5' 8\""} ] products_b = [{color: "Black", size: "2' 3\""}, {color: "Sky blue", size: "5' 8\""} ] I would like to be able to accurately tell similarity between the colo... | NLP packages may be better at longer text fragments and more sophisticated text analysis. As you've discovered with 'black' and 'white', they make assumptions about similarity that are not right in the context of a simple list of products. Instead you can see this not as an NLP problem, but as a data transformation pro... | 7 | 2 |
69,437,526 | 2021-10-4 | https://stackoverflow.com/questions/69437526/what-is-this-odd-sorting-algorithm | Some answer originally had this sorting algorithm: for i from 0 to n-1: for j from 0 to n-1: if A[j] > A[i]: swap A[i] and A[j] Note that both i and j go the full range and thus j can be both larger and smaller than i, so it can make pairs both correct and wrong order (and it actually does do both!). I thought that's ... | To prove that it's correct, you have to find some sort of invariant. Something that's true during every pass of the loop. Looking at it, after the very first pass of the inner loop, the largest element of the list will actually be in the first position. Now in the second pass of the inner loop, i = 1, and the very firs... | 102 | 50 |
69,390,411 | 2021-9-30 | https://stackoverflow.com/questions/69390411/attributeerror-module-html5lib-treebuilders-etree-has-no-attribute-getetreem | Suggestions please, thanks :) pip list --outdated --format=freeze Gives the following error: ERROR: Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/_internal/cli/base_command.py", line 223, in _main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/_intern... | I solved this problem updating pip, i updated from pip 20.3.4 to 21.3 so just type: pip install pip -U Seems like there is some bug in pip itself. | 8 | 10 |
69,418,576 | 2021-10-2 | https://stackoverflow.com/questions/69418576/sqlalchemy-adding-a-foreignkeyconstraint-to-a-many-to-many-table-that-is-based | Forgive me if this has been answered elsewhere. I've been searching SO and haven't been able to translate the seemingly relevant Q&As to my scenerio. I'm working on a fun personal project where I have 4 main schemas (barring relationships for now): Persona (name, bio) Episode (title, plot) Clip (url, timestamp) Image ... | Add: a non-nullable column episode_id, a composite foreign key referencing personas_episode, and a trigger to autofill episode_id. The non-nullable column and the composite foreign key are sufficient to produce the correct constraints on a database-level as well as ensure that only proper data can be added outside of... | 7 | 2 |
69,417,027 | 2021-10-2 | https://stackoverflow.com/questions/69417027/how-to-typecheck-class-with-method-inserted-by-metaclass-in-python | In the following code some_method has been added by metaclass: from abc import ABC from abc import ABCMeta from typing import Type def some_method(cls, x: str) -> str: return f"result {x}" class MyMeta(ABCMeta): def __new__(mcs, *args, **kwargs): cls = super().__new__(mcs, *args, **kwargs) cls.some_method = classmethod... | As is explained in the MyPy documentation, MyPy's support for metaclasses only goes so far: Mypy does not and cannot understand arbitrary metaclass code. The issue is that if you monkey-patch a method onto a class in your metaclass's __new__ method, you could be adding anything to your class's definition. This is muc... | 5 | 12 |
69,427,175 | 2021-10-3 | https://stackoverflow.com/questions/69427175/how-to-pass-forwardref-as-args-to-typevar-in-python-3-6 | I'm working on a library that currently supports Python 3.6+, but having a bit of trouble with how forward references are defined in the typing module in Python 3.6. I've setup pyenv on my local Windows machine so that I can switch between different Python versions at ease for local testing, as my system interpreter de... | To state the obvious, the issue here appears to be due to several changes in the typing module between Python 3.6 and Python 3.7. In both Python 3.6 and Python 3.7: All constraints on a TypeVar are checked using the typing._type_check function (links are to the 3.6 branch of the source code on GitHub) before the Type... | 7 | 7 |
69,386,603 | 2021-9-30 | https://stackoverflow.com/questions/69386603/complexity-of-sparse-matrix-cholesky-decomposition | I am having trouble finding a straightforward answer to the following question: If you compute the Cholesky decomposition of an nxn positive definite symmetric matrix A, i.e factor A=LL^T with L a lower triangular matrix, the complexity is O(n^3). For sparse matrices, there are apparently faster algorithms, but how muc... | This can only be answered exactly for abitrary matrices if P=NP ... so it's not possible to answer in general. The time complexity depends on the fill-reducing ordering used, which is attempting to get an approximate solution to an NP hard problem. However, for the very special case of a matrix coming from a regular sq... | 5 | 3 |
69,429,950 | 2021-10-4 | https://stackoverflow.com/questions/69429950/dask-what-does-memory-limit-control | In dask's LocalCluster, there is a parameter memory_limit. I can't find in the documentation (https://distributed.dask.org/en/latest/worker.html#memory-management) details about whether the limit is per worker, per thread, or for the whole cluster. This is probably at least in part because I have trouble following how ... | The memory_limit keyword argument to LocalCluster sets the limit per worker. Related documentaion: https://github.com/dask/distributed/blob/7bf884b941363242c3884b598205c75373287190/distributed/deploy/local.py#L76-L78 Note, if the memory_limit given is greater than the available memory, the total available memory will b... | 5 | 5 |
69,396,898 | 2021-9-30 | https://stackoverflow.com/questions/69396898/trying-to-figure-out-uwsgi-thread-workers-configuration | So, I started working with uWSGI for my python application just two days ago and I'm trying to understand the various parameters we specify in an .ini file. This is what my app.ini file currently looks like: # The following article was referenced while creating this configuration # https://www.techatbloomberg.com/blog/... | Cores vs Processors First of all, the number of cores is not necessarily the number of processors. On early computers days it was like 1-1, but with modern improvements one processor can offer more than one core. (Check this: https://www.tomshardware.com/news/cpu-core-definition,37658.html). So, if it detected 12 cores... | 11 | 28 |
69,458,399 | 2021-10-5 | https://stackoverflow.com/questions/69458399/numpy-1-21-2-may-not-yet-support-python-3-10 | Python 3.10 is released and when I try to install NumPy it gives me this: NumPy 1.21.2 may not yet support Python 3.10.. what should I do? | If on Windows, numpy has not yet released a precompiled wheel for Python 3.10. However you can try the unofficial wheels available at https://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy . Specifically look for numpy‑1.21.2+mkl‑cp310‑cp310‑win_amd64.whl or numpy‑1.21.2+mkl‑cp310‑cp310‑win32.whl depending on you system a... | 28 | 23 |
69,441,767 | 2021-10-4 | https://stackoverflow.com/questions/69441767/error-using-selenium-chrome-webdriver-with-python | hi im using chrome driver but i cant fix this error mycode: options = Options() options.add_argument('--disable-gpu') options.add_argument('--disable-dev-shm-usage') self.site = webdriver.Chrome(executable_path="C:\chromedriver.exe",chrome_options=options) self.site.get("https://sgite.com/en/site/") error: [23468:1469... | If you are using Selenium with Python then add these extra options into your Selenium code- options = webdriver.ChromeOptions() options.add_experimental_option('excludeSwitches', ['enable-logging']) driver = webdriver.Chrome(options=options) | 4 | 13 |
69,444,526 | 2021-10-5 | https://stackoverflow.com/questions/69444526/python-grpc-failed-to-pick-subchannel | I'm trying to setup a GRPC client in Python to hit a particular server. The server is setup to require authentication via access token. Therefore, my implementation looks like this: def create_connection(target, access_token): credentials = composite_channel_credentials( ssl_channel_credentials(), access_token_call_cre... | The issue here was actually fairly deep. First, I turned on tracing and set GRPC log-level to debug and then found this line: D1006 12:01:33.694000000 9032 src/core/lib/security/transport/security_handshaker.cc:182] Security handshake failed: {"created":"@1633489293.693000000","description":"Cannot check peer: missing... | 5 | 5 |
69,442,203 | 2021-10-4 | https://stackoverflow.com/questions/69442203/how-to-hide-legend-selectively-in-a-plotly-line-plot | I'm struggling to hide the legend for some but not all of the lines in my line plot. Here is what the plot looks like now. Plot: Essentially I want to hide the legend for the light grey lines while keeping it in place for the coloured lines. Here's my code: import plotly.graph_objects as go fig = go.Figure() fig.updat... | If I understand your desired output correctly, you can use showlegend = False for the traces where you've set a grey color with color = #F5F5F5: for c in cols1: fig.add_trace(go.Scatter(x = df.index, y = df[c], line_color = '#F5F5F5', showlegend = False)) And then leave that out for the lines you'd like colors assigne... | 7 | 5 |
69,452,755 | 2021-10-5 | https://stackoverflow.com/questions/69452755/how-to-parse-xml-from-string-in-python | I'm trying to parse an XML from a string in Python with no success. The string I'm trying to parse is: <?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:573a453c-72c0-4185-8c54-9010593dd102"> <data> <... | Your original XML has namespaces. You need to honor them in your XPath queries. import xml.etree.ElementTree as ET reply_xml '''<?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:573a453c-72c0-4185-8c5... | 4 | 6 |
69,452,329 | 2021-10-5 | https://stackoverflow.com/questions/69452329/walrus-operator-in-dict-comprehension | I wanted to avoid double evaluation of a mean in a dict comprehension, and I tried using the walrus operator: >>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]} >>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65} but this gave me the following error: Traceback (most... | Your code is roughly equivalent to q = {} for x in dic: if mean > 65: mean := ... q[x] = mean which means you are using mean before assigning it. You need to move the definition to the if-clause-section of the dict-comprehension. >>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]} >>> q = {x:... | 14 | 14 |
69,451,227 | 2021-10-5 | https://stackoverflow.com/questions/69451227/how-to-replace-multiple-substrings-at-the-same-time | I have a string like a = "X1+X2*X3*X1" b = {"X1":"XX0","X2":"XX1","X0":"XX2"} I want to replace the substring 'X1,X2,X3' using dict b. However, when I replace using the below code, for x in b: a = a.replace(x,b[x]) print(a) 'XXX2+XX1*X3' Expected result is XX0 + XX1*X3*XX0 I know it is because the substring is rep... | You can create a pattern with '|' then search in dictionary transform like below. Try this: import re a = "X1+X2*X3*X1" b = {"X1":"XX0","X2":"XX1","X0":"XX2"} pattern = re.compile("|".join(b.keys())) out = pattern.sub(lambda x: b[re.escape(x.group(0))], a) Output: >>> out 'XX0+XX1*X3*XX0' | 6 | 8 |
69,440,494 | 2021-10-4 | https://stackoverflow.com/questions/69440494/python-3-10-optionaltype-or-type-none | Now that Python 3.10 has been released, is there any preference when indicating that a parameter or returned value might be optional, i.e., can be None. So what is preferred: Option 1: def f(parameter: Optional[int]) -> Optional[str]: Option 2: def f(parameter: int | None) -> str | None: Also, is there any preference... | PEP 604 covers these topics in the specification section. The existing typing.Union and | syntax should be equivalent. int | str == typing.Union[int, str] The order of the items in the Union should not matter for equality. (int | str) == (str | int) (int | str | float) == typing.Union[str, float, int] Optional val... | 105 | 115 |
69,447,823 | 2021-10-5 | https://stackoverflow.com/questions/69447823/how-to-convert-array-to-string-in-python | i have array like below arr = [1,2,3] how can i convert it to '1,2,3' using python i have a usecase where i want to add a filter parameter to url like below url = some_url?id__in=1,2,3 i was initially thinking to pass it like so url = some_url?id__in={arr} but this is incorrect. i am new to python and i have browsed... | This gives you the 1,2,3 that you asked for. ",".join(str(x) for x in arr) | 9 | 11 |
69,444,593 | 2021-10-5 | https://stackoverflow.com/questions/69444593/best-way-to-forward-redirect-methods-attributes-in-python-class-without-redundan | I have a project, with some modules each of which contains a class doing their respective thing. Then I have an API class for the user. The API class instantiate those classes, and should forward/redirect to those who are doing the actual processing. I have the following questions: How do I do the forwarding without r... | Try redirecting the __getattr__ magic method: class Foo: def __init__(self, bar: Bar): self.bar = bar def __getattr__(self, attr): return getattr(self.bar, attr) This would redirect all functions to the bar variable. For multiple classes: class Foo: def __init__(self, bar: Bar, foo: Foo, blah: Blah): self.bar = bar se... | 7 | 5 |
69,442,971 | 2021-10-4 | https://stackoverflow.com/questions/69442971/error-in-importing-environment-openai-gym | I am trying to run an OpenAI Gym environment however I get the following error: import gym env = gym.make('Breakout-v0') ERROR /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ale_py/gym/environment.py:11: DeprecationWarning: Importing atari-py roms won't be supported in future releases of... | Code works for me with gym 0.18.0 and 0.19.0 but not with 0.20.0 You may downgrade it with pip install --upgrade gym==0.19.0 BTW: it may also need to install gym[atari] or gym[all] to have all elements to work. Base on information in Release Note for 0.21.0 (which is not ready on pip but you can install from GitHub) ... | 23 | 4 |
69,416,986 | 2021-10-2 | https://stackoverflow.com/questions/69416986/attributeerror-module-tweepy-has-no-attribute-streamlistener-with-python | class MyStreamListener(tweepy.StreamListener): def on_status(self, status): print(status.text) # prints every tweet received def on_error(self, status_code): if status_code == 420: # end of monthly limit rate (500k) return False I use Python 3.9 and installed Tweepy via pip. I get the AttributeError on the class line.... | Tweepy v4.0.0 was released recently and it merged StreamListener into Stream. I recommend updating your code to subclass Stream instead. Alternatively, you can downgrade to v3.10.0. | 7 | 12 |
69,429,846 | 2021-10-4 | https://stackoverflow.com/questions/69429846/how-to-use-jax-vmap-for-nested-loops | I want to use vmap to vectorise this code for performance. def matrix(dataA, dataB): return jnp.array([[func(a, b) for b in dataB] for a in dataA]) matrix(data, data) I tried this: def f(x, y): return func(x, y) mapped = jax.vmap(f) mapped(data, data) But this only gives the diagonal entries. Basically I have a vecto... | jax.vmap maps across one set of axes at a time. If you want to map across two independent sets of axes, you can do so by nesting two vmap transformations: mapped = jax.vmap(jax.vmap(f, in_axes=(None, 0)), in_axes=(0, None)) result = mapped(data, data) | 5 | 4 |
69,432,439 | 2021-10-4 | https://stackoverflow.com/questions/69432439/how-to-add-transparency-to-a-line-with-opencv-python | I can draw a line with OpenCV Python but I can't make the line transparent def draw_from_pitch_to_image(image, reverse_output_points): for i in range(0, len(reverse_output_points), 2): x1, y1 = reverse_output_points[i] x2, y2 = reverse_output_points[i + 1] x1 = int(x1) y1 = int(y1) x2 = int(x2) y2 = int(y2) color = [25... | One approach is to create a mask "overlay" image (copy of input image), draw a line onto this overlay image, and then perform the weighted addition of the two images using cv2.addWeighted() to mimic an alpha channel. Here's an example: Line with no transparency -> Result with alpha=0.5 Result with alpha=0.25 This ... | 6 | 11 |
69,433,024 | 2021-10-4 | https://stackoverflow.com/questions/69433024/error-message-with-sklearn-function-roccurvedisplay-has-no-attribute-from-p | I am trying to use the sklearn function RocCurveDisplay.from_predictions as presented in https://scikit-learn.org/stable/modules/generated/sklearn.metrics.RocCurveDisplay.html#sklearn.metrics.RocCurveDisplay.from_predictions. I run the function like this: from sklearn.metrics import RocCurveDisplay true = np.array([0.,... | Your version 0.24.1 is not the latest version, You'll need to upgrade to scikit-learn 1.0 as from_predictions is supported in 1.0 You can upgrade using: pip install --upgrade scikit-learn | 6 | 8 |
69,426,664 | 2021-10-3 | https://stackoverflow.com/questions/69426664/modulenotfounderror-no-module-named-jsonschema-compat | I have been working with the Bybit API for the last week when I encountered the title problem yesterday. I have started a new env and installed only the bybit wrapper again and the issue still arises. From what I can see I have jsonschema installed and in my env PATH. It was working a few days ago, so I do believe this... | That module was removed in jsonschema 4.0. Your packages haven't been pinned to only use jsonschema 3.x, so that might happen. For now, you can downgrade to version 3.x of the jsonschema package with pip install -U 'jsonschema<4.0' and things should work. | 17 | 27 |
69,426,453 | 2021-10-3 | https://stackoverflow.com/questions/69426453/declaration-of-list-of-type-python | Let's suppose to have a class Bag that contains a list of item. What we know about item is just that it has a method called : printDescription(). Now I want to define a method printAllItemsDescription inside Bag, that invokes the method printDescription() on each item inside items list. This should be the code (it's wr... | Python's type hinting is ever-evolving, and they've made some changes over time. Older versions of Python don't support subscripting list as in list[item]. Fortunately, we can get around all of this using a future import. The annotations import from __future__ works in all Python versions starting from 3.7 and effectiv... | 11 | 22 |
69,422,878 | 2021-10-3 | https://stackoverflow.com/questions/69422878/how-to-check-for-boolean-without-using-for-loop | I have this running well, however am unable to avoid the loop, how can I get an only True if present or False if not present without having to loop through the list using a for loop? my_list = [[1, 2], [4, 6], [8, 3]] combined = [3, 8] for value in my_list: print(value) if set(combined) == set(value): print("present") ... | To avoid the multiple absent printing, you can use a for/else construct: for value in my_list: if set(combined) == set(value): print("present") break else: print("absent") But if you're looking to optimize/reduce the loop, you can "hide" the loop inside an any call: any(set(combined) == set(value) for value in my_list... | 4 | 3 |
69,397,039 | 2021-9-30 | https://stackoverflow.com/questions/69397039/pymongo-ssl-certificate-verify-failed-certificate-has-expired-on-mongo-atlas | I am using MongoDB(Mongo Atlas) in my Django app. All was working fine till yesterday. But today, when I ran the server, it is showing me the following error on console Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\admin\appdata\local\programs\python\python39\lib\threading.py... | This is because of a root CA Let’s Encrypt uses (and Mongo Atals uses Let's Encrypt) has expired on 2020-09-30 - namely the "IdentTrust DST Root CA X3" one. The fix is to manually install in the Windows certificate store the "ISRG Root X1" and "ISRG Root X2" root certificates, and the "Let’s Encrypt R3" intermediate on... | 15 | 17 |
69,403,190 | 2021-10-1 | https://stackoverflow.com/questions/69403190/mypy-returns-error-unexpected-keyword-argument-for-subclass-of-a-decorated-cla | I have two decorated classes using attrs package as follows: @attr.s(kw_only=True) class Entity: """ base class of all entities """ entity_id = attr.ib(type=str) # ... @attr.s(kw_only=True) class Customer(Entity): customer_name = attr.ib(type=Name) # ... I get Unexpected keyword argument "entity_id" for "Customer" for... | Your code is correct and should work. If I run the following simplified version: import attr @attr.s(kw_only=True) class Entity: """ base class of all entities """ entity_id = attr.ib(type=str) # ... @attr.s(kw_only=True) class Customer(Entity): customer_name = attr.ib(type=str) def register_customer(customer_name: str... | 5 | 4 |
69,406,767 | 2021-10-1 | https://stackoverflow.com/questions/69406767/cant-load-spacy-en-core-web-trf | As the self guide says, I've installed it with (conda environment) conda install -c conda-forge spacy python -m spacy download en_core_web_trf I have spacy-transformers already installed. But when I simply do: import spacy spacy.load("en_core_web_trf") It shows me this error: ValueError: [E002] Can't find factory for... | Are you sure you did install spacy-transformers? After installing spacy? I am using pip: pip install spacy-transformers and I have no problems loading the en_core_web_trf. | 15 | 12 |
69,409,255 | 2021-10-1 | https://stackoverflow.com/questions/69409255/how-to-get-city-state-and-country-from-a-list-of-latitude-and-longitude-coordi | I have a 500,000 list of latitudes and longitudes coordinates like below: Latitude Longitude 42.022506 -88.168156 41.877445 -87.723846 29.986801 -90.166314 I am looking to use python to get the city, state, and country for each coordinate in a new column like below: Latitude Longitude City State Country 42.022506 -88.... | You want to run a function on each row, which can be done using apply(). There are two complications, which is that you want to 1) provide multiple arguments to the function, and 2) get back multiple results. These questions explain how to do those things: python pandas- apply function with two arguments to columns Re... | 8 | 12 |
69,403,474 | 2021-10-1 | https://stackoverflow.com/questions/69403474/hiding-bar-labels-less-than-n-in-matplotlib-bar-label | Am loving ease of ax.bar_label in recent matpolotlib update. I'm keen to hide low-value data labels for readability in the final plot to avoid overlapping labels. How would I hide labels less than a predefined value (here, let's say less than 0.025) in the code below? df_plot = pd.crosstab(df['Yr_Lvl_Cd'], df['Achieve... | You can filter the container's datavalues attribute (requires matplotlib >= 3.4.0) using your threshold: threshold = 0.025 for c in ax.containers: # Filter the labels labels = [v if v > threshold else "" for v in c.datavalues] ax.bar_label(c, labels=labels, label_type="center") | 9 | 14 |
69,388,274 | 2021-9-30 | https://stackoverflow.com/questions/69388274/python-pandas-drop-rows-by-condition | hello I need help to drop some rows by the condition: if the estimated price minus price is more than 1500 (positive) drop the row price estimated price 0 13295 13795 1 19990 22275 2 7295 6498 for example only the index 1 would be drop thank you! | You can use pd.drop() in which you can drop specific rows by index. : >>> df.drop(df[(df['estimated price']-df['price'] >= 1500)].index) price estimated price 0 13295 13795 2 7295 6498 index 1 is dropped. Note that this method assumes that your index is unique. If otherwise, boolean indexing is the better solution. | 4 | 5 |
69,400,900 | 2021-10-1 | https://stackoverflow.com/questions/69400900/how-to-call-on-a-class-using-3-functions | I would like to create a Python class with 3 functions. Function 1 will ask the user to input one number. Function 2 will ask the user to input another number. Function 3 will multiply function 1 * function 2 and return to the product. Here is the code I have so far: class Product: def __init__(self, x, y): self.x = ... | Here is a working solution. Compare it to your current solution and spot the differences. After the following code snippet, I will highlight concepts you need to research in order to understand this program better. Here is a correct version of your code (note: there is potentially more than one solution): class Product... | 7 | 5 |
69,400,871 | 2021-10-1 | https://stackoverflow.com/questions/69400871/how-do-you-join-multiple-rows-into-one-row-in-pandas | I have a list that I'm trying to add to a dataframe. It looks something like this: list_one = ['apple','banana','cherry',' ', 'grape', 'orange', 'pineapple',''] If I add the list to a dataframe, using df = pd.DataFrame({'list_one':list_one}) it'll look like this: list_one ------------- 0 apple 1 banana 2 cherry 3 4 g... | Create mask for match words by Series.str.contains, invert by ~ and crate groups by Series.cumsum, filter only matched rows and pass to GroupBy.agg with join function: m = df['list_one'].str.contains('\w+') df = df[m].groupby((~m).cumsum(), as_index=False).agg(', '.join) print (df) list_one 0 apple, banana, cherry 1 gr... | 8 | 9 |
69,399,503 | 2021-9-30 | https://stackoverflow.com/questions/69399503/how-to-return-the-last-character-of-a-string-in-python | How can I get the last character of this string? seed_name = "Cocoa" | As shown in the official Python tutorial, >>> word = 'Python' [...] Indices may also be negative numbers, to start counting from the right: >>> word[-1] # last character 'n' | 8 | 29 |
69,398,013 | 2021-9-30 | https://stackoverflow.com/questions/69398013/seaborn-jointplot-turn-off-one-of-the-marginal-plots | Is there a way to turn off the top marginal plot in a Seaborn Jointplot? tips = sns.load_dataset('tips') g = sns.jointplot( data=tips, x="total_bill", y="tip", hue="smoker", ) | Perhaps just call remove on .ax_marg_x. g.ax_marg_x.remove() Output: (Note that ax_marg_y and ax_joint are the remaining plots, as detailed in the JointGrid docs). | 9 | 7 |
69,396,635 | 2021-9-30 | https://stackoverflow.com/questions/69396635/how-to-detect-eof-when-reading-a-file-with-readline-in-python | I need to read the file line by line with readline() and cannot easily change that. Roughly it is: with open(file_name, 'r') as i_file: while True: line = i_file.readline() # I need to check that EOF has not been reached, so that readline() really returned something The real logic is more involved, so I can't read the... | From the documentation: f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file... | 10 | 10 |
69,395,834 | 2021-9-30 | https://stackoverflow.com/questions/69395834/deep-python-dictionary-recursion | I have a python dictionary: d = { "config": { "application": { "payment": { "dev": { "modes": {"credit,debit,emi": {}}, "company": { "address": { "city": {"London": {}}, "pincode": {"LD568162": {}}, }, "country": {"United Kingdom": {}}, "phone": {"7865432765": {}}, }, "levels": {"0,1,2": {}}, }, "prod": {"modes": {"cre... | Solution 1 We can use a non-recursive approach with queues to enqueue each inner/nested element of the document and put as value if the nested value is just {}: # d = ... queue = [d] while queue: data = queue.pop() for key, value in data.items(): if isinstance(value, dict) and list(value.values()) == [{}]: data[key] = ... | 5 | 2 |
69,395,130 | 2021-9-30 | https://stackoverflow.com/questions/69395130/understanding-the-asterisk-operator-in-python-when-its-before-the-function-in-a | I know that the asterisk is used to unpack values like system args or when you unpack lists into variables. But I have not seen this syntax here before in this example of asyncio. I was reading this article here, https://realpython.com/async-io-python/#the-10000-foot-view-of-async-io , but I don't understand what the a... | The asterisk isn't before makerandom, it's before the generator expression (makerandom(i, 10 - i - 1) for i in range(3)) asyncio.gather doesn't take an iterable as its first argument; it accepts a variable number of awaitables as positional arguments. In order to get from a generator expression to that, you need to un... | 6 | 9 |
69,392,936 | 2021-9-30 | https://stackoverflow.com/questions/69392936/can-i-introduce-the-output-of-variables-in-the-message-of-asserts | I am doing some validation of the input data of one program I have created. I am doing this with assert. If assertion arises I want to know in which part of the data occurs so I want to get the value that arises the assertion. assert all(isinstance(e, int) for l1 in sequence.values() for l2 in l1 for e in l2),"Values o... | Not when using all as it does not expose the "iteration variable". You will need an explicit, nested loop. You also forgot the f'' prefix to denote an f-string: for l1 in [['a']]: for l2 in l1: for e in l2: assert isinstance(e, int), f"Values of the dictionnary aren't lists of integers. Assert found in '{l2}'" Asserti... | 6 | 4 |
69,389,252 | 2021-9-30 | https://stackoverflow.com/questions/69389252/multiply-all-lists-in-list-of-lists | I have a list of masks and I want to obtain the resulting mask by multiplying all of them. My Donkey Kong approach is the following: a = [[1, 1], [1, 0], [1, 0]] b = a[0] for i in range(1, len(a)): b = b * np.array(a[i]) which I think it works as returns [1,0] as value of b. Is there a nicer way of doing this? EDIT: ... | Take a look at np.prod, which returns the product of array elements over a given axis: import numpy as np a = [[1, 1], [1, 0], [1, 0]] np.prod(a, axis=0) | 5 | 8 |
69,372,488 | 2021-9-29 | https://stackoverflow.com/questions/69372488/python-3-6-9-importerror-no-module-named-setuptools-rust-and-a-command-pytho | I am trying to install pyOpenSSl and it shows the following error Requirement already satisfied: six>=1.5.2 in /home/tony/hx-preinstaller-venv/lib/python3.6/site-packages (from pyOpenSSL) Collecting cryptography>=3.3 (from pyOpenSSL) Using cached https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d35063979... | Try upgrade pip and install setuptools-rust: pip install --upgrade pip pip install setuptools-rust | 11 | 23 |
69,378,901 | 2021-9-29 | https://stackoverflow.com/questions/69378901/get-ranges-where-values-are-not-none | The Goal I would like to get the ranges where values are not None in a list, so for example: test1 = [None, 0, None] test2 = [2,1,None] test3 = [None,None,3] test4 = [1,0,None,0,0,None,None,1,None,0] res1 = [[1,1]] res2 = [[0,1]] res3 = [[2,2]] res4 = [[0,1],[3,4],[7,7],[9,9]] What I have tried This is my super length... | Use itertools.groupby: from itertools import groupby test1 = [None, 0, None] test2 = [2, 1, None] test3 = [None, None, 3] test4 = [1, 0, None, 0, 0, None, None, 1, None, 0] def get_not_None_ranges(lst): result = [] for key, group in groupby(enumerate(lst), key=lambda x: x[1] is not None): if key: index, _ = next(group)... | 7 | 4 |
69,376,943 | 2021-9-29 | https://stackoverflow.com/questions/69376943/how-can-i-insert-linebreak-in-yaml-with-ruamel-yaml | Here is the code I have from ruamel.yaml import YAML yaml = YAML() user = [{"login":"login1","fullName":"First1 Last1", "list":["a"]},{"login":"login2","fullName":"First2 Last2", "list":["b"]}] test = {"category":[{"year":2023,"users":user}]} yaml.indent(mapping=4, sequence=4, offset=2) yaml.width = 2048 with open(r'te... | You should load the result that you want in ruamel.yaml. For good measure you can then dump it back to see if the extra line is preserved. If it isn't you might not be able to write out such a format in the first place. As you will see the extra line is preserved, so you should be able to get it inothe output in some w... | 6 | 3 |
69,375,868 | 2021-9-29 | https://stackoverflow.com/questions/69375868/extract-month-from-datetime-column-in-pandas-dataframe | I have a DataFrame read from Excel with one of the columns of type DateTime. sales_data=pandas.read_excel(r'Sample Sales Data.xlsx') I was able to extract substrings from other columns using str.extract/lambda functions. But I was unable to process the column "Order Date" The command sales_data['Order Date'] gives the... | I found the issue. The sales_data['Order Date'] column had a mix of both date and int values due to some input data inaccuracy. I found this since sales_data['DateType']=sales_data['Order Date'].apply(lambda x:type(x)) sales_data['DateType'].unique() returned array([<class 'datetime.datetime'>, <class 'int'>], dtype=o... | 6 | 0 |
69,372,201 | 2021-9-29 | https://stackoverflow.com/questions/69372201/get-excel-column-letter-based-on-column-header-python | This seems relatively straight forward, but I have yet to find a duplicate that answers my question, or a method with the needed functionality. I have an Excel spreadsheet where each column that contains data has a unique header. I would like to use pandas to get the letter key of the column by passing this header stri... | You can try: import xlsxwriter col_no = df.columns.get_loc("col_name") print(xlsxwriter.utility.xl_col_to_name(col_no)) | 5 | 8 |
69,370,507 | 2021-9-29 | https://stackoverflow.com/questions/69370507/prompting-importerror-no-module-named-py27-urlquote-when-running-dev-appserve | When I run dev_appserver.py on google-cloud-sdk, I get ImportError: No module named py27_urlquote. Traceback (most recent call last): File "/Users/user/Downloads/google-cloud-sdk/platform/google_appengine/dev_appserver.py", line 109, in <module> _run_file(__file__, globals()) File "/Users/user/Downloads/google-cloud-sd... | Right now this is a public issue and is currently being addressed by our Google Engineering Team. A workaround was provided for you to run your local development server: Install pip for Python 2 sudo apt update sudo apt install python-pip Install urlquote instead of py27_urlquote pip install urlquote Modify modu... | 5 | 3 |
69,363,867 | 2021-9-28 | https://stackoverflow.com/questions/69363867/difference-between-os-replace-and-os-rename | I want to move a file form one directory to another in linux with python. I wish to achieve a behavior similar to bash mv command. What is the difference in practice between the two commands os.replace() os.rename() Is it simply that os.rename() will raise an error if file exists in destination while os.replace() will... | On POSIX systems, the rename system call will silently replace the destination file if the user has sufficient permissions. The same is not true on Windows: a FileExistsError is always raised. os.replace and os.rename are the same function on POSIX systems, but on Windows os.replace will call MoveFileExW with the MOVEF... | 14 | 16 |
69,363,178 | 2021-9-28 | https://stackoverflow.com/questions/69363178/resize-to-specific-height-and-width-with-pyvips | I find this answer, and I want to use pyvips to resize images. In the mentioned answer and the official documentation image resized by scale. However, I want to resize the image to a specific height and width. Is there any way to achieve this with pyvips? | The thumbnail operation in pyvips will load an image to fit a box, for example: thumb = pyvips.Image.thumbnail("some-file.jpg", 128) Will load some-file.jpg and make an image that fits within 128x128 pixels. Variations on thumbnail can load from strings, buffers or pipes, load to fit other boxes, check the chapter on ... | 6 | 5 |
69,352,179 | 2021-9-27 | https://stackoverflow.com/questions/69352179/package-streamlit-app-and-run-executable-on-windows | this is my first question on Stackoverflow. I hope my question is clear, otherwise let me know and don't hesitate to ask me more details. I'm trying to package a streamlit app for a personal project. I'm developing under linux but I have to deploy the app on Windows. I want it to be a standalone executable, which once ... | EDIT: a streamlit example was added to the examples of pynsist repo. Here you can find a minimal and refined example of a working application (which also includes plotly). ORIGINAL ANSWER Finally I get it to work. In my last attempt, I made a mistake by setting --server.headless=false, while it must be true instead. I ... | 5 | 5 |
69,306,103 | 2021-9-23 | https://stackoverflow.com/questions/69306103/is-it-possible-to-change-the-output-alias-in-pydantic | Setup: # Pydantic Models class TMDB_Category(BaseModel): name: str = Field(alias="strCategory") description: str = Field(alias="strCategoryDescription") class TMDB_GetCategoriesResponse(BaseModel): categories: list[TMDB_Category] @router.get(path="category", response_model=TMDB_GetCategoriesResponse) async def get_all_... | Use the Config option by_alias. from fastapi import FastAPI, Path, Query from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str = Field(..., alias="keck") @app.post("/item") async def read_items( item: Item, ): return item.dict(by_alias=False) Given the request: { "keck": "string" } t... | 37 | 18 |
69,355,161 | 2021-9-28 | https://stackoverflow.com/questions/69355161/git-filter-repo-commands-output-nothing-on-windows | I installed git-filter-repo via scoop, tried multiple git filter-repo commands e.g. git filter-repo -h, they all logged nothing, no warning or error, just nothing. Tried rebooting, reinstalling, and installing it on another Windows 10 computer, all reproduced it. git-filter-repo: v2.33.0 git: v2.33.0.windows.2 python: ... | (Now updated for newer Python installers.) When I installed git-filter-repo on Windows earlier this year, the following steps worked for me: Download and install Python for Windows. In newer installers you need to go into the Advanced Options to make sure Python is added to your Path: Confirm python was added to you... | 15 | 77 |
69,298,452 | 2021-9-23 | https://stackoverflow.com/questions/69298452/how-to-write-or-in-a-glob-pattern | glob.glob() does not use regex. it uses Unix path expansion rules. How can I emulate this regex in glob: ".*.jpg|.*.png" | @U12-Forward is correct that there isn't an exact solution but depending on your use case you might be able to solve it with the [...] wildcard. For your example with .png or .jpg you could use this: .*.[jp]* which will match any extension that starts with a j or p If you have other extensions that start with j or p y... | 20 | 12 |
69,294,350 | 2021-9-23 | https://stackoverflow.com/questions/69294350/1d-cnn-in-tensorflow-for-time-series-classification | My Time-Series is a 30000 x 500 table representing points from three different types of graphs: Linear, Quadratic, and Cubic Sinusoidal. Thus, there are 10000 Rows for Linear Graphs, 10000 for Quadratics, and 10000 for Cubics. I have sampled 500 points from every graph. Here's an image to illustrate my point: I've bui... | Conv1D equivalent code. Conv1D layer expects 3D input and outputs 3D shape. Maxpooling2D expects 4D input. You need to use maxpooling1D layer. Sample code import tensorflow as tf input_shape = (4, 7, 10, 128) num_classes = 3 model = tf.keras.models.Sequential() model.add(tf.keras.layers.Conv1D(filters= 32, kernel_size=... | 5 | 4 |
69,330,668 | 2021-9-25 | https://stackoverflow.com/questions/69330668/efficient-way-to-extract-data-from-netcdf-files | I have a number of coordinates (roughly 20000) for which I need to extract data from a number of NetCDF files each comes roughly with 30000 timesteps (future climate scenarios). Using the solution here is not efficient and the reason is the time spent at each i,j to convert "dsloc" to "dataframe" (look at the code belo... | This is a perfect use case for xarray's advanced indexing using a DataArray index. # Make the index on your coordinates DataFrame the station ID, # then convert to a dataset. # This results in a Dataset with two DataArrays, lat and lon, each # of which are indexed by a single dimension, stid crd_ix = crd.set_index('sti... | 8 | 9 |
69,349,620 | 2021-9-27 | https://stackoverflow.com/questions/69349620/in-operator-chaining-true-in-true-in-true-output-false | I'm trying to figure out in what order this code runs: print( True in [True] in [True] ) False even though: print( ( True in [True] ) in [True] ) True and: print( True in ( [True] in [True] ) ) TypeError If the first code is neither of these two last ones, then what? | in is comparing with chaining there so True in [True] in [True] is equivalent to (except middle [True] is evaluated once) (True in [True]) and ([True] in [True]) which is True and False which is False This is all similar to 2 < 4 < 12 operation which is equivalent to (2 < 4) and (4 < 12). | 6 | 11 |
69,352,472 | 2021-9-27 | https://stackoverflow.com/questions/69352472/lookup-values-by-corresponding-column-header-in-pandas-1-2-0-or-newer | The operation pandas.DataFrame.lookup is "Deprecated since version 1.2.0", and has since invalidated a lot of previous answers. This post attempts to function as a canonical resource for looking up corresponding row col pairs in pandas versions 1.2.0 and newer. Standard LookUp Values With Default Range Index Given the ... | Standard LookUp Values With Any Index The documentation on Looking up values by index/column labels recommends using NumPy indexing via factorize and reindex as the replacement for the deprecated DataFrame.lookup. import numpy as np import pandas as pd df = pd.DataFrame({'Col': ['B', 'A', 'A', 'B'], 'A': [1, 2, 3, 4], ... | 10 | 12 |
69,312,922 | 2021-9-24 | https://stackoverflow.com/questions/69312922/how-to-encrypt-large-file-using-python | I'm trying to encrypt file that is larger than 1GB. I don't want to read it all to memory. I chose Fernet (cryptography.fernet) for this task, because it was most recommended (faster than asymetric solutions). I generated the key. Then I've created a script to encrypt: key = Fernet(read_key()) with open(source, "rb") ... | Fernet is not supposed to be used in a streaming fashion. They explain that in the documentation: From the documentation (last section): Limitations Fernet is ideal for encrypting data that easily fits in memory. As a design feature it does not expose unauthenticated bytes. This means that the complete message content... | 5 | 4 |
69,334,475 | 2021-9-26 | https://stackoverflow.com/questions/69334475/how-to-hint-at-number-types-i-e-subclasses-of-number-not-numbers-themselv | Assuming I want to write a function that accepts any type of number in Python, I can annotate it as follows: from numbers import Number def foo(bar: Number): print(bar) Taking this concept one step further, I am writing functions which accept number types, i.e. int, float or numpy dtypes, as arguments. Currently, I am... | In general, how do we hint classes, rather than instances of classes? In general, if we want to tell a type-checker that any instance of a certain class (or any instance of a subclass of that class) should be accepted as an argument to a function, we do it like so: def accepts_int_instances(x: int) -> None: pass class... | 30 | 60 |
69,332,196 | 2021-9-26 | https://stackoverflow.com/questions/69332196/mutiprocessing-with-spawn-context-cannot-access-shared-variables-in-linux | I have to use the Process method with "spawn" context in Linux. Then I write a sample code as follows: from multiprocessing import Value import multiprocessing class Test(object): def __init__(self, m_val): print("step1") self.m_val = m_val print("step2") self.m_val_val = m_val.value self.prints() def prints(self): pri... | The problem is that you are creating Value in the default context, which is fork on Unix. You can resolve this by setting the default start context to "spawn": multiprocessing.set_start_method("spawn") # Add this v = Value("i",10) Better yet, create the Value in the context explicitly: # v = Value("i",10) # Change thi... | 6 | 4 |
69,326,748 | 2021-9-25 | https://stackoverflow.com/questions/69326748/poetry-install-command-fails-whl-files-are-not-found | I am managing dependencies in my Python project via Poetry. Now I want to run this project in a machine which is different from my dev machine. To install dependecies, I simply run this command from the root directory: $ poetry install but then it raises the following errors: Updating dependencies Resolving dependenci... | Specifically I found that deleting the AppData\Local\pypoetry\Cache\artifacts folder (I'm on Windows 10) worked for me. virtualenvs for other projects may be in AppData\Local\pypoetry\Cache\virtualenvs so you might not want to delete the root cache folder at AppData\Local\pypoetry\Cache in its entirety. | 22 | 38 |
69,312,333 | 2021-9-24 | https://stackoverflow.com/questions/69312333/django-admin-two-listfilter-spanning-multi-valued-relationships | I have a Blog model and an Entry model, following the example in django's documentation. Entry has a ForeignKey to Blog: one Blog has several Entries. I have two FieldListFilters for Blog: one for "Entry title", one for "Entry published year". If in the Blog list admin page I filter for both entry__title='Lennon' and e... | So the fundamental problem as you point out is that django builds the queryset by doing a sequence of filters, and once a filter is "in" the queryset, it's not easy to alter it, because each filter builds up the queryset's Query object. However, it's not impossible. This solution is generic and requires no knowledge of... | 5 | 3 |
69,314,257 | 2021-9-24 | https://stackoverflow.com/questions/69314257/explosion-of-memory-when-using-pandas-loc-with-umatching-indices-assignment-g | This is an observation from Most pythonic way to concatenate pandas cells with conditions I am not able to understand why third solution one takes more memory compared to first one. If I don't sample the third solution does not give runtime error, clearly something is weird To emulate large dataframe I tried to resam... | @2e0byo hit the nail on the head saying pandas' algorithm is "inefficient" in this case. As far as .loc, it's not really doing anything remarkable. Its use here is analogous to indexing a numpy array with a boolean array of the same shape, with an added dict-key-like access to a specific column - that is, df['city'] ==... | 9 | 6 |
69,330,379 | 2021-9-25 | https://stackoverflow.com/questions/69330379/how-to-properly-type-hint-a-class-decorator | Assume we have some function func that maps instances of class A to instances of class B, i.e. it has the signature Callable[[A], B]. I want to write a class decorator autofunc for subclasses of A that automatically applies func to instances as they are created. For example, think of automatic jit-compilation based on ... | This is simply a bug in mypy: https://github.com/python/mypy/issues/5865 | 5 | 3 |
69,367,479 | 2021-9-28 | https://stackoverflow.com/questions/69367479/cant-show-info-level-logging-in-aws-lambda | I'm trying to run a script in AWS lambda and I want to output info level logs to the console after the script runs. I've tried looking for help from This post on using logs in lambda buy haven't had any success. I think AWS Cloudwatch is overriding my configuration shown bellow. import logging # log configuration logg... | from my understanding, I think one fix would be to add this: logging.getLogger().setLevel('INFO') I believe that logging.basicConfig(level=...) affects the minimum log level at which logs show up in the console, but across all loggers. The one above explicitly sets the minimum enabled level for the root logger, i.e. l... | 5 | 7 |
69,363,012 | 2021-9-28 | https://stackoverflow.com/questions/69363012/how-to-make-itertools-combinations-increase-evenly | Consider the following example: import itertools import numpy as np a = np.arange(0,5) b = np.arange(0,3) c = np.arange(0,7) prods = itertools.product(a,b,c) for p in prods: print(p) This iterate over the products in the following order: (0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 0, 3) (0, 0, 4) (0, 1, 0) But I would much rat... | The easiest way to do this without storing extra products in memory is with recursion. Instead of range(a,b), pass in a list of (a,b) pairs and do the iteration yourself: def prod_by_sum(range_bounds: List[Tuple[int, int]]): """ Yield from the Cartesian product of input ranges, produced in order of sum. >>> range_bound... | 6 | 3 |
69,322,595 | 2021-9-25 | https://stackoverflow.com/questions/69322595/duplicate-information-in-typing-and-docstring | I am confused about the use of type hints and docstrings. Aren't they duplicate information? For example: def my_func(name: str): """ print a name. Parameters ---------- name : str a given name """ print(name) Isn't the information name: str given twice? | Putting the type as a type hint and as part of the docstring would be redundant. It is also prone to human errors since one could easily forget updating one of them, thus effort is constantly needed to keep them both in sync. The documentation for type hints also mentions it: Docstrings. There is an existing conventio... | 5 | 6 |
69,360,198 | 2021-9-28 | https://stackoverflow.com/questions/69360198/correctly-typing-a-function-that-can-return-a-provided-default-value | I have a function of the following structure: def get_something_from_data(data: Mapping[str, str], default: Optional[str] = None) -> Optional[str]: """Get something out of `data` if it is there, if not return the value of `default`. If `default` is not provided, return None. """ So this can return either Optional[str]... | Using typing.overload you can describe multiple combinations of arguments and return types for a function from typing import overload, Mapping, Optional @overload def get_something_from_data(data: Mapping[str, str], default: None = None) -> Optional[str]: ... @overload def get_something_from_data(data: Mapping[str, str... | 5 | 5 |
69,356,599 | 2021-9-28 | https://stackoverflow.com/questions/69356599/delay-between-different-function-calls | I have a question about adding delay after calling various functions. Let's say I've function like: def my_func1(): print("Function 1") def my_func2(): print("Function 2") def my_func3(): print("Function 3") Currently I've added delay between invoking them like below: delay = 1 my_func1() time.sleep(delay) my_func2() ... | I've tested this based on "How to Make Decorators Optionally Turn On Or Off" (How to Make Decorators Optionally Turn On Or Off) from time import sleep def funcdelay(func): def inner(): func() print('inner') sleep(1) inner.nodelay = func return inner @funcdelay def my_func1(): print("Function 1") @funcdelay def my_func2... | 10 | 6 |
69,356,332 | 2021-9-28 | https://stackoverflow.com/questions/69356332/counting-contiguous-sawtooth-subarrays | Given an array of integers arr, your task is to count the number of contiguous subarrays that represent a sawtooth sequence of at least two elements. For arr = [9, 8, 7, 6, 5], the output should be countSawSubarrays(arr) = 4. Since all the elements are arranged in decreasing order, it won’t be possible to form any sawt... | This can be solved by just splitting the array into multiple sawtooth sequences..which is O(n) operation. For example [1,2,1,3,4,-2] can be splitted into two sequence [1,2,1,3] and [3,4,-2] and now we just have to do C(size,2) operation for both the parts. Here is psedo code explaining the idea ( does not have all corn... | 7 | 4 |
69,294,075 | 2021-9-23 | https://stackoverflow.com/questions/69294075/how-can-i-play-video-or-audio-on-a-jupyter-notebook-through-vs-code | I'm running a Jupyter Notebook on VS code and trying to display/play a video. From all the other forums, I've seen that using IPython.display is the standard method; however, it isn't working for me. For example, for Video: from IPython.display import Video Video('test.mp4') This code generates a video box in the outp... | To get it to work I did the following: Uninstalled and reinstalled VS Code and installed the extensions Python, Jupyter and Jupyter Keymap Installed FFmpeg through Homebrew: brew install ffmpeg Converted the video codec from "MPEG4" to "H.264": ffmpeg -i test.mp4 video.mp4 Then used the following code to display the ... | 6 | 5 |
69,355,736 | 2021-9-28 | https://stackoverflow.com/questions/69355736/how-can-i-find-the-sum-of-a-users-input | print("Fazli's Vet Services\n") print("Exam: 50") print("Vaccinations: 25") print("Trim Nails: 5") print("Bath: 20\n") exam = "exam" vaccinations = "vaccinations" trim_nails = "trim nails" bath = "bath" none = "none" exam_price = 50 vaccination_price = 25 trim_nails_price = 5 bath_price = 20 none_price = 0 first_servic... | Use dictionary - print("Fazli's Vet Services\n") print("Exam: 50") print("Vaccinations: 25") print("Trim Nails: 5") print("Bath: 20\n") dictionary = {'exam':50,'vaccinations':25,'trim nails':5,'bath':20,'none':0} first_service = input("Select first service:").lower() second_service = input("Select second service:").low... | 5 | 2 |
69,355,100 | 2021-9-28 | https://stackoverflow.com/questions/69355100/reducing-python-zip-size-to-use-with-aws-lambda | I'm following this blog post to create a runtime environment using Docker for use with AWS Lambda. I'm creating a layer for using with Python 3.8: docker run -v "$PWD":/var/task "lambci/lambda:build-python3.8" /bin/sh -c "pip install -r requirements.txt -t python/lib/python3.8/site-packages/; exit" And then archiving ... | The key idea behind shrinking your layers is to identify what pip installs and what you can get rid off, usually manually. In your case, since you are only slightly above the limit, I would get rid off pandas/tests. So before you create your zip layer, you can run the following in the layer's folder (mylayer from your ... | 5 | 3 |
69,350,888 | 2021-9-27 | https://stackoverflow.com/questions/69350888/list-from-key-in-django-querydict-return-one-element-instead-of-the-whole-list | I am using Django and I am accessing request.POST from my view. The code is as follows: data = request.POST print(data) Which returns: <QueryDict: {'name': ['Sam'], 'phone': ['+10795524594'], 'message': ['Es-sénia'], 'Coupon': [''], 'csrfmiddlewaretoken': ['xcGnoJOtnAmXcUBXe01t7ItuMC8BAFHE 6H9Egqd8BuooxLbp3ZrqvwzTZAxu... | Use data.getlist(key). It is a bit weird, see the docs: https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.QueryDict.getlist | 5 | 7 |
69,341,607 | 2021-9-27 | https://stackoverflow.com/questions/69341607/mypy-error-overloaded-function-signature-2-will-never-be-matched-signature-1 | I'm trying to understand how to use the overload decorator when typing functions. If I write the following code and run it through mypy: from typing import Union, overload @overload def myfunc(a: float, b: float) -> float: ... @overload def myfunc(a: int, b: int) -> int: ... def myfunc(a: Union[float, int], b: Union[fl... | mypy has a weird special case that treats int as valid where float is expected, because requiring people to write Union[int, float] all over the place would have been awkward enough to seriously hinder adoption of type annotations. That means myfunc(1, 2) matches both signatures. When multiple signatures of an overload... | 7 | 12 |
69,339,497 | 2021-9-26 | https://stackoverflow.com/questions/69339497/why-wont-mypy-understand-this-object-instantiation | I'm trying to define a class that takes another class as an attribute _model and will instantiate objects of that class. from abc import ABC from typing import Generic, TypeVar, Any, ClassVar, Type Item = TypeVar("Item", bound=Any) class SomeClass(Generic[Item], ABC): _model: ClassVar[Type[Item]] def _compose_item(self... | MyPy can sometimes be a bit funny about the types of classes. You can solve this by specifying _model as Callable[..., Item] (which, after all, isn't a lie) instead of Type[Item]: from abc import ABC from typing import Generic, TypeVar, Any, ClassVar, Callable Item = TypeVar("Item") class SomeClass(Generic[Item], ABC):... | 6 | 5 |
69,338,089 | 2021-9-26 | https://stackoverflow.com/questions/69338089/cant-import-streamlistener | I'm trying to create a data stream in Python using the Twitter API, but I'm unable to import the StreamListener correctly. Here's my code: import tweepy from tweepy import Stream from tweepy.streaming import StreamListener class MyListener(StreamListener): def on_data(self, data): try: with open('python.json', 'a') as ... | Tweepy v4.0.0 was released yesterday and it merged StreamListener into Stream. I recommend updating your code to subclass Stream instead. Alternatively, you can downgrade to v3.10.0. | 11 | 15 |
69,336,816 | 2021-9-26 | https://stackoverflow.com/questions/69336816/how-can-i-use-a-custom-search-field-model-property-to-search-in-django-admin | This is very similar to this question, but unfortunately, I still couldn't get it working. I have a model, with a property that combines a few fields: class Specimen(models.Model): lab_number = ... patient_name = ... specimen_type = ... @property def specimen_name(self): return f"{self.lab_number}_{self.patient_name}_{... | The correct way to filter on a property is to make an equivalent annotation for the property and filter on that instead. Looking at your property all it does is it concatenates some of the fields, corresponding to that Django has the Concat database function. Hence you can do the following annotation: from django.db.mo... | 6 | 6 |
69,328,143 | 2021-9-25 | https://stackoverflow.com/questions/69328143/why-doesnt-nan-raise-any-errors-in-python | In my opinion, things like float('nan') should be optimized, but apparently they aren't in Python. >>> NaN = float('nan') >>> a = [ 1, 2, 3, NaN ] >>> NaN in a True >>> float('nan') in a False Does it have any meaning with not optimizing nan like other things? In my thought, nan is only nan. As well as this, when you ... | Membership testing Two different instances of float('nan') are not equal to each other. They are "Not a Number" so it makes sense that they shouldn't also have to be equal. They are different instances of objects which are not numbers: print(float('nan') == float('nan')) # False As documented here: For container type... | 9 | 9 |
69,327,629 | 2021-9-25 | https://stackoverflow.com/questions/69327629/aws-lambda-in-container-python-works-locally-but-not-deployed | I try to wrap an R based application that is deployed to a docker container. I changed the base image to lambda/python3.9 and added another app with its own Dockerfile. This contains a simple python script as the handler for the function. In this handler I call the code to run the R script and upload the result to S3. ... | I wasn't able to get my container to run. But I decided to take the approach, where I use amazonlinux:2 as a baseimage and add the python stuff around afterwards and now it's working. Seems that the R stuff has some dependencies that interfere with the amazon libraries. By using this approach I faced another issue rega... | 6 | 1 |
69,329,521 | 2021-9-25 | https://stackoverflow.com/questions/69329521/create-an-enum-class-from-a-list-of-strings-in-python | When I run this from enum import Enum class MyEnumType(str, Enum): RED = 'RED' BLUE = 'BLUE' GREEN = 'GREEN' for x in MyEnumType: print(x) I get the following as expected: MyEnumType.RED MyEnumType.BLUE MyEnumType.GREEN Is it possible to create a class like this from a list or tuple that has been obtained from elsewh... | You can use the enum functional API for this: from enum import Enum myEnumStrings = ('RED', 'GREEN', 'BLUE') MyEnumType = Enum('MyEnumType', myEnumStrings) From the docs: The first argument of the call to Enum is the name of the enumeration. The second argument is the source of enumeration member names. It can be a w... | 6 | 13 |
69,327,239 | 2021-9-25 | https://stackoverflow.com/questions/69327239/how-to-validate-a-complex-nested-data-structure-with-pydantic | I had complex and nested data structure like below: { 0: { 0: {'S': 'str1', 'T': 4, 'V': 0x3ff}, 1: {'S': 'str2', 'T': 5, 'V': 0x2ff}}, 1: { 0: {'S': 'str3', 'T': 8, 'V': 0x1ff}, 1: {'S': 'str4', 'T': 7, 'V': 0x0ff}}, ...... } It's a 2D dictionary basically. The innermost dict follows {Str: str, str:int, str:int}, whi... | You could use Dict as custom root type with int as key type (with nested dict). Like so: from pydantic import BaseModel, StrictInt from typing import Union, Literal, Dict sample = {0: {0: {'S': 'str1', 'T': 4, 'V': 0x3ff}, 1: {'S': 'str2', 'T': 5, 'V': 0x2ff}}, 1: {0: {'S': 'str3', 'T': 8, 'V': 0x1ff}, 1: {'S': 'str4',... | 5 | 5 |
69,328,274 | 2021-9-25 | https://stackoverflow.com/questions/69328274/enum-raises-attributeerror-dict-object-has-no-attribute-member-names | I am trying to create an Enum class dynamically, using type(name, base, dict). from enum import Enum class FriendlyEnum(Enum): def hello(self): print(self.name + ' says hello!') The normal way works fine: class MyEnum(FriendlyEnum): foo = 1 bar = 2 MyEnum.foo.hello() # -> foo says hello! But if I try dynamically: MyE... | The Enum class can be called to dynamically create a new Enum type. This will also work for subclasses of Enum MyEnum = FriendlyEnum('MyEnum', {'foo': 1, 'bar': 2}) MyEnum.foo.hello() | 6 | 8 |
69,322,097 | 2021-9-24 | https://stackoverflow.com/questions/69322097/distinguishing-between-pydantic-models-with-same-fields | I'm using Pydantic to define hierarchical data in which there are models with identical attributes. However, when I save and load these models, Pydantic can no longer distinguish which model was used and picks the first one in the field type annotation. I understand that this is expected behavior based on the documenta... | As correctly noted in the comments, without storing additional information models cannot be distinguished when parsing. As of today (pydantic v1.8.2), the most canonical way to distinguish models when parsing in a Union (in case of ambiguity) is to explicitly add a type specifier Literal. It will look like this: from a... | 11 | 6 |
69,315,586 | 2021-9-24 | https://stackoverflow.com/questions/69315586/when-are-model-call-and-train-step-called | I am going through this tutorial on how to customize the training loop https://colab.research.google.com/github/tensorflow/docs/blob/snapshot-keras/site/en/guide/keras/customizing_what_happens_in_fit.ipynb#scrollTo=46832f2077ac The last example shows a GAN implemented with a custom training, where only __init__, train_... | These are different concepts and are used like this: train_step is called by fit. Basically, fit loops over the dataset and provide each batch to train_step (and then handles metrics, bookkeeping, etc., of course). call is used when you, well, call the model. To be precise, writing model(inputs) or in your case self(i... | 9 | 16 |
69,295,870 | 2021-9-23 | https://stackoverflow.com/questions/69295870/aws-data-wrangler-error-waitererror-waiter-bucketexists-failed-max-attempts-e | I am trying to read data from athena into python's pandas dataframe. However, I encounter this error WaiterError: Waiter BucketExists failed: Max attempts exceeded. Previously accepted state: Matched expected HTTP status code: 404 Do anyone have the same problem when using data wrangler? This is my code below import ... | I have faced the same issue and resolved it by specifying AWS_DEFAULT_REGION env variable. Like this. os.environ['AWS_DEFAULT_REGION'] = 'ap-northeast-1' # specify your AWS region. Execute it before you throw the query. | 5 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.