eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: This answer did not work for me, nor for some Mac users, and I did not find a working solution among the following similar questions:  How to open an image in Python and close afterwards? How to Close an Image? How can I close an image shown to the user with the Python Imaging Library? How do I close figure in matplotlib? How can I close an image shown to the user with the Python Imaging Library? How to use user input to display image?  How can one open an image in Python, then let the user answer questions about it in the CLI, and close the image afterwards? Contstaints  Don't use sub-process. Don't start killing processes that happen to match a substring. In essence, use a Python-only method that opens an image and then closes that, and only that image, with control, whilst allowing other code (that allows user interaction) to be executed in between. 

Answer: The answer below opens an image from a file path in a separate Window, then asks the questions in the CLI. After the questions are answered by the user, the image is closed. Requirements pip install tensorflow pip install matplotlib  Solution def make_receipt_label(img_filepath): """ Opens an image, asks the user questions about it, and returns the answers. Args: img_filepath: The path to the image file. Returns: A dictionary containing the user's answers to the questions. Returns None if there is an issue opening the image. """ from tensorflow import io from tensorflow import image as img from matplotlib import pyplot as plt tensor_img = io.read_file(img_filepath) tensor_img = img.decode_png(tensor_img, channels=3) plt.ion() plt.imshow(tensor_img) plt.show(block=False) root=tk.Tk() root.withdraw() answers = {} answers["image_colour"] = input("0. What is the image colour? ") answers["total"] = input("1. Another question? ") plt.close() plt.ioff() root.destroy() return answers  Satisfied constraints It does not use subproces it does not try to kill processes with a pid that matches some string, it uses pure Python.
Question: I'm validating inputs to a function using Pydantic's @validate_call as follows: from typing import Literal from pydantic import validate_call @validate_call def foo(a: Literal[0, 90, 180, 270]) -> None: print(a, type(a))  I want Pydantic to perform its default type coercion like it does with the int type: foo(90) # Works as expected foo('90') # Doesn't work, but I want it to  If I use the annotation a: int, it will coerce strings like '180', but then I have to manually validate which integers are given. How do I make Pydantic perform type coercion on Literals? Note: I'll accept a solution that requires a to be a string type instead of an integer, as long as it still allows both integer and string input.  Bad Solutions  I don't want to add every literal case. Literal[0, 90, 180, 270, '0', '90', '180', '270'] is bad because it doesn't allow the strings '-0' or '180.0'.  I could do Annotated[int, Field(ge=0, le=0)] | Annotated[int, Field(ge=90, le=90)] | ..., but that's stupidly verbose.  I don't want to define some separate function or model. At that point, it's easier to just accept a: int and validate the particular value inside the method.  

Answer: You can combine the BeforeValidator and the Literal like this: from typing import Annotated, Literal from pydantic import validate_call, BeforeValidator, ValidationError # First try has the following validator: # BeforeValidator(int) @validate_call def foo(a: Annotated[Literal[0, 90, 180, 270], BeforeValidator(float)]) -> None: print(a, type(a)) if __name__ == "__main__": foo("90") foo("180.0") foo("180.0") try: foo(0.1) except ValidationError as err: print(err) try: foo("70") except ValidationError as err: print(err) try: foo("can't convert to int") except ValueError as err: print(err)  The BeforeValidator function will be called before checks and thus the literal validation will be done against an integer. Edit: better manage string with decimal number.
Question: I have really large ASCII file (63 million lines or more) that I would like to read using numpy.genfromtxt(). But, it is taking up so much memory. I want to know what python actually does when numpy.genfromtxt() is executed. Does it read all the lines at once? Look at the below code, for example. import numpy as np data = np.genfromtxt("large.file.txt")  When I execute the code above, would python read all the contents in large.file.txt and load it on to the memory? If yes, is there another way of reading a large file line-by-line so that python would not use large memory?

Answer: It reads all the lines. It has to. That data array has to hold all of the file's data, and NumPy can't build an array with all of the file's data without reading all of the file. That said, the implementation uses a lot more memory than the output needs. The implementation parses the requested columns of the file's data into a list of tuples before applying further processing, and a list of tuples takes a lot more memory than a NumPy array. If you want to use less intermediate memory, I think numpy.loadtxt is more efficient on that front - digging down into the implementation eventually hits a function that stores parsed data into an array directly, instead of using a list of tuples. numpy.loadtxt isn't as flexible as numpy.genfromtxt, but you don't seem to need the extra flexibility. This won't make data itself take any less memory, though. Also, numpy.loadtxt does still need extra intermediate memory. It should just be less intermediate memory than numpy.genfromtxt.
Question: This is a strange issue. I maintain the pi3d python module and it contains this file github.com/tipam/pi3d/blob/master/src/pi3d/util/icons/pointer.png When I clone the repo locally it has the .png file but when the package is installed using pip it seems to be missing. This didn't used to be a problem. Is it something to do with the fact that pip insists on installing to a venv now, i.e. if I made pip install with --no-warn-script-location would it include the missing file?

Answer: It's because it's not present in tool.setuptools.package-data in pyproject.toml file. [tool.setuptools.package-data] "*" = ["*.fs", "*.vs", "*.inc", "*.gif"]  With the previous configuration, you add all this extensions in your package as you can see in the next screenshot (content of the package uploaded on pypi).  So adding the png extension should work: [tool.setuptools.package-data] "*" = ["*.fs", "*.vs", "*.inc", "*.gif", "*.png"]
Question: I have a parent Python task that starts a child task to listen for a USB/BLE response. Problem is that if the parent task dies, the child listener task keeps running and the process has to be killed. Parent Process:  self.listenerTask = threading.Thread(target=self.listener, name="Listener", args=[interface])  Listener thread:  def listener(self, interface): logger.info(f"Listener started, threadid={threading.get_ident()}") self.event = threading.Event() while not self.stopListener: responseMsg = asyncio.run((interface.readMsg(timeout=None))) ...  Anyway to catch the parent in it's death and have it set self.stopListener? Any better way?

Answer: you can mark your listener thread as a daemon so that if the main (parent) process exits, the listener will automatically be killed. For example: # In your parent process where you create the thread self.listenerTask = threading.Thread( target=self.listener, name="Listener", args=[interface], daemon=True # Ensure the thread is a daemon thread ) self.listenerTask.start()  Daemon threads are abruptly stopped when the main thread exits, so you won’t have a stranded listener. However, note that daemon threads don’t execute cleanup code upon termination. If you need a graceful shutdown, you might need to signal the thread from your parent’s signal handler or exception handling logic, ensuring you set self.stopListener = True when appropriate.
Question: I am coding a small project that goes through every class and prints them in the fashion of the Exception hierarchy at the very bottom of https://docs.python.org/3/library/exceptions.html. I got it to a readable point(not finished), and saw something interesting. It was a class called MISSING. I looked it up, nothing. Asked AI, and it denied it. Is it possible that my code just messed up? It didn't produce an error like TypeError, NameError, or AttributeError, like other classes did(when they didn't have subclasses). It isn't the NoneType class(that AI said it was), as that is also present as shown in this screenshot. When I try to access it by typing MISSING, it doesn't show as green, rather white as an undefined variable would. This isn't important, per say, but I'm just curious if anyone else has seen this before. As I said earlier, I looked it up and found nothing about it. Here is the code that reproduces this: class subclasses: def __init__(self): self.sub = self.get_all_subclasses(object) def get_all_subclasses(self, cls): try: all_subclasses = {cls.__name__: []} for subclass in cls.__subclasses__(): if subclass.__name__ == 'subclasses': continue if subclass.__name__ == 'MISSING': print('MISSING IIITTTTTTT', subclass) all_subclasses[cls.__name__].append(self.get_all_subclasses(subclass)) return all_subclasses except (TypeError, NameError, AttributeError): return {cls.__name__: []} subs = subclasses() 

Answer: Ok, first, actually retreive the class: In [1]: def search_for_missing(cls): ...: if isinstance(cls, type): ...: subclasses = type.__subclasses__(cls) ...: else: ...: subclasses = cls.__subclasses__() ...: for sub in subclasses: ...: if sub.__name__ == "MISSING": ...: return sub ...: subsub = search_for_missing(sub) ...: if subsub is not None: ...: return sub ...: return None ...: In [2]: m = search_for_missing(object) In [3]: m Out[3]: Token.MISSING  Now, try to find the module, In [4]: m.__module__ Out[4]: 'Token' In [5]: import sys In [6]: sys.modules[m.__module__] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[21], line 1 ----> 1 sys.modules[m.__module__] KeyError: 'Token'  Ok, this means it is almost certainly a built-in class used by the interpreter runtime. Next step, let's check the CPython source code, I did a query for the string "MISSING" and found this in the source code: PyTypeObject _PyContextTokenMissing_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "Token.MISSING", sizeof(_PyContextTokenMissing), .tp_dealloc = context_token_missing_tp_dealloc, .tp_getattro = PyObject_GenericGetAttr, .tp_flags = Py_TPFLAGS_DEFAULT, .tp_repr = context_token_missing_tp_repr, };  This is in cpython/Python/context.c which I'm pretty sure is for the contextvars module. If we look in there, we see that there is a contextvars.Token object documented, which has a .MISSING attribute. And low and behold: In [19]: import contextvars In [20]: type(contextvars.Token.MISSING) is m Out[20]: True  I just did this as an exercise to show you how you might go and find such a class, but these are internal implementation details.
Question: """ 14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". """ class Solution: def longestCommonPrefix(self,strs: list[str]) -> str: list_length = len(strs) shortest_length = len(strs[0]) for i in range(list_length): length = len(strs[i]) if shortest_length > length: shortest_length = length shortest_char = strs[i] char = [0]*len(shortest_char) for i in range(shortest_length): for str in strs: if str[i] == shortest_char[i]: char[i] +=1 for i in range(shortest_length): if char[i] < list_length: char_list = list(shortest_char) return "".join(char_list[:i]) print(Solution.longestCommonPrefix(None,["flower","flow","flight"]))  result : enter image description here but in vscode ,i get an error : UnboundLocalError: cannot access local variable 'shortest_char' where it is not associated with a value ^^^^^^^^^^^^^ char = [0]*len(shortest_char) Line 11 in longestCommonPrefix (Solution.py) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ret = Solution().longestCommonPrefix(param_1) Line 46 in _driver (Solution.py) _driver() Line 61 in <module> (Solution.py)  How can i solve this problem? In vscode, it goes through 3 for loop without any issue. I think in leetcode, it cant get variable between for loop, but why?

Answer: if shortest_length <= length than your shortest_char variable will not be defined. It is bad practice to define variables like that.
Question: I'm trying to get the date of monday given some weeknr and year. But I feel like strptime is just returning the wrong date. This is what I try: from datetime import date, datetime today = date.today() today_year = today.isocalendar()[0] today_weeknr = today.isocalendar()[1] print(today) print(today_year, today_weeknr) d = "{}-W{}-1".format(today_year, today_weeknr) monday_date = datetime.strptime(d, "%Y-W%W-%w").date() print(monday_date) print(monday_date.isocalendar()[1])  Result: $ python test.py 2025-02-13 2025 7 2025-02-17 8  So how the hell am I in the next week now?

Answer: There was an answer here before, but it got removed. I don't know why. The issue is that I was taking the weeknr from the isocalendar and later was parsing the isocalendar week,year into a date with non isocalendar directives. "%Y-W%W-%w" takes:  %Y Year with century as a decimal number. %W Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Monday are considered to be in week 0 %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.  The solution for was to just use the iso directives: d = "{}-{}-1".format(year, weeknr) monday_date = datetime.strptime(d, "%G-%V-%u").date()   %G ISO 8601 year with century representing the year that contains the greater part of the ISO week (%V). %V ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. %u ISO 8601 weekday as a decimal number where 1 is Monday.  Clearly if you use isocalendar() to get the week and year, you also need ISO directives to parse it back to a date.
Question: I have the following code: def from_utf8(string: bytes | str) -> str: if isinstance(string, bytes): return string.decode("utf-8") else: return string # <- type warning on this line  pylance gives me a type warning on the return string line: Type "bytearray | memoryview[_I@memoryview] | str" is not assignable to return type "str" Type "bytearray | memoryview[_I@memoryview] | str" is not assignable to type "str" "bytearray" is not assignable to "str"  My understanding is: the type annotation x: bytes is actually an alias for "runtime types" x: bytes | bytearray | memoryview[_I@memoryview], but isinstance(x, bytes) only checks for bytes, not the two others. I tried checking for types the other way around: def from_utf8(string: bytes | str) -> str: if isinstance(string, str): return string else: return string.decode("utf-8") # <- no attribute 'decode' for 'memoryview'  The error now becomes: Cannot access attribute "decode" for class "memoryview[_I@memoryview]" Attribute "decode" is unknown  For context:  my project uses python 3.11 I see these warnings in vscode, using pylance version 2025.2.1 and python (ms-python.python) extension version 2025.0.0   Do I have a convenient way to write a version of from_utf8(string) that passes the type checker ? also: is my assumption correct, and is it documented somewhere ?

Answer: Before Python 3.12, bytes was specified to behave as an alias of builtins.bytes | builtins.bytearray | builtins.memoryview. From the Python 3.10 docs (emphasis mine):  class typing.ByteString(Sequence[int]) A generic version of collections.abc.ByteString. This type represents the types bytes, bytearray, and memoryview of byte sequences. As a shorthand for this type, bytes can be used to annotate arguments of any of the types mentioned above.  The static typing error you're seeing is a consequence of this behaviour. This behaviour is now removed in Python 3.12 with the introduction of PEP 688. pyright 1.1.329 (released over a year ago) has since disabled this static typing behaviour by default under strict mode. If you don't want to use strict mode but still want to disable this behaviour, set disableBytesTypePromotions to true.  As pointed out in the comments, a typed third party library may have been developed under this behaviour, in which case you should watch out when referring to variables or return values of functions from this library. As an example, without the --strict-bytes option, mypy will pass the following in type-checking (see mypy Playground): def f() -> bytes: return memoryview(b"")
Question: I'm using the python‑pptx library to generate PowerPoint presentations on a Linux environment (Python 3.10). I need to add text to the slides, but it must display from right to left (RTL). I have tried the following approaches: Setting RTL on font runs: I attempted to set the RTL property with: run.font.rtl = True  However, this does not change the text direction as expected. Prepending a Unicode Right-to-Left mark: I added the Unicode control character \u200F to the beginning of the text, e.g. text_frame.text = "\u200F" + "lalala"  Unfortunately, the text still appears in LTR order. Adjusting paragraph alignment: I set the paragraph alignment to right using: p.alignment = 2  Yet, this only changes the alignment, not the underlying RTL behavior. I have also experimented with directly modifying the underlying XML within the PPTX file, but I haven’t been able to achieve consistent results. Has anyone encountered this issue with RTL text in python‑pptx? What are the recommended workarounds (including any XML editing techniques) to force a presentation generated with python‑pptx to display text in proper RTL format? Thank you in advance for your help!

Answer: Microsoft Office provides bidirectional writing only when a language which needs this is listed under Office authoring languages and proofing. See Change the language Office uses in its menus and proofing tools. The property rtl for right-to-left writing is a paragraph-property, not a character-property. Not clear why Python pptx programmers thought it is the latter. So, for me, having hebrew listed under Office authoring languages and proofing, the following works and produces the result shown. from pptx import Presentation from pptx.util import Inches, Pt prs = Presentation() blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) left = top = Inches(1) width = Inches(7) height = Inches(3) txBox = slide.shapes.add_textbox(left, top, width, height) tf = txBox.text_frame p = tf.paragraphs[0] p.text = "Hello, world" p.font.size = Pt(40) p = tf.add_paragraph() p.text = "שלום, עולם" p.font.size = Pt(40) p._pPr.set('algn', 'r') p._pPr.set('rtl', '1') p = tf.add_paragraph() p.text = "Hello, world again" p.font.size = Pt(40) p = tf.add_paragraph() p.text = "Lorem ipsum semit dolor..." p.font.size = Pt(40) p._pPr.set('algn', 'r') p._pPr.set('rtl', '1') prs.save('test.pptx')   Note: It is bidirectional writing, thus property rtl changes writing direction. Do not expect it turns the glyphs of the letters. Thus Lorem ipsum semit dolor... will not appear like so:
Question: I have two lists, animal_list and outer_list. animal_list contains dictionaries within the list. outer_list is just a simple list with exact same elements animal_list = [{'animal': 'dog', 'color': 'black'}, {'animal': 'cat', 'color': 'brown'}] outer_list = ['pet', 'pet']  How can I combine the two lists to make a nested dictionary within a single list without overwriting each record since the outer key (outer_list) is the exact same. My desired state below [ {'pet':{'animal': 'dog', 'color': 'black'}}, {'pet':{'animal': 'cat', 'color': 'brown'}} ]  I've tried the following but it just writes the last value since the outer key 'pet' is the same attempt_list = [] attempt_list.append(dict(zip(outer_list,animal_list))) Failed output below [{'pet': {'animal': 'cat', 'color': 'brown'}}]  I imagine a loop is needed but can't for the life of me figure it out

Answer: You can use a list comprehension that outputs a new dict for each key-value pair: [{key: value} for key, value in zip(outer_list, animal_list)]  Demo: https://ideone.com/IDUJL8 Also, if it is truly guaranteed that outer_list always contains the same value throughout, you can simply extract the first item as a fixed key instead: key = outer_list[0] [{key: animal} for animal in animal_list]
Question: I have a Polars DataFrame where each id can appear multiple times with different state values (either 1 or 2). I want to count how many unique ids have only state 1, only state 2, or both states 1 and 2. import polars as pl df = pl.DataFrame({ "id": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 13, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 20, 20, 20], "state": [1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 1, 2, 1, 2, 2, 2, 2, 1, 1, 2, 2, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 2] })  I want to count how many unique ids fall into each category: • Only state 1 (e.g., IDs that only have 1) • Only state 2 (e.g., IDs that only have 2) • Both states 1 and 2 (e.g., IDs that have both 1 and 2) Expected Result (Example): State combination [1] -> 20 IDs State combination [2] -> 15 IDs State combination [1, 2] -> 30 IDs 

Answer: You could group by the id and use .all() and .any() to check the states. (df.group_by("id") .agg( one = (pl.col.state == 1).all(), two = (pl.col.state == 2).all(), both = (pl.col.state == 1).any() & (pl.col.state == 2).any() # both = pl.lit(1).is_in("state") & pl.lit(2).is_in("state") ) # .select(pl.exclude("id").sum()) )  shape: (20, 4) ┌─────┬───────┬───────┬───────┐ │ id ┆ one ┆ two ┆ both │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ bool ┆ bool ┆ bool │ ╞═════╪═══════╪═══════╪═══════╡ │ 6 ┆ false ┆ true ┆ false │ │ 3 ┆ false ┆ true ┆ false │ │ 2 ┆ true ┆ false ┆ false │ │ 12 ┆ true ┆ false ┆ false │ │ 16 ┆ false ┆ false ┆ true │ │ … ┆ … ┆ … ┆ … │ │ 9 ┆ false ┆ false ┆ true │ │ 13 ┆ false ┆ true ┆ false │ │ 8 ┆ false ┆ true ┆ false │ │ 15 ┆ false ┆ false ┆ true │ │ 10 ┆ false ┆ false ┆ true │ └─────┴───────┴───────┴───────┘  The .sum() of the bool columns are the counts. shape: (1, 3) ┌─────┬─────┬──────┐ │ one ┆ two ┆ both │ │ --- ┆ --- ┆ --- │ │ u32 ┆ u32 ┆ u32 │ ╞═════╪═════╪══════╡ │ 6 ┆ 7 ┆ 7 │ └─────┴─────┴──────┘