eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I have a really pretty gt table that we'd like to automate production of. Running this on our remote server has some limitations: enterprise policy is that no browsers, headless or otherwise, may be installed on the server; the admin has been unwilling to install wkhtmltopdf. So I can either run this locally, which I'd rather avoid, or I can schedule it to crank out an HTML table, which is a pain for the person who actually uses these images. Rendering the gt_tbl using ggplot destroys a lot of the formatting that was done. The R script that generates the table is set up now to output an html table. I'm open to solutions in R or Python that can run after the table is generated. Thanks!

Answer: Figured it out! foo <- <a gt_tbl object> library(ggplot2) library(ggplotify) library(rsvg) #required to render SVG cells foo_1 <- as_gtable(foo) foo_2 <- as.ggplot(foo_1) ggsave('path/to/file.png', foo_2)
Question: I have a script for doing test readouts that worked fine with Python 3.9 but now we upgraded to Python 3.12 we have those carets that break the script. So the easiest way would be disabling it. Is there a way to disable the carets (^^^^^^^^^^^^^^^^^^^^) in the Python stacktrace? ERROR: test_email (tests.test_emails.EmailTestCase.test_email) ---------------------------------------------------------------------- Traceback (most recent call last): File "/my-project/email/tests/test_emails.py", line 72, in test_email self.assertNotEquals(self.email.id, self.email_id) ^^^^^^^^^^^^^^^^^^^^ 

Answer: You can run Python with the -X no_debug_ranges command-line option, or set the PYTHONNODEBUGRANGES environment variable (to any nonempty string) before running your program, to disable these indicators.
Question: Issue The docstring is lost when setting type parameters on a generic. Minimal example: from typing import TypeVar, Generic T = TypeVar("T") class Test(Generic[T]): """My docstring""" assert Test.__doc__ == "My docstring"  This works fine as expected. However, this fails as __doc__ is now None: assert Test[int].__doc__ == "My docstring"  Expectation I would expect the docstring to still be the same. Afterall, it's still the "same" class. Is there something I just don't understand about how Python's typing system making this intendet behavior? Background Using parameterized types in FastAPI, I'm losing the description (coming from the docstring) when generating OpenAPI specs. I can fix this with a decorator, but that leads to more problems in my case with Pydantic's model creation. But that's besides the point. I'd like to understand why this is happening in the first place regardless of non-builtin tools.

Answer: Parameterising user-defined generic types with type arguments results in instances of typing._GenericAlias, which inherits from typing._BaseGenericAlias. >>> type(Test[int]) <class 'typing._GenericAlias'> >>> type(Test[int]).mro() [<class 'typing._GenericAlias'>, <class 'typing._BaseGenericAlias'>, <class 'typing._Final'>, <class 'object'>]  If you look at the source code, it shows you that attributes are relayed from Test to Test[int] via a __getattr__ defined on _BaseGenericAlias. This reveals 2 issues preventing __doc__ from being relayed from Test to Test[int]:  Since Test[int] is an instance of typing._GenericAlias, when you're accessing Test[int].__doc__, you are actually accessing typing._GenericAlias.__doc__; since all classes (including typing._GenericAlias) have a .__doc__ = None if no docstring is provided, __getattr__ is never called and you get None. If you add a dummy docstring to your Python standard library's typing.py, # typing.py ... class _GenericAlias(_BaseGenericAlias, _root=True): """ HELLO """ ...  you can verify the behaviour: >>> Test[int].__doc__ 'HELLO'   Even if __getattr__ were called, the implementation deliberately avoids relaying dunder attributes (like __doc__):  def __getattr__(self, attr): ... # We are careful for copy and pickle. # Also for simplicity we don't relay any dunder names if '__origin__' in self.__dict__ and not _is_dunder(attr): return getattr(self.__origin__, attr) raise AttributeError(attr)
Question: With the following code : nb_vars=4 fig, axs = plt.subplots(4,4,figsize=(8,8), gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi= 100) for i_ax in axs: for ii_ax in i_ax: ii_ax.set_yticklabels([]) for i_ax in axs: for ii_ax in i_ax: ii_ax.set_xticklabels([])  The space between the subplots is white. How is it possible to colour them ? And with different colors ? See for example this figure : 

Answer: You could add patches in between the axes: from matplotlib import patches nb_vars=4 # colors between two axes in a row r_colors = [['#CC0000', '#CC0000', '#CC0000'], ['#0293D8', '#0293D8', '#0293D8'], ['#FF8E00', '#FF8E00', '#FF8E00'], ['#ABB402', '#ABB402', '#ABB402'], ] # colors between two axes in a column c_colors = [['#CC0000', '#0293D8', '#FF8E00', '#ABB402'], ['#CC0000', '#0293D8', '#FF8E00', '#ABB402'], ['#CC0000', '#0293D8', '#FF8E00', '#ABB402'], ] fig, axs = plt.subplots(4, 4, figsize=(4, 4), gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi= 100) h, w = axs.shape for r, i_ax in enumerate(axs): for c, ii_ax in enumerate(i_ax): ii_ax.set_yticklabels([]) ii_ax.set_xticklabels([]) ii_ax.plot([-r, r], [-c, c]) # plot dummy line for demo bbox = ii_ax.get_position() if r+1 < h: ii_ax.add_patch(patches.Rectangle((bbox.x0, bbox.y0), bbox.width, -0.2, facecolor=c_colors[r][c], zorder=-1, clip_on=False, transform=fig.transFigure, figure=fig )) if c+1 < w: ii_ax.add_patch(patches.Rectangle((bbox.x1, bbox.y0), 0.2, bbox.height, facecolor=r_colors[r][c], zorder=-1, clip_on=False, transform=fig.transFigure, figure=fig ))  Output:
Question: def func(string): stringlist= string.split() stringlist =[] for pos in string: stringlist.append(pos) for pan in stringlist: if pan %2 ==0: pan.upper() print(stringlist) func("Hello")  Tried everything I know. I just get an error about TypeError: not all arguments converted during string formatting

Answer: You could make use of enumerate, which returns index and value within the string: def func(string): return ''.join(char.upper() if index % 2 == 0 else char for index, char in enumerate(string)) print(func("Hello")) HeLlO
Question: I would like to write complex numbers z into the standard form z = a + i b with a and b real numbers. For most of my cases, the sympy construct z.expand(complex=True) does what I am expecting but not in all cases. For instance, I fail to rewrite z = 5**sp.I and SymPy just gives back the input: In [1]: import sympy as sp In [2]: c1 = 2 * sp.sqrt(2) * sp.exp(-3 * sp.pi * sp.I / 4) In [3]: c1.expand(complex=True) # works as expected Out[3]: -2 - 2*I In [4]: c2 = 5**(sp.I) # SymPy fails here In [5]: c2.expand(complex=True) Out[5]: re(5**I) + I*im(5**I) In [6]: sp.__version__ Out[6]: '1.13.2'  For c2, I would expect the conversion to give me cos(log(5)) + i * sin(log(5)). Is there a way to obtain this result?

Answer: First convert it to exponential form, then convert to trig. from sympy import I, cos, exp expr = 5 ** I expr = expr.rewrite(exp).rewrite(cos) print( expr )  Output: cos(log(5)) + I*sin(log(5))
Question: 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: In order to have an extra level of dictionary nesting, you need to perform an additional groupby. This is most easily done in a dictionary comprehension: out = {k: {k2: ['ALL']+sorted(v2.unique().tolist()) for k2, v2 in v.groupby('Country')['AREA_CODE'] } for k, v in df.drop_duplicates().groupby('Region') }  Or using a single groupby and a for loop: out = {} for (k1, k2), v in df.groupby(['Region', 'Country'])['AREA_CODE']: out.setdefault(k1, {})[k2] = ['ALL']+sorted(v.unique())  Output: {'AMER': {'CANADA': ['ALL', 'A1'], 'US': ['ALL', 'A1', 'B1'], }, }  Example with more regions: # input Region Country AREA_CODE 0 AMER US A1 1 AMER CANADA A1 2 AMER US B1 3 AMER US A1 4 ASIA INDIA C1 # output {'AMER': {'CANADA': ['ALL', 'A1'], 'US': ['ALL', 'A1', 'B1']}, 'ASIA': {'INDIA': ['ALL', 'C1']}}
Question: I have set of microscopy images, each subset has two channels which I need to merge into one .tif image (Each merged image should contain two channels) import cv2 as cv im1 = cv.imread('/img1.tif', cv.IMREAD_UNCHANGED) im2 = cv.imread('/img1.tif', cv.IMREAD_UNCHANGED) im3 = im1 + im2 cv.imwrite('img3.tif', im3)  That way it creates a file with one channel, but I'd like to get 16-bit .tif image with two channels that can be viewed separately in ImageJ, for example. Which way it can be corrected?

Answer: If you wanted to generate a TIFF file containing a "stack" of images, you don't need tifffile. You can use OpenCV's own function cv.imwritemulti(): import cv2 as cv im1 = cv.imread('img1.tif', cv.IMREAD_UNCHANGED) im2 = cv.imread('img1.tif', cv.IMREAD_UNCHANGED) im3 = [im1, im2] # a stack of two cv.imwritemulti('img3.tif', im3)
Question: When use match-case pattern, I found that case typing.BinaryIO(): can not match object with type io.BytesIO. So I try this: import io import typing assert issubclass(list, typing.Sequence) assert issubclass(list, typing.List) assert issubclass(dict, typing.Mapping) assert issubclass(dict, typing.Dict) # assert issubclass(io.StringIO, typing.TextIO) # failed! # assert issubclass(io.BytesIO, typing.BinaryIO) # failed! a = [1, 2, 3] b = {"a": 1, "b": 2, "c": 3} c = io.BytesIO(b"123123123") d = io.StringIO("123123123") assert isinstance(a, typing.List) assert isinstance(a, typing.Sequence) assert isinstance(b, typing.Dict) assert isinstance(b, typing.Mapping) # assert isinstance(c, typing.BinaryIO) # failed! # assert isinstance(d, typing.TextIO) # failed!  It shows that io.BytesIO and io.StringIO are not subclass of typing.BinaryIO and typing.TextIO, which in my opinion is strange since official documents never hint me to be carefule about this behaviour (or at least I never found it). What is more strange is a .pyi stub file i found, its path is /data/users/XXXXXX/.vscode-server/extensions/ms-python.vscode-pylance-2024.11.1/dist/typeshed-fallback/stdlib/_io.pyi. I found this line in the stub file: class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO):, which implies that things should be as they should be for my intuition. Is this intentional design or a bug? If is a design, why? I'm using Python 3.12.3 with mypy 1.13.0, under VSCode 1.93.1 with pylance 2024.11.1 extension.

Answer: Classes in the typing module are not meant to be used for instance / subclass checks at runtime. Their purpose is type hinting. If you want to use instance / subclass checks like that, check out collections.abc, especially this overview. For io.StringIO and io.BytesIO, their abstract base classes are io.TextIOBase and io.BufferedIOBase. Their common base class is io.IOBase.
Question: I'm writing a Python script that uploads a Polars DataFrame to Google Sheets and formats it accordingly. One of my goals is to create a summary row at the bottom of the table that sums the numerical values for each column. Currently, I have the following code snippet that successfully constructs a summary row: # Add a summary row at the end of the data num_rows = len(data) total_row = ['Grand Total', ""] for col in range(2, len(header)): total_formula = f'=SUM({chr(65 + col)}2:{chr(65 + col)}{num_rows})' total_row.append(total_formula) new_sheet.append_row(total_row)  The problem is, I've encountered an issue where this code creates a string in the grand total row that includes a leading single quote, like this: '=SUM(F2:F47)  This prevents Google Sheets from executing it as a formula. My Question: How can I modify this code to ensure that it writes an executable formula to Google Sheets without the leading single quote? Any insights or suggestions would be greatly appreciated! Additional Context: Packages use include  gspread oauth2client polars gspread-formatting  Data Structure: I’m using a Polars DataFrame to manage my data before uploading it to Google Sheets. Thank you!

Answer: The default value_input_option is set to RAW in gspread's append_row method. The input data won't be parsed, if set to RAW according to sheets API. Set it to USER_ENTERED: new_sheet.append_row(total_row, value_input_option='USER_ENTERED')  Or new_sheet.append_row(total_row, value_input_option=gspread.utils.ValueInputOption.user_entered)
Question: I've got the next code: data = [{'TpoMoneda': 'UYU'}, {'MntNetoIvaTasaMin': '3825.44'}, {'IVATasaMin': '10.000'}, {'IVATasaBasica': '22.000'}, {'MntIVATasaMin': '382.54'}, {'MntTotal': '4207.98'}, {'MntTotRetenido': '133.90'}, {'CantLinDet': '2'}, {'RetencPercep': None}, {'RetencPercep': None}, {'MontoNF': '0.12'}, {'MntPagar': '4342.00'}] df = pd.DataFrame.from_dict(data, orient = 'columns')  My dataframe looks like this: # TpoMoneda MntNetoIvaTasaMin IVATasaMin ... RetencPercep MontoNF MntPagar # 0 UYU NaN NaN ... NaN NaN NaN # 1 NaN 3825.44 NaN ... NaN NaN NaN # 2 NaN NaN 10.000 ... NaN NaN NaN # 3 NaN NaN NaN ... NaN NaN NaN # 4 NaN NaN NaN ... NaN NaN NaN # 5 NaN NaN NaN ... NaN NaN NaN # 6 NaN NaN NaN ... NaN NaN NaN # 7 NaN NaN NaN ... NaN NaN NaN # 8 NaN NaN NaN ... NaN NaN NaN # 9 NaN NaN NaN ... NaN NaN NaN # 10 NaN NaN NaN ... NaN 0.12 NaN # 11 NaN NaN NaN ... NaN NaN 4342.00 # # [12 rows x 11 columns]  I want to have all the data in one unique index (1 row x 11 columns), for example: # TpoMoneda MntNetoIvaTasaMin IvaTasaMin ... RetencPercep MontoNF MntPagar # 0 UYU 3825.44 10.000 Nan 0.12 4342.00 # # [1 rows x 11 columns]  Despite I don´t speak english very well, I´m open to trying understand all the solutions someone can give me. Thank all!

Answer: You can use map + pd.transpose like below pd.DataFrame( map(lambda x: df[x].dropna().values, df.columns), index=df.columns ).transpose()  which gives  TpoMoneda MntNetoIvaTasaMin IVATasaMin IVATasaBasica MntIVATasaMin MntTotal \ 0 UYU 3825.44 10.000 22.000 382.54 4207.98 MntTotRetenido CantLinDet RetencPercep MontoNF MntPagar 0 133.90 2 None 0.12 4342.00   Or, you can try pd.aggregate like below pd.DataFrame( df.agg(lambda x: x.dropna().values[0] if any(~x.isna()) else np.nan, axis=0) ).transpose()  which gives  TpoMoneda MntNetoIvaTasaMin IVATasaMin IVATasaBasica MntIVATasaMin MntTotal \ 0 UYU 3825.44 10.000 22.000 382.54 4207.98 MntTotRetenido CantLinDet RetencPercep MontoNF MntPagar 0 133.90 2 NaN 0.12 4342.00
Question: As you might have recognized from my other questions I am transitioning from pandas to polars right now. I have a polars df with differently nested lists like this: ┌────────────────────────────────────┬────────────────────────────────────┬─────────────────┬──────┐ │ col1 ┆ col2 ┆ col3 ┆ col4 │ │ --- ┆ --- ┆ --- ┆ --- │ │ list[list[str]] ┆ list[list[str]] ┆ list[str] ┆ str │ ╞════════════════════════════════════╪════════════════════════════════════╪═════════════════╪══════╡ │ [["a", "a"], ["b", "b"], ["c", "c"]┆ [["a", "a"], ["b", "b"], ["c", "c"]┆ ["A", "B", "C"] ┆ 1 │ │ [["a", "a"]] ┆ [["a", "a"]] ┆ ["A"] ┆ 2 │ │ [["b", "b"], ["c", "c"]] ┆ [["b", "b"], ["c", "c"]] ┆ ["B", "C"] ┆ 3 │ └────────────────────────────────────┴────────────────────────────────────┴─────────────────┴──────┘  Now I want to join the lists inside out using different separators to reach this: ┌─────────────┬─────────────┬───────┬──────┐ │ col1 ┆ col2 ┆ col3 ┆ col4 │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str │ ╞═════════════╪═════════════╪═══════╪══════╡ │ a+a-b+b-c+c ┆ a+a-b+b-c+c ┆ A-B-C ┆ 1 │ │ a+a ┆ a+a ┆ A ┆ 2 │ │ b+b-c+c ┆ b+b-c+c ┆ B-C ┆ 3 │ └─────────────┴─────────────┴───────┴──────┘  I do this by using map_elements and a for loop, but I guess that is highly inefficient. Is there a polars native way to manage this? Here is my code: import polars as pl df = pl.DataFrame({"col1": [[["a", "a"], ["b", "b"], ["c", "c"]], [["a", "a"]], [["b", "b"], ["c", "c"]]], "col2": [[["a", "a"], ["b", "b"], ["c", "c"]], [["a", "a"]], [["b", "b"], ["c", "c"]]], "col3": [["A", "B", "C"], ["A"], ["B", "C"]], "col4": ["1", "2", "3"]}) nested_list_cols = ["col1", "col2"] list_cols = ["col3"] for col in nested_list_cols: df = df.with_columns(pl.lit(df[col].map_elements(lambda listed: ['+'.join(element) for element in listed], return_dtype=pl.List(pl.String))).alias(col)) # is the return_dtype always pl.List(pl.String)? for col in list_cols + nested_list_cols: df = df.with_columns(pl.lit(df[col].list.join(separator='-')).alias(col)) 

Answer: You could use list.eval() and .list.join() df.with_columns( pl.col(nested_list_cols).list.eval(pl.element().list.join("+")).list.join("-"), pl.col(list_cols).list.join("-") )  shape: (3, 4) ┌─────────────┬─────────────┬───────┬──────┐ │ col1 ┆ col2 ┆ col3 ┆ col4 │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str │ ╞═════════════╪═════════════╪═══════╪══════╡ │ a+a-b+b-c+c ┆ a+a-b+b-c+c ┆ A-B-C ┆ 1 │ │ a+a ┆ a+a ┆ A ┆ 2 │ │ b+b-c+c ┆ b+b-c+c ┆ B-C ┆ 3 │ └─────────────┴─────────────┴───────┴──────┘
Question: newlist = ['test', '%ing', 'osh', '16fg'] tartext = 'Singing'  I want to check my tartext value doesn't matching with any value with newlist. if the newlist string contains % symbol in the value then I need to match this as wildcard charecter. I want to achieve condition as below. if (tartext != 'test' and tartext not like '%ing' and tartext != 'osh' and tartext != '16fg') then return true else false  Since %ing from the lsit contains '%' symbol in it I need to change the comparison as wildcard chatecter search like sql. In this example 'Singing' is matching with '%ing' then I am expecting the condition to return False. Below is the code that I have tried but didn't work import re newlist = ['test', '%ing', 'osh', '16fg'] tartext = 'Singing' def wildcard_compare(string, match): match = match.replace('%','.*')#.replace('_','.') match_expression = f'^{match}$' return bool(re.fullmatch(match_expression,string)) def condition_match(lookupstring, mylist): for value in mylist: if '%' in value: if not wildcard_compare(lookupstring,value): return True else: if value != lookupstring: return True return False print(condition_match(tartext,newlist)) print(condition_match('BO_IN',['AP_IN','BO_IN','CA_PS'])) 

Answer: One approach would be to use regular expressions. In this approach, we can replace % in the newlist by .*. Then, use re.search along with a list comprehension to find any matches. newlist = ['test', '%ing', 'osh', '16fg'] tartext = 'Singing' newlist = [r'^' + x.replace('%', '.*') + r'$' for x in newlist] num_matches = sum([1 for x in newlist if re.search(x, tartext)]) if num_matches > 0: print("found a match") # prints here else: print("no matches")  Edit: See the comment below by @ekhumoro in the case that your input string might also have regex metacharacters in it.
Question: When I run Dutch sentiment analysis RobBERTje, it outputs just positive/negative labels, netural label is missing in the data. https://huggingface.co/DTAI-KULeuven/robbert-v2-dutch-sentiment There are obvious neutral sentences/words e.g. 'Fhdf' (nonsense) and 'Als gisteren inclusief blauw' (neutral), but they both evaluate to positive or negative. Is there a way to get neutral labels for such examples in RobBERTje? from transformers import RobertaTokenizer, RobertaForSequenceClassification from transformers import pipeline import torch model_name = "DTAI-KULeuven/robbert-v2-dutch-sentiment" model = RobertaForSequenceClassification.from_pretrained(model_name) tokenizer = RobertaTokenizer.from_pretrained(model_name) classifier = pipeline('sentiment-analysis', model=model, tokenizer = tokenizer) result1 = classifier('Fhdf') result2 = classifier('Als gisteren inclusief blauw') print(result1) print(result2)  Output: [{'label': 'Positive', 'score': 0.7520257234573364}] [{'label': 'Negative', 'score': 0.7538396120071411}] 

Answer: This model was trained only on negative and positive labels. Therefore, it will try to categorize every input as positive or negative, even if it is nonsensical or neutral. what you can do is to: 1- Find other models that was trained to include neutral label. 2- Fine-tune this model on a dataset that includes neutral label. 3- Empirically define a threshold based on the confidence outputs and interpret it as neutral. The first 2 choices are extensive in effort. I would suggest you go with the third option for a quick workaround. Try feeding the model with a few neutral input and observe the range of confidence score in the output. then use that threshold to classify as neutral. Here's a sample: def classify_with_neutral(text, threshold=0.5): result = classifier(text)[0] # Get the classification result if result['score'] < threshold: result['label'] = 'Neutral' # Override label to 'Neutral' return result
Question: I was surprised that this seems to work without parentheses: dict = { "a": 1 if True else 2, "b": 2 }  I know that dictionaries have implicit line continuation, but I presumed that only let you split between commas. Does it simply function like parentheses, where everything is treated as one line?

Answer: Yes, implicit line continuation/joining takes place within parentheses, square brackets and curly braces in Python as documented:  Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes.
Question: I am learning pytorch and deep learning. The documentation for torch.max doesn't make sense in that it looks like we can compare 2 tensors but I don't see where in the documentation I could have determined this. I had this code at first where I wanted to check ReLU values against the maximum. I thought that 0 could be broadcast for and h1.shape=torch.Size([10000, 128]). h1 = torch.max(h1, 0) y = h1 @ W2 + b2  However, I got this error: TypeError: unsupported operand type(s) for @: 'torch.return_types.max' and 'Tensor' I got to fix this when I changed the max equation to use a tensor instead of 0. h1 = torch.max(h1, torch.tensor(0)) y = h1 @ W2 + b2  1. Why does this fix the error? This is when I checked the documentation again and realized that there is nothing mentions a collection like a tuple or list for multiple tensors or even a *input for iterable unpacking. Here are the 2 versions: 1st torch.max version:  torch.max(input) → Tensor Returns the maximum value of all elements in the input tensor. Warning This function produces deterministic (sub)gradients unlike max(dim=0)  2nd version of torch.max  torch.max(input, dim, keepdim=False, *, out=None) Returns a namedtuple (values, indices) where values is the maximum value of each row of the input tensor in the given dimension dim. And indices is the index location of each maximum value found (argmax). If keepdim is True, the output tensors are of the same size as input except in the dimension dim where they are of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensors having 1 fewer dimension than input.  2. What is tensor(0) according to this documentation?

Answer: Check the bottom of the documentation page you linked where it says: torch.max(input, other, *, out=None) → Tensor See torch.maximum().  When the second argument is a tensor, torch.max computes torch.maximum