eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: sys.setrecursionlimit is set to 20000, but I get error because of "996 more times", despite setting limit to a bigger number import sys from functools import * sys.setrecursionlimit(20000) @lru_cache(None) def f(n): if n <= 3: return n - 1 if n > 3: if n % 2 == 0: return f(n - 2) + (n / 2) - f(n - 4) else: return f(n - 1) * n + f(n - 2) result = f(4952) + 2 * f(4958) + f(4964) print(result)  error: Traceback (most recent call last): File "-", line 21, in <module> result = f(4952) + 2 * f(4958) + f(4964) ^^^^^^^ File "-", line 14, in f return f(n - 2) + (n / 2) - f(n - 4) ^^^^^^^^ File "-", line 14, in f return f(n - 2) + (n / 2) - f(n - 4) ^^^^^^^^ File "-", line 14, in f return f(n - 2) + (n / 2) - f(n - 4) ^^^^^^^^ [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded  the answer should be 9200 Why doesn't sys.setrecursionlimit change the limit?

Answer: First, your code, as shown above, works fine on my system. Even when I reduce the recursion limit from 20000 down to 4000. However, if you rewrite your expressions to invoke f() on smaller numbers before larger numbers, then I'm able to run it with a recursion limit around 1250: import sys from functools import lru_cache sys.setrecursionlimit(1250) @lru_cache(None) def f(n): if n <= 3: return n - 1 if n % 2 == 0: return - f(n - 4) + f(n - 2) + n/2 return f(n - 2) + f(n - 1) * n result = f(4952) + 2 * f(4958) + f(4964) print(result)  The problem you describe sounds similar to this issue 3.12 setrecursionlimit is ignored in connection with @functools.cache which may also be Windows specific. Try an older or newer Python, possibly on a different architecture.
Question: Is there a way to write a function that takes some parameter, to modify multiple existing functions? For example, if I have: def add(a, b): return a + b def minus(a, b): return a - b def offset_b(func, n): (??) func(a, b - n)  then I want to execute below: offset_b(add(1, 2), 0.5) offset_b(minus(1, 2), 0.5)  I know one way to do it is: def new_b(b): return b-0.5 add(1, new_b(b)) minus(1, new_b(b))  Is there a way to use a wrapper or something to take the func (add/minus) and n, so that every time if I input some add(1, 2) it actually does add(1, 2 - 0.5) instead of the original version?

Answer: Define a function that accepts an existing function with known parameters, and returns a new function that wraps it: import functools # To borrow wrapped function's docs nicely def offset_b(func, n): @functools.wraps(func) def wrapped(a, b): return func(a, b-n) return wrapped  You can then define new versions of add and minus that apply the offset: add_with_offset_1 = offset_b(add, 1) minus_with_offset_1 = offset_b(minus, 1)  Or if you want to be able to make a proper decorator to apply this mutation to a new function that should only be called with an offset applied, you can increase the nesting, to produce a decorator with parameters, so that the first call takes the offset and returns a function that, when called with another function, produces the wrapped function: def offset_b(n): def do_wrap(func): @functools.wraps(func) def wrapped(a, b): return func(a, b-n) return wrapped return do_wrap  which allows you to use it as before, but in a different ordering: offset_by_1 = offset_b(1) add_with_offset_1 = offset_by_one(add) # Or as one-liner: add_with_offset_1 = offset_b(1)(add) minus_with_offset_1 = offset_by_one(minus)  or use it as a decorator to modify the wrapped function immediately: @offset_b(0.5) def add(a, b): return a + b @offset_b(0.5) def minus(a, b): return a - b  so add and minus exist immediately with the offset of 0.5 applied to all calls (confusing in this case, but useful in others).
Question: I have an array: U = np.array([3, 5, 7, 9, 11])  I want to get a result like: result = np.array([ [ np.nan, np.nan, np.nan, np.nan, np.nan], [U[0] - U[1], np.nan, np.nan, np.nan, np.nan], [U[0] - U[2], U[1] - U[2], np.nan, np.nan, np.nan], [U[0] - U[3], U[1] - U[3], U[2] - U[3], np.nan, np.nan], [U[0] - U[4], U[1] - U[4], U[2] - U[4], U[3] - U[4], np.nan] ])  I can use np.tril_indices(4, k=-1) to get indices of lower triangle without diagonal, but what is next?

Answer: A naive approach that does more work than necessary is to compute the entire difference and select the elements you need: np.where(np.arange(U.size)[:, None] > np.arange(U.size), U[:, None] - U, np.nan)  This is one of the times where np.where is actually useful over a simple mask, although it can be done with a mask as well: result = np.full((U.size, U.size), np.nan) index = np.arange(U.size) mask = index[:, None] > index result[mask] = [U[:, None] - U][mask]  A more efficient approach might be to use the indices more directly to index into the source: result = np.full((U.size, U.size), np.nan) r, c = np.tril_indices(U.size, k=-1) result[r, c] = U[c] - U[r]
Question: I've got a problem with Python Telebot, here is my code: import telebot token = 'token' bot = telebot.TeleBot(token) @bot.message_handler(func=lambda message: True) def start(message): bot.send_message(message.chat.id,"message") bot.register_next_step_handler(message, nextstep) def nextstep(message): bot.send_message(message.chat.id,"anothermessage") bot.register_next_step_handler(message, finalstep) def finalstep(message): bot.send_message(message.chat.id,"in previous step you sent: " + str(message.text) + ". Now let's start again") start(message) print ("running") bot.infinity_polling(skip_pending=True)  This code is running ok and looks like this in Telegram chat:  But if I send two messages it starts looking like this:  And ends up like this:  After this the bot keeps to duplicate answers to my messages, as well as multiply triggering the functions. Like the code is double-running itself from the point when bot receives two or more messages. After restart it's ok again, until the next double message. What is causing duplicate messages? How to prevent it?

Answer: Because your code does double-runs itself: at the end of the first turn finalstep calls start but then bot's message handler calls start again. And further: bot.register_next_step_handler() just adds a callable object to the bot's list of handlers, so that list grows after each message and bot runs all that handlers at every next step. I think your nextstep and finalstep should by like: def nextstep(message): bot.send_message(message.chat.id,"anothermessage") bot.clear_step_handler(message) bot.register_next_step_handler(message, finalstep) def finalstep(message): bot.send_message(message.chat.id,"in previous step you sent: " + str(message.text) + ". Now let's start again") bot.clear_step_handler(message)
Question: Say that I have an array: arr = np.arange(4).reshape(2,2)  The array arr contains the elements array([[0, 1], [2, 3]])  I want to increase the resolution of the array in such a way that the following is achieved: np.array([0,0,1,1], [0,0,1,1], [2,2,3,3], [2,2,3,3]])  what is this operation called? Nearest-neighbor interpolation? It is possible to get my desired output with the following np.concat(np.repeat(arr,4).reshape(-1,2,2,2), axis=-1).reshape(4,4)  Is there a more general way of doing this for any kind of matrix?

Answer: You're looking for "nearest-neighbour upsampling", instead of "interpolation". A concise and efficient way to do this in numpy: import numpy as np arr = np.arange(6).reshape(2, 3) upsampled = np.repeat(np.repeat(arr, 2, axis=0), 2, axis=1) print("Original Array:") print(arr) print("Upsampled Array:") print(upsampled)  Note: I changed your sample data to (2,3) to show that the original shape does not affect the function. Result: Original Array: [[0 1 2] [3 4 5]] Upsampled Array: [[0 0 1 1 2 2] [0 0 1 1 2 2] [3 3 4 4 5 5] [3 3 4 4 5 5]]  If you need it to be more memory efficient, you can also use: upsampled2 = np.kron(arr, np.ones((2, 2), dtype=int)) print("Upsampled Array using Kronecker product:") print(upsampled2)  Result: Upsampled Array using Kronecker product: [[0 0 1 1 2 2] [0 0 1 1 2 2] [3 3 4 4 5 5] [3 3 4 4 5 5]]  Libraries like scipy may offer even more efficient methods of doing the same, if your data is very large.
Question: I have a pyhton program from which I am using python-openvpn-client API to connect to a vpn server using an .ovpn configuration file. I have installed python 3.13.1 from the official website. Then I have created a virtual python environment to use in my python project. I have successfully installed the python-openvpn-client (version 0.0.1) package which says it requires python >= 3.9. I have used below command to install it in my virtual environment: pip install python-openvpn-client  I installed OpenVpn from here. I am using version OpenVPN 2.6.12 - Released 18 July 2024. Then I do below: from openvpnclient import OpenVPNClient def connect_to_vpn(config_path): vpn = OpenVPNClient(config_path) try: vpn.connect() while not vpn.is_connected(): print(f"Status: {vpn.status}") sleep(2) print("Connection successfully established.") return vpn except Exception as e: print(f"Error connecting to VPN server: {e}") return None  config_path is the full path to an .ovpn file. When executing the line of code vpn.connect() an exception is thrown: module 'signal' has no attribute 'SIGUSR1'  If I import the same .ovpn file from OpenVPN app and connect to the the VPN server, then is working but not from my python program. My platform is Windows 10 Pro. So what am I doing wrong?

Answer: The python-openvpn-client 0.0.1 is for Unix-like systems like Linux, macOS or BSD. It's page says it was tested to work on macOS and Linux. The Windows systems do not support POSIX signals like SIGUSR1. You had this error message because SIGURS1 is not defined.The POSIX signals are supported on Unix-like systems.You could try openvpn-api.
Question: How can I check if all values of a polars DataFrame, containing only boolean columns, are True? Example df: df = pl.DataFrame({"a": [True, True, None], "b": [True, True, True], })  The reason for my question is that sometimes I want to check if all values of a df fulfill a condition, like in the following: df = pl.DataFrame({"a": [1, 2, None], "b": [4, 5, 6], }).select(pl.all() >= 1)  By the way, I didn't expect that .select(pl.all() >= 1) keeps the null (None) in last row of column "a", maybe that's worth noting.

Answer: As of the date of this answer, I found the following snippet most appropriate for polars: df.fill_null(False).min_horizontal().min()  If no null values exist in df, one could omit .fill_null(False). Credit goes to roman, the logic of min_horizotnal().min() was first described by him in this answer on a similar issue on any. Example with the df from above: >>> df.fill_null(False).min_horizontal().min() False >>> df = pl.DataFrame({"a": [True, True, True], ... "b": [True, True, True], ... }) ... ... df.fill_null(False).min_horizontal().min() True
Question: I have tried to do this in order to create a new column, with each row being an array containing the values of column b multiplied by column a. data = {'a': [3, 2], 'b': [[4], [7, 2]]} df = pd.DataFrame(data) df['c'] = df.apply(lambda row: [row['a'] * x for x in row['b']])  The final result should look like this    a b c     3 [4] [12]   2 [7, 2] [14, 4]   

Answer: Your approach would have been correct with axis=1 (= row-wise, the default apply is column-wise): df['c'] = df.apply(lambda row: [row['a'] * x for x in row['b']], axis=1)  Using apply is however quite slow since pandas creates an intermediate Series for each row. It will be more efficient to use pure python: a list comprehension is well suited. df['c'] = [[a * x for x in b] for a, b in zip(df['a'], df['b'])]  Output:  a b c 0 3 [4] [12] 1 2 [7, 2] [14, 4]  Comparison of timings (on 200k rows) # list comprehension # df['c'] = [[a * x for x in b] for a, b in zip(df['a'], df['b'])] 98.3 ms ± 3.47 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # conversion to numpy arrays # df['c'] = df['a'] * df['b'].map(np.array) 371 ms ± 75.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # apply with axis=1 # df['c'] = df.apply(lambda row: [row['a'] * x for x in row['b']], axis=1) 1.65 s ± 65.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Question: I have this setup File 1 from playwright.sync_api import sync_playwright class A: def __init__(self,login_dict): self.start = sync_playwright().start() self.browser = self.start.chromium.launch() self.context = self.browser.new_context() self.page = self.context.new_page() self.login_dict = login_dict  File 2 import file_1.py class B(A): def __init__(self): super().__init__()  from file_1 import A from file_2 import B a = A(some_login_dict) b = B()  I get this error at the super init of B class  It looks like you are using Playwright Sync API inside the asyncio loop. Please use the Async API instead. I do not understand why is this happening, can someone explain? Is there a way to avoid this?

Answer: The files and classes in your code are obscuring the root cause. Nonetheless, it's good to see your intended use case, since you'd normally start Playwright with a with context manager, which isn't as obvious in the class setup. The minimal trigger is simply starting Playwright's sync API twice, which it wasn't designed to do: from playwright.sync_api import sync_playwright # 1.48.0 browser = sync_playwright().start().chromium.launch() browser = sync_playwright().start().chromium.launch() # raises 'It looks like...'  The error message is not very clear. The solution is to only .start() Playwright once for the application: from playwright.sync_api import sync_playwright sync_playwright = sync_playwright().start() browser = sync_playwright.chromium.launch() browser = sync_playwright.chromium.launch()  In your code, the error occurs when you initialize both A() and B() (removing one initializer or the other works). Since you're working with classes, you can move playwright = sync_playwright().start() to the module-level scope of a shared, one-off module, which is then imported from any other file that needs to launch a browser. An alternative approach is to use the async API, which doesn't seem to mind being started multiple times: import asyncio from playwright.async_api import async_playwright async def run(): pw1 = await async_playwright().start() pw2 = await async_playwright().start() browser1 = await pw1.chromium.launch() browser2 = await pw2.chromium.launch() page1 = await browser1.new_page() page2 = await browser2.new_page() await page1.goto("https://www.example.com") await page2.goto("https://en.wikipedia.org") print(await page1.title()) print(await page2.title()) await pw1.stop() await pw2.stop() asyncio.run(run())  Remember to clean up with .stop() when not using context-managed Playwright. See also Playwright issue #1391 on GitHub.
Question: I'm working on a wiki project with django. I'm trying to render 'add.html' with the view add, but it sends me to 404 instead. All the other views are working fine. How should I fix add? views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django import forms import re from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def detail(request, entry): #if search based on title returns result if util.get_entry(entry): content = util.get_entry(entry) return render(request, "encyclopedia/details.html", { "title": entry, "content": content }) else: return render(request, "encyclopedia/404.html", { 'entry': entry }) def add(request): return render(request, "encyclopedia/add.html") urls.py: from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:entry>/", views.detail, name="entry"), path("add/", views.add, name="add"), ] 

Answer: in your urls.py, <str:entry>/ path is defined before the add/ path. this causes django to interpret add/ as a dynamic entry parameter for the detail view instead of routing it to the add view. django document urlpatterns = [ path("", views.index, name="index"), path("add/", views.add, name="add"), # place "add/" before "<str:entry>/" path("<str:entry>/", views.detail, name="entry"), ]
Question: I’m given two string arrays, words1 and words2. A string b is a subset of string a if all characters in b appear in a with at least the same frequency. I need to find all strings in words1 that are universal, meaning every string in words2 is a subset of them. I need to return those universal strings from words1 in any order. I've written a function to find universal words from two lists, words1 and words2. The function uses a hashmap to store character frequencies from words2 and then checks each word in words1 against these frequencies. The code passed all the test cases but I am confused about analyzing time complexity. For time complexity: Processing all words in words2 takes O(m * k), where m = length of words2 and k = average word length. Checking all words in words1 involves O(n * 26), where n = length of words1, and 26 is the max number of hashmap keys (a-z). If I consider the count() in both the loops it will make whole time complexity O(m * k^2 + n*k). Is this the correct analysis? def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: ans = [] hmap = {} for i in words2: for j in i: if j in hmap.keys(): hmap[j] = max(hmap[j], i.count(j)) else: hmap[j] = i.count(j) for j in words1: flag = True for k in hmap.keys(): if hmap[k] > j.count(k): flag = False break if flag: ans.append(j) return ans 

Answer: Indeed, the call of count represents O(𝑘) time complexity, as it needs to scan all letters in the given word. So this makes the first loop's time complexity O(𝑚𝑘²). Similarly, the second loop has a complexity of O(26𝑛𝑘) = O(𝑛𝑘), if indeed your assumption about the range of the characters (a-z) is correct. You can avoid using count and so reduce the complexity of the first loop, by just increasing a count by 1 as you iterate the letters. For instance, like this: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: # A helper function to count the frequency of each letter in a single string def get_freq(word): # O(k) hmap = {} for ch in word: hmap[ch] = hmap.get(ch, 0) + 1 return hmap hmap = {} # O(mk): for hmap2 in map(get_freq, words2): for ch, freq in hmap2.items(): hmap[ch] = max(hmap.get(ch, 0), freq) res = [] # O(nk) for hmap1, word1 in zip(map(get_freq, words1), words1): if all(hmap1.get(ch, 0) >= freq2 for ch, freq2 in hmap.items()): res.append(word1) return res  So now the complexity is O((𝑛+𝑚)𝑘). We can further adapt and make use of Counter from the collections module, and make use of more comprehension-syntax: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: hmap = Counter() for word2 in words2: hmap |= Counter(word2) return [word1 for word1 in words1 if Counter(word1) >= hmap]  The time complexity remains the same.
Question: In Polars / pandas / PyArrow, I can instantiate an object from a dict, e.g. In [12]: pl.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) Out[12]: shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ └─────┴─────┘  Is there a way to do that in DuckDB, without going via pandas / pyarrow / etc.?

Answer: duckdb features a function duckdb.read_json which should do this by simply streaming the dict as a json string, but no combination of its various parameters will make it read that dict the same way polars does unfortunately. You can rearrange the dict to match the structure expected for a "unstructured" json format in their documentation pretty easily and then use the duckdb.read_json function to load it the same way as polars, which I think the closest you can get with the library as it currently stands. Here is a demonstration which shows the polars interpretation we expected, the naive duckdb interpretation we probably didn't and the transformation necessary to load it like polars did: import polars import duckdb import io import json # Silent requirement for fsspec data = {'a': [1,2,3], 'b': [4,5,6]} polars_data = polars.DataFrame(data) print('polars\' interpretation:') print(polars_data) duckdb_data = duckdb.read_json(io.StringIO(json.dumps(data))) print('duckdb \'s naive interpretation:') print(duckdb_data) def transform_to_duckjson(dictdata: dict): return [{fieldname: fieldrecords[recordnum] for fieldname, fieldrecords in dictdata.items()} for recordnum in range(len(dictdata[next(iter(dictdata.keys()))]))] duckdb_data2 = duckdb.read_json(io.StringIO(json.dumps(transform_to_duckjson(data)))) print('duckdb \'s interpretation after adjustment:') print(duckdb_data2)  Which gives me the following output: polars' interpretation: shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ └─────┴─────┘ duckdb 's naive interpretation: ┌───────────┬───────────┐ │ a │ b │ │ int64[] │ int64[] │ ├───────────┼───────────┤ │ [1, 2, 3] │ [4, 5, 6] │ └───────────┴───────────┘ duckdb 's interpretation after adjustment: ┌───────┬───────┐ │ a │ b │ │ int64 │ int64 │ ├───────┼───────┤ │ 1 │ 4 │ │ 2 │ 5 │ │ 3 │ 6 │ └───────┴───────┘  As a note: Here is the python api reference (scroll down to "read_csv(..." for the relevant information) which doesn't provide any help at all for using the function unfortunately. Let me know if you have any questions.
Question: Consider two boolean arrays import numpy as np A = np.asarray([[True, False], [False, False]]) B = np.asarray([[False, True], [True, True]])  I want to take the kronecker product of A and B under the xor operation. The result should be: C = np.asarray([[True, False, False, True], [False, False, True, True], [False, True, False, True], [True, True, True, True]])  More generally, is there a simple way to implement the Kronecker product with some multiplication operator distinct from the operator *, in this instance the xor operator ^?

Answer: You could use broadcasting and reshaping: m, n = A.shape p, q = B.shape C = (A[:, None, :, None] ^ B[None, :, None, :]).reshape(m*p, n*q)  Simplified: C = (A[:, None, :, None] ^ B[None, :, None, :] ).reshape(A.shape[0]*B.shape[0], -1)  Also equivalent to: C = (np.logical_xor.outer(A, B) .swapaxes(1, 2) .reshape(A.shape[0]*B.shape[0], -1) )  Or with explicit alignment using repeat/tile without reshaping: p, q = B.shape C = np.repeat(np.repeat(A, p, axis=0), q, axis=1) ^ np.tile(B, A.shape)  Output: array([[ True, False, False, True], [False, False, True, True], [False, True, False, True], [ True, True, True, True]])  ND-generalization for N dimensional inputs, one could follow the same logic by expanding the dimensions in an interleaved fashion with expand_dims, before reshaping to the element-wise product of the dimensions: C = ( np.expand_dims(A, tuple(range(1, A.ndim*2, 2))) ^ np.expand_dims(B, tuple(range(0, A.ndim*2, 2))) ).reshape(np.multiply(A.shape, B.shape))  Interestingly, this is how kron is actually implemented in numpy (with some extra checks in place). Variant with outer: C = (np.logical_xor.outer(A, B) .transpose(np.arange(A.ndim+B.ndim) .reshape(-1, 2, order='F') .ravel()) .reshape(np.multiply(A.shape, B.shape)) )
Question: I am working with uv for the first time and have created a venv to manage my dependencies. Now, I'd like to install some dependencies from a requirements.txt file. How can this be achieved with uv? I already tried manually installing each requirement using uv pip install .... However, this gets tedious for a large list of requirements.

Answer: You can install the dependencies to the virtual environment managed by uv using: uv pip install -r requirements.txt  When working with a project (application or library) managed by uv, the following command might be used instead: uv add -r requirements.txt  This will also add the requirements to the project's pyproject.toml.