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,031,990
2021-9-2
https://stackoverflow.com/questions/69031990/how-can-i-use-both-required-and-optional-path-parameters-in-a-fastapi-endpoint
I've read through the documentation and this doesn't seem to be working for me. I followed this doc. But I'm not sure if it's related to what I'm trying to do, I think this doc is for passing queries like this - site.com/endpoint?keyword=test Here's my goal: api.site.com/test/(optional_field) So, if someone goes to the...
As far as I know, it won't work the way you've set it up. Though you can try something like this: @app.get("/company/{company_ticker}/model/", dependencies=[Depends(api_counter)]) @app.get("/company/{company_ticker}/model/{financialColumn}", dependencies=[Depends(api_counter)]) async def myendpoint( company_ticker: str...
6
7
69,024,599
2021-9-2
https://stackoverflow.com/questions/69024599/scraping-data-from-zillow-com-using-beautifulsoup
Following this tutorial, I am trying to extract basic property information from zillow.com. More specifically, I want to extract the information pertinent to property cards displayed on the website. The following code is able to extract information of only 3 properties, even though several property cards exist on the ...
The results are stored in <script> variable inside the page. To parse them, you can use next example: import json import requests from bs4 import BeautifulSoup url = "https://www.zillow.com/homes/for_sale/house,multifamily,townhouse_type/?searchQueryState={%22pagination%22%3A{}%2C%22mapBounds%22%3A{%22west%22%3A-106.97...
4
8
69,028,920
2021-9-2
https://stackoverflow.com/questions/69028920/why-does-mypy-have-a-hard-time-with-assignment-to-nested-dicts
mypy version 0.910 Consider d = { 'a': 'a', 'b': { 'c': 1 } } d['b']['d'] = 'b' Feeding this to mypy results with error: Unsupported target for indexed assignment ("Collection[str]") Putting a side that mypy inferred the wrong type for d (it is clearly not a collection of strings), adding a very basic explicit type f...
d is not being inferred as a collection of strings. It is being inferred as a dict, but dicts take two type variables, one for the keys and one for the values. If we use reveal_type: d = { 'a': 'a', 'b': { 'c': 1 } } reveal_type(d) d['b']['d'] = 'b' I get: (py39) jarrivillaga-mbp16-2019:~ jarrivillaga$ mypy --version ...
12
7
69,027,829
2021-9-2
https://stackoverflow.com/questions/69027829/how-to-add-row-titles-to-the-following-the-matplotlib-code
I am trying to create a plot containing 8 subplots (4 rows and 2 columns). To do so, I have made this code that reads the x and y data and plots it in the following fashion: fig, axs = plt.subplots(4, 2, figsize=(15,25)) y_labels = ['k0', 'k1'] for x in range(4): for y in range(2): axs[x, y].scatter([i[x] for i in X_va...
The solution in the answer that you linked is the correct one, however it is specific for the 3x3 case as shown there. The following code should be a more general solution for different numbers of subplots. This should work provided your data and y_label arrays/lists are all the correct size. Note that this requires ma...
5
4
69,021,077
2021-9-1
https://stackoverflow.com/questions/69021077/start-an-async-background-daemon-in-a-python-fastapi-app
I'm building an async backend for an analytics system using FastAPI. The thing is it has to: a) listen for API calls and be available at all times; b) periodically perform a data-gathering task (parsing data and saving it into the DB). I wrote this function to act as a daemon: async def start_metering_daemon(self) -> ...
try @app.on_event("startup") async def startup_event() -> None: """tasks to do at server startup""" asyncio.create_task(Gatherer().start_metering_daemon())
14
7
69,021,815
2021-9-2
https://stackoverflow.com/questions/69021815/how-to-read-json-file-with-comments
The comment are causing errors. I have a contents.json file which looks like: { "Fridge": [ ["apples"], ["chips","cake","10"] // This comment here is causing error ], "car": [ ["engine","tires","fuel"], ] } My python script is like this import json jsonfile = open('contents.json','r') jsondata = jsonfile.read() objec ...
Read the file per line and remove the comment part. import json jsondata = "" with open('contents.json', 'r') as jsonfile: for line in jsonfile: jsondata += line.split("//")[0] objec = json.loads(jsondata) list_o = objec['Fridge'] for i in (list_o): print(i) ['apples'] ['chips', 'cake', '10'] Update You can also easi...
5
1
69,022,873
2021-9-2
https://stackoverflow.com/questions/69022873/is-there-any-straightforward-option-of-unpacking-a-dictionary
If I do something like this some_obj = {"a": 1, "b": 2, "c": 3} first, *rest = some_obj I'll get a list, but I want it in 2 dictionaries: first = {"a": 1} and rest = {"b": 2, "c": 3}. As I understand, I can make a function, but I wonder if I can make it in one line, like in javascript with spread operator.
I don't know if there is a reliable way to achieve this in one line, But here is one method. First unpack the keys and values(.items()). Using some_obj only iterate through the keys. >>> some_obj = {"a":1, "b":2, "c": 3} >>> first, *rest = some_obj.items() But this will return a tuple, >>> first ('a', 1) >>> rest [('...
5
8
69,016,584
2021-9-1
https://stackoverflow.com/questions/69016584/python-is-there-a-shorthand-for-eg-printftypevar-typevar
Is there a shorthand in Python for (e.g.) print(f'type(var) = {type(var)}'), without having to state the object in the text and the {.}? The short answer may be "no", but I had to ask! E.g. in SAS one may use &= to output a macro variable and its value to the log... %let macrovar = foobar; %put &=macrovar; which retur...
Indeed there is. As of python 3.8, you can simply type f'{type(var)=}', and you will get the output you desire: >>> x = {} >>> f'{x=}' 'x={}' >>> f'{type(x)=}' "type(x)=<class 'dict'>" Further reading: The "What's New In Python 3.8" page The documentation for f-strings The discussion on BPO that led to this feature b...
5
7
69,015,915
2021-9-1
https://stackoverflow.com/questions/69015915/spliting-a-list-into-n-uneven-buckets-with-all-combinations
I have a list like: lst = [1,2,3,4,5,6,7,8,9,10] and I want to get the combination of all splits for a given n bucket without changing the order of the list. Output exp for n=3: [ [1],[2],[3,4,5,6,7,8,9,10], [1],[2,3],[4,5,6,7,8,9,10], [1],[2,3,4],[5,6,7,8,9,10], . . . [1,2,3,4,5,6,7,8],[9],[10], ] Python is the lang...
Try: from itertools import product def generate(n, l): for c in product(range(1, l), repeat=n - 1): s = sum(c) if s > l - 1: continue yield *c, l - s lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n = 3 for groups in generate(n, len(lst)): l, out = lst, [] for g in groups: out.append(l[:g]) l = l[g:] print(out) Prints: [[1], [...
6
4
69,015,534
2021-9-1
https://stackoverflow.com/questions/69015534/seaborn-heatmap-annotation-valueerror-unknown-format-code-g-for-object-of-typ
I want to draw a seaborn.heatmap and annotate only some rows/columns. Example where all cells have annotation: import seaborn as sns import matplotlib.pyplot as plt import numpy as np n1 = 5 n2 = 10 M = np.random.random((n1, n2)) fig, ax = plt.subplots() sns.heatmap(ax = ax, data = M, annot = True) plt.show() Followi...
It is a formatting issue. Here the fmt = '' is required if you are using non-numeric labels (defaults to: fmt='.2g') which consider only for numeric values and throw an error for labels with text format. import seaborn as sns import matplotlib.pyplot as plt import numpy as np n1 = 5 n2 = 10 M = np.random.random((n1, n2...
12
15
69,009,440
2021-9-1
https://stackoverflow.com/questions/69009440/bash-how-to-capture-the-version-from-rpm
this is the way when I try to get the Kafka version rpm -qa | grep "^kafka_" kafka_2_6_5_0_292-1.0.0.2.6.5.0-292.noarch Kafka version is 1.0 , so I did the following in order to cut the Kafka version rpm -qa | grep "^kafka_" | sed s'/-/ /g' | awk '{print $2}' | cut -c 1-3 1.0 <----- results above cli seems to be not...
Refactoring your code rpm -qa | grep "^kafka_" | sed s'/-/ /g' | awk '{print $2}' | cut -c 1-3 1st step: use AWK's FS (Field Seperator) instead preprocessing in sed rpm -qa | grep "^kafka_" | awk 'BEGIN{FS="-"}{print $2}' | cut -c 1-3 2nd step: register {print $2} action to lines matching description rather than filt...
6
4
69,006,887
2021-9-1
https://stackoverflow.com/questions/69006887/return-multiple-values-from-a-pandas-rolling-apply-function
I have a function that needs to return multiple values: def max_dd(ser): ... compute i,j,dd return i,j,dd if I have code like this that calls this function passing in a series: date1, date2, dd = df.rolling(window).apply(max_dd) however, I get an error: pandas.core.base.DataError: No numeric types to aggregate If I...
Rolling apply can only produce single numeric values. There is no support for multiple returns or even nonnumeric returns (like something as simple as a string) from rolling apply. Any answer to this question will be a work around. That said, a viable workaround is to take advantage of the fact that rolling objects are...
5
14
68,919,220
2021-8-25
https://stackoverflow.com/questions/68919220/using-getattr-to-access-built-in-functions
I would like to use getattr() to access Python's built-in functions. Is that possible? For example: getattr(???, 'abs') I know I can just simply do: >>> abs <built-in function abs> But I want to use getattr, because the keyword names are strings.
The builtins module: You could try importing builtins module: >>> import builtins >>> getattr(builtins, 'abs') <built-in function abs> >>> As mentioned in the documentation: This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in functio...
4
20
68,916,383
2021-8-25
https://stackoverflow.com/questions/68916383/can-i-disable-type-errors-from-third-party-packages-in-pylance
Some of the packages I use don't type hint their code, so when I use them, Pylance keeps telling me that the functions I use have partially unknown types, which is a problem I can't fix. Is there a way to disable such errors?
If you're absolutely certain of the type you're getting from the external library and you're sure it's not documented through typeshed either, you can always cast it to signal to the type checker it's to be treated as that type. from typing import cast from elsewhere import Ham spam = some_untyped_return() ham = cast(H...
20
2
68,961,796
2021-8-28
https://stackoverflow.com/questions/68961796/how-do-i-melt-a-pandas-dataframe
On the pandas tag, I often see users asking questions about melting dataframes in pandas. I am going to attempt a canonical Q&A (self-answer) with this topic. I am is going to clarify: What is melt? How do I use melt? When do I use melt? I see some hotter questions about melt, like: Convert columns into rows with...
Note for pandas versions < 0.20.0: I will be using df.melt(...) for my examples, but you will need to use pd.melt(df, ...) instead. Documentation references: Most of the solutions here would be used with melt, so to know the method melt, see the documentation explanation. Unpivot a DataFrame from wide to long format, ...
49
37
68,957,800
2021-8-27
https://stackoverflow.com/questions/68957800/how-to-fix-pylance-syntax-highlighting-showing-wrong-color-for-self-and-cls-pyth
I have encountered this issue when I use Pylance and syntax highlighting is enabled for python in the VSCode with default or the visual studio theme. self and cls parameter are LightSkyBlue color like other parameters It should be like this:
Added the color code inside the settings.json file for the dark themes I use. // correct color self and cls python "editor.semanticTokenColorCustomizations": { "[Default Dark+]": { "rules": { "selfParameter": "#569CD6", "clsParameter": "#569CD6" }, }, "[Visual Studio Dark]": { "rules": { "selfParameter": "#569CD6", "cl...
7
11
68,924,471
2021-8-25
https://stackoverflow.com/questions/68924471/plotly-express-doesnt-load-and-refuse-to-connect
I have this simple program that should display a pie chart, but whenever I run the program, it opens a page on Chrome and just keeps loading without any display, and sometimes it refuses to connect. How do I solve this? P.S.: I would like to use it offline, and I'm running it using cmd on windows10 import pandas as pd ...
Disclaimer: I extracted this answer from the OPs question. Answers should not be contained in the question itself. Answer provided by g_odim_3: So instead of figure0.show(), I used figure0.write_html('first_figure.html', auto_open=True) and it worked: import pandas as pd import numpy as np from datetime import datetim...
5
7
68,999,178
2021-8-31
https://stackoverflow.com/questions/68999178/pipenv-error-no-python-at-c-python39-python-exe
I installed and added Python3.9 and Pip to the PATH through the installer. python --version # Python 3.9.7 pip --version # pip 21.2.4 from C:\Users\{MyUserName}\AppData\Local\Programs\Python\Python39\lib\site-packages\pip (python 3.9) I installed pipenv with pip install pipenv and pipenv --version outputs pipenv, vers...
For anyone running into this error, run the following to delete the virtual environment (built with the previous/future version of Python): cd $project_folder pipenv --rm Then rerun this to build your pipenv virtual environment with your new version of Python: pipenv install
9
24
68,916,893
2021-8-25
https://stackoverflow.com/questions/68916893/typeerror-numpy-dtypemeta-object-is-not-subscriptable
I'm trying to type hint a numpy ndarray like this: RGB = numpy.dtype[numpy.uint8] ThreeD = tuple[int, int, int] def load_images(paths: list[str]) -> tuple[list[numpy.ndarray[ThreeD, RGB]], list[str]]: ... but at the first line when I run this, I got the following error: RGB = numpy.dtype[numpy.uint8] TypeError: 'numpy...
It turns out that strongly type a numpy array is not straightforward at all. I spent a couple of hours to figure out how to do it properly. A simple method that do not add yet another dependency to your project is to use a trick described here. Just wrap numpy types with with ': import numpy import numpy.typing as npt ...
11
5
68,929,799
2021-8-25
https://stackoverflow.com/questions/68929799/pysimplegui-right-justify-a-button-in-a-frame
I am building a simple GUI with pysimplegui and want to right-justify a button inside a frame. I have found details on how to do this with text but not with buttons. For example, I would like the button below to snap to the right side of the frame with the groove around it. I want this: To look more like this: But wi...
Your question just missed a release of PySimpleGUI that makes this operation trivial. One problem with StackOverflow is - "nothing dies"... including old solutions. It's a genuine problem that I've yet to find a solid solution for. This technique was released in Sept 2021 in version 4.48.0 and uses the, then new, Push ...
5
2
68,945,080
2021-8-26
https://stackoverflow.com/questions/68945080/pytube-exceptions-regexmatcherror-get-throttling-function-name-could-not-find
I used to download songs the following way: from pytube import YouTube video = YouTube('https://www.youtube.com/watch?v=AWXvSBHB210') video.streams.get_by_itag(251).download() Since today there is this error: Traceback (most recent call last): File "C:\Users\Me\AppData\Local\Programs\Python\Python39\lib\site-packages\...
I had same issue when i was using pytube 11.0.0 so found out that there is a regular expression filter mismatch in pytube library in cipher.py class function_patterns = [ r'a\.C&&\(b=a\.get\("n"\)\)&&\(b=([^(]+)\(b\),a\.set\("n",b\)\)}};', ] Now there is a update of pytube code yesterday to 11.0.1 function_patterns = ...
28
16
68,965,072
2021-8-28
https://stackoverflow.com/questions/68965072/pytorch-model-take-too-much-to-load-the-first-time-in-a-new-machine
I have a manual scaling set-up on EC2 where I'm creating instances based on an AMI which already runs my code at boot (using Systemd). I'm facing a fundamental problem: on the main instance (the one I use to create the AMI, the Python code takes 8 seconds to be ready after the image is booted, this includes importing l...
This was caused because of the high latencies required while restoring AWS EBS snapshots. At first when you restore a snapshot, the latency is extremely high, explaining why the model takes so much to load in my example when the instance is freshly created. Check the initialization section of this article: https://clou...
6
3
68,930,093
2021-8-25
https://stackoverflow.com/questions/68930093/modulenotfounderror-no-module-named-ffmpeg-on-spyder-although-ffmpeg-is-insta
ffmpeg is installed on Anaconda Navigator (in base(root) environment), but when I run import ffmpeg, I got this error message: ModuleNotFoundError: No module named 'ffmpeg' Why is this module not found and how can I fix this?
You need to install the ffmpeg-python module to the environment: pip install ffmpeg-python or conda install -c conda-forge ffmpeg-python from there import ffmpeg statements when using the environment should work.
10
18
68,967,514
2021-8-28
https://stackoverflow.com/questions/68967514/importing-the-numpy-c-extensions-failed-amplify
Cross posted on GitHub I'm working with AWS Amplify and pipenv for my python 3.9 lambda. I'm attempting to use pandas to create a dataframe, do some processing and write it back to CSV for sagemaker inference. Reproducing code example: import pandas as pd (Code immediately fails after this) Error message: Here's the f...
I had ran into a similar issue. After much research it looks like the Lambda Layer AWSLambda-Python38-SciPy1x provided by Amazon is your best bet. More Info is here. You can manually add the Layer via the Console like so: Picture for you Or you can add the layer via the Amplify CLI. I ran the following commands on an...
4
3
68,924,790
2021-8-25
https://stackoverflow.com/questions/68924790/parenthesized-context-managers-work-in-python-3-9-but-not-3-8
So I have this simple example of a with statement. It works in Python 3.8 and 3.9: class Foo: def __enter__(self, *args): print("enter") def __exit__(self, *args): print("exit") with Foo() as f, Foo() as b: print("Foo") Output (as expected): enter enter Foo exit exit But if I add parentheses like this it only works i...
Parenthesized context managers are mentioned as a new feature in What’s New In Python 3.10. The changelog states: This new syntax uses the non LL(1) capacities of the new parser. Check PEP 617 for more details. But PEP 617 was already accepted in Python 3.9, as described in its changelog: Python 3.9 uses a new parse...
6
8
68,973,827
2021-8-29
https://stackoverflow.com/questions/68973827/how-to-send-a-inlinekeyboardbutton-in-telegram-bot-periodically
I'm trying to send an InlineKeyboardHandler every x second. for that purpose I used updater.job_queue.run_repeating but it acts weird. The keyboard doesn't work unless I have another interaction with the bot first. I've written a simple piece of code that you can test. from telegram import Update, InlineKeyboardButton,...
The problem with your code as a_guest mentioned in the comments, is that InlineKeyboardHandler will start to work only after calling request_button command. Here's a working version where InlineKeyboardHandler is registered independently: from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from tele...
7
2
68,971,787
2021-8-29
https://stackoverflow.com/questions/68971787/unit-test-for-django-update-form
I do not understand how to manage updates on forms and related unit tests and I would really appreciate some advises =) I have a Company model, and related very simple CompanyForm: class Company(models.Model): """ Company informations - Detailed information for display purposes in the application but also used in docum...
In this case, you need to use refresh_from_db to "refresh" your object once the view and the form are done updating your object. This means that when you are currently asserting, you are using an "old snapshot" of self.company hence the failure on assertion, so you need to update it: # Options update response = self.c...
4
6
68,937,783
2021-8-26
https://stackoverflow.com/questions/68937783/why-do-i-get-mysql-server-has-gone-away-after-running-a-telegram-bot-for-some
I'm building a Django (ver. 3.0.5) app that uses mysqlclient (ver. 2.0.3) as the DB backend. Additionally, I've written a Django command that runs a bot written using the python-telegram-bot API, so the mission of this bot is to run indefinitely, as it has to answer to commands anytime. Problem is that approximately 24...
I ended up scheduling a DB query every X hours (in this case, 6h) in the bot. The python-telegram-bot has a class called JobQueue which has a method called run_repeating. This will run a task every n seconds. So I declared: def check_db(context): # Do the code for running "SELECT 1" in the DB return updater.job_queue.r...
7
0
68,939,894
2021-8-26
https://stackoverflow.com/questions/68939894/implement-a-python-websocket-listener-without-async-asyncio
I'm running a websocket listener in a separate thread. I'd like to connect to the websocket then do: while True: msg = sock.wait_for_message() f(msg) i.e. no async/asyncio Is this stupid? Is there a way to do this?
In absence of a better answer, I have found https://github.com/websocket-client/websocket-client which prove painless to use.
4
6
68,995,523
2021-8-31
https://stackoverflow.com/questions/68995523/how-to-get-the-first-sheet-of-an-excel-workbook-using-openpyxl
I'm able to get the desired sheet by using wb["sheet_name"] method but I want to get the first, or let's say the nth sheet, regardless of the name. wb = load_workbook(filename = xlsx_dir) # xlsx_dir is the workbook path ws = wb["Details"] # Details is the sheet name
You need to use the worksheets property of the workbook object ws = wb.worksheets[0]
10
32
68,938,628
2021-8-26
https://stackoverflow.com/questions/68938628/why-is-anytrue-for-if-cond-much-faster-than-anycond-for
Two similar ways to check whether a list contains an odd number: any(x % 2 for x in a) any(True for x in a if x % 2) Timing results with a = [0] * 10000000 (five attempts each, times in seconds): 0.60 0.60 0.60 0.61 0.63 any(x % 2 for x in a) 0.36 0.36 0.36 0.37 0.37 any(True for x in a if x % 2) Why is the second wa...
The first method sends everything to any() whilst the second only sends to any() when there's an odd number, so any() has fewer elements to go through.
98
92
68,932,099
2021-8-26
https://stackoverflow.com/questions/68932099/how-to-get-alembic-to-recognise-sqlmodel-database-model
Using SQLModel how to get alembic to recognise the below model? from sqlmodel import Field, SQLModel class Hero(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None One approach I've been looking at is to import the SQLalchemy model for Alembic but...
There should be info about that in Advanced user guide soon with better explanation than mine but here is how I made Alimbic migrations work. First of all run alembic init migrations in your console to generate migrations folder. Inside migrations folder should be empty versions subfolder,env.py file, script.py.mako fi...
23
45
68,990,830
2021-8-30
https://stackoverflow.com/questions/68990830/how-to-preserve-axis-aspect-ratio-with-tight-layout
I have a plot with both a colorbar and a legend. I want to place the legend outside of the plot to the right of the colorbar. To accomplish this, I use bbox_to_anchor argument, but this causes the legend to get cut off: import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm _, ax = plt.subplots...
You can manage the ratio between axis height and width with matplotlib.axes.Axes.set_aspect. Since you want them to be equal: ax.set_aspect(1) Then you can use matplotlib.pyplot.tight_layout to fit the legend within the figure. If you want to adjust margins too, you can use matplotlib.pyplot.subplots_adjust. Complete ...
6
2
69,005,034
2021-8-31
https://stackoverflow.com/questions/69005034/multiple-inheritance-metaclass-conflict-involving-enum
I need a double inheritance for a class that is an Enum but also support my own methods. Here's the context: import abc from enum import Enum class MyFirstClass(abc.ABC): @abc.abstractmethod def func(self): pass class MySecondClass(Enum, MyFirstClass): VALUE_1 = 0 VALUE_2 = 1 def func(self): return 42 The declaration ...
The solution to your immediate problem is: class MyFinalClass(MyFirstClass, Enum, metaclass=MyMetaClass): pass Note that Enum is the last regular class listed. For a fully functioning abstract Enum you'll want to use the ABCEnumMeta from this answer -- otherwise missing abstract methods will not be properly flagged.
10
6
69,005,509
2021-8-31
https://stackoverflow.com/questions/69005509/place-an-order-in-interactive-brokers-using-api-request
First, to begin with, I was successfully able to place an order using TWS API. However, for that, as I understood, I need to run the TWS desktop version in the background. But I need to run this on my remote server. So I used a 3rd party API called IBeam and created a gateway using it, in the remote server. Now it is w...
I found this article helpful in the process of placing an order. I.e, this is a sample request that you can use to place an order { "orders": [ { "acctId": "DU4299134", "conid": 8314, "secType": "8314:STK", "cOId": "testAlgoOrder", "orderType": "LMT", "price": 142, "side": "BUY", "tif": "DAY", "quantity": 1, "strategy"...
8
4
68,938,614
2021-8-26
https://stackoverflow.com/questions/68938614/file-pyinstaller-loader-pyimod03-importers-py-line-546-in-exec-module-modul
EDIT I'm trying to import algosec.models in a file inside the algobot package. I've tried to add --hidden-import algosec, I've also tried to add the path before importing, using sys.path.append(./../algosec) this is the error message I get when I try to run the program: Traceback (most recent call last): File "algobot_...
Apparently since I took the highest version of zeep and deprecated without giving a fixed version, it caused issues because of a newer release. I had to add them to setup.py of the algobot package which is the main package of the executable with a fixed version. In addition I had to add a .egg file of the algosec packa...
6
1
68,957,147
2021-8-27
https://stackoverflow.com/questions/68957147/aiofiles-take-longer-than-normal-file-operation
I have a question I'm new to the python async world and I write some code to test the power of asyncio, I create 10 files with random content, named file1.txt, file2.txt, ..., file10.txt here is my code: import asyncio import aiofiles import time async def reader(pack, address): async with aiofiles.open(address) as fil...
I post an issue #110 on aiofiles's GitHub and the author of aiofiles answer that: You're not doing anything wrong. What aiofiles does is delegate the file reading operations to a thread pool. This approach is going to be slower than just reading the file directly. The benefit is that while the file is being read in a ...
5
14
68,960,005
2021-8-27
https://stackoverflow.com/questions/68960005/saving-an-animated-matplotlib-graph-as-a-gif-file-results-in-a-different-looking
I created an animated plot using FuncAnimation from the Matplotlib Animation class, and I want to save it as a .gif file. When I run the script, the output looks normal, and looks like this (the animation works fine): However, when I try to save the animated plot as a .gif file using ImageMagick or PillowWriter, the p...
See if this works. I don't have Imagemagick so I used Pillow. To prevent the animation showing stacked frames (i.e., dot traces), the trick is to clear the axes to refresh each frame. Then set xlim and ylim for each frame, and plot the incremental lines using ax.plot(x1[0:i], y1[0:i]... To improve the image resolution,...
13
20
68,997,995
2021-8-31
https://stackoverflow.com/questions/68997995/can-i-read-parquet-from-https-octet-stream
Some backend endpoint returns a parquet file as an octet-stream. In Pandas I can do something like this: result = requests.get("https://..../file.parquet") df = pd.read_parquet(io.BytesIO(result.content)) Can I do it in Dask somehow? This code: dd.read_parquet("https://..../file.parquet") raises exception (obviously,...
This is not an answer, but I believe the following change in fsspec will fix your problem. If you would be willing to try and confirm, we can make this a patch. --- a/fsspec/implementations/http.py +++ b/fsspec/implementations/http.py @@ -472,7 +472,10 @@ class HTTPFileSystem(AsyncFileSystem): async def _isdir(self, pa...
5
1
68,999,248
2021-8-31
https://stackoverflow.com/questions/68999248/mock-external-api-post-call-in-view-from-test-view-python
I have an external API POST call that is being made from within my views.py as such: class MyView(APIView): def post(self, request): my_headers = { "Content-Type": "application/json" } response = requests.post("https://some-external-api.com", data=json.dumps(request.data), headers=my_headers) return Response(status.res...
No need to reinvent the wheel, just use the available mockers for the requests library such as requests_mock. import json import pytest import requests import requests_mock # python3 -m pip install requests-mock def post(): my_headers = {"Content-Type": "application/json"} my_data = {"some_key": "some_value"} response ...
4
5
68,933,195
2021-8-26
https://stackoverflow.com/questions/68933195/how-do-i-pass-multiple-arguments-to-a-pandas-udf-in-pyspark
I'm working with the following snippet: from cape_privacy.pandas.transformations import Tokenizer max_token_len = 5 @pandas_udf("string") def Tokenize(column: pd.Series)-> pd.Series: tokenizer = Tokenizer(max_token_len) return tokenizer(column) spark_df = spark_df.withColumn("name", Tokenize("name")) Since Pandas UDF ...
After trying a myriad of approaches, I found an effortless solution as illustrated below: I created a wrapper function (Tokenize_wrapper) to wrap the Pandas UDF (Tokenize_udf) with the wrapper function returning the Pandas UDF's function call. def Tokenize_wrapper(column, max_token_len=10): @pandas_udf("string") def To...
5
17
69,003,730
2021-8-31
https://stackoverflow.com/questions/69003730/understanding-whats-happening-in-the-kadane-algorithm-python
I'm having a difficult time understanding what's happening in these two examples I found of the Kadane Algorithm. I'm new to Python and I'm hoping understanding this complex algo will help me see/read programs better. Why would one example be better than the other, is it just List vs Range? Is there something else that...
Simply watch each step and you could figure out this problem: [Notes] this program seems to work based on the assumption of mixed integer numbers? only positive and negatives. # starting so_far = -2 # init. to nums[0] max_sum = 0 # in the for-loop: x = 1 # starting with nums[1:] so_far = max(1, -1) -> 1 (x is 1, -2 + 1...
6
1
68,997,345
2021-8-31
https://stackoverflow.com/questions/68997345/how-to-dict-or-data-check-keys-in-pydantic
class mail(BaseModel): mailid: int email: str class User(BaseModel): id: int name: str mails: List[mail] data1 = { 'id': 123, 'name': 'Jane Doe', 'mails':[ {'mailid':1,'email':'aeajhs@gmail.com'}, {'mailid':2,'email':'aeajhsds@gmail.com'} ] } userobj = User(**data1) # Accepted data2 = { 'id': 123, 'name': 'Jane Doe', '...
You may use pydantic.validator as @juanpa-arrivillaga said. There are few little tricks: Optional it may be empty when the end of your validation. pre=True whether or not this validator should be called before the standard validators (else after) from pydantic import BaseModel, validator from typing import List, Opti...
7
5
68,995,862
2021-8-31
https://stackoverflow.com/questions/68995862/how-to-activate-virtual-env-in-vs-code
I cant activate virtual env in vs code. I tried same code in the cmd console is work but not in the vs code terminal. "D:\python\djangoapp\djangovenv\Scripts\activate.bat" I write this code. I am using windows 10 pro
yeah Its beacuse of terminal vs code was using powershell ı changed with cmd
8
0
68,991,947
2021-8-31
https://stackoverflow.com/questions/68991947/reversing-lists-splices-python-optimization-usaco-february-2020-bronze-question
I am trying to solve a problem that involves reversing list splices, and I am having trouble with the time limit for a test case,, which is 4 seconds. The question: Farmer John's N cows (1≤N≤100) are standing in a line. The ith cow from the left has label i, for each 1≤i≤N. Farmer John has come up with a new morning ex...
Lets first talk about how we could solve this mathematically, and then work out a solution programmatically. Lets say the cow at each position is represented by the variable Pi.j, where i is the cow index, and j is the the swap iteration. These variables will each contain an integer corresponding to that cow's unique i...
8
8
68,996,444
2021-8-31
https://stackoverflow.com/questions/68996444/in-operator-functionality-in-python
I needed to remove the characters in string1 which are present in string2. Here string1 and string2 have only the lower case characters a-z with given condition that the length of string1 will be greater every time. I was using the in operator: def removeChars (string1, string2): for char in string2: if char in string1...
in does not necessarily use loops behind the scenes. For example: r = range(100000000000) print(333 in r) # prints True immediately without looping If you were to loop r it will take quite a long time, so clearly that doesn't happen. in basically calls (behind the scenes) the object's __contains__ method. For some ite...
5
7
68,995,170
2021-8-31
https://stackoverflow.com/questions/68995170/pydantic-get-a-fields-type-hint
I want to store metadata for my ML models in pydantic. Is there a proper way to access a fields type? I know you can do BaseModel.__fields__['my_field'].type_ but I assume there's a better way. I want to make it so that if a BaseModel fails to instantiate it is very clear what data is required to create this missing fi...
In the case you dont need to handle nested classes, this should work from pydantic import BaseModel, ValidationError import typing class PeaksPerDayType(float): data_required = 123.22 data_type = "foo" @classmethod def determine(cls, data): return cls(data) # use our custom float class Metadata(BaseModel): peaks_per_da...
6
6
68,986,802
2021-8-30
https://stackoverflow.com/questions/68986802/multiprocessing-process-are-modifying-non-shared-variables-they-should-not-hav
Processes are mutating things they should not be able to mutate. A Workerhas a single state variable (an mp.Value). This value is set to -1, and it (the Worker) changes it to 1 in a loop. However, it seems to be possible to reset that value back to -1 by spawning a second Worker, even though this shares nothing with th...
The issue is that you are creating Value instances that immediately go out of scope in the parent process, which makes them get garbage collected. Because of the way Python allocates memory for multiprocessing.Value objects, the second Value ends up using the exact same shared memory location as the first Value, which ...
5
5
68,981,780
2021-8-30
https://stackoverflow.com/questions/68981780/rounding-a-number-in-google-sheets-using-gspread-api
I am writing a pandas dataframe to google sheets using gspread: from gspread_formatting import * import gspread from df2gspread import df2gspread as d2g import pandas as pd d2g.upload(data, sheet.id, 'test_name', clean=True, credentials=creds, col_names=True, row_names=False) While the pandas dataframe is rounded to 2...
If you get the worksheet element you can use format to achieve what you want. sh = gc.open("sheet_name") worksheet = sh.get_worksheet(0) # your sheet number worksheet.format('A', {'numberFormat': {'type' : 'NUMBER', 'pattern': '0.0#'}})
4
5
68,981,869
2021-8-30
https://stackoverflow.com/questions/68981869/how-to-upload-a-single-file-to-fastapi-server-using-curl
I'm trying to set up a FastAPI server that can receive a single file upload from the command line using curl. I'm following the FastAPI Tutorial here: https://fastapi.tiangolo.com/tutorial/request-files/?h=upload+file from typing import List from fastapi import FastAPI, File, UploadFile from fastapi.responses import HT...
The solution was to tell curl to follow a redirect. curl -L -F "file=@1.json" http://127.0.0.1:5094/uploadfile which then uploads the file.
8
4
68,979,379
2021-8-30
https://stackoverflow.com/questions/68979379/what-is-the-clientip-in-namecheap-api-request
According to namecheap api docs, a request should have this structure: response_request = f'https://api.namecheap.com/xml.response?ApiUser={ApiUser}&ApiKey={ApiKey}&UserName={ApiUser}&Command=namecheap.domains.check&ClientIp={ClientIp}&DomainList={DomainList}' But I keep receiving Error Number="1011150" Invalid reques...
The ClientIp is: The public IP address of the system making the request. Google search for "What is my IP" for several services that will provide your public IP address. The same public IP address must be whitelisted. This link provides details on Whitelisting IP.
5
5
68,956,951
2021-8-27
https://stackoverflow.com/questions/68956951/after-installing-django-with-poetry-it-says-no-module-named-django-in-active-v
I'm playing with poetry because I'm thinking about switching from pip. Following the basic usage examples, I'm doing the following: $ poetry new poetry-demo $ cd poetry-demo $ poetry add django $ django-admin #can't find it $ poetry shell #or poetry $(poetry env info --path)/bin/activate $ django-admin Traceback (most ...
Should have read this more closely: https://python-poetry.org/docs/basic-usage/#using-poetry-run poetry run django-admin
5
2
68,916,387
2021-8-25
https://stackoverflow.com/questions/68916387/stripe-checkout-session-is-missing-metadata
I have been trying to pass metadata through stripe.checkout.Session.create() like so: stripe.api_key = STRIPE_SECRET_KEY payments_blueprint = Blueprint('payments', __name__, url_prefix='/payments') @payments_blueprint.route('/checkout', methods=['POST']) def create_checkout_session(): try: checkout_session = stripe.che...
What exactly do you mean by "session response" here? Can you provide an example? For the webhook, which exact event type are you subscribed to? If, for example, you're listening to payment_intent.succeeded instead of checkout.session.completed, then it would be expected for the session metadata to not be present. You c...
13
2
68,960,891
2021-8-28
https://stackoverflow.com/questions/68960891/how-to-run-lambda-application-as-local-api
I've looked all over for some supported library that does this but can't find anything. I just want to run my lambda as a local api (ie localhost:80000/api/get/1) so I can run both my frontend and backend all on my machine for rapid development. I've hacked together a fastapi "gateway" that I run locally and use that t...
You can use AWS SAM for this. Local Testing and Debugging Use SAM CLI to step-through and debug your code. It provides a Lambda-like execution environment locally and helps you catch issues upfront. You might need to install Docker first as it would be the execution environment used to run the APIs. Setup the sam pro...
6
7
68,960,171
2021-8-27
https://stackoverflow.com/questions/68960171/python-error-importerror-attempted-relative-import-with-no-known-parent-packa
So, my files/folders structure is the following: project/ ├─ utils/ │ ├─ module.py ├─ server/ │ ├─ main.py Inside project/server/main.py I'm trying to import project/utils/module.py using this syntax: from ..utils.module import my_function. I'm using VSCode, and it even autocomplete for me as I type the module path. B...
Here is a reference that explains this problem well. Basically, the problem is that __package__ is not set when running standalone scripts. File structure . └── project ├── server │ └── main.py └── utils └── module.py project/server/main.py if __name__ == '__main__': print(__package__) Output $ python3 project/server...
27
44
68,951,594
2021-8-27
https://stackoverflow.com/questions/68951594/python-lru-cache-how-can-currsize-misses-maxsize
I have a class with a method that is annotated with the lru_cache annotation: CACHE_SIZE=16384 class MyClass: [...] @lru_cache(maxsize=CACHE_SIZE) def _my_method(self, texts: Tuple[str]): <some heavy text processing> def cache_info(self): return self._my_method.cache_info() After running for a while, I look at the cac...
If your program is either multi-threaded, or recursive - basically, any sort of condition where _my_method() might be called again while another call is partially completed - then it's possible to see the behavior you're experiencing. lru_cache() is thread-aware and uses the following set of steps for size-limited cach...
6
4
68,957,686
2021-8-27
https://stackoverflow.com/questions/68957686/pillow-how-to-binarize-an-image-with-threshold
I would like to binarize a png image. I would like to use Pillow if possible. I've seen two methods used: image_file = Image.open("convert_image.png") # open colour image image_file = image_file.convert('1') # convert image to black and white This method appears to handle a region filled with a light colour by ditheri...
I think you need to convert to grayscale, apply the threshold, then convert to monochrome. image_file = Image.open("convert_iamge.png") # Grayscale image_file = image_file.convert('L') # Threshold image_file = image_file.point( lambda p: 255 if p > threshold else 0 ) # To mono image_file = image_file.convert('1') The ...
8
20
68,917,844
2021-8-25
https://stackoverflow.com/questions/68917844/why-do-i-get-a-futurewarning-with-pandas-concat
Does anyone meet this similar FutureWarning? I got this when I was using Tiingo+pandas_datareader? The warning is like: python3.8/site-packages/pandas_datareader/tiingo.py:234: FutureWarning: In a future version of pandas all arguments of concat except for the argument 'objs' will be keyword-only return pd.concat(dfs, ...
Most function parameters in python are "positional or keyword" arguments. I.e. if I have this function: def do_something(x, y): pass Then I can either call it like this, using positional arguments: do_something(1, 2) Or like this, using keyword arguments: do_something(x=1, y=2) Or like this, using a mixture of the t...
6
17
68,947,934
2021-8-27
https://stackoverflow.com/questions/68947934/read-a-text-file-line-by-line-and-check-for-a-substring-on-2-of-the-lines
I want to read a text file and check for strings with open(my_file,'r') as f: for line in f: if 'text1' in line: f.next() if 'text2' in line: # do some processing I want to first find the text 'text1' at the beginning of the line then if found I want to check the next line for 'text2' if found then I will do some othe...
The variable line does not magically get updated when you call f.next() (or next(f) in Python 3). You would instead have to assign the line returned by next to a variable and test against it: with open(my_file,'r') as f: for line in f: if 'text1' in line: try: next_line = next(f) except StopIteration: break # in case w...
5
3
68,947,752
2021-8-27
https://stackoverflow.com/questions/68947752/is-it-possible-to-override-just-one-column-type-when-using-pyspark-to-read-in-a
I'm trying to use PySpark to read in a CSV file with many columns. The inferschema option is great at inferring majority of the columns' data types. If I want to override just one of the columns types that were inferred incorrectly, what is the best way to do this? I have this code working, but it makes PySpark import ...
Easier way would be using .withColumn and casting column_one_of_many as string. Example from pyspark.sql.types import * spark.read.format('com.databricks.spark.csv') \ .option('delimited',',') \ .option('header','true') \ .option('inferschema', 'true') \ .load('dbfs:/FileStore/some.csv')\ .withColumn("column_one_of_ma...
5
3
68,939,963
2021-8-26
https://stackoverflow.com/questions/68939963/efficiently-insert-multiple-elements-in-a-list-or-another-data-structure-keepi
I have a list of items that should be inserted in a list-like data structure one after the other, and I have the indexes at which each item should be inserted. For example: items = ['itemX', 'itemY', 'itemZ'] indexes = [0, 0, 1] The expected result is to have a list like this: result = ['itemY', 'itemZ', 'itemX']. I'm...
Here's python code for a treap with a size decoration that allows insertion at specific indexes, and reordering of whole contiguous sections. It was adapted from C++ code, Kimiyuki Onaka's solution to the Hackerrank problem, "Give Me the Order." (I cannot guarantee that this adaptation is bug free -- a copy of the orig...
7
1
68,941,232
2021-8-26
https://stackoverflow.com/questions/68941232/pandas-how-to-explode-data-frame-with-json-arrays
How to explode pandas data frame? Input df: Required output df: +----------------+------+-----+------+ |level_2 | date | val | num | +----------------+------+-----+------+ | name_1a | 2020 | 1 | null | | name_1b | 2019 | 2 | null | | name_1b | 2020 | 3 | null | | name_10000_xyz | 2018 | 4 | str | | name_10000_xyz | 20...
Explode the dataframe on value column, then pop the value column and create a new dataframe from it then join the new frame with the exploded frame. s = df.explode('value', ignore_index=True) s.join(pd.DataFrame([*s.pop('value')], index=s.index)) level_2 date val num 0 name_1a 2020 1 NaN 1 name_1b 2019 2 NaN 2 name_...
4
7
68,929,785
2021-8-25
https://stackoverflow.com/questions/68929785/how-to-apply-mask-to-image-tensors-in-pytorch
Applying mask with NumPy or OpenCV is a relatively straightforward process. However, if I need to use masked image in loss calculations of my optimization algorithm, I need to employ exclusively PyTorch, as doing otherwise interferes with gradient computations. Assuming that I have an image tensor [1, 512, 512, 3] (bat...
First of all, the definition of the function selective_mask is far for what You may call 'straightforward'. The key point in using numpy (and torch, which is designed to be mostly compatible) is to take advantage of the vectorization of operations and to avoid using loops, which are not parallelizable. If You rewrite t...
6
5
68,931,854
2021-8-26
https://stackoverflow.com/questions/68931854/pandas-infer-freq-returns-none
I have a pandas frame where the index is a DateTimeIndex and I am trying to infer its frequency and it is coming up as None. df.index DatetimeIndex(['2020-08-24 00:00:00', '2020-08-24 00:01:00', '2020-08-24 00:02:00', '2020-08-24 00:03:00', '2020-08-24 00:04:00', '2020-08-24 00:05:00', '2020-08-24 00:06:00', '2020-08-2...
freq is already None in this case, so you should try: >>> pd.to_timedelta(np.diff(df.index).min()) Timedelta('0 days 00:01:00') >>> Or just: >>> np.diff(df.index).min() numpy.timedelta64(60000000000,'ns')
5
4
68,926,935
2021-8-25
https://stackoverflow.com/questions/68926935/importerror-cannot-import-name-dtypearg-from-pandas
I'm using Pandas 1.3.2 in a Conda environment. When importing pandas on a Jupyter Notebook: import pandas as pd I get the error: ImportError: cannot import name 'DtypeArg' from 'pandas._typing' (C:\Users\tone_\anaconda3\envs\spyder\lib\site-packages\pandas\_typing.py) I've seen similar questions, but so far no soluti...
According to the answer provided in this post it is a bug in pandas==1.3.1. A possible solution is to downgrade it to some earlier version, e.g pip install pandas==1.3.0
5
1
68,925,966
2021-8-25
https://stackoverflow.com/questions/68925966/how-to-plot-each-pandas-row-as-a-line-plot
I have a pandas dataframe where the column names are frequencies in 1 Hz steps, each row is a participant id, and the values are an amplitude^2 value for the participant in each respective frequency. I am trying to plot a time-series of the data where the x axis are the frequencies, and the y axis is the amplitude^2 va...
I think, the easiest solution would be to transpose your DataFrame and then use pandas' plotting method. This is somewhat based on this answer. The code would look like this: import pandas as pd import matplotlib.pyplot as plt data = [['1', 9.45e-09, 9.85e-09, 8.33e-09, 6.06e-09, 4.80e-09, 4.08e-09], ['2', 1.30e-08, 1....
6
1
68,925,951
2021-8-25
https://stackoverflow.com/questions/68925951/scikit-learn-attributeerror-in-custom-transformer
I'm trying to create a transformer that changes types of columns from "object" to "category", so I created custom class for that: from sklearn.base import BaseEstimator, TransformerMixin class ChangeToCategory(BaseEstimator, TransformerMixin): def __init__(self, to_categories = None): self.to_categories_ = to_categorie...
So, I found there I was wrong. From sklearn documentation you must initialize all estimator parameters as attributes of the class. In addition, every keyword argument accepted by init should correspond to an attribute on the instance. Scikit-learn relies on this to find the relevant attributes to set on an estimator w...
7
8
68,926,132
2021-8-25
https://stackoverflow.com/questions/68926132/creation-of-a-class-wrapper-in-python
I would like to do the following: given an instance of a Base class create an object of a Wrapper class that has all the methods and attributes of the Base class + some additional functionality. class Base: def __init__(self, *args, **kwargs): self.base_param_1 = ... # some stuff def base_method_1(self, *args, **kwargs...
You can override __getattr__. That way, Wrapper specific attributes are looked up first, then the wrapped object's attributes are tried. class Wrapper: def __init__(self, base_obj, *args, **kwargs): self.base_obj = base_obj # some stuff def wrapper_method(self): return "new stuff" def __getattr__(self, name): return ge...
4
7
68,926,007
2021-8-25
https://stackoverflow.com/questions/68926007/make-number-of-rows-based-on-column-values-pandas-python
I want to expand my data frame based on numeric values in two columns (index_start and index_end). My df looks like this: item index_start index_end A 1 3 B 4 7 I want this to expand to create rows for A from 1 to 3 and rows for B from 4 to 7 like so. item index_start index_end index A 1 3 1 A 1 3 2 A 1 3 3 B 4 7 4 B ...
You could use .explode() df['index'] = df.apply(lambda row: list(range(row['index_start'], row['index_end']+1)), axis=1) df.explode('index') item index_start index_end index 0 A 1 3 1 0 A 1 3 2 0 A 1 3 3 1 B 4 7 4 1 B 4 7 5 1 B 4 7 6 1 B 4 7 7
4
6
68,915,407
2021-8-25
https://stackoverflow.com/questions/68915407/celery-retry-with-updated-arguments
Considering a task takes a list as arguments and process each element in the list, which may succeed or fail. In this case, how to "retry" with the failed elements only? Example: @app.task(bind=True) def my_test(self, my_list:list): new_list = [] for ele in my_list: try: do_something_may_fail(ele) except: new_list.appe...
Solution 1 Use Task.retry with its args and kwargs input. retry(args=None, kwargs=None, exc=None, throw=True, eta=None, countdown=None, max_retries=None, **options) Retry the task, adding it to the back of the queue. Parameters args (Tuple) – Positional arguments to retry with. kwargs (Dict) – Keyword arguments to ret...
7
5
68,915,672
2021-8-25
https://stackoverflow.com/questions/68915672/specify-metaclass-for-dynamic-type
In Python, you can create types dynamically using the function my_type = type(name, bases, dict). How would you specify a metaclass for this type my_type? (Ideally other than defining a throwaway class object that simply binds the metaclass to instantiated subclasses)
For Dynamic Type Creation where you need to provide keywords in the class statement (including, but not limited to, the keyword "metaclass"), you would use types.new_class. The following class definition: class A(B, C, metaclass=AMeta): pass Can be created dynamically like: A = types.new_class( name="A", bases=(B, C),...
4
10
68,870,009
2021-8-21
https://stackoverflow.com/questions/68870009/equivalent-of-python-walrus-operator-in-c11
Recently I have been using the := operator in python quite a bit, in this way: if my_object := SomeClass.function_that_returns_object(): # do something with this object if it exists print(my_object.some_attribute) The question Is there any way to do this in c++11 without the use of stdlib? for example in an arduino sk...
Python's := assignment expression operator (aka, the "walrus" operator) returns the value of an assignment. C++'s = assignment operator (both copy assignment and move assignment, as well as other assignment operators) does essentially the same thing, but in a different way. The result of an assignment is a reference to...
5
9
68,848,991
2021-8-19
https://stackoverflow.com/questions/68848991/in-python-how-are-triple-quotes-considered-comments-by-the-ide
My CS teacher told me that """ triple quotations are used as comments, yet I learned it as strings with line-breaks and indentations. This got me thinking - does python completely triple quote lines outside of relevant statements? """is this completely ignored like a comment""" or, is the computer actually considering...
Triple quoted strings are used as comment by many developers but it is actually not a comment, it is similar to regular strings in python but it allows the string to be in multi-line. You will find no official reference for triple quoted strings to be a comment. In python, there is only one type of comment that starts ...
21
22
68,912,915
2021-8-24
https://stackoverflow.com/questions/68912915/vscode-python-automatically-implementing-abstract-methods
Is there any support to automatically implement all abstract methods of an abstract class in VSCode with Python Environment? class AbstractClass(ABC): @abstractclass def abstract_method(): pass class NonAbstractClass(AbstractClass): # shortcut in vscode to implement all abstract methods # it works if I start writing me...
Seems like it is now (2024-04-17) in pre-release. Checkout the release notes.
9
1
68,885,950
2021-8-22
https://stackoverflow.com/questions/68885950/how-to-pass-the-script-path-to-run-magic-command-as-a-variable-in-databricks-no
I want to run a notebook in databricks from another notebook using %run. Also I want to be able to send the path of the notebook that I'm running to the main notebook as a parameter. The reason for not using dbutils.notebook.run is that I'm storing nested dictionaries in the notebook that's called and I wanna use them ...
Unfortunately it's impossible to pass the path in %run as variable. You can pass variable as parameter only, and it's possible only in combination with with widgets - you can see the example in this answer. In this case you can have all your definitions in one notebook, and depending on the passed variable you can rede...
14
1
68,901,049
2021-8-24
https://stackoverflow.com/questions/68901049/copying-the-docstring-of-function-onto-another-function-by-name
I'm looking to copy the docstring of a function in the same file by name (with a decorator). I can easily do it with a function that is out of the current module, but I'm a bit confused when it comes to the same module (or the same class more specifically) Here's what I have so far: import inspect def copy_doc(func_nam...
After some testing and experimentation, I learned you could directly reference the function in a given class. * Note ParamSpec and TypeVar are to keep the correct signature of the wrapped function, you can remove all the annotations if you do not need them. from typing import Callable, TypeVar, Any, TypeAlias from typi...
8
11
68,826,941
2021-8-18
https://stackoverflow.com/questions/68826941/python-coverage-for-async-methods
I use aiohttp, pytest and pytest-cov to get coverage of my code. I want to get better coverage< but now I am a little bit stuck, because event simple code does not show 100% cov. For example this piece of code: @session_decorator() async def healthcheck(session, request): await session.scalar("select pg_is_in_recovery(...
I had the same issue when testing FastAPI code using asyncio. The fix is to create or edit a .coveragerc at the root of your project with the following content: [run] concurrency = gevent If you use a pyproject.toml you can also include this section in that file instead: [tool.coverage.run] concurrency = ["gevent"] I...
12
7
68,888,941
2021-8-23
https://stackoverflow.com/questions/68888941/keyerror-received-unregistered-task-of-type-on-celery-while-task-is-registere
I'm a bit new in celery configs. I have a task named myapp.tasks.my_task for example. I can see myapp.tasks.my_task in registered tasks of celery when I use celery inspect registered. doesn't it mean that the task is successfully registered? why it raises the following error for it: KeyError celery.worker.consumer.cons...
Back in the day, when I faced the problem a senior solved it for me in a mushroom management way unfortunately (see more about this anti-pattern here). I came back to this problem recently to figure out the solution in our own project domain. As Niel pointed in his/her solution, we were using celery_app.autodiscover_ta...
10
5
68,836,551
2021-8-18
https://stackoverflow.com/questions/68836551/keras-attributeerror-sequential-object-has-no-attribute-predict-classes
Im attempting to find model performance metrics (F1 score, accuracy, recall) following this guide https://machinelearningmastery.com/how-to-calculate-precision-recall-f1-and-more-for-deep-learning-models/ This exact code was working a few months ago but now returning all sorts of errors, very confusing since i havent c...
This function was removed in TensorFlow version 2.6. According to the keras in rstudio reference update to predict_x=model.predict(X_test) classes_x=np.argmax(predict_x,axis=1) Or use TensorFlow 2.5.x . If you are using TensorFlow version 2.5, you will receive the following warning: tensorflow\python\keras\engine\seq...
78
124
68,882,603
2021-8-22
https://stackoverflow.com/questions/68882603/using-python-poetry-to-publish-to-test-pypi-org
I have been investigating the use of Poetry to publish Python projects. I wanted to test the publishing process using a trivial project similar to the Python Packaging Authority tutorial. Since this is a trivial project, I want to publish it to the test instance of pypi rather than the real instance. Test.pypi requires...
I've successfully used tokens and poetry to upload to PyPI and TestPyPI. I believe you just need to change the TestPyPI URL you are configuring by appending /legacy/: poetry config repositories.test-pypi https://test.pypi.org/legacy/ You can then create your token as you were doing previously: poetry config pypi-token...
25
37
68,844,666
2021-8-19
https://stackoverflow.com/questions/68844666/github-action-is-being-killed
I'm running a little python project to collect data. It's being triggered by a scheduled GitHub Action script (every midnight). As part of expanding the project I've added the pycaret library to the project. So currently installing the requirements for the project is taking about 15 minutes, plus running the python pro...
Error 137 indicates that the container (runner/build agent) that builds your project received SIGKILL and terminated. It can be initiated manually or by the host machine when the runner exceeds its allocated memory limit. In your case, since it is initiated by Github itself, then it is generally due to being out of mem...
9
9
68,896,173
2021-8-23
https://stackoverflow.com/questions/68896173/issue-caching-python-dependencies-in-github-actions
I have the following steps in a github action: steps: - name: Check out repository code uses: actions/checkout@v2 - name: Cache dependencies id: pip-cache uses: actions/cache@v2 with: path: ~.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} restore-keys: | ${{ runner.os }}-pip- - name: Instal...
You're only caching source tarballs and binary wheels downloaded by pip. You're not caching: Installed Python packages (i.e., the site-packages/ subdirectory of the active Python interpreter). Installed entry points (i.e., executable commands residing in the current ${PATH}). That isn't necessarily a bad thing. Merel...
5
8
68,860,879
2021-8-20
https://stackoverflow.com/questions/68860879/vscode-keras-intellisensesuggestion-not-working-properly
Intellisense works fine on importing phrase But when it comes with chaining method, it shows different suggestions Python & Pylance extensions are installed.
From this issue on github try adding this to the bottom of your tensorflow/__init__.py (in .venv/Lib/site-packages/tensorflow for me) # Explicitly import lazy-loaded modules to support autocompletion. # pylint: disable=g-import-not-at-top if _typing.TYPE_CHECKING: from tensorflow_estimator.python.estimator.api._v2 impo...
7
14
68,900,763
2021-8-24
https://stackoverflow.com/questions/68900763/how-to-update-pandas-dataframe-drop-for-future-warning-all-arguments-of-data
The following code: df = df.drop('market', 1) generates the warning: FutureWarning: In a future version of pandas all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only market is the column we want to drop, and we pass the 1 as a second parameter for axis (0 for index, 1 for columns, s...
From the documentation, pandas.DataFrame.drop has the following parameters: Parameters labels: single label or list-like Index or column labels to drop. axis: {0 or ‘index’, 1 or ‘columns’}, default 0 Whether to drop labels from the index (0 or ‘index’) or columns (1 or ‘columns’). index: single label or list-like ...
42
47
68,849,673
2021-8-19
https://stackoverflow.com/questions/68849673/importing-numpy-shows-warning-when-running-in-mod-wsgi
I am running a Flask application in Apache using mod_wsgi. When I try to import numpy, I get the following warning: /usr/local/lib/python3.8/dist-packages/scipy/__init__.py:67: UserWarning: NumPy was imported from a Python sub-interpreter but NumPy does not properly support sub-interpreters. This will likely work for ...
Following the information here, you can eliminate the warning (and prevent potential problems) by adding WSGIApplicationGroup %{GLOBAL} to your httpd.conf.
11
16
68,826,091
2021-8-18
https://stackoverflow.com/questions/68826091/the-specified-device-is-not-open-or-is-not-recognized-by-mci
I was programming a game using Python and a sound effect needed to be played, so I used the playsound module: from playsound import playsound playsound("Typing.wav", False) And when I attempted the run the program this error was returned: Error 263 for command: open Typing.wav The specified device is not open or is no...
I faced this problem too firstly as mentioned in the previous comments I downgraded my python version from 3.10 to 3.7 and yet the problem persisted. So what actually worked is that the recent versions of playsound are giving such errors in order to fix this run the following commands in cmd as admin pip uninstall play...
24
63
68,893,521
2021-8-23
https://stackoverflow.com/questions/68893521/simple-example-of-pandas-extensionarray
It seems to me that Pandas ExtensionArrays would be one of the cases where a simple example to get one started would really help. However, I have not found a simple enough example anywhere. Creating an ExtensionArray To create an ExtensionArray, you need to Create an ExtensionDtype and register it Create an ExtensionA...
Update 2021-09-19 There were too many issues trying to get NullableIntArray to pass the test suite, so I've created a new example (AngleDtype + AngleArray) that currently passes 398 tests (fails 2). 0. Usage (pandas 1.3.2, numpy 1.20.2, python 3.9.2) AngleArray stores either radians or degrees depending on its unit (r...
20
34
68,906,112
2021-8-24
https://stackoverflow.com/questions/68906112/how-to-get-an-exact-representation-of-floats-during-dataframe-to-json
I observed the following behavior with DataFrame.to_json: >>> df = pd.DataFrame([[eval(f'1.12345e-{i}') for i in range(8, 20)]]) >>> df 0 1 2 3 4 5 6 7 8 9 10 11 0 1.123450e-08 1.123450e-09 1.123450e-10 1.123450e-11 1.123450e-12 1.123450e-13 1.123450e-14 1.123450e-15 1.123450e-16 1.123450e-17 1.123450e-18 1.123450e-19 ...
I'm not sure on achieving this with pd.DataFrame.to_json, but we can use pd.DataFrame.to_dict, json, and pd.read_json to achieve a full precision json representation from a pandas dataframe. json_df = json.dumps(df.to_dict('index'), indent=2) >>> print(json_df) { "0": { "0": 1.12345e-08, "1": 1.12345e-09, "2": 1.12345e...
7
1
68,895,380
2021-8-23
https://stackoverflow.com/questions/68895380/automated-legend-creation-for-3d-plot
I'm trying to update below function to report the clusters info via legend: color_names = ["red", "blue", "yellow", "black", "pink", "purple", "orange"] def plot_3d_transformed_data(df, title, colors="red"): ax = plt.figure(figsize=(12,10)).gca(projection='3d') #fig = plt.figure(figsize=(8, 8)) #ax = fig.add_subplot(11...
You need to save the reference to the first legend and add it to your ax as a separate artist before creating the second legend. That way, the second call to ax.legend(...) does not erase the first legend. For the second legend, I simply created a circle for each unique color and added it in. I forgot how to draw real ...
5
0
68,887,729
2021-8-23
https://stackoverflow.com/questions/68887729/vs-pylance-warning-import-module-could-not-be-resolved
Hi I am getting the following warning (A squiggly line underneath imports), import "numpy" could not be resolved Pylance(reportMissingModuleSource). There is no issues with executing the code - works fine, just the warning (squiggly line). In the following github page, it states to change Settings.JSON with following l...
If I understand your problem correctly, your python environment is properly set (for you are able to run your code) but your IDE (Vs code) points import errors. That is probably because your IDE does not know which python environment use for your current project (which seems to live somewhere in /home/imantha/workspace...
15
18
68,850,403
2021-8-19
https://stackoverflow.com/questions/68850403/best-way-to-flatten-and-remap-orm-to-pydantic-model
I am using Pydantic with FastApi to output ORM data into JSON. I would like to flatten and remap the ORM model to eliminate an unnecessary level in the JSON. Here's a simplified example to illustrate the problem. original output: {"id": 1, "billing": [ {"id": 1, "order_id": 1, "first_name": "foo"}, {"id": 2, "order_id"...
What if you override the from_orm class method? class Order(BaseModel): id: int name: List[str] = None billing: List[Billing] class Config: orm_mode = True @classmethod def from_orm(cls, obj: Any) -> 'Order': # `obj` is the orm model instance if hasattr(obj, 'billing'): obj.name = obj.billing.first_name return super()....
10
14
68,848,055
2021-8-19
https://stackoverflow.com/questions/68848055/pip-installing-a-whl-file-from-a-private-github-repository
How can one install a .whl (python library) from a private github repo? I have setup a personal access token and can install the library if its not a .whl by using the following command pip install git+https://{token}@github.com/{org_name}/{repo_name}.git However if there is a .whl in the repo and I want to install fr...
You should be able to do pip install https://{token}@raw.githubusercontent.com/{user}/{repo}/master/{name.whl}
12
9
68,876,869
2021-8-21
https://stackoverflow.com/questions/68876869/sort-and-concatenate-the-dataframes
I have following two dataframes: >>> df1 c1 c2 v1 v2 0 A NaN 9 2 1 B NaN 2 5 2 C NaN 3 5 3 D NaN 4 2 >>> df2 c1 c2 v1 v2 0 A P 4 1 1 A T 3 1 2 A Y 2 0 3 B P 0 1 4 B T 2 2 5 B Y 0 2 6 C P 1 2 7 C T 1 2 8 C Y 1 1 9 D P 1 1 10 D T 2 0 11 D Y 1 1 I need to concatenate the dataframes and sort them or vice versa. The first ...
Another solution using groupby without sorting groups: import itertools out = pd.concat([df1.sort_values('v1'), df2.sort_values('v2')], ignore_index=True) # Original answer # >>> out.reindex(out.groupby('c1', sort=False) # .apply(lambda x: x.index) # .explode()) # Faster alternative >>> out.loc[itertools.chain.from_it...
7
4
68,914,523
2021-8-24
https://stackoverflow.com/questions/68914523/fastapi-pydantic-value-error-raises-internal-server-error
I am using FastAPI with Pydantic. My problem - I need to raise ValueError using Pydantic from fastapi import FastAPI from pydantic import BaseModel, validator from fastapi import Depends, HTTPException app = FastAPI() class RankInput(BaseModel): rank: int @validator('rank') def check_if_value_in_range(cls, v): """ chec...
If you're not raising an HTTPException then normally any other uncaught exception will generate a 500 response (an Internal Server Error). If your intent is to respond with some other custom error message and HTTP status when raising a particular exception - say, ValueError - then you can use add a global exception han...
18
15
68,913,379
2021-8-24
https://stackoverflow.com/questions/68913379/how-to-create-the-custom-loss-function-by-adding-negative-entropy-to-the-cross-e
I recently read a paper entitled "REGULARIZING NEURAL NETWORKS BY PENALIZING CONFIDENT OUTPUT DISTRIBUTIONS https://arxiv.org/abs/1701.06548". The authors discuss regularizing neural networks by penalizing low entropy output distributions through adding a negative entropy term to the negative log-likelihood and creatin...
The entropy of y_pred is essentially the categorical cross entropy between y_pred and itself: def custom_loss(y_true, y_pred, beta): cce = tf.keras.losses.CategoricalCrossentropy() return cce(y_true, y_pred) - beta*cce(y_pred, y_pred)
5
1
68,913,649
2021-8-24
https://stackoverflow.com/questions/68913649/python3-dataframe-mutiple-separators
I'm trying to take my df.to_csv which is sep="\t" and turn that tab into two spaces instead. This question is similar but the solution isn't working: Pandas to_csv with multiple separators \s+ won't work as python will complain that its not a single char separator. This works as its a tab: df2.to_csv('test.csv', index=...
Let's look at using to_markdown instead of to_csv: df = pd.DataFrame({'col1':'aaa bbb ccc'.split(), 'col2':[1, 10, 1000], 'col3': [True, False, True]}) df.to_markdown('a.txt', tablefmt='plain', index=False) !type a.txt File: col1 col2 col3 aaa 1 True bbb 10 False ccc 1000 True
5
1
68,848,853
2021-8-19
https://stackoverflow.com/questions/68848853/how-can-i-set-a-number-of-default-values-for-many-fastapi-endpoints
I am using FastAPI and I have a number of endpoints that look like this: @app.get("/REDS/") def query_REDS( request: Request, lighter: Optional[bool] = False, darker: Optional[bool] = False, inverse: Optional[bool] = False, amount: Optional[int] = 10): pass # Work done here @app.get("/BLUES/") def query_BLUES( request:...
To do what you want, you can use regular classes or pydantic models as class dependencies: class CommonParams: def __init__(self, request: Request, lighter: Optional[bool] = False, darker: Optional[bool] = False, inverse: Optional[bool] = False, amount: Optional[int] = 10): self.request = request self.lighter = lighter...
5
7
68,869,110
2021-8-20
https://stackoverflow.com/questions/68869110/python-static-type-hint-check-mismatch-between-iterableanystr-vs-iterablestr
I'm running into this static type hint mismatch (with Pyright): from __future__ import annotations from typing import AnyStr, Iterable def foo(i: Iterable[AnyStr]): return i def bar(i: Iterable[str] | Iterable[bytes]): return i def baz(i: Iterable[str | bytes]): return i def main(): s = ['a'] # makes sense to me baz(fo...
Paraphrased answer from erictraut@github: This isn't really the intended use for a constrained TypeVar. I recommend using an @overload instead: @overload def foo(i: Iterable[str]) -> Iterable[str]: ... @overload def foo(i: Iterable[bytes]) -> Iterable[bytes]: ... def foo(i: Iterable[AnyStr]) -> Iterable[AnyStr]: retur...
5
2
68,909,283
2021-8-24
https://stackoverflow.com/questions/68909283/how-to-customize-pandas-pie-plot-with-labels-and-legend
Tried plotting a pie chart using: import pandas as pd import numpy as np data = {'City': ['KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'ACCRA'], 'Building': ['Commercial', 'Commercial', 'Industrial', 'Commercial', 'Industrial', 'Commercial', 'Commercial', 'Commercial', 'Commercial'], 'LPL':...
legend=True adds the legend title='Air Termination System' puts a title at the top ylabel='' removes 'Air Termination System' from inside the plot. The label inside the plot was a result of radius=1.5 labeldistance=None removes the other labels since there is a legend. If necessary, specify figsize=(width, height) ins...
5
12
68,905,848
2021-8-24
https://stackoverflow.com/questions/68905848/how-to-correctly-specify-type-hints-with-asyncgenerator-and-asynccontextmanager
Consider the following code import contextlib import abc import asyncio from typing import AsyncContextManager, AsyncGenerator, AsyncIterator class Base: @abc.abstractmethod async def subscribe(self) -> AsyncContextManager[AsyncGenerator[int, None]]: pass class Impl1(Base): @contextlib.asynccontextmanager async def sub...
I just happened to come up with the same problem and found this question on the very same day, but also figured out the answer quickly. You need to remove async from the abstract method. To explain why, I'll simplify the case to a simple async iterator: @abc.abstractmethod async def foo(self) -> AsyncIterator[int]: pas...
27
32