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,667,806 | 2022-9-9 | https://stackoverflow.com/questions/73667806/how-to-convert-list-items-to-dictionary-keys-with-0-as-default-values | I'm trying to turn this list: ['USA', 'Canada', 'Japan'] into this dictionary: {'USA': 0, 'Canada': 0, 'Japan': 0} Can it be achieved with a simple loop? How would you go about it? Thanks! | Use dict.fromkeys: lst = ["USA", "Canada", "Japan"] out = dict.fromkeys(lst, 0) print(out) Prints: {'USA': 0, 'Canada': 0, 'Japan': 0} | 5 | 6 |
73,667,014 | 2022-9-9 | https://stackoverflow.com/questions/73667014/python-get-first-x-elements-of-a-list-and-remove-them | Note: I know there is probably an answer for this on StackOverflow already, I just can't find it. I need to do this: >>> lst = [1, 2, 3, 4, 5, 6] >>> first_two = lst.magic_pop(2) >>> first_two [1, 2] >>> lst [3, 4, 5, 6] Now magic_pop doesn't exist, I used it just to show an example of what I need. Is there a method l... | Do it in two steps. Use a slice to get the first two elements, then remove that slice from the list. first_list = lst[:2] del lst[:2] If you want a one-liner, you can wrap it in a function. def splice(lst, start = 0, end = None): if end is None: end = len(lst) partial = lst[start:end] del lst[start:end] return partial... | 6 | 7 |
73,665,184 | 2022-9-9 | https://stackoverflow.com/questions/73665184/how-do-i-close-figure-in-matplotlib | import matplotlib.pyplot as plt import pandas as pd l1 = [1,2,3,4] l2 = [2,4,6,8] fig = plt.figure() def func(): plt.pause(1) plt.plot(l1,l2) plt.draw() plt.pause(1) input("press any key to continue...") plt.close(fig) plt.pause(1) while True: func() plt.pause(1) This is the modified one: import matplotlib.pyplot as p... | The issue is not while True: as much as how you create your figures. Let's step through your process conceptually: fig = plt.figure() creates a figure and stores the handle in fig. Then you call func, which draws on the figure and eventually calls plt.pause(1). You loop around and call func again. This time, plt.plot(... | 9 | 12 |
73,664,830 | 2022-9-9 | https://stackoverflow.com/questions/73664830/pydantic-object-has-no-attribute-fields-set-error | I'm working with FastAPI to create a really simple dummy API. For it I was playing around with enums to define the require body for a post request and simulating a DB call from the API method to a dummy method. To have the proper body request on my endpoint, Im using Pydantic's BaseModel on the class definition but for... | You basically completely discarded the Pydantic BaseModel.__init__ method on your MagicItem. Generally speaking, if you absolutely have to override the Base Model's init-method (and in your case, you don't), you should at least call it inside your own like this: super().__init__(...) Pydantic does a whole lot of magic... | 14 | 28 |
73,661,849 | 2022-9-9 | https://stackoverflow.com/questions/73661849/which-specific-characters-does-the-strip-function-remove | Here is what you can find in the str.strip documentation: The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. Now my question is: which specific characters are considered whitespace? These function calls share the same ... | The most trivial way to know which characters are removed by str.strip() is to loop over each possible characters and check if a string containing such character gets altered by str.strip(): c = 0 while True: try: s = chr(c) except ValueError: break if (s != s.strip()): print(f"{hex(c)} is stripped", flush=True) c+=1 ... | 9 | 5 |
73,660,050 | 2022-9-9 | https://stackoverflow.com/questions/73660050/how-to-achieve-resumption-semantics-for-python-exceptions | I have a validator class with a method that performs multiple checks and may raise different exceptions: class Validator: def validate(something) -> None: if a: raise ErrorA() if b: raise ErrorB() if c: raise ErrorC() There's a place in the outside (caller) code where I want to customize its behaviour and prevent Erro... | With bare exceptions you are looking at the wrong tool for the job. In Python, to raise an exception means that execution hits an exceptional case in which resuming is not possible. Terminating the broken execution is an express purpose of exceptions. Execution Model: 4.3. Exceptions Python uses the “termination” mode... | 7 | 3 |
73,661,082 | 2022-9-9 | https://stackoverflow.com/questions/73661082/how-to-generate-a-certain-number-of-random-whole-numbers-that-add-up-to-a-certai | I want to generate 10 whole numbers that add up to 40 and are in the range of 2-6. For example: 2 + 6 + 2 + 5 + 6 + 2 + 2 + 6 + 3 + 6 = 40 Ten random numbers between 2 and 6 that add up to 40. | Given the relatively small search space, you could use itertools.combinations_with_replacement() to generate all possible sequences of 10 numbers between 2 and 6, save the ones that sum to 40 - then pick and shuffle one at random when requested: from itertools import combinations_with_replacement as combine from random... | 6 | 7 |
73,659,394 | 2022-9-9 | https://stackoverflow.com/questions/73659394/python-merge-two-dictionary-without-losing-the-order | I have a dictionary containing UUID generated for documents like below. { "UUID": [ "b8f2904b-dafd-4be3-9615-96bac8e16c7f", "1240ad39-4815-480f-8cb2-43f802ba8d4e" ] } And another dictionary as a nested one { "R_Id": 304, "ContextKey": "Mr.Dave", "ConsolidationInformation": { "Input": [ { "DocumentCode": "BS", "Obj... | Issues: You have done well with your attempt. The only issue is that the values must be accessed and added at the correct nesting level. Solution: You can correct your attempt as follows: for i, doc in enumerate(document['ConsolidationInformation']['Input']): doc['DocumentUUID'] = uuid['UUID'][i] Alternatively: You ca... | 3 | 6 |
73,639,623 | 2022-9-7 | https://stackoverflow.com/questions/73639623/how-can-i-pass-the-gitlab-job-token-into-a-docker-build-without-causing-a-cache | We are using the PyPI repos built into our gitlab deployment to share our internal packages with multiple internal projects. When we build our docker images we need to install those packages as part of image creation. However the gitlab CI token that we use to get access to the gitlab PyPI repository is a one-off token... | Use build secrets instead (requires build kit) You can mount the secret at build time using the --mount argument to the RUN instruction. Suppose you have the following in a dockerfile: # ... RUN --mount=type=secret,id=mysecret echo "$(cat /run/secrets/mysecret)" > .foo RUN echo "another layer" > .bar Then you can pass... | 6 | 3 |
73,652,967 | 2022-9-8 | https://stackoverflow.com/questions/73652967/how-to-define-a-uniqueconstraint-on-two-or-more-columns-with-sqlmodel | With SQLAlchemy it is possible to create a constraint on two or more columns using the UniqueConstraint declaration. What would be the most idiomatic way of doing that using SQLModel? For example: from sqlmodel import SQLModel, Field class SubAccount(SQLModel): id: int = Field(primary_key=True) name: str description: s... | As of now, exactly the same way. The SQLModel metaclass inherits a great deal from the SQLAlchemy DeclarativeMeta class. In many respects, you can treat an SQLModel subclass the way you would treat your SQLAlchemy ORM base class. Example: from sqlmodel import Field, SQLModel, UniqueConstraint, create_engine class User(... | 10 | 20 |
73,652,973 | 2022-9-8 | https://stackoverflow.com/questions/73652973/add-values-to-column-pandas-dataframe-by-index-number | Imagine I have a list that represents the indexes of a dataframe, like this one: indexlist = [0,1,4] And the following dataframe: Name Country 0 John BR 1 Peter BR 2 Paul BR 3 James CZ 4 Jonatan CZ 5 Maria DK I need to create a column on this dataframe named "Is it valid?" that would add "Yes" if the index row is in... | You can use isin for index, that you'd normally use with Series, it essentially creates an array of truth value, which you can pass to np.where with true and false values, assign the result as a column. df['Is it valid?'] = np.where(df.index.isin(indexlist), 'Yes', 'No') OUTPUT: Name Country Is it valid? 0 John BR Ye... | 3 | 5 |
73,645,294 | 2022-9-8 | https://stackoverflow.com/questions/73645294/return-deeply-nested-json-objects-with-response-model-fastapi-and-pydantic | This is my schema file from pydantic import BaseModel from typing import Optional class HolidaySchema(BaseModel): year: int month: int country: str language: str class HolidayDateSchema(BaseModel): name: str date: str holidays: HolidaySchema | None = None class Config: orm_mode = True and this is the router that I hav... | HolidaySchema isn't configured with orm_mode = True. You need this for all the models that you want to automagically convert from SQLAlchemy model objects. class HolidaySchema(BaseModel): year: int month: int country: str language: str class Config: orm_mode = True You can configure that setting on a common BaseModel ... | 5 | 3 |
73,647,685 | 2022-9-8 | https://stackoverflow.com/questions/73647685/why-does-a-temporary-variable-in-python-change-how-this-pass-by-sharing-variable | first-time questioner here so do highlight my mistakes. I was grinding some Leetcode and came across a behavior (not related to the problem) in Python I couldn't quite figure out nor google-out. It's especially difficult because I'm not sure if my lack of understanding is in: recursion the += operator in Python or var... | In Python, if you have expression1() + expression2(), expression1() is evaluated first. So 1 and 2 are really equivalent to: left = holder.val right = self.diveDeeper(holder, n - 1) holder.val = left + right Now, holder.val is only ever modified after the recursive call, but you use the value from before the recursive... | 8 | 3 |
73,642,805 | 2022-9-8 | https://stackoverflow.com/questions/73642805/what-is-more-correct-to-use-to-centralize-this-case | I want to centralize frm_login using pack or grid without using another auxiliary widget. Is it possible? I put an anchor="center" in frm_login.pack(side="left") but it didn't work. import tkinter as tk from tkinter import ttk principal = tk.Tk() principal.title("Login") principal.resizable(False, False) largura = 300 ... | Use the tkinter grid method and pass your parameter sticky="nsew". Use rowconfigure() and columnconfigure(). Set the parameter weight=1 in rowconfigure and columnconfigure. So your widget is going to fill in the whole space they can using sticky. When you configure row and column, only the rows and columns you specifie... | 4 | 1 |
73,633,371 | 2022-9-7 | https://stackoverflow.com/questions/73633371/how-to-configure-fastapi-to-publish-logs-to-cloudwatch | I have a FastAPI service that works as expected in every regard except the logging, only when it runs as a AWS Lambda function. When running it locally the logs are displayed on the console as expected: INFO: 127.0.0.1:62160 - "POST /api/v1/feature-requests/febbbc21-9650-44e6-8df5-80c8bb33b6ea/upvote HTTP/1.1" 200 OK I... | As it turns out the following setup is needed: On the top of the logging.conf above uvicorn has to be imported that creates an extra property on logging and than fileConfig has to be used like this: import uvicorn logging.config.fileConfig("logging.conf", disable_existing_loggers=False) LOG = logging.getLogger(__name__... | 4 | 0 |
73,629,154 | 2022-9-7 | https://stackoverflow.com/questions/73629154/command-line-stable-diffusion-runs-out-of-gpu-memory-but-gui-version-doesnt | I installed the GUI version of Stable Diffusion here. With it I was able to make 512 by 512 pixel images using my GeForce RTX 3070 GPU with 8 GB of memory: However when I try to do the same thing with the command line interface, I run out of memory: Input: >> C:\SD\stable-diffusion-main>python scripts/txt2img.py --pro... | This might not be the only answer, but I solved it by using the optimized version here. If you already have the standard version installed, just copy the "OptimizedSD" folder into your existing folders, and then run the optimized txt2img script instead of the original: >> python optimizedSD/optimized_txt2img.py --promp... | 9 | 7 |
73,641,835 | 2022-9-7 | https://stackoverflow.com/questions/73641835/unnesting-event-parameters-in-json-format-within-a-pandas-dataframe | I have a dataset that looks like the one below. It is relational, but has a dimension called event_params which is a JSON object of data related to the event_name in the respective row. import pandas as pd a_df = pd.DataFrame(data={ 'date_time': ['2021-01-03 15:12:42', '2021-01-03 15:12:46', '2021-01-03 15:13:01' , '20... | I hope I've understood your question right. You can transform the event_params column from dict to list of dicts, explode it and transform to new columns key/value: from ast import literal_eval a_df = a_df.assign( event_params=a_df["event_params"].apply( lambda x: [{"key": k, "value": v} for k, v in literal_eval(x).ite... | 6 | 7 |
73,635,937 | 2022-9-7 | https://stackoverflow.com/questions/73635937/extract-key-value-pairs-as-a-tuple-from-nested-json-with-python | I want to extract all key-value pairs from JSON file, I loaded it as a Python dictionary. I created this function below that stores all values. However, I am struggling to put them inside a list to store them like that. Any support is very appreciated. json_example = {'name': 'TheDude', 'age': '19', 'hobbies': { 'love... | Issues: Your recursive function currently does not pass the key as part of the function call. Also, you will need to deal with nesting when trying to create the key. Hints: We can assemble a list of all the keys that lead to a particular value (e.g. ['hobbies', 'love']) and then join the keys into a single string (e.g.... | 5 | 4 |
73,635,605 | 2022-9-7 | https://stackoverflow.com/questions/73635605/combine-multiple-columns-into-one-category-column-using-the-column-names-as-valu | I have this data ID A B C 0 0 True False False 1 1 False True False 2 2 False False True And want to transform it into ID group 0 0 A 1 1 B 2 2 C I want to use the column names as value labels for the category column. There is a maximum of only one True value per row. This is the MWE #!/usr/bin/env python3 import... | You can use melt then a lookup based on the column where the values are true to get the results you are expecting df = df.melt(id_vars = 'ID', var_name = 'group') df.loc[df['value'] == True][['ID', 'group']] | 26 | 7 |
73,634,640 | 2022-9-7 | https://stackoverflow.com/questions/73634640/issue-using-if-statement-in-python | Input: import random I = 0 z = [] while I < 6: y = random. Choices(range(1,50)) if y in z: break z += y I += 1 print(z) Output: [8, 26, 8, 44, 31, 22] I'm trying to make a Lotto numbers generator but I can't make the code to generate 6 numbers that do not repeat. As you can see in the Output 8 is repeating. I'm not cl... | Use random.sample: >>> from random import sample >>> sample(range(1, 50), k=6) [40, 36, 43, 15, 37, 25] It already picks k unique items from the range. | 3 | 8 |
73,632,886 | 2022-9-7 | https://stackoverflow.com/questions/73632886/combining-split-with-findall | I'm splitting a string with some separator, but want the separator matches as well: import re s = "oren;moish30.4.200/-/v6.99.5/barbi" print(re.split("\d+\.\d+\.\d+", s)) print(re.findall("\d+\.\d+\.\d+", s)) I can't find an easy way to combine the 2 lists I get: ['oren;moish', '/-/v', '/barbi'] ['30.4.200', '6.99.5']... | From the re.split docs: If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. So just wrap your regex in a capturing group: print(re.split(r"(\d+\.\d+\.\d+)", s)) | 5 | 4 |
73,564,771 | 2022-9-1 | https://stackoverflow.com/questions/73564771/fastapi-is-very-slow-in-returning-a-large-amount-of-json-data | I have a FastAPI GET endpoint that is returning a large amount of JSON data (~160,000 rows and 45 columns). Unsurprisingly, it is extremely slow to return the data using json.dumps(). I am first reading the data from a file using json.loads() and filtering it per the inputted parameters. Is there a faster way to return... | One of the reasons for the response being that slow is that in your parse_parquet() method, you initially convert the file into JSON (using df.to_json()), then into dictionary (using json.loads()) and finally into JSON again, as FastAPI, behind the scenes, automatically converts the returned value into JSON-compatible ... | 5 | 13 |
73,567,187 | 2022-9-1 | https://stackoverflow.com/questions/73567187/how-do-i-change-the-size-of-the-flet-window-on-windows-or-specify-that-it-is-not | In Flet on Windows, I'm running the calc demo and trying to modify properties of the application window in Python. How do I change the size of the Flet window in code and specify that it should not be user resizable? (Ideally this post should be tagged with 'Flet' but the tag doesn't exist yet as the project's in it's ... | You can use this as an example import flet as ft def main(page: ft.Page): page.window.width = 200 # window's width is 200 px page.window.height = 200 # window's height is 200 px page.window.resizable = False # window is not resizable page.update() ft.app(target=main) | 4 | 13 |
73,600,082 | 2022-9-4 | https://stackoverflow.com/questions/73600082/how-to-reference-a-requirements-txt-in-the-pyproject-toml-of-a-setuptools-projec | I'm trying to migrate a setuptools-based project from the legacy setup.py towards modern pyproject.toml configuration. At the same time I want to keep well established workflows based on pip-compile, i.e., a requirements.in that gets compiled to a requirements.txt (for end-user / non-library projects of course). This h... | In setuptools 62.6 the file directive was made available for dependencies and optional-dependencies. Use dynamic metadata: [project] dynamic = ["dependencies"] [tool.setuptools.dynamic] dependencies = {file = ["requirements.txt"]} Note that the referenced file will use a requirements.txt-like syntax; each line must co... | 87 | 126 |
73,596,058 | 2022-9-3 | https://stackoverflow.com/questions/73596058/creating-an-sqlalchemy-engine-based-on-psycopg3 | I need to upgrade the following code to some equivalent code based on psycopg version 3: import psycopg2 from sqlalchemy import create_engine engine = create_engine('postgresql+psycopg2://', creator=connector) This psycopg2 URL worked like a charm, but: import psycopg # v3.1 from sqlalchemy import create_engine engine... | Just an update to the current answer: Sqlalchemy 2.0 has been released and it does support psycopg3. You need to upgrade to 2.0 to use it. Note the connection string will have to be changed from postgresql to postgresql+psycopg or SqlAlchemy will (at time of writing) try using psycopg2. See docs here for more info: htt... | 23 | 38 |
73,585,779 | 2022-9-2 | https://stackoverflow.com/questions/73585779/how-to-return-a-pdf-file-from-in-memory-buffer-using-fastapi | I want to get a PDF file from s3 and then return it to the frontend from FastAPI backend. This is my code: @router.post("/pdf_document") def get_pdf(document : PDFRequest) : s3 = boto3.client('s3') file=document.name f=io.BytesIO() s3.download_fileobj('adm2yearsdatapdf', file,f) return StreamingResponse(f, media_type="... | As the entire file data are already loaded into memory, there is no actual reason for using StreamingResponse. You should instead use Response, by passing the file bytes (use BytesIO.getvalue() to get the bytes containing the entire contents of the buffer), defining the media_type, as well as setting the Content-Dispos... | 8 | 14 |
73,616,000 | 2022-9-6 | https://stackoverflow.com/questions/73616000/hide-pandas-warning-sqlalchemy | I want to hide this warning UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy and I've tried import warnings warnings.simplefilter(action='ignore', category=UserWarning) impor... | I tried this and it doesn't work. import warnings warnings.filterwarnings('ignore') Therefore, I used SQLAlchemy (as the warning message wants me to do so) to wrap the psycopg2 connection. I followed the instruction here: SQLAlchemy for psycopg2 documentation A simple example: import psycopg2 import sqlalchemy import ... | 5 | 9 |
73,599,734 | 2022-9-4 | https://stackoverflow.com/questions/73599734/python-dataclass-one-attribute-referencing-other | @dataclass class Stock: symbol: str price: float = get_price(symbol) Can a dataclass attribute access to the other one? In the above example, one can create a Stock by providing a symbol and the price. If price is not provided, it defaults to a price which we get from some function get_price. Is there a way to referen... | You can use __post_init__ here. Because it's going to be called after __init__, you have your attributes already populated so do whatever you want to do there: from typing import Optional from dataclasses import dataclass def get_price(name): # logic to get price by looking at `name`. return 1000.0 @dataclass class Sto... | 10 | 13 |
73,550,398 | 2022-8-31 | https://stackoverflow.com/questions/73550398/how-to-download-a-large-file-using-fastapi | I am trying to download a large file (.tar.gz) from FastAPI backend. On server side, I simply validate the filepath, and I then use Starlette.FileResponse to return the whole file—just like what I've seen in many related questions on StackOverflow. Server side: return FileResponse(path=file_name, media_type='applicatio... | If you find yield from f being rather slow when using StreamingResponse with file-like objects, for instance: from fastapi import FastAPI from fastapi.responses import StreamingResponse some_file_path = 'large-video-file.mp4' app = FastAPI() @app.get('/') def main(): def iterfile(): with open(some_file_path, mode='rb')... | 5 | 17 |
73,589,431 | 2022-9-3 | https://stackoverflow.com/questions/73589431/value-of-field-type-must-be-one-of-4-in-a-modal-using-discord-py-2-0 | I am trying to show the user a Modal after they display a button, which contains a dropdown select menu from which they can choose multiple options. This code has functioned in the past, but is not causing an exception. Specifically: [2022-09-02 22:30:47] [ERROR ] discord.ui.view: Ignoring exception in view <TestButton... | ui.Modal does only support items with type 4, which is a ui.TextInput. Means ui.Select is not a supported item (yet). See Component Types table: Discord API Documentation The error is quite inaccurate, but it's intended that the error handling is not done better because of future purposes. See here: Add better errors... | 6 | 6 |
73,596,677 | 2022-9-4 | https://stackoverflow.com/questions/73596677/uwsgi-locking-up-after-a-few-requests-with-nginx-traefik-flask-app-running-over | Problem I have an app that uses nginx to serve my Python Flask app in production that only after a few requests starts locking up and timing out (will serve the first request or two quickly then start timing out and locking up afterwards). The Nginx app is served via Docker, the uwsgi Python app is served on barebones ... | This is no longer a problem and the solution is real frustrating - it was Docker's fault. For ~6 months there was a bug in Docker that was dropping connections (ultimately leading to the timeouts mentioned above) which was finally fixed in Docker Desktop 4.14. The moment I upgraded Docker (it had just come out at the t... | 4 | 6 |
73,604,954 | 2022-9-5 | https://stackoverflow.com/questions/73604954/error-when-using-python-kaleido-from-r-to-convert-plotly-graph-to-static-image | I am trying to use the R reticulate package to convert a plotly graph to a static image. I am using save_image/kaleido. Link to documentation for save_image / kaleido Initial setup: install.packages("reticulate") reticulate::install_miniconda() reticulate::conda_install('r-reticulate-test', 'python-kaleido') reticulate... | As @Salim B pointed out there is a workaround documented to call import sys in Python before executing save_img(): p <- plot_ly(x = 1:10) reticulate::py_run_string("import sys") save_image(p, "./pic.png") | 6 | 13 |
73,581,384 | 2022-9-2 | https://stackoverflow.com/questions/73581384/plotting-a-fancy-diagonal-correlation-matrix-with-coefficients-in-upper-triangle | I have the following synthetic dataframe, including numerical and categorical columns as well as the label column. I want to plot a diagonal correlation matrix and display correlation coefficients in the upper part as the following: expected output: Despite the point that categorical columns within synthetic dataset/d... | I'd be interested in a Pythonic solution. Use a seaborn scatter plot with matplotlib text/line annotations: Plot the lower triangle via sns.scatterplot with square markers Annotate the upper triangle via plt.text Draw the heatmap grid via plt.vlines and plt.hlines Full code using the titanic sample: import pandas ... | 10 | 1 |
73,593,712 | 2022-9-3 | https://stackoverflow.com/questions/73593712/calculating-similarities-of-text-embeddings-using-clip | I am trying to use CLIP to calculate the similarities between strings. (I know that CLIP is usually used with text and images but it should work with only strings as well.) I provide a list of simple text prompts and calculate the similarity between their embeddings. The similarities are off but I can't figure what I'm... | If you use the text embeddings from the output of CLIPTextModel ([number of prompts, 77, 512]), flatten them ([number of prompts, 39424]) and the apply cosine similarity, you'll get improved results. This code lets you test both solutions ([1,512] and [77,512]). I'm running it on Google Colab. !pip install -U torch tr... | 10 | 9 |
73,584,269 | 2022-9-2 | https://stackoverflow.com/questions/73584269/vertex-ai-automatic-retraining | I’m trying to create a Vertex AI endpoint with Monitoring enabled that can trigger a Vertex AI pipeline execution when one of the deployed models drops its performance. However, Vertex AI does not provide any built-in feature to do it. Is there a method to capture the alert thrown by Vertex AI Monitoring and trigger th... | The Vertex AI Model Monitoring jobs are logged as part of Cloud Logging 1. You can react to those loggings using log-based alerts 2. For that, you need to configure a notification channel to PubSub 3 Based on those PubSub message you can trigger a Cloud Function 4 The Cloud Function can initiate the Vertex AI Pipeline... | 4 | 3 |
73,622,815 | 2022-9-6 | https://stackoverflow.com/questions/73622815/gcp-python-delete-project-labels | I am trying to delete labels from projects, by using the UpdateProjectRequest. It says that it needs an 'update_mask', but I do not know how to created this mask. It is a google.protobuf.field_mask_pb2.FieldMask https://cloud.google.com/python/docs/reference/cloudresourcemanager/latest/google.cloud.resourcemanager_v3.t... | As you already mentioned, when you want to delete all labels, it requires an update mask for the labels field. Reviewing this documentation, please note that if a request is provided, this should not be set. Also, you will find a code example that might help you. Additionally, you should import filed_mask_pb2 if you wi... | 5 | 1 |
73,612,107 | 2022-9-5 | https://stackoverflow.com/questions/73612107/selenium-chromedrivermanager-webdriver-install-not-updating-through-proxy | I need to access a website using selenium and Chrome using python. Below is shortened version of my code. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service # PROXY='https://myproxy.com:3128' PROXY = 'https://username:password@my... | I have modified the code as follows. essentially i have now used custom download manager and this is worling from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.core.download_manager import WDMDownloadManager from webdriver_manager.core.http import HttpClient f... | 5 | 5 |
73,611,981 | 2022-9-5 | https://stackoverflow.com/questions/73611981/django-how-to-annotate-group-by-display-it-in-serializer | I have following Model class ModelAnswer(BaseModel): questions = models.ForeignKey( to=Question, on_delete=models.CASCADE ) answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) Basically usecase is answer can be added multiple time i.e at once 3 answer can be added and all answers neede... | View from collections import defaultdict class ListAnswerLogView(ListAPIView): serializer_class = AnswerLogSerializer def get_queryset(self): grouped_answers = defaultdict(lambda: dict(answer=set())) for answer_log in AnswerLog.objects.all(): grouped_by_key = ( answer_log.order, answer_log.answer.questions.category ) g... | 5 | 4 |
73,623,986 | 2022-9-6 | https://stackoverflow.com/questions/73623986/sqlalchemy-how-to-create-a-composite-index-between-a-polymorphic-class-and-its | I am trying to get a composite index working between a polymorphic subclass and it's parent. Alembic autogenerate does not seem to detect Indexes outside of __table_args__. I can't use __table_args__ because, being in the subclass, it does not count my class as having a __table__. How do I create a composite Index betw... | Create the index externally after both classes: class Main(Base, SomeMixin): __tablename__ = "main" __table_args__ = ( # Some constraints and Indexes specific to main ) id = Column(String, primary_key=True, default=func.generate_object_id()) mtype = Column(String, nullable=False) __mapper_args__ = {"polymorphic_on": mt... | 7 | 4 |
73,623,225 | 2022-9-6 | https://stackoverflow.com/questions/73623225/using-python-difflib-to-compare-more-than-two-files | I would like to get an overview over e.g. the ldd dependency list of multiple (3+) computers by comparing them with each other and highlighting the differences. For example, if I have a dict that looks as following: my_ldd_outputs = { 01:"<ldd_output>", 02:"<ldd_output>", ... 09:"<ldd_output>", 10:"<ldd_output>" } I w... | Pure Python solution, no libraries or extra dependencies. Note: this solutions works due some assumptions: Order of lines do not matter A line either exists, or is missing (no logic to check similarity between lines) from collections import defaultdict import re def transform(input): # differing hashvalues from ldd ... | 4 | 1 |
73,597,456 | 2022-9-4 | https://stackoverflow.com/questions/73597456/what-is-the-python-poetry-config-file-after-1-2-0-release | I have been using python-poetry for over a year now. After poetry 1.2.0 release, I get such an info warning: Configuration file exists at ~/Library/Application Support/pypoetry, reusing this directory. Consider moving configuration to ~/Library/Preferences/pypoetry, as support for the legacy directory will be removed ... | Looks like it is as simple as copy/pasting to the new directory. I got the same error after upgrading to Poetry 1.2. So I created a pypoetry folder in the new Preferences directory, copy/pasted the config.toml to it, and just to be safe, I renamed the original folder to: ~/Library/Application Support/pypoetry_bak After... | 14 | 16 |
73,624,959 | 2022-9-6 | https://stackoverflow.com/questions/73624959/pubkeyacceptedkeytypes-ssh-rsa-with-paramiko | Is there a way to have the same behavior with Paramiko, as when using ssh option: -o PubkeyAcceptedKeyTypes=+ssh-rsa | Paramiko uses ssh-rsa by default. No need to enable it. But if you have problems with public keys, it might be because recent versions of Paramiko first try rsa-sha2-*. And some legacy servers choke on that. So you likely rather want to disable the rsa-sha2-*. For that, see: Paramiko authentication fails with "Agreed u... | 4 | 1 |
73,616,963 | 2022-9-6 | https://stackoverflow.com/questions/73616963/runtimeerror-a-view-of-a-leaf-variable-that-requires-grad-is-being-used-in-an | I am working on some paper replication, but I am having trouble with it. According to the log, it says that RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation. However, when I check the line where the error is referring to, it was just a simple property setter inside the c... | In-place operation means the assignment you've done is modifiying the underlying storage of your Tensor, of which requires_grad is set to True, according to your error message. That said, your param.pdfvec[self.key] is not a leaf Tensor, because they will be updated during back-propagation. And you tried to assign a va... | 8 | 12 |
73,592,665 | 2022-9-3 | https://stackoverflow.com/questions/73592665/python-requests-get-post-with-data-over-ssl-truncates-the-response | For example take this app.py and run it with python3 -m flask run --cert=adhoc. from flask import Flask app = Flask(__name__) @app.route('/', methods=["GET", "POST"]) def hello_world(): return {"access_token": "aa" * 50000} How could sending data truncate the response? >>> import requests >>> len(requests.post('https:... | This is a weird one, and I confess I am not entirely sure if my answer is really correct in every detail. But it seems you might need to report this to Flask rather than requests... @app.route('/', methods=["GET", "POST"]) def hello_world(): print(f"hello_world: content_type: {request.content_type}, data: {request.data... | 4 | 3 |
73,626,888 | 2022-9-6 | https://stackoverflow.com/questions/73626888/function-not-being-called-in-main-function | I'm fairly new to python and I'm trying to build a game with Pygame. I kept having issues with collisions not being recognized. Here's the code I tried import pygame pygame.init() WIDTH, HEIGHT = (900, 500) WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Bong Pong') FPS = 60 WHITE = (255, 255... | Python has no concept of in-out parameters. The argument is passed by value. If you change ball_vel_x in the player_collision function, only the parameter changes, but the argument remains unchanged. You must return the new value of ball_vel_x from the function: def player_collision(player_1, player_2, game_ball, ball_... | 3 | 6 |
73,621,269 | 2022-9-6 | https://stackoverflow.com/questions/73621269/jax-jitting-functions-parameters-vs-global-variables | I've have the following doubt about Jax. I'll use an example from the official optax docs to illustrate it: def fit(params: optax.Params, optimizer: optax.GradientTransformation) -> optax.Params: opt_state = optimizer.init(params) @jax.jit def step(params, opt_state, batch, labels): loss_value, grads = jax.value_and_gr... | During JIT tracing, JAX treats global values as implicit arguments to the function being traced. You can see this reflected in the jaxpr representing the function. Here are two simple functions that return equivalent results, one with implicit arguments and one with explicit: import jax import jax.numpy as jnp def f_ex... | 5 | 7 |
73,616,848 | 2022-9-6 | https://stackoverflow.com/questions/73616848/getting-valueerror-input-contains-nan-when-using-package-pmdarima | I get the error ValueError: Input contains NaN, when I try to predict the next value of series by using ARIMA model from pmdarima. But the data I use didn't contains null values. codes: from pmdarima.arima import ARIMA tmp_series = pd.Series([0.8867208063423082, 0.4969678051201152, -0.35079875681211814, 0.0715619774320... | Downgrading the following packages will resolve this error: numpy==1.19.3 pandas==1.3.3 pmdarima==1.8.3 | 5 | 0 |
73,618,820 | 2022-9-6 | https://stackoverflow.com/questions/73618820/nested-loop-optimisation-in-python-for-a-list-of-50k-items | I have a csv file with roughly 50K rows of search engine queries. Some of the search queries are the same, just in a different word order, for example "query A this is " and "this is query A". I've tested using fuzzywuzzy's token_sort_ratio function to find matching word order queries, which works well, however I'm str... | Since what you are looking for are strings consisting of identical words (just not necessarily in the same order), there is no need to use fuzzy matching at all. You can instead use collections.Counter to create a frequency dict for each string, with which you can map the strings under a dict of lists keyed by their fr... | 5 | 1 |
73,614,379 | 2022-9-5 | https://stackoverflow.com/questions/73614379/how-do-i-use-piecewise-af%ef%ac%81ne-transformation-to-straighten-curved-text-line-cont | Consider the following image: and the following bounding contour( which is a smooth version of the output of a text-detection neural network of the above image ), so this contour is a given. I need to warp both images so that I end up with a straight enough textline, so that it can be fed to a text recognition neural... | If the goal is to just unshift each column, then: import numpy as np from PIL import Image source_img = Image.open("73614379-input-v2.png") contour_img = Image.open("73614379-map-v3.png").convert("L") assert source_img.size == contour_img.size contour_arr = np.array(contour_img) != 0 # convert to boolean array col_offs... | 5 | 3 |
73,604,732 | 2022-9-5 | https://stackoverflow.com/questions/73604732/selenium-webdriverexception-unknown-error-session-deleted-because-of-page-cras | Good morning, This is a duplicate of a similar post on StackOverflow WHICH DIDN'T have an answer that solved the problem for me. For the last couple of days, my Python-Selenium script which uses Chrome Driver 104 has been having issue while scrolling down on infinite scroll, dynamically-loaded pages. This script is use... | For everyone facing the same issue in the future. The problem isn't with the chrome driver, it is with the DOM getting too large that causes the V8 JS memory to break at a point and call the OOM. To fix this for me, I thought of using the Facebook mobile version and it actually worked. Facebook mobile version of the we... | 4 | 1 |
73,617,676 | 2022-9-6 | https://stackoverflow.com/questions/73617676/mypy-slow-when-using-vscodes-python-extension | When enabling mypy in vscode ("python.linting.mypyEnabled": true,), then any manual mypy commands become very slow and CPU intensive (10s before vs 3min after). It seems like the two mypy processes should be independent, or even aid each other through a cache, but they seem to be in each other's way. I noticed that fro... | I found that making vscode use a different cache directory resolves the problem. Consider adding e.g. the following to your settings.json: "python.linting.mypyArgs": [ "--cache-dir=.mypy_cache/.vscode" ], Bonus: by remaining within the default directory (mypy_cache), the second cache directory is ignored by git. | 5 | 6 |
73,617,305 | 2022-9-6 | https://stackoverflow.com/questions/73617305/django-rest-framework-attributeerror-got-attributeerror-when-attempting-to-ge | Got AttributeError when attempting to get a value for field Firstname in serializer NameSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. The original exception text was: 'QuerySet' object has no attribute Firstname. Error: serializers.py from res... | You need to add many=True in your serializer when initializing with multiple instances. myname = NameSerializer(names,many=True) | 3 | 9 |
73,569,894 | 2022-9-1 | https://stackoverflow.com/questions/73569894/permutation-based-alternative-to-scipy-stats-ttest-1samp | I would like to use a permutation-based alternative to scipy.stats.ttest_1samp to test if the mean of my observations is significantly greater than zero. I stumbled upon scipy.stats.permutation_test but I am not sure if this can also be used in my case? I also stumbled upon mne.stats.permutation_t_test which seems to d... | This test can be performed with permutation_test. With permutation_type='samples', it "permutes" the signs of the observations. Assuming data has been generated as above, the test can be performed as from scipy import stats def t_statistic(x, axis=-1): return stats.ttest_1samp(x, popmean=0, axis=axis).statistic res = s... | 4 | 5 |
73,599,970 | 2022-9-4 | https://stackoverflow.com/questions/73599970/how-to-solve-wkhtmltopdf-reported-an-error-exit-with-code-1-due-to-network-err | I'm using Django. This is code is in views.py. def download_as_pdf_view(request, doc_type, pk): import pdfkit file_name = 'invoice.pdf' pdf_path = os.path.join(settings.BASE_DIR, 'static', 'pdf', file_name) template = get_template("paypal/card_invoice_detail.html") _html = template.render({}) pdfkit.from_string(_html, ... | I solved this problem. Theare are 3 step to pass this problems. You need to set options {"enable-local-file-access": ""}. pdfkit.from_string(_html, pdf_path, options={"enable-local-file-access": ""}) pdfkit.from_string() can't load css from URL. It's something like this. <link rel="stylesheet" href="https://path/to/s... | 27 | 44 |
73,610,869 | 2022-9-5 | https://stackoverflow.com/questions/73610869/the-expanded-size-of-the-tensor-1011-must-match-the-existing-size-512-at-non | I have a trained a LayoutLMv2 model from huggingface and when I try to inference it on a single image, it gives the runtime error. The code for this is below: query = '/Users/vaihabsaxena/Desktop/Newfolder/labeled/Others/Two.pdf26.png' image = Image.open(query).convert("RGB") encoded_inputs = processor(image, return_te... | The error message tells you that the extracted text via ocr is longer (1011 tokens) than the underlying text model is able to handle (512 tokens). Depending on your task, you maybe can truncate your text with the tokenizer parameter truncation (the processor will pass this parameter to the tokenizer): import torch from... | 4 | 8 |
73,589,662 | 2022-9-3 | https://stackoverflow.com/questions/73589662/in-apache-beam-dataflows-writetobigquery-transform-how-do-you-enable-the-deadl | In this document, Apache Beam suggests the deadletter pattern when writing to BigQuery. This pattern allows you to fetch rows that failed to be written from the transform output with the 'FailedRows' tag. However, when I try to use it: WriteToBigQuery( table=self.bigquery_table_name, schema={"fields": self.bigquery_tab... | You can use a dead letter queue in the pipeline instead of let BigQuery catch errors for you. Beam proposes a native way for error handling and dead letter queue with TupleTags but the code is little verbose. I created an open source library called Asgarde for Python sdk and Java sdk to apply error handling for less co... | 3 | 4 |
73,609,583 | 2022-9-5 | https://stackoverflow.com/questions/73609583/efficient-ways-to-aggregate-and-replicate-values-in-a-numpy-matrix | In my work I often need to aggregate and expand matrices of various quantities, and I am looking for the most efficient ways to do these actions. E.g. I'll have an NxN matrix that I want to aggregate from NxN into PxP where P < N. This is done using a correspondence between the larger dimensions and the smaller dimensi... | Assuming you don't your indices don't have a regular structure I would do it try sparse matrices. import scipy.sparse as ss import numpy as np # your current array of indices g=np.array([[0,0],[1,1],[2,0],[3,1]]) # a sparse matrix of (data=ones, (row_ind=g[:,0], col_ind=g[:,1])) # it is one for every pair (g[i,0], g[i,... | 4 | 3 |
73,585,377 | 2022-9-2 | https://stackoverflow.com/questions/73585377/warning-401-error-credentials-not-correct-for-azure-artifact-during-pip-instal | When I attempt to install a package from our Azure DevOps Artifacts feed, I get the error: Command: pip install org-test-framework --index-url https://<company_url>/tfs/<orgname>/_packaging/<feedname>/pypi/simple/ The keyring prompts for username and password for the site once entered getting the error as below Error:... | You need to use PAT for authenticate as password. Create a Personal access token with Packaging > Read scope to authenticate into Azure DevOps. Refer to this official link for details: https://learn.microsoft.com/en-us/azure/devops/artifacts/quickstarts/python-packages?view=azure-devops#manually-configure-authenticatio... | 6 | 7 |
73,599,859 | 2022-9-4 | https://stackoverflow.com/questions/73599859/setting-environment-variable-when-running-python-unit-tests-inside-vscode | I'd like to execute code inside my unit tests conditioned on whether they're running from within VSCode or the command line. Is there a way to do so? The reasoning is to add additional visual feedback through cv2.imwrite statements, but to omit these when running a full regression from the command line or when running ... | Try defining environment variables by using .env files .env: MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS = 1 test1.py: import os from pathlib import Path from dotenv import find_dotenv, load_dotenv env_path = Path(".") / ".env" load_dotenv(dotenv_path=env_path, verbose=True) print(os.getenv("MY_ENVIRONMENT_SWITCH_FOR_WRI... | 3 | 5 |
73,605,095 | 2022-9-5 | https://stackoverflow.com/questions/73605095/why-the-grad-is-unavailable-for-the-tensor-in-gpu | a = torch.nn.Parameter(torch.ones(5, 5)) a = a.cuda() print(a.requires_grad) b = a b = b - 2 print('a ', a) print('b ', b) loss = (b - 1).pow(2).sum() loss.backward() print(a.grad) print(b.grad) After executing codes, the a.grad is None although a.requires_grad is True. But if the code a = a.cuda() is removed, a.grad ... | The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf T... | 5 | 2 |
73,599,783 | 2022-9-4 | https://stackoverflow.com/questions/73599783/vscode-pylance-auto-import-incorrect-root-path | Let's suppose that I have a project with this file structure: project_dir └── src ├── package1 │ └── module1.py └── package2 └── module2.py When I want to use some class from module1 in some other module I type something like class SomeNewClass(ClassFromModule1): # here I press ctrl-space to make auto-import ... When... | By default, if you import a module in src, it should look like the following (same effect as you want). So please check if the following settings in vscode are modified: Open Settings and search for Analysis: Auto Search Paths. This item is enabled (checked) by default. If it was modified to be off, turn it back on.... | 6 | 4 |
73,603,289 | 2022-9-4 | https://stackoverflow.com/questions/73603289/why-doesnt-parameter-type-dictstr-unionstr-int-accept-value-of-type-di | I have a type for a dictionary of variables passed to a template: VariablesDict = Dict[str, Union[int, float, str, None]] Basically, any dictionary where the keys are strings and the values are strings, numbers or None. I use this type in several template related functions. Take this example function: def render_templ... | The reason it doesn't work is that Dict is mutable, and a function which accepts a Dict[str, int|float|str|None] could therefore reasonably insert any of those types into its argument. If the argument was actually a Dict[str, str], it now contains values that violate its type. (For more on this, google "covariance/cont... | 10 | 11 |
73,599,594 | 2022-9-4 | https://stackoverflow.com/questions/73599594/asyncio-works-in-python-3-10-but-not-in-python-3-8 | Consider the following code: import asyncio sem: asyncio.Semaphore = asyncio.Semaphore(2) async def async_run() -> None: async def async_task() -> None: async with sem: await asyncio.sleep(1) print('spam') await asyncio.gather(*[async_task() for _ in range(3)]) asyncio.run(async_run()) Run with Python 3.10.6 (Fedora 3... | As discussed in this answer, pre-python 3.10 Semaphore sets its loop on __init__ based on the current running loop, while asyncio.run starts a new loop. And so, when you try and async.run your coros, you are using a different loop than your Semaphore is defined on, for which the correct error message really is got Fut... | 5 | 5 |
73,598,187 | 2022-9-4 | https://stackoverflow.com/questions/73598187/how-fix-python-import-error-in-vs-code-editor-when-using-a-dev-container | I've opened a project with the following structure in VS Code (1.71.0 on macOS, Intel) and activated a Dev Container (I've tried the default Python 3.9 and 3.10 containers from Microsoft, with and without using python3 -m venv ...): project/ .devcontainer/ devcontainer.json Dockerfile foo/ foo/ tests/ test_bar.py <-- I... | I often have this same issue with Python+Devcontainer. What works for me is: setting this env variable: export PYTHONPATH=/workspace, you can also try with /workspaces or /yourProjectName depending on your setup. restart the Python Language Server with Ctrl+Shift+P > Python: Restart Language Server. Note that you d... | 5 | 6 |
73,598,938 | 2022-9-4 | https://stackoverflow.com/questions/73598938/why-is-dataclass-field-shared-across-instances | First time using dataclass, also not really good at Python. The following behaviour conflicts with my understanding so far: from dataclasses import dataclass @dataclass class X: x: int = 1 y: int = 2 @dataclass class Y: c1: X = X(3, 4) c2: X = X(5, 6) n1 = Y() n2 = Y() print(id(n1.c1)) print(id(n2.c1)) n1.c1.x = 99999 ... | Why does c1 behave like a class variable? Because you specified default value for them and they're now a class attribute. In the Mutable Default Values section, it's mentioned: Python stores default member variable values in class attributes. But look at this: @dataclass class X: x: int = 1 y: int = 2 @dataclass cl... | 5 | 5 |
73,598,825 | 2022-9-4 | https://stackoverflow.com/questions/73598825/how-to-get-file-from-url-in-python | I want to download text files using python, how can I do so? I used requests module's urlopen(url).read() but it gives me the bytes representation of file. | When downloading text files with python I like to use the wget module import wget remote_url = 'https://www.google.com/test.txt' local_file = 'local_copy.txt' wget.download(remote_url, local_file) If that doesn't work try using urllib from urllib import request remote_url = 'https://www.google.com/test.txt' file = 'co... | 3 | 2 |
73,598,430 | 2022-9-4 | https://stackoverflow.com/questions/73598430/how-to-make-a-customized-grouped-dataframe-with-multiple-aggregations | I have a standard dataframe like the one below : Id Type Speed Efficiency Durability 0 Id001 A OK OK nonOK 1 Id002 A nonOK OK nonOK 2 Id003 B nonOK nonOK nonOK 3 Id004 B nonOK nonOK OK 4 Id005 A nonOK nonOK OK 5 Id006 A OK OK OK 6 Id007 A OK nonOK OK 7 Id008 B nonOK nonOK OK 8 Id009 C OK OK OK 9 Id010 B OK OK nonOK 10... | You could try as follows: out = df.groupby('Type').agg({col:'value_counts' for col in df.columns[2:]})\ .fillna(0).astype(int).sort_index().reset_index().rename( columns={'level_1':'Test'}) print(out) Type Test Speed Efficiency Durability 0 A OK 3 3 3 1 A nonOK 2 2 2 2 B OK 1 1 2 3 B nonOK 3 3 2 4 C OK 3 2 6 5 C nonOK ... | 5 | 3 |
73,563,677 | 2022-9-1 | https://stackoverflow.com/questions/73563677/setting-torch-nn-linear-diagonal-elements-zero | I am trying to build a model with a layer of torch.nn.linear with same input size and output size, so the layer would be square matrix. In this model, I want the diagonal elements of this matrix fixed to zero. Which means, during training, I don't want the diagonal elements to be changed from zero. I could only think o... | You can always implement your own layers. Note that all custom layers should be implemented as classes derived from nn.Module. For example: class LinearWithZeroDiagonal(nn.Module): def __init__(self, num_features, bias): super(LinearWithZeroDiagonal, self).__init__() self.base_linear_layer = nn.Linear(num_features, num... | 4 | 3 |
73,596,506 | 2022-9-4 | https://stackoverflow.com/questions/73596506/typex-is-list-vs-typex-list | In Python, suppose one wants to test whether the variable x is a reference to a list object. Is there a difference between if type(x) is list: and if type(x) == list:? This is how I understand it. (Please correct me if I am wrong) type(x) is list tests whether the expressions type(x) and list evaluate to the same obje... | The "one obvious way" to do it, that will preserve the spirit of "duck typing" is isinstance(x, list). Rather, in most cases, one's code won't be specific to a list, but could work with any sequence (or maybe it needs a mutable sequence). So the recomendation is actually: from collections.abc import MutableSequence ...... | 3 | 4 |
73,594,044 | 2022-9-3 | https://stackoverflow.com/questions/73594044/structural-pattern-matching-python-match-at-any-position-in-sequence | I have a list of objects, and want to check if part of the list matches a specific pattern. Consider the following lists: l1 = ["foo", "bar"] l2 = [{1, 2},"foo", "bar"] l3 = ["foo", "bar", 5] l4 = [{1,2},"foo", "bar", 5, 6] How would I match the sequence ["foo", "bar"] in all the different cases? My naive idea is: mat... | def struct_match(lst_target, lst_pattern): for i in range(len(lst_target)-(len(lst_pattern)-1)): if lst_target[i:i+len(lst_pattern)] == lst_pattern: print('matched!') break l1 = ["foo", "bar"] l2 = [{1, 2},"foo", "bar"] l3 = ["foo", "bar", 5] l4 = [{1,2},"foo", "bar", 5, 6] l5 = [{1,2},"foo", "baz", "bar", 5, 6] patt ... | 5 | 1 |
73,593,736 | 2022-9-3 | https://stackoverflow.com/questions/73593736/why-can-we-inherit-typing-namedtuple | After Python 3.6, we have typing.NamedTuple, which is a typed version of collections.namedtuple(), we can inherit it like a class: class Employee(NamedTuple): name: str id: int Compared with collections.namedtuple, this syntax is more beautiful, but I still can't understand its implementation, whether we look at typin... | typing.NamedTuple uses a really esoteric feature, __mro_entries__: If a base that appears in class definition is not an instance of type, then an __mro_entries__ method is searched on it. If found, it is called with the original bases tuple. This method must return a tuple of classes that will be used instead of this ... | 5 | 8 |
73,590,510 | 2022-9-3 | https://stackoverflow.com/questions/73590510/modulenotfounderror-no-module-named-requests-error-for-docker-run | I have created the docker image to run python script. Now when I run below command it throwing error. command in powershell: docker build -t pull_request_summary . Error: Traceback (most recent call last): File "/usr/app/src/./listPullRequest.py", line 1, in import requests ModuleNotFoundError: No module named 'request... | your container also must have requests installed on it In your docker file put this line RUN pip install requests | 3 | 5 |
73,572,941 | 2022-9-1 | https://stackoverflow.com/questions/73572941/writing-style-to-prevent-string-concatenation-in-a-list-of-strings | Suppose I have a list/tuple of strings, COLOURS = [ "White", "Black", "Red" "Green", "Blue" ] for c in COLOURS: # rest of the code Sometimes I forget placing a comma after each entry in the list ("Red" in the above snippet). This results in one "RedGreen" instead of two separate "Red" and "Green" list items. Since thi... | You're incorrect that "no IDE/text editor shows a warning/error". Pylint can identify this problem using rule implicit-str-concat (W1404) with flag check-str-concat-over-line-jumps. (And for that matter, there are lots of things that are valid Python that a linter will warn you about, like bare except: for example.) Pe... | 7 | 5 |
73,587,060 | 2022-9-2 | https://stackoverflow.com/questions/73587060/how-to-load-a-pandas-column-from-a-csv-file-with-lists-as-lists-and-not-as-strin | when I write a list in pandas when I read it, its dtype is string and not array, is there any way to write a column of list in such a way that be again array type when we read it? Here is what I mean: d=[['d',['A','B','C']],['p',['F','G']]] df=pd.DataFrame(d) df.to_csv('file.csv') when I run the following code, pd.rea... | one solution would be to run it through literal_eval. you make a dictionary with the column name as key and the converter function as value. and pass that into read_csv with the keyword converters Note that if your column has mixed data (also strings and other stuff) you might want to write a custom function which filt... | 3 | 6 |
73,563,804 | 2022-9-1 | https://stackoverflow.com/questions/73563804/what-is-the-recommended-way-to-instantiate-and-pass-around-a-redis-client-with-f | I'm using FastAPI with Redis. My app looks something like this from fastapi import FastAPI import redis # Instantiate redis client r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) # Instantiate fastapi app app = FastAPI() @app.get("/foo/") async def foo(): x = r.get("foo") return {"message": x}... | Depends will evaluate every time your function got a request, so your second example will create a new connection for each request. As @JarroVGIT said, we can use connection pooling to maintain the connection from FastAPI to Redis and reduce open-closing connection costs. Usually, I create a different file to define th... | 17 | 20 |
73,569,804 | 2022-9-1 | https://stackoverflow.com/questions/73569804/dataset-batch-doesnt-work-as-expected-with-a-zipped-dataset | I have a dataset like this: a = tf.data.Dataset.range(1, 16) b = tf.data.Dataset.range(16, 32) zipped = tf.data.Dataset.zip((a, b)) list(zipped.as_numpy_iterator()) # output: [(0, 16), (1, 17), (2, 18), (3, 19), (4, 20), (5, 21), (6, 22), (7, 23), (8, 24), (9, 25), (10, 26), (11, 27), (12, 28), (13, 29), (14, 30), (15,... | One thing you can try doing is something like this: import tensorflow as tf a = tf.data.Dataset.range(16) b = tf.data.Dataset.range(16, 32) zipped = tf.data.Dataset.zip((a, b)).batch(4).map(lambda x, y: tf.transpose([x, y])) list(zipped.as_numpy_iterator()) [array([[ 0, 16], [ 1, 17], [ 2, 18], [ 3, 19]]), array([[ 4,... | 6 | 1 |
73,582,293 | 2022-9-2 | https://stackoverflow.com/questions/73582293/airflow-external-api-call-gives-negsignal-sigsegv-error | I am calling weather API using Python script but the airflow task fails with error Negsignal.SIGSEGV. The Python script to call the weather API work fine when ran outside Airflow. DAG from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOpe... | I am afraid this is a problem with your machine. SIGSEGV is an indication of serious problem with the environment you run Airflow on, not Airflow itself. Neither Airflow nor the code of yours (Which might be the culprit) does not seem to use any low-level C-Code (Airflow for sure and your code is likely not to use it) ... | 5 | 2 |
73,578,690 | 2022-9-2 | https://stackoverflow.com/questions/73578690/how-to-load-custom-yolo-v-7-trained-model | How do I load a custom yolo v-7 model. This is how I know to load a yolo v-5 model : model = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5/runs/train/exp15/weights/last.pt', force_reload=True) I saw videos online and they suggested to use this : !python detect.py --weights runs/train/yolov7x-custom/weigh... | You cannot use attempt_load from the Yolov5 repo as this method is pointing to the ultralytics release files. You need to use attempt_load from Yolov7 repo as this one is pointing to the right files. # yolov7 def attempt_download(file, repo='WongKinYiu/yolov7'): # Attempt file download if does not exist file = Path(str... | 4 | 2 |
73,561,079 | 2022-8-31 | https://stackoverflow.com/questions/73561079/yet-another-combinations-with-conditions-question | I want to efficiently generate pairs of elements from two lists equal to their Cartesian product with some elements omitted. The elements in each list are unique. The code below does exactly what's needed but I'm looking to optimize it perhaps by replacing the loop. See the comments in the code for details. Any advice ... | About 5-6 times faster than the fastest in your answer's benchmark. I build sets of values that appear in both lists or just one, and combine them appropriately without further filtering. from itertools import product, combinations def pairs(list1, list2): a = {*list1} b = {*list2} ab = a & b return [ *product(a, b-a),... | 5 | 2 |
73,562,722 | 2022-8-31 | https://stackoverflow.com/questions/73562722/extending-generic-class-getitem-in-python-to-accept-more-params | How can one extend __class_getitem__ for a Python Generic class? I want to add arguments to __class_getitem__ while having some be propagated upwards to Generic.__class_getitem__. Please see the below code snippet for an example use case (that doesn't run): from typing import ClassVar, Generic, TypeVar T = TypeVar("T")... | As @juanpa.arrivillaga suggests, this is the way to go: from typing import ClassVar, Generic, TypeVar T = TypeVar("T") class Foo(Generic[T]): cls_attr: ClassVar[int] def __class_getitem__(cls, item: tuple[int, T]): cls.cls_attr = item[0] return super().__class_getitem__(item[1]) def __init__(self, arg: T): self.arg = a... | 4 | 3 |
73,570,416 | 2022-9-1 | https://stackoverflow.com/questions/73570416/python-multiprocessing-cant-pickle-local-object | i have read a little about multiprocessing and pickling problems, I have also read that there are some solutions but I don't really know how can they help to mine situation. I am building Test Runner where I use Multiprocessing to call modified Test Class methods. Modified by metaclass so I can have setUp and tearDown ... | As for your original question of why you are getting the pickling error, this answer summarizes the problem and offers solutions (similar to those already provided here). Now as to why you are receiving the IndexError, this is because you are not passing an instance of the class to the function (the self argument). A q... | 5 | 3 |
73,572,119 | 2022-9-1 | https://stackoverflow.com/questions/73572119/no-idea-how-to-exit-source-control-in-vscode | I was trying to connect my Python files. Didn't go as planned and for some reason started source control without a clue how to get back. Does anyone have a clue how I exit and just go back to normal? | You may have inadvertently clicked the Initialize Repository button. You can remove the source control by opening the directory in your File Manager and deleting the .git folder. That will remove the source control from your project. If you want to go further, you can right click on the source control icon: and then c... | 8 | 4 |
73,568,255 | 2022-9-1 | https://stackoverflow.com/questions/73568255/what-is-the-correct-way-to-obtain-explanations-for-predictions-using-shap | I'm new to using shap, so I'm still trying to get my head around it. Basically, I have a simple sklearn.ensemble.RandomForestClassifier fit using model.fit(X_train,y_train), and so on. After training, I'd like to obtain the Shap values to explain predictions on unseen data. Based on the docs and other tutorials, this s... | I think your question already contains a hint: explainer = shap.Explainer(model.predict, X_train) shap_values = explainer.shap_values(X_test) is expensive and most probably is a kind of an exact algo to calculate Shapely values out of a function. explainer = shap.Explainer(model, X_train) shap_values = explainer.shap_... | 8 | 12 |
73,566,774 | 2022-9-1 | https://stackoverflow.com/questions/73566774/group-by-and-combine-intersecting-overlapping-geometries-in-geopandas | I have a geopandas dataframe that has several rows with overlapping polygon geometries along with an index (unique and sequential). I want to merge the overlapping polygon geometries into a multi-polygon and keep the corresponding minimum index of the individual overlapping polygons. For example: The geodataframe is as... | I think this is what you had in mind: import geopandas as gpd # load your geodataframe .. # self join on geodataframe to get all polygon intersections intersects = gdf.sjoin(gdf, how="left", predicate="intersects") # dissolve intersections on right index indices using the minimum value intersects_diss = intersects.dis... | 3 | 7 |
73,567,100 | 2022-9-1 | https://stackoverflow.com/questions/73567100/pip-install-with-extra-index-url-to-requirements-txt | I have following install comand for a package: pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116 and would need to add this to my requirements.txt file. I have done it by adding this to the end of the file: -i https://download.pytorch.org/whl/cu116 torch torchvision tor... | Found the solution, the command you used and the requirements.txt file were NOT in fact the same. It works with a requirements.txt like this --extra-index-url https://download.pytorch.org/whl/cu116 torch torchvision torchaudio Turns out -i is not the same as --extra-index-url. Docs: https://pip.pypa.io/en/stable/refer... | 8 | 24 |
73,568,036 | 2022-9-1 | https://stackoverflow.com/questions/73568036/flake8-line-break-before-binary-operator-how-to-fix-it | I keep getting: W503 line break before binary operator Please help me fix my code, as I can't figure out what is wrong here: def check_actionable(self, user_name, op, changes_table): return any(user_name in row.inner_text() and row.query_selector( self.OPS[op]) is not None and row.query_selector(self.DISABLED) is not ... | the other (imo better) alternative to ignore (which resets the default ignore list) is to use extend-ignore by default both W503 and W504 are ignored (as they conflict and have flip-flopped historically). there are other rules which are ignored by default as well that you may want to preserve extend-ignore = ABC123 ig... | 6 | 18 |
73,568,980 | 2022-9-1 | https://stackoverflow.com/questions/73568980/how-to-get-pairwise-iterator-with-last-element-as-being-the-first | I am using the following function pairwise to get the iteration of ordered pairs. For example, if the iterable is a list [1, 2, 3, 4, 5, 6] then I want to get (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1). If I use the following function from itertools import tee, zip_longest def pairwise(iterable): "s -> (s0,s1), (s1... | zip_longest has fillvalue parameter return zip_longest(a, b, fillvalue=iterable[0]) or as suggested in the comments use the returned value of the next(b, None) in fillvalue def pairwise(iterable): a, b = tee(iterable) return zip_longest(a, b, fillvalue=next(b, None)) Output print(list(pairwise(lst))) # [(1, 2), (2, 3... | 5 | 7 |
73,567,411 | 2022-9-1 | https://stackoverflow.com/questions/73567411/ansible-molecule-python-not-found | I have some ansible roles and I would like to use molecule testing with them. When I execute command molecule init scenario -r get_files_uid -d docker I get the following file structure get_files_uid ├── molecule │ └── default │ ├── converge.yml │ ├── molecule.yml │ └── verify.yml ├── tasks │ └── main.yml └── vars └── ... | The default scaffold for role molecule role initialization uses quay.io/centos/centos:stream8 as the test instance image (see molecule/default/molecule.yml) This image does not have any /usr/bin/python3 file available: $ docker run -it --rm quay.io/centos/centos:stream8 ls -l /usr/bin/python3 ls: cannot access '/usr/bi... | 4 | 0 |
73,567,668 | 2022-9-1 | https://stackoverflow.com/questions/73567668/convert-numbers-in-millions-and-thousands-to-string-format | I have a column in my pandas dataframe: df = pd.DataFrame([[3000000, 2500000, 1800000, 800000, 500000]], columns=['Market value']) I want to convert the numbers in this column to a format with millions and hundred thousands, for example: 3000000 -> €3M 2500000 -> €2.5M 1800000 -> €1.8M 800000 -> €800K 500000 -> €500K... | You can apply this function to the column: def format(num): if num > 1000000: if not num % 1000000: return f'€{num // 1000000}M' return f'€{round(num / 1000000, 1)}M' return f'€{num // 1000}K' Testing: nums_list = [3000000, 2500000, 1800000, 800000, 500000] for num in nums_list: print(format(num)) Output: €3M €2.5M €... | 4 | 5 |
73,566,474 | 2022-9-1 | https://stackoverflow.com/questions/73566474/unable-to-locate-package-python-openssl | I'm trying to install Pyenv, and I'm running on Ubuntu 22.04 LTS. but whenever I run this command sudo apt install -y make build-essential libssl-dev zlib1g-dev \ libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev \ libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl \ git I ge... | Make sure your list of packages is updated (sudo apt update). Python openssl bindings are available in 22.04 in python3-openssl (link), so you can install it by running sudo apt install python3-openssl | 31 | 58 |
73,560,307 | 2022-8-31 | https://stackoverflow.com/questions/73560307/exclude-some-attributes-from-fields-method-of-dataclass | I have a python dataclass that looks something like: @dataclass class MyDataClass: field0: int = 0 field1: int = 0 # --- Some other attribute that shouldn't be considered as _fields_ of the class attr0: int = 0 attr1: int = 0 I'd like to write the class in such a way that, when calling dataclasses.fields(my_data:=MyDa... | Not the most elegant solution, but you may declare the non-field attributes as InitVar[int] and set them in a __post_init__() method. @dataclass class MyDataClass: field0: int = 0 field1: int = 0 # --- Some other attribute that shouldn't be considered as _fields_ of the class attr0: InitVar[int] = 0 attr1: InitVar[int]... | 5 | 4 |
73,559,902 | 2022-8-31 | https://stackoverflow.com/questions/73559902/flask-app-hello-run-error-no-such-option-app | TL;DR running flask --app from the command line results in Error: No such option: --app. The current version of Anaconda (at the time of this question) includes Flask version 1.x. Here is the code from the Flask hello world tutorial at: palletsprojects.com quickstart from flask import Flask app = Flask(__name__) @app.r... | Display your flask version with flask --version. Using the defaults from the anaconda package manager condata update flask won't update flask to 2.x. --app works in >=2.2.x. In my case, at the time of this post, conda search flask did not show anything past version 2.1.3. To get this version or the latest available, n... | 10 | 6 |
73,556,924 | 2022-8-31 | https://stackoverflow.com/questions/73556924/how-to-reorder-measures-in-customizing-hover-label-appearance-plotly | I'm making an interactive map, there is no problem with the map itself, there is a problem with the way the elements are located in the additional hover marks. Is there any way to change this order? Is it possible not to display latitude and longitude indicators there? Sample code: @st.cache(hash_funcs={dict: lambda _:... | This is covered here: https://plotly.com/python/hover-text-and-formatting/#disabling-or-customizing-hover-of-columns-in-plotly-express fig_map = px.scatter_mapbox( df_region_map, hover_name="Region name", hover_data={ "Confirmed":True, "Deaths":True, "Recovered":True, "Daily confirmed":True, "Daily deaths":True, "Dail... | 6 | 2 |
73,558,171 | 2022-8-31 | https://stackoverflow.com/questions/73558171/inheritance-with-dataclasses | I am trying to understand what are the good practices when using inheritance with dataclasses. Let's say I want an "abstract" parent class containing a set of variables and methods, and then a series of child classes that inherit these methods and the variables, where in each of them the variables have a different defa... | I would argue that #1 is the most correct method. For the example you showed, it appears to be irrelevant which method you use, but if you add a second variable, the differences become apparent. This is implicitly confirmed by the Inheritance section in the documentation. @dataclass class ParentClass: a: str b: str = "... | 5 | 3 |
73,558,036 | 2022-8-31 | https://stackoverflow.com/questions/73558036/add-label-multi-index-on-top-of-columns | Context: I'd like to add a new multi-index/row on top of the columns. For example if I have this dataframe: tt = pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]}) Desired Output: How could I make it so that I can add "Table X" on top of the columns A,B, and C? Table X A B C 0 1 4 7 1 2 5 8 2 3 6 9 Possible solutio... | If you want a data frame like you wrote, you need a Multiindex data frame, try this: import pandas as pd # you need a nested dict first dict_nested = {'Table X': {'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]}} # then you have to reform it reformed_dict = {} for outer_key, inner_dict in dict_nested.items(): for inner_key, values... | 6 | 2 |
73,557,943 | 2022-8-31 | https://stackoverflow.com/questions/73557943/mypy-fails-with-overloads-and-literals | I'm trying to understand typing.overload and have applied it in a simple case where I want a function that takes input x: Literal["foo", "bar"] and returns the list [x]. I'd like mypy to type the resulting list as list[Literal["foo"]] or list[Literal["bar"]] depending on the value of x. I know I could achieve this with... | Lists in Python are invariant. That means that, even if B is a subtype of A, there is no relation between the types list[A] and list[B]. If list[B] were allowed to be a subtype of list[A], then someone could come along and do this. my_b_list: list[B] = [] my_a_list: list[A] = my_b_list my_a_list.append(A()) print(my_b_... | 7 | 4 |
73,557,596 | 2022-8-31 | https://stackoverflow.com/questions/73557596/count-occurrences-of-stings-in-a-row-pandas | I'm trying to count the number of instances of a certain sting in a row in a pandas dataframe. In the example here I utilized a lambda function and pandas .count() to try and count the number of times 'True' exists in each row. Though instead of a count of 'True' it is just returning a boolean whether or not it exists ... | You can use np.where: df['count'] = np.where(df == 'True', 1, 0).sum(axis=1) Regarding why your apply returns a boolean: both any and all returns boolean, not numbers Edit: You can include df.isin for multiple conditions: df['count'] = np.where(df.isin(['True', 'False']), 1, 0).sum(axis=1) | 3 | 4 |
73,553,299 | 2022-8-31 | https://stackoverflow.com/questions/73553299/how-do-you-perform-conditional-operations-on-different-elements-in-a-pandas-data | Let's say I have a Pandas Dataframe of the price and stock history of a product at 10 different points in time: df = pd.DataFrame(index=[np.arange(10)]) df['price'] = 10,10,11,15,20,10,10,11,15,20 df['stock'] = 30,20,13,8,4,30,20,13,8,4 df price stock 0 10 30 1 10 20 2 11 13 3 15 8 4 20 4 5 10 30 6 10 20 7 11 13 8 15... | First, set up data frame and add some calculations: import pandas as pd import numpy as np df = pd.DataFrame(index=[np.arange(10)]) df['price'] = 10,10,11,15,20,10,10,11,15,20 df['stock'] = 30,20,13,8,4,30,20,13,8,4 df['stock_under_5'] = df['stock'] < 5 df['stock_over_25'] = df['stock'] > 25 df['cum_stock_under_5'] = d... | 4 | 1 |
73,551,471 | 2022-8-31 | https://stackoverflow.com/questions/73551471/deploying-django-channels-with-nginx | I am trying to deploy the Django application in AWS ubuntu os with Django channels, Using Nginx. I had configured the Django server in Nginx. But I don't know how to configure channels or Redis-server in Nginx. My nginx config is as follows: server { listen 80; server_name 52.77.215.218; location / { include proxy_par... | You will need to download Daphne. Daphne is a high-performance websocket server for Django channels. https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/daphne/ https://github.com/django/daphne https://channels.readthedocs.io/en/stable/deploying.html How you can run daphne: daphne -b 0.0.0.0 -p 8070 django_proj... | 4 | 4 |
73,516,000 | 2022-8-28 | https://stackoverflow.com/questions/73516000/is-there-a-way-to-cumulatively-and-distinctively-expand-list-in-polars | For distance, I want to accomplish conversion like below. df = pl.DataFrame({ "col": [["a"], ["a", "b"], ["c"]] }) ┌────────────┐ │ col │ │ --- │ │ list[str] │ ╞════════════╡ │ ["a"] │ │ ["a", "b"] │ │ ["c"] │ └────────────┘ ↓ ↓ ↓ ┌────────────┬─────────────────┐ │ col ┆ col_cum │ │ --- ┆ --- │ │ list[str] ┆ list[str]... | We can use the cumulative_eval expression. But first, let's expand your data so that we can include some other things that may be of interest. We'll include a group variable to show how the algorithm can be used with grouping variables. We'll also include an empty list to show how the algorithm will handle these. imp... | 5 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.