eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I am getting the following TypeError Traceback (most recent call last): File "/my/path/my_project/src/my_project/exploration/mre_lazyframe_error.py", line 39, in <module> current.with_columns(pl.col("foo_bar").is_in(reference["foo_bar"])) File "/my/path/.cache/pypoetry/virtualenvs/my_project-p95GORRi-py3.10/lib/python3.10/site-packages/polars/lazyframe/frame.py", line 619, in __getitem__ raise TypeError(msg) TypeError: 'LazyFrame' object is not subscriptable (aside from slicing)  MRE import numpy as np import polars as pl num_rows = 10000 ids = np.arange(num_rows) foo_bar = np.random.randint(1, 101, num_rows) current = pl.LazyFrame( { "id": ids, "foo_bar": foo_bar, } ) reference = pl.LazyFrame( { "id": ids, "foo_bar": np.random.randint( 1, 101, num_rows ), # different random numbers for 'reference' } ) current.with_columns( pl.col("foo_bar").is_in(reference["foo_bar"]).name.suffix("_avail"), ) current.with_columns(pl.col("foo_bar").is_in(reference["foo_bar"]))  As far as I understand it this should be possible (is_in docs). When I do it in eager it runs through without any error. However I would preferably compute everything in lazy. Is there anyway to make this work?

Answer: Subscription of DataFrame return series, but subscription (or get_column() method) is not implemented for LazyFrame (what would it even return?). There is a closed issue where it was decided that it's not going to be implemented. If amount of distinct values in reference frame is not large (as in your case), you could collect the values and convert them to series: ( current .with_columns( pl.col("foo_bar").is_in( reference.select("foo_bar").unique().collect().to_series() ).name.suffix("_avail") ) )  In general such operations are usually much faster with joins, though. To get all the rows where foo_bar exists in reference you could use pl.LazyFrame.join with how="semi":   semi Returns rows from the left table that have a match in the right table.    current.join(reference, on="foo_bar", how="semi")
Question: I am trying to run a simple "Hello World" script which is named print("hello world!").py by pressing the "play" button in the top-right of the VS Code window. I'm using Python 3.13.0, macOS 12.6.1 and VS Code 1.94. The VS Code terminal prints: dafyddpowell@Dafydds-MBP \~ % cd "/Volumes/SAMSUNG/Python projects" dafyddpowell@Dafydds-MBP Python projects % /usr/bin/python3 "/Volumes/SAMSUNG/Python projects/print("Hello world!").py" zsh: parse error near \`)' dafyddpowell@Dafydds-MBP Python projects %   What is wrong?

Answer: It seems like VSCode isn't escaping the file name that contains special characters. The simplest way around this would be to use a filename that doesn't have any special characters like hello_world.py.
Question: Given a function which is a staticmethod of a class, is there a way to extract the parent class object from this? class A: @staticmethod def b(): ... ... f = A.b ... assert get_parent_object_from(f) is A  I can see this buried in the __qualname__, but can't figure out how to extract this. The function get_parent_object_from should have no knowledge of the parent class A.

Answer: One approach would be to use a custom static method descriptor that sets the owner class as an attribute of the wrapped function: class StaticMethod(staticmethod): def __set_name__(self, owner, name): self.__wrapped__.owner = owner class A: @StaticMethod def b(): ... f = A.b assert f.owner is A  Demo here
Question: I can't get my tkinter project to work. i haven't been succesful into getting the input from the entry label from a user to then that info get worked on through my function of encryptation, so it can print the output in the output label. from tkinter import * from cryptography.fernet import Fernet raiz= Tk() #def output():# # texto.set(print(Encriptador))# raiz.title("Codec") texto= StringVar() raiz.resizable(False, False) #raiz.iconbitmap("logo.ico")# #raiz.geometry("650x360")# raiz.config(bg="dark green") frame1= Frame() frame1.pack() frame1.config(bg="dark green") frame1.config(width=650,height=400) prompt= Label(text="Coloque el texto a encriptar", fg="black", font="Bold", bg="dark green") prompt.place(x=230, y=80) def Encriptador(): mensaje= cuadroinput.get key= Fernet.generate_key() cifrar= Fernet(key) mensaje_cifrado = cifrar.encrypt(mensaje.encode()) cuadroutput.config(Text= mensaje_cifrado) cuadroinput=Entry(frame1, width=40) cuadroinput.place(x=200 , y=120) cuadroutput=Entry(frame1, width=70, textvariable=texto) cuadroutput.place(x=100, y=300) boton=Button(raiz,text="Encriptar", command=Encriptador) boton.place(x=305, y=170) raiz.mainloop() 

Answer: The problem with your code is: def Encriptador(): mensaje= cuadroinput.get # <------ here key= Fernet.generate_key() cifrar= Fernet(key) mensaje_cifrado = cifrar.encrypt(mensaje.encode()) cuadroutput.config(Text= mensaje_cifrado)  The .get that you are calling, is a function, and a function, in Python, must have (). The fix is simply changing mensaje= cuadroinput.get to mensaje= cuadroinput.get() Another thing you can do is give cuadroinput a textvariable, and create a StringVar(). Here is an example, using your code: invar = StringVar() def Encriptador(): mensaje= invar.get() key= Fernet.generate_key() cifrar= Fernet(key) mensaje_cifrado = cifrar.encrypt(mensaje.encode()) cuadroutput.config(Text= mensaje_cifrado) cuadroinput=Entry(frame1, width=40, textvariable = invar)
Question:  <div class="mb-3"> {{ form.ism.label(class="form-label") }} {{% if form.ism.errors %}} {{ form.ism(class="form-control form-control-lg is-invalid") }} <div class="invalid-feedback"> {% for error in form.ism.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.ism(class="form-control form-control-lg") }} {{% endif %}} </div>  jinja2.exceptions.TemplateSyntaxError:  unexpected '%'  How can I solve this error? I looked code again and again, but I could not find the what is real problem. Debugger saying error at 4. line. This code: {{% if form.ism.errors %}} 

Answer: The syntax for variables is {{ myVar }} The syntax for expressions such as if and for is {% if ... %} Thus, instead of writing {{% %}}, you should go with {% %} which is the appropriate syntax.
Question: The question is:  You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?  I wrote this code: if __name__ == '__main__': count_sundays = 0 day_name = 3 # this is tuesday day = 1 month = 1 year = 1901 months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 0: 31} while not ((year == 2000) and (month == 0) and (day == 0)): print(year, month, day) if day_name == day == month == 1: count_sundays += 1 day += 1 day_name += 1 day_name = day_name % 7 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: months[2] = 29 else: months[2] = 28 day = day % months[month] if day == 1: month = month + 1 month = month % 12 if month == 1 and day == 1: year += 1 print(count_sundays)  I am getting 14 which is the wrong answer, if anyone can point out what's wrong with my code that would be great.

Answer: Your code has issue on following condition, where you are checking if month == 1, which means it'll only count Sundays if it's 1st January of the year. if day_name == day == month == 1:  instead you should use: if day_name == day == 1:   just a suggestion if you are open to code change, as you are only concern about 1st day of every month, instead of going through every day of the years, traverse through 1st day of every month. if __name__ == "__main__": count_sundays = 0 week_day = 3 # this is tuesday year = 1901 months = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 } while year < 2001: if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: months[2] = 29 else: months[2] = 28 for month in range(1, 13): # first day of the next month week_day = (week_day + months[month]) % 7; if week_day == 1: count_sundays += 1 year += 1 print(count_sundays)
Question: d = defaultdict(str) d['one'] = 'hi' del d['one'] del d['one']  The second del raises a KeyError. d.pop('one') has the same problem. Is there a concise way to make the defaultdict reset-to-default a keypair? if 'one' in d: del d['one']  is more verbose than I would like.

Answer: The below should work (pop with None) The pop() method allows you to specify a default value that gets returned if the key is not found, avoiding a KeyError exception. from collections import defaultdict d = defaultdict(str) d['one'] = 'hi' d.pop('one', None) d.pop('one', None) print('Done')
Question: I have a pandas DataFrame with a time series (in this case price of a used car model) and am looking for a vectorized function to map each cell to the time it takes the price to grow n percent from that cell (if it never reaches n% more then return nan) It should in theory be possible to execute in a vectorized way as the output of each row is independent of what comes before it Here is a sample of the data and expected output import numpy as np import pandas as pd import datetime df = pd.DataFrame( [ 1490.47, 1492.98, 1494.69, 1497.43, 1499.02, 1503.29, 1501.60, 1502.80, 1502.30, 1509.38, 1512.01, 1508.98, 1512.63, ], columns=['price'], ) df.index.names = ['time'] n=1/100  So in this case I want to run for n=1/100 so compute for each cell the time it takes the price to increase by 1%. So for the first cell, 1% grows would be at 1490.47*1.01 = 1505.3747, the first cell greater than this value is 1509.38 which is 9 cells after the first cell so the output for that cell would be 9, and so on for the rest... Expected output would then be: df.some_functions(n=1/100) print(df) price time 0 9 1 8 2 8 3 nan 4 nan 5 nan 6 nan 7 nan 8 nan 9 nan 10 nan 11 nan 12 nan  The latter 10 being nan because the price does not grow to greater than 1% of their cell in the remaining DataFrame.

Answer: Another option is to use numba (you can even easily parallelize the task): import numba @numba.njit(parallel=True) def search(price, n, out): for idx in numba.prange(len(price)): p = price[idx] search_for = p * n for idx2, v in enumerate(price[idx:]): if v >= search_for: out[idx] = idx2 break df["out"] = np.nan search(df["price"].values, 1.01, df["out"].values) print(df)  Prints:  price out time 0 1490.47 9.0 1 1492.98 8.0 2 1494.69 8.0 3 1497.43 9.0 4 1499.02 NaN 5 1503.29 NaN 6 1501.60 NaN 7 1502.80 NaN 8 1502.30 NaN 9 1509.38 NaN 10 1512.01 NaN 11 1508.98 NaN 12 1512.63 NaN   On my AMD 5700x it took ~0.8seconds to compute dataframe with 1_000_000 np.random.uniform(1000, 2000, 1_000_000) values.
Question: I have an df which has 2 columns lets say Region and Country. Region Country ================================ AMER US AMER CANADA APJ INDIA APJ CHINA  I have grouped the unique Country list for each Region using the code and o/p like below: df.drop_duplicates().groupby("Region")['Country'].agg(lambda x: sorted(x.unique().tolist())).to_dict()  OUTPUT { 'AMER': ['US', 'CANADA'], 'APJ': ['INDIA', 'CHINA'] }  Is there way with to add a default value "ALL" to every list? ============================================================= EDIT: I have a similar situation again and really would need some help here. I have an df which has 3 columns lets say Region, Country and AREA_CODE. Region Country AREA_CODE =================================== AMER US A1 AMER CANADA A1 AMER US B1 AMER US A1  I want to get the output like list of AREA_CODE for each country under each Region with 'ALL' as list value as well. something like { "AMER": { "US": ["ALL", "A1", "B1"], "CANADA": ["ALL", "A1"] } }  So far i have tried to groupby both region and country column and then tried to group & agg it by AREA_CODE, it is throwing error df.drop_duplicates().groupby(["Region", "Country"]).groupby("Country")['AREA_CODE'].agg(lambda x: ["ALL"]+sorted(x.unique().tolist())).to_dict()  Could someone kindly help me with this. Thanks,

Answer: You can add ['ALL'] in your agg: (df.drop_duplicates().groupby("Region")['Country'] .agg(lambda x: sorted(x.unique().tolist())+['ALL']) .to_dict() )  Also note you you don't really need agg and could use a dictionary comprehension: out = {k: sorted(v.unique().tolist())+['ALL'] for k, v in df.drop_duplicates().groupby("Region")['Country']}  Output: {'AMER': ['CANADA', 'US', 'ALL'], 'APJ': ['CHINA', 'INDIA', 'ALL']}
Question: I try to sort all rows with a certain value in a group to the last place in every group. data = {'a':[1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3], 'b':[100, 300, 200, 222, 500, 300, 222, 100, 200, 222, 300, 500, 400, 100], 'c':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]} df1 = pd.DataFrame(data) df1 Out[29]: a b c 0 1 100 1 1 1 300 2 2 1 200 3 3 1 222 4 4 1 500 5 5 2 300 6 6 2 222 7 7 2 100 8 8 3 200 9 9 3 222 10 10 3 300 11 11 3 500 12 12 3 400 13 13 3 100 14 should be: Out[31]: a b c 0 1 100 1 1 1 300 2 2 1 200 3 3 1 500 5 4 1 222 4 5 2 300 6 6 2 100 8 7 2 222 7 8 3 200 9 9 3 300 11 10 3 500 12 11 3 400 13 12 3 100 14 13 3 222 10  one of my attempts is: df1 = df1['b'].eq[222].sort(position='last').groupby(df1['a']) But I haven't found a solution yet

Answer: Use double DataFrame.sort_values - first by b with key parameter and then by a column with kind parameter: out = (df1.sort_values('b', key = lambda x: x==222) .sort_values('a', ignore_index=True, kind='stable')) print (out) a b c 0 1 100 1 1 1 300 2 2 1 200 3 3 1 500 5 4 1 222 4 5 2 300 6 6 2 100 8 7 2 222 7 8 3 200 9 9 3 300 11 10 3 500 12 11 3 400 13 12 3 100 14 13 3 222 10  Solution with helper column should be faster - added by DataFrame.assign and removed by DataFrame.drop: out = df1.assign(tmp = df1['b'].eq(222)).sort_values(['a','tmp']).drop('tmp', axis=1) print (out) a b c 0 1 100 1 1 1 300 2 2 1 200 3 4 1 500 5 3 1 222 4 5 2 300 6 7 2 100 8 6 2 222 7 8 3 200 9 10 3 300 11 11 3 500 12 12 3 400 13 13 3 100 14 9 3 222 10  Or use np.lexsort for positions and change order by DataFrame.iloc: out = df1.iloc[np.lexsort([df1['b'].eq(222), df1.a])] print (out) a b c 0 1 100 1 1 1 300 2 2 1 200 3 4 1 500 5 3 1 222 4 5 2 300 6 7 2 100 8 6 2 222 7 8 3 200 9 10 3 300 11 11 3 500 12 12 3 400 13 13 3 100 14 9 3 222 10  For default index add DataFrame.reset_index with drop=True: out = out.reset_index(drop=True) print (out) a b c 0 1 100 1 1 1 300 2 2 1 200 3 3 1 500 5 4 1 222 4 5 2 300 6 6 2 100 8 7 2 222 7 8 3 200 9 9 3 300 11 10 3 500 12 11 3 400 13 12 3 100 14 13 3 222 10
Question: My input data: df=pd.DataFrame({'ID':['A','B','C','D'], 'Group':['group1','group1','group2','group2'], 'Flag_1':[1,0,0,1], 'Flag_2':[1,1,0,1], 'Value':[30,40,60,70] })  I am trying to add up "Value" per group when flag is equal to 1. My expected output is: df_value_group=pd.DataFrame({ 'Flag_1 Sum':[1,1], 'Flag_2 Sum':[2,1], 'Value_1 Sum':[30,70], 'Value_2 Sum':[70,70]}, index=['group1','group2'])  I have tried this but it throws me an AssertionError error primarly due to the latter two lambda function. df.groupby('Group').agg( **{ 'Flag_1 Sum': ('Flag_1','sum'), 'Flag_2 Sum': ('Flag_2','sum'), 'Value_1 Sum': ('Flag_1', lambda col: df.loc[col.eq(1), 'Value'].sum()), 'Value_2 Sum': ('Flag_2', lambda col: df.loc[col.eq(1), 'Value'].sum()) }) 

Answer: For a generic approach, you could use a custom groupby.agg (named aggregation): cols = df.columns[df.columns.str.startswith('Flag_')] val = df['Value'] out = (df.groupby('Group', as_index=False) .agg(**({f'{c} Sum': (c, lambda x: x.sum()) for c in cols} |{f'Value{c[4:]} Sum': (c, lambda x: val[x.index][x==1].sum()) for c in cols} ) ) )  NB. lambda x: val[x.index][x==1].sum() could be replaced by lambda x: val.where(x==1).sum(). Or reshape with melt and aggregate with pivot_table: tmp = (df .melt(['ID', 'Group', 'Value'], var_name='flag', value_name='bool') .query('bool == 1') .pivot_table(index='Group', columns='flag', aggfunc='sum', fill_value=0, ) ) out = (pd.concat([tmp['bool'], tmp['Value'].rename(columns=lambda x: x.replace('Flag', 'Value')) ], axis=1) .reset_index() .rename_axis(columns=None) )  Output:  Group Flag_1 Flag_2 Value_1 Value_2 0 group1 1 2 30 70 1 group2 1 1 70 70
Question: I have been trying to use the scikit-learn library to solve this problem. Roughly: from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression # Make or load an n x p data matrix X and n x 1 array y of the corresponding # function values. poly = PolynomialFeatures(degree=2) Xp = poly.fit_transform(X) model = LinearRegression() model.fit(Xp, y) # Approximate the derivatives of the gradient and Hessian using the relevant # finite-difference equations and model.predict.  As the above illustrates, sklearn makes the design choice to separate polynomial regression into PolynomialFeatures and LinearRegression rather than combine these into a single function. This separation has conceptual advantages but also a major drawback: it effectively prevents model from offering the methods gradient and hessian, and model would be significantly more useful if it did. My current work-around uses finite-difference equations and model.predict to approximate the elements of the gradient and Hessian (as described here). But I don't love this approach — it is sensitive to floating-point error and the "exact" information needed to build the gradient and Hessian is already contained in model.coef_. Is there any more elegant or accurate method to fit a p-dimensional polynomial and find its gradient and Hessian within Python? I would be fine with one that uses a different library.

Answer: To compute the gradient or the Hessian of a polynomial, one needs to know exponents of variables in each monomial and the corresponding monomial coefficients. The first piece of this information is provided by poly.powers_, the second by model.coef_: from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression import numpy as np np.set_printoptions(precision=2, suppress=True) X = np.arange(6).reshape(3, 2) y = np.arange(3) poly = PolynomialFeatures(degree=2) Xp = poly.fit_transform(X) model = LinearRegression() model.fit(Xp, y) print("Exponents:") print(poly.powers_.T) print("Coefficients:") print(model.coef_)  This gives: Exponents: [[0 1 0 2 1 0] [0 0 1 0 1 2]] Coefficients: [ 0. 0.13 0.13 -0.12 -0. 0.13]  The following function can be then used to compute the gradient at a point given by an array x: def gradient(x, powers, coeffs): x = np.array(x) gp = np.maximum(0, powers[:, np.newaxis] - np.eye(powers.shape[1], dtype=int)) gp = gp.transpose(1, 2, 0) gc = coeffs * powers.T return (((x[:, np.newaxis] ** gp).prod(axis=1)) * gc).sum(axis=1)  For example, we can use it to compute the gradient at the point [0, 1]: print(gradient([0, 1], poly.powers_, model.coef_))  This gives: [0.13 0.38]  The Hessian at a given point can be computed in a similar way.
Question: I'm trying to solve this problem from Leetcode using regexes (just for fun):  You are given two strings sentence1 and sentence2, each representing a sentence composed of words. A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of only uppercase and lowercase English characters. Two sentences s1 and s2 are considered similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. Note that the inserted sentence must be separated from existing words by spaces. For example,  s1 = "Hello Jane" and s2 = "Hello my name is Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in s1. s1 = "Frog cool" and s2 = "Frogs are cool" are not similar, since although there is a sentence "s are" inserted into s1, it is not separated from "Frog" by a space.  Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.  Assuming small and big are the smaller and bigger sentences respectively, it's easy to check whether small is a prefix/suffix of big: if re.match(f'^{small} .*$', big) or re.match(f'^.* {small}$', big): print('similar')  How to best check if the sentences can be made equal by inserting a new sentence in the middle of small using a regex?

Answer: My idea needs the strings to be sorted descending by length before using regex. Then concatenate s1 and s2 by newline and check what single part of s1 could be omitted to match s2 (in next line). import re def isSimilar(s1, s2): regex = r'(?is)\A(?!.* )(\b[a-z ]*)(\b[a-z ]*)(\b[a-z ]*)\n\1\b\3\Z' # sort strings by length desc s = sorted([s1,s2], key=len, reverse=True) # concat by newline and match pattern m = re.match(regex, s[0]+'\n'+s[1]) if(m): return 'similar -> ' + m.group(2).strip() else: return 'not similar!'  See this Python demo at tio.run or a regex demo at regex101 (differs a bit for showcase) s1 = "Hello Jane" s2 = "Hello my name is Jane" print(isSimilar(s1, s2))  will output: similar -> my name is  Note that this was just playing around, the regex pattern is not efficient. It uses three capture groups and checks if the line after the newline can be completed by the captures of the first and third group (omitting second group). The allowed character-set inside each capture group is set to [a-z ] starting with a word boundary. The lookahead at start checks for not more than one space.
Question: I am facing an issue with the title of the following colorbar plots using Python's Matplotlib library. There are two subplots. The title of the first one works well, i.e., LaTeX rendering is done successfully. However, it returns an error for the second one. fig, axs = plt.subplots(1, 2, figsize=(24, 10)) c1 = axs[0].contourf(x, y, zT, 60, cmap='seismic', vmin=-2.5, vmax=2.5) axs[0].set_title(r'$\zeta_T$ at t={}'.format(l)) fig.colorbar(c1, ax=axs[0]) c2 = axs[1].contourf(x, y, bcv, 40, cmap='seismic', vmin=-0.25, vmax=0.25) axs[1].set_title(r'$\sqrt{U_c^2 + V_c^2}$ at t={}'.format(l)) fig.colorbar(c2, ax=axs[1])  The error is as follows: KeyError Traceback (most recent call last) Cell In[27], line 80 79 c2 = axs[1].contourf(x, y, bcv, 40, cmap='seismic', vmin=-0.25, vmax=0.25) ---> 80 axs[1].set_title(r'$\sqrt{U_c^2 + V_c^2}$ at t={}'.format(l)) 81 fig.colorbar(c2, ax=axs[1]) KeyError: 'U_c^2 + V_c^2'  I wonder why the LaTeX command $\sqrt{U_c^2+V_c^2}$ does not work in the title. Why is the LaTeX rendering not working in Matplotlib? I tried to fix it in several ways, but I consistently get that "KeyError". I used plt.rc('text', usetex=True) to enable LaTeX rendering in Matplotlib. But it did not work either. I want to fix this LaTeX rendering issue in Matplotlib.

Answer: This is LaTeX syntax clashing with function of pythons .format() method. The latter looks for curly brackets {...} in the string and operates on them, but there are two sets of curly brackets in  r'$\sqrt{U_c^2 + V_c^2}$ at t={}'  and the first contains something that does not fit with the .format() syntax. I suggest you split this up as two strings, with just the format method on the second one  r'$\sqrt{U_c^2 + V_c^2}$ ' + 'at t={}'.format(l)  Here is a complete working example of similar character (I don't have your data). import matplotlib.pyplot as plt import numpy as np plt.rc('text', usetex=True) x = np.linspace(-np.pi, np.pi, 100) t = 3.0 fig, ax = plt.subplots() ax.plot(x, np.sqrt(x**2+1)) ax.set_title(r'$\sqrt{x^2 + 1}$' + ' at {}'.format(t))