eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm trying to SSH into final_machine via the jump host portal_machine. Both remote machines are Linux, local is Windows. When I run the following command in a cmd, I can successfully connect ssh {username}@{final_machine} -oProxyCommand="ssh -W {final_machine}:22 {username}@{portal_machine}"  And I can also successfully connect through python with ssh_command = plumbum.local["ssh"][f"{username}@{final_machine}", "-o", f"ProxyCommand=ssh -W {final_machine}:22 {username}@{portal_machine}"] ssh_command()  However, I need to connect via an SshMachine object for compatibility, and when I try the following, it fails plumbum.SshMachine(final_machine, user=username, ssh_opts=[fr'-o ProxyCommand="ssh -W {final_machine}:22 {username}@{portal_machine}"'])  with error Return code: | None Command line: | 'true ' Host: | {final machine} Stderr: | CreateProcessW failed error:2  I've tried replacing ssh with C:\Windows\System32\OpenSSH\ssh.exe, but no change. I have SSH keys set up from my machine to portal_machine, my machine to final_machine, and portal_machine to final_machine. Any other suggestions for how to debug would be appreciated. When I connect simply to the portal machine, it works fine.

Answer: I would rather use ProxyJump than ProxyCommand, and move as many settings as possible into ~/.ssh/config. Sample configuration for the mentioned hosts: HOST portal HostName portal.machine.host.name.or.IP User username IdentityFile ~/.ssh/your.portal.key HOST final HostName final.machine.host.name.or.IP User username IdentityFile ~/.ssh/your.final.key ProxyJump portal  Tunnel then with: machine = plumbum.SshMachine('final') pwd = machine['pwd'] pwd() # '/home/ec2-user\n'
Question: I am using vscode on my desktop and laptop and each machine would generate a random folder name with a hash for the virtual environment path when creating the virtual environment using poetry. In order to use the same launch.json file in my project for both computers, I'd like to reference an environment variable instead of hard coding the virtual environment path names. I've tried the below but vscode is stating "The Python path in your debug configuration is invalid." How can I reference the environment variable for the "python" path? my ~/.zshrc: export PROJ_VENV=$HOME/.cache/pypoetry/virtualenvs/myproj-NMmw6p6o-py3.12  my launch.json: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "python": "${env:PROJ_VENV}/bin/python", "request": "launch", "program": "${workspaceFolder}/src/manage.py", "args": [ "runserver", ], "django": true } ] } 

Answer: As of vscode 1.85, specifying "python": "${env:PROJ_VENV}/bin/python" in launch.json will not work. As a workaround, you can remove "python" from launch.json and set "python.defaultInterpreterPath": "${env:PROJ_VENV}/bin/python" in settings.json. You can then select "Use Python from python.defaultInterpreterPath" when selecting your python interpreter.
Question: I am learning python , i use Vs code as my IDE, i am have some very strange and annoying errors. examples: when i import modules import telegram i get error "telegram" is not accessed Pylance invalid syntaxMypysyntax (module) telegram on my files, which is very annoying. I have write import telegram #type:ignore for the error to go away. when i also write  async def hello(self, update: Update, context: ContextTypes.DEFAULT_TYPE): await context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, my name is MAS.")  i get this error on chat_id=update.effective_chat.id  Item "None" of "Optional[Chat]" has no attribute "id"Mypyunion-attr Item "None" of "Optional[Chat]" has no attribute "id"Mypyunion-attr Item "None" of "Optional[Chat]" has no attribute "id"Mypyunion-attr Item "None" of "Optional[Chat]" has no attribute "id"Mypyunion-attr Item "None" of "Optional[Chat]" has no attribute "id"Mypyunion-attr (property) effective_chat: Chat | None  . Even with these errors i runs the files perfectly without any issues, i don't why vscode is acting up. it is impacting my productivity. i have to add #type:ignore to make these errors go away. i have these running extensions.    I have searched all of google and stack overflow and found nothing that solve my problem. i came across mypy-type-checker.args on Vscode marketplace. i believe it could solve my problem, but there is no docs on how to set the arguments. nothing at all on vscode marketplace. The docs for mypy even made less sense to me as a beginner.

Answer: I enabled Copilot, ask it to explain the probem to me . it told me to do  if update.effective_chat is not None: await context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, my name is MAS, i am your bot that provides movies to you for free.")  instead of  await context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, my name is MAS, i am your bot that provides movies to you for free.")  My code is now error free. if you have a Copilot subscription enable the extension to *6 your productivity.
Question: I'm running a GH actions pipeline which is configured to login Azure cli using federated credentials (and this works fine): env: ARM_USE_OIDC: true steps: - name: az login uses: azure/login@v1 with: client-id: ${{ env.ARM_CLIENT_ID }} tenant-id: ${{ env.ARM_TENANT_ID }} subscription-id: ${{ env.ARM_SUBSCRIPTION_ID }}  then I'm running pytest which does some python code, some TF runs, etc. plain Az Cli\TF calls using subprocess work, however when I'm using AzureCliCredential or DefaultAzureCredential calls to get_token fail with:  Output: ERROR: AADSTS700024: Client assertion is not within its valid time range. Current time: 2023-12-19T07:20:31.3554289Z, assertion valid from 2023-12-19T05:59:24.0000000Z, expiry time of assertion 2023-12-19T06:04:24.0000000Z  The same code was working previously using certificate auth EDIT: what was confusing me is the fact that the tokens I'm getting have proper lifetime, which doesnt match the error. what I'm thinking now is that the underlying OIDC token issued by Github has only 5 minutes of lifetime hence it doesnt matter if oAuth tokens have 1h lifetime EDIT: related issues: https://github.com/Azure/login/issues/372 https://github.com/Azure/login/issues/180

Answer: the underlying OIDC token issued by Github has only 5 minutes of lifetime hence it doesnt matter if oAuth tokens have 1h lifetime. my workaround is to refresh Azure Cli auth everytime I need to use it until anything can be done about this (at least I dont see a way to extend token lifetime: https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect) def get_azure_credentials(): token_request = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN") token_uri = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL") subprocess_helper(f'token=$(curl -H "Authorization: bearer {token_request}" "{token_uri}&audience=api://AzureADTokenExchange" | jq .value -r) && az login --service-principal -u {CLIENT_ID} -t {TENANT_ID} --federated-token $token') return AzureCliCredential()  ps. subprocess_helper is a wrapper around: subprocess.run(["/bin/sh", "-c", run_me], stdout=subprocess.PIPE, stderr=subprocess.PIPE)  pps. if any1 knows a better solution - I'm up for it
Question: I am querying data from raydium using their SDK, but i am trying to do it in Python instead. So, I am obtaining an address: <BN: b870e12dd379891561d2e9fa8f26431834eb736f2f24fc2a2a4dff1fd5dca4df>  And I know it correspond to : PublicKey(DQyrAcCrDXQ7NeoqGgDCZwBvWDcYmFCjSb9JtteuvPpz)]  But anyone know how one could decode the first into the second please, so i could implement this in Python. Thanks

Answer: With Solana use base58 for encode address. In python, you can use module base58 to encode from hex string address. import base58 hex_sting="b870e12dd379891561d2e9fa8f26431834eb736f2f24fc2a2a4dff1fd5dca4df" byte_string = bytes.fromhex(hex_sting) encoded_string = base58.b58encode(byte_string).decode() # DQyrAcCrDXQ7NeoqGgDCZwBvWDcYmFCjSb9JtteuvPpz
Question: I am attempting to analyse high school attendance and behaviour data. I have a raw excel data sheet as shown in the image.  I get lost with how to index it. Essentially the first three columns should be "Student Name, Class and Percent Attendance". Then all subsequent columns are a 2 level index, the first of which is "date" and the sub-index "period name". How can I delete the appropriate rows and columns to achieve this and the index be correct. Many thanks Graham I don't really know what to try? Historically I have "hard-wired" what I want into a Python Array but I really want to become more proficient with dataframes and see this as a good project to have a go upon.

Answer: You can read_excel to load the spreadsheet as it is, then post-process it : raw = pd.read_excel("file.xlsx") idx_names = ["Student Name", "Class", "Percent Attendance"] left = raw.iloc[2:, :3].set_axis(idx_names, axis=1) col_mux = pd.MultiIndex.from_arrays(raw.iloc[:2, 3:].ffill(axis=1).to_numpy()) right = raw.iloc[2:, 3:] df = (pd.concat([left, right], axis=1) .set_index(idx_names).set_axis(col_mux, axis=1))  Output : # df.index.nlevels # 2 # df.columns.nlevels # 3 print(df) 19/9/2023 20/9/2023 AM PM P1 P2 P3 P4 P5 AM PM P1 P2 P3 Student Name Class Percent Attendance Student A 7M 100% / \ / / / NaN / / \ / / / Student B 12H 100% / \ NaN / N NaN NaN / \ / / / Student C 8R 100% / \ / / / NaN NaN / \ / / / [3 rows x 12 columns]
Question: I am trying to develop a program in Python that streams a webcam captured video, through an ML process, to "the internet". Are there particular packages for Python that are designed to handle the live webcam capture and streaming/receiving from the internet? The ML processes I understand fairly well but currently require loading from storage whereas I'm trying to understand essentially how to make a P2P video chat client in Python. Any pointer are greatly appreciated

Answer: You can capture video from webcam using the opencv-python like the following: import cv2 cap = cv2.VideoCapture(0) # Open the default camera (0) while True: ret, frame = cap.read() # Read a frame from the webcam # Perform your ML processing here on 'frame' cv2.imshow('Webcam', frame) # Display the frame if cv2.waitKey(1) & 0xFF == ord('q'): # Press 'q' to exit break cap.release() cv2.destroyAllWindows()  For streaming video over a network, you can use imagezmq library for streaming OpenCV images from one computer to another. It's based on ZeroMQ, a messaging library that allows you to connect multiple devices over a network. for sender device: import cv2 import zmq import base64 context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:5555") # Set the appropriate address and port cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() # Perform your ML processing here on 'frame' _, buffer = cv2.imencode('.jpg', frame) jpg_as_text = base64.b64encode(buffer) socket.send(jpg_as_text) cap.release()  for receiver device: import zmq import cv2 import numpy as np import base64 context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://sender_ip:5555") # Replace 'sender_ip' with the actual sender's IP socket.setsockopt_string(zmq.SUBSCRIBE, '') while True: jpg_as_text = socket.recv() jpg_original = base64.b64decode(jpg_as_text) jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8) frame = cv2.imdecode(jpg_as_np, flags=1) cv2.imshow('Receiver', frame) if cv2.waitKey(1) & 0xFF == ord('q'): # Press 'q' to exit break cv2.destroyAllWindows()  This is a basic approach for video streaming setup using OpenCV for webcam capture, ML processing on frames, and imagezmq for streaming frames over a network. But do keep in mind that setting up a P2P video chat client involves more complexities, such as handling network discovery, establishing connections, handling latency, and potentially incorporating signaling protocols. For a full-fledged P2P video chat, you might consider additional libraries or frameworks specifically designed for real-time communication, like WebRTC. You can get a more clear idea from this tutorial I found: https://pyimagesearch.com/2019/04/15/live-video-streaming-over-network-with-opencv-and-imagezmq/
Question: I have a dataframe called df with features, col1, col2, col3. Their values should be combined and produce a result. What result each combination will produce is defined in mapping_table. However, mapping_table sometimes has the value '*'. This mean that this feature can have any value, it doesn't affect the result. This makes a join impossible(?) to make, since I need to evaluate which features to use in the join for every row. What would be a good pyspark solution for this problem? from pyspark.sql import SparkSession from pyspark.sql.functions import col # Create a Spark session spark = SparkSession.builder.appName("example").getOrCreate() # Example DataFrames map_data = [('a', 'b', 'c', 'good'), ('a', 'a', '*', 'very good'), ('b', 'd', 'c', 'bad'), ('a', 'b', 'a', 'very good'), ('c', 'c', '*', 'very bad'), ('a', 'b', 'b', 'bad')] columns = ["col1", "col2", 'col3', 'result'] mapping_table = spark.createDataFrame(X, columns) data =[[('a', 'b', 'c'), ('a', 'a', 'b' ), ('c', 'c', 'a' ), ('c', 'c', 'b' ), ('a', 'b', 'b'), ('a', 'a', 'd') ]] columns = ["col1", "col2", 'col3'] df = spark.createDataFrame(data, columns) 

Answer: Transform map_data into a case statement: ressql = 'case ' for m in map_data: p = [f"{p[0]} = '{p[1]}'" for p in zip(columns, m[:3]) if p[1] != "*"] ressql = ressql + ' when ' + ' and '.join(p) + f" then '{m[3]}'" ressql = ressql + ' end' df.withColumn('result', F.expr(ressql)).show()  ressql is now case when col1 = 'a' and col2 = 'b' and col3 = 'c' then 'good' when col1 = 'a' and col2 = 'a' then 'very good' when col1 = 'b' and col2 = 'd' and col3 = 'c' then 'bad' when col1 = 'a' and col2 = 'b' and col3 = 'a' then 'very good' when col1 = 'c' and col2 = 'c' then 'very bad' when col1 = 'a' and col2 = 'b' and col3 = 'b' then 'bad' end  Result: +----+----+----+---------+ |col1|col2|col3| result| +----+----+----+---------+ | a| b| c| good| | a| a| b|very good| | c| c| a| very bad| | c| c| b| very bad| | a| b| b| bad| | a| a| d|very good| +----+----+----+---------+
Question: I would like to use python to do an SQL query that prompts the user for input to complete the query. Currently when I run my code it will tell me I have a TypeError (see below for full error message). My code will be posted below first. import pyodbc from datetime import datetime import pandas as pd def today(): return datetime.now().strftime('%Y-%m-%d') ## return (datetime.now()+timedelta(days=1)).strftime('%Y-%m-%d') #create connection string conn = pyodbc.connect('Driver={SQL Server};' 'Server=OPTSAPPS02,1433\\SQLEXPRESS;' 'Database=OPTS Production Tracking Service;' 'UID=fetch;' 'PWD=Reader123') cursor = conn.cursor() #create query parameter for target targetDTString = today()+' 23:59' targetDate = datetime.strptime(targetDTString,'%Y-%m-%d %H:%M') ###FIND A WAY TO TAKE INPUT FOR QUERY AND MAKE IT SO YOU CAN SEARCH/FILTER BY MOTHER AND STAMPER NUMBER#### query = cursor.execute("""SELECT TOOL_OUT, TANK, STATION, FORMING_CURRENT, TIME, BUILDING_CURRENT, CYCLE_TIME FROM ELECTROFORMING WHERE PROCESS='ELECTROFORMING' AND (TOOL_OUT=?)""", (input("TOOL_OUT: "))) DF = pd.read_sql_query(query,conn) print(DF)   Traceback (most recent call last): File "C:\Users\mberardi\Documents\python scripts\print-eforming-stats.py", line 39, in DF = pd.read_sql_query(query,conn) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mberardi\AppData\Local\anaconda3\Lib\site-packages\pandas\io\sql.py", line 486, in read_sql_query return pandas_sql.read_query( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mberardi\AppData\Local\anaconda3\Lib\site-packages\pandas\io\sql.py", line 2328, in read_query cursor = self.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mberardi\AppData\Local\anaconda3\Lib\site-packages\pandas\io\sql.py", line 2260, in execute raise TypeError("Query must be a string unless using sqlalchemy.") TypeError: Query must be a string unless using sqlalchemy. 

Answer: You have to pass query directly as a string without using conn.cursor() and pass the TOOL_OUT value into params as a tuple: query = """SELECT TOOL_OUT, TANK, STATION, FORMING_CURRENT, TIME, BUILDING_CURRENT, CYCLE_TIME FROM ELECTROFORMING WHERE PROCESS='ELECTROFORMING' AND (TOOL_OUT=?)""" tool_out = input("TOOL_OUT: ") DF = pd.read_sql_query(query, conn, params=(tool_out,)) print(DF)
Question: I can get the lowest values from multiple arrays by using the following: first_arr = np.array([0,1,2]) second_arr = np.array([1,0,3]) third_arr = np.array([3,0,4]) fourth_arr = np.array([1,1,9]) print(np.minimum.reduce([first_arr, second_arr, third_arr, fourth_arr]))  Result = [0 0 2] However if the arrays are different lengths or empty I get an error: ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (4,) + inhomogeneous part.  The arrays will often be different lengths or empty. How can I handle this? I want to compare all elements that exist. So, changing the above example: first_arr = np.array([0,1]) second_arr = np.array([1,0,3]) third_arr = np.array([3,0,4]) fourth_arr = np.array([1,1,9]) print(np.minimum.reduce([first_arr, second_arr, third_arr, fourth_arr]))  The result should be [0 0 3].

Answer: If you don't mind the overhead, use pandas's DataFrame.min: l = [first_arr, second_arr, third_arr, fourth_arr] out = pd.DataFrame(l).min().to_numpy()  Or with itertools.zip_longest and numpy.nanmin: from itertools import zip_longest l = [first_arr, second_arr, third_arr, fourth_arr] out = np.nanmin(np.c_[list(zip_longest(*l, fillvalue=np.nan))], axis=1)  Output: array([0., 0., 3.])
Question: Hello I have the aim to optimize a currently simple set of equations in order to obtain the value of kd with a fit. Generate testing data (works fine) def solve_gekko_equations(H0input, D0input, Kinput): m = GEKKO(remote=False) d0 = m.Const(D0input) h0 = m.Const(H0input) hdLimit=min([D0input,H0input]) d = m.Var(1,0,D0input) h = m.Var(1,0,H0input) hd = m.Var(1,0,hdLimit) kd = m.Const(Kinput) m.Equations([h + hd == h0, d + hd == d0, kd == h * d / hd]) m.solve(disp=False) return d.value[0], h.value[0], hd.value[0] H0values= np.linspace(0, 12, 100) solve_gekko_equations_vec = np.vectorize(solve_gekko_equations) dvalues, hvalues, hdvalues = solve_gekko_equations_vec(H0values, 2, 0.5)  Optimize kd from gekko import GEKKO m = GEKKO(remote=False) kd = m.FV(value=1) kd.STATUS = 1 d0 = m.Const(2) hdmeas = m.Param(value=hdvalues) h0 = m.Param(value=H0values) d = m.Var(1,0,2) h = m.Var(1,0) hd = m.Var(1,0) m.Equation(h + hd == h0) m.Equation(d + hd == d0) # Objective m.Obj(h * d / hd) m.Minimize(((hd-hdmeas)/hdmeas)**2) # Solve m.solve(disp=False) m.options.IMODE = 2 # Final objective print('Final Objective: '+ str(m.options.objfcnval)) # Print solution print('Solution') print('kd: ' + str(kd.value))  I constantly receive this error: EXIT: Invalid number in NLP function or derivative detected. Please help.

Answer: Thank you very much for your answer, and now the optimization finishes, but the result is wrong. we generated testing data for kd=0.5 but the fitting result is kd=1.0 in the suggested solution. It seemed that any initalValue in mFV(value=initialValue) was in the end the found solution. So I modified the code to only provide one minimize function: from gekko import GEKKO H0values= np.linspace(0, 12, 100) dvalues, hvalues, hdvalues = solve_gekko_equations_vec(H0values, 2, 0.5) print(len(hdvalues)) print(len(H0values)) print('optimize kd') m = GEKKO(remote=False) kd = m.FV(value=2) kd.STATUS = 1 d0 = 2 hdmeas = m.Param(value=hdvalues) h0 = m.Param(value=H0values) d = m.Var(1,lb=0,ub=2) h = m.Var(1,lb=0) hd = m.Var(1,lb=0) m.Equation(h + hd == h0) m.Equation(d + hd == d0) m.Equation(kd == (h * d)/hd) # Objective m.Minimize(((hd-hdmeas)/(hdmeas+0.001))**2) # Solve m.options.IMODE = 2 m.solve(disp=True) # Final objective print('Final Objective: '+ str(m.options.objfcnval)) # Print solution print('Solution') print('kd: ' + str(kd.value[0]))  The solve_gekko_equations_vec is the same as in my initial question. Now the result is correct but it strongly depends on the range of the numbers. This was just an example; the final ranges will be around 110-9 - 110-6; if I use the current code and make a range with np.linspace(0, 0.00012, 100) it already does not find a solution; is there maybe a more robust minimization approach or other suggestions? Thank you very much, I really appriciate your help! Stephan
Question: I would like to create a column of color lists of type [r,g,b,a] from another float column using a matplotlib cmap. Is there a faster way then: data.with_columns( pl.col("floatCol")/100) .map_elements(cmap1) )  Minimal working example: import matplotlib as mpl import polars as pl cmap1 = mpl.colors.LinearSegmentedColormap.from_list("GreenBlue", ["limegreen", "blue"]) data = pl.DataFrame( { "floatCol": [12,135.8, 1235.263,15.236], "boolCol": [True, True, False, False] } ) data = data.with_columns( pl.when( pl.col("boolCol").not_() ) .then( mpl.colors.to_rgba("r") ) .otherwise( ( pl.col("floatCol")/100) .map_elements(cmap1) ) .alias("c1") ) 

Answer: If you're using map_elements, then it can (nearly) always be faster ;) data.with_columns( pl.when(pl.col("boolCol").not_()) .then(mpl.colors.to_rgba("r")) .otherwise((pl.col("floatCol") / 100).map_batches(lambda x: pl.Series(cmap1(x)))) .alias("c1") )  Use map_batches to operate over the entire column
Question: Given an n by m matrix of integers, there is a well known problem of finding the submatrix with maximum sum. This can be solved with a 2d version of Kadane's algorithm. An explanation of an O(nm^2) time algorithm for the 2D version which is based on Kadane's algorithm can be found here. I am interested in a simpler version where only submatrices that include the top left cell of the matrix are considered. Can this version be solved faster in O(nm) time? If so, how can you do it? I would also like to see what the optimal submatrix is, not just its sum.

Answer: Yes, you can do it in O(nm), for example by accumulating over the rows and then accumulating over the columns. That gives you all the sums, so just take the max. Example implementation to find the max sum: from itertools import accumulate max(max(accumulate(c)) for c in zip(*map(accumulate, A)))  And to also find the bottom-right corner indexes of the max sum submatrix: max( (sum, i, j) for j, column in enumerate(zip(*map(accumulate, A))) for i, sum in enumerate(accumulate(column)) )  A few variations and testing (fast4 returns the indexes of the bottom-right cell of the max sum submatrix instead of the sum, and fast5 to fast7 return sum and indexes): import random from itertools import accumulate, chain, count, repeat def sum_until(A, i, j): return sum(sum(row[:j+1]) for row in A[:i+1]) def naive(A): return max( sum(sum(row[:width]) for row in A[:height]) for height in range(len(A) + 1) for width in range(len(A[0]) + 1) ) def fast1(A): return max(max(accumulate(c)) for c in zip(*map(accumulate, A))) def fast2(A): return max(map(max, map(accumulate, zip(*map(accumulate, A))))) def fast3(A): return max(chain(*map(accumulate, zip(*map(accumulate, A))))) def fast4(A): sums = *chain(*map(accumulate, zip(*map(accumulate, A)))), return divmod(sums.index(max(sums)), len(A))[::-1] def fast5(A): return max( max(zip(accumulate(c), count(), repeat(j))) for j, *c in zip(count(), *map(accumulate, A)) ) def fast6(A): return max( (sum, i, j) for j, column in enumerate(zip(*map(accumulate, A))) for i, sum in enumerate(accumulate(column)) ) def fast7(A): return max(map(max, map(zip, map(accumulate, zip(*map(accumulate, A))), map(count, repeat(0)), map(repeat, count()) ) )) random.seed(4) for _ in range(8): A = [random.choices(range(-15, 16), k=23) for _ in range(42)] print( {naive(A), fast1(A), fast2(A), fast3(A), sum_until(A, *fast4(A))}, {fast5(A), fast6(A), fast7(A)} )  Output for eight test cases, showing that all solutions find the same max sum (Attempt This Online!): {311} {(311, 23, 22)} {429} {(429, 33, 21)} {252} {(252, 28, 3)} {262} {(262, 39, 13)} {196} {(196, 41, 22)} {513} {(513, 39, 14)} {252} {(252, 41, 4)} {365} {(365, 16, 14)}