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 |
|---|---|---|---|---|---|---|
73,744,658 | 2022-9-16 | https://stackoverflow.com/questions/73744658/resource-punkt-not-found-please-use-the-nltk-downloader-to-obtain-the-resource | I have NLTK installed and it is giving me an error: Resource punkt not found. Please use the NLTK Downloader to obtain the resource: import nltk nltk.download('punkt') For more information see: https://www.nltk.org/data.html Attempted to load tokenizers/punkt/PY3/english.pickle Searched in: - '/Users/divyanshundley/nlt... | Adding these code will resolve your issue: nltk.download('punkt') nltk.download('wordnet') nltk.download('omw-1.4') | 13 | 11 |
73,721,736 | 2022-9-14 | https://stackoverflow.com/questions/73721736/what-is-the-proper-way-to-make-downstream-http-requests-inside-of-uvicorn-fastap | I have an API endpoint (FastAPI / Uvicorn). Among other things, it makes a request to yet another API for information. When I load my API with multiple concurrent requests, I begin to receive the following error: h11._util.LocalProtocolError: can't handle event type ConnectionClosed when role=SERVER and state=SEND_RESP... | Instead of using requests, you could use httpx, which offers an async API as well (httpx is also suggested in FastAPI's documentation when performing async tests, as well as FastAPI/Starlette recently replaced the HTTP client on TestClient from requests to httpx). The below example is based on the one given in httpx do... | 9 | 17 |
73,759,718 | 2022-9-18 | https://stackoverflow.com/questions/73759718/how-to-post-json-data-from-javascript-frontend-to-fastapi-backend | I am trying to pass a value called 'ethAddress' from an input form on the client to FastAPI so that I can use it in a function to generate a matplotlib chart. I am using fetch to POST the inputted text in Charts.tsx file: fetch("http://localhost:8000/ethAddress", { method: "POST", headers: { "Content-Type": "applicati... | The way you defined ethAddress in your endpoint is expected as a query parameter; hence, the 422 Unprocessable Entity error. As per the documentation: When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters. For the parameter to be ... | 5 | 9 |
73,776,179 | 2022-9-19 | https://stackoverflow.com/questions/73776179/element-wise-aggregation-of-a-column-of-type-listf64-in-polars | I want to apply aggregation functions like sum, mean, etc to a column of type List[f64] after a group_by such that I get a List[64] entry back. Say I have: import polars as pl df = pl.DataFrame( { "Case": ["case1", "case1"], "List": [[1, 2, 3], [4, 5, 6]], } ) print(df) shape: (2, 2) ┌───────┬────────────┐ │ Case ┆ L... | Note that the length of each of the lists are 256, so indexing each of them is not a good solution. If you are sure of the length of your lists ahead of time, then we can avoid the typical explode/index/group_by solution as follows: list_size = 3 ( df.group_by("Case") .agg( pl.concat_list( pl.col("List") .list.slice(... | 4 | 4 |
73,716,862 | 2022-9-14 | https://stackoverflow.com/questions/73716862/converting-string-to-datetime-polars | I have a Polars dataframe with a column of type str with the date and time df = pl.from_repr(""" ┌─────────────────────────┐ │ EventTime │ │ --- │ │ str │ ╞═════════════════════════╡ │ 2020-03-02T13:10:42.550 │ └─────────────────────────┘ """) I want to convert this column to the polars.Datetime type. After reading th... | You were close. You forgot the seconds component of your format specifier: ( df .with_columns( pl.col('EventTime') .str.to_datetime( format="%Y-%m-%dT%H:%M:%S%.f", strict=False) .alias('parsed EventTime') ) ) shape: (1, 2) ┌─────────────────────────┬─────────────────────────┐ │ EventTime ┆ parsed EventTime │ │ --- ┆ -... | 4 | 8 |
73,733,368 | 2022-9-15 | https://stackoverflow.com/questions/73733368/how-to-set-a-minimal-logging-level-with-loguru | I would like to use a different logging level in development and production. To do so, I need early in my program to set the minimal level for logs to be triggered. The default is to output all severities: from loguru import logger as log log.debug("a debug log") log.error("an error log") # output # 2022-09-15 16:51:23... | Like so: import sys from loguru import logger as log log.remove() #remove the old handler. Else, the old one will work along with the new one you've added below' log.add(sys.stderr, level="INFO") log.debug("debug message") log.info("info message") log.warning("warning message") log.error("error message") You can use s... | 9 | 19 |
73,763,352 | 2022-9-18 | https://stackoverflow.com/questions/73763352/how-do-i-type-hint-a-variable-whose-value-is-itself-a-type-hint | I have a function one of whose arguments is expected to be a type hint: something like typing.List, or typing.List[int], or even just int. Anything you would reasonably expect to see as a type annotation to an ordinary field. What's the correct type hint to put on this argument? (The context for this is that I'm writin... | Answer for Python 3.10: Almost complete but less readable answer: type | types.GenericAlias | types.UnionType | typing._BaseGenericAlias | typing._SpecialForm Here are the possibilities of all types of annotations I can think of: Type object itself, such as int, list, etc. Corresponds to type. Type hinting generics i... | 6 | 8 |
73,753,000 | 2022-9-17 | https://stackoverflow.com/questions/73753000/how-to-address-current-state-of-list-comprehension-in-its-if-condition | I would like to turn the loop over the items in L in following code: L = [1,2,5,2,1,1,3,4] L_unique = [] for item in L: if item not in L_unique: L_unique.append(item) to a list comprehension like: L_unique = [ item for item in L if item not in ???self??? ] Is this possible in Python? And if it is possible, how can it... | It's possible. Here's a hack that does it, but I wouldn't use this in practice as it's nasty and depends on implementation details that might change and I believe it's not thread-safe, either. Just to demonstrate that it's possible. You're mostly right with your "somewhere must exist an object storing the current state... | 4 | 12 |
73,778,532 | 2022-9-19 | https://stackoverflow.com/questions/73778532/aws-glue-job-an-error-occurred-while-calling-getcatalogsource-none-get | I was using Password/Username in my aws glue conenctions and now I switched to Secret Manager. Now I get this error when I run my etl job : An error occurred while calling o89.getCatalogSource. None.get Even tho the connections and crawlers works : The Connection Image. (I added the connection to the job details) ... | Update: It appears that this issue has fixed by AWS. I did not see any official announcement on this, however I noticed a few months ago that my Python Glue jobs started running successfully after updating the Glue connections to use Secrets Manager. I would try this again and see if it works for you now. Old Answer: I... | 4 | 4 |
73,750,930 | 2022-9-16 | https://stackoverflow.com/questions/73750930/how-can-i-ensure-that-my-quilt-data-package-displays-relevant-information-by-def | When viewing a Quilt data package in the catalog view, how do I ensure that the relevant information and data to my users bubbles up from N-depth of folders/files to the data package landing view? | [Disclaimer: I originally wrote this answer when I was working at Quilt Data] Create a file called quilt_summarize.json [Reference] which is a configuration file that renders one or more data-package elements in both Bucket view and Packages view. The contents of quilt_summarize.json are a JSON array of files that you ... | 5 | 6 |
73,718,577 | 2022-9-14 | https://stackoverflow.com/questions/73718577/updating-multiple-pydantic-fields-that-are-validated-together | How do you update multiple properties on a pydantic model that are validated together and dependent upon each other? Here is a contrived but simple example: from pydantic import BaseModel, root_validator class Example(BaseModel): a: int b: int @root_validator def test(cls, values): if values['a'] != values['b']: raise ... | I found a couple solutions that works well for my use case. manually triggering the validation and then updating the __dict__ of the pydantic instance directly if it passes -- see update method a context manager that delays validation until after the context exits -- see delay_validation method from pydantic import B... | 4 | 4 |
73,724,304 | 2022-9-15 | https://stackoverflow.com/questions/73724304/how-to-display-a-bytes-type-image-in-html-jinja2-template-using-fastapi | I have a FastAPI app that gets an image from an API. This image is stored in a variable with type: bytes. I want to display the image in HTML/Jinja2 template (without having to download it). I followed many tutorials but couldn't find the solution. Here is what I came up with so far: @app.get("/{id}") async def root(re... | On server side—as shown in the last section of this answer—you should return only the base64-encoded string in the context of the TemplateResponse (without using the <img> tag, as shown in your question): # ... base64_encoded_image = base64.b64encode(image_bytes).decode("utf-8") return templates.TemplateResponse("index... | 4 | 4 |
73,745,607 | 2022-9-16 | https://stackoverflow.com/questions/73745607/how-to-pass-arguments-to-huggingface-tokenclassificationpipelines-tokenizer | I've finetuned a Huggingface BERT model for Named Entity Recognition. Everything is working as it should. Now I've setup a pipeline for token classification in order to predict entities out the text I provide. Even this is working fine. I know that BERT models are supposed to be fed with sentences less than 512 tokens ... | I took a closer look at https://github.com/huggingface/transformers/blob/v4.24.0/src/transformers/pipelines/token_classification.py#L86. It seems you can override preprocess() to disable truncation and add padding to longest. from transformers import TokenClassificationPipeline class MyTokenClassificationPipeline(Token... | 5 | 2 |
73,749,897 | 2022-9-16 | https://stackoverflow.com/questions/73749897/imports-are-incorrectly-sorted-and-or-formatted-vs-code-python | In a few of my beginner projects this strange red line underscoring one or more of my imports keeps appearing almost randomly and I can't figure out why. As the module is working perfectly fine it shouldn't have something to do regarding which Folder I open VS Code in as it can get resolved, so sys.path should also hav... | Edit: I realized that recently the isort extension from Microsoft was automatically added to my extensions and this has caused the annoying error to start showing. It may be that the extension is conflicting somehow with the isort library installed in your venv. The extension isn't needed, so I've just disabled it and ... | 8 | 10 |
73,785,052 | 2022-9-20 | https://stackoverflow.com/questions/73785052/working-with-picture-in-alternatecontent-tag | I need to move an element from one document to another by using python-docx. The element is AlternateContent which represents shapes and figures in Office Word, the issue here is that one of the elements contains an image like this: <AlternateContent> <Choice Requires="wpc"> <drawing> <inline distT="0" distB="0" distL=... | Because of the fact that this functionality is not fully supported through python-docx API and processing images is kind of complicated -because of the multiple parts that must be handled (ImagePart, Relationship, rId)- the work had to be done at a low level by going into lxml, in these steps: Save the images into the... | 4 | 1 |
73,758,140 | 2022-9-17 | https://stackoverflow.com/questions/73758140/python-macos-loop-files-get-file-info | I am trying to loop through all mp3 files in my directory in MacOS Monterrey and for every iteration get the file's more info attributes, like Title, Duration, Authors etc. I found a post saying use xattr, but when i create a variable with xattr it doesn't show any properties or attributes of the files. This is in Pyth... | xattr is not reading mp3 metadata or tags, it is for reading metadata that is stored for the particular file to the filesystem itself, not the metadata/tags thats stored inside the file. In order to get the data you need, you need to read the mp3 file itself with some library that supports reading ID3 of the file, for ... | 4 | 5 |
73,793,363 | 2022-9-20 | https://stackoverflow.com/questions/73793363/how-can-i-check-if-a-protobuf-message-has-a-field-defined | I'm working with a protobuf message that has some of the fields marked for deprecation with [deprecated = true]. To my understanding the field can still be used by some part of the code (maybe with a warning). I want to make sure that my code is still supporting this field with the possibility of handling the case when... | Deprecated fields have no impact on code, as per the docs. In your case, it looks like you are trying to evaluate if the class Message2 has a field defined or not? Before going forward, you need add optional as an option in your proto to allow for HasField() to work: my_message.proto syntax = "proto3"; message Message1... | 6 | 3 |
73,721,599 | 2022-9-14 | https://stackoverflow.com/questions/73721599/in-the-conda-environment-yml-file-how-do-i-append-to-existing-variables-without | This is a follow up question for this answer. For a conda environment specification file environment.yml, if the variable that I am defining is PATH, for example, how can I prepend or append to it instead of just overwriting it? Is the following correct? name: foo channels: - defaults dependencies: - python variables: ... | It dependes on whether you are using windows or linux. A look at the source code of the environment init code reveals that conda itself simply executes bash (linux) or cmd.exe (win) calls: linux: yield from (f"export {envvar}='{value}'" for envvar, value in sorted(env_vars.items())) windows: yield from (f'@SET "{envva... | 5 | 2 |
73,713,072 | 2022-9-14 | https://stackoverflow.com/questions/73713072/solving-sylvester-equations-in-pytorch | I'm trying to solve a Sylvester matrix equation of the form AX + XB = C From what I've seen, these equations are usually solved with the Bartels-Stewart algorithm taking successive Schur decompositions. I'm aware scipy.linalg already has a solve_sylvester function, but I'm integrating the solution to the Sylvester eq... | Initially I wrote a solution that would give complex X based on Bartels-Stewart algorithm for the m=n case. I had some problems because the eigenvector matrix is not accurate enough. Also the real part gives the real solution, and the imaginary part must be a solution for AX - XB = 0 import torch def sylvester(A, B, C,... | 4 | 4 |
73,778,158 | 2022-9-19 | https://stackoverflow.com/questions/73778158/how-can-i-type-hint-the-init-params-are-the-same-as-fields-in-a-dataclass | Let us say I have a custom use case, and I need to dynamically create or define the __init__ method for a dataclass. For exampel, say I will need to decorate it like @dataclass(init=False) and then modify __init__() method to taking keyword arguments, like **kwargs. However, in the kwargs object, I only check for prese... | What you are describing is impossible in theory and unlikely to be viable in practice. TL;DR Type checkers don't run your code, they just read it. A dynamic type annotation is a contradiction in terms. Theory As I am sure you know, the term static type checker is not coincidental. A static type checker is not executing... | 4 | 6 |
73,711,633 | 2022-9-14 | https://stackoverflow.com/questions/73711633/how-to-calculate-and-store-results-based-upon-the-matching-rows-of-two-different | I have three DataFrames which I am importing from Excel Files. The dataframes are given below as HTML Tables, Season Wise Record (this contains a Column Reward which is initialized with 0 initially) <table><tbody><tr><th>Unnamed: 0</th><th>Name</th><th>Team</th><th>Position</th><th>Games Played</th><th>PassingComplet... | I hope I understood correctly your intentions. To avoid double for loops, you need to use groupby() method and then apply the desired function to every row of the group; finally the aggregation function (sum()) should be applied to the group. Although you can use the Name as a key for grouping, I recommend to add Playe... | 9 | 1 |
73,787,469 | 2022-9-20 | https://stackoverflow.com/questions/73787469/errno-13-permission-denied-error-when-trying-to-load-huggingface-dataset | I'm trying to do a very simple thing: to load a dataset from the Huggingface library (see example code here) on my Mac: from datasets import load_dataset raw_datasets = load_dataset("glue", "mrpc") I'm getting the following error: PermissionError: [Errno 13] Permission denied: '/Users/username/.cache/huggingface/datas... | OK, I managed to solve it by manually changing the permissions of the right folders on my Mac: I navigated to the /Users/username/.cache/huggingface/datasets/downloads folder in the Finder (you can see hidden files and folders such as ".cache" by pressing " command shift + . ") Then I went to the info window for this ... | 5 | 3 |
73,791,594 | 2022-9-20 | https://stackoverflow.com/questions/73791594/how-to-vectorize-a-torch-function | When using numpy I can use np.vectorize to vectorize a function that contains if statements in order for the function to accept array arguments. How can I do the same with torch in order for a function to accept tensor arguments? For example, the final print statement in the code below will fail. How can I make this wo... | You can use .apply_() for CPU tensors. For CUDA ones, the task is problematic: if statements aren't easy to SIMDify. You may apply the same workaround for functorch.vmap as video drivers used to do for shaders: evaluate both branches of the condition and stick to arithmetics. Otherwise, just use a for loop: that's what... | 4 | 6 |
73,782,876 | 2022-9-20 | https://stackoverflow.com/questions/73782876/debugging-a-streamlit-application-in-pycharm-on-windows | I'm trying to setup a way to debug a Streamlit script in PyCharm. I'm on a Win10/64bit machine, working within an virtual environment created with conda. Running the code in the default way with streamlit run main.py works as expected. I have already read several forum posts and most importantly this related question o... | Stumbled across the (rather simple) answer by accident: Simply use the "correct" module name, which in my case was streamlit instead of streamlit.cli. So for debugging I now have the following configuration: Module Name (instead of "Script path"): streamlit Parameter: run main.py Interpreter options: not set Working d... | 8 | 16 |
73,790,207 | 2022-9-20 | https://stackoverflow.com/questions/73790207/how-to-override-the-update-action-in-django-rest-framework-modelviewset | These are the demo models class Author(models.Model): name = models.CharField(max_lenght=5) class Post(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_lenght=50) body = models.TextField() And the respective views are class AuthorViewSet(viewsets.ModelViewSet): q... | I figured out some less code fix for my issue. class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostStatSerializer def update(self, request, *args, **kwargs): super().update(request, *args, **kwargs) instance = self.get_object() return Response(AuthorSerializer(instance.author)... | 5 | 2 |
73,793,168 | 2022-9-20 | https://stackoverflow.com/questions/73793168/dataframe-column-stores-lists-of-dictionaries-as-strings-parse-it-and-build-a-n | I have a huge dataframe (2 million rows) in which a certain column has a string representations of a list of dictionaries (it is the school history of several people). So, what I'm trying to do is parsing this data to a new dataframe (because the relation is going to be 1 person to many schools). However, my first opti... | This does the trick using your sample data (thanks for the performance tip in comments): list_df = df_dict.school_history.map(ast.literal_eval) exploded = list_df[list_df.str.len() > 0].explode() final = pd.DataFrame(list(exploded), index=exploded.index) This produces the following: In [54]: final Out[54]: name subjec... | 4 | 3 |
73,790,198 | 2022-9-20 | https://stackoverflow.com/questions/73790198/how-to-prevent-inpainting-blocks-and-improve-coloring | I wanted to Remove all the texts USING INPAINTING from this IMAGE. I had been trying various methods, and eventually found that I can get the results through OCR and then using thresholding MASK THE IMAGE. processedImage = preprocess(partOFimg) mask = np.ones(img.shape[:2], dtype="uint8") * 255 for c in cnts: cv2.drawC... | Python/OpenCV inpaint methods, generally, are not appropriate to your type of image. They work best on thin (scratch-like) regions, not large blocks. You really need an exemplar type method such as https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/criminisi_tip2004.pdf. But OpenCV does not have that. ... | 4 | 4 |
73,791,116 | 2022-9-20 | https://stackoverflow.com/questions/73791116/sum-every-n-elements-from-numpy-array | For example, given an array arr = np.array([1,2,3,2,3,7,2,3,4]) there are 9 elements. I want to get sum every 3 elements: [6, 12, 9] Is there any numpy api I can use? | If your arr can be divided into groups of 3, i.e. has length 3*k, then: arr.reshape(-1,3).sum(axis=-1) # array([ 6, 12, 9]) In the general case, bincounts: np.bincount(np.arange(len(arr))//3, arr) # array([ 6., 12., 9.]) | 6 | 6 |
73,766,401 | 2022-9-18 | https://stackoverflow.com/questions/73766401/why-file-write-is-appending-in-r-mode-in-python | Assume I have a file content.txt, with the content Ex nihilo nihil fit. I am willing to replace it with Ex nihilo nihil est. The code is: with open("content.txt", "r+") as f: content = f.read() content = content.replace("fit", "est") print(content) f.write(content) f.close() After that, the content of the file becomes... | r+ opens the file and puts a pointer at the first byte. When you use f.read() the pointer moves to the end of the file, so when you try to write it starts at the end of the file. To move back to the start (so you can override), use f.seek(0): with open("text.txt", "r+") as f: content = f.read() content = content.replac... | 4 | 3 |
73,785,952 | 2022-9-20 | https://stackoverflow.com/questions/73785952/pandas-join-two-dataframes-according-to-range-and-date | I have two dataframes like this: DATE MAX_AMOUNT MIN_AMOUNT MAX_DAY MIN_DAY RATE 01/09/2022 20 15 10 5 0.01 01/09/2022 25 20 15 10 0.02 03/09/2022 30 10 5 3 0.03 03/09/2022 40 30 20 5 0.04 04/09/2022 10 5 10 1 0.05 ID DATE AMOUNT DAY 1 01/09/2022 18 7 2 01/09/2022 22 11 3 01/09/2022 30 20 4 03/09/2022 35 10 5 04/09/202... | Use merge first with filter columns by Series.between and then use Series.map for RATE column with first matched ID - added DataFrame.drop_duplicates: df = df2.merge(df1, on='DATE') df = (df[df['AMOUNT'].between(df['MIN_AMOUNT'], df['MAX_AMOUNT']) & df['DAY'].between(df['MIN_DAY'], df['MAX_DAY'])]) df2['RATE'] = df2['I... | 4 | 4 |
73,739,552 | 2022-9-16 | https://stackoverflow.com/questions/73739552/select-columns-from-a-highly-nested-data | For the dataframe below, which was generated from an avro file, I'm trying to get the column names as a list or other format so that I can use it in a select statement. node1 and node2 have the same elements. For example I understand that we could do df.select(col('data.node1.name')), but I'm not sure how to select al... | The following way, you will not need to hardcode all the struct fields. But you will need to provide a list of those columns/fields which have the type of array of struct. You have 3 of such fields, we will add one more column, so in total it will be 4. First of all, the dataframe, similar to yours: from pyspark.sql im... | 6 | 1 |
73,779,649 | 2022-9-19 | https://stackoverflow.com/questions/73779649/pandas-dataframe-reshaping-columns-using-start-and-end-pairs | I have been trying to figure out a way to transform this dataframe. It contains only two columns; one is timeseries data and the other is event markers. Here is an example of the initial dataframe: df1 = pd.DataFrame({'Time': ['1:42 AM','2:30 AM','3:29 AM','4:19 AM','4:37 AM','4:59 AM','5:25 AM','5:33 AM','6:48 AM'], '... | Try: df1["tmp"] = df1["Event"].eq("Start").cumsum() df1 = df1.pivot(index="tmp", columns="Event", values="Time").fillna("") df1.columns.name, df1.index.name = None, None print(df1[["Start", "End"]]) Prints: Start End 0 1:42 AM 1 2:30 AM 3:29 AM 2 4:19 AM 4:37 AM 3 4:59 AM 4 5:25 AM 5:33 AM 5 6:48 AM | 4 | 5 |
73,775,424 | 2022-9-19 | https://stackoverflow.com/questions/73775424/python-http-server-how-to-serve-html-from-directory-above-cwd | I've got a question that I could really use some guidance with. I am simply trying to serve HTML from a directory that is not the same directory as the server itself. Ideally, I'd like to move one level above the server's directory, and serve a file located there. When I try that, I get a 404. class Server(SimpleHTTPRe... | This is a security feature as you mentioned. You wouldn't want users to be able to see all files of the server, would you? Starting with Python 3.7, the constructor of SimpleHTTPRequestHandler has a directory parameter (see docs: https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler). ... | 5 | 4 |
73,745,853 | 2022-9-16 | https://stackoverflow.com/questions/73745853/celery-send-task-method | I have my API, and some endpoints need to forward requests to Celery. Idea is to have specific API service that basically only instantiates Celery client and uses send_task() method, and seperate service(workers) that consume tasks. Code for task definitions should be located in that worker service. Basicaly seperating... | Your API side should hold the router. I guess it's not an issue because it is only a map of task -> queue (aka send task1 to queue1). In other words, your celery_client should have task_routes like: task_routes = { 'mytasks.some_task': 'queue_1', 'mytasks.some_other_task': 'queue_2', } | 4 | 3 |
73,748,939 | 2022-9-16 | https://stackoverflow.com/questions/73748939/this-tensorflow-binary-is-optimized-with-oneapi-deep-neural-network-library-one | I have the following code: import tensorflow as tf print("Hello") And the output is: This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the ap... | The message is just telling you that certain optimizations are on for you by default and if you want even more optimizations you can recompile TF to get even more performant optimizations. By default they compile using AVX2 which isn’t the fastest AVX, but it is the most compatible. If you don’t need to enable those (w... | 6 | 7 |
73,772,930 | 2022-9-19 | https://stackoverflow.com/questions/73772930/pip-failing-to-install-psycopg2-binary-on-ubuntu-22-04-with-python-3-10 | seeing this on Ubuntu 22.04 which has python 3.10 pip3 install psycopg2-binary==2.8.5 Defaulting to user installation because normal site-packages is not writeable Collecting psycopg2-binary==2.8.5 Using cached psycopg2-binary-2.8.5.tar.gz (381 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-e... | This is a known issue. Use the binary version instead: pip install psycopg2-binary EDIT: You dont have 'pg_config' which is part of libpq-dev on Ubuntu. Install it with sudo apt-get install libpq-dev and try abgain. | 5 | 14 |
73,743,988 | 2022-9-16 | https://stackoverflow.com/questions/73743988/stratified-sampling-with-priors-in-python | Context The common scenario of applying stratified sampling is about choosing a random sample that roughly maintains the distribution of the selected variable(s) so that it is representative. Goal: The goal is to create a function to perfrom stratified sampling but with some provided proportions of the considered varia... | From your question it is unclear if you need it to be a probabilistic function. That is, that the expectation of the proportions converge to the prior, or do you wish it to conform to the prior no matter what? If you want it to conform to the prior then I see 2 major issues: The randomness of the sampling could potent... | 4 | 1 |
73,739,158 | 2022-9-16 | https://stackoverflow.com/questions/73739158/nodejs-convert-to-byte-array-code-return-different-results-compare-to-python | I got the following Javascript code and I need to convert it to Python(I'm not an expert in hashing so sorry for my knowledge on this subject) function generateAuthHeader(dataToSign) { let apiSecretHash = new Buffer("Rbju7azu87qCTvZRWbtGqg==", 'base64'); let apiSecret = apiSecretHash.toString('ascii'); var hash = Crypt... | It took me 2 days to look it up and ask for people in python discord and I finally got an answer. Let me summarize the problems: API secret hash from both return differents hash of the byte array javascript Javascript apiSecret = "E8nm,ns:\u0002NvQY;F*" Python api_secret_hash = b'E\xb8\xee\xed\xac\xee\xf3\xba\x82N\x... | 6 | 5 |
73,765,587 | 2022-9-18 | https://stackoverflow.com/questions/73765587/how-to-get-a-warning-about-a-list-being-a-mutable-default-argument | I accidentally used a mutable default argument without knowing it. Is there a linter or tool that can spot this and warn me? | flake8-bugbear, Pylint, PyCharm, and Pyright can detect this: Bugbear has B006 (Do not use mutable data structures for argument defaults). Do not use mutable data structures for argument defaults. They are created during function definition time. All calls to the function reuse this one instance of that data structur... | 8 | 8 |
73,722,570 | 2022-9-14 | https://stackoverflow.com/questions/73722570/unable-to-write-files-in-a-gcp-bucket-using-gcsfuse | I have mounted a storage bucket on a VM using the command: gcsfuse my-bucket /path/to/mount After this I'm able to read files from the bucket in Python using Pandas, but I'm not able to write files nor create new folders. I have tried with Python and from the terminal using sudo but get the same error. I have also tri... | I ran into the same thing a while ago, which was really confusing. You have to set the correct access scope for the virtual machine so that anyone using the VM is able to call the storage API. The documentation shows that the default access scope for storage on a VM is read-only: When you create a new Compute Engine i... | 6 | 3 |
73,762,452 | 2022-9-18 | https://stackoverflow.com/questions/73762452/what-is-the-most-efficient-way-to-read-and-augment-copy-samples-and-change-some | Currently, I have managed to solve this but it is slower than what I need. It takes approximately: 1 hour for 500k samples, the entire dataset is ~100M samples, which requires ~200hours for 100M samples. Hardware/Software specs: RAM 8GB, Windows 11 64bit, Python 3.8.8 The problem: I have a dataset in .csv (~13GB) where... | Pandas efficiency comes in to play when you need to manipulate columns of data, and to do that Pandas reads the input row-by-row building up a series of data for each column; that's a lot of extra computation your problem doesn't benefit from, and in fact just slows your solution down. You actually need to manipulate r... | 5 | 3 |
73,724,454 | 2022-9-15 | https://stackoverflow.com/questions/73724454/plot-density-function-on-sphere-surface-using-plotly-python | I'm interested in plotting a real-valued function f(x,y,z)=a, where (x,y,z) is a 3D point on the sphere and a is a real number. I calculate the Cartesian coordinates of the points of the sphere as follows, but I have no clue on how to visualize the value of f on each of those points. import plotly.graph_objects as go i... | Here's an answer that's far from perfect, but hopefully that's enough for you to build on. For the sphere itself, I don't know of any "shortcut" to do something like that in plotly, so my approach is simply to manually create a sphere mesh. Generating the vertices is simple, for example like you did - the slightly more... | 4 | 5 |
73,763,827 | 2022-9-18 | https://stackoverflow.com/questions/73763827/python-equality-statement-of-the-form-a-b-in-c-d-e | I just came across some python code with the following statement: if a==b in [c,d,e]: ... It turns out that: >>> 9==9 in [1,2,3] False >>> 9==9 in [1,2,3,9] True >>> (9==9) in [1,2,3,9] True >>> 9==(9 in [1,2,3,9]) False >>> True in [1,2,3,9] True >>> True in [] False >>> False in [] False >>> False in [1,2,3] False ... | Am I right in assuming that a==b in [c,d,e] is equivalent to (a==b) in [c,d,e] No. Since both == and in are comparison operators, the expression a == b in [c, d, e] is equivalent to (a == b) and (b in [c, d, e]) since all comparison operators have the same precedence but can be chained. and therefore only really m... | 5 | 3 |
73,761,571 | 2022-9-18 | https://stackoverflow.com/questions/73761571/row-wise-cumulative-mean-across-grouped-columns-using-pandas | I would like to create multiple columns which show the row-wise cumulative mean for grouped columns. Here is some sample data: import pandas as pd data = [[1, 4, 6, 10, 15, 40, 90, 100], [2, 5, 3, 11, 25, 50, 90, 120], [3, 7, 9, 14, 35, 55, 100, 120]] df = pd.DataFrame(data, columns=['a1', 'a2', 'a3', 'a4', 'b1', 'b2',... | expanding.mean for c in ('a', 'b'): m = df.filter(like=c).expanding(axis=1).mean().iloc[:, 1:] df[m.columns.str.replace(r'(\d+)$', r'1_\1', regex=True)] = m Result a1 a2 a3 a4 b1 b2 b3 b4 a1_2 a1_3 a1_4 b1_2 b1_3 b1_4 0 1 4 6 10 15 40 90 100 2.5 3.666667 5.25 27.5 48.333333 61.25 1 2 5 3 11 25 50 90 120 3.5 3.333333 ... | 5 | 3 |
73,749,995 | 2022-9-16 | https://stackoverflow.com/questions/73749995/why-does-matplotlib-3-6-0-on-macos-throw-an-attributeerror-when-showing-a-plot | I have the following straightforward code: import matplotlib.pyplot as plt x = [1,2,3,4] y = [34, 56, 78, 21] plt.plot(x, y) plt.show() But after changing my MacBook Pro to the M1 chip, I'm getting the following error: Traceback (most recent call last): File "/Users/freddy/PycharmProjects/TPMetodosNoParametricos/main.... | i had the same problem today on a different machine in the same matplotlib version. I downgrade to Version 3.5.0 and now it works. | 8 | 13 |
73,743,437 | 2022-9-16 | https://stackoverflow.com/questions/73743437/how-can-i-add-a-column-of-empty-arrays-to-polars-dataframe | I am trying to add a column of empty lists to a polars dataframe in python. My code import polars as pl a = pl.DataFrame({'a': [1, 2, 3]}) a.with_columns([pl.lit([]).alias('b')]) throws Traceback (most recent call last): File "<input>", line 1, in <module> a.with_columns([pl.lit([]).alias('b')]) File "/usr/local/lib/p... | This works for me. I wrote pl.Series() with empty lists [] as values: import polars as pl from polars import col df = pl.DataFrame({'a': [1, 2, 3]}) # .lazy() df = df.with_columns([ col('a'), pl.Series('empty lists', [[]], dtype=pl.List), pl.lit(None).alias('null column'), ]) print(df) # print(df.collect()) (in case of... | 8 | 11 |
73,731,982 | 2022-9-15 | https://stackoverflow.com/questions/73731982/update-to-python-3-10-in-google-cloud-shell | I want to upgrade to python 3.10 in my google cloud shell, but I failed to do so. I found two methods online, which were unsuccessful so far. Using the deadsnakes repo: I tried the following commands: sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update But I get an Error The repository 'http://ppa.launchpad.n... | This worked out for me. The default python version remained 3.10.7 even after the shell restarted. # install pyenv to install python on persistent home directory curl https://pyenv.run | bash # add to path echo 'export PATH="$HOME/.pyenv/bin:$PATH"' >> ~/.bashrc echo 'eval "$(pyenv init -)"' >> ~/.bashrc echo 'eval "$(... | 4 | 7 |
73,740,018 | 2022-9-16 | https://stackoverflow.com/questions/73740018/how-to-iterate-through-a-nested-dictionary-with-varying-depth-and-make-a-copy-w | I have a dictionary {'n11' : {'n12a': {'n13a' : 10 , 'n13b' : "some text"}, 'n12b': {'n13c' : {'n14a': 40} } }, 'n21': {'n22a' : 20 } } And I want to iterate through the dictionary until I reach a value which is not a dictionary, and replace it with the "full path" to that value. {'n11' : {'n12a': {'n13a' : 'n11_n12... | The most efficient way to do this would be using the same recursive function to not generate excess performance overhead. To copy the dictionary you can use copy.deepcopy() and then take that copy through the function, but replace the values instead of just printing the path: import copy data = {'n11': {'n12a': {'n13a'... | 4 | 5 |
73,740,722 | 2022-9-16 | https://stackoverflow.com/questions/73740722/smtpsenderrefused-at-password-reset-django | settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('USER_EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('USER_PASS') Error: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Requir... | I have solved the issue the issue was with my Gmail account you need to go to the settings > security then create a new app password and then replace the Gmail password in settings.py with your newly created app password. I think your Gmail should also have 2-factor authentication, mine was already on but if you try th... | 4 | 3 |
73,740,568 | 2022-9-16 | https://stackoverflow.com/questions/73740568/pandas-faster-method-than-df-atx-y | I have df1 df1 = pd.DataFrame({'x':[1,2,3,5], 'y':[2,3,4,6], 'value':[1.5,2.0,0.5,3.0]}) df1 x y value 0 1 2 1.5 1 2 3 2.0 2 3 4 0.5 3 5 6 3.0 and I want to assign the value at x and y coordinates to another dataframe df2 df2 = pd.DataFrame(0.0, index=[x for x in range(0,df1['x'].max()+1)], columns=[y for y in range(0... | You can avoid create zero df2 and using df.at method by DataFrame.pivot, DataFrame.fillna and DataFrame.reindex: df2 = (df1.pivot('x','y','value') .fillna(0) .reindex(index=range(df1['x'].max()+1), columns=range(df1['y'].max()+1), fill_value=0)) print (df2) y 0 1 2 3 4 5 6 x 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 1.5 ... | 4 | 8 |
73,739,633 | 2022-9-16 | https://stackoverflow.com/questions/73739633/python-ast-libary-how-to-retreive-value-of-a-specific-node | I have the following script: extras_require={"dev": dev_reqs} x = 3 entry_points={ "console_scripts": ["main=smamesdemo.run.main:main"] } I want to retrieve the following part as python data, dict and list not Nodes. entry_points={ "console_scripts": ["main=smamesdemo.run.main:main"] } I have tried the following, but... | You should use ast.NodeVisitor rather than ast.NodeTransformer since you are not making modifications to nodes. But for the purpose of retrieving a single node, it is simpler to use ast.walk instead to traverse the AST in a flat manner and find the ast.Assign node whose target id is 'entry_points', and then wrap its va... | 5 | 2 |
73,735,974 | 2022-9-15 | https://stackoverflow.com/questions/73735974/convert-dataclass-of-dataclass-to-json-string | I have a json string that I want to read, convert it to an object that I can manipulate, and then convert it back into a json string. I am utilizing the python 3.10 dataclass, and one of the attributes of the class is another class (mySubClass). When I call json.loads(myClass), I get the following error: TypeError: Obj... | If I've understood your question correctly, you can do something like this:: import json import dataclasses @dataclasses.dataclass class mySubClass: sub_item1: str sub_item2: str @dataclasses.dataclass class myClass: item1: str item2: mySubClass # We need a __post_init__ method here because otherwise # item2 will conta... | 6 | 7 |
73,735,592 | 2022-9-15 | https://stackoverflow.com/questions/73735592/how-to-display-the-label-from-models-textchoices-in-the-template | The Django docs says that one can use .label, but it does not work in the template. class Model(models.Model): class ModelChoices(models.TextChoices): ENUM = 'VALUE', 'Label' model_choice = models.CharField(choices=ModelChoices.choices) In the template object.model_choice displays the value ('VALUE'). object.model_cho... | You'd use get_{field_name}_display Python modelObj.get_model_choice_display() Template {{modelObj.get_model_choice_display}} | 5 | 8 |
73,715,821 | 2022-9-14 | https://stackoverflow.com/questions/73715821/jupyter-lab-issue-displaying-widgets-javascript-error | I have troubles replicating a JupyterLab install on a new PC. It is working fine on my previous one. I am unable to display simple widgets (like a checkbox from ipywidgets or ipyvuetify). I checked that jupyter-widgets is enabled with jupyter labextension list. The results is : jupyter-vue v1.7.0 enabled ok jupyter-vue... | That error is consistent with one noted here in an issue report recently. The suggestion there is to change to ipywidgets version 7.7.2 or 7.6.5 to fix this issue. Also, see the note here, too. | 16 | 10 |
73,724,269 | 2022-9-14 | https://stackoverflow.com/questions/73724269/which-module-should-i-use-for-python-collection-type-hints-collections-abc-or-t | I am unclear on whether to use typing or ABC classes for collection type hints in Python. It seems one can use either one, but the name typing suggests that's the preferred one. However, I see several places saying collections.abc should be used instead, not least PEP 585. I am getting the sense that typing was created... | Yes. collections.abc is the correct module going forward. Collections in typing have been deprecated since 3.9 | 4 | 6 |
73,719,101 | 2022-9-14 | https://stackoverflow.com/questions/73719101/connecting-a-c-program-to-a-python-script-with-shared-memory | I'm trying to connect a C++ program to python using shared memory but I don't know how to pass the name of the memory segment to python. Here is my C++ code: key_t key = ftok("address", 1); int shm_o; char* msg = "hello there"; int len = strlen(msg) + 1; void* addr; shm_o = shmget(key, 20, IPC_CREAT | 0600); if(shm_o =... | Taking the liberty to post a working example here for POSIX shared memory segments, which will work across C/C++ and Python on Linux/UNIX-like systems. This will not work on Windows. C++ code to create and write data into a shared memory segment (name provided on command line): #include <sys/mman.h> #include <sys/stat.... | 9 | 2 |
73,720,063 | 2022-9-14 | https://stackoverflow.com/questions/73720063/docker-compose-keeps-running-healthcheck | I am running a couple of services with docker compose. The data-loader service has to wait for the translator, but once the data-loader is running, the healthcheck does not stop executing, even after exiting. translator: build: ./translator container_name: translator command: uvicorn app.main:app --reload --host 0.0.0.... | so it must be the healthechk at the compose. Yes, translator health check is run by docker, which will keep running the health check every 5 seconds interval: 5s, whether there are any dependent services running or not. | 4 | 2 |
73,715,131 | 2022-9-14 | https://stackoverflow.com/questions/73715131/pydantic-nonetype-object-is-not-subscriptable-type-type-error | I have the following structure of the models using Pydantic library. I created some of the classes, and one of them contains list of items of another, so the problem is that I can't parse json using this classes: class FileTypeEnum(str, Enum): file = 'FILE' folder = 'FOLDER' class ImportInModel(BaseModel): id: constr(m... | You have to return parsed result after validation if success, i.e., you should add return values in the end of the two root_validator in ImportInModel. For instance, if I run below code, a corresponding error will throw up: if __name__ == '__main__': try: x_raw = ''' { "id": "элемент_1_4", "url": "/file/url1", "parentI... | 4 | 2 |
73,717,356 | 2022-9-14 | https://stackoverflow.com/questions/73717356/casting-a-value-based-on-a-trigger-in-pandas | I would like to create a new column every time I get 1 in the 'Signal' column that will cast the corresponding value from the 'Value' column (please see the expected output below). Initial data: Index Value Signal 0 3 0 1 8 0 2 8 0 3 7 1 4 9 0 5 10 0 6 14 1 7 10 0 8 10 0 9 4 1 10 10 0 11 1... | You can use a pivot: out = df.join(df # keep only the values where signal is 1 # and get Signal's cumsum .assign(val=df['Value'].where(df['Signal'].eq(1)), col=df['Signal'].cumsum() ) # pivot cumsumed Signal to columns .pivot(index='Index', columns='col', values='val') # ensure column 0 is absent (using loc to avoid Ke... | 5 | 4 |
73,653,265 | 2022-9-8 | https://stackoverflow.com/questions/73653265/whats-the-cleanest-way-to-indent-multiple-function-arguments-considering-pep8 | I am wondering what's the best way to format a function with multiple arguments. Suppose I have a function with many arguments with potentially long argument names or default values such as for example: def my_function_with_a_long_name(argument1="this is a long default value", argument2=["some", "long", "default", "val... | If pep8 doesn't strictly say that you have to use this style, you're free to choose between correct ones. But why bothering yourself to format it manually? The only important thing is to be consistent in your code. So just leave it to a formatter. That takes care of it. I would suggest Black. Written by a core develope... | 5 | 4 |
73,699,500 | 2022-9-13 | https://stackoverflow.com/questions/73699500/python-polars-split-string-column-into-many-columns-by-delimiter | In pandas, the following code will split the string from col1 into many columns. is there a way to do this in polars? data = {"col1": ["a/b/c/d", "a/b/c/d"]} df = pl.DataFrame(data) df_pd = df.to_pandas() df_pd[["a", "b", "c", "d"]] = df_pd["col1"].str.split("/", expand=True) pl.from_pandas(df_pd) shape: (2, 5) ┌─────... | Here's an algorithm that will automatically adjust for the required number of columns -- and should be quite performant. Let's start with this data. Notice that I've purposely added the empty string "" and a null value - to show how the algorithm handles these values. Also, the number of split strings varies widely. im... | 15 | 14 |
73,700,879 | 2022-9-13 | https://stackoverflow.com/questions/73700879/interaction-between-pydantic-models-schemas-in-the-fastapi-tutorial | I follow the FastAPI Tutorial and am not quite sure what the exact relationship between the proposed data objects is. We have the models.py file: from sqlalchemy import Boolean, Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from .database import Base class User(Base): __tablename__ = "user... | I'll go through your bullet points one by one. The models data classes define the SQL tables. Yes. More precisely, the orm classes that map to actual database tables are defined in the models module. The schemas data classes define the API that FastAPI uses to interact with the database. Yes and no. The Pydantic ... | 20 | 30 |
73,664,464 | 2022-9-9 | https://stackoverflow.com/questions/73664464/setuptools-and-pyproject-toml-specify-source | I am defining a python project using a pyproject.toml file. No setup.py, no setup.cfg. The project has dependencies on an alternate repository: https://artifactory.mypypy.com, how do I specify it ? | You put this in pyproject.toml: [[tool.poetry.source]] name = "internal-repo-2" url = "https://<private-repo-2>" priority = "explicit" There are alternative for priority but they come with a security risk: an attacker who learns the name of your internal package can push a package of the same name to PyPI, and it wil... | 4 | 0 |
73,705,069 | 2022-9-13 | https://stackoverflow.com/questions/73705069/how-to-type-hint-kwargs-when-they-are-passed-as-is-to-another-function | Suppose I have a fully type hinted method with only keyword arguments : class A: def func(a: int, b: str, c: SomeIntricateTypeHint) -> OutputClass: ... Now suppose I have a function that takes in variable keyword arguments, and passes them entirely onto that method : def outer_func(n_repeat: int, **kwargs: ???) -> Oth... | In my case, it is json.loads wrapper. My get_json accept the bytes and doing the decoding but the json.loads will accept str | bytes | bytearray as first argument. from typing import ( ParamSpec, Callable, Generic, Concatenate, Any, ) P = ParamSpec("P") def __get_json_func_creator( _: Callable[ Concatenate[Any, P], Any... | 9 | 3 |
73,637,315 | 2022-9-7 | https://stackoverflow.com/questions/73637315/oserror-no-library-called-cairo-2-was-found-from-custom-widgets-import-proje | How to fix this error? C:\Users\vanvl\OneDrive\Bureaublad\Progammeren\Project 1.02.2>python Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Custom_Widgets import ProjectMaker Traceback (most ... | This is quite an annoying dependency problem because cairocffi is not built for windows, you need the additional dependency as explained there: https://doc.courtbouillon.org/cairocffi/stable/overview.html#installing-cairo-on-windows A quicker solution is to do the following: I used pipwin which install from an unoffici... | 10 | 20 |
73,700,143 | 2022-9-13 | https://stackoverflow.com/questions/73700143/bad-string-representation-of-negative-imaginary-numbers-in-python | For some reason the string representation of negative imaginary numbers in Python is different for equal values: >>> str(-3j) '(-0-3j)' >>> str(0-3j) '-3j' Moreover, if I try to get the string representation of -0-3j, I get: >>> str(-0-3j) '-3j' Which seems like an inconsistency. The problem is that I use the string ... | This issue is filed as a bug and stimulated appearance of PEP-0682 - Format Specifier for Signed Zero and originates from Floating-point arithmetic limitations. Once the bug is resolved -0 will not scare unnecessarily any more. But until then... You can adapt the snippet from this answer: def real_norm(no): return no i... | 4 | 2 |
73,633,063 | 2022-9-7 | https://stackoverflow.com/questions/73633063/distribute-alembic-migration-scripts-in-application-package | I have an application that uses SQLAlchemy and Alembic for migrations. The repository looks like this: my-app/ my_app/ ... # Source code migrations/ versions/ ... # Migration scripts env.py alembic.ini MANIFEST.in README.rst setup.py When in the repo, I can call alembic commands (alembic revision, alembic upgrade). I ... | The obvious part of the answer is "include migration files in app directory". my-app/ my_app/ ... # Source code migrations/ versions/ ... # Migration scripts env.py alembic.ini MANIFEST.in README.rst setup.py The not so obvious part is that when users install the package, they are not in the app directory, so they wou... | 5 | 5 |
73,656,975 | 2022-9-9 | https://stackoverflow.com/questions/73656975/pytorch-silent-data-corruption | I am on a workstation with 4 A6000 GPUs. Moving a Torch tensor from one GPU to another GPU corrupts the data, silently!!! See the simple example below. x >tensor([1], device='cuda:0') x.to(1) >tensor([1], device='cuda:1') x.to(2) >tensor([0], device='cuda:2') x.to(3) >tensor([0], device='cuda:3') Any ideas what is the... | The solution was to disable IOMMU. On our server, in the BIOS settings /Advanced/AMD CBS/NBIO Common Options/IOMMU -> IOMMU - Disabled See the PyTorch issues thread for more information. | 5 | 2 |
73,663,939 | 2022-9-9 | https://stackoverflow.com/questions/73663939/is-there-a-way-to-specify-min-and-max-values-for-integer-column-in-slqalchemy | class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) age = Column(Integer) # I need age to have min value of 0 and max of 100 email = Column(String) SQLAlchemy documentation says that there is no such attributes to pass while creating a column | As described in brunson's answer, you can add a check constraint to perform the validation in the database, if the database supports check constraints. import sqlalchemy as sa ... class Test(Base): __tablename__ = 'test' id = sa.Column(sa.Integer, primary_key=True) age = sa.Column(sa.Integer, sa.CheckConstraint('age > ... | 3 | 7 |
73,662,432 | 2022-9-9 | https://stackoverflow.com/questions/73662432/pipenv-no-such-option-requirements-in-latest-version | command: pipenv lock --requirements --keep-outdated output: Usage: pipenv lock [OPTIONS] Try 'pipenv lock -h' for help. Error: No such option: --requirements Did you mean --quiet? Any idea how to fix this? | the -r option on pipenv lock command is deprecated for some time. use the requirements option to generate the requirements.txt ie: pipenv requirements > requirements.txt (Default dependencies) and to freeze dev dependencies as well use the --dev option pipenv requirements --dev > dev-requirements.txt Sometimes, you wo... | 14 | 21 |
73,683,616 | 2022-9-12 | https://stackoverflow.com/questions/73683616/multiple-rows-into-single-row-in-pandas | I wish to flatten(I am not sure whether is the correct thing to call it flatten) the columns with rows. multiple rows into single row with column change to column_rows I have a dataframe as below: data = {"a":[3,4,5,6], "b":[88,77,66,55], "c":["ts", "new", "thing", "here"], "d":[9.1,9.2,9.0,8.4]} df = pd.DataFrame(data... | Update let's use the walrus operator new in Python 3.8 to create a one-liner: (df_new := df.unstack().to_frame().T).set_axis( [f"{i}_{j}" for i, j in df_new.columns], axis=1 ) Output: a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0 c_1 c_2 c_3 d_0 d_1 d_2 d_3 0 3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4 Try this, us... | 3 | 5 |
73,636,196 | 2022-9-7 | https://stackoverflow.com/questions/73636196/masking-layer-vs-attention-mask-parameter-in-multiheadattention | I use MultiHeadAttention layer in my transformer model (my model is very similar to the named entity recognition models). Because my data comes with different lengths, I use padding and attention_mask parameter in MultiHeadAttention to mask padding. If I would use the Masking layer before MultiHeadAttention, will it ha... | The Tensoflow documentation on Masking and padding with keras may be helpful. The following is an excerpt from the document. When using the Functional API or the Sequential API, a mask generated by an Embedding or Masking layer will be propagated through the network for any layer that is capable of using them (for exa... | 5 | 3 |
73,704,681 | 2022-9-13 | https://stackoverflow.com/questions/73704681/how-to-iterate-through-json-to-print-in-a-formatted-way | This is the JSON i have """ { "A":1, "B":[ { "C": { "D": "0" }, "E": { "F": "1", "G": [ { "H": { "I": 12, "J": 21 } } ] } } ] } """ I want to print the JSON in the following way more likely in a tree fashion ----------------------------------------------------------------------- --------------------------EXPECTED OUTP... | Simple recursion: def tree(json_data): def _tree(obj): if isinstance(obj, dict): return [{'title': k, 'key': k, 'children': _tree(v)} for k, v in obj.items()] elif isinstance(obj, list): return [elem for lst in map(_tree, obj) for elem in lst] else: return [] return {'title': 'ROOT', 'key': '0', 'children': _tree(json_... | 4 | 6 |
73,698,100 | 2022-9-13 | https://stackoverflow.com/questions/73698100/pandas-how-to-merging-on-multiple-columns-not-working-and-other-solutions-regula | I have an old dataframe (dfo) that someone decided to add additional columns (notes) to and this data set does not have a key column. I also have a new dataframe (dfn) that is suppose to represent the same data but does not have the notes columns. I was asked just to transfer the old notes to the new dataframe. I have ... | If I understand correctly the ’25% that do not merge’ refers to the length of the data frame that results from an inner join: print('inner', pd.merge(dfn, dfo, how="inner", on=subset).shape) # (7445, 10) Which means that roughly 2700 rows of the old data frame are not merged with the new data frame. It seems to me you... | 4 | 1 |
73,638,290 | 2022-9-7 | https://stackoverflow.com/questions/73638290/python-on-mac-is-it-safe-to-set-objc-disable-initialize-fork-safety-yes-globall | Some python processes crash with: objc[51435]: +[__NSCFConstantString initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug. Those are processes usin... | Apple changed the way fork() behaves in High Sierra (>= 10.13). If enabled, the OBJC_DISABLE_INITIALIZE_FORK_SAFETY variable turns off the immediate crash behaviour that their newer ObjectiveC framework otherwise enforces by default, as part of this change. Your question "is it safe to set it as a global environment va... | 7 | 10 |
73,708,409 | 2022-9-13 | https://stackoverflow.com/questions/73708409/resolved-geopandas-sjoin-nearest-where-dataframes-share-a-common-attribute | What is the most elegant way to group df1 and df2 by admin region as a constraint on a near spatial join? Data I have two spatial dataframes, df1 and df2. Both are from polygon shapefiles. The two dataframes have a common attribute, ADM, which is the administrative area that contains their centroids. df1: df1_ID year A... | Have adapted sharding approach. First generate a dict of df2 then use groupby apply to sjoin_nearest() each group to appropriate shard now have settlement associated in way you want import geopandas as gpd df1 = gpd.read_file("https://github.com/gracedoherty/urban_growth/blob/main/df1.zip?raw=true") df2 = gpd.read_fi... | 4 | 4 |
73,667,333 | 2022-9-9 | https://stackoverflow.com/questions/73667333/open-ai-gym-environments-dont-render-dont-show-at-all | So I wanted to try some reinforcement learning, I haven't coded anything for a while. On Jupiter Notebooks when I run this code import gym env = gym.make("MountainCar-v0") env.reset() done = False while not done: action = 2 # always go right! env.step(action) env.render() it just tries to render it but can't, the hour... | Use an older version that supports your current version of Python. I solved the problem using gym 0.17.3 pip install gym==0.17.3 and the code: import gym env = gym.make("MountainCar-v0") state = env.reset() done = False while not done: action = 2 # always go right! env.step(action) print(new_state, render) env.render(... | 5 | 8 |
73,708,478 | 2022-9-13 | https://stackoverflow.com/questions/73708478/the-git-or-python-command-requires-the-command-line-developer-tools | This knowledge post isn't a duplication of other similar ones, since it's related to 12/September/2022 Xcode update, which demands a different kind of solution I have come to my computer today and discovered that nothing runs on my terminal Every time I have opened my IDE (VS Code or PyCharm), it has given me this mess... | I was prompted to reinstall commandLine tools over and over when trying to accept the terms I FIXED this by opening xcode and confirming the new update information | 33 | 80 |
73,708,230 | 2022-9-13 | https://stackoverflow.com/questions/73708230/pandas-groupby-and-transform-based-on-multiple-columns | I have seen a lot of similar questions but none seem to work for my case. I'm pretty sure this is just a groupby transform but I keep getting KeyError along with axis issues. I am trying to groupby filename and check count where pred != gt. For example Index 2 is the only one for f1.wav so 1, and Index (13,14,18) for f... | .transform operates on each column individually, so you won't be able to access both 'pred' and 'gt' in a transform operation. This leaves you with 2 options: aggregate and reindex or join back to the original shape pre-compute the boolean array and .transform on that approach 2 will probably be the fastest here: df[... | 3 | 7 |
73,698,041 | 2022-9-13 | https://stackoverflow.com/questions/73698041/how-retain-grad-in-pytorch-works-i-found-its-position-changes-the-grad-result | in a simple test in pytorch, I want to see grad in a non-leaf tensor, so I use retain_grad(): import torch a = torch.tensor([1.], requires_grad=True) y = torch.zeros((10)) gt = torch.zeros((10)) y[0] = a y[1] = y[0] * 2 y.retain_grad() loss = torch.sum((y-gt) ** 2) loss.backward() print(y.grad) it gives me a normal ou... | Okay so what's going on is really weird. What .retain_grad() essentially does is convert any non-leaf tensor into a leaf tensor, such that it contains a .grad attribute (since by default, pytorch computes gradients to leaf tensors only). Hence, in your first example, after calling y.retain_grad(), it basically converte... | 13 | 9 |
73,700,044 | 2022-9-13 | https://stackoverflow.com/questions/73700044/how-to-update-two-columns-with-different-values-on-the-same-condition-in-pyspark | I have a DataFrame with column a. I would like to create two additional columns (b and c) based on column a. I could solve this problem doing the same thing twice: df = df.withColumn('b', when(df.a == 'something', 'x'))\ .withColumn('c', when(df.a == 'something', 'y')) I would like to avoid doing the same thing twice,... | A struct is best suited in such a case. See below example. spark.sparkContext.parallelize([('something',), ('foobar',)]).toDF(['a']). \ withColumn('b_c_struct', func.when(func.col('a') == 'something', func.struct(func.lit('x').alias('b'), func.lit('y').alias('c')) ) ). \ select('*', 'b_c_struct.*'). \ show() # +-------... | 4 | 2 |
73,679,164 | 2022-9-11 | https://stackoverflow.com/questions/73679164/how-to-turn-off-automatic-deletion-of-unused-imports-in-vs-code | VS Code automatically deletes unused imports and even more annoyingly it deletes imports that are used, but commented out. So for example, if I was to save this code: from pprint import pprint # pprint("foo") It would remove the first line. So how can I turn this feature off, because it constantly forces me to rewrite... | Check your settings.json (User and Workspace) for the following settings, delete this configuration or change it to false. "editor.codeActionsOnSave": { "source.fixAll": true, }, | 4 | 7 |
73,694,266 | 2022-9-12 | https://stackoverflow.com/questions/73694266/how-to-specify-date-bin-ranges-for-seaborn-displot | Problem statement I am creating a distribution plot of flood events per N year periods starting in 1870. I am using Pandas and Seaborn. I need help with... specifying the date range of each bin when using sns.displot, and clearly representing my bin size specifications along the x axis. To clarify this problem, here ... | Seaborn internally converts its input data to numbers so that it can do math on them, and it uses matplotlib's "unit conversion" machinery to do that. So the easiest way to pass bins that will work is to use matplotlib's date converter: sns.displot(data=tcdf, x="Date", bins=mpl.dates.date2num(my_bins)) | 5 | 6 |
73,667,667 | 2022-9-9 | https://stackoverflow.com/questions/73667667/installing-odoo-on-mac-raises-gevent-error | I'm following this tutorial to install Odoo 15 on Mac, but I'm getting this error when running pip install -r requirements.txt: Error compiling Cython file: ------------------------------------------------------------ ... cdef load_traceback cdef Waiter cdef wait cdef iwait cdef reraise cpdef GEVENT_CONFIG ^ ---------... | Odoo 15 currently seems to be incompatible with Python 3.10. You can get rid of that error by upgrading gevent/greenlet to newer versions in the requirements file. I've successfully tried gevent 21.12.0 and greenlet 1.1.3, BUT then you'll run into more trouble due to changes in the Python collections package. Here is a... | 3 | 1 |
73,693,104 | 2022-9-12 | https://stackoverflow.com/questions/73693104/valueerror-exceeds-the-limit-4300-for-integer-string-conversion | >>> import sys >>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default. >>> _ = int('2' * 5432) Traceback (most recent call last): ... ValueError: Exceeds the limit (4300) for integer string conversion: value has 5432 digits. Python 3.10.7 introduced this breaking change for type conversion. Documen... | See github issue CVE-2020-10735: Prevent DoS by large int<->str conversions #95778: Problem A Denial Of Service (DoS) issue was identified in CPython because we use binary bignum’s for our int implementation. A huge integer will always consume a near-quadratic amount of CPU time in conversion to or from a base 10 (dec... | 28 | 12 |
73,693,149 | 2022-9-12 | https://stackoverflow.com/questions/73693149/replace-value-of-variable-directly-inside-f-string | I'm trying to replace a value inside a variable that I use within an f-string. In this case it is a single quote. For example: var1 = "foo" var2 = "bar '" print(f"{var1}-{var2}") Now, I want to get rid of the single quote within var2, but do it directly in the print statement. I've tried: print(f"{var1}-{var2.replace(... | When the contents contains both ' and ", you can use a triple quoted string: >>> print(f'''{var1}-{var2.replace("'","")}''') foo-bar | 4 | 3 |
73,650,173 | 2022-9-8 | https://stackoverflow.com/questions/73650173/poetry-and-buildkit-mount-type-cache-not-working-when-building-over-airflow-imag | I have 2 examples of docker file and one is working and another is not. The main difference between the 2 is the base image. Simple python base image docker file: # syntax = docker/dockerfile:experimental FROM python:3.9-slim-bullseye RUN apt-get update -qy && apt-get install -qy \ build-essential tini libsasl2-dev lib... | Maybe it is not answering the question directly but I think what you are trying to do makes very little sense in the first place, so I would recommend you to change the approach, completely, especially that what you are trying to achieve is very well described in The Airflow Official image documentation including plent... | 4 | 1 |
73,685,400 | 2022-9-12 | https://stackoverflow.com/questions/73685400/regex-to-match-the-first-occurance-starting-from-the-end-of-the-string | How do you match the first occurance of start, starting from the end of the string? I have tried it with a negative lookahead but instead I get start\nfoo\nmoo\nstart\nfoo\ndoo as match import re pattern='(start[\s\S]*$)(?=$)' string='start\nfoo\nmoo\nstart\nfoo\ndoo' re.search(pattern, string) expected match: start\n... | You can use this code: string='start\nfoo\nmoo\nstart\nfoo\ndoo' print (re.findall(r'(?s).*(\bstart\b.*)', string)) ##> ['start\nfoo\ndoo'] RegEx Breakup: (?s): Enable single line or DOTALL mode to make dot match line break as well .*: Match longest possible match including line breaks (\bstart\b.*): Match word start... | 4 | 5 |
73,676,321 | 2022-9-11 | https://stackoverflow.com/questions/73676321/how-do-you-simulate-buoyancy-in-games | I have a working code for buoyancy simulation but it's not behaving properly. I have 3 scenarios and the expected behavior as follows: Object initial position is already submerged : (a) expected to move up; (b) then down but not beyond its previous submersion depth; (c) repeat a-b until object stops or floats at surfa... | Finally found the solution, though not as perfect as it should be. I'm no physics expert but based on my research, in addition to the buoyant force, there are three drag forces acting on a moving/submerging body namely (1) skin friction drag, (2) form drag, and (3) interference drag. To my understanding, skin friction ... | 4 | 4 |
73,675,431 | 2022-9-10 | https://stackoverflow.com/questions/73675431/printing-a-pdf-with-selenium-chrome-driver-in-headless-mode | I have no problems printing without headless mode, however once I enable headless mode, it just refuses to print a PDF. I'm currently working on an app with a GUI, so I'd rather not have the Selenium webdriver visible to the end user if possible. For this project I'm using an older version of Selenium, 4.2.0. That coup... | For anyone else coming across this with a similar issue, I fixed it by using the print method described here: Selenium print PDF in A4 format Using my example from above, I replaced: driver.execute_script("window.print();") with: pdf_data = driver.execute_cdp_cmd("Page.printToPDF", print_settings) with open('Google.pd... | 3 | 6 |
73,679,420 | 2022-9-11 | https://stackoverflow.com/questions/73679420/how-to-extract-a-part-of-the-string-to-another-column | I have a column that contains data like Dummy data: df = pd.DataFrame(["Lyreco A-Type small 2i", "Lyreco C-Type small 4i", "Lyreco N-Part medium", "Lyreco AKG MT 4i small", "Lyreco AKG/ N-Type medium 4i", "Lyreco C-Type medium 2i", "Lyreco C-Type/ SNU medium 2i", "Lyreco K-part small 4i", "Lyreco K-Part medium", "Lyrec... | Looking at the example you posted, it's enough to split the column values and return "the middle" items. You can make a simple function to encapsulate the logic and apply it to the dataframe. from math import floor df = pd.DataFrame( {'Columns_1': ["Lyreco A-Type small 2i", "Lyreco C-Type small 4i", "Lyreco N-Part medi... | 4 | 2 |
73,676,661 | 2022-9-11 | https://stackoverflow.com/questions/73676661/how-to-trap-this-nested-httpx-exception | I'm trapping thus: with httpx.Client(**sessions[scraperIndex]) as client: try: response = client.get(...) except TimeoutError as e: print('does not hit') except Exception as e: print(f'⛔️ Unexpected exception: {e}') print_exc() # hits! However I'm getting the below crashdump. Pulling out key lines: TimeoutError: The r... | The base class for all httpx timeout errors is not the built-in TimeoutError (presumably because that would also make timeouts OSErrors, which doesn't sound correct), but httpx.TimeoutException. import httpx with httpx.Client() as client: try: response = client.get("http://httpbin.org/get", timeout=0.001) except httpx.... | 6 | 4 |
73,677,424 | 2022-9-11 | https://stackoverflow.com/questions/73677424/plotly-express-colorscale-map-by-absolute-value-instead-of-0-1 | I have a map of the US and am plotting winning margin in Presidential elections in Plotly Express. I want a winning margin of 0 to be displayed as white and the scale to diverge into red/blue. However, the color_continuous_scale keyword argument takes a range from 0-1, and where a winning margin of 0 falls in this 0-1 ... | In plotly you can pass the midpoint for continuous scales: color_continuous_scale=px.colors.sequential.RdBu, color_continuous_midpoint=0.0 The RdBu scale goes from red to white to blue. By passing color_continuous_midpoint=0.0 you specify that 0.0 is in the middle of the scale, i.e. white. The other colors will be det... | 4 | 3 |
73,630,653 | 2022-9-7 | https://stackoverflow.com/questions/73630653/redirect-to-login-page-if-user-not-logged-in-using-fastapi-login-package | I would like to redirect users to the login page, when they are not logged in. Here is my code: from fastapi import ( Depends, FastAPI, HTTPException, status, Body, Request ) from fastapi.encoders import jsonable_encoder from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from fastapi.responses... | From the code snippet you provided, you seem to be using the (third-party) FastAPI-Login package. Their documentation suggests using a custom Exception on the LoginManager instance, which can be used to redirect the user to the login page, if they are not logged in. Working example: The authentication below is based on... | 4 | 9 |
73,674,735 | 2022-9-10 | https://stackoverflow.com/questions/73674735/how-to-search-and-select-column-names-based-on-values | Suppose I have a pandas DataFrame like this name col1 col2 col3 0 AAA 1 0 2 1 BBB 2 1 2 2 CCC 0 0 2 I want (a) the names of any columns that contain a value of 2 anywhere in the column (i.e., col1, col3), and (b) the names of any columns that contain only values of 2 (i.e., col3). I understand how to use DataFrame.an... | You can do what you described with columns: df.columns[df.eq(2).any()] # Index(['col1', 'col3'], dtype='object') df.columns[df.eq(2).all()] # Index(['col3'], dtype='object') | 4 | 3 |
73,672,316 | 2022-9-10 | https://stackoverflow.com/questions/73672316/how-to-get-debug-logs-from-boto3-in-a-local-script | I have a local script that lists buckets: import boto3 s3_client = boto3.client('s3') for bucket in s3_client.list_buckets()["Buckets"]: print(bucket['Name']) when I execute it locally, it does just that. Now if I execute this code as a lambda on AWS and set the log level to DEBUG, like so: import boto3 import logging... | This seems to work for me: import boto3 import logging boto3.set_stream_logger('', logging.DEBUG) s3_client = boto3.client('s3') for bucket in s3_client.list_buckets()["Buckets"]: print(bucket['Name']) Spews out a whole bunch of stuff. From this doc | 9 | 13 |
73,659,445 | 2022-9-9 | https://stackoverflow.com/questions/73659445/get-directories-only-with-glob-pattern-using-pathlib | I want to use pathlib.glob() to find directories with a specific name pattern (*data) in the current working dir. I don't want to explicitly check via .isdir() or something else. Input data This is the relevant listing with three folders as the expected result and one file with the same pattern but that should be part ... | The trailing path separator certainly should be respected in pathlib.glob patterns. This is the expected behaviour in shells on all platforms, and is also how the glob module works: If the pattern is followed by an os.sep or os.altsep then files will not match. However, there is a bug in pathlib that was fixed in bpo... | 6 | 8 |
73,668,028 | 2022-9-9 | https://stackoverflow.com/questions/73668028/how-would-i-group-summarize-and-filter-a-df-in-pandas-in-dplyr-fashion | I'm currently studying pandas and I come from an R/dplyr/tidyverse background. Pandas has a not-so-intuitive API and how would I elegantly rewrite such operation from dplyr using pandas syntax? library("nycflights13") library("tidyverse") delays <- flights %>% group_by(dest) %>% summarize( count = n(), dist = mean(dist... | pd.DataFrame.agg method doesn't allow much flexibility for changing columns' names in the method itself That's not exactly true. You could actually rename the columns inside agg similar to in R although it is a better idea to not use count as a column name as it is also an attribute: delays = ( flights .groupby('des... | 4 | 6 |
73,668,088 | 2022-9-9 | https://stackoverflow.com/questions/73668088/can-we-use-plotly-express-to-plot-zip-codes | I'm using the code from this link. https://devskrol.com/2021/12/27/choropleth-maps-using-python/ Here's my actual code. import plotly.express as px from urllib.request import urlopen import json with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = j... | Since you did not provide any user data, I tried your code with data including US zip codes from here. I think the issue is that you don't need to specify the location mode. I specified county_fips for the location and population for the color fill. import plotly.express as px from urllib.request import urlopen import ... | 4 | 3 |
73,664,093 | 2022-9-9 | https://stackoverflow.com/questions/73664093/lightgbm-train-vs-update-vs-refit | I'm implementing LightGBM (Python) into a continuous learning pipeline. My goal is to train an initial model and update the model (e.g. every day) with newly available data. Most examples load an already trained model and apply train() once again: updated_model = lightgbm.train(params=last_model_params, train_set=new_d... | In lightgbm (the Python package for LightGBM), these entrypoints you've mentioned do have different purposes. The main lightgbm model object is a Booster. A fitted Booster is produced by training on input data. Given an initial trained Booster... Booster.refit() does not change the structure of an already-trained mode... | 10 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.