eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: 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 some reason I get this error File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__setattr__ AttributeError: 'MagicItem' object has no attribute '__fields_set__'  I'm not sure what's the problem, here is my code that generate all this:    I'm kinda lost right now cuz I don't see the error in such a simple code.

Answer: 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 in the init-method. One of those things being the setting of the __fields_set__ attribute. That is why you are getting that error. I suggest just completely removing your custom __init__ method. One of the main benefits of using Pydantic models is that you don't have to worry about writing boilerplate like this. Check out their documentation, it is really good in my opinion. PS: If you insist because you want to be able to initialize your MagicItem with positional arguments, you could just do this: class MagicItem(BaseModel): name: str damage: Damage def __init__(self, name: str, damage: Damage) -> None: super().__init__(name=name, damage=damage)
Question: 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 result: >>> ' '.strip() '' >>> '\n'.strip() '' >>> '\r'.strip() '' >>> '\v'.strip() '' >>> '\x1e'.strip() ''  In this related question, a user mentioned that the str.strip function works with a superset of ASCII whitespace characters (in other words, a superset of string.whitespace). More specifically, it works with all unicode whitespace characters. Moreover, I believe (but I'm just guessing, I have no proofs) that c.isspace() returns True for each character c that would also be removed by str.strip. Is that correct? If so, I guess one could just run c.isspace() for each unicode character c, and come up with a list of whitespace characters that are removed by default by str.strip. >>> ' '.isspace() True >>> '\n'.isspace() True >>> '\r'.isspace() True >>> '\v'.isspace() True >>> '\x1e'.isspace() True  Is my assumption correct? And if so, how can I find some proofs? Is there an easier way to know which specific characters are automatically removed by str.strip?

Answer: 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  As suggested in the comments, you may also print a table to check if str.strip(), str.split() and str.isspace() share the same behaviour about white spaces: c = 0 print("char\tstrip\tsplit\tisspace") while True: try: s = chr(c) except ValueError: break stripped = s != s.strip() splitted = not s.split() spaced = s.isspace() if (stripped or splitted or spaced): print(f"{hex(c)}\t{stripped}\t{splitted}\t{spaced}", flush=True) c+=1  If I run the code above I get: char strip split isspace 0x9 True True True 0xa True True True 0xb True True True 0xc True True True 0xd True True True 0x1c True True True 0x1d True True True 0x1e True True True 0x1f True True True 0x20 True True True 0x85 True True True 0xa0 True True True 0x1680 True True True 0x2000 True True True 0x2001 True True True 0x2002 True True True 0x2003 True True True 0x2004 True True True 0x2005 True True True 0x2006 True True True 0x2007 True True True 0x2008 True True True 0x2009 True True True 0x200a True True True 0x2028 True True True 0x2029 True True True 0x202f True True True 0x205f True True True 0x3000 True True True  So, at least in python 3.10.4, your assumption seems to be correct.
Question: 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.

Answer: 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 import choice, shuffle sequences = [list(combo) for combo in combine(range(2, 6+1), 10) if sum(combo) == 40] def get_random_sequence_of_sum_40(): seq = choice(sequences) shuffle(seq) return seq # ... later when you need random sequences of sum=40 for i in range(10): rand_sequence = get_random_sequence_of_sum_40() print(f"The sum of {rand_sequence} is {sum(rand_sequence)}")  Sample output: The sum of [6, 3, 4, 4, 3, 3, 4, 6, 5, 2] is 40 The sum of [3, 3, 5, 3, 5, 5, 3, 3, 5, 5] is 40 The sum of [3, 3, 6, 3, 4, 6, 3, 4, 4, 4] is 40 The sum of [6, 6, 5, 3, 4, 3, 3, 2, 4, 4] is 40 The sum of [5, 2, 2, 4, 4, 4, 5, 4, 4, 6] is 40 The sum of [4, 4, 4, 3, 4, 4, 3, 6, 4, 4] is 40 The sum of [4, 4, 5, 4, 2, 4, 4, 5, 5, 3] is 40 The sum of [4, 2, 6, 2, 5, 6, 2, 5, 4, 4] is 40 The sum of [3, 6, 3, 4, 3, 3, 4, 4, 6, 4] is 40 The sum of [2, 2, 6, 2, 3, 5, 6, 4, 4, 6] is 40
Question:  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", "ObjectType": "Document", "InputContextKey": "Mr.Dave_HDFC.pdf2022-08-010T09:40:06.429358" }, { "DocumentCode": "F16", "ObjectType": "Document", "InputContextKey": "Mr.Dave_F16.pdf2022-08-010T09:40:06.429358" } ] } }   I want to add the UUID by index to the ['ConsolidationInformation']['Input'] and inside individual Input as DocumentUUID, how can I map it using a for a loop. I tried searching on the internet but could not find a solution that could satisfy this nested condition. Expected output  { "R_Id": 304, "ContextKey": "Mr.Dave", "ConsolidationInformation": { "Input": [ { "DocumentCode": "BS", "ObjectType": "Document", "InputContextKey": "Mr.Dave_HDFC.pdf2022-08-010T09:40:06.429358", "DocumentUUID": "b8f2904b-dafd-4be3-9615-96bac8e16c7f" }, { "DocumentCode": "F16", "ObjectType": "Document", "InputContextKey": "Mr.Dave_F16.pdf2022-08-010T09:40:06.429358", "DocumentUUID": "1240ad39-4815-480f-8cb2-43f802ba8d4e" } ] } }   I tried something like the below, but it resulted in  Traceback (most recent call last): File "<string>", line 26, in <module> KeyError: 0   Code  uuid = { "UUID": [ "b8f2904b-dafd-4be3-9615-96bac8e16c7f", "1240ad39-4815-480f-8cb2-43f802ba8d4e" ] } document = { "R_Id": 304, "ContextKey": "Mr.Dave", "ConsolidationInformation": { "Input": [ { "DocumentCode": "BS", "ObjectType": "Document", "InputContextKey": "Mr.Dave_HDFC.pdf2022-08-010T09:40:06.429358" }, { "DocumentCode": "F16", "ObjectType": "Document", "InputContextKey": "Mr.Dave_F16.pdf2022-08-010T09:40:06.429358" } ] } } for i, document in enumerate(document): uuid = uuid[i] print(f"${uuid} for 1 {document}") 

Answer: 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 can use the zip function. You can learn more about this function here. Here is an example of how you may apply the function to your code: for u, doc in zip(uuid['UUID'], document['ConsolidationInformation']['Input']): doc['DocumentUUID'] = u  Output: The output is as follows: { "R_Id":304, "ContextKey":"Mr.Dave", "ConsolidationInformation":{ "Input":[ { "DocumentCode":"BS", "ObjectType":"Document", "InputContextKey":"Mr.Dave_HDFC.pdf2022-08-010T09:40:06.429358", "DocumentUUID":"b8f2904b-dafd-4be3-9615-96bac8e16c7f" }, { "DocumentCode":"F16", "ObjectType":"Document", "InputContextKey":"Mr.Dave_F16.pdf2022-08-010T09:40:06.429358", "DocumentUUID":"1240ad39-4815-480f-8cb2-43f802ba8d4e" } ] } }
Question: 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, and so is different every time we run the build. Our Dockerfile starts something like this: FROM python:3.9 WORKDIR /project COPY poetry.lock pyproject.toml RUN pip install poetry ARG CI_JOB_TOKEN RUN poetry config http-basic.gitlab-pypi-repo gitlab-ci-token ${CI_JOB_TOKEN} RUN poetry install --no-interaction  Now because we're using poetry and the versions are locked in poetry.lock, when we get to the poetry steps we shouldn't need to reinstall poetry unless the poetry.lock file has changed, but because the CI_JOB_TOKEN is always different we always miss the cache and have to rebuild poetry and everything downstream (which is actually where most of the work is) as well. So is there a way that we can pass CI_JOB_TOKEN into the docker build but in a way that is ignored for the purposes of the cache? Or maybe there's another way to achieve this?

Answer: 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 the secret into the build using the --secret flag. On the first run, you'll see the RUN instruction executed and if you were to inspect the .foo file, it would contain the secret (because we echoed it to the file in the RUN command -- in practice, this might be your poetry configuration, for example). $ echo -n supersecret > ../secret.txt $ docker build --secret id=mysecret,src=../secret.txt -t test . # ... => [3/4] RUN --mount=type=secret,id=mysecret echo "$(cat /run/secrets/mysecret)" > .foo 0.2s => [4/4] RUN echo "another layer" > .bar 0.4s # ...  Even if your secret changes, on subsequent runs, you'll see the relevant layers still remain cached: $ echo -n newvalue > ../secret.txt $ docker build --secret id=mysecret,src=../secret.txt -t test . # ... => CACHED [3/4] RUN --mount=type=secret,id=mysecret echo "$(cat /run/secrets/mysecret)" > .foo 0.0s => CACHED [4/4] RUN echo "another layer" > .bar 0.0s # ...  Of course, because the RUN instruction was cached, you would see the old secret value in .foo in the resulting build.  As a separate note, you should be aware that your poetry config command is writing to disk. This means that your secret will be contained in the resulting image layers, which may not be ideal from a security standpoint.
Question: 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: str user_id: int = Field(foreign_key="user.id")  How can I enforce that name should be unique for a given user_id ?

Answer: 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(SQLModel, table=True): id: int = Field(primary_key=True) ... class SubAccount(SQLModel, table=True): __table_args__ = ( UniqueConstraint("name", "user_id", name="your_unique_constraint_name"), ) id: int = Field(primary_key=True) name: str description: str user_id: int = Field(foreign_key="user.id") if __name__ == '__main__': engine = create_engine("sqlite:///:memory:", echo=True) SQLModel.metadata.create_all(engine)  SQLModel even re-imports compatible classes/functions from SQLAlchemy explicitly to indicate that they can be used the way you expect it from SQLAlchemy. This is not to say that this works with everything. Far from it. The project is still in its earliest stages. But in this case it does. Here is the corresponding SQL output for creating the table: CREATE TABLE subaccount ( id INTEGER NOT NULL, name VARCHAR NOT NULL, description VARCHAR NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (id), CONSTRAINT your_unique_constraint_name UNIQUE (name, user_id), FOREIGN KEY(user_id) REFERENCES user (id) )
Question: 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 the list. Otherwise would add "No", resulting in this dataframe:  Name Country Is it valid? 0 John BR Yes 1 Peter BR Yes 2 Paul BR No 3 James CZ No 4 Jonatan CZ Yes 5 Maria DK No  Is there any way I could do it? Thanks!

Answer: 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 Yes 1 Peter BR Yes 2 Paul BR No 3 James CZ No 4 Jonatan CZ Yes 5 Maria DK No
Question: 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 have @router.get("/holidays/",response_model = List[HolidayDateSchema])  The response I want to get is [ { "date": "2021-08-14", "name": "Independence Day", "holidays": { "year": 2022, "month":5, "country":"pk", "language":"en"}, "id": 13 }, ]  Right now it doesn't support the pydantic schema with response model, I don't know why and it gives error  pydantic.error_wrappers.ValidationError: 2 validation errors for HolidayDateSchema and value is not a valid dict It would be great if anyone can specify the best to get deeply nested JSON objects with response_model.

Answer: 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 and inherit from that instead if you want the setting for all your models.
Question: 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 variable assignment in general or Python's pass-by-sharing behavior or just something else entirely  Here's the simplified code: class Holder: def __init__(self, val=0): self.val = val class Solution: def runThis(self): holder = Holder() self.diveDeeper(holder, 5) return def diveDeeper(self, holder, n): if n==0: return 1 # 1) Doesn't result in mutation holder.val += self.diveDeeper(holder, n-1) # 2) Also doesn't result in mutation # holder.val = holder.val + self.diveDeeper(holder, n-1) # 3) !! Results in mutations # returnVal = self.diveDeeper(holder, n-1) # holder.val += returnVal print(holder.val) return 1 a = Solution() a.runThis()  So yeah my main source of confusion is how (1) and (3) look semantically identical to me but results in two completely different outcomes: ================ RESTART: Case 1 =============== 1 1 1 1 1 >>> ================ RESTART: Case 3 =============== 1 2 3 4 5 >>>  From (2), it doesn't seem related to the += operator and for brevity, I haven't included the tens of variations I've tried but none of them have given me any leads so far. Would really appreciate any pointers in the right direction (especially in case I get blindsided in job interviews lmao) PS: In case this is relevant, I'm using Python 3.8.2

Answer: 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 call, which means that no matter the iteration, left == 0. Your solution 3 is equivalent to: right = self.diveDeeper(holder, n - 1) left = holder.val holder.val = left + right  So the recursive call is made before left = holder.val is evaluated, which means left is now the result of the sum of the previous iteration. This is why you have to be careful with mutable state, you got to understand the order of operations perfectly.
Question: 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 altura = 200 posx = int(principal.winfo_screenwidth() / 2 - largura / 2) posy = int(principal.winfo_screenheight() / 2 - altura / 1.2) principal.geometry("{0}x{1}+{2}+{3}".format(largura, altura, posx, posy)) frm_login = ttk.Frame(principal) frm_login.pack(side="left") lb_usuario = ttk.Label(frm_login, text="Usuário") lb_usuario.grid(row=0, column=0, padx=5, pady=5, sticky="e") ed_usuario = ttk.Entry(frm_login, width=24) ed_usuario.grid(row=0, column=1, sticky="w") lb_senha = ttk.Label(frm_login, text="Senha") lb_senha.grid(row=1, column=0, padx=5, pady=5, sticky="e") ed_senha = ttk.Entry(frm_login, width=24) ed_senha.grid(row=1, column=1, sticky="w") frm_botoes = ttk.Frame(frm_login) frm_botoes.grid(row=2, column=1, pady=5, sticky="w") bt_entrar = ttk.Button(frm_botoes, text="Entrar") bt_entrar.grid(row=1, column=1) bt_sair = ttk.Button(frm_botoes, text="Sair") bt_sair.grid(row=1, column=2) principal.mainloop()  

Answer: 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 specified are going to be in the frame with equal weight if all are configured the same. This code should work: Note: You can use padx and pady if the frame is expanding too much. Use them when you are calling grid() but entirely depends on your purpose. import tkinter as tk from tkinter import ttk principal = tk.Tk() principal.title("Login") principal.resizable(False, False) largura = 300 altura = 200 posx = int(principal.winfo_screenwidth() / 2 - largura / 2) posy = int(principal.winfo_screenheight() / 2 - altura / 1.2) principal.geometry("{0}x{1}+{2}+{3}".format(largura, altura, posx, posy)) principal.rowconfigure(0, weight=1) principal.columnconfigure(0, weight=1) frm_login = ttk.Frame(principal) frm_login.grid(row=0, column=0, sticky="nsew") frm_login.rowconfigure((0, 1, 2), weight=1) frm_login.columnconfigure((0, 1, 2), weight=1) lb_usuario = ttk.Label(frm_login, text="Usuário") lb_usuario.grid(row=0, column=0, padx=5, pady=5, sticky="e") ed_usuario = ttk.Entry(frm_login, width=24) ed_usuario.grid(row=0, column=1, sticky="w") lb_senha = ttk.Label(frm_login, text="Senha") lb_senha.grid(row=1, column=0, padx=5, pady=5, sticky="e") ed_senha = ttk.Entry(frm_login, width=24) ed_senha.grid(row=1, column=1, sticky="w") frm_botoes = ttk.Frame(frm_login) frm_botoes.grid(row=2, column=1, pady=5, sticky="w") bt_entrar = ttk.Button(frm_botoes, text="Entrar") bt_entrar.grid(row=1, column=1) bt_sair = ttk.Button(frm_botoes, text="Sair") bt_sair.grid(row=1, column=2) principal.mainloop()  Hopefully this answers your question.
Question: 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 INFO: 127.0.0.1:62158 - "OPTIONS /api/v1/feature-requests HTTP/1.1" 200 OK INFO: 127.0.0.1:62160 - "GET /api/v1/feature-requests HTTP/1.1" 200 OK INFO: 127.0.0.1:62158 - "OPTIONS /api/v1/feature-requests-meta HTTP/1.1" 200 OK INFO: 127.0.0.1:62160 - "GET /api/v1/feature-requests-meta HTTP/1.1" 200 OK INFO: 127.0.0.1:62160 - "GET /api/v1/feature-requests/febbbc21-9650-44e6-8df5-80c8bb33b6ea HTTP/1.1" 200 OK INFO: 127.0.0.1:62160 - "GET /api/v1/feature-requests-meta/febbbc21-9650-44e6-8df5-80c8bb33b6ea HTTP/1.1" 200 OK  However, when deployed as a Lambda function the logs are not there: 2022-09-07T10:44:57.426+02:00 START RequestId: fd44ae47-5bfb-42e3-aeb4-d9f29857bb39 Version: $LATEST 2022-09-07T10:44:57.604+02:00 END RequestId: fd44ae47-5bfb-42e3-aeb4-d9f29857bb39 2022-09-07T10:44:57.604+02:00 REPORT RequestId: fd44ae47-5bfb-42e3-aeb4-d9f29857bb39 Duration: 177.85 ms Billed Duration: 178 ms Memory Size: 2048 MB Max Memory Used: 152 MB Init Duration: 1733.88 ms 2022-09-07T10:45:00.299+02:00 START RequestId: 08a7a6da-c2c6-446c-baa3-1d08c9816f5b Version: $LATEST 2022-09-07T10:45:00.318+02:00 END RequestId: 08a7a6da-c2c6-446c-baa3-1d08c9816f5b  Even for the logs that are produced by our code (as opposed to the framework) are not visible when running as a Lambda function. Configuration: In app.py LOG = logging.getLogger() log_format = "%(asctime)s %(levelname)s %(message)s" log_date_fmt = "%Y-%m-%d %H:%M:%S" logging.basicConfig( format=log_format, level=logging.INFO, datefmt=log_date_fmt, )  In every other Python file: LOG = logging.getLogger(__name__)  logging.conf [loggers] keys=root,api,config [handlers] keys=console_handler [formatters] keys=normal_formatter [logger_root] level=INFO handlers=console_handler [logger_api] level=INFO handlers=console_handler qualname=api propagate=0 [logger_config] level=INFO handlers=console_handler qualname=config propagate=0 [handler_console_handler] class=StreamHandler level=INFO formatter=normal_formatter args=(sys.stdout,) [formatter_normal_formatter] format=%(asctime)s %(levelname)s %(name)s %(message)s datefmt=%Y-%m-%d %H:%M:%S  I am not sure what else needs to happen to get the logs in CloudWatch.

Answer: 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__)