eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: A permutation of size n is a sequence of n integers in which each of the values ​​from 1 to n occurs exactly once. For example, the sequences [3, 1, 2], [1], and [1, 2, 3, 4] are permutations, while [2], [4, 1, 2], [3, 1] are not. So i recieve 2 inputs: 1 - number of numbers in permutation,2 - the permutation by itself. The question is: how many intervals are there [l;r](1 ≤ l ≤ r ≤ n) for which the sequence p[l..r] is also a permutation? For example: input - 7; [6, 3, 4, 1, 2, 7, 5] The answer is 4: permutation is [6, 3, 4, 1, 2, 7, 5]; permutation is [1]; permutation is [1, 2]; permutation is [3, 4, 1, 2]  Hope u undestood the question. I wrote the first 2 cases, but i don't know how to check for others: numbers = int(input("Amount of elements in permutation: ")) perm = list(input("Permutation: ")) perm = [ int(x) for x in perm if x != " "] amount = 1 first = 1 if len(perm) == numbers and int(max(perm)) == numbers and int(min(perm)) == 1: if first in perm and len(perm) > 1: amount += 1 

Answer: l = [6, 3, 4, 1, 2, 7, 5] left_bound = right_bound = l.index(1) permutations = [] for i in range(1,len(l)+1): new_index = l.index(i) # special case if i == 1 if new_index == left_bound == right_bound: pass # if new index if further to the left, update the left index elif new_index < left_bound: left_bound = new_index # same with the right one elif new_index > right_bound: right_bound = new_index # Because we always have all numbers up to and including i # in the list l[left_bound:right_bound+1], we know that if # it has not the length i, numbers that are not in the order # are in there -> no permutation. if len(l[left_bound:right_bound+1])==i: permutations.append(l[left_bound:right_bound+1]) print(permutations)  Actually just tried it with that one example, if there is an error pls tell me.
Question: I am learning basic flask but cannot import db(database) from freecodecamp I cannot find the solution plz answer this query as soon as possible There are 4 files : when I write from app import db the pythonshell shows error app.py from flask import Flask,render_template, url_for from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URL'] = 'sqlite://test.db' db = SQLAlchemy(app) class Todo(db.Model): id = db.Column(db.Integer, primary_key = True) content = db.Column(db.String(200), nullable = False) date_created = db.Column(db.DateTime, default = datetime.utcnow) def __repr__(self): return '<Task %r>' % self.id @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run(debug = True)  main.css body { margin: 0; font-family: sans-serif; }  base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width-device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie-edge"> <link rel="stylesheet" href= "{{ url_for('static', filename = 'css/main.css')}}"> {% block head %}{% endblock %} </head> <body> {% block body %}{% endblock %} </body> </html>  index.html {% extends 'base.html'%} {% block head %} {% endblock %} {% block body %} <h1>Template</h1> {% endblock %}  Terminal Window

Answer: You need to initialize db as well, db = SQLAlchemy() # db intitialized here app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://test.db" db.init_app(app)  It's SQLALCHEMY_DATABASE_URI not SQLALCHEMY_DATABASE_URL
Question: I call Flask-SQLAlchemy's query.paginate method with arguments. Recently this stopped working and instead raised a TypeError. How do I pass page and other arguments to query.paginate? Ticker.query.paginate(page, app.config["TICKERS_PER_PAGE"], False)  TypeError: Query.paginate() takes 1 positional argument but 4 were given 

Answer: As of Flask-SQLAlchemy 3.0, all arguments to paginate are keyword-only. Ticker.query.paginate(page=page, per_page=app.config["TICKERS_PER_PAGE"], error_out=False)
Question: Not sure how else to word the title, but this is what I need: Print either the number zero, the number one or a phrase in no consecutive order twenty times. This is what I have:  n = 0 x = “hello” for i in range(20): print(n, end= ‘’) or print(n+1, end= ‘’) or print(x)  The only problem is that it prints them out in order so that it is always 01hello01hello01hello and so on. I need it to be randomized so that it could print something like 000hello1hello101 or just any random variation of the three variables. Let me know how :)

Answer: import random choices = [1, 0, "hello"] for i in range(20): print(random.choice(choices))
Question: I am looking for an efficient way to turn this pandas dataframe:  A B C 0 0 1 0 1 0 1 1 2 1 1 1 3 1 1 0 4 0 0 1  into  A B C 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 0 4 0 0 1  I only want "1" in a cell, if in the original dataframe the value jumps from "0" to "1". If it's the first row, I want a "1", if "1" is the start value. I have to use this operation often in my project and on a large dataframe, so it should be as efficient as possible. Thanks in advance!

Answer: You can use: df.diff().clip(0).fillna(df)  output:  A B C 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 0 4 0 0 1
Question: We have a discriminator field type which we want to hide from the Swagger UI docs: class Foo(BDCBaseModel): type: Literal["Foo"] = Field("Foo", exclude=True) Name: str class Bar(BDCBaseModel): type: Literal["Bar"] = Field("Bar", exclude=True) Name: str class Demo(BDCBaseModel): example: Union[Foo, Bar] = Field(discriminator="type")  The following router: @router.post("/demo") async def demo( foo: Foo, ): demo = Demo(example=foo) return demo  And this is shown in the Swagger docs:  We don't want the user to see the type field as it is useless for him/her anyways. We tried making the field private: _type which hides it from the docs but then it cannot be used as discriminator anymore:  class Demo(BDCBaseModel): File "pydantic\main.py", line 205, in pydantic.main.ModelMetaclass.__new__ File "pydantic\fields.py", line 491, in pydantic.fields.ModelField.infer File "pydantic\fields.py", line 421, in pydantic.fields.ModelField.__init__ File "pydantic\fields.py", line 537, in pydantic.fields.ModelField.prepare File "pydantic\fields.py", line 639, in pydantic.fields.ModelField._type_analysis File "pydantic\fields.py", line 753, in pydantic.fields.ModelField.prepare_discriminated_union_sub_fields File "pydantic\utils.py", line 739, in pydantic.utils.get_discriminator_alias_and_values pydantic.errors.ConfigError: Model 'Foo' needs a discriminator field for key '_type' 

Answer: This is a very common situation and the solution is farily simple. Factor out that type field into its own separate model. The typical way to go about this is to create one FooBase with all the fields, validators etc. that all child models will share (in this example only name) and then subclass it as needed. In this example you would create one Foo subclass with that type field that you then use for the Demo annotation, and one FooRequest class without any additions. Here is a full working example: from typing import Literal, Union from fastapi import FastAPI from pydantic import BaseModel, Field class FooBase(BaseModel): name: str class FooRequest(FooBase): pass # possibly configure other request specific things here class Foo(FooBase): type: Literal["Foo"] = Field("Foo", exclude=True) class Config: orm_mode = True class Bar(BaseModel): type: Literal["Bar"] = Field("Bar", exclude=True) name: str class Demo(BaseModel): example: Union[Foo, Bar] = Field(discriminator="type") api = FastAPI() @api.post("/demo") async def demo(foo: FooRequest): foo = Foo.from_orm(foo) return Demo(example=foo)  Note that I used the orm_mode = True setting just to have a very concise way of converting a FooRequest instance into a Foo instance inside the route handler function. This is not necessary. You could also just do foo = Foo.parse_obj(foo.dict()) there. Also, the addition of the FooRequest model is redundant here of course. You can just as well use the FooBase as the request model. I wrote it this way just to demonstrate a typical pattern because sometimes the request model has additional things that distinguish it from its siblings. In your example it is overkill.
Question: I have a function that can return different types given a boolean input argument. Currently, I just annotate it using union: def fn(x: int, ret_str: bool) -> Union[int, str]: if ret_str: return str(x) else: return x  However, if I annotate like this, the output of this function will be typed as a union type as well. out = fn(8, ret_str=False) # out will have type Union[int, str] but we know it's int  Is there a way to annotate it such that the type checker will know if I call the function with a literal False, the return type has to be int instead of str?

Answer: Yes, this is possible using the typing module and overload/Literal. It isn't the most elegant solution since it is so verbose (in comparison to most typed languages), but will cause the type checker to associate a return type depending on arguments passed. I would probably avoid doing this in most circumstances outside of libraries/modules or other code I know will be referenced repeatedly from an external source. from typing import Literal, overload @overload def fn(x: int, ret_str: Literal[False]) -> int: ... @overload def fn(x: int, ret_str: Literal[True]) -> str: ... def fn(x: int, ret_str: bool) -> int | str: if ret_str: return str(x) return x  If wanting to implement more advanced type checking like this, it is usually beneficial to store this information in a separate pyi file instead of directly in your program. Finally, please note that the @overload decorator is purely for the type checker. You cannot put different functionality into a function with it, since the final declaration of the function will always overwrite any previous definitions (regardless of if the decorator is used). As such, putting an ellipsis (...) in overloaded function definitions is the paradigm.
Question: I am having a very simple FastAPI service, when I try to hit the /spell_checking endpoint, I get this error `AttributeError: 'dict' object has no attribute 'encode'. I am hitting the endpoint using postman, with Post request, and this is the url: http://127.0.0.1:8080/spell_checking, the payload is JSON with value: {"word": "testign"}  Here is my code: from fastapi import FastAPI, Response, Request import uvicorn from typing import Dict app = FastAPI() @app.post('/spell_checking') def spell_check(word: Dict ) : data = { 'corrected': 'some value' } return Response(data) @app.get('/') def welcome(): return Response('Hello World') if __name__ == '__main__': uvicorn.run(app, port=8080, host='0.0.0.0')  I still dont know why a simple service like this would show this error!

Answer: The problem happens when you try to create the Response object. This object expects a string as input (infact it tries to call .encode() on it). There is no need to explicitly create one, you can just return the data and fastapi will do the rest. from typing import Dict import uvicorn from fastapi import FastAPI app = FastAPI() @app.post("/spell_checking") def spell_check(word: Dict): data = {"corrected": "some value"} return data @app.get("/") def welcome(): return "Hello World" if __name__ == "__main__": uvicorn.run(app, port=8080, host="0.0.0.0")
Question: So I have this simple python dash application in which I've laid out a graph and a button. My goal is this: when I press the button, I want to retrieve the shapes that have been drawn. import plotly.graph_objects as go import dash from dash import html, dcc, Input, Output, State app = dash.Dash(__name__) fig = go.Figure() app.layout = html.Div([ dcc.Graph(id = "graph-pic", className="graph-pic", figure=fig, config={'modeBarButtonsToAdd':['drawrect', 'eraseshape']}), html.Button("Shape count", id = "shape-count-button") ]) fig.add_shape(editable=True, x0=-1, x1=0, y0=2, y1=3, xref='x', yref='y') @app.callback( Output("graph-pic", "figure"), Input("shape-count-button", "n_clicks") ) def on_shape_count_button_pressed(n_clicks): trigger_id = dash.callback_context.triggered_id if trigger_id == "shape-count-button": print("Shape count: " + str(len(fig.layout.shapes))) print(fig.layout.shapes) return dash.no_update if __name__ == "__main__": app.run_server()   When I press the button, it only prints the first shape that I've added through code... and NOT the ones that I've drawn on the graph with the draw rectangle tool. Output: Shape count: 1 (layout.Shape({ 'editable': True, 'x0': -1, 'x1': 0, 'xref': 'x', 'y0': 2, 'y1': 3, 'yref': 'y' }),)  Any hint would be appreciated!

Answer: You should use relayout_data to detect all the drawn shapes on the graph, and then you can parse the desired data as you would: import dash import json import plotly.graph_objects as go from dash import html, dcc, Input, Output, State app = dash.Dash(__name__) fig = go.Figure() app.layout = html.Div([ dcc.Graph(id = "graph-pic", className="graph-pic", figure=fig, config={'modeBarButtonsToAdd':['drawrect', 'eraseshape']}), html.Button("Shape count", id = "shape-count-button"), html.Div(id="text") ]) fig.add_shape(editable=True, x0=-1, x1=0, y0=2, y1=3, xref='x', yref='y') @app.callback( Output("text", "children"), Input("shape-count-button", "n_clicks"), Input("graph-pic", "relayoutData"), ) def on_shape_count_button_pressed(n_clicks, relayout_data): trigger_id = dash.callback_context.triggered_id if trigger_id == "shape-count-button": text_lst = "Shape count: " + str(len(fig.layout.shapes)) text_lst += str(fig.layout.shapes) if "shapes" in relayout_data: text_lst += json.dumps(relayout_data["shapes"], indent=2) return text_lst return dash.no_update if __name__ == "__main__": app.run_server()  Output
Question: Is there a way to use match case to select string endings/beginnings like below? match text_string: case 'bla-bla': return 'bla' case .endswith('endofstring'): return 'ends' case .startswith('somestart'): return 'start' 

Answer: You were close. You wanted a conditional guard on a pattern. In the following case, one that simply matches the value. match text_string: case 'bla-bla': return 'bla' case s if s.endswith('endofstring'): return 'ends' case s if s.startswith('somestart'): return 'start'  This doesn't gain much over the following. if text_string == 'bla-bla': return 'bla' elif text_string.endswith('endofstring'): return 'ends' elif text_string.startswith('somestart'): return 'start'  Unless you're also using the match and want to differentiate between two otherwise identical patterns.
Question: I'm running a flask app using itsdangerous python package in AWS EC2 instance. Traceback (most recent call last): File "run.py", line 4, in <module> app = create_app() File "/home/ubuntu/RHS_US/application/portal/__init__.py", line 29, in create_app from portal.users.routes import users File "/home/ubuntu/RHS_US/application/portal/users/routes.py", line 7, in <module> from portal.models import User File "/home/ubuntu/RHS_US/application/portal/models.py", line 7, in <module> from itsdangerous import TimedJSONWebSignatureSerializer as Serializer ImportError: cannot import name 'TimedJSONWebSignatureSerializer' from 'itsdangerous' (/home/ubuntu/.local/lib/python3.7/site-packages/itsdangerous/__init__.py)  Any resolution for this?

Answer: First make sure to re-install and update itsdangerous. pip install -U itsdangerous  Then what you want to do is  from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer  This works well.
Question: I'm trying to start a subprocess and pass a pipe file descriptor to it to read from. However when I try to read from the pipe in the child process I get "Bad file descriptor", even though I can read from the pipe in the parent process just fine. Here's the parent process: import subprocess import sys import os r, w = os.pipe() os.set_inheritable(r, True) p = subprocess.Popen(["python3", "client.py", str(r)]) os.write(w, b"hello") p.wait()  And here's the child process: import sys import os r = int(sys.argv[1]) print("[Client]", os.read(r, 5))  Any help would be much appreciated.

Answer: From the official Python docs:  Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds parameter is False.
Question: Environment:  Visual Code Jupyter extension (v2022.9.1202862440) Kernel: Python 3.10.1 64-bit Pyplot version: 5.10.0 Nbformat version: 5.7.0  What happened? I am trying to use simple boxplot with plotly.express via this code: #Basic vizualization fig = px.box(dataset, y='Rh2') fig.update_layout( height=1000 )  First error was pretty straight forward: ValueError: Mime type rendering requires nbformat>=4.2.0 but it is not installed which I resolved using this answer. Second error is the one I am getting now: No renderer could be found for mimetype "application/vnd.plotly.v1+json", but one might be available on the Marketplace.  I have no idea what could be done here - on the internet no such question is mentioned (at least I couldn't find any) + market space didn't help either! Thanks in advance  EDIT: Tried adding: pio.renderers.default = "vscode" and various others but they result in no error and just blank space.

Answer: Try to install Jupyter Notebook Renderers extension on vscode.
Question: I am learning FastAPI and I have this example. from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}  I saved the script as main.ipynb The tutorial says to run this line of code in the command line: uvicorn main:app --reload I am getting this error: (venv) PS C:\Users\xxx\xxxx> uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [21304] using WatchFiles ERROR: Error loadinimport module "main".INFO: Stopping reloader process [21304]  The reason is because I am using .ipynb as opposed to .py. How can i fix this error while using .ipynb. Thanks so much

Answer: If you attempted to start the server as usual inside Jupyter, for example: import uvicorn if __name__ == "__main__": uvicorn.run(app)  you would get the following error: RuntimeError: asyncio.run() cannot be called from a running event loop  This is due to Jupyter already running an event loop, and once Uvicorn calls asyncio.run() internally, the above error is raised. As per asyncio.run() documentation:  This function cannot be called when another asyncio event loop is running in the same thread (see relevant asyncio implementation, where the error is raised). [...] This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.  Solution 1 If you wouldd like to run uvicorn from an already running async environment, use uvicorn.Server.serve() instead (you could add the below to a new code cell in your Jupyter notebook, and then run it): import asyncio import uvicorn if __name__ == "__main__": config = uvicorn.Config(app) server = uvicorn.Server(config) await server.serve()  or, get the current (running) event loop, using asyncio.get_running_loop(), and then call loop.create_task() for creating a task to run inside the event loop for the current thread: import asyncio import uvicorn if __name__ == "__main__": config = uvicorn.Config(app) server = uvicorn.Server(config) loop = asyncio.get_running_loop() loop.create_task(server.serve())  Solution 2 Alternatively, you can use nest_asyncio, which allows nested use of asyncio.run() and loop.run_until_complete(): import nest_asyncio import uvicorn if __name__ == "__main__": nest_asyncio.apply() uvicorn.run(app)
Question: I am trying to set up a simple Discord bot for a server, but it only appears to be responding in DMs to commands and not in any server channels. The bot has admin permissions in the server I am trying to get it to respond in. After doing some looking around I have found no fixes. Here's the code: import discord token_file = open("bot_token.txt", "r+") TOKEN = str(token_file.readlines()).strip("[]'") token_file.close() command_prefix = ">" client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print("Logged in as: {0.user}".format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith(command_prefix): if message.content == ">help": await message.channel.send("What do you need help with?") elif message.content == ">hello": await message.channel.send("Hi there!") else: await message.channel.send("This command is not recognised by our bot, please use the help menu if required.") else: return client.run(TOKEN)  Hope someone can help!

Answer: Two things must be done before you can respond to messages within channels:  Configuration the intent of the bot within discord developer portal Specify the intent within the bot itself.  Step 1: Configuring the intent of the bot in developer portal: Within the developer portal, find your bot under applications. Selecting the "bot" tab from the left, you'll see the following option:  It needs to be enabled. If you try the below without enabling it, you will get a permission error:  ... from None discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.  Step 2: Specifying intent in the bot: Specifying intent is done through the following lines. It is required in addition to the option being enabled in the developer portal.  intents = discord.Intents.default() intents.message_content = True  Discord added a message content intent that has to be used since the first September 2022. if you‘re doing a discord.py tutorial, be aware that it should be a 2.0 tutorial as many things have been updated since then. Consider using the commands extension of discord.py as it is handling some annoying stuff and provides more easier interfaces to handle commands.
Question: I have Pandas lambda function which I use with .apply. This function will output a dictionary with string keys and values that are either strings or pd.NA. When I try to type hint the function I get an error: def _the_function(x: str) -> dict[str, str | pd.NA]: ...  ERROR: Expected class type but received "NAType"  How can I tell it of the possible pd.NA value without having to import numpy and using its NaN type hint? My project has no need to import numpy.

Answer: Your problem comes from the fact that pandas.NA is not a type. It is an instance (a singleton in fact) of the NAType class in Pandas. You need to use classes in type annotations.* More precisely, annotations must be made with instances of type (typically called classes) or special typing constructs like Union or generics. You can fix this by importing and using that class in the type annotation: import pandas as pd from pandas._libs.missing import NAType ... def _the_function(x: str) -> dict[str, str | NAType]: return {"foo": pd.NA} # example to show annotations are correct  Running mypy over that code shows no errors. The only problem is that _libs is a non-public module (as denoted by its name starting with _). This may be due to the NA singleton still being considered experimental. I don't know. But importing from non-public modules is generally discouraged. I searched through the Pandas (and pandas-stubs) source and found no public re-import of the NAType class, so I see no other way around it. If NA is still experimental, I suppose you know the risk you are taking when relying on it in your functions, so importing its class should not make much of a difference to you. Hope this helps.  * Confusion can arise because Python allows using None in type annotations, even though strictly speaking it is also an object (also a singleton) of the NoneType class. But the good people working on type hints in Python decided to still allow None as a special case for convenience, even though it is not exactly consistent. As far as I know, that is the only such exception.