eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: is there a way to use JupyterLab in VS Code? I know that VS Code provides the Jupyter Notebook extension. However, I need to connect to another server remotely...... Any guidance will be appreciated!

Answer: You can offload intensive computation in a Jupyter Notebook to other computers by connecting to a remote Jupyter server. Once connected, code cells run on the remote server rather than the local computer. To connect to a remote Jupyter server:  Select the Jupyter Server: local button in the global Status bar or run the Jupyter: Specify local or remote Jupyter server for connections command from the Command Palette (Ctrl+Shift+P).    When prompted to Pick how to connect to Jupyter, select Existing: Specify the URI of an existing server.    When prompted to Enter the URI of a Jupyter server, provide the server's URI (hostname) with the authentication token included with a URL parameter. (If you start the server in the VS Code terminal with an authentication token enabled, the URL with the token typically appears in the terminal output from where you can copy it.) Alternatively, you can specify a username and password after providing the URI.   For guidance about securing a notebook server, refer to the Jupyter documentation.
Question: I want to create Python LOGO. So I import Turtle Module into my code. My problem is it creates only half Python LOGO and then throws errors. How can I resolve it? Python Logo Using Python Turtle | Cool Python Turtle Graphics | Python Turtle coding| coding I'm trying to create a PYTHON LOGO using turtle module. However, I'm stuck on this and don't know how to proceed. CODE BEGIN from turtle import * speed(100) #blue part pencolor('#4584b6') fillcolor('#4584b6') begin_fill() penup() goto(-70,20) left(180) pendown() forward(10) def curve(): for i in range(50): forward(0.5) right(1) for i in range(80): forward(2) right(1) for i in range(50): forward(0.5) right(1) curve() def line(): forward(130) left(90) forward(10) left(90) forward(90) right(90) forward(30) line() curve() forward(80) for i in range(90): forward(0.5) right(1) forward(120) for i in range(90): forward(0.5) left(1) forward(72.7) right(90) right(1) forward(19) end_fill() penup() goto(160,186) right(180) pendown() #yellow part pencolor('ffde57') fillcolor('ffde57') begin_fill() forward(10) curve() line() curve() forward(80) for i in range(90): forward(0.5) right(1) forward(120) for i in range(90): forward(0.5) left(1) forward(72.7) right(90) right(1) forward(19) end_fill() penup() goto(-20,210) pendown() #circledots pencolor('white') fillcolor('white') begin_fill() circle(10) end_fill() pencolor('blue') penup() goto(110,-30) pendown() pencolor('white') fillcolor('white') begin_fill() circle(10) end_fill() hideturtle() done() 

Answer: Taking advantage of turtle's methods, we can come up with an approximation of the Python logo with less code: from turtle import Screen, Turtle def curved_box(t, sides): for _ in range(sides): t.circle(90, extent=90) t.forward(120) t.circle(90, extent=90) def snake(t, color): t.backward(16) t.left(90) t.forward(16) t.right(90) t.fillcolor(color) t.begin_fill() t.forward(64) curved_box(t, 2) t.forward(44) t.left(90) t.forward(152) t.right(90) t.forward(16) t.right(90) t.forward(204) curved_box(t, 1) t.forward(44) t.left(90) t.forward(60) t.circle(-90, extent=90) t.forward(64) t.end_fill() t.backward(86) t.left(90) t.forward(224) t.dot(48, 'white') t.backward(224) t.right(90) t.forward(86) screen = Screen() turtle = Turtle() turtle.hideturtle() turtle.speed('fastest') turtle.penup() snake(turtle, '#3774A8') turtle.left(180) snake(turtle, '#F6D646') screen.exitonclick()  But it's still only an approximation:
Question: I have a large 100000,6 array and would like to find the diffence to the each element in the vector. np.diff is almost exactly what I need but also want it to wrap around and it also finds the differnce in the first and last element. Toy model: array=np.array([[0,2,4],[0,3,6]]) np.diff(array,axis=1)  gives [[2,2],[3,3]] would like to have [[2,2,-4],[3,3,-6]] or [[-4,2,2],[-6,3,3]] Is there a built in way in numpy to do this?

Answer: You can use numpy.roll: np.roll(array, -1, axis=1)-array  Output: array([[ 2, 2, -4], [ 3, 3, -6]])
Question: I'm using Python with the Django Rest framework and am trying to receive webhook events correctly from stripe. However I constantly get this error:  stripe.error.SignatureVerificationError: No signatures found matching the expected signature for payload  This is the code: WEBHOOK_SECRET = settings.STRIPE_WEBHOOK_SK @csrf_exempt def webhook(request): sig_header = request.headers.get('Stripe-Signature', None) payload = request.body try: event = stripe.Webhook.construct_event( payload=payload, sig_header=sig_header, secret=WEBHOOK_SECRET ) except ValueError as e: raise e except stripe.error.SignatureVerificationError as e: raise e return HttpResponse(status=200)  I have also tried modifying the request body format like so: payload = request.body.decode('utf-8') # and also payload = json.loads(request.body)  And yet no luck. The error is coming from the verify_header() class method inside the WebhookSignature class. This is the part of the method where it fails: if not any(util.secure_compare(expected_sig, s) for s in signatures): raise error.SignatureVerificationError( "No signatures found matching the expected signature for payload", header, payload, )  So I printed out exptected_sig and signatures before this line and found that regardless of what format request.body is in, signatures is always there (which is good), but they never match the signature from the header. Why is this?

Answer: When Stripe calculates the signature for the Event it sends you, it uses a specific "payload" representing the entire Event's content. The signature is done on that exact payload and any change to it such as adding a new line, removing a space or changing the order of the properties will change the payload and the corresponding signature. When you verify the signature, you need to make sure that you pass the exact raw payload that Stripe sent you, otherwise the signature you calculate won't match the Stripe one. Frameworks can sometimes try to be helpful when receiving a request and they detect JSON and automatically parse it for you. This means that you think you are getting the "raw payload/body" but really you get an alternate version. It has the same content but it doesn't match what Stripe sent you. This is fairly common with Express in Node.js for example. So, as the developer, you have to explicitly request the exact raw/original payload Stripe sent you. And how to do this can differ based on a variety of factors. There are 2 issues on the stripe-node github with numerous potential fixes here and here. With Django, the same can happen and you need to make sure that your code requests the raw payload. You seem to use request.body as expected but that's one thing you want to dig into further. Additionally, another common mistake is using the wrong Webhook secret. If you use the Stripe CLI for example, it creates a new secret for you that is different from the one you see in the Dashboard for this Webhook Endpoint. You need to make sure you use the correct secret based on the environment you're in.
Question: Take the sample from https://docs.docker.com/language/python/build-images/ for instance: # ... COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . # ...  vs # ... COPY . . RUN pip3 install -r requirements.txt # ...  What are the disadvantages of the latter?

Answer: Docker checks every ADD and COPY statement to see if any files have changed and invalidate the cache for it and every later step if it has. So, in the later, after changes in your code, all requirements will be reinstalled.
Question: This is my code and I want to make the plot bigger so it's easier to read. Here I'm trying to get feature importance based on mean decrease in impurity. I'm getting some output but since my barplot has 63 bins, I want it much bigger. I tried everything that is commented. Can someone please suggest how can I make this bar plot more readable?  import pandas as pd from matplotlib.pyplot import figure # fig.set_figheight(20) # fig.set_figwidth(20) #plt_1 = plt.figure(figsize=(20, 15), dpi = 100) forest_importances = pd.Series(importances, index=feature_names) fig, ax = plt.subplots() forest_importances.plot.bar(yerr=std, ax=ax) ax.set_title("Feature importances using MDI") ax.set_ylabel("Mean decrease in impurity") # fig = plt.figure() fig.tight_layout() plt.show() 

Answer: Use fig.set_size_inches before plt.show(): width = 8 height = 6 fig.set_size_inches(width, height)
Question: Given a list of several elements, find all the possible parentheses combinations. For example with [1, 2, 3, 4], it would return [ [1,2,3,4], [[1,2],3,4], [[1,2],[3,4]], [1,[2,3],4], [1,2,[3,4]], [[1,2,3],4], [[[1,2],3],4], [[1,[2,3]],4], [1,[2,3,4]], [1,[[2,3],4]], [1,[2,[3,4]]] ]  in no paticular order. PLEASE READ: Before you mark this as a duplicate of How to print all possible balanced parentheses for an expression?, although similar, it is a slightly different question than that. In that question, it only asks for parentheses expressions where every value is surrounded. This question however asks for every single combination regardless of whether every element is within parentheses.

Answer: To list all the possible trees from the list:  Iterate on all the possible number of children from the root; For a chosen number of children, iterate on all the possible ways to split the list into that number of sublists; Recursively find all the possible subtrees of the sublists; Combine all the possible subtrees of the children using itertools.product.  from itertools import product, combinations, pairwise, chain def all_trees(seq): if len(seq) <= 1: yield from seq else: for n_children in range(2, len(seq)+1): for breakpoints in combinations(range(1, len(seq)), n_children-1): children = [seq[i:j] for i,j in pairwise(chain((0,), breakpoints, (len(seq)+1,)))] yield from product(*(all_trees(child) for child in children))  Testing: for seq in ([], [1], [1,2], [1,2,3], [1,2,3,4]): print(seq) print(list(all_trees(seq))) print() [] [] [1] [1] [1, 2] [(1, 2)] [1, 2, 3] [(1, (2, 3)), ((1, 2), 3), (1, 2, 3)] [1, 2, 3, 4] [(1, (2, (3, 4))), (1, ((2, 3), 4)), (1, (2, 3, 4)), ((1, 2), (3, 4)), ((1, (2, 3)), 4), (((1, 2), 3), 4), ((1, 2, 3), 4), (1, 2, (3, 4)), (1, (2, 3), 4), ((1, 2), 3, 4), (1, 2, 3, 4)]
Question: Get this error when trying to run a MarianMT-based nmt model. Traceback (most recent call last): File "/home/om/Desktop/Project/nmt-marionmt-api/inference.py", line 45, in <module> print(batch_inference(model_path="en-ar-model/Mark2", text=text)) File "/home/om/Desktop/Project/nmt-marionmt-api/inference.py", line 15, in batch_inference tokenizer = AutoTokenizer.from_pretrained(model_path, local_file_only=True) File "/home/om/.virtualenvs/marianmt-api/lib/python3.8/site-packages/transformers/models/auto/tokenization_auto.py", line 525, in from_pretrained raise ValueError( ValueError: Tokenizer class MarianTokenizer does not exist or is not currently imported. 

Answer: Installing SentencePiece worked for me. pip install sentencepiece
Question: How do I return an excel file (version: Office365) using FastAPI? The documentation seems pretty straightforward. But, I don't know what media_type to use. Here's my code: import os from fastapi import FastAPI from fastapi.responses import FileResponse from pydantic import BaseModel from typing import Optional excel_file_path = r"C:\Users\some_path\the_excel_file.xlsx" app = FastAPI() class ExcelRequestInfo(BaseModel): client_id: str @app.post("/post_for_excel_file/") async def serve_excel(item: ExcelRequestInfo): # (Generate excel using item.) # For now, return a fixed excel. return FileResponse( path=excel_file_path, # Swagger UI says 'cannot render, look at console', but console shows nothing. media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # Swagger renders funny chars with this argument: # 'application/vnd.ms-excel' )  Assuming I get it right, how to download the file? Can I use Swagger UI generated by FastAPI to view the sheet? Or, curl? Ideally, I'd like to be able to download and view the file in Excel. Solution Here's my final (edited) solution to save you from clicking about. In the course of development, I had to switch from a FileResponse to Response that returns io.BytesIO. import io import os.path from fastapi.responses import Response @router.get("/customer/{customer}/sheet") async def generate_excel(customer: str): excel_file_path: str = None buffer: io.BytesIO = None # Generate the sheet. excel_file_path, buffer = make_excel(customer=customer) # Return excel back to client. headers = { # By adding this, browsers can download this file. 'Content-Disposition': f'attachment; filename={os.path.basename(excel_file_path)}', # Needed by our client readers, for CORS (cross origin resource sharing). "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*", "Access-Control_Allow-Methods": "POST, GET, OPTIONS", } media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' return Response( content=buffer.getvalue(), headers=headers, media_type=media_type ) 

Answer: You could set the Content-Disposition header using the attachment parameter, indicating to the web browser that the file should be downloaded, as described in the answers here and here. Swagger UI will provide a Download file link for you to download the file, as soon as you execute the request. headers = {'Content-Disposition': 'attachment; filename="Book.xlsx"'} return FileResponse(excel_file_path, headers=headers)  To have the file viewed in the web browser, one can use the inline, instead of attachment, parameter in the Content-Disposition header, as explained in the linked answers earlier. However, for the browser to be able to display the Excel file, one should set the correct media_type in the FileResponse (for Excel files see here), as well as .xlsx (or .xls) must be a known file extension to the browser (this is usually achieved through web browser extensions/plug-ins).
Question: I was working on a medium level leetcode question 11. Container With Most Water. Besides the brute force solution with O(n^2), there is an optimal solution with complexity of O(n) by using two pointers from left and right side of the container. I am a little bit confused why this "two pointers" method must include the optimal solution. Does anyone know how to prove the correctness of this algorithm mathematically? This is an algorithm that I don't know of. Thank you! The original question is:  You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container.  A brutal solution for this question is(O(n^2)):  def maxArea(self, height: List[int]) -> int: length = len(height) volumn = 0 #calculate all possible combinations, and compare one by one: for position1 in range(0,length): for position2 in range (position1 + 1, length): if min(height[position1],height[position2])*(position2 - position1) >=volumn: volumn = min(height[position1],height[position2])*(position2 - position1) else: volumn = volumn return volumn  Optimal solution approach, The code I wrote is like this(O(n)):  def maxArea(self, height: List[int]) -> int: pointerOne, pointerTwo = 0, len(height)-1 maxVolumn = 0 #Move left or right pointer one step for whichever is smaller while pointerOne != pointerTwo: if height[pointerOne] <= height[pointerTwo]: maxVolumn = max(height[pointerOne]*(pointerTwo - pointerOne), maxVolumn) pointerOne += 1 else: maxVolumn = max(height[pointerTwo]*(pointerTwo - pointerOne), maxVolumn) pointerTwo -= 1 return maxVolumn  Does anyone know why this "two pointers" method can find the optimal solution? Thanks!

Answer: Based on my understanding the idea is roughly:  Starting from the farthest-apart bars (i.e. first and last bar) and then narrowing width to find potentially better pair(s).  Steps:  We need to have the ability to loop over all 'potential' candidates (the candidates better than what we have on hand rather than all candidates as you did in brutal solution) thus starting from outside bars and no inner pairs will be missed.  If an inner bar pair does exist, it means the height is higher than bars we have on hand, so you should not just #Move left or right pointer one step but #Move left or right pointer to next taller bar .  Why #Move left or right pointer whichever is smaller? Because the smaller bar doesn't fulfill the 'potential' of the taller bar.   The core idea behind the steps is: starting from somewhere that captures optimal solution inside (step 1), then by each step you are reaching to a better solution than what you have on hand (step 2 and 3), and finally you will reach to the optimal solution. One question left for you to think about: what makes sure the optimal solution is not missed when you are executing the steps above? :)
Question: I use black to automatically format all of my Python code whenever I save in VSCode. I'd like the same functionality, but within a Jupyter notebook in VSCode. This answer shows how to right click and format a cell or a whole notebook from the right click context menu, or a keyboard shortcut. Can I make this happen on save instead? It looks like there is an issue related to this, but it is over a year old. Are there any good workarounds? Maybe a way to set the format notebook option to the same keybinding as save? UPDATE: If you like me want this functionality to be added please go to the issue and upvote it, the devs said they will need a bunch of upvotes before it's considered. UPDATE: This got enough attention that it has been added!

Answer: Good news! This is now an option in the newest VSCode release (1.77) Setting "notebook.formatOnSave.enabled": true will do the trick. You can read more about it here. If you have black already enabled for Python it should work fine.
Question: I’m learning py-script where you can use <py-script></py-script> in an HTML5 file to write Python Code. As a python coder, I would like to try web development while still using python, so it would be helpful if we could output and input information using py-script. For example, could someone explain how to get this function to work: <html> <head> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <div>Type an sample input here</div> <input id = “test_input”></input> <-- How would you get this button to display the text you typed into the input into the div with the id, “test”--!> <button id = “submit-button” onClick = “py-script-function”> <div id = “test”></div> <div <py-script> <py-script> </body> </html  I would appreciate it and I hope this will also help the other py-script users.

Answer: I checked source code on GitHub and found folder examples. Using files todo.html and todo.py I created this index.html (which I tested using local server python -m http.server) Some elements I figured out because I have some experience with JavaScript and CSS - so it could be good to learn JavaScript and CSS to work with HTML elements. <!DOCTYPE html> <html> <head> <!--<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />--> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <div>Type an sample input here</div> <input type="text" id="test-input"/> <button id="submit-button" type="submit" pys-onClick="my_function">OK</button> <div id="test-output"></div> <py-script> from js import console def my_function(*args, **kwargs): #print('args:', args) #print('kwargs:', kwargs) console.log(f'args: {args}') console.log(f'kwargs: {kwargs}') text = Element('test-input').element.value #print('text:', text) console.log(f'text: {text}') Element('test-output').element.innerText = text </py-script> </body> </html>   Here screenshot with JavaScript console in DevTool in Firefox. It needed longer time to load all modules (from Create pyodine runtime to Collecting nodes...) Next you can see outputs from console.log(). You may also use print() but it shows text with extra error writing to undefined ....
Question: I'm sure this question must have already been answered somewhere but I couldn't find an answer that suits my case. I have 2 pandas DataFrames a = pd.DataFrame({'A1':[1,2,3], 'A2':[2,4,6]}, index=['a','b','c']) b = pd.DataFrame({'A1':[3,5,6], 'A2':[3,6,9]}, index=['a','c','d'])  I want to merge them in order to obtain something like result = pd.DataFrame({ 'A1' : [3,2,5,6], 'A2' : [3,4,6,9] }, index=['a','b','c','d'])  Basically, I want a new df with the union of both indexes. Where indexes match, the value in each column should be updated with the one from the second df (in this case b). Where there is no match the value is taken from the starting df (in this case a). I tried with merge(), join() and concat() but I could not manage to obtain this result.

Answer: You could use pd.concat to create one dataframe (b being the first one as it is b that has a priority for it's values to be kept over a), and then drop the duplicated index: Using your sample data: c = pd.concat([b,a]) c[~c.index.duplicated()].sort_index()  prints:  A1 A2 a 3 3 b 2 4 c 5 6 d 6 9
Question: So i have the following schema: domain (partition key) time_stamp (sort key) I am (attempting) to use boto to query dynamo. I want to return all records with a given domain, after a given time_stamp. I have tried a couple of different approaches to no avail: First is my ideal approach. I believe it to be much cleaner it also uses between which i would like to incorporate if possible. resp = table.query( KeyConditionExpression=Key('domain').eq(domain) and Key('time_stamp').between(start,end), ProjectionExpression= 'time_stamp,event_type,country,tablet,mobile,desktop') ERROR: An error occurred (ValidationException) when calling the Query operation: Query condition missed key schema element: domain  Here is the second approach that I took. It appeared more often in docs and other stack questions that I found. Yet, I am still getting an error. resp = table.query( ExpressionAttributeNames={ '#nd': 'domain', '#nts': 'time_stamp' }, ExpressionAttributeValues={ ':vd': domain, ':vts': start, }, KeyConditionExpression='(#nd = :vd) AND (#nts > :vts)', ProjectionExpression= 'time_stamp,event_type,country,tablet,mobile,desktop') ERROR: An error occurred (ValidationException) when calling the Query operation: One or more parameter values were invalid: Condition parameter type does not match schema type  I believe this error may be related to the data type of time_stamp being a string and not the Decimal() format that dynamo uses to represent numbers.

Answer: You have to use & not and. resp = table.query( KeyConditionExpression=Key('domain').eq(domain) & Key('time_stamp').between(start,end), ProjectionExpression= 'time_stamp,event_type,country,tablet,mobile,desktop')  This is where the AWS docs say this, but it's kind of buried in there.