eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm trying to get rid of the white border around the OptionMenu. What I tried I changed the colour to red, but there is still a white border around it. Can anyone help?  Here's the code: from tkinter import * import tkinter as tk from tkinter import ttk root = tk.Tk() root.geometry('500x500') var = StringVar() option = ttk.OptionMenu(root,var,'1','2','3') option["menu"].config(bg="red") option.pack() root.mainloop()  Also, is there a way to change the colour of the OptionMenu trigger box (In the red Circle)? 

Answer: As stated in the comments by @Mike-SMT,   Have you considered writing your own option menu?  This, to me, seems to be the only way to get an OptionMenu without having that irritating grey border.  Here is my attempt at it:  import tkinter as tk root = tk.Tk() root.geometry('500x500') class custom_option_menu(tk.Tk): def down(self, *menu_items): if self.button["text"] == "↓": self.frame.place(x = self.x + (len(self.first) * 13)/2, y = self.y + 50, anchor = "center") self.button.config(text = "↑") elif self.button["text"] == "↑": self.frame.place_forget() self.button.config(text = "↓") def __init__(self, master, first, bg, *menu_items): self.master = master self.first = first self.menu_items = menu_items self.bg = bg self.frame = tk.Frame(master, height = 100, width = 100) self.otherframe = tk.Frame(master, height = 10, width = len(first) * 13) self.label = tk.Label(self.otherframe, text = str(first)) self.button = tk.Button(self.otherframe, text = "↓", command = lambda: self.down(), relief= "flat") def save_var(event = "<Button-1>"): print(event.widget["text"]) for i in range(len(self.menu_items)): self.frame.config(bg = self.bg) self.option = tk.Button(self.frame, text = self.menu_items[i], relief = "flat", bg = self.bg, textvariable = int(i)) self.option.pack() self.option.bind("<Button-1>", save_var) def put(self, x, y): self.x = x self.y = y self.button.pack(side = "right") self.label.pack() self.frame.place(x = x + (len(self.first) * 13)/2, y = y + 50, anchor = "center") self.frame.place_forget() self.otherframe.place(x = x + (len(self.first) * 13)/2, y = y, anchor = "center") nice = custom_option_menu(root, "o000000000000000", "blue", "First", "second", "Third") nice.put(100, 200) root.mainloop()  Sadly I couldn't get the default geometry managers to work for this, so I created .put(). It's just the x and y coordinates.  The arguments to the class custom_option_menu go as follows:  The first argument is the parent widget.  The second argument is the text on the OptionMenu.  The third argument is the background color for the options.  The remaining arguments are the options.  To open the menu, click the down arrow.  I hope this is what you were looking for!
Question: How do I annotate the type of a function parameter of a abstractmethod, when the parameter can have any type derived from a specific base type? Example: import abc import attr @attr.s(auto_attribs=True) class BaseConfig(abc.ABC): option_base: str @attr.s(auto_attribs=True) class ConfigA(BaseConfig): option_a: str @attr.s(auto_attribs=True) class ConfigB(BaseConfig): option_b: bool class Base(abc.ABC): @abc.abstractmethod def do_something(self, config: BaseConfig): pass class ClassA(Base): def do_something(self, config: ConfigA): # test.py:27: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig" print("option_a: " + config.option_a) class ClassB(Base): def do_something(self, config: ConfigB): # test.py:33: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig" print("option_b: " + str(config.option_b)) conf_a = ConfigA(option_a="value_a", option_base="value_base") conf_b = ConfigB(option_b=True, option_base="value_base") object_a = ClassA() object_b = ClassB() object_a.do_something(conf_a) object_b.do_something(conf_b)  When parsing this with mypy I get test.py:27: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig" test.py:33: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig"  How would I need to change the signature of Base.do_something() so mypy doesn't report any error, while still enforcing, that the function parameter of the abstract method do_something is derived from BaseConfig?

Answer: TLDR: Make the baseclass Generic and parameterise the type of configuration: C = TypeVar('C', bound=BaseConfig) class Base(abc.ABC, Generic[C]): @abc.abstractmethod def do_something(self, config: C): pass   The original class hierarchy declares that ClassA can be used anywhere Base is valid. When we assume some variable obj: Base, this leads to a conflict:  We can assign obj = ClassA() since ClassA "is a" Base class. We can use obj.do_something(BaseConfig()) since obj "is a" Base instance.  However, ClassA.do_something(config: ConfigA) says we cannot do both at the same time, contradicting the type equivalence.  Instead, we need to distinguish between "Base that takes a ConfigA", "Base that takes a ConfigB" and so on. This is done by parameterising Base with a type-variable for the config. from typing import Generic, TypeVar C = TypeVar('C', bound=BaseConfig) # C "is some" BaseConfig type class Base(abc.ABC, Generic[C]): # class takes type variable ... @abc.abstractmethod def do_something(self, config: C): # ... and uses it in method signature pass  This allows us to have both generic and concrete Base variants - for example, Base[ConfigA] is a "Base that takes a ConfigA". From this, the subclasses can be derived as taking the appropriate configuration: class ClassA(Base[ConfigA]): # set type variable to ConfigA def do_something(self, config: ConfigA): print("option_a: " + config.option_a)
Question: I am getting this message on the VS Code that "Python is not installed. Please download and install python before using the extension." There is also no *"Python Interpreter"* to select. When I click on it it shows it empty.  I do have Python and Python extension installed and I do have virtual environments set up in the Anaconda navigator but for some reason, I am not able to use them. I tried many ways like reinstalling the Python, Anaconda, and VS Code and also the Python extension for VS code but it's not solving the issue. What could be the reason? I have attached a screenshot of the VS Code as well. Pleae click here to see the screenshot Thanks for your help. 

Answer: I tried many methods but none worked. So then I removed this extension "Anaconda Extension Pack by Microsoft" and it solved the issue. So anyone facing the same issue might try uninstalling this extension.
Question: I am trying to access a Jupyter Notebook created with the shell_plus command from django-extensions in a Docker container. docker-compose -f local.yml run --rm django python manage.py shell_plus --notebook  My configuration is based on the answers of @RobM and @Mark Chackerian to this Stack Overflow question. I.e. I installed and configured a custom kernel and my Django apps config file has the constant NOTEBOOK_ARGUMENTS set to: NOTEBOOK_ARGUMENTS = [ '--ip', '0.0.0.0', '--port', '8888', '--allow-root', '--no-browser', ]  I can see the container starting successfully in the logs: [I 12:58:54.877 NotebookApp] The Jupyter Notebook is running at: [I 12:58:54.877 NotebookApp] http://10d56bab37fc:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6 [I 12:58:54.877 NotebookApp] or http://127.0.0.1:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6  But I can't open the url. I have forwarded the port 8888 in my docker-compose, tried to use localhost instead of 127.0.0.1 and also tried to use the containers IP w/o success. It feels like I am missing the obvious here … Any help is appreciated.

Answer: For the sake of records as of 2020, I managed to have a working django setup with Postgresql in docker-compose: development.py (settings.py) INSTALLED_APPS += [ "django_extensions", ] SHELL_PLUS = "ipython" SHELL_PLUS_PRINT_SQL = True NOTEBOOK_ARGUMENTS = [ "--ip", "0.0.0.0", "--port", "8888", "--allow-root", "--no-browser", ] IPYTHON_ARGUMENTS = [ "--ext", "django_extensions.management.notebook_extension", "--debug", ] IPYTHON_KERNEL_DISPLAY_NAME = "Django Shell-Plus" SHELL_PLUS_POST_IMPORTS = [ # extra things to import in notebook ("module1.submodule", ("func1", "func2", "class1", "etc")), ("module2.submodule", ("func1", "func2", "class1", "etc")) ] os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" # only use in development  requirements.txt django-extensions jupyter notebook Werkzeug # needed for runserver_plus ...  docker-compose.yml version: "3" services: db: image: postgres:13 environment: - POSTGRES_HOST_AUTH_METHOD=trust restart: always ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . environment: - DJANGO_SETTINGS_MODULE=settings.development command: - scripts/startup.sh volumes: - ... ports: - "8000:8000" # webserver - "8888:8888" # ipython notebook depends_on: - db volumes: postgres_data:  From your host terminal run this command: docker-compose exec web python manage.py shell_plus --notebook  Finally navigate to http://localhost:8888/?token=<xxxx> in the web browser of host.
Question: I use social-auth-app-django for my django website. Login all works, but after the token expires. I cant access the google's user data anymore. I found how to refresh the token, but it gives  File "/mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py", line 17, in handle new_token = self.get_token(user=booking_user, provider='google-oauth2') File "/mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py", line 28, in get_token social.refresh_token(strategy) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/storage.py", line 58, in refresh_token response = backend.refresh_token(token, *args, **kwargs) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/backends/oauth.py", line 438, in refresh_token request = self.request(url, **request_args) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/backends/base.py", line 234, in request response.raise_for_status() File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/requests/models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token  Here is some of my code def get_token(self, user, provider): social = user.social_auth.get(provider=provider) print('This is social of user: ', social) if (social.extra_data['auth_time'] + social.extra_data['expires']) <= int(time.time()): print('\n Token is out of date \n') strategy = load_strategy() social.refresh_token(strategy) return social.extra_data['access_token']  in my settings file: AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('DJANGO_SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') # Paste CLient Key SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('DJANGO_SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') # Paste Secret Key SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar.events' ] 

Answer: Fixed it by adding this: SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'approval_prompt': 'auto' }  If the user already registered, you need to force the prompt first time (otherwhise you dont get the refresh token) /login/google-oauth2?approval_prompt=force
Question: I was recently wondering about Time Travel Debugging in relation to Python. I found information about tools like:   RevPDB - unfortunately the last recorded activity is from 2016 timetravelpdb - unfortunately the last recorded activity is in 2015  Since the projects were updated so long ago, I was wondering if the tools used for TTD had changed for the moment? I am counting on constructive discussion and advice & suggestions what to use now. It is all about sharing the knowledge. 

Answer: General Overview of TTD Research  At this very moment, available solutions are those listed in the description of the question and additionally PyTrace. As far as RevPDB and timetravelpdb are concerned, I haven't tested these solutions in any way as the activity in these projects is registered a few years ago so I assumed that in case of problems contact with the support will be difficult. How to start working with it? To start with, it is worth using an interactive demo to learn about the basic functionalities and the way it works: PyTrace Interactive Demo If you need more information, check this site: PyTrace Official Site I am impressed with this project and I'm going to start using it in my daily coding routine so I will post my thought and tips about it later. Stay tuned!
Question: I am working on this python notebook in Google Colab: https://github.com/AllenDowney/ModSimPy/blob/master/notebooks/chap01.ipynb I had to change the configuration line because the one stated in the original was erroring out: # Configure Jupyter to display the assigned value after an assignment # Line commented below because errors out # %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # Edit solution given below %config InteractiveShell.ast_node_interactivity='last_expr'  However, I think the original statement was meant to show values of assignments (if I'm not mistaken), so that when I run the following cell in the notebook, I should see an output: meter = UNITS.meter second = UNITS.second a = 9.8 * meter / second**2  If so, how can I make the notebook on Google Colab show output of assignments?

Answer: Google Colab has not yet been upgraded to the latest IPython version- if you explicitly upgrade with  !pip install -U ipython  then last_expr_or_assign will work.
Question: I am generating thumbnails for mp4 videos using the following code: import cv2 as cv from PIL import Image vidcap = cv.VideoCapture(videoPath) vidcap.set(cv.CAP_PROP_POS_MSEC, millisecond) #Turn video frame into numpy ndarray success, image = vidcap.read() cv.imwrite('fromImage.jpg', image) #line to be replaced  The thumbnail generated from a high budget, professionally shot video looks like this:  Unfortunately in my application context, I will not be able to write the image frame directly to a file. Instead I must convert the image array generated by cv into a PIL image and then go from there. It looks something like this: # Turn numpy ndarray int PIL image img = Image.fromarray(image) img.save('fromArray.jpg') #Saving it for stackoverflow  But the outputted thumbnail from the same mp4 video is completely distorted as it seems to have swapped red and blue and looks like this: Who or what is the culprit in this image distortion?

Answer: https://note.nkmk.me/en/python-opencv-bgr-rgb-cvtcolor/  imageRGB = cv.cvtColor(image, cv.COLOR_BGR2RGB) img = Image.fromarray(imageRGB) img.save('fromArray.jpg')
Question: The matplotlibrc sample file states that: ## The font.size property is the default font size for text, given in pts. ## 10 pt is the standard value. ## ## Note that font.size controls default text sizes. To configure ## special text sizes tick labels, axes, labels, title, etc, see the rc ## settings for axes and ticks. Special text sizes can be defined ## relative to font.size, using the following values: xx-small, x-small, ## small, medium, large, x-large, xx-large, larger, or smaller  What are the equivalent values in pts for those "special text sizes"?

Answer: You can also compute the absolute font sizes yourself very easily import matplotlib as mpl import matplotlib.pyplot as plt fig, ax = plt.subplots() t = ax.text(0.5, 0.5, 'Text') fonts = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller'] for font in fonts: t.set_fontsize(font) print (font, round(t.get_fontsize(), 2)) plt.close()  Output xx-small 5.79 x-small 6.94 small 8.33 medium 10.0 large 12.0 x-large 14.4 xx-large 17.28 larger 12.0 smaller 8.33
Question: I was trying to plot barplot and scatterplot in the same plot in plotly, but it shows only scatterplot. How to show both the plots? data import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter import plotly import plotly.offline as py import plotly.graph_objs as go import plotly.figure_factory as ff import plotly.tools as tls from plotly.subplots import make_subplots from plotly.offline import plot, iplot, init_notebook_mode init_notebook_mode(connected=False) df = pd.DataFrame({ 'price': [ 4.0, 17.0, 7.0, 7.0, 2.0, 1.0, 1.0], 'item': ['apple', 'banana', 'carrot', 'plum', 'orange', 'date', 'cherry']}) df = df.sort_values(num,ascending=False) df['cumulative_sum'] = df[num].cumsum() df['cumulative_perc'] = 100*df['cumulative_sum']/df[num].sum() df['demarcation'] = 80 num = 'price' cat = 'item' title = 'Pareto Chart'  Code trace1 = go.Bar( x=df[cat], y=df[num], name=num, marker=dict( color='rgb(34,163,192)' ) ) trace2 = go.Scatter( x=df[cat], y=df['cumulative_perc'], name='Cumulative Percentage', yaxis='y2', ) data = [trace1,trace2] fig = dict(data=data) iplot(fig)  Output  Required  show both barchart and scatterplot barchart y-ticks on left y-axis scatterplot y-ticks on right y-axis xticklabels rotate 90 degree 

Answer: Try this: import plotly.graph_objects as go from plotly.subplots import make_subplots trace1 = go.Bar( x=df[cat], y=df[num], name=num, marker=dict( color='rgb(34,163,192)' ) ) trace2 = go.Scatter( x=df[cat], y=df['cumulative_perc'], name='Cumulative Percentage', yaxis='y2' ) fig = make_subplots(specs=[[{"secondary_y": True}]]) fig.add_trace(trace1) fig.add_trace(trace2,secondary_y=True) fig['layout'].update(height = 600, width = 800, title = title,xaxis=dict( tickangle=-90 )) iplot(fig)  Gives,
Question: To format strings in Python 3.6+, I usually use the lowercase "f" option to include variables. For example: response = requests.get(f'{base_url}/{endpoint}?fields={field_list}') I've recently seen one of my coworkers who always uses capital "F", instead. Like this: response = requests.get(F'{base_url}/{endpoint}?fields={field_list}')  Is there a difference between the lowercase "f" and capital "F"? And if yes, when would you use each?

Answer: As explained in the PEP 498, chapter Specification, both are accepted, and should not differ. In source code, f-strings are string literals that are prefixed by the letter 'f' or 'F'. Everywhere this PEP uses 'f', 'F' may also be used.
Question: I'm having trouble getting all of the axes onto the same scale when using altair to make a group of plots like so: class_list = ['c-CS-m','c-CS-s','c-SC-m','c-SC-s','t-CS-m','t-CS-s','t-SC-m','t-SC-s'] list_of_plots = [] for class_name in class_list: list_of_plots.append(alt.Chart(data[data['class'] == class_name]).mark_bar().encode( x = alt.X('DYRK1A', bin = True, scale=alt.Scale()), y = 'count()').resolve_scale( y='independent' )) list_of_plots[0] & list_of_plots[1] | list_of_plots[2] & list_of_plots[3] | list_of_plots[4] & list_of_plots[5] | list_of_plots[6] & list_of_plots[7]  I'd like to have the x axis run from 0.0 to 1.4 and the y axis run from 0 to 120 so that all eight plots I'm producing are on the same scale! I've tried to use domain, inside the currently empty Scale() call but it seems to result in the visualisations that have x axis data from say 0.0 to 0.3 being super squished up and I can't understand why? For context, I'm trying to plot continuous values for protein expression levels. The 8 plots are for different classes of mice that have been exposed to different conditions. The data is available at this link if that helps: https://archive.ics.uci.edu/ml/datasets/Mice+Protein+Expression Please let me know if I need to provide some more info in order for you to help me!

Answer: First of all, it looks like you're trying to create a wrapped facet chart. Rather than doing that manually with concatenation, it's better to use a wrapped facet encoding. Second, when you specify resolve_scale(y='independent'), you're specifying that the y-scales should not match between subcharts. If instead you want all scales to be shared, you can use resolve_scale(y='shared'), or equivalently just leave that out, as it is the default. To specify explicit axis domains, use alt.Scale(domain=[min, max]). Put together, it might look something like this: alt.Chart(data).mark_bar().encode( x = alt.X('DYRK1A', bin = True, scale=alt.Scale(domain=[0, 1.4])), y = alt.Y('count()', scale=alt.Scale(domain=[0, 120]), facet = alt.Facet('class:N', columns=4), )
Question: How do these function works? I am using Python3.7 and OpenCv 4.2.0. Thanks in Advance. approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True) 

Answer: If you are looking for a example snippet, below is one: import cv2 import imutils # edged is the edge detected image cnts = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # loop over the contours for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) # if our approximated contour has four points, then we # can assume that we have found our screen if len(approx) == 4: screenCnt = approx break  In the above snippet, first it finds the contours from a edge detected image, then it sorts the contours to find the five largest contours. Finally it loop over the contours and used cv2.approxPolyDP function to smooth and approximate the quadrilateral. cv2.approxPolyDP works for the cases where there are sharp edges in the contours like a document boundary.
Question: The following file: from typing import List class A: def __init__(self, myStr): self.chars: List[int] = list(myStr) def toString(self): return "".join(self.chars)  typechecks (note: chars should be List[str] not List[int]): ➜ Python python3 -m mypy temp.py => Success: no issues found in 1 source file, but the following one, where I declare the return type of toString, does: from typing import List class A: def __init__(self, myStr): self.chars: List[int] = list(myStr) def toString(self) -> str: return "".join(self.chars) ➜ Python python3 -m mypy temp.py temp.py:9: error: Argument 1 to "join" of "str" has incompatible type "List[int]"; expected "Iterable[str]" Found 1 error in 1 file (checked 1 source file)  Could anyone explain mypy's behaviour in this case? Why do I need to add the return type to the function to force mypy to correctly diagnose the problem? (it already has all necessary information: that chars is List[int] and join accepts Iterable[str])

Answer: This behavior of mypy is by design. Mypy assumes that if a function signature is missing type hints, the user did not want that function to be type checked yet and so skips analyzing that function body. This behavior is intended to make progressively adding type hints when working on large codebases easier: you end up being warned only about functions you've had a chance to examine and migrate instead of being hit with a wall of warnings up front. If you don't like this behavior and would prefer that mypy tries type checking function bodies no matter what, pass in the --check-untyped-defs command line flag (or config file option). Alternatively, if you'd like mypy to warn you when you forget to add a type signature, use the --disallow-untyped-defs and --disallow-incomplete-defs flags. The --strict flag may also enable all three of these flags, among other ones. You can run mypy --help to double-check this for yourself.