eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm using Django, and in my view I generate a diagram of relations between parties. The problem is with the following: nx.set_node_attributes(G, fill_coloring, name="background")  But this unfortunately doesn't work. I'm unable to find in the documentation how I can set it properly. What I want to achieve is to direct the coloring / formatting of each node based on masterdata related to it. nx.set_node_attributes(G, border_coloring, name="color")  With the above I'm able to set the border color, but not the inner color. What am I overlooking? Ideally later on by adding information to the lines etc., but for now I want to color the nodes themselves in specific colors. Currently, it only colors the border. What am I overlooking / misunderstanding? def index(request): filename = f'{datetime.now():%Y-%m-%d_%H-%M-%S}.png' save_path = 'static/app/master/routing/' completeName = os.path.join(save_path, filename) print(completeName) G = nx.DiGraph() routings = Customer_Routing.objects.all() end_customers = [] border_coloring = {} fill_coloring = {} for e in routings: G.add_edge(e.customer_start.name, e.customer_end.name) if e.customer_end.end_customer == True: try: print(e.customer_end.customer_class.name) if e.customer_end.customer_class.name == "DIY": border_coloring[e.customer_end.name] = "#DAC85A" fill_coloring[e.customer_end.name] = "#FEF19C" except AttributeError: print(e.customer_end.name + " has no class.") ### Define the customer coloring nx.set_node_attributes(G, border_coloring, name="color") nx.set_node_attributes(G, fill_coloring, name="background") A = to_agraph(G) A.draw(completeName, prog='dot') template = loader.get_template('index.html') context = { 'img': completeName, 'routing': routings, } return HttpResponse(template.render(context, request))  EDIT: I found the answer, shortly after posting this. Graphviz needs the style to be set to "filled". Below solved this: nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style") 

Answer: Thanks @Paul Brodersen; below posted as accepted answer: I found the answer, shortly after posting this. Graphviz needs the style to be set to "filled". Below solved this: nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style")  Additionally I changed the model to add colors based on the segmentation. Now the for looks as follows: nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style") border_coloring[e.customer_end.name] = e.customer_end.customer_segment.border_color fill_coloring[e.customer_end.name] = e.customer_end.customer_segment.fill_color
Question: As of May 4, 2023, at 16:00, I started seeing one of our Jenkins job failing with the following error: Traceback (most recent call last): File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 822, in get_info return json.loads(self.jenkins_open( File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 560, in jenkins_open return self.jenkins_request(req, add_crumb, resolve_auth).text File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 576, in jenkins_request self.maybe_add_crumb(req) File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 373, in maybe_add_crumb response = self.jenkins_open(requests.Request( File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 560, in jenkins_open return self.jenkins_request(req, add_crumb, resolve_auth).text File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 579, in jenkins_request self._request(req)) File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 553, in _request return self._session.send(r, **_settings) File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/requests/sessions.py", line 701, in send r = adapter.send(request, **kwargs) File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/requests/adapters.py", line 483, in send timeout = TimeoutSauce(connect=timeout, read=timeout) File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/urllib3/util/timeout.py", line 119, in __init__ self._connect = self._validate_timeout(connect, "connect") File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/urllib3/util/timeout.py", line 156, in _validate_timeout raise ValueError( ValueError: Timeout value connect was <object object at 0x7efe5adb9aa0>, but it must be an int, float or None.  As nothing had changed on my side in my configuration, it looks like an upstream issue. I was using requests Python library in my job and requests uses urllib3. How can we fix this?

Answer: A new version 2.0.2 of urllib3 was released on May 4, 2023, which can be seen here: urllib3 2.0.2 - Release history As my job installs the Python libraries in the beginning of the job using pip in a virtual Python environment, it started installing the latest version of urllib3 which had some issues. So, it is looks an upstream issue. I fixed it by adding urllib3>=1.26.15,<2 in my requirements.txt file.
Question: I have several Python packages developed locally, which I often use in VSCode projects. For these projects, I create a new virtualenv and install these packages with pip install -e ../path/to/package. This succeeds, and I can use these packages in the project. However, VSCode underlines the package's import line in yellow, with this error:  Import "mypackage" could not be resolved Pylance(reportMissingImports)  Again, mypackage works fine in the project, but VSCode reports that error, and I lose all autocomplete and type hint features when calling mypackage in the project. I ensured that the right Python interpreter is selected (the one from the project's virtualenv), but the error persists. The error and Pylance docs do not offer any other possible solutions. VSCode version: 1.78.0

Answer: Usually, when you choose the correct interpreter, Pylance should take effect immediately. You can try adding "python.analysis.extraPaths": ["path/to/your/package"] to your settings.json. You can also try clicking on the install prompt in vscode to see which environment it will install the package in. I still believe that the problem was caused by incorrect selection of the interpreter.
Question: I am trying to use plotly to create a scatter plot where the x-variable can be selected from a drop-down menu. The scatter plot would also have marginal histogram plots. # Generate data and import libraries import pandas as pd import numpy as np import plotly.express as px import plotly.graph_objects as go # set the random seed np.random.seed(123) # generate arrays of random numbers a = np.random.rand(100) b = np.random.rand(100) c = np.random.rand(100) y = np.random.rand(100) # create a DataFrame with columns A, B, and C df_scatterplot = pd.DataFrame({'A': a, 'B': b, 'C': c, 'y':y}) df_scatterplot_nocc = df_scatterplot.loc[:, df_scatterplot.columns != 'y'] # print the DataFrame print(df_scatterplot)  I have created a working script where the y-variable can be changed: # Plot scatter plot and marginal histograms fig = px.scatter(df_scatterplot, x='A', y='y', marginal_x="histogram", marginal_y="histogram") buttonlist = [] for col in df_scatterplot.columns: buttonlist.append( dict( args = [ {'y': [df_scatterplot[str(col)]]}, # update y variable {'yaxis.title.text': str(col)} # update y-axis title ], label=str(col), method='update' ) ) # Add dropdown menu fig.update_layout(updatemenus=[ go.layout.Updatemenu( buttons=buttonlist, x=0.75, xanchor="left", y=1.0, yanchor="top", ), ], ) fig.update_layout(autosize=False, width=1000, height=700,) fig.show()  Output for varying y variable:  As expected, only the marginal_y histogram is changing. The issue is when trying to modify my script so that the x-variable can be changed, resulting in the marginal_y histogram plot changing as well (it plots a marginal_x histogram for both x and y). It should not be changing. Modifying to: args = [ {'x': [df_scatterplot[str(col)]]}, # update x variable {'xaxis.title.text': str(col)} # update x-axis title ],  Output for varying x variable now becomes:  I have tried changing the method argument from update to restyle with no luck. Any help is appreciated; thank you.

Answer: You can fix this by specifying which trace to update, passing an array of trace indices to the update method : args = [ {'x': [df_scatterplot[str(col)]]}, # update x variable {'xaxis.title.text': str(col)}, # update x-axis title [0, 1] # update only trace 0 and 1 (preserve marginal_y) ],  The idea is to preserve the marginal_y histogram from the data update. Nb. The plot ends up with 3 traces, indexed as follows :  0 the main scatter trace on subplot xy 1 the marginal_x histogram above the scatter on subplot x3y3 2 the marginal_y histogram on the right on subplot x2y2
Question: I am writing a script which runs a Windows executable file in a directory supplied by a user. If this script is a network path, making it the current directory will look like it worked, but running any commands in this directory will fail: >>> import os >>> os.chdir(r'\\server\share\folder') # my actual name is different but similar >>> os.getcwd() '\\\\server\\share\\folder' >>> os.system('echo %CD%') '\\server\share\folder' CMD.EXE was started with the above path as the current directory. UNC paths are not supported. Defaulting to Windows directory. C:\Windows 0  I want to predict this situation in my script — if the user supplies a network path instead of a local path like c:\work\project42, give a meaningful error immediately instead of letting it fail later. How can I determine if a path is a Windows network path?

Answer: I agree that the simplest check is yourpathstring.startswith(r'\\'). However, this will be a false-positive for any linux path which starts with \\ (unlikely but possible) and a false-negative when people use forward slashes: //server\share\folder. It appears that the library function splitdrive was designed with network path support in mind. The network part is considered "drive", so just have to check if it's a non-DOS drive: def is_network_path(path): drive = os.path.splitdrive(path)[0] if drive: return not drive.endswith(':') else: return False  Probably not worth the effort, but it "feels" more correct.
Question: I have been trying to install pyrebase4 using pip install pyrebase4 but when ran it throws below error "C:\Users\ChodDungaTujheMadhadchod\anaconda3\envs\sam_upgraded\lib\site-packages\requests_toolbelt\adapters\appengine.py", line 42, in <module> from .._compat import gaecontrib ImportError: cannot import name 'gaecontrib' from 'requests_toolbelt._compat' As I see the error direct directly to requests_toolbelt , but I cannot figure out the possible way to fix it, I tried upgrading to latest version as which is requests-toolbelt==1.0.0 . So is there any way to fix it.

Answer: Okay so what I found that the latest requests-toolbelt 1.0.1 is currently throwing this issue. So downgrading it to next previous version requests-toolbelt==0.10.1 fixes the issue.
Question: In module.py, I have: def func(x: int) -> str | None: if x > 9: return "OK" return None def main(x: int) -> str | None: return func(x)  In test_module.py, I have: import pytest from pytest_mock import MockerFixture from module import main @pytest.fixture(name="func") def fixture_func(mocker: MockerFixture) -> MockerFixture: return mocker.patch("module.func", autospec=True) def test_main(func: MockerFixture) -> None: _ = main(11) func.assert_called_once()  pytest says: 1 passed in 0.01s [100%]  But mypy generates the following error: test_module.py:13:5: error: "MockerFixture" has no attribute "assert_called_once" [attr-defined] Found 1 error in 1 file  What am I missing?

Answer: You have declared a wrong type for the func argument. The return type of mocker.patch is unittest.mock.MagicMock: import pytest from unittest.mock import MagicMock from pytest_mock import MockerFixture from module import main @pytest.fixture(name="func") def fixture_func(mocker: MockerFixture) -> MagicMock: return mocker.patch("module.func", autospec=True) def test_main(func: MagicMock) -> None: main(11) func.assert_called_once()
Question: Given an n integer (n >= 1), and a number k, return all possible ways to write n as kth power different integers. For instance, if n = 100 and k = 2: 100 = 1**2 + 3**2 + 4**2 + 5**2 + 7**2 = 6**2 + 8**2 = 10**2  or if k = 3: 100 = 1**3 + 2**3 + 3**3 + 4**3  So program(100,2) returns something like [(2, [1, 3, 4, 5, 7]), (2, [6, 8]), (2, [10])], and program(100,3) [(3, [1, 2, 3, 4])]. Everything works fine, as long as the input n is small, or k is "big" (>=3). My approach was to first get a list of all integers, whose kth power is <= n. def possible_powers(n,k): arr,i = [],1 while i**k <= n: arr.append(i) i += 1 return arr  Then (and here's the mistake), I created all subsets of this list (as lists): def subsets(L): subsets = [[]] for i in L: subsets += [subset+[i] for subset in subsets] return subsets  And finally I cycled through all these subsets, raising each element to the kth power and adding them together, selecting only the ones that add up to n. def kth_power_sum(arr,k): return sum([i**k for i in arr]) def solutions(n,k): return [(k,i) for i in subsets(possible_powers(n,k)) if kth_power_sum(i,k) == n]  I know the problem is with the subset-creation, but I have no clue how to optimize this. Like, if I try solutions(1000,2), it creates a large set, which takes up more than 4GB memory. My guess would be to sieve out a few subsets, but that wouldn't help much, unless I have a very efficient sieve. Any help is greatly appreciated. If something isn't clear, or I made a mistake in posting this, please tell me.

Answer: If you implement this as a recursive generator, you won't need to store a large number of values (not even the results): def powersum(n,k,b=1): bk = b**k while bk < n: for bases in powersum(n-bk,k,b+1): yield [b]+bases b += 1 bk = b**k if bk == n : yield [b] print(*powersum(100,2)) # [1, 3, 4, 5, 7] [6, 8] [10] print(*powersum(100,3)) # [1, 2, 3, 4] print(sum(1 for _ in powersum(1000,2))) # 1269 solutions print(sum(1 for _ in powersum(2000,2))) # 27526 solutions (6 seconds)  Note that this still has an exponential time complexity so it will be much slower for slightly larger values of n print(sum(1 for _ in powersum(2200,2))) # 44930 solutions (12 seconds) print(sum(1 for _ in powersum(2500,2))) # 91021 solutions (25 seconds) print(sum(1 for _ in powersum(2800,2))) # 175625 solutions (55 seconds) print(sum(1 for _ in powersum(3100,2))) # 325067 solutions (110 seconds)  [EDIT] For future reference, here is Kelly Bundy's cached version which runs considerably faster. Posting it here in case his demo link gets broken: from functools import cache from time import time @cache def powersum(n,k,b=1): bk = b**k res = [] while bk < n: for bases in powersum(n-bk,k,b+1): res.append([b]+bases) b += 1 bk = b**k if bk == n : res.append([b]) return res  Note: although the cache will consume some memory, it will be nowhere near the size the full powerset of all possible combinations.
Question: import requests import pandas as pd url = "https://coinmarketcap.com/new/" page = requests.get(url,headers={'User-Agent': 'Mozilla/5.0'}, timeout=1) pagedata = page.text usecols = ["Name", "Price", "1h", "24h", "MarketCap", "Volume"]#, "Blockchain"] df = pd.read_html(pagedata)[0] #Checking table df[["Name", "Symbol"]] = df["Name"].str.split(r"\d+", expand=True) df = df.rename(columns={"Fully Diluted Market Cap": "MarketCap"})[usecols] dfAsString = df.to_string(index=False) print(dfAsString)  Current Code Output: (Truncated)  Name Price 1h 24h MarketCap Volume 0 DollarPepe $0.02752 22.64% 336.25% $3 $456,913 1 Billy Token $0.00002822 41.69% 75.80% $1,958,942 $6,999,241 2 JEFF $0.1946 4.42% 226.18% $19,458,328 $19,744,583 3 PUG AI $0.00000001459 10.80% 15.84% $1,459,428 $239,454 4 FART COIN $0.0000004281 1.13% 42.13% $42,806,075 $46,604 [30 rows x 6 columns]  How to produce the outpur sorted based on a particular column (24h)? -> Truncated  Name Price 1h 24h MarketCap Volume 0 DollarPepe $0.02752 22.64% 336.25% $3 $456,913 2 JEFF $0.1946 4.42% 226.18% $19,458,328 $19,744,583 1 Billy Token $0.00002822 41.69% 75.80% $1,958,942 $6,999,241 4 FART COIN $0.0000004281 1.13% 42.13% $42,806,075 $46,604 3 PUG AI $0.00000001459 10.80% 15.84% $1,459,428 $239,454 [30 rows x 6 columns] 

Answer: I would convert all the numeric columns in your df to numeric values; then you can sort them easily (you can always add back $ and % as required on display). numcols = df.columns[df.columns != 'Name'] df[numcols] = df[numcols].apply(lambda c:pd.to_numeric(c.str.replace(r'[^\d.]|(?<!\d)\.|\.(?!\d)', '', regex=True))) df = df.sort_values('24h', ascending=False)  Output (for your sample data):  Name Price 1h 24h MarketCap Volume 0 DollarPepe 2.752000e-02 22.64 336.25 3 456913 2 JEFF 1.946000e-01 4.42 226.18 19458328 19744583 1 Billy Token 2.822000e-05 41.69 75.80 1958942 6999241 4 FART COIN 4.281000e-07 1.13 42.13 42806075 46604 3 PUG AI 1.459000e-08 10.80 15.84 1459428 239454  Note the non-numeric character replacement is more complicated than just [^\d.] as would be implied by your sample data; this is because some of the other price values fetched from that page have ... in them (presumably because they are too small to represent). Ideally you need to figure out how to get those as exact values; otherwise they can only be approximated. Alternatively, you can sort on the values by converting them to floats before passing the series to sort_values: df = df.sort_values('24h', ascending=False, key=lambda v:v.str.replace('%', '').astype(float))  Output:  Name Price 1h 24h MarketCap Volume 0 DollarPepe $0.02752 22.64% 336.25% $3 $456,913 2 JEFF $0.1946 4.42% 226.18% $19,458,328 $19,744,583 1 Billy Token $0.00002822 41.69% 75.80% $1,958,942 $6,999,241 4 FART COIN $0.0000004281 1.13% 42.13% $42,806,075 $46,604 3 PUG AI $0.00000001459 10.80% 15.84% $1,459,428 $239,454
Question: I have a problem, which I am trying to solve, and have reproduced it with the code below. The issue that I have, is that I can get the specified command to work from a main menu item, but when the same command is included in a cascade menu, it doesn't appear to execute. I'm not sure whether this is in anyway to do with my requirements, which are that I need to render a grid of buttons and attach a context menu to each. Here is some code which I contrived which demonstrate the issue: import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.title('Tkinter Validation Demo') self.create_widgets() @staticmethod def print_bg_color(button, button_id): colour = button.cget('bg') print(f'Button {button_id} colour is {colour}') @staticmethod def _context_menu(event: tk.Event = None, menu: tk.Menu = None): menu.tk_popup(event.x_root, event.y_root) def create_widgets(self): colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] for i in range(0, 7): button = tk.Button(master=self, bg=colors[i], width=10, height=10) button.grid(row=0, column=i) context_menu = tk.Menu(button, tearoff=False) # Add print option to main menu context_menu.add_command(label="Print colour", command=lambda btn=button, button_id=i: self.print_bg_color(button=btn, button_id=button_id)) sub_menu = tk.Menu(button, tearoff=False) # Add a print colour option on the sub menu sub_menu.add_command(label="Print colour", command=lambda btn=button, button_id=i: self.print_bg_color(button=btn, button_id=button_id)) context_menu.add_cascade(label='Cascade', menu=sub_menu) button.bind("<Button-3>", lambda event, menu=context_menu, button_id=i: self._context_menu(event, menu)) if __name__ == '__main__': app = App() app.mainloop()  When the above code is run, it allows you to right click on any of the rendered buttons, and select the "Print color" from either the main context menu, or from a cascade option. The command bound to the event, simply obtains the colour of the button and prints it to the console. This works for the main context menu option, but the cascade menu entry does nothing, despite having the same command. Any suggestions gratefully received. Thanks. UPDATE: Having determined that this only seems to be happening on my Linux Mint environment running Python 3.8 (it works on my Windows 10 with Python 3.10), I ran the script suggested by Nordine in the comments: import tkinter from platform import python_version print(python_version()) root = tkinter.Tk() print(root.tk.call("info", "patchlevel"))  The results showed as: 3.8.10 8.6.10 FURTHER UPDATE: I just upgraded to Python 3.10 on my Linux Mint machine, and it still isn't working :o/

Answer: The submenu in the code in the question is set up as an element of button: sub_menu = tk.Menu(button, tearoff=False)  However, this causes the submenu to be displayed correctly but to not be clickable (reproduced on Ubuntu, Python 3.10.6, Tkinter 8.6). When you make the submenu an element of context_menu then it does work: sub_menu = tk.Menu(context_menu, tearoff=False)
Question: I have a df like: df1 = AA BB CC DD 1 X Y Z 2 M N O 3 P Q R  I have another df like: df2 = BB CC DD G K O H L P I M Q  I want to copy all the columns and rows of df2 for every distinct value of 'AA' column of df1 and get the resultant df as: df = AA BB CC DD 1 X Y Z 1 G K O 1 H L P 1 I M Q 2 M N O 2 G K O 2 H L P 2 I M Q 3 P Q R 3 G K O 3 H L P 3 I M Q  What I am doing right now is: AAs = df1.select("AA").distinct().rdd.flatMap(lambda x: x).collect() out= [] for i in AAs: dff = df1.filter(col('AA')==i) temp_df = (df1.orderBy(rand()) .withColumn('AA', lit(i)) ) out.append(temp_df) df = reduce(DataFrame.unionAll, out)  Which is taking extremely long time and failing the cluster as these are mock dataframes, actual dataframes are quite large in dimension. Any Pysparky way of doing it? Thanks in advance.

Answer: This would work: resultDf= df.select("AA")\ .crossJoin(df2)\ .union(df) # No Need to order the actual result, this is just for displaying this example. resultDf.orderBy("AA").show()  Although, this would still be a huge operation and can be expensive on the cluster. Input DF1: +---+---+---+---+ | AA| BB| CC| DD| +---+---+---+---+ | 1| X| Y| Z| | 2| M| N| O| | 3| P| Q| R| +---+---+---+---+  DF2: +---+---+---+ | BB| CC| DD| +---+---+---+ | G| K| O| | H| L| P| | I| M| Q| +---+---+---+  Output: +---+---+---+---+ | AA| BB| CC| DD| +---+---+---+---+ | 1| G| K| O| | 1| X| Y| Z| | 1| I| M| Q| | 1| H| L| P| | 2| M| N| O| | 2| I| M| Q| | 2| H| L| P| | 2| G| K| O| | 3| P| Q| R| | 3| I| M| Q| | 3| H| L| P| | 3| G| K| O| +---+---+---+---+
Question: I want to index all elements in a numpy array and also include the first index at the end. So if I have the array [2, 4, 6] , I want to index the array such that the result is [2, 4, 6, 2]. import numpy as np a = np.asarray([2,4,6]) # One solution is cycle = np.append(a, a[0]) # Another solution is cycle = a[[0, 1, 2, 0]] # Instead of creating a list, can indexing type be combined? cycle = a[:+0] 

Answer: Another possible solution: a = np.asarray([2,4,6]) cycle = np.take(a, np.arange(len(a)+1), mode='wrap')  Output: [2 4 6 2]