eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: The following code import numpy as np x = np.arange(32).reshape(2,2,2,2,2) extra = [1 for _ in range(3)] print(x[*extra, 0, 0])  prints 28 as expected in Python 3.12 but results in the syntax error  File "main.py", line 4 print(x[*extra, 0, 0]) ^ SyntaxError: invalid syntax  in Python 3.8. Replacing the indexing with print(x[(*extra, 0, 0)]) works in both versions. The NumPy documentation states that the offending line is syntax sugar for the working one, so I do not understand why there is a syntax error. A quick search for the terms "unpack","index", and "getitem" for the versions 3.9 to 3.12 (inclusive) on https://docs.python.org/3/whatsnew/index.html didn't turn up any indication that there was a change to indexing or unpacking syntax, although I may have missed something. The closest I found was that Python 3.11 has the change "Starred unpacking expressions can now be used in for statements."

Answer: This was a consequence of grammar changes in PEP 646 – Variadic Generics and somehow didn't get a mention in the changelog for 3.11. Minimal reproducer: $ python3.11 -c 'print({():42}[*()])' 42 $ python3.10 -c 'print({():42}[*()])' File "<string>", line 1 print({():42}[*()]) ^^^^^^^^^^^^ SyntaxError: invalid syntax. Perhaps you forgot a comma?  The relevant diff can be found at #31018: Implement PEP 646 grammar changes.
Question: I am using groupby and agg to summarize groups of dataframe rows. I summarize each group in terms of its count and size: >>> import pandas as pd >>> df = pd.DataFrame([ [ 1, 2, 3 ], [ 2, 3, 1 ], [ 3, 2, 1 ], [ 2, 1, 3 ], [ 1, 3, 2 ], [ 3, 3, 3 ] ], columns=['A','B','C'] ) >>> gbB = df.groupby('B',as_index=False) >>> Cagg = gbB.C.agg(['count','size']) B count size 0 1 1 1 1 2 2 2 2 3 3 3  The result looks like a dataframe with columns for the grouping variable B and for the summaries count and size: >>> Cagg.columns Index(['B', 'count', 'size'], dtype='object')  However, I can't access each of the count and size columns for further manipulation as series or by conversion to_list: >>> Cagg.count <bound method DataFrame.count of B count size 0 1 1 1 1 2 2 2 2 3 3 3> >>> Cagg.size 9  Can I access the individual column-like data with headings count and size?

Answer: Don't use attributes to access the columns, this conflicts with the existing methods/properties. Go with indexing using square brackets: Cagg['count'] # 0 1 # 1 2 # 2 3 # Name: count, dtype: int64 Cagg['size'] # 0 1 # 1 2 # 2 3 # Name: size, dtype: int64
Question: It is not allowed to set a value for a MultiIndex. It works for the single index. Maybe becaause of the version of pandas. import pandas as pd df = pd.DataFrame() df.loc[('a', 'b'), 'col1'] = 1 print(df)   KeyError: "None of [Index(['a', 'b'], dtype='object')] are in the [index]" 

Answer: You can do either import pandas as pd index = pd.MultiIndex.from_tuples([], names=['level_1', 'level_2']) df = pd.DataFrame(columns=['col1'], index=index) df.loc[('a', 'b'), 'col1'] = 1 print(df)  or import pandas as pd df = pd.DataFrame(columns=['col1'], index=pd.MultiIndex(levels=[[], []], codes=[[], []], names=['level_1', 'level_2'])) df.loc[('a', 'b'), 'col1'] = 1 print(df)  which returns  col1 level_1 level_2 a b 1
Question: I'm trying to get the StringVar object associated with an Entry widget, but I can't figure out how. I found this question: get StringVar bound to Entry widget but none of the answers work for me. Both entry["textvariable"] and entry.cget("textvariable") return the name of the StringVar and not the StringVar itself (although the answer with the second explains it properly, unlike the answer with the first which is NOT clear that it only returns the name. I've submitted an edit for the first that fixes this). You're supposed to be able to get the StringVar from its name using entry.getvar(name), but this is returning a str with the contents of the StringVar instead of the StringVar itself. I don't understand why this is happening, because the answer that explains this is marked as correct, and the person who asked the question seems to have wanted the StringVar itself. Did something get changed? If so, how would I get the StringVar now? I'm using Python 3.11.9 at the moment. I would also prefer a method that doesn't need the name of the StringVar, as an Entry without a StringVar explicitly set seems to have a StringVar without a name. Here is some example code: from tkinter import * from tkinter.ttk import * root = Tk() stringVar = StringVar(root, "test") # obviously in the real program I wouldn't be able to access this without using the Entry entry = Entry(root, textvariable=stringVar) entry.pack() name1 = entry["textvariable"] name2 = entry.cget("textvariable") print(name1 == name2) # True shouldBeStringVar = entry.getvar(name1) print(name1, type(name1)) # PY_VAR0 <class 'str'> print(shouldBeStringVar, type(shouldBeStringVar)) # test <class 'str'> 

Answer: If you know the name of the variable, you can simply "create" a StringVar and set its parameter "name" to that name. This way you will simply get the variable you created earlier. So try this: ... string_name = entry["textvariable"] TheVarObjectYouNeed = var = tk.StringVar(name=string_name) print(f"The var {var} has a type {type(var)}, just as you wanted") print(f'And it has the value "{var.get()}"') ...  Note that this code actually creates a new StringVar object. But since I set it to an existing name, "TheVarObjectYouNeed" will actually refer to the same internal variable inside the underlying TCL interpreter (as correctly stated in the comment below), same TCL variable is used for your Entry widget.
Question: i have a question regarding comparison with numpy arrays while using cusom data types. Here is my code: import numpy as np class Expr: def __add__(self, other): return Add(self, other) def __eq__(self, other): return Eq(self, other) class Variable(Expr): def __init__(self, name): self.name = name def __repr__(self): return self.name class Operator(Expr): def __init__(self, left, right): self.left = left self.right = right def __repr__(self): return f'{self.__class__.__name__}({self.left}, {self.right})' class Add(Operator): ... class Eq(Operator): ... if __name__ == '__main__': arr1 = np.array([Variable('v1'), Variable('v2')]) arr2 = np.array([Variable('v3'), Variable('v4')]) print(arr1 + arr2) print(arr1 == arr2)  The output is: [Add(v1, v3) Add(v2, v4)] [ True True]  I dont get why the equal comparison does not return [Eq(v1, v3) Eq(v2, v4)], because my code works for the Addition. How do i make this work. Thank you!

Answer: == on arrays produces an output of boolean dtype. The result array physically cannot hold Eq instances; it can only hold booleans. Your Eq instances get converted to booleans, producing True, since that's the boolean value of any object that doesn't define __len__ or __bool__. If you want an array of Eq instances, you need an output of object dtype. You can get that by specifying a dtype for numpy.equal: res = numpy.equal(arr1, arr2, dtype=object)
Question: MRE from transitions import Machine class TradingSystem: def __init__(self): self.machine = Machine(model=self, states=['RUNNING'], initial='RUNNING') def check_running(self) -> None: if self.is_RUNNING(): print("System is running")  Example usage system = TradingSystem() system.check_running()  Issue mypy transitions_mypy.py  gives the error: transitions_mypy.py:9: error: "TradingSystem" has no attribute "is_RUNNING" [attr-defined]  This can be avoided by bypassing mypy, for example adding # type: ignore[attr-defined] at the end of line 9. But what is the proper way? Is it better to avoid bypassing mypy? Perhaps by manually defining the attribute?

Answer: The answer @Mark proposed won't work since transitions does not override already existing model attributes because that would be unexpected (mis)behaviour (as @Mark pointed out). If you enable logging, transitions will also tell you that: import logging logging.basicConfig(level=logging.DEBUG)  The output should contain: WARNING:transitions.core:Model already contains an attribute 'is_RUNNING'. Skip binding.  In the past, I suggested to inherit from Machine and override Machine._checked_assignment to workaround that safeguard. However, @james-hirschorn's approach using attrs which was posted in the transitions issue tracker is a better solution in my oppinion: from typing import Callable from attrs import define, field from transitions import Machine @define(slots=False) class TradingSystem: is_RUNNING: Callable[[], bool] = field(init=False) stop: Callable[[], None] = field(init=False) def __attrs_post_init__(self): self.machine = Machine(model=self, states=['RUNNING', 'STOPPED'], initial='RUNNING') self.machine.add_transition(trigger='stop', source='RUNNING', dest='STOPPED') def check_running(self) -> None: if self.is_RUNNING(): print("System is running") def stop_system(self) -> None: self.stop() print("System stopped") # Example usage system = TradingSystem() system.check_running() system.stop_system()  This produces some overhead since you have to define triggers and convenience methods twice. Furthermore, type information are also incomplete because transitions will also add is_STOPPED and auto transitions like to_STOPPED/RUNNING or 'peek' transition methods such as may_stop to TradingSystem during runtime. Improving transitions typing support is currently an open issue.
Question: What I am after is Python code able to reverse the order of the values in each of the array anti-diagonals in a numpy array. I have already tried various combinations of np.rot90, np.fliplr, np.transpose, np.flipud but none is able to give me the original shape of the 5x3 array with all the anti-diagonals reversed. Any idea how to accomplish this? Example: [[ 1 2 4] [ 3 5 7] [ 6 8 10] [ 9 11 13] [12 14 15]]  Should become: [[ 1 3 6] [ 2 5 9] [ 4 8 12] [ 7 11 14] [10 13 15]]  I suppose it must be easy, but somehow I have yet failed to find how to do it efficiently on arrays with millions of values.  Inspired by the already provided answers (status 2024-05-23 11:37 CET) and re-thinking what would be the most efficient way of getting the required transformation done it seems that giving a simple function taking two indices : iRow, jColumn of a value in an array and returning the required i,j indices to access the array as if it were flipped/reversed over the diagonals will provide fastest results. With such function for the over the diagonals flipped version of the array would be getting the right values without operating on the array as easy as in a trivial case of one-based and column/row based access to array values demonstrated below: import numpy as np srcArr = np.array([[ 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24]]) def ijOfArrayValueGivenOneBasedColumnRowBasedIndices(i, j): return ( j - 1, i - 1 ) print( srcArr[ ijOfArrayValueGivenOneBasedColumnRowBasedIndices( 3,4)] ) # gives 21 print( srcArr[3,4] ) # gives 23  From this perspective the question comes down to providing a function ijIndicesToSourceArray_gettingValueOfSourceArrayWithReversedRightLeftAntiDiagonalsAt(i,j,arrShapeRows,arrShapeColumns)

Answer: This one seems fairly fast, especially for wide matrices like your width=n=1920, height=m=1080 : def mirror(a): m, n = a.shape if m == n: return a.T.copy() if m > n: return mirror(a.T).T # Shear v = a.flatten() w = v[:-m].reshape((m, n-1)) # Flip the parallelogram w[:, m-1:] = w[::-1, m-1:] # Flip the triangles t = np.vstack((w[:, :m-1].reshape((m-1, m)), v[-m:])) t = t.T w[:, :m-1] = t[:-1].reshape((m, m-1)) # Write flipped parts back and unshear v[:-m] = w.ravel() v[-m:] = t[-1] return v.reshape((m, n))  Attempt This Online! The idea: Slice/reshape the m×n matrix to an m×(n-1) matrix so that the parallelogram (green part) becomes a rectangle so we can just flip it upside down. For example:  Now reshape the m×n matrix to an m×(n-1) matrix (omit the black last m cells), which moves the yellow cells to the front of the next row, shifting the next row as needed:  Now we can easily flip the green parallelogram part. For the top-left and bottom-right triangles, reshape/shear the left part of this back and put the omitted cells under it:  This can now simply be transposed and written back.
Question: import typing a: dict[int, int] = {} b: dict[int, int | str] = a c: typing.Mapping[int, int | str] = a d: typing.Mapping[int | str, int] = a  Pylance reports an error for b: dict[int, int | str] = a: Expression of type "dict[int, int]" is incompatible with declared type "dict[int, int | str]" "dict[int, int]" is incompatible with "dict[int, int | str]" Type parameter "_VT@dict" is invariant, but "int" is not the same as "int | str" Consider switching from "dict" to "Mapping" which is covariant in the value type  But c: typing.Mapping[int, int | str] = a is OK. Additionally, d: typing.Mapping[int | str, int] = a also gets an error: Expression of type "dict[int, int]" is incompatible with declared type "Mapping[int | str, int]" "dict[int, int]" is incompatible with "Mapping[int | str, int]" Type parameter "_KT@Mapping" is invariant, but "int" is not the same as "int | str"  Why are these types hint incompatible? If a function declares a parameter of type dict[int, int | str], how can I pass a dict[int, int] object as its parameter?

Answer: dict type was designed to be completely invariant on key and value. Hence when you assign dict[int, int] to dict[int, int | str], you make the type system raise errors. [1] Mapping type on the other hand wasn’t designed to be completely invariant but rather is invariant on key and covariant on value. Hence you can assign one Mapping type (dict[int, int]) to another (Mapping[int, int | str]) if they are both covariant on value. if they are invariant on key, you can assign them else you cannot. Hence when you assign dict[int, int] to Mapping[int | str, int], you make the type system raise errors. [2][3] There is a good reason for the above design in the type system and I will give a few: 1. dict type is a concrete type so it will actually get used in a program. 2. Because of the above mentioned, it was designed the way it was to avoid things like this: a: dict[int, int] = {} b: dict[int, int | str] = a b[0] = 0xDEADBEEF b[1] = "Bull" dicts are assigned by reference [4] hence any mutation to b is actually a mutation to a. So if one reads a as follows: x: int = a[0] assert isinstance(x, int) y: int = a[1] assert isinstance(y, int) One gets unexpected results. x passes but y doesn’t. It then seems like the type system is contradicting itself. This can cause worse problems in a program. For posterity, to correctly type a dictionary in Python, use Mapping type to denote a readonly dictionary and use MutableMapping type to denote a read-write dictionary.  [1] Of course Python’s type system doesn’t influence program’s running behaviour but at least linters have some use of this. [2] dict type is a Mapping type but Mapping type is not a dict type. [3] Keep in mind that the ordering of types is important in type theory. [4] All variable names in Python are references to values.
Question: I am trying to install python dependencies on a python:3.12.3-alpine3.19 Docker immage. When the requirements.txt file is processed I get the following error: 7.932 ERROR: Ignored the following versions that require a different python version: 0.5.12 Requires-Python >=3.7,<3.12; 0.5.13 Requires-Python >=3.7,<3.12; 1.21.2 Requires-Python >=3.7,<3.11; 1.21.3 Requires-Python >=3.7,<3.11; 1.21.4 Requires-Python >=3.7,<3.11; 1.21.5 Requires-Python >=3.7,<3.11; 1.21.6 Requires-Python >=3.7,<3.11 7.932 ERROR: Could not find a version that satisfies the requirement onnxruntime==1.18.0 (from versions: none) 7.933 ERROR: No matching distribution found for onnxruntime==1.18.0 ------ failed to solve: process "/bin/sh -c pip install -r requirements.txt && pip uninstall  Even if I try to install an older version of python I still get an error: From Python:3.10.14-alpine3.19. 61.58 ERROR: Could not find a version that satisfies the requirement onnxruntime==1.18.0 (from versions: none) 61.58 ERROR: No matching distribution found for onnxruntime==1.18.0  Why is this happening?

Answer: It seems that Chroma vector DB does not work (or not out of the box) with Alpine distributions of Python. I switched to Bookworm and was able to install Chroma and use it in the script running in my Docker container.
Question: I'm trying to build MST from a directed graph by converting it to an undirected one. I followed cuGraph example here but getting NotImplementedError: Not supported for distributed graph. I tried doing G = cugraph.Graph(directed=False), but it still gave me an error. My code: columns_to_read = ['subject', 'object', 'predicate'] # Read the TSV file using Dask cuDF with specific columns df = dask_cudf.read_csv('graph_edge.tsv', sep='\t', usecols=columns_to_read) # Renaming columns to match cuGraph requirements df = df.rename(columns={'subject': 'src', 'object': 'dst'}) # Create undirected graph from input data DiG = cugraph.Graph(directed=True) DiG.from_dask_cudf_edgelist(df, source='src', destination='dst') G = DiG.to_undirected() # Verify the graph has edges print("Number of edges in the graph:", G.number_of_edges()) # Define the list of target terminals terminals = ['COMPOUND:7045767', 'COMPOUND:0007271', 'COMPOUND:0035249', 'COMPOUND:0005947', 'COMPOUND:0004129', 'COMPOUND:26519', 'COMPOUND:C0132173', 'COMPOUND:0018393', 'COMPOUND:0006979', 'COMPOUND:0025464', 'COMPOUND:0007613', 'COMPOUND:64645', 'COMPOUND:000010173', 'COMPOUNDGO:0014055', 'COMPOUND:0061535', 'COMPOUND:0150076', 'COMPOUND:0001152', 'COMPOUND:0002185', 'COMPOUND:0004975', 'COMPOUND:0005816', 'COMPOUND:60425'] # Compute the minimum spanning tree of the graph mst = cugraph.minimum_spanning_tree(G) # Convert the resulting MST to a cuDF DataFrame mst_df = mst.view_edge_list() # Ensure to finalize the cuGraph communication client.close() cluster.close() # Display the MST DataFrame print(mst_df.compute())  I looked at cuGraph documentation and Stackoverflow posts, but I still get errors.

Answer: cugraph does not currently have a multi-GPU (distributed) implementation of MST. This is the reason you are getting the NotImplementedError: Not supported for distributed graph message. The latest detail on what algorithms are supported for multi-GPU can be found here: https://docs.rapids.ai/api/cugraph/stable/graph_support/algorithms/#supported-algorithms We welcome user feedback, if you would like to register your interested in a multi-GPU implementation (or any other cugraph features) you can create an issue here: https://github.com/rapidsai/cugraph/issues. A multi-GPU implementation is not currently on our development road map, although it is on the list of things to eventually get to.
Question: `I have a list of arrays like this (in x, y coordinates): coordinates= array([[ 300, 2300], [ 670, 2360], [ 400, 2300]]), array([[1500, 1960], [1620, 2200], [1505, 1975]]), array([[ 980, 1965], [1060, 2240], [1100, 2250], [ 980, 1975]]), array([[ 565, 1940], [ 680, 2180], [ 570, 1945]])]  I want the arrays to be sorted by the nearest neighbor. So, the last coordinate of the first array should be close to the first coordinate of the next array and so forth. I extracted all of the first and last coordinates and put them in two lists using python numpy. Then tried to use sklearn.neighbors NearestNeighbors, but it didn't work.` expected output: coordinates= array([[ 300, 2300], [ 670, 2360], [ 400, 2300]]), array([[ 565, 1940], [ 680, 2180], [ 570, 1945]]), array([[ 980, 1965], [1060, 2240], [1100, 2250], [ 980, 1975]]), array([[1500, 1960], [1620, 2200], [1505, 1975]])] 

Answer: This looks like a traveling_salesman_problem. Compute the pairwise distance between all nodes, make the self distance NaN/Inf, then get the shortest path: from numpy import array import networkx as nx coordinates= [array([[ 300, 2300], [ 670, 2360], [ 400, 2300]]), array([[1500, 1960], [1620, 2200], [1505, 1975]]), array([[ 980, 1965], [1060, 2240], [1100, 2250], [ 980, 1975]]), array([[ 565, 1940], [ 680, 2180], [ 570, 1945]])] # extract starts and ends starts = np.vstack([a[0] for a in coordinates]) ends = np.vstack([a[-1] for a in coordinates]) # compute pairwise distances, except self dist = np.sqrt(((starts[:, None] - ends)**2).sum(-1)) np.fill_diagonal(dist, np.nan) # build the graph G = nx.from_numpy_array(np.round(dist, 1), create_using=nx.DiGraph) G.remove_edges_from(nx.selfloop_edges(G)) # find shortest path (NB. cycle could be False) path = nx.approximation.traveling_salesman_problem(G, cycle=True) # [1, 0, 3, 2, 1] out = [coordinates[i] for i in path[1:]]  If you don't necessarily want a cycle, use cycle=False and out = [coordinates[i] for i in path]. Output: [array([[ 300, 2300], [ 670, 2360], [ 400, 2300]]), array([[ 565, 1940], [ 680, 2180], [ 570, 1945]]), array([[ 980, 1965], [1060, 2240], [1100, 2250], [ 980, 1975]]), array([[1500, 1960], [1620, 2200], [1505, 1975]])]  Intermediate dist: array([[ nan, 1248.05849222, 753.67433285, 446.01008957], [1151.34703717, nan, 520.21630117, 930.12095988], [ 669.79474468, 525.09522946, nan, 410.48751504], [ 396.01136347, 940.65137006, 416.47328846, nan]])  Graph (with distances as edge labels and the shortest path in red):
Question: import time from pywinauto.application import Application import os #Installer path pycharm_exe = r"G:\Softwarewa\JetBrains PyCharm\JetBrains PyCharm Professional 2023.1 [FileCR]\JetBrains PyCharm Professional 2023.1\pycharm-professional-2023.1.exe" app = Application(backend="uia").start(pycharm_exe) # Wait for window to appear while True: if app.PyCharmSetup.exists() == True: break #activate the window app.PyCharmSetup.window() # app.PyCharmSetup.print_control_identifiers() app.PyCharmSetup.Next.click() #click on next again app.PyCharmSetup.Next.click() #click on next once again #app.PyCharmSetup.print_control_identifiers()  hi there, i am trying to automate PyCharm installation but there is a problem with script when it reaches where it starts to click on "Next" button it takes about 3 sec to click next button again.... how do i get rid of these delays between clicks?

Answer: You need to modify global timings. See the bottom of this guide: https://pywinauto.readthedocs.io/en/latest/wait_long_operations.html#global-timings-for-all-actions But please be careful, especially about setting all timings to zero. It may affect reliability of the automation steps. Because often some time is needed to handle some events at the app side. Maybe Timings.fast() is better in general.