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 |
|---|---|---|---|---|---|---|
71,670,587 | 2022-3-30 | https://stackoverflow.com/questions/71670587/node-gyp-rebuilding-failing-on-macos-12-3-to-make-for-hunspell-with-error-127 | I started facing and error on node-gyp when running make for hunspell which a dependency from the the npm library spellchecker after updating my macOS to 12.3 last week. No other change related to environment or versions changed, and compilation still work for colleagues of mine: > spellchecker@3.7.1 install /Users/myu... | The problem was related to this line in the log: env: python: No such file or directory Apple did removed the default Python installation (Python 2.7) that used to come with macOS (macOS 12.3 Release Notes). The fix is quite simple and consist on installing Python and changing the path to become the default one. This ... | 7 | 19 |
71,650,452 | 2022-3-28 | https://stackoverflow.com/questions/71650452/use-fastapi-to-parse-incoming-post-request-from-slack | I'm building a FastAPI server to receive requests sent by slack slash command. Using the code below, I could see that the following: token=BLAHBLAH&team_id=BLAHBLAH&team_domain=myteam&channel_id=BLAHBLAH&channel_name=testme&user_id=BLAH&user_name=myname&command=%2Fwhatever&text=test&api_app_id=BLAHBLAH&is_enterprise_in... | Receive JSON data You would normally use Pydantic models to declare a request body—if you were about to receive data in JSON format—thus, benefiting from the automatic validation that Pydantic has to offer (for more options on how to post JSON data, have a look at this answer). In Pydantic V2 the dict() method has been... | 4 | 11 |
71,613,305 | 2022-3-25 | https://stackoverflow.com/questions/71613305/how-to-process-requests-from-multiiple-users-using-ml-model-and-fastapi | I'm studying the process of distributing artificial intelligence modules through FastAPI. I created a FastAPI app that answers questions using a pre-learned Machine Learning model. In this case, it is not a problem for one user to use it, but when multiple users use it at the same time, the response may be too slow. He... | First, you should rather not load your model every time a request arrives, but rahter have it loaded once at startup (you could use the startup event for this) and store it on the app instance—using the generic app.state attribute (see implementation of State too)—which you can later retrieve, as described here and her... | 6 | 10 |
71,595,635 | 2022-3-24 | https://stackoverflow.com/questions/71595635/render-numpy-array-in-fastapi | I have found How to return a numpy array as an image using FastAPI?, however, I am still struggling to show the image, which appears just as a white square. I read an array into io.BytesIO like so: def iterarray(array): output = io.BytesIO() np.savez(output, array) yield output.get_value() In my endpoint, my return is... | Option 1 - Return image as bytes The below examples show how to convert an image loaded from disk, or an in-memory image (in the form of numpy array), into bytes (using either PIL or OpenCV libraries) and return them using a custom Response directly. For the purposes of this demo, the below code is used to create the i... | 4 | 11 |
71,591,971 | 2022-3-23 | https://stackoverflow.com/questions/71591971/how-can-i-fix-the-zsh-command-not-found-python-error-macos-monterey-12-3 | Since I got the macOS v12.3 (Monterey) update (not sure it's related though), I have been getting this error when I try to run my Python code in the terminal: I am using Python 3.10.3, Atom IDE, and run the code in the terminal via atom-python-run package (which used to work perfectly fine). The settings for the packa... | OK, after a couple of days trying, this is what has worked for me: I reinstalled Monterey (not sure it was essential, but I just figured I had messed with terminal and $PATH too much). I installed python via brew rather than from the official website. It would still return command not found error. I ran echo "alias py... | 262 | 184 |
71,654,669 | 2022-3-28 | https://stackoverflow.com/questions/71654669/what-is-the-point-of-the-slice-indices-method | What is the point of the slice.indices method, since we have the following equality? s = slice(start, stop, step) assert range(*s.indices(length)) == range(length)[s] | Since Python 3.2 added slicing support to range, the slice.indices method is unnecessary because s.indices(length) is equal to (range(length)[s].start, range(length)[s].stop, range(length)[s].step): range objects now support index and count methods. This is part of an effort to make more objects fully implement the co... | 4 | 4 |
71,592,285 | 2022-3-23 | https://stackoverflow.com/questions/71592285/how-to-annotate-that-a-function-produces-a-dataclass | Say you want to wrap the dataclass decorator like so: from dataclasses import dataclass def something_else(klass): return klass def my_dataclass(klass): return something_else(dataclass(klass)) How should my_dataclass and/or something_else be annotated to indicate that the return type is a dataclass? See the following ... | There is no feasible way to do this prior to PEP 681. A dataclass does not describe a type but a transformation. The actual effects of this cannot be expressed by Python's type system – @dataclass is handled by a MyPy Plugin which inspects the code, not just the types. This is triggered on specific decorators without u... | 8 | 9 |
71,603,314 | 2022-3-24 | https://stackoverflow.com/questions/71603314/ssl-error-unsafe-legacy-renegotiation-disabled | I am running a Python code where I have to get some data from HTTPSConnectionPool(host='ssd.jpl.nasa.gov', port=443). But each time I try to run the code I get the following error. I am on MAC OS 12.1 raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='ssd.jpl.nasa.gov', port=443)... | This error comes up when using OpenSSL 3 to connect to a server which does not support it. The solution is to downgrade the cryptography package in python: run pip install cryptography==36.0.2 in the used enviroment. source: https://github.com/scrapy/scrapy/issues/5491 EDIT: Refer to Harry Mallon and ahmkara's answer f... | 83 | 18 |
71,599,282 | 2022-3-24 | https://stackoverflow.com/questions/71599282/how-to-pass-kwargs-as-params-to-fastapi-endpoint | I have a function generating a dict template. This function consists of several generators and requires one parameter (i.e., carrier) and has many optional parameters (keyword arguments - **kwargs). def main_builder(carrier, **params): output = SamplerBuilder(DEFAULT_JSON) output.generate_flight(carrier) output.generat... | Using Pydantic Model Since your function "..has many optional parameters" and passengers parameter requires a dictionary as an input, I would suggest creating a Pydantic model, where you define the parameters, and which would allow you sending the data in JSON format and getting them automatically validated by Pydantci... | 4 | 4 |
71,617,325 | 2022-3-25 | https://stackoverflow.com/questions/71617325/ssl-decryption-failed-or-bad-record-mac-decryption-failed-or-bad-record-mac-s | When I try to install python on Windows using anaconda, I get the following error: SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC decryption failed or bad record mac (_ssl.c:2633) Anaconda Prompt Error How can I fix? I have already try to set ssl verification parameter to false using: conda config --set ssl_verify false Thi... | Had this error when updating conda with: conda update -n base -c defaults conda which led to: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption failed or bad record mac (_ssl.c:2622) [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption failed or bad record mac (_ssl.c:2622) I found two downloads that had been st... | 4 | 1 |
71,592,060 | 2022-3-23 | https://stackoverflow.com/questions/71592060/makefile-how-should-i-extract-the-version-number-embedded-in-pyproject-toml | I have a python project with a pyproject.toml file. Typically I store the project's version number in pyproject.toml like this: % grep version pyproject.toml version = "0.0.2" % I want to get that version number into a Makefile variable regardless of how many spaces wind up around the version terms. What should I do t... | An alternative solution to parse major.minor.patch, based on @Mike Pennington's answer: grep -m 1 version pyproject.toml | grep -e '\d.\d.\d' -o | 10 | 3 |
71,665,819 | 2022-3-29 | https://stackoverflow.com/questions/71665819/is-it-possible-to-write-a-csv-file-from-a-xarray-dataset-in-python | I have been using the python package xgrads to parse and read a descriptor file with a suffix .ctl which describes a raw binary 3D dataset, provided by GrADS (Grid Analysis and Display System), a widely used software for easy access, manipulation, and visualization of earth science data. I have been using the following... | Try this: Convert netcdf to dataframe df = ds.to_dataframe() Save dataframe to csv df.to_csv('df.csv') | 4 | 7 |
71,632,325 | 2022-3-26 | https://stackoverflow.com/questions/71632325/cannot-import-name-mapping-from-collections-on-importing-requests | Python Version: Python 3.10.4 PIP Version: pip 22.0.4 So I was trying to make a small project with sockets, I added a feature to upload files but whenever I import requests, it throws this error. Below is the code I ran. Traceback (most recent call last): File "C:\Programming\WireUS\test.py", line 1, in <module> impo... | As user2357112-supports-monica said, running pip install urllib3 fixes it. | 4 | 7 |
71,581,084 | 2022-3-23 | https://stackoverflow.com/questions/71581084/why-does-bot-get-channel-produce-nonetype | I'm making a Discord bot to handle an announcement command. When the command is used, I want the bot to send a message in a specific channel and send a message back to the user to show that the command was sent. However, I cannot get the message to be sent to the channel. I tried this code: import discord import os im... | Make sure you are sending an integer to get_channel(): await bot.get_channel(int(channel_id)).send(embed=embed_announce) | 4 | 3 |
71,643,087 | 2022-3-28 | https://stackoverflow.com/questions/71643087/vscode-will-not-autofocus-on-integrated-terminal-while-running-code | When I run without debugging in python on vscode it no longer autofocuses on the terminal forcing me to click into the terminal everytime to input data. Is there any solution to cause vscode to autofocus when code is running? | The following solution to this issue has been tested on Visual Studio Code 1.74.3. Install the Python extension for Visual Studio Code. Go to File >> Preferences >> Settings. In the Search settings field enter, "Python › Terminal: Focus After Launch" Click on, When launching a python terminal, whether to focus the cur... | 7 | 6 |
71,584,511 | 2022-3-23 | https://stackoverflow.com/questions/71584511/aws-cdk-type-cls-runtime-runtime-cannot-be-assigned-to-type-runtime | I get this flycheck error pointing to the runtime=_lambda.. variable: Argument of type "(cls: Runtime) -> Runtime" cannot be assigned to parameter "runtime" of type "Runtime" in function "__init__" Type "(cls: Runtime) -> Runtime" cannot be assigned to type "Runtime" # create lambda function # executed as root function... | This was a bug in jsii, the library CDK uses to transpile TypeScript (the language in which CDK is written) to Python. Here is the PR that fixed it. The fix was released in 1.64.0 If you are using a version before 1.64.0, you can use casting to suppress the error: import typing ... function = lambda_.Function( self, "f... | 4 | 8 |
71,584,885 | 2022-3-23 | https://stackoverflow.com/questions/71584885/ipdb-stops-showing-prompt-text-after-carriage-return | Recently when setting up a breakpoint using ipdb.set_trace(context=20) I can see the command I'm inputing the first time, after hitting return, next time I write an instruction or command in my ipdb prompt is not showing. When I hit enter it executes it and shows it in the previous lines. This wasn't happening until ve... | This doesn't seem like a bug in ipdb (nor in IPython for that matter, with which this reproduces as well). The problem is between freezegun and prompt-toolkit, which IPython (and consequently ipdb) rely on. I'm hoping they will accept this PR, but until then this behavior can be resolved by adding prompt_toolkit to the... | 14 | 7 |
71,652,965 | 2022-3-28 | https://stackoverflow.com/questions/71652965/importerror-cannot-import-name-safe-str-cmp-from-werkzeug-security | Any ideas on why I get this error? My project was working fine. I copied it to an external drive and onto my laptop to work on the road; it worked fine. I copied it back to my desktop and had a load of issues with invalid interpreters etc, so I made a new project and copied just the scripts in, made a new requirements.... | Werkzeug released v2.1.0 today, removing werkzeug.security.safe_str_cmp. You can probably resolve this issue by pinning Werkzeug~=2.0.0 in your requirements.txt file (or similar). pip install Werkzeug~=2.0.0 After that it is likely that you will also have an AttributeError related to the jinja package, so if you have ... | 38 | 66 |
71,654,590 | 2022-3-28 | https://stackoverflow.com/questions/71654590/dash-importerror-cannot-import-name-get-current-traceback-from-werkzeug-debu | I'm trying to run a simple dash app in a conda environment in Pycharm, however I'm running into the error in the title. Weirdly enough, I couldn't find a place on the internet which has a mention of this bug, except for here. The code is simple, as all I'm trying to run is a simple dashapp; code obtained the code from ... | I've been in the same problem. Uninstall the wrong version with: pip uninstall werkzeug Install the right one with: pip install -v https://github.com/pallets/werkzeug/archive/refs/tags/2.0.3.tar.gz | 22 | 13 |
71,660,787 | 2022-3-29 | https://stackoverflow.com/questions/71660787/how-to-trim-crop-bottom-whitespace-of-a-pdf-document-in-memory | I am using wkhtmltopdf to render a (Django-templated) HTML document to a single-page PDF file. I would like to either render it immediately with the correct height (which I've failed to do so far) or render it incorrectly and trim it. I'm using Python. Attempt type 1: wkhtmltopdf render to a very, very long single-pag... | There might be better ways to do this, but this at least works. I'm assuming that you are able to crop the PDF yourself, and all I'm doing here is determining how far down on the last page you still have content. If that assumption is wrong, I could probably figure out how to crop the PDF. Or otherwise, just crop the i... | 5 | 1 |
71,622,869 | 2022-3-25 | https://stackoverflow.com/questions/71622869/typeerror-init-missing-1-required-positional-argument-scheme-in-elasti | Below is my code- Elasticsearch is not using https protocol, it's using http protocol. pip uninstall elasticsearch pip install elasticsearch==7.13.4 import elasticsearch.helpers from elasticsearch import Elasticsearch # from elasticsearch import Elasticsearch, RequestsHttpConnection es_host = '<>' es_port = '<>' es_use... | I ran into a similar error. I am using elasticsearch==8.3.1. When you construct your url with the list of dictionaries, you need to define the schema. Add "scheme": "https" to your dictionary and that will solve the missing argument. es = Elasticsearch( [ {'host': 'localhost', 'port': '9200', "scheme": "https"} ], basi... | 11 | 10 |
71,666,214 | 2022-3-29 | https://stackoverflow.com/questions/71666214/deprecation-warnings-distutils-and-netcdf-file | I get two deprecation warnings whenever I try running any python code. They are: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. MIN_CHEMFILES_VERSION = LooseVersion("0.9") DeprecationWarning: Please use netcdf_file from the scipy.io namespace, the scipy.io.netcdf namespace ... | The DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. message is caused by the distutils module being overridden since setuptools 60.0.0. You would notice because the distutils.__file__ variable evals to .../site-packages/setuptools/_distutils/__init__.py, regardless of your ... | 4 | 12 |
71,599,769 | 2022-3-24 | https://stackoverflow.com/questions/71599769/importerror-cannot-import-name-inference-from-paddle | I am trying to implement paddleocr. I have installed it using: #Github repo installation for paddle ! python3 -m pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple #install paddle ocr !pip install paddleocr !git clone https://github.com/PaddlePaddle/PaddleOCR.git But while importing from paddleocr import... | I had the same error. My solution was to: pip install paddlepaddle Then I got another error (luckily you will not get this one but just in case) telling me to downgrade protoc to a version between 3.19 and 3.20, which I fixed by executing the following command: pip install protobuf==3.19.0 After this I was able to ex... | 5 | 5 |
71,639,534 | 2022-3-27 | https://stackoverflow.com/questions/71639534/why-the-sum-value-isnt-equal-to-the-number-of-samples-in-scikit-learn-rando | I built a random forest by RandomForestClassifier and plot the decision trees. What does the parameter "value" (pointed by red arrows) mean? And why the sum of two numbers in the [] doesn't equal to the number of "samples"? I saw some other examples, the sum of two numbers in the [] equals to the number of "samples". W... | Nice catch. Although undocumented, this is due to the bootstrap sampling taking place by default in a Random Forest model (see my answer in Why is Random Forest with a single tree much better than a Decision Tree classifier? for more on the RF algorithm details and its difference from a mere "bunch" of decision trees).... | 4 | 5 |
71,590,362 | 2022-3-23 | https://stackoverflow.com/questions/71590362/json-unicodedecodeerror-charmap-codec-cant-decode-byte-0x8d-in-position-3621 | I'm loading a json file on my computer. I can load it in without specifying the encoding on Kaggle, no, errors. On my PC I get the error in the title. with open('D:\soccer\statsbomb360\matches.json') as f: data = json.load(f, encoding = 'utf8') Adding errors = 'ignore' or changing encoding to 'latin' doesn't work eith... | Try with open('D:\soccer\statsbomb360\matches.json', encoding="utf8") as f: data = json.load(f) per @mark-tolonen Also see this post: UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> | 4 | 9 |
71,648,007 | 2022-3-28 | https://stackoverflow.com/questions/71648007/npm-install-error-npm-err-gyp-err-find-python-stack-error | Whenever I try to run npm install or npm update in my nuxt.js(vue.js) project, error below appears. npm ERR! code 1 npm ERR! path /Users/kyeolhan/ForWork/BackOffceFront/node_modules/deasync npm ERR! command failed npm ERR! command sh -c node ./build.js npm ERR! gyp info it worked if it ends with ok npm ERR! gyp info us... | I resolved this issue by downgrading node version (to v14.19.1). #reference! How to solve npm install error “npm ERR! code 1” | 7 | 10 |
71,627,943 | 2022-3-26 | https://stackoverflow.com/questions/71627943/update-an-element-in-faiss-index | I am using faiss indexflatIP to store vectors related to some words. I also use another list to store words (the vector of the nth element in the list is nth vector in faiss index). I have two questions: Is there a better way to relate words to their vectors? Can I update the nth element in the faiss? | You can do both. Is there a better way to relate words to their vectors? Call index.add_with_ids(vectors, ids) Some index types support the method add_with_ids, but flat indexes don't. If you call the method on a flat index, you will receive the error add_with_ids not implemented for this type of index If you want ... | 8 | 9 |
71,612,119 | 2022-3-25 | https://stackoverflow.com/questions/71612119/how-to-extract-texts-and-tables-pdfplumber | With the pdfplumber library, you can extract the text of a PDF page, or you can extract the tables from a pdf page. The issue is that I can't seem to find a way to extract text and tables. Essentially, if the pdf is formatted in this way: text1 tablename ___________ | Header 1 | ------------ | row 1 | ------------ text... | You can get tables' bounding boxes and then filter out all of the words inside them, something like this: def check_bboxes(word, table_bbox): """ Check whether word is inside a table bbox. """ l = word['x0'], word['top'], word['x1'], word['bottom'] r = table_bbox return l[0] > r[0] and l[1] > r[1] and l[2] < r[2] and l... | 4 | 3 |
71,652,903 | 2022-3-28 | https://stackoverflow.com/questions/71652903/torchtext-vocab-typeerror-vocab-init-got-an-unexpected-keyword-argument | I am working on a CNN Sentiment analysis machine learning model which uses the IMDb dataset provided by the Torchtext library. On one of my lines of code vocab = Vocab(counter, min_freq = 1, specials=('\<unk\>', '\<BOS\>', '\<EOS\>', '\<PAD\>')) I am getting a TypeError for the min_freq argument even though I am certai... | As https://github.com/pytorch/text/issues/1445 mentioned, you should change "Vocab" to "vocab". I think they miss-type the legacy-to-new notebook. correct code: from torchtext.datasets import IMDB from collections import Counter from torchtext.data.utils import get_tokenizer from torchtext.vocab import vocab tokenizer ... | 5 | 6 |
71,713,719 | 2022-3-24 | https://stackoverflow.com/questions/71713719/runtimeerror-dataloader-worker-pids-15876-2756-exited-unexpectedly | I am compiling some existing examples from the PyTorch tutorial website. I am working especially on the CPU device no GPU. When running a program the type of error below is shown. Does it become I'm working on the CPU device or setup issue? raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(p... | You need to first figure out why the dataLoader worker crashed. A common reason is out of memory. You can check this by running dmesg -T after your script crashes and see if the system killed any python process. | 4 | 2 |
71,628,971 | 2022-3-26 | https://stackoverflow.com/questions/71628971/jupyter-is-busy-stuck-randomly-when-input-is-executed-inside-while-statement | Has anyone ever had a problem that Jupyter is busy (stuck) when executing input() inside the while statement? The problem is randomly happening to me. Sometimes the command box is prompted next to the cell, and sometimes the input() box never prompts. Here is the simpler version of my code: from IPython.display import ... | Someone gave me an insight. The problem is because clear_output() asynchronous problem. Then I created this function: from time import sleep from IPython.display import clear_output def refresh_screen(): clear_output() sleep(0.02) and replaced all clear_output() with refresh_screen() in my code. The problem is gone. A... | 4 | 3 |
71,642,233 | 2022-3-28 | https://stackoverflow.com/questions/71642233/replacing-pythons-parser-functionality | First of all I want to mention that I know this is a horrible idea and it shouldn't be done. My intention is mainly curiosity and learning the innards of Python, and how to 'hack' them. I was wondering whether it is at all possible to change what happens when we, for instance, use [] to create a list. Is there a way to... | [] and {} are compiled to specific opcodes that specifically return a list or a dict, respectively. On the other hand list() and dict() compile to bytecodes that search global variables for list and dict and then call them as functions: import dis dis.dis(lambda:[]) dis.dis(lambda:{}) dis.dis(lambda:list()) dis.dis(lam... | 5 | 3 |
71,597,789 | 2022-3-24 | https://stackoverflow.com/questions/71597789/generate-all-digraphs-of-a-given-size-up-to-isomorphism | I am trying to generate all directed graphs with a given number of nodes up to graph isomorphism so that I can feed them into another Python program. Here is a naive reference implementation using NetworkX, I would like to speed it up: from itertools import combinations, product import networkx as nx def generate_digra... | There’s a useful idea that I learned from Brendan McKay’s paper “Isomorph-free exhaustive generation” (though I believe that it predates that paper). The idea is that we can organize the isomorphism classes into a tree, where the singleton class with the empty graph is the root, and each class with graphs having n > 0 ... | 8 | 3 |
71,607,514 | 2022-3-24 | https://stackoverflow.com/questions/71607514/stopiteration-error-while-drawing-a-pgmpy-networkx-graph | I have a python script that loads a csv file using pandas, and then uses pgmpy to learn a bayesian network over the data. After learning the structure, I am drawing the graph using the function: nx.draw(graph_model, node_color='#00b4d9', with_labels=True) This works perfectly in Ubuntu, However, it is throwing a StopI... | I finally solved it by adding the position as a circular layout. Looks like in the previous version, it automatically did this, but in the new version that was installed in the virtual machine don't. pos = nx.circular_layout(graph_model) nx.draw(graph_model, node_color='#00b4d9', pos=pos, with_labels=True) | 5 | 6 |
71,655,179 | 2022-3-29 | https://stackoverflow.com/questions/71655179/how-can-i-make-an-object-with-an-interface-like-a-random-number-generator-but-t | I'd like to construct an object that works like a random number generator, but generates numbers in a specified sequence. # a random number generator rng = lambda : np.random.randint(2,20)//2 # a non-random number generator def nrng(): numbers = np.arange(1,10.5,0.5) for i in range(len(numbers)): yield numbers[i] for j... | Edit: The cleanest way to do this would be to use a lambda to wrap your call to next(nrng) as per great comment from @GACy20: def nrng_gen(): yield from range(10) nrng = nrng_gen() nrng_func = lambda: next(nrng) for i in range(10): print(nrng_func()) Original answer: If you want your object to keep state and look like... | 18 | 16 |
71,665,973 | 2022-3-29 | https://stackoverflow.com/questions/71665973/inputting-just-a-comma-returns-strange-behaviour | Today I by mistake inputted just a comma on an interactive session Input: , and I noticed strangely that it did not return an error but instead: Output '' So I explored a bit this behaviour and tried some random stuff, and it seems like it creates tuples of strings, but it seems like these objects cannot be interacte... | This is an input transformation performed by the EscapedCommand class, specifically here. It's not part of autocall (details see below) which is handled by prefilter.AutoHandler. I couldn't find any public documentation on "escaped commands" and the class' docstring just mentions that it is a "transformer for escaped c... | 4 | 2 |
71,668,895 | 2022-3-29 | https://stackoverflow.com/questions/71668895/pydantic-inherit-generic-class | New to python and pydantic, I come from a typescript background. I was wondering if you can inherit a generic class? In typescript the code would be as follows interface GenericInterface<T> { value: T } interface ExtendsGeneric<T> extends GenericInterface<T> { // inherit value from GenericInterface otherValue: string }... | Generics are a little weird in Python, and the problem is that ExtendsGenericField itself isn't declared as generic. To solve, just add Generic[T] as a super class of ExtendsGenericField: from pydantic.generics import GenericModel from typing import TypeVar from typing import Generic T = TypeVar("T", int, str) class Ge... | 9 | 14 |
71,641,609 | 2022-3-28 | https://stackoverflow.com/questions/71641609/how-does-cpython-implement-os-environ | I was looking through source and noticed that it references a variable environ in methods before its defined: def _createenviron(): if name == 'nt': # Where Env Var Names Must Be UPPERCASE def check_str(value): if not isinstance(value, str): raise TypeError("str expected, not %s" % type(value).__name__) return value en... | TLDR search for from posix import * in os module content. The os module imports all public symbols from posix (Unix) or nt (Windows) low-level module at the beginning of os.py. posix exposes environ as a plain Python dict. os wraps it with _Environ dict-like object that updates environment variables on _Environ items c... | 7 | 2 |
71,644,405 | 2022-3-28 | https://stackoverflow.com/questions/71644405/why-is-it-faster-to-compare-strings-that-match-than-strings-that-do-not | Here are two measurements: timeit.timeit('"toto"=="1234"', number=100000000) 1.8320042459999968 timeit.timeit('"toto"=="toto"', number=100000000) 1.4517491540000265 As you can see, comparing two strings that match is faster than comparing two strings with the same size that do not match. This is quite disturbing: Duri... | Combining my comment and the comment by @khelwood: TL;DR: When analysing the bytecode for the two comparisons, it reveals the 'time' and 'time' strings are assigned to the same object. Therefore, an up-front identity check (at C-level) is the reason for the increased comparison speed. The reason for the same object ass... | 77 | 75 |
71,669,583 | 2022-3-29 | https://stackoverflow.com/questions/71669583/is-there-a-converse-to-operator-contains | edit: I changed the title from complement to converse after the discussion below. In the operator module, the binary functions comparing objects take two parameters. But the contains function has them swapped. I use a list of operators, e.g. operator.lt, operator.ge. They take 2 arguments, a and b. I can say operator.l... | If either of them posts an answer, you should accept that, but between users @chepner and @khelwood, they gave you most of the answer. The complement of operator.contains would be something like operator.does_not_contain, so that's not what you're looking for exactly. Although I think a 'reflection' isn't quite what yo... | 8 | 3 |
71,668,058 | 2022-3-29 | https://stackoverflow.com/questions/71668058/import-module-after-pip-install-wheel | I have a customized built module, lets call it abc, and pip install /local_path/abc-0.1-py3-none-any.whl. Installation is correct, >>pip install dist/abc-0.1-py3-none-any.whl Processing ./dist/abc-0.1-py3-none-any.whl Successfully installed abc-0.1 but I could not import the module. After I ran ppip freeze list and fo... | The setup.py is wrong, which means you're building a wheel with no packages actually inside. Instead of setup( ... packages=find_packages(include=["src"]), ... ) Try this: setup( ... packages=find_packages(where="src"), package_dir={"": "src"}, ... ) See Testing & Packaging for more info. | 4 | 3 |
71,664,875 | 2022-3-29 | https://stackoverflow.com/questions/71664875/what-is-the-replacement-for-distutils-util-get-platform | Apparently, Python 3.10 / 3.12 is going to deprecate / remove distutils (cpython/issues/92584). Unfortunately, I have not been able to find a replacement for the one and only function I am using from it; distutils.util.get_platform(). What is the replacement for this? Note that platform is NOT an answer. I need a funct... | For your use-case, sysconfig has a replacement import sysconfig sysconfig.get_platform() This is what the wheel project itself used as a replacement for distutils.util.get_platform() when removing distutils from the code in Replaced all uses of distutils with setuptools #428. | 7 | 9 |
71,661,851 | 2022-3-29 | https://stackoverflow.com/questions/71661851/typeerror-init-got-an-unexpected-keyword-argument-as-tuple | While I am testing my API I recently started to get the error below. if request is None: > builder = EnvironBuilder(*args, **kwargs) E TypeError: __init__() got an unexpected keyword argument 'as_tuple' /usr/local/lib/python3.7/site-packages/werkzeug/test.py:1081: TypeError As I read from the documentation in the new... | As of version 2.1.0, werkzeug has removed the as_tuple argument to Client. Since Flask wraps werkzeug and you're using a version that still passes this argument, it will fail. See the exact change on the GitHub PR here. You can take one of two paths to solve this: Upgrade flask Pin your werkzeug version # in requir... | 37 | 48 |
71,657,355 | 2022-3-29 | https://stackoverflow.com/questions/71657355/run-mypy-from-pre-commit-for-different-directories | I have the following structure for my project: project/ ├── backend │ ├── api_v1 │ ├── api_v2 │ └── api_v3 └── frontend Each of the API dirs, api_v1, api_v2, and api_v3, have python files. I would like to run pre-commit for each of these directories only if there is a change in the code. For eg., I would like to run m... | pre-commit operates on files so what you're trying to do isn't exactly supported but anything is possible. when not running on files you're going to take some efficiency concessions as you'll be linting much more often than you need to be here's a rough sketch for how you would do this: - repo: https://github.com/pre-c... | 6 | 10 |
71,661,228 | 2022-3-29 | https://stackoverflow.com/questions/71661228/how-to-multiply-several-vectors-by-one-matrix-at-once-in-numpy | I have a 2x2 rotation matrix and several vectors stored in a Nx2 array. Is there a way to rotate them all (i.e. multiply them all by the rotation matrix) at once? I'm sure there is a numpy method for that, it's just not obvious. import numpy as np vectors = np.array( ( (1,1), (1,2), (2,2), (4,2) ) ) # 4 2D vectors ang ... | Because m has shape (2,2) and vectors has shape (4,2), you can simply do dots = vectors @ m.T Then each row i contains the matrix-vector product m @ vectors[i, :]. | 4 | 2 |
71,654,966 | 2022-3-28 | https://stackoverflow.com/questions/71654966/how-can-i-append-or-concatenate-two-dataframes-in-python-polars | I see it's possible to append using the series namespace (https://stackoverflow.com/a/70599059/5363883). What I'm wondering is if there is a similar method for appending or concatenating DataFrames. In pandas historically it could be done with df1.append(df2). However that method is being deprecated (if it hasn't alrea... | There are different append strategies depending on your needs. df1 = pl.DataFrame({"a": [1], "b": [2], "c": [3]}) df2 = pl.DataFrame({"a": [4], "b": [5], "c": [6]}) # new memory slab new_df = pl.concat([df1, df2], rechunk=True) # append free (no memory copy) new_df = df1.vstack(df2) # try to append in place df1.extend(... | 17 | 43 |
71,656,644 | 2022-3-29 | https://stackoverflow.com/questions/71656644/python-type-hint-for-iterablestr-that-isnt-str | In Python, is there a way to distinguish between strings and other iterables of strings? A str is valid as an Iterable[str] type, but that may not be the correct input for a function. For example, in this trivial example that is intended to operate on sequences of filenames: from typing import Iterable def operate_on_f... | As of March 2022, the answer is no. This issue has been discussed since at least July 2016. On a proposal to distinguish between str and Iterable[str], Guido van Rossum writes: Since str is a valid iterable of str this is tricky. Various proposals have been made but they don't fit easily in the type system. You'll ne... | 23 | 10 |
71,656,436 | 2022-3-29 | https://stackoverflow.com/questions/71656436/pandas-groupby-cumcount-one-cumulative-count-rather-than-a-cumulative-count-fo | Let's say I have a df pd.DataFrame( {'name':['pam','pam','bob','bob','pam','bob','pam','bob'], 'game_id':[0,0,1,1,0,2,1,2] } ) name game_id 0 pam 0 1 pam 0 2 bob 1 3 bob 1 4 pam 0 5 bob 2 6 pam 1 7 bob 2 I want to calculate how many games bob and amy have appeared in cumulatively. However, when I use .groupby() and .c... | Lets try sort df, check consecutive difference, create new group by cumsum and then resort the df new_df=df.sort_values(by=['name','game_id']) new_df=new_df.assign(rank=new_df['game_id']!=new_df['game_id'].shift()) new_df=new_df.assign(rank=new_df.groupby('name')['rank'].cumsum()).sort_index() print(new_df) name game_i... | 4 | 2 |
71,650,564 | 2022-3-28 | https://stackoverflow.com/questions/71650564/pandas-dataframe-styler-how-to-style-pandas-dataframe-as-excel-table | How to style the pandas dataframe as an excel table (alternate row colour)? Sample style: Sample data: import pandas as pd import seaborn as sns df = sns.load_dataset("tips") | If your final goal is to save to_excel, the only way to retain the styling after export is using the apply-based methods: df.style.apply / df.style.applymap are the styling counterparts to df.apply / df.applymap and work analogously df.style.apply_index / df.style.applymap_index are the index styling counterparts (req... | 7 | 12 |
71,653,262 | 2022-3-28 | https://stackoverflow.com/questions/71653262/how-to-join-dataframes-with-multiple-ids | I have two dataframes and a rather tricky join to accomplish. The first dataframe: data = [[0, 'Standard1', [100, 101, 102]], [1, 'Standard2', [100, 102]], [2, 'Standard3', [103]]] df1 = pd.DataFrame(data, columns = ['RuleSetID', 'RuleSetName', 'KeyWordGroupID']) df1 Output: RuleSetID RuleSetName KeyWordGroupID 0 Stand... | The main idea is to convert df2 as a dict mapping Series where the key is the KeyWordGroupID column and the value is the KeyWords column. You can use explode to flatten KeyWordGroupID column of df1 then map it to df2 then groupby to reshape your first dataframe: df1['KeyWordGroupID'] = ( df1['KeyWordGroupID'].explode()... | 4 | 1 |
71,629,200 | 2022-3-26 | https://stackoverflow.com/questions/71629200/apache-beam-infer-schema-using-namedtuple-python | I am quite new to apache beam and I am wondering how to infer schema to a pcollection using namedtuple. The example from the documentation Programming Guide states: class Transaction(typing.NamedTuple): bank: str purchase_amount: float pc = input | beam.Map(lambda ...).with_output_types(Transaction) I tried to impleme... | Ok after some research on beam schema and digging in the source code I finally found the solution. It looks like you need to convert every single value in the pcollection to NamedTuple and later apply a type hint. with beam.Pipeline() as pipeline: record = pipeline | "Read Parquet" >> beam.io.ReadFromParquet("test.parq... | 4 | 4 |
71,648,736 | 2022-3-28 | https://stackoverflow.com/questions/71648736/how-to-get-a-list-of-all-custom-django-commands-in-a-project | I want to find a custom command in a project with many apps, how to get a list of all commands from all apps? | This command will list all the custom or existing command of all installed apps: python manage.py help | 6 | 13 |
71,648,826 | 2022-3-28 | https://stackoverflow.com/questions/71648826/why-gunicorn-use-same-thread | a simple python name myapp.py: import threading import os def app(environ, start_response): tid = threading.get_ident() pid = os.getpid() ppid = os.getppid() # ##### print('tid ================ ', tid) # why same tid? # ##### print('pid', pid) # print('ppid', ppid) # data = b"Hello, World!\n" start_response("200 OK", ... | Gunicorn creates multiple processes to avoid the Python GIL. Each process has a unique PID. Regarding the threads, threading.get_ident() is a Python specific thread identifier, it should be regarded as meaningless and relevant only within the local process. Instead, you should use threading.get_native_id() which retur... | 4 | 2 |
71,648,478 | 2022-3-28 | https://stackoverflow.com/questions/71648478/nested-list-after-json-normalize | I'm trying to get all the data out of an API call which is returned in the json format. For this purpose I'm using the json_normalize library from pandas, but I'm left with a list within that list that is not unwrapped. This is the code I am using: data=requests.get(url,endpointParams) data_read=json.loads(data.content... | Try: metadata = ['name', 'period', 'title', 'description', 'id'] out = pd.json_normalize(data_read['data'], 'values', metadata) value end_time name period title description id 50 2022-03-27T07:00:00+0000 follower_count day Follower Count Total number of unique accounts following this profile 1/insights/followe... | 4 | 4 |
71,642,386 | 2022-3-28 | https://stackoverflow.com/questions/71642386/how-to-open-excel-file-in-polars-dataframe | I am a python pandas user but recently found about polars dataframe and it seems quite promising and blazingly fast. I am not able to find a way to open an excel file in polars. Polars is happily reading csv, json, etc. but not excel. I am extensive user of excel files in pandas and I want to try using polars. I have m... | This is more of a workaround than a real answer, but you can read it into pandas and then convert it to a polars dataframe. import polars as pl import pandas as pd df = pd.read_excel(...) df_pl = pl.DataFrame(df) You could, however, make a feature request to the Apache Arrow community to support excel files. | 5 | 3 |
71,596,075 | 2022-3-24 | https://stackoverflow.com/questions/71596075/how-to-detect-corners-of-a-square-with-python-opencv | In the image below, I am using OpenCV harris corner detector to detect only the corners for the squares (and the smaller squares within the outer squares). However, I am also getting corners detected for the numbers on the side of the image. How do I get this to focus only on the squares and not the numbers? I need a m... | Here's a potential approach using traditional image processing: Obtain binary image. We load the image, convert to grayscale, Gaussian blur, then adaptive threshold to obtain a black/white binary image. We then remove small noise using contour area filtering. At this stage we also create two blank masks. Detect horiz... | 4 | 8 |
71,613,837 | 2022-3-25 | https://stackoverflow.com/questions/71613837/couldnt-use-data-file-coverage-unable-to-open-database-file | A strange issue with permissions occured when pushing to GitHub. I have a test job which runs tests with coverage and then pushes results to codecov on every push and pull request. However, this scenario only works with root user. If running with digitalshop user it throws an error: Couldn't use data file '/digital-sho... | So I ended up creating another Dockerfile called Dockerfile.test and putting pretty much the same configuration except non-admin user creation. Here's the final variant: Running code as root user is not recommended thus please read UPDATE section Dockerfile.test: FROM python:3.9-alpine3.13 ENV PYTHONUNBUFFERED 1 COPY .... | 9 | 1 |
71,600,077 | 2022-3-24 | https://stackoverflow.com/questions/71600077/make-all-keys-in-a-typed-dict-not-required | I have an existing TypedDict containing multiple entries: from typing import TypedDict class Params(TypedDict): param1:str param2:str param3:str I want to create the exact same TypedDict but with all the keys being optional so that the user can specify only certain parameters. I know I can do something like: class Opt... | What you ask for is not possible - at least if you use mypy - as you can read in the comments of Why can a Final dictionary not be used as a literal in TypedDict? and on mypy's github: TypedDict keys reuse?. Pycharm seems to have the same limitation, as tested in the two other "Failed attempts" answers to your question... | 6 | 5 |
71,632,230 | 2022-3-26 | https://stackoverflow.com/questions/71632230/pandas-create-a-date-range-with-utc-time | I have this code to create a date range dataframe dates_df = pd.date_range(start='01/01/2022', end='02/02/2022', freq='1H') The problem is that the time is not UTC. It is dtype='datetime64[ns] instead of dtype='datetime64[ns, UTC] How can I generate the date range in UTC without having the generated time change? | pass the parameter timezone = 'utc' otherwise the result of date_range() is timezone neutral and can be interpreted as your desired timezone dates_df = pd.date_range(start='01/01/2022', end='02/02/2022', freq='1H',tz='UTC') output: >>> DatetimeIndex(['2022-01-01 00:00:00+00:00', '2022-01-01 01:00:00+00:00', ... '2022-... | 4 | 9 |
71,632,064 | 2022-3-26 | https://stackoverflow.com/questions/71632064/why-i-cant-get-dictionary-keys-by-index | Since Python 3.7, dictionaries are ordered. So why I can't get keys by index? | Building in such an API would be an "attractive nuisance": the implementation can't support it efficiently, so better not to tempt people into using an inappropriate data structure. It's for much the same reason that, e.g., a linked list rarely offers an indexing API. That's totally ordered too, but there's no efficien... | 5 | 6 |
71,630,563 | 2022-3-26 | https://stackoverflow.com/questions/71630563/syntax-for-making-objects-callable-in-python | I understand that in python user-defined objects can be made callable by defining a __call__() method in the class definition. For example, class MyClass: def __init__(self): pass def __call__(self, input1): self.my_function(input1) def my_function(self, input1): print(f"MyClass - print {input1}") my_obj = MyClass() # ... | Functions are normal first-class objects in python. The name to with which you define a function object, e.g. with a def statement, is not set in stone, any more than it would be for an int or list. Just as you can do a = [1, 2, 3] b = a to access the elements of a through the name b, you can do the same with function... | 9 | 6 |
71,599,069 | 2022-3-24 | https://stackoverflow.com/questions/71599069/sort-a-list-of-dicts-according-to-a-list-of-values-with-regex | I'd like to sort the keys of the list_of_dicts according to the list_months. It works fine once I remove the digits (years) from the keys of list_of_dicts, but I cannot figure out how to use the regex correctly in the lambda function to include the digits. My code so far: import re list_months = ["Jan", "Feb", "Mar", "... | No need for a regex here. dict_months = {m:i for i, m in enumerate(list_months)} result = sorted(list_of_dicts, key=lambda d: dict_months[next(iter(d))[:3]]) print(result) # [{'Jan23': '92.731'}, {'Feb23': '90.459'}, {'Mar23': '86.209'}, {'Apr23': '64.401'}, {'May23': '58.705'}, {'Jun23': '56.509'}, {'Jul23': '56.6'}, ... | 4 | 3 |
71,594,548 | 2022-3-23 | https://stackoverflow.com/questions/71594548/sending-message-with-slack-webclient-that-includes-an-uploading-image | I'm trying to use the Slack Web Client to send a message from a bot to a private channel. The message would include some text and an image. After reading the current Slack documentation, it seems like the best way to accomplish this would be to use the file.upload method to upload the file to Slack, and then use the ch... | I found out that you need to have the top-level text property in addition to the blocks. The example below works as expected and now I'm able upload an image to Slack and the include that image in a message. See https://github.com/slackapi/python-slack-sdk/issues/1194 for more info. # get the file URL file_url = image[... | 4 | 3 |
71,591,770 | 2022-3-23 | https://stackoverflow.com/questions/71591770/typeerror-shield-got-an-unexpected-keyword-argument-loop-when-running-dis | When I launch my discord.py bot with this code: > from discord.ext import commands > > bot = commands.Bot(command_prefix = ",", description = "Bot de eagle57") > > bot.run("Mytoken") I get this error: C:\Users\Elève\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\connector.py:964: RuntimeWarning: co... | This is usually caused because of outdated aiohttp module You can run pip install -U aiohttp and pip install -U discord.py This will fix your issue in most cases | 5 | 7 |
71,595,728 | 2022-3-24 | https://stackoverflow.com/questions/71595728/pip-importerror-cannot-import-name-mapping-from-collections | There appear to be conflicting libraries of python that pip is trying to access, as you can see with the following error: [root@fedora user]# pip Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pip._internal import main File "/usr/local/lib/python3.10/site-packages/pip/_internal/_... | I fixed this by removing all pip folders in /usr/local/lib/python3.10/site-packages | 5 | 4 |
71,589,455 | 2022-3-23 | https://stackoverflow.com/questions/71589455/get-the-regex-match-and-the-rest-none-match-from-pythons-re-module | Does the re module of Python3 offer an in-build way to get the match and the rest (none-match) back? Here is a simple example: >>> import re >>> p = r'\d' >>> s = '1a' >>> re.findall(p, s) ['1'] The result I want is something like ['1', 'a'] or [['1'], ['a']] or something else where I can differentiate between match a... | Possible solution is the following: import re string = '1a' re_pattern = r'^(\d+)(.*)' result = re.findall(re_pattern, string) print(result) Returns list of tuples [('1', 'a')] or if you like to return list of str items result = [item for t in re.findall(re_pattern, string) for item in t] print(result) Returns ['1',... | 4 | 3 |
71,589,628 | 2022-3-23 | https://stackoverflow.com/questions/71589628/np-where-for-2d-array-manipulate-whole-rows | I want to rebuild the following logic with numpy broadcasting function such as np.where: From a 2d array check per row if the first element satisfies a condition. If the condition is true then return the first three elements as a row, else the last three elements. A short MWE in form of a for-loop which I want to circu... | If you want to use np.where: import numpy as np array = np.array([ [1, 2, 3, 4], [1, 2, 4, 2], [2, 3, 4, 6] ]) cond = array[:, 0] == 1 np.where(cond[:, None], array[:,:3], array[:,-3:]) output: array([[1, 2, 3], [1, 2, 4], [3, 4, 6]]) EDIT slightly more concise version: np.where(array[:, [0]] == 1, array[:,:3], array... | 4 | 2 |
71,581,197 | 2022-3-23 | https://stackoverflow.com/questions/71581197/what-is-the-loss-function-used-in-trainer-from-the-transformers-library-of-huggi | What is the loss function used in Trainer from the Transformers library of Hugging Face? I am trying to fine tune a BERT model using the Trainer class from the Transformers library of Hugging Face. In their documentation, they mention that one can specify a customized loss function by overriding the compute_loss method... | It depends! Especially given your relatively vague setup description, it is not clear what loss will be used. But to start from the beginning, let's first check how the default compute_loss() function in the Trainer class looks like. You can find the corresponding function here, if you want to have a look for yourself ... | 16 | 26 |
71,583,528 | 2022-3-23 | https://stackoverflow.com/questions/71583528/python-extracting-string | I have a dataframe where one of the columns which is in string format looks like this filename 0 Machine02-2022-01-28_00-21-45.blf.424 1 Machine02-2022-01-28_00-21-45.blf.425 2 Machine02-2022-01-28_00-21-45.blf.426 3 Machine02-2022-01-28_00-21-45.blf.427 4 Machine02-2022-01-28_00-21-45.blf.428 I want my column to loo... | please try this: df['filename'] = df['filename'].str.split('-',1).apply(lambda x:' '.join(x[1].split('_')).replace('.blf.',' ')) | 7 | 4 |
71,580,727 | 2022-3-23 | https://stackoverflow.com/questions/71580727/translating-async-generator-into-sync-one | Imagine we have an original API that returns a generator (it really is a mechanisms that brings pages/chunks of results from a server while the providing a simple generator to the user, and lets him iterate over these results one by one. For simplicity: # Original sync generator def get_results(): # fetch from server y... | For the reason that asyncio is contagious, it's hard to write elegant code to integrate asyncio code into the old codes. For the scenario above, the flowing code is a little better, but I don't think it's elegant enough. async def get_results_async(): # await fetch from server yield 1 yield 2 # await fetch next page yi... | 6 | 7 |
71,580,859 | 2022-3-23 | https://stackoverflow.com/questions/71580859/importerror-when-importing-psycopg2-on-m1 | Has anyone gotten this error when importing psycopg2 after successful installation? ImportError: dlopen(/Users/chrishicks/Desktop/test/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 0x0002): tried: '/Users/chrishicks/Desktop/test/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-da... | Using this line should fix it: pip3.9 install psycopg2-binary --force-reinstall --no-cache-dir | 10 | 35 |
71,516,140 | 2022-3-17 | https://stackoverflow.com/questions/71516140/fastapi-runs-api-calls-in-serial-instead-of-parallel-fashion | I have the following code: from fastapi import FastAPI, Request import time app = FastAPI() @app.get("/ping") async def ping(request: Request): print("Hello") time.sleep(5) print("bye") return {"ping": "pong!"} If I run my code on localhost—e.g., http://localhost:8501/ping—in different tabs of the same browser window,... | As per FastAPI's docs: When you declare an endpoint with normal def instead of async def, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server). and: If you are using a third party library that communicates with something (a database, an API, the fi... | 92 | 262 |
71,526,175 | 2022-3-18 | https://stackoverflow.com/questions/71526175/how-to-switch-vs-code-to-use-pylance-rather-than-jedi | I am trying to use Structural Pattern Matching (PEP634) from Python 3.10, but Jedi language server doesn't support the syntax. I've heard Pylance is better, but I can't find any way to switch VS Code to Pylance. I've downloaded the default Python extension, but only the Jedi language server is running. How can I make t... | I was using the open source version of VS Code which doesn't have all extensions. Switching to the proprietary version (available on the AUR) fixed my issue. | 9 | 9 |
71,512,035 | 2022-3-17 | https://stackoverflow.com/questions/71512035/how-should-i-specify-default-values-on-pydantic-fields-with-validate-always-to | My type checker moans at me when I use snippets like this one from the Pydantic docs: from datetime import datetime from pydantic import BaseModel, validator class DemoModel(BaseModel): ts: datetime = None # Expression of type "None" cannot be # assigned to declared type "datetime" @validator('ts', pre=True, always=Tru... | New answer Use a Field with a default_factory for your dynamic default value: from datetime import datetime from pydantic import BaseModel, Field class DemoModel(BaseModel): ts: datetime = Field(default_factory=datetime.now) Your type hints are correct, the linter is happy and DemoModel().ts is not None. From the Fiel... | 21 | 37 |
71,539,448 | 2022-3-19 | https://stackoverflow.com/questions/71539448/using-different-pydantic-models-depending-on-the-value-of-fields | I have 2 Pydantic models (var1 and var2). The input of the PostExample method can receive data either for the first model or the second. The use of Union helps in solving this issue, but during validation it throws errors for both the first and the second model. How to make it so that in case of an error in filling in ... | You could use Discriminated Unions (credits to @larsks for mentioning that in the comments). Setting a discriminated union, "validation is faster since it is only attempted against one model", as well as "only one explicit error is raised in case of failure". Working example is given below. Another approach would be to... | 19 | 20 |
71,542,183 | 2022-3-19 | https://stackoverflow.com/questions/71542183/websocket-getting-closed-immediately-after-connecting-to-fastapi-endpoint | I'm trying to connect a websocket aiohttp client to a fastapi websocket endpoint, but I can't send or recieve any data because it seems that the websocket gets closed immediately after connecting to the endpoint. server import uvicorn from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket('/ws') async d... | The connection is closed by either end (client or server), as shown from your code snippets. You would need to have a loop in both the server and the client for being able to await for messages, as well as send messages, continuously (have a look here and here). Additionally, as per FastAPI's documentation: When a Web... | 9 | 7 |
71,528,875 | 2022-3-18 | https://stackoverflow.com/questions/71528875/signal-handling-in-uvicorn-with-fastapi | I have an app using Uvicorn with FastAPI. I have also some connections open (e.g. to MongoDB). I want to gracefully close these connections once some signal occurs (SIGINT, SIGTERM and SIGKILL). My server.py file: import uvicorn import fastapi import signal import asyncio from source.gql import gql app = fastapi.FastAP... | FastAPI allows defining event handlers (functions) that need to be executed before the application starts up, or when the application is shutting down. Thus, you could use the shutdown event, as described here: @app.on_event("shutdown") def shutdown_event(): # close connections here Update Since startup and shutdown e... | 6 | 8 |
71,497,081 | 2022-3-16 | https://stackoverflow.com/questions/71497081/how-to-build-multiple-packages-from-a-single-python-module-using-pyproject-toml | I want to achieve a similar behavior as the library Dask does, it is possible to use pip to install dask, dask[dataframe], dask[array] and others. They do it by using the setup.py with a packages key like this. If I install only dask the dask[dataframe] is not installed and they warn you about this when executing the m... | Actually the Dask example does not install subpackages separately, it just installs the custom dependencies separately as explained in this link. In order to accomplish the same behavior using poetry you need to use this (as mentioned by user @sinoroc in this comment) The example pyproject.toml from the poetry extras p... | 5 | 5 |
71,549,500 | 2022-3-20 | https://stackoverflow.com/questions/71549500/how-to-create-an-abstract-cached-property-in-python | In order to create an abstract property in Python one can use the following code: from abc import ABC, abstractmethod class AbstractClassName(ABC): @cached_property @abstractmethod def property_name(self) -> str: pass class ClassName(AbstractClassName): @property def property_name(self) -> str: return 'XYZ' >>> o = Abs... | Here is a possible solution from abc import ABC, abstractmethod from functools import cached_property class AbstractClassName(ABC): @cached_property def property_name(self) -> str: return self._property_name() @abstractmethod def _property_name(self) -> str: ... class ClassName(AbstractClassName): def _property_name(se... | 8 | 1 |
71,563,696 | 2022-3-21 | https://stackoverflow.com/questions/71563696/pandas-to-gbq-typeerror-expected-bytes-got-a-int-object | I am using the pandas_gbq module to try and append a dataframe to a table in Google BigQuery. I keep getting this error: ArrowTypeError: Expected bytes, got a 'int' object. I can confirm the data types of the dataframe match the schema of the BQ table. I found this post regarding Parquet files not being able to have ... | Had this same issue - solved it simply with df = df.astype(str) and doing to_gbq on that instead. Caveat is that all your fields will now be strings... | 15 | 11 |
71,542,947 | 2022-3-19 | https://stackoverflow.com/questions/71542947/how-can-i-fix-task-was-destroyed-but-it-is-pending | I have a problem. So I have a task that runs every time when a user writes a chat message on my discord server - it's called on_message. So my bot has many things to do in this event, and I often get this kind of error: Task was destroyed but it is pending! task: <Task pending name='pycord: on_message' coro=<Client._ru... | The await expression blocks the containing coroutine until the awaited awaitable returns. This hinders the progress of the coroutine. But await is necessary in a coroutine to yield control back to the event loop so that other coroutines can progress. Too many awaits can be problematic, it just makes progress slow. I've... | 9 | 5 |
71,562,597 | 2022-3-21 | https://stackoverflow.com/questions/71562597/replace-image-in-word-docx-format | I'm attempting to replace an image in a Word 2019 .docx file using the following code in Python: from docxtpl import DocxTemplate tpl = DocxTemplate("C:\\temp\\replace_picture_tpl.docx") context = {} tpl.replace_pic('Sample.png','C:\\temp\\NewImage.png') tpl.render(context) tpl.save("C:\\temp\\TestOutput.docx") I get ... | So, this worked for me using docxtpl and a template I modified in MS Word: Right click the image in MS Word, Select "View Alt Text": Write "replace_me" as the Alt Text. Save and close. Then: from docxtpl import DocxTemplate tpl = DocxTemplate("sometemplate.docx") tpl.replace_pic("replace_me", "yourimage.png") Definit... | 5 | 1 |
71,525,132 | 2022-3-18 | https://stackoverflow.com/questions/71525132/how-to-write-a-custom-fastapi-middleware-class | I have read FastAPI's documentation about middlewares (specifically, the middleware tutorial, the CORS middleware section and the advanced middleware guide), but couldn't find a concrete example of how to write a middleware class which you can add using the add_middleware function (in contrast to a basic middleware fun... | As FastAPI is actually Starlette underneath, you could use BaseHTTPMiddleware that allows you to implement a middleware class (you may want to have a look at this post as well). Below are given two variants of the same approach on how to do that, where the add_middleware() function is used to add the middleware class. ... | 35 | 50 |
71,504,627 | 2022-3-16 | https://stackoverflow.com/questions/71504627/runtimewarning-coroutine-botbase-load-extension-was-never-awaited-after-upd | The discord bot I made a year ago and deployed to Heroku has worked until now. However, after changing some cogs and updating python to version 3.9.10, I get the following warning in the Heroku logs: app[worker.1]: /app/m_bot.py:120: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited app[worker.1]: cl... | Explanation As of discord.py version 2.0, Bot.load_extension is now a coroutine and has to be awaited. This is to allow Cog subclasses to override cog_unload with a coroutine. Code await must be used in front of client.load_extension, as shown: await client.load_extension("your_extension") In each of your cogs: Replac... | 9 | 17 |
71,512,301 | 2022-3-17 | https://stackoverflow.com/questions/71512301/error-could-not-build-wheels-for-spacy-which-is-required-to-install-pyproject | Hi Guys, I am trying to install spacy model == 2.3.5 but I am getting this error, please help me! | I had the similar error while executing pip install -r requirements.txt but for aiohttp module: socket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o aiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found #include "longintrepr.h" ^~~~~~~ 1 error generated. error: command '/data/data/com... | 5 | 4 |
71,570,607 | 2022-3-22 | https://stackoverflow.com/questions/71570607/sqlalchemy-models-vs-pydantic-models | I'm following this tutorial to adapt it to my needs, in this case, to perform a sql module where I need to record the data collected by a webhook from the gitlab issues. For the database module I'm using SQLAlchemy library and PostgreSQL as database engine. So, I would like to solve some doubts, I have regarding the us... | The tutorial you mentioned is about FastAPI. Pydantic by itself has nothing to do with SQL, SQLAlchemy or relational databases. It is FastAPI that is showing you a way to use a relational database. is the integration of pydantic strictly necessary [when using FastAPI]? Yes. Pydantic is a requirement according to the... | 31 | 48 |
71,517,365 | 2022-3-17 | https://stackoverflow.com/questions/71517365/pyproject-toml-wont-find-project-name-with-setuptools-python-m-build-format | What is the correct format for supplying a name to a Python package in a pyproject.toml? Here's the pyproject.toml file: [project] name = "foobar" version = "0.0.1" [build-system] requires = ["setuptools>=40.8.0", "wheel"] build-backend = "setuptools.build_meta" A build called using python -m build results in the foll... | Update At the time the question was asked, setuptools did not have support for writing its configuration in a pyproject.toml file (PEP 621). So it was not possible to answer the question. Now and since its version 61.0.0, setuptools has support for PEP 621: https://setuptools.pypa.io/en/latest/userguide/pyproject_conf... | 14 | 10 |
71,558,637 | 2022-3-21 | https://stackoverflow.com/questions/71558637/poetry-fails-with-retrieved-digest-for-package-not-in-poetry-lock-metadata | We're trying to merge and old branch in a project and when trying to build a docker image, poetry seems to fail for some reason that I don't understand. I'm not very familiar with poetry, as I've only used requirements.txt for dependencies up to now, so I'm fumbling a bit on what's going on. The error that I'm getting ... | When I've had this issue myself it has been fixed by recreating the lock file using a newer version of poetry. If you are able to view the .toml file I suggest deleting this lock file and then running poetry install to create a new lock file. | 22 | 10 |
71,577,892 | 2022-3-22 | https://stackoverflow.com/questions/71577892/how-change-the-syntax-in-elasticsearch-8-where-body-parameter-is-deprecated | After updating Python package elasticsearch from 7.6.0 to 8.1.0, I started to receive an error at this line of code: count = es.count(index=my_index, body={'query': query['query']} )["count"] receive following error message: DeprecationWarning: The 'body' parameter is deprecated and will be removed in a future versio... | According to the documentation, this is now to be done as follows: # ✅ New usage: es.search(query={...}) # ❌ Deprecated usage: es.search(body={"query": {...}}) So the queries are done directly in the same line of code without "body", substituting the api you need to use, in your case "count" for "search". You can try ... | 9 | 17 |
71,530,764 | 2022-3-18 | https://stackoverflow.com/questions/71530764/binance-order-timestamp-for-this-request-was-1000ms-ahead-of-the-servers-time | I am writing some Python code to create an order with the Binance API: from binance.client import Client client = Client(API_KEY, SECRET_KEY) client.create_order(symbol='BTCUSDT', recvWindow=59999, #The value can't be greater than 60K side='BUY', type='MARKET', quantity = 0.004) Unfortunately I get the following error... | Probably the PC's time is out of sync. You can do it using Windows -> Setting-> Time & Language -> Date & Time -> 'Sync Now'. Screenshot: | 14 | 34 |
71,557,674 | 2022-3-21 | https://stackoverflow.com/questions/71557674/when-importing-cartopy-importerror-dll-load-failed-while-importing-trace-the-s | I installed Christoph Gohlke's prebuilt wheel Cartopy‑0.20.2‑cp39‑cp39‑win_amd64.whl using pip in an active virtual environment. The environment is using Python 3.9.5. When trying to import Cartopy I get the error message below. This used to work before and now it no longer works and I can't figure out why. Does anyone... | As mentioned by cgohlke in the comments, installing the wheels of shapely and pyproj from his website solves the issue. If the libraries are already installed, use --force-reinstall to overwrite the existing installations. | 8 | 15 |
71,542,207 | 2022-3-19 | https://stackoverflow.com/questions/71542207/when-to-use-oauth-in-django-what-is-its-exact-role-on-django-login-framework | I am trying to be sure that I understand it correctly: Is OAuth a bridge for only third party authenticator those so common like Facebook, Google? And using it improves user experience in secure way but not adding extra secure layer to Django login framework? Or only Authorization Code grant type is like that? Can I ta... | What is OAuth? According to RFC 6749: The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party applic... | 6 | 5 |
71,560,036 | 2022-3-21 | https://stackoverflow.com/questions/71560036/how-to-preform-loc-with-one-condition-that-include-two-columns | I have df with two columns A and B both of them are columns with string values. Example: df_1 = pd.DataFrame(data={ "A":['a','b','c'], "B":['a x d','z y w','q m c'] #string values not a list }) print(df_1) #output A B 0 a a x d 1 b z y w 2 c q m c now what I'm trying to do is to preform loc in the df_1 to get all the ... | There is no vectorial method, to map in using two columns. You need to loop here: mask = [a in b for a,b in zip(df_1['A'], df_1['B'])] df_1.loc[mask] Output: A B 0 a a x d 2 c q m c comparison of speed (3000 rows) # operator.contains 518 µs ± 4.61 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # list comp... | 13 | 21 |
71,531,344 | 2022-3-18 | https://stackoverflow.com/questions/71531344/how-to-spawn-a-docker-container-in-a-remote-machine | Is it possible, using the docker SDK for Python, to launch a container in a remote machine? import docker client = docker.from_env() client.containers.run("bfirsh/reticulate-splines", detach=True) # I'd like to run this container ^^^ in a machine that I have ssh access to. Going through the documentation it seems like... | It's possible, simply do this: client = docker.DockerClient(base_url=your_remote_docker_url) Here's the document I found related to this: https://docker-py.readthedocs.io/en/stable/client.html#client-reference If you only have SSH access to it, there is an use_ssh_client option | 5 | 4 |
71,520,075 | 2022-3-17 | https://stackoverflow.com/questions/71520075/zip-longest-for-the-left-list-always | I know about the zip function (which will zip according to the shortest list) and zip_longest (which will zip according to the longest list), but how would I zip according to the first list, regardless of whether it's the longest or not? For example: Input: ['a', 'b', 'c'], [1, 2] Output: [('a', 1), ('b', 2), ('c', Non... | Solutions Chaining the repeated fillvalue behind the iterables other than the first: from itertools import chain, repeat def zip_first(first, *rest, fillvalue=None): return zip(first, *map(chain, rest, repeat(repeat(fillvalue)))) Or using zip_longest and trim it with a compress and zip trick: def zip_first(first, *res... | 34 | 37 |
71,493,439 | 2022-3-16 | https://stackoverflow.com/questions/71493439/unable-to-import-module-lambda-function-no-module-named-psycopg2-psycopg-aw | I have installed the psycopg2 with this command in my package folder : pip install --target ./package psycopg2 # Or pip install -t ./package psycopg2 now psycopg2 module is in my package and I have created the zip and upload it in AWS lambda. In my local sprint is working fine but on AWS lambda it was not working. It ... | add this lib pip install aws-psycopg2 | 7 | 2 |
71,491,982 | 2022-3-16 | https://stackoverflow.com/questions/71491982/how-to-segment-and-get-the-time-between-two-dates | I have the following table: id | number_of _trip | start_date | end_date | seconds 1 637hui 2022-03-10 01:20:00 2022-03-10 01:32:00 720 2 384nfj 2022-03-10 02:18:00 2022-03-10 02:42:00 1440 3 102fiu 2022-03-10 02:10:00 2022-03-10 02:23:00 780 4 948pvc 2022-03-10 02:40:00 2022-03-10 03:20:00 2400 5 473mds 2022-03-10 02:... | This can be done in plain sql (apart from time_bucket function), in a nested sql query: select interval_start, sum(seconds_before_trip_ended - seconds_before_trip_started) as seconds from ( select interval_start, greatest(0, extract(epoch from start_date - interval_start)::int) as seconds_before_trip_started, least(360... | 6 | 1 |
71,527,595 | 2022-3-18 | https://stackoverflow.com/questions/71527595/efficiently-count-all-the-combinations-of-numbers-having-a-sum-close-to-0 | I have following pandas dataframe df column1 column2 list_numbers sublist_column x y [10,-6,1,-4] a b [1,3,7,-2] p q [6,2,-3,-3.2] the sublist_column will contain the numbers from the column "list_numbers" that adds up to 0 (0.5 is a tolerance) I have written following code. def return_list(original_lst,target_sum,tol... | Step 1: using Numba Based on the comments, it appear that memo_func is the main bottleneck. You can use Numba to speed up its execution. Numba compile the Python code to a native one thanks to a just-in-time (JIT) compiler. The JIT is able to perform tail-call optimizations and native function calls are significantly f... | 7 | 17 |
71,538,933 | 2022-3-19 | https://stackoverflow.com/questions/71538933/preparing-metadata-pyproject-toml-error-when-installing-numpy-on-vs-code | So I was trying to install numpy 1.20.3, on VS Code, when it says: Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [239 lines of output] setup.py:66: RuntimeWarning: NumPy 1.20.3 may not yet support Pyt... | It says it in the error message. RuntimeWarning: NumPy 1.20.3 may not yet support Python 3.10. Two quick trys: Without looking through each packages, try removing numpy from requirements, and run "python -m pip install -r requirements.txt" again. Then in command line, try typing this to see if it installed because t... | 5 | 1 |
71,575,112 | 2022-3-22 | https://stackoverflow.com/questions/71575112/annotate-a-function-argument-as-being-a-specific-module | I have a pytest fixture that imports a specific module. This is needed as importing the module is very expensive, so we don't want to do it on import-time (i.e. during pytest test collection). This results in code like this: @pytest.fixture def my_module_fix(): import my_module yield my_module def test_something(my_mod... | If I get your question, you have two (or three) separate goals Deferred import of slowmodule Autocomplete to continue to work as if it was a standard import (Potentially?) typing (e.g. mypy?) to continue to work I can think of at least five different approaches, though I'll only briefly mention the last because it's ... | 5 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.