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 |
|---|---|---|---|---|---|---|
70,395,238 | 2021-12-17 | https://stackoverflow.com/questions/70395238/add-multiple-annotations-at-once-to-plotly-line-chart | I want to add many annotations with an arrow to my line plot. However, I don't want to add them all manually (like I did in the code below). This will be a hell of a job and I would rather add the annotations directly from the column df['text'] (or a list from this column). import plotly.express as px import pandas as ... | I figured it out myself. See below the answer: import plotly.express as px import pandas as pd # assign data of lists. data = {'x': [0, 1, 2, 3, 4, 5, 6, 7, 8], 'y': [0, 1, 3, 2, 4, 3, 4, 6, 5], 'text':["","","Annotation1","","Annotation2","","","",""]} # Create DataFrame df = pd.DataFrame(data) fig = px.line(df, x='x'... | 5 | 4 |
70,403,906 | 2021-12-18 | https://stackoverflow.com/questions/70403906/type-hint-for-a-list-with-0-or-more-items | I have a list which can have one or more items: a_list = ["apple"] But it can also be empty: a_list = [] In this case, which of List[str] and List[Optional[str]] is the appropriate type-hint for this variable and why? | List[str] includes all lists of strings, including the empty list. (From a typing perspective, an empty list of type List[str] is distinct from an empty list of type List[int]). Optional[str] is shorthand for Union[None, str], so List[Optional[str]] is the type of lists that can contain str values and Nones, not the ty... | 7 | 11 |
70,402,667 | 2021-12-18 | https://stackoverflow.com/questions/70402667/how-to-use-create-all-for-sqlalchemy-orm-objects-across-files | I have declared multiple orm classes in a.py: Base = declarative_base() class Message(Base): __tablename__ = "message" __table_args__ = {"schema": "stocktwits"} id = Column(BigInteger, primary_key=True) user_id = Column(BigInteger, nullable=False) body = Column(String, nullable=False) created_at = Column(DateTime, null... | Should I use Base.metadata.create_all(bind=engine)? Yes - all model classes that inherit from Base are registered in its metadata, so calling Base.metadata.create_all(engine) will create all the associated tables. In that case I have to figure out a way to share the Base object across files from a import Base in b... | 5 | 5 |
70,398,579 | 2021-12-17 | https://stackoverflow.com/questions/70398579/matplotlib-background-matches-vscode-theme-on-dark-mode-and-cant-see-axis | I just got a new PC and downloaded visual studio code. I'm trying to run the exact same plots as the code I had on my other PC (just plt.plot(losses)) but now matplotlib seems to have a dark background instead of white: I found this and this that had opposite problems. To clarify, I'm asking how to change the matplotl... | Difficult to be sure since I cannot reproduce your problem. Two things to try (both presume that you import matplotlib using import matplotlib.pyplot as plt): if you use plt.figure, add facecolor='white' parameter. Or try to run fig.set_facecolor('white') (fig here is the variable that stored the figure which facecolo... | 9 | 6 |
70,393,064 | 2021-12-17 | https://stackoverflow.com/questions/70393064/what-does-event-pos0-mean-in-the-pygame-library-i-saw-an-example-using-it | I don't understand how it works. I don't know if I understood the purpose of this function wrong. I tried to search what posx=event.pos[0] means but all I found was that if you want to take x, write the code of posx,posy=pygame.mouse.get_pos() and then take posx. But I still can't understand the method he followed in t... | See pygame.event module. The MOUSEMOTION, MOUSEBUTTONUP and MOUSEBUTTONDOWN events provide a position property pos with the position of the mouse cursor. pos is a tuple with 2 components, the x and y coordinate. e.g.: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: print("mouse cursor x", even... | 6 | 2 |
70,387,080 | 2021-12-17 | https://stackoverflow.com/questions/70387080/what-allows-bare-class-instances-to-have-assignable-attributes | I am trying to fill in a gap in my understanding of how Python objects and classes work. A bare object instance does not support attribute assignment in any way: > object().a = 5 # or > setattr(object(), 'a', 5) AttributeError: 'object' object has no attribute 'a' I assume that this is because a bare object instance ... | The object() class is like a fundamental particle of the python universe, and is the base class (or building block) for all objects (read everything) in Python. As such, the stated behavior is logical, for not all objects can (or should) have arbitrary attributes set. For example, it wouldn't make sense if a NoneType o... | 11 | 6 |
70,396,519 | 2021-12-17 | https://stackoverflow.com/questions/70396519/make-sure-each-print-is-on-a-newline-when-threading-indefinitely-in-python | just a small problem. I'm using around 6 threads, all of which are printing something every couple of seconds. Occasionally they print on the same line like this: OUTPUT OUTPUT OUTPUTOUTPUT OUTPUT OUTPUT This leaves an empty line and a double print as you can see. Is there a way that I can make sure this doesn't happe... | One way to manage this is to have a wrapper function for print and utilise a threading.Lock. Here's an example: from threading import Thread, Lock import time LOCK = Lock() def doprint(msg): with LOCK: print(msg) def athread(): doprint('Thread is starting') time.sleep(0.1) doprint('Thread is ending') threads = [] for _... | 7 | 8 |
70,393,970 | 2021-12-17 | https://stackoverflow.com/questions/70393970/how-to-add-missing-spaces-after-periods-using-regex-without-changing-decimals | I have a large piece of text that is missing spaces after some of the periods. However the text also contains decimal numbers. Here's what I have so far to fix the problem using regex (I'm using python): re.sub(r"(?!\d\.\d)(?!\. )\.", '. ', my_string) But the first escape group doesn't seem to work. It still matches pe... | You can use re.sub(r'\.(?!(?<=\d\.)\d) ?', '. ', text) See the regex demo. The trailing space is matched optionally, so if it is there, it will be removed and put back. Details \. - a dot (?!(?<=\d\.)\d) - do not match any further if the dot before was a dot between two digit ? - an optional space. See a Python dem... | 7 | 1 |
70,392,403 | 2021-12-17 | https://stackoverflow.com/questions/70392403/dividing-an-even-number-into-n-parts-each-part-being-a-multiple-of-2 | Let's assume I have the number 100 which I need to divide into N parts each of which shouldn't exceed 30 initially. So the initial grouping would be (30,30,30). The remainder (which is 10) is to be distributed among these three groups by adding 2 to each group in succession, thus ensuring that each group is a multiple ... | Simplified problem: forget about multiples of 2 First, let's simplify your problem for a second. Forget about the multiples of 2. Imagine you want to split a non-necessarily-even number n into k non-necessarily-even parts. Obviously the most balanced solution is to have some parts be n // k, and some parts be n // k + ... | 7 | 9 |
70,381,559 | 2021-12-16 | https://stackoverflow.com/questions/70381559/ensure-that-an-argument-can-be-iterated-twice | Suppose I have the following function: def print_twice(x): for i in x: print(i) for i in x: print(i) When I run: print_twice([1,2,3]) or: print_twice((1,2,3)) I get the expected result: the numbers 1,2,3 are printed twice. But when I run: print_twice(zip([1,2,3],[4,5,6])) the pairs (1,4),(2,5),(3,6) are printed onl... | I could insert a line at the beginning of the function: x = list(x). But this might be inefficient in case x is already a list, a tuple, a range, or any other iterator that can be iterated more than once. Is there a more efficient solution? Copying single-use iterables to a list is perfectly adequate, and reasonably ... | 9 | 2 |
70,390,050 | 2021-12-17 | https://stackoverflow.com/questions/70390050/pythonic-way-to-make-a-dictionary-from-lists-of-unequal-length-without-padding-n | I have a list of 'Id's' that I wish to associate with a property from another list, their 'rows'. I have found a way to do it by making smaller dictionaries and concatenating them together which works, but I wondered if there was a more pythonic way to do it? Code row1 = list(range(1, 6, 1)) row2 = list(range(6, 11, 1)... | This dict-comprehension should do it: rows = [row1, row2, row3, row4] {k: v for v, row in enumerate(rows, 1) for k in row} | 8 | 10 |
70,385,155 | 2021-12-16 | https://stackoverflow.com/questions/70385155/why-is-this-float-conversion-made | I have this dataframe Python 3.9.0 (v3.9.0:9cf6752276, Oct 5 2020, 11:29:23) [Clang 6.0 (clang-600.0.57)] on darwin >>> import pandas as pd >>> import datetime as datetime >>> pd.__version__ '1.3.5' >>> dates = [datetime.datetime(2012, 2, 3) , datetime.datetime(2012, 2, 4)] >>> x = pd.DataFrame({'Time': dates, 'Selecte... | x.iloc[0] selects a single "row". A new series object is actually created. When it decides on the dtype of that row, a pd.Series, it uses a floating point type, since that would not lose information in the "Nr" column. On the other hand, x['Selected'].iloc[0] first selects a column, which will always preserve the dtype... | 6 | 3 |
70,377,512 | 2021-12-16 | https://stackoverflow.com/questions/70377512/can-a-function-and-local-variable-have-the-same-name | Here's an example of what I mean: def foo(): foo = 5 print(foo + 5) foo() # => 10 The code doesn't produce any errors and runs perfectly. This contradicts the idea that variables and functions shouldn't have the same name unless you overwrite them. Why does it work? And when applied to real code, should I use differen... | foo = 5 creates a local variable inside your function. def foo creates a global variable. That's why they can both have the same name. If you refer to foo inside your foo() function, you're referring to the local variable. If you refer to foo outside that function, you're referring to the global variable. Since it evid... | 47 | 54 |
70,376,424 | 2021-12-16 | https://stackoverflow.com/questions/70376424/other-than-max-value-replace-all-value-to-0-in-each-column-pandas-python | i have a df which I want to replace values that are not the max value for each column to 0. code: data = { "A": [1, 2, 3], "B": [3, 5, 1], "C": [9, 0, 1] } df = pd.DataFrame(data) sample df: A B C 0 1 3 9 1 2 5 0 2 3 1 1 result trying to get: A B C 0 0 0 9 1 0 5 0 2 3 0 0 kindly advise. many thanks | Try: df[df!=df.max()] = 0 Output: A B C 0 0 0 9 1 0 5 0 2 3 0 0 | 6 | 3 |
70,374,346 | 2021-12-16 | https://stackoverflow.com/questions/70374346/how-to-remove-special-characters-from-rows-in-pandas-dataframe | I have a column in pandas data frame like the one shown below; LGA Alpine (S) Ararat (RC) Ballarat (C) Banyule (C) Bass Coast (S) Baw Baw (S) Bayside (C) Benalla (RC) Boroondara (C) What I want to do, is to remove all the special characters from the ending of each row. ie. (S), (RC). Desired output should be; LGA Alpi... | I have different approach using regex. It will delete anything between brackets: import re import pandas as pd df = {'LGA': ['Alpine (S)', 'Ararat (RC)', 'Bass Coast (S)'] } df = pd.DataFrame(df) df['LGA'] = [re.sub("[\(\[].*?[\)\]]", "", x).strip() for x in df['LGA']] # delete anything between brackets | 6 | 2 |
70,369,790 | 2021-12-15 | https://stackoverflow.com/questions/70369790/python-requests-response-403-forbidden | So I am trying to scrape this website: https://www.auto24.ee I was able to scrape data from it without any problems, but today it gives me "Response 403". I tried using proxies, passing more information to headers, but unfortunately nothing seems to work. I could not find any solution on the internet, I tried different... | The code here import requests headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36'} page = requests.get("https://www.auto24.ee/", headers=headers) print(page.text) Always will get something as the following <div class="cf-section... | 6 | 13 |
70,369,697 | 2021-12-15 | https://stackoverflow.com/questions/70369697/winsorizing-on-column-with-nan-does-not-change-the-max-value | Please note that a similar question was asked a while back but never answered (see Winsorizing does not change the max value). I am trying to winsorize a column in a dataframe using winsorize from scipy.stats.mstats. If there are no NaN values in the column then the process works correctly. However, NaN values seem to ... | It looks like the nan_policy is being ignored. But winsorization is just clipping, so you can handle this with pandas. def winsorize_with_pandas(s, limits): """ s : pd.Series Series to winsorize limits : tuple of float Tuple of the percentages to cut on each side of the array, with respect to the number of unmasked dat... | 5 | 3 |
70,368,592 | 2021-12-15 | https://stackoverflow.com/questions/70368592/pandas-group-by-cumsum-with-a-flag-condition | Assuming i have the following data frame date flag user num 0 2019-01-01 1 a 10 1 2019-01-02 0 a 20 2 2019-01-03 1 b 30 3 2019-03-04 1 b 40 I want to create a cumulative sum of the nums grouped by user only if flag == 1 so i will get this: date flag user num cumsum 0 2019-01-01 1 a 10 10 ... | You could multiply num by flag to make num = 0 where flag = 0, group by user, and cumsum: df['cumsum'] = df['num'].mul(df['flag']).groupby(df['user']).cumsum() Output: >>> df date flag user num cumsum 0 2019-01-01 1 a 10 10 1 2019-01-02 0 a 20 10 2 2019-01-03 1 b 30 30 3 2019-03-04 1 b 40 70 | 6 | 4 |
70,365,296 | 2021-12-15 | https://stackoverflow.com/questions/70365296/how-to-use-conda-update-n-base-conda-properly | I have two very simple questions regarding updating conda. I.e. when updating one of my environments with conda update --all, I get a warning ==> WARNING: A newer version of conda exists. <== current version: xyz1 latest version: xyz2 Please update conda by running $ conda update -n base conda My setup comprises a bas... | Q1: -n explicitly specifies environment - this command will run in any environment and even if you have no environment active. Q2: In all but very few cases updating conda will not affect the packages ought to be installed in other environments. conda plays the role as a package manager. The packages are pulled from an... | 28 | 7 |
70,363,722 | 2021-12-15 | https://stackoverflow.com/questions/70363722/python-pandas-groupby-and-if-any-condition | I have a dataframe similar to the one below, and I would like to create a new variable which contains true/false if for each project the sector "a" has been covered at least once. I'm trying with the group.by() function, and wanted to use the .transform() method but since my data is text, I don't know how to use it. p... | You could try the following: df['new_col'] = df.groupby('project')['sector'].transform(lambda x: (x == 'a').any() ) This will group by project and check if any 'a' is in the groups sectors | 9 | 4 |
70,363,072 | 2021-12-15 | https://stackoverflow.com/questions/70363072/group-together-consecutive-numbers-in-a-list | I have an ordered Python list of forms: [1, 2, 3, 4, 5, 12, 13, 14, 15, 20, 21, 22, 23, 30, 35, 36, 37, 38, 39, 40] How can I group together consecutive numbers in a list. A group like this: [[1, 2, 3, 4, 5], [12, 13, 14, 15], [20, 21, 22, 23,], [30], [35, 36, 37, 38, 39, 40]] I tried using groupby from here but was ... | You could use negative indexing: def group_by_missing(seq): if not seq: return seq grouped = [[seq[0]]] for x in seq[1:]: if x == grouped[-1][-1] + 1: grouped[-1].append(x) else: grouped.append([x]) return grouped Example Usage: >>> lst = [1, 2, 3, 4, 5, 12, 13, 14, 15, 20, 21, 22, 23, 30, 35, 36, 37, 38, 39, 40] >>> ... | 5 | 6 |
70,359,226 | 2021-12-15 | https://stackoverflow.com/questions/70359226/circular-objects-rotate-angle-detection | I'm trying to detect angle difference between two circular objects, which be shown as 2 image below. I'm thinking about rotate one of image with some small angle. Every time one image rotated, SSIM between rotated image and the another image will be calculated. The angle with maximum SSIM will be the angle difference. ... | Here's a way to do it: detect circles (for the example I assume circle is in the image center and radius is 50% of the image width) unroll circle images by polar coordinates make sure that the second image is fully visible in the first image, without a "circle end overflow" simple template matching Result for the fol... | 7 | 8 |
70,359,583 | 2021-12-15 | https://stackoverflow.com/questions/70359583/drf-from-django-conf-urls-import-url-in-django-4-0 | I've a project in django 3.2 and I've updated (pip install -r requirements.txt) to version 4.0 (new release) and I've currently the below error when I run the server in a virtual environment. I use DRF. Can't import => from rest_framework import routers in urls.py from django.conf.urls import url ImportError: cannot im... | As per the Django docs here: url(regex, view, kwargs=None, name=None)¶ This function is an alias to django.urls.re_path(). Deprecated since version 3.1: Alias of django.urls.re_path() for backwards compatibility. django.conf.urls.url() was deprecated since Django 3.1, and as per the release notes here, is removed i... | 5 | 2 |
70,344,193 | 2021-12-14 | https://stackoverflow.com/questions/70344193/pandas-dataframe-set-categories-the-inplace-parameter-in-pandas-categorical | I have following statement in my code: mcap_summary['cap'].cat.set_categories(['Large','Mid','Small','None'],inplace=True) Which now generates a warning as: D:\Python\Python39\lib\site-packages\pandas\core\arrays\categorical.py:2630: FutureWarning: The inplace parameter in pandas.Categorical.set_categories is deprecat... | pandas v1.3.0+ deprecated the inplace option. Deprecated the inplace parameter of Categorical.remove_categories(), Categorical.add_categories(), Categorical.reorder_categories(), Categorical.rename_categories(), Categorical.set_categories() and will be removed in a future version (GH37643) — https://pandas.pydata.org/... | 6 | 7 |
70,342,277 | 2021-12-13 | https://stackoverflow.com/questions/70342277/vs-code-python-execute-statement-during-debug | Is it possible to execute statements while the debug mode is active, possibly in the interactive mode? Let's say I'm working with a dataframe, and it doesn't behave as I want. I go line by line in debug mode, and I want to check some properties while doing that, for example the number of NaN values. Using the variable ... | When on a breakpoint you can use the Debug Console to run Python code in the current context. It's in the same tab as "Problems", "Output" and "Terminal", typically under the Editor pane. See in the upper menu "View > Debug Console". More info is available in the official Visual Studio Code documentation: Debug Conso... | 6 | 14 |
70,339,355 | 2021-12-13 | https://stackoverflow.com/questions/70339355/are-python-coroutines-stackless-or-stackful | I've seen conflicting views on whether Python coroutines (I primarily mean async/await) are stackless or stackful. Some sources say they're stackful: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2074r0.pdf 'Python coroutines are stackful.' How do coroutines in Python compare to those in Lua? Yes, Pytho... | TLDR: Going by the C++ definition, Python's coroutines too are stackless. The defining feature is that the coroutine's persistent state is stored separately from the stack. Coroutines are stackless: they suspend execution by returning to the caller and the data that is required to resume execution is stored separately... | 15 | 12 |
70,297,043 | 2021-12-9 | https://stackoverflow.com/questions/70297043/when-and-how-to-use-polynomial-fit-as-opposed-to-polyfit | Using Python 3.10.0 and NumPy 1.21.4. I'm trying to understand why Polynomial.fit() calculates wildly different coefficient values from polyfit(). In the following code: import numpy as np def main(): x = np.array([3000, 3200, 3400, 3600, 3800, 4000, 4200, 4400, 4600, 4800, 5000, 5200, 5400, 5600, 5800, 6000, 6200, 640... | According to Polynomial.fit() documentation, it returns: A series that represents the least squares fit to the data and has the domain and window specified in the call. If the coefficients for the unscaled and unshifted basis polynomials are of interest, do new_series.convert().coef. You can find in https://numpy.org... | 5 | 9 |
70,337,120 | 2021-12-13 | https://stackoverflow.com/questions/70337120/create-pydantic-model-for-optional-field-with-alias | Pydantic model for compulsory field with alias is created as follows class MedicalFolderUpdate(RWModel): id : str = Field(alias='_id') university : Optional[str] How to add optional field university's alias name 'school' as like of id? | It is not documented on the Pydantic website how to use the typing Optional with the Fields Default besides their allowed types in which they include the mentioned Optional: Optional[x] is simply shorthand for Union[x, None]; see Unions below for more detail on parsing and validation and Required Fields for details ab... | 6 | 13 |
70,272,742 | 2021-12-8 | https://stackoverflow.com/questions/70272742/how-to-check-for-floatnan-in-python | In some data I am processing I am encountering data of the type float, which are filled with 'nan', i.e. float('nan'). However checking for it does not work as expected: float('nan') == float('nan') >> False You can check it with math.isnan, but as my data also contains strings (For example: 'nan', but also other user... | Why not just wrap whatever you pass to math.isnan with another float conversion? If it was already a float (i.e. float('nan')) you just made a "redundant" call: import math def is_nan(value): return math.isnan(float(value)) And this seems to give your expected results: >>> is_nan(float('nan')) True >>> is_nan('nan') T... | 16 | 13 |
70,318,352 | 2021-12-11 | https://stackoverflow.com/questions/70318352/how-to-get-the-price-of-a-crypto-at-a-given-time-in-the-past | Is there any way I can use ccxt to extract the price of a crypto currency at a given time in the past? Example: get price of BTC on binance at time 2018-01-24 11:20:01 | You can use the fetch_ohlcv method on the binance class in CCXT def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): You'll need the date as a timestamp in milliseconds, and you can only get it precise to the minute, so take away the seconds, or you'll get the price for the minute after ti... | 7 | 11 |
70,297,011 | 2021-12-9 | https://stackoverflow.com/questions/70297011/why-is-numba-so-fast | I want to write a function which will take an index lefts of shape (N_ROWS,) I want to write a function which will create a matrix out = (N_ROWS, N_COLS) matrix such that out[i, j] = 1 if and only if j >= lefts[i]. A simple example of doing this in a loop is here: class Looped(Strategy): def copy(self, lefts): out = np... | Numba currently uses LLVM-Lite to compile the code efficiently to a binary (after the Python code has been translated to an LLVM intermediate representation). The code is optimized like a C++ code compiled with Clang with the flags -O3 and -march=native. This last parameter is very important as it enables LLVM to use w... | 7 | 9 |
70,329,648 | 2021-12-13 | https://stackoverflow.com/questions/70329648/type-friendly-delegation-in-python | Consider the following code sample def sum(a: int, b: int): return a + b def wrap(*args, **kwargs): # delegate to sum return sum(*args, **kwargs) The code works well except that type hint is lost. It's very common in Python to use *args, **kwargs to implement delegation pattern. It would be great to have a way to keep... | See https://github.com/python/typing/issues/270 for a long discussion of this problem. You can achieve this by decorating wrap with an appropriately typed identity function: F = TypeVar("F", bound=Callable) def copy_signature(_: F) -> Callable[..., F]: return lambda f: f def s(x: int, y: int) -> int: return x + y @copy... | 11 | 6 |
70,356,656 | 2021-12-14 | https://stackoverflow.com/questions/70356656/google-colab-change-variable-name-everywhere-in-code-cell | When I highlight a variable within a cell in colab, all the instances of that variable shines up. Is it possible to change all these instances of the variables at the same time and if such, how? | Google colab uses the same keys short-cuts of microsoft VS, just use Ctrl+D to add to the selection the next occurrence. Use instead Ctrl+Shift+L to select all occurrence. Once you selected the occurrences you can edit them by just typing the new name. If you use short variable names ( as X) this method will probably n... | 7 | 10 |
70,319,606 | 2021-12-11 | https://stackoverflow.com/questions/70319606/importerror-cannot-import-name-url-from-django-conf-urls-after-upgrading-to | After upgrading to Django 4.0, I get the following error when running python manage.py runserver ... File "/path/to/myproject/myproject/urls.py", line 16, in <module> from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (/path/to/my/venv/lib/python3.9/site-packages/django/conf... | django.conf.urls.url() was deprecated in Django 3.0, and is removed in Django 4.0+. The easiest fix is to replace url() with re_path(). re_path uses regexes like url, so you only have to update the import and replace url with re_path. from django.urls import include, re_path from myapp.views import home urlpatterns = [... | 204 | 323 |
70,300,675 | 2021-12-10 | https://stackoverflow.com/questions/70300675/fastapi-uvicorn-run-always-create-3-instances-but-i-want-it-1-instance | I run FastAPI at PyCharm IDE and it always run 3 workers. I don't know why, but, the last instance created is being accessed on every API call. Could anyone can help how can I get single running worker? Code: import uvicorn from fastapi import FastAPI from fastapi.templating import Jinja2Templates from starlette.middle... | Thanks to your last comment I understood better your question. Your real question So in fact your question is why is FastAPI object is created 3 times. In the log one can indeed see that you have 3 different memory adresses 0x102b35d50, 0x10daadf50, 0x1106bfe50 This doesn't mean that you have 3 workers, just that the F... | 15 | 24 |
70,339,062 | 2021-12-13 | https://stackoverflow.com/questions/70339062/read-spark-data-with-column-that-clashes-with-partition-name | I have the following file paths that we read with partitions on s3 prefix/company=abcd/service=xyz/date=2021-01-01/file_01.json prefix/company=abcd/service=xyz/date=2021-01-01/file_02.json prefix/company=abcd/service=xyz/date=2021-01-01/file_03.json When I read these with pyspark self.spark \ .read \ .option("basePath... | One way is to list the files under prefix S3 path using for example Hadoop FS API, then pass that list to spark.read. This way Spark won't detect them as partitions and you'll be able to rename the file columns if needed. After you load the files into a dataframe, loop through the df columns and rename those which are ... | 6 | 3 |
70,321,132 | 2021-12-12 | https://stackoverflow.com/questions/70321132/mypy-cant-find-types-for-my-local-package | I have two python packages. One is a util library, and one is an application that will use the util library (eventually I will have more apps sharing the library. I am using poetry for both, and the app specifies the common library as a dependency using the path and develop properties. For example, my layout looks some... | Assuming the "util" package has type hints, you'll want to add a py.typed file to it (in the root directory of the package) so mypy understands it comes with type hints. py.typed should be empty, it's just a flag file. If your package does not have type hints, then you'd have to add stubs files (.pyi). More details: ht... | 12 | 7 |
70,356,867 | 2021-12-14 | https://stackoverflow.com/questions/70356867/solverproblemerror-on-install-tensorfow-with-poetry | when i add tensoflow with poetry (poetry add tensorflow) i get this error : Using version ^2.7.0 for tensorflow Updating dependencies Resolving dependencies... (0.8s) SolverProblemError The current project's Python requirement (>=3.6,<4.0) is not compatible with some of the required packages Python requirement: - tens... | The error message tells you, that your project aims to be compatible for python >=3.6,<4.0 (You probably have ^3.6 in your pyproject.toml), but pytorch says it's compatible only for >=3.6, <3.10. This is only a subset of the range of you project definition. Poetry doesn't care about your current environment. It cares a... | 4 | 8 |
70,351,937 | 2021-12-14 | https://stackoverflow.com/questions/70351937/loading-pandas-dataframe-from-parquet-lists-are-deserialized-as-numpys-ndarra | import pandas as pd df = pd.DataFrame({ "col1" : ["a", "b", "c"], "col2" : [[1,2,3], [4,5,6,7], [8,9,10,11,12]] }) df.to_parquet("./df_as_pq.parquet") df = pd.read_parquet("./df_as_pq.parquet") [type(val) for val in df["col2"].tolist()] Output: [<class 'numpy.ndarray'>, <class 'numpy.ndarray'>, <class 'numpy.ndarray'>... | You can't change this behavior in the API, either when loading the parquet file into an arrow table or converting the arrow table to pandas. But you can write your own function that would look at the schema of the arrow table and convert every list field to a python list import pyarrow as pa import pyarrow.parquet as p... | 11 | 5 |
70,350,364 | 2021-12-14 | https://stackoverflow.com/questions/70350364/automatic-change-of-discord-about-me | THE PROBLEM: In Discord, as you may know, there is an "About me" section. This section is a description of a profile that you can write yourself. Bots can have an "About me" section. What I want to do is to edit this "About me" section automatically in discord.py; For example, the "About me" section of the bot changes ... | There is an answer. You can fully automate it with Python in a few lines. With the requests library. You just have to first include requests with: import requests Then, do a patch request requests.patch(url="https://discord.com/api/v9/users/@me", headers= {"authorization": token}, json = {"bio": abio} ) # With token y... | 5 | 8 |
70,353,961 | 2021-12-14 | https://stackoverflow.com/questions/70353961/tenacity-output-the-messages-of-retrying | The code import logging from tenacity import retry, wait_incrementing, stop_after_attempt import tenacity @retry(wait=wait_incrementing(start=10, increment=10, max=100), stop=stop_after_attempt(3)) def print_msg(): logging.info('Hello') logging.info("World") raise Exception('Test error') if __name__ == '__main__': logg... | You can write your own callback function to get attempt_number from retry_state. code: def log_attempt_number(retry_state): """return the result of the last call attempt""" logging.error(f"Retrying: {retry_state.attempt_number}...") log the attempt after every call of the function as shown below @retry(wait=wait_incre... | 4 | 13 |
70,351,360 | 2021-12-14 | https://stackoverflow.com/questions/70351360/keep-getting-307-temporary-redirect-before-returning-status-200-hosted-on-fast | Edit: I found the problem but not sure why this happens. Whenever I query: http://localhost:4001/hello/ with the "/" in the end - I get a proper 200 status response. I do not understand why. Original Post: Whenever I send a query to my app - I keep getting a 307 redirect. How to get my app to return regular status 200 ... | It happens because the exact path defined by you for your view is yourdomainname/hello/, so when you hit it without / at the end, it first attempts to get to that path but as it is not available it checks again after appending / and gives a redirect status code 307 and then when it finds the actual path it returns the ... | 58 | 114 |
70,324,030 | 2021-12-12 | https://stackoverflow.com/questions/70324030/using-apply-function-works-however-using-assign-the-same-function-does-not | I am a bit stuck, I have a working function that can be utilised using .apply(), however, I cannot seem to get it to work with .assign(). I'd like this to work with assign, so I can chain a number of transformations together. Could anyone point me in the right direction to resolving the issue? This works data = {'headi... | From the documentation of DataFrame.assign: DataFrame.assign(**kwargs) (...) Parameters **kwargs : dict of {str: callable or Series} The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas... | 8 | 8 |
70,347,526 | 2021-12-14 | https://stackoverflow.com/questions/70347526/filtering-a-mutli-index | C1 C2 C3 C4 A 12 True 89 9 False 77 5 True 23 B 9 True 45 5 True 45 2 False 78 C 11 True 10 8 False 08 12 False 09 C1 & C2 are the multi index. I'm hoping to get a result which gives me only values in C1 which have values both lower than 10 and greater than or equal to 10 in C2. So in ... | Use GroupBy.transform with GroupBy.any for test at least one condition match per groups, so possible last filter by m DataFrame: filter1 = df.index.get_level_values('C2') < 10 filter2 = df.index.get_level_values('C2') >= 10 m = (df.assign(filter1= filter1, filter2=filter2) .groupby(level=0)[['filter1','filter2']] .tran... | 7 | 2 |
70,290,958 | 2021-12-9 | https://stackoverflow.com/questions/70290958/asking-isinstance-on-a-union-type | I'm trying to ask an isinstance question on a user defined type: ConstData = Union[int, str]: from typing import Union, Optional ConstData = Union[int, str] def foo(x) -> Optional[ConstData]: if isinstance(x, ConstData): # <--- this doesn't work # if isinstance(x, (int, str)): <--- this DOES work ... return x return No... | About: "Still, with if isinstance(x, get_args(ConstData)): return x mypy can't infer that x has the correct return type. It complains it's Any" I think it is a bug in reveal_type(), Mypy undertands the narrowing of x type. As you can see in the following code, it does not raise an error when test() is called with x: de... | 8 | 2 |
70,344,739 | 2021-12-14 | https://stackoverflow.com/questions/70344739/backend-youtube-dl-py-line-54-in-fetch-basic-self-dislikes-self-ydl-info | I have the below code that has been used to download youtube videos. I automatically detect if it's a playlist or single video. However all the sudden it is giving the above error. What can be the problem? import pafy from log import * import tkinter.filedialog import pytube url = input("Enter url :") directory = tkint... | Your issue doesn't have anything to do with your code. Youtube does no longer have a dislike count, they simply removed it. You just have to wait for the pafy package to be updated accordingly, or patch the package locally and remove that part by yourself. Keep in mind there are at least 5 different pull requests open ... | 4 | 5 |
70,343,666 | 2021-12-14 | https://stackoverflow.com/questions/70343666/python-boto3-float-types-are-not-supported-use-decimal-types-instead | I'm using Python 3.7 to store data in a DynamoDB database and encountering the following error message when I try and write an item to the database: Float types are not supported. Use Decimal types instead. My code: ddb_table = my_client.Table(table_name) with ddb_table.batch_writer() as batch: for item in items: item... | Ran into the same issue and it turned out that Python was passing a string parameter as something else. The issue went away when I wrapped all of the items in str(). | 33 | 10 |
70,343,350 | 2021-12-14 | https://stackoverflow.com/questions/70343350/what-does-sys-executable-do-in-jupyter-notebook | I bought a book which comes with jupyter notebook. In the first chapter, it asks me to install required libraries. It use {sys.executable} -m. I never see it before. what does {sys.executable} and -m do? also why use --user at the end? typically, I just use ! pip install numpy==1.19.2 Anyone can help me understand it? ... | Let's split this question up into multiple parts. Part 1 From the Python documentation: sys.executable A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, sys.executable will be an emp... | 7 | 7 |
70,339,388 | 2021-12-13 | https://stackoverflow.com/questions/70339388/using-numba-with-np-concatenate-is-not-efficient-in-parallel | I’m having some trouble getting np.concatenate to parallelize efficiently. Here is a minimal working example. (I know that here I could sum a and b separately, but I am focussing on parallelizing the concatenate operation since this is what I need to do in my project. I would then do further operations on the concatena... | The main issue comes from contention of the allocator. The cc function creates many implicit small temporary arrays. For example np.random.rand do that as well as r < 0.5 or even a = r[condition], not to mention np.concatenate. Temporary arrays generally needs to be allocated in the heap using a given allocator. The de... | 5 | 10 |
70,332,426 | 2021-12-13 | https://stackoverflow.com/questions/70332426/type-hinting-a-function-that-takes-the-return-type-as-parameter | Is there a way to type hint a function that takes as argument its return type? I naively tried to do this: # NOTE: # This code does not work! # # If I define `ret_type = TypeVar("ret_type")` it becomes syntactically # correct, but type hinting is still broken. # def mycoerce(data: Any, ret_type: type) -> ret_type retur... | Have a look at Generics, especially TypeVar. You can do something like this: from typing import TypeVar, Callable R = TypeVar("R") D = TypeVar("D") def mycoerce(data: D, ret_type: Callable[[D], R]) -> R: return ret_type(data) a = mycoerce("123", int) # desired: a type hinted to int b = mycoerce("123", float) # desired:... | 5 | 5 |
70,335,028 | 2021-12-13 | https://stackoverflow.com/questions/70335028/how-do-i-convert-an-ioc-country-code-to-country-name | I have a pandas dataframe import pandas as pd s = pd.DataFrame({'ioc' : ['ESP', 'CYP', 'USA', 'ESP', 'NED']}) and I want to return out = pd.DataFrame( {'ioc' : ['ESP', 'CYP', 'USA', 'ESP', 'NED'], 'countryName' : ['Spain', 'Cyprus', 'United States of America', 'Spain', 'Netherlands']}) | Use List of IOC country codes ioc = pd.read_html('https://en.wikipedia.org/wiki/List_of_IOC_country_codes')[0] ioc = ioc.assign(Code=ioc['Code'].str[-3:]).set_index('Code')['National Olympic Committee'] s['countryName'] = s['ioc'].map(ioc) print(s) # Output: ioc countryName 0 ESP Spain 1 CYP Cyprus 2 USA United States ... | 4 | 6 |
70,328,519 | 2021-12-12 | https://stackoverflow.com/questions/70328519/find-cosine-similarity-between-two-columns-of-type-arraydouble-in-pyspark | I am trying to find the cosine similarity between two columns of type array in a pyspark dataframe and add the cosine similarity as a third column, as shown below Col1 Col2 Dot Prod [0.5, 0.6 ... 0.7] [0.5, 0.3 .... 0.1] dotProd(Col1, Col2) The current implementation I have is: import pyspark.sql.functions ... | For the array of double, you can use the aggregate function. df = spark.createDataFrame([[[0.1, 0.5, 2.0, 1.0], [3.0, 2.4, 0.2, 1.1]]], ['Col1', 'Col2']) df.show() +--------------------+--------------------+ | Col1| Col2| +--------------------+--------------------+ |[0.1, 0.5, 2.0, 1.0]|[3.0, 2.4, 0.2, 1.1]| +---------... | 5 | 4 |
70,318,373 | 2021-12-11 | https://stackoverflow.com/questions/70318373/copying-a-list-of-numpy-arrays | I am working with (lists of) lists of numpy arrays. As a bare bones example, consider this piece of code: a = [np.zeros(5)] b = a.copy() b[0] += 1 Here, I copy a list of one array from a to b. However, the array itself is not copied, so: print(a) print(b) both give [array([1., 1., 1., 1., 1.])]. If I want to make a c... | What you are looking for is a deepcopy import numpy as np import copy a = [np.zeros(5)] b = copy.deepcopy(a) b[0] += 1 # a[0] is not changed This is actually method recommended in numpy doc for the deepcopy of object arrays. | 5 | 4 |
70,327,505 | 2021-12-12 | https://stackoverflow.com/questions/70327505/python-type-checking-literalfalse-overload-and-noreturn | I have the following (typed) Python function: from typing import overload, Literal, NoReturn @overload def check(condition: Literal[False], msg: str) -> NoReturn: pass @overload def check(condition: Literal[True], msg: str) -> None: pass def check(condition, msg): if not condition: raise Exception(msg) Pyright type-ch... | I posted this to the Pyright issue tracker and was informed that I had to add a Union[NoReturn, None] annotation to the check implementation to resolve the error: [This] falls out of pyright's rules for return type inference. Pyright will infer a NoReturn type only in the case that all code paths raise an exception. I... | 7 | 5 |
70,316,221 | 2021-12-11 | https://stackoverflow.com/questions/70316221/difference-between-gridsearchcv-and-cross-val-score | I have a binary time series classification problem. Since it is a time series, I can't just train_test_split my data. So, I used the object tscv = TimeSeriesSplit() from this link, and got something like this: I can see from GridSearchCV and cross_val_score that i can pass as parameter my split strategy cv = tscv. But... | Grid search is a method to evaluate models by using different hyperparameter settings (the values of which you define in advance). Your GridSearch can use cross validation (hence, GridSearchCV exists) in order to deliver a final score for the the different parameter settings of your model. After the training and the ev... | 5 | 5 |
70,326,002 | 2021-12-12 | https://stackoverflow.com/questions/70326002/typeerror-webdriver-init-got-an-unexpected-keyword-argument-firefox-opti | I'm trying to create a script which downloads a file from a website and for this I want to change the download filepath. When I try to do this with the Firefox options it gives me this error: TypeError: WebDriver.__init__() got an unexpected keyword argument 'firefox_options' Code: from selenium import webdriver from ... | The browser option parameter firefox_options was deprecated in Selenium 3.8.0 Browser option parameters are now standardized across drivers as options. firefox_options, chrome_options, and ie_options are now deprecated Instead you have to use options as follows: from selenium.webdriver.firefox.options import Opti... | 15 | 15 |
70,286,615 | 2021-12-9 | https://stackoverflow.com/questions/70286615/extract-mutiple-tables-from-excel | I have seen many relatable posts for my question but couldn't find the proper solutions. read excel sheet containing multiple tables, tables that have headers with a non white background cell color here is the link of that excel data: https://docs.google.com/spreadsheets/d/1m4v_wbIJCGWBigJx53BRnBpMDHZ9CwKf/edit?usp=sha... | Here is one way of creating dataframes out of that excel file. See comments in the code itself. You can uncomment some print() to see how this is developed. Code import pandas as pd import numpy as np def get_dataframes(fn): """ Returns 3 dataframes from the 3 tables given inside excel file fn. """ # (1) Read file df_s... | 5 | 4 |
70,315,657 | 2021-12-11 | https://stackoverflow.com/questions/70315657/get-width-and-height-of-plotly-figure | e.g. if I write import plotly.express as px df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", facet_col="sex") then how can I get the width and height of fig? If I do fig.layout.width then I get None. | That is the correct way to get the width. fig.layout.width is None because the width has not been set yet. If you set it explicitly you can retrieve it fig = px.scatter(df, x="total_bill", y="tip", facet_col="sex", width=200) >>> fig.layout.width 200 If not set explicitly the width is initialised when executing the sh... | 4 | 10 |
70,315,213 | 2021-12-11 | https://stackoverflow.com/questions/70315213/either-of-the-two-pydantic-attributes-should-be-optional | I want validate a payload schema & I am using Pydantic to do that. The class created by inheriting Pydantic's BaseModel is named as PayloadValidator and it has two attributes, addCustomPages which is list of dictionaries & deleteCustomPages which is a list of strings. class NestedCustomPages(BaseModel): """This is the ... | There was a question on this a while ago on the pydantic Github page: https://github.com/samuelcolvin/pydantic/issues/506. The conclusion there includes a toy example with a model that requires either a or b to be filled by using a validator: from typing import Optional from pydantic import validator from pydantic.main... | 5 | 6 |
70,311,592 | 2021-12-10 | https://stackoverflow.com/questions/70311592/numba-np-convolve-really-slow | I'm trying to speed up a piece of code convolving a 1D array (filter) over each column of a 2D array. Somehow, when I run it with numba's njit, I get a 7x slow down. My thoughts: Maybe column indexing is slowing it down, but switching to row indexing didn't affect performance Maybe slice indexing the results of the co... | The problem comes from the Numba implementation of np.convolve. This is a known issue. It turns out that the current Numba implementation is much slower than the one of Numpy (version <=0.54.1 tested on Windows). Under the hood On one hand, the Numpy implementation call correlate which itself performs a dot product th... | 6 | 12 |
70,302,056 | 2021-12-10 | https://stackoverflow.com/questions/70302056/define-a-pydantic-nested-model | If I use GET (given an id) I get a JSON like: { "data": { "id": "81", "ks": { "k1": 25, "k2": 5 }, "items": [ { "id": 1, "name": "John", "surname": "Smith" }, { "id": 2, "name": "Jane", "surname": "Doe" } ] }, "server-time": "2021-12-09 14:18:40" } with the particular case (if id does not exist): { "data": { "id": -1,... | If you don't need data validation that pydantic offers, you can use data classes along with the dataclass-wizard for this same task. It's slightly easier as you don't need to define a mapping for lisp-cased keys such as server-time. Simple example below: from __future__ import annotations from dataclasses import datacl... | 8 | 4 |
70,303,895 | 2021-12-10 | https://stackoverflow.com/questions/70303895/python-3-10-asyncio-gather-shows-deprecationwarning-there-is-no-current-event | I have a Django app and in one of its views I use asyncio in order to make some concurent requests to an external component. Here is the idea: import asyncio async def do_request(project): result = ... return result def aggregate_results(projects: list): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) resu... | According to the documentation, this happens because there is no event loop running at the time when you call gather. Deprecated since version 3.10: Deprecation warning is emitted if no positional arguments are provided or not all positional arguments are Future-like objects and there is no running event loop. As you... | 5 | 7 |
70,297,207 | 2021-12-9 | https://stackoverflow.com/questions/70297207/python-should-i-upload-my-coverage-file-to-my-github-repository | Im using python 3.9 and coverage 6.2 I would like to have a record of my most recent coverage but Im not sure if I should upload my .coverage file. Im guessing no since it sort of has info about my directory layout. So i would like to know how I should go about that, is it even standard to upload such a thing? If not, ... | Most people don't upload the .coverage or HTML report, because they don't need to track it over time. But there's no harm in uploading them. You mention directory layout as if it was a secret to protect, but isn't your layout already committed to GitHub? If you want to commit the HTML report, you will need to remove th... | 8 | 7 |
70,301,475 | 2021-12-10 | https://stackoverflow.com/questions/70301475/difference-between-functools-cache-and-lru-cache | Recently I came across functools.cache and didn't know how it differs from functools.lru_cache. I found posts about the difference between functools.cached_property and lru_cache but nothing specifically for cache and lru_cache. | functools.cache was newly added in version 3.9. The documentation states: Simple lightweight unbounded function cache. Sometimes called “memoize”. Returns the same as lru_cache(maxsize=None), creating a thin wrapper around a dictionary lookup for the function arguments. Because it never needs to evict old values, this... | 50 | 65 |
70,298,050 | 2021-12-9 | https://stackoverflow.com/questions/70298050/how-to-send-a-document-with-telegram-bot | I followed a tutorial in youtube on how to create a Telegram Bot and for now it can only send messages but I want to send even files like documents or audio, video, photos etc... For now im just trying to send a file but I'm pretty confused and I don't know how to do it. The source code of the bot is divided in 2 main ... | Try the following as your send_document function: def send_document(update, context): chat_id = update.message.chat_id document = open('image1.png', 'rb') context.bot.send_document(chat_id, document) And add the command 'send' to the bot in the main function like this: dp.add_handler(CommandHandler("send", send_docume... | 5 | 11 |
70,296,308 | 2021-12-9 | https://stackoverflow.com/questions/70296308/how-to-create-substrings-efficiently | Given a string, typically a sentence, I want to extract all substrings of lengths 3, 4, 5, 6. How can I achieve this efficiently using only Python's standard library? Here is my approach, I am looking for one which is faster. To me it seems the three outer loops are inevitable either way, but maybe there is a low-level... | Well, I think this is not possible to improve the algorithm, but you can micro-optimize the function: def naive3(test_sentence,start,end): rng = range(start,end) return [word[i:i+size] for word in test_sentence if len(word) >= start for size in rng for i in range(len(word)+1-size)] Python 3.8 introduces assignment Exp... | 5 | 4 |
70,281,103 | 2021-12-8 | https://stackoverflow.com/questions/70281103/can-winget-install-an-older-version-of-python | Currently, the latest Python 3 offered through winget is 3.10.150.0: Name Id Version Match Source ----------------------------------------------------------------------------------------------------------------------------------- Python 3 Python.Python.3 3.10.150.0 Command: python winget but I'd like to install 3.9 an... | winget install -e --id Python.Python -v 3.9.0 | 18 | 21 |
70,275,016 | 2021-12-8 | https://stackoverflow.com/questions/70275016/split-torch-dataset-without-shuffling | I'm using Pytorch to run Transformer model. when I want to split data (tokenized data) i'm using this code: train_dataset, test_dataset = torch.utils.data.random_split( tokenized_datasets, [train_size, test_size]) torch.utils.data.random_split using shuffling method, but I don't want to shuffle. I want to split it seq... | The random_split method has no parameter that can help you create a non-random sequential split. The easiest way to achieve a sequential split is by directly passing the indices for the subset you want to create: # Created using indices from 0 to train_size. train_dataset = torch.utils.data.Subset(tokenized_datasets, r... | 6 | 18 |
70,272,486 | 2021-12-8 | https://stackoverflow.com/questions/70272486/convert-each-row-of-a-dataframe-to-list | I have a dataframe like this: df = pd.DataFrame({'A': ['1', '2', '3'], 'B': ['aa', 'b', 'c']}) A B 0 1 aa 1 2 b 2 3 c I want to convert each row of column B to a list. For example, my desired output is something like this: df_new A B 0 1 [aa] 1 2 [b] 2 3 [c] | You can use split to do stuff. import pandas as pd df = pd.DataFrame({'A': ['1', '2', '3'], 'B': ['a', 'b', 'c']}) df['B'] = df['B'].apply(lambda x: x.split(',')) print(df) | 4 | 6 |
70,270,181 | 2021-12-8 | https://stackoverflow.com/questions/70270181/enter-doesnt-work-in-vs-code-for-python | I installed Anaconda. Somehow, afterwards, when I press Enter in Python files, it no longer works. This error shows up: command 'pythonIndent.newlineAndIndent' not found How do I solve this problem? | Try checking your keybindings.json file, also disable all VS Code extensions and install them one by one. Maybe it's caused by some buggy extension. | 9 | 3 |
70,185,942 | 2021-12-1 | https://stackoverflow.com/questions/70185942/why-i-am-getting-notimplementederror-database-objects-do-not-implement-truth-v | I am trying to connect Django with MongoDB using Djongo. I have changed the Database parameter but I am getting this error: NotImplementedError: Database objects do not implement truth value testing or bool(). when I am running the makemigration command. Please can anybody explain why I am getting this error and how ... | The problem is with the new version of pymongo (4.0 from 29.11.2021) which is not supported by Djongo 1.3.6. You need to install pymongo 3.12.1. | 28 | 87 |
70,187,831 | 2021-12-1 | https://stackoverflow.com/questions/70187831/hide-variable-e-g-password-from-print-and-call-of-pydantic-data-model | I am using pydantic for some user/password data model. When the model is printed, I want to replace the value of password with something else (*** for example) to prevent that the password is e.g. written into log-files or the console accidentally. from pydantic import BaseModel class myUserClass(BaseModel): User = 'fo... | Pydantic provides SecretStr data type. Which is replaced by *** when converted to str (e.g printed) and actual value can be obtained by get_secret_value() method: class Foobar(BaseModel): password: SecretStr empty_password: SecretStr # Initialize the model. f = Foobar(password='1234', empty_password='') # Assert str an... | 5 | 7 |
70,189,517 | 2021-12-1 | https://stackoverflow.com/questions/70189517/requests-chunkedencodingerror-with-requests-get-but-not-when-using-postman | I have a URL that can only be accessed from within our VPC. If I enter the URL via Postman, I am able to see the content (which is a Pdf) and I'm able to save the output to a file perfectly fine. However, when trying to automate this using python requests with import requests r = requests.get(url, params=params) I get... | I think the reason for this error is server is not correctly encoding the chunk. some of the chunk sizes are not integer b'' due to which you are getting chunk encoding error. Try below code import requests from requests.exceptions import ChunkedEncodingError response = requests.get(url, params=params, stream=True) try... | 11 | 15 |
70,219,200 | 2021-12-3 | https://stackoverflow.com/questions/70219200/python-fastapi-base-path-control | When I use FastAPI , how can I sepcify a base path for the web-service? To put it another way - are there arguments to the FastAPI object that can set the end-point and any others I define, to a different root path? For example , if I had the code with the spurious argument root below, it would attach my /my_path end-p... | You can use an APIRouter and add it to the app after adding the paths: from fastapi import APIRouter, FastAPI app = FastAPI() prefix_router = APIRouter(prefix="/my_server_path") # Add the paths to the router instead @prefix_router.get("/my_path") def service( request : Request ): return { "message" : "my_path" } # Now ... | 10 | 17 |
70,199,494 | 2021-12-2 | https://stackoverflow.com/questions/70199494/how-to-make-vscode-honor-black-excluded-files-in-pyproject-toml-configuration-wh | I have the following pyproject.toml for configuring black: [tool.black] exclude = 'foo.py' If I run black . from the project's root folder that only contains foo.py, I get No Python files are present to be formatted. Nothing to do �😴 as expected. However, when I save foo.py from within VS Code (I have black configure... | The --force-exclude option also excludes files if they are explicitly listed. Thus, it also works with formatOnSave in VS Code. In the example above, simply use [tool.black] force-exclude = 'foo.py' | 5 | 2 |
70,263,918 | 2021-12-7 | https://stackoverflow.com/questions/70263918/how-to-prevent-multiprocessing-from-inheriting-imports-and-globals | I'm using multiprocessing in a larger code base where some of the import statements have side effects. How can I run a function in a background process without having it inherit global imports? # helper.py: print('This message should only print once!') # main.py: import multiprocessing as mp import helper # This print... | Is there a resources that explains exactly what the multiprocessing module does when starting an mp.Process? Super quick version (using the spawn context not fork) Some stuff (a pair of pipes for communication, cleanup callbacks, etc) is prepared then a new process is created with fork()exec(). On windows it's Create... | 5 | 2 |
70,184,494 | 2021-12-1 | https://stackoverflow.com/questions/70184494/on-what-systems-does-python-not-use-ieee-754-double-precision-floats | Python makes various references to IEEE 754 floating point operations, but doesn't guarantee 1 2 that it'll be used at runtime. I'm therefore wondering where this isn't the case. CPython source code defers to whatever the C compiler is using for a double, which in practice is an IEEE 754-2008 binary64 on all common sys... | Update: Since I wrote the original answer below, the situation has changed slightly. CPython versions 3.11 and later now require that the platform C double follows the IEEE 754 binary64 format. This was mostly a matter of convenience for developers - it allowed us to remove special-case code that was in practice close ... | 10 | 15 |
70,236,730 | 2021-12-5 | https://stackoverflow.com/questions/70236730/ssl-sslcertverificationerror-ssl-certificate-verify-failed-certificate-verif | I was playing with some web frameworks for Python, when I tried to use the framework aiohhtp with this code (taken from the documentation): import aiohttp import asyncio #******************************** # a solution I found on the forum: # https://stackoverflow.com/questions/50236117/scraping-ssl-certificate-verify-fa... | Picking up on the comment by @salparadise, the following worked for me: session.get("https://python.org", ssl=False) Edit (2023-03-10): I've run into this problem again and have found this answer to a similar question, which provides a much better long-term solution. In short: use the certificates in the certifi packa... | 11 | 6 |
70,184,634 | 2021-12-1 | https://stackoverflow.com/questions/70184634/setting-a-default-value-based-on-another-value | I have the following Pydantic model: from pydantic import BaseModel import key class Wallet(BaseModel): private_key: str = Field(default_factory=key.generate_private_key) address: str I want address to have a default_factory as a function that takes a private_key as input and returns an address. My intentions would be... | Another option is to just use @validator because in it you can access previously validated fields. From the documentation: validators are "class methods", so the first argument value they receive is the UserModel class, not an instance of UserModel. the second argument is always the field value to validate; it can be... | 9 | 6 |
70,253,218 | 2021-12-6 | https://stackoverflow.com/questions/70253218/macos-m1-system-is-detected-as-arm-by-python-package-even-though-im-using-roset | I'm on a Macbook with M1 (Apple ARM architecture) and I've tried running the following Python code using the layoutparser library, which indirectly uses pycocotools: import layoutparser as lp lp.Detectron2LayoutModel() And I've received the error: [...] ImportError: dlopen([...]/.venv/lib/python3.9/site-packages/pycoc... | Charles Duffy explained the problem in the comments, thank you! 😃 When I checked the platform in Python, it was indeed ARM: > python -c 'import platform; print(platform.platform())' macOS-12.0.1-arm64-i386-64bit So I had been using a Python installation for ARM. Now I installed brew and then python3 from the Rosetta ... | 6 | 12 |
70,229,552 | 2021-12-4 | https://stackoverflow.com/questions/70229552/package-requirement-psycopg2-2-9-1-not-satisfied-pycharm-macos | after long hours of trying: i installed psycopg2==2.9.1 with pip installed with pip I tried adding it to all the interpreter paths i could find but still keep getting this message: error message I tried as well restarting pycharm, invalidate caches .. When trying to just install it with pycharm i get this error messege... | Usually had something similar happen to me while using anaconda, and I had to manually delete the folder location and reinstall to be importable (even with new enviroment). I would suggest you try anaconda, miniconda with the same requirements and see if those help you out with your environment problem. Note: This requ... | 8 | -2 |
70,192,880 | 2021-12-2 | https://stackoverflow.com/questions/70192880/how-to-know-what-version-of-a-github-action-to-use | I've noticed in various GitHub Action workflow examples, often when calling a pre-defined action (with the uses: syntax) then a particular version of that action is specified. For example: steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.x' The above workf... | How to know which version to use? When writing a workflow and including an action, I recommend looking at the Release tab on the GitHub repository. For actions/setup-python, that would be https://github.com/actions/setup-python/releases On that page, you should see what versions there are and what the latest one is. Yo... | 13 | 21 |
70,184,543 | 2021-12-1 | https://stackoverflow.com/questions/70184543/import-numpy-could-not-be-resolved-pylance | I have wrote the following code: import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) y = x**2 plt.plot(x, y) plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("graph of $x^2$") plt.show() When I run the code, it shows the following error: I have installed NumPy, successfully, but still get... | Try this in VSCode IDE: (1) ctrl-shift-p (2) In search box, type python and then select Python: Select Interpreter (3) select Python 3.10.4 or any one matches your verion the problem usually caused by IDE didn't pick up the right interpreter | 19 | 49 |
70,266,649 | 2021-12-7 | https://stackoverflow.com/questions/70266649/python-difference-of-typing-with-asyncgenerator-or-asynciterator | I make creating a discord asynchronous library that is fully typed. I have a method that create objects from a aiohttp get requests such as the following example: async def get_bans(self): """|coro| Fetches all the bans in the guild. """ data = await self._http.get(f"guilds/{self.id}/bans") for ban_data in data: yield ... | Official documentation describes AsyncIterator as: ... that provide __aiter__ and __anext__ methods ... AsyncGenerator leads from documentation to PEP525. ... generator is any function containing one or more yield expressions ... The result of calling an asynchronous generator function is an asynchronous generator... | 5 | 8 |
70,240,506 | 2021-12-6 | https://stackoverflow.com/questions/70240506/why-is-numpy-native-on-m1-max-greatly-slower-than-on-old-intel-i5 | I just got my new MacBook Pro with M1 Max chip and am setting up Python. I've tried several combinational settings to test speed - now I'm quite confused. First put my questions here: Why python run natively on M1 Max is greatly (~100%) slower than on my old MacBook Pro 2016 with Intel i5? On M1 Max, why there isn't s... | Update Mar 28 2022: Please see @AndrejHribernik's comment below. How to install numpy on M1 Max, with the most accelerated performance (Apple's vecLib)? Here's the answer as of Dec 6 2021. Steps I. Install miniforge So that your Python is run natively on arm64, not translated via Rosseta. Download Miniforge3-MacOSX-... | 19 | 18 |
70,265,306 | 2021-12-7 | https://stackoverflow.com/questions/70265306/python-selenium-aws-lambda-change-webgl-vendor-renderer-for-undetectable-headles | Concept: Using AWS Lambda functions with Python and Selenium, I want to create a undetectable headless chrome scraper by passing a headless chrome test. I check the undetectability of my headless scraper by opening up the test and taking a screenshot. I ran this test on a Local IDE and on a Lambda server. Implementati... | A solution I found for the missing WebGL Vendor/Renderer was using a docker container instead of the normal Lambda layers when creating a function. Not only does the storage increase by a factor of 40X but it also solves the WebGL Vendor/Renderer problem: | 10 | 1 |
70,203,927 | 2021-12-2 | https://stackoverflow.com/questions/70203927/how-to-prevent-alembic-revision-autogenerate-from-making-revision-file-if-it-h | I have project where I'm using SQLAlchemy for models and I'm trying to integrate Alembic for making migrations. Everything works as expected when I change models and Alembic sees that models have changed -> it creates good migration file with command: alembic revision --autogenerate -m "model changed" But when I have N... | Accepted answer does not answer the question. The correct answer is: Yes, you can call alembic revision --autogenerate and be sure that only if there are changes a revision file would be generated: As per alembic's documentation Implemented in Flask-Migrate (exactly in this file), it's just a change to env.py to accoun... | 8 | 10 |
70,193,443 | 2021-12-2 | https://stackoverflow.com/questions/70193443/colab-notebook-cannot-import-name-container-abcs-from-torch-six | I'm trying to run the deit colab notebook found here: https://colab.research.google.com/github/facebookresearch/deit/blob/colab/notebooks/deit_inference.ipynb but I'm running into an issue in the second cell, specifically the import timm line, which returns this: ImportError: cannot import name 'container_abcs' from 't... | Issue related to this error here: Try a specific version of timm library: !pip install timm==0.3.2 | 5 | 3 |
70,183,853 | 2021-12-1 | https://stackoverflow.com/questions/70183853/send-pathlib-path-data-to-fastapi-posixpath-is-not-json-serializable | I have built an API using FastAPI and am trying to send data to it from a client. Both the API and the client use a similar Pydantic model for the data that I want to submit. This includes a field that contains a file path, which I store in a field of type pathlib.path. However, FastAPI does not accept the submission b... | The problem with you code is, that you first transform the pydantic model into a dict, which you then pass to the client, which uses its own json serializer and not the one provided by pydantic. submission.dict() converts any pydantic model into a dict but keeps any other datatype. With client.post("/", json=payload) r... | 8 | 3 |
70,251,565 | 2021-12-6 | https://stackoverflow.com/questions/70251565/how-to-implement-the-hindenburg-omen-indicator | As defined here the Hindenburg omen indicator is: The daily number of new 52-week highs and 52-week lows in a stock market index are greater than a threshold amount (typically 2.2%). To me it means, we roll daily and look back 52 weeks or 252 business/trading days, then count the number of highs (or lows) and finally... | Interesting question! Could I suggest the following code - it runs much faster than the apply solution because it is vectorised, and also lays out the steps a bit more clearly so you can inspect the interim results. I got a different result to your code - you can compare by also plotting your result on the timeseries a... | 5 | 1 |
70,229,330 | 2021-12-4 | https://stackoverflow.com/questions/70229330/embedding-jupyter-notebook-google-colab-in-django-app | I wanted to build a website and embed the jupyter notebook functionality of being able to create cells and run python code within it into my website For creating a website I m using Django and I would like to embed either the google collab or jupyter notebook By the way I have researched enough and have been stuck with... | You have many options to do that: Note:: I used "jupyter-lab" you can use "jupyter notebook" 1- The first option to redirect to "jupyter notebook" django view.py from django.shortcuts import redirect,HttpResponse import subprocess import time def open_jupiter_notbook(request): b= subprocess.check_output("jupyter-lab li... | 7 | 4 |
70,247,344 | 2021-12-6 | https://stackoverflow.com/questions/70247344/save-video-in-opencv-with-h264-codec | I am using opencv-python==4.5.1.48 and python3.9 docker. I want to save a video in h264 format. Here is my function to save a video: import cv2 def save_video(frames): fps = 30 video_path = '/home/save_test.mp4' fourcc = cv2.VideoWriter_fourcc(*'h264') video_writer = cv2.VideoWriter(video_path, fourcc, fps, (112, 112))... | Finally, I found the solution. I can solve my problem in the ubuntu:20.04 docker. The important thing you should notice is that you should install OpenCV via apt-get install python3-opencv not using pip. | 13 | 3 |
70,221,003 | 2021-12-3 | https://stackoverflow.com/questions/70221003/patch-request-not-patching-403-returned-django-rest-framework | I'm trying to test an API endpoint with a patch request to ensure it works. I'm using APILiveServerTestCase but can't seem to get the permissions required to patch the item. I created one user (adminuser) who is a superadmin with access to everything and all permissions. My test case looks like this: class FutureVehicl... | Recommended Solution The test you have written is also testing the Django framework logic (ie: Django admin login). I recommend testing your own functionality, which occurs after login to the Django admin. Django's testing framework offers a helper for logging into the admin, client.login. This allows you to focus on t... | 10 | 5 |
70,267,576 | 2021-12-7 | https://stackoverflow.com/questions/70267576/merge-two-files-and-add-computation-and-sorting-the-updated-data-in-python | I need help to make the snippet below. I need to merge two files and performs computation on matched lines I have oldFile.txt which contains old data and newFile.txt with an updated sets of data. I need to to update the oldFile.txt based on the data in the newFile.txt and compute the changes in percentage. Any idea wil... | Here is a sample code to output what you need. I use the formula below to calculate pct change. percentage_change = 100*(new-old)/old If old is 0 it is changed to 1 to avoid division by zero error. import pandas as pd def read_file(fn): """ Read file fn and convert data into a dict of dict. data = {pname1: {grp: grp1, ... | 12 | 9 |
70,246,591 | 2021-12-6 | https://stackoverflow.com/questions/70246591/delete-directory-and-all-symlinks-recursively | I tried to use shutil to delete a directory and all contained files, as follows: import shutil from os.path import exists if exists(path_dir): shutil.rmtree(path_dir) Unfortunately, my solution does not work, throwing the following error: FileNotFoundError: [Errno 2] No such file or directory: '._image1.jpg' A quick ... | That is strange, I have no issues with shutil.rmtree() with or without symlink under the folder to be deleted, both in windows 10 and Ubuntu 20.04.2 LTS. Anyhow try the following code. I tried it in windows 10 and Ubuntu. from pathlib import Path import shutil def delete_dir_recursion(p): """ Delete folder, sub-folders... | 11 | 6 |
70,264,157 | 2021-12-7 | https://stackoverflow.com/questions/70264157/logistic-regression-and-gridsearchcv-using-python-sklearn | I am trying code from this page. I ran up to the part LR (tf-idf) and got the similar results After that I decided to try GridSearchCV. My questions below: 1) #lets try gridsearchcv #https://www.kaggle.com/enespolat/grid-search-with-logistic-regression from sklearn.model_selection import GridSearchCV grid={"C":np.logsp... | You end up with the error with precision because some of your penalization is too strong for this model, if you check the results, you get 0 for f1 score when C = 0.001 and C = 0.01 res = pd.DataFrame(logreg_cv.cv_results_) res.iloc[:,res.columns.str.contains("split[0-9]_test_score|params",regex=True)] params split0_te... | 8 | 5 |
70,199,088 | 2021-12-2 | https://stackoverflow.com/questions/70199088/selenium-with-proxy-not-working-wrong-options | I have the following working test-solutions which outputs the IP-address and information - Now I want to use this with my ScraperAPI-Account with other Proxies. But when I uncomment this 2 lines - # PROXY = f'http://scraperapi:{SCRAPER_API}@proxy-server.scraperapi.com:8001' # options.add_argument('--proxy-server=%s' % ... | There are a couple of things you need to look back: First of all, there seems be a typo. There is a space character between get and () which may cause: IndexError: list index out of range Not sure what the following line does as I'm able to execute without the line. You may like to comment it. from dotenv import loa... | 6 | 2 |
70,236,617 | 2021-12-5 | https://stackoverflow.com/questions/70236617/inheriting-generic-classes-with-restricted-typevar | Consider a simple pair of generic classes: T = TypeVar("T", str, int) class Base(Generic[T]): def __init__(self, v: T): self.v: T = v @property def value(self) -> T: return self.v class Child(Base[T]): def __init__(self, v: T): super().__init__(v) x = Child(123) reveal_type(x.value) While using T = TypeVar("T") works ... | Bounding T to an Union[int,str] should do the job: T = TypeVar("T", bound=Union[str, int]) class Base(Generic[T]): def __init__(self, v: T): self.v: T = v @property def value(self) -> T: return self.v class Child(Base[T]): def __init__(self, v: T): super().__init__(v) x = Child(123) reveal_type(x.value) y = Child('a') ... | 6 | 2 |
70,261,541 | 2021-12-7 | https://stackoverflow.com/questions/70261541/use-on-conflict-do-update-with-sqlalchemy-orm | I am currently using SQLAlchemy ORM to deal with my db operations. Now I have a SQL command which requires ON CONFLICT (id) DO UPDATE. The method on_conflict_do_update() seems to be the correct one to use. But the post here says the code have to switch to SQLAlchemy core and the high-level ORM functionalities are miss... | As noted in the documentation, the constraint= argument is The name of a unique or exclusion constraint on the table, or the constraint object itself if it has a .name attribute. so we need to pass the name of the PK constraint to .on_conflict_do_update(). We can get the PK constraint name via the inspection interfac... | 7 | 6 |
70,265,961 | 2021-12-7 | https://stackoverflow.com/questions/70265961/install-specific-version-of-bazel-with-bazelisk | I am trying to use Bazel to rebuild Tensorflow with compiler flags, but have been getting errors. In the documentation explaining how to build Tensorflow from the source, they say that Bazelisk will download the correct version for Tensorflow... but when I was getting the errors, I decided to check the Bazel version an... | Bazelisk will look in the WORKSPACE root for a file named .bazelversion (see here). This file is supposed to contain the Bazel version number you want to use. There are also other options to tell Bazelisk which version to use: How does Bazelisk know which Bazel version to run? To use for instance Bazel 0.26.1 you can B... | 7 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.