eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I am trying to add finplot, https://pypi.org/project/finplot/, as a widget to one of the layouts in my UI. I created a widget for finplot and added it to the widgets in the layout but I get the following error: self.tab1.layout.addWidget(self.tab1.fplt_widget) TypeError: addWidget(self, QWidget, stretch: int = 0, alignment: Union[Qt.Alignment, Qt.AlignmentFlag] = Qt.Alignment()): argument 1 has unexpected type 'PlotItem'  Here is the code that I used. import sys from PyQt5.QtWidgets import * import finplot as fplt import yfinance # Creating the main window class App(QMainWindow): def __init__(self): super().__init__() self.title = 'PyQt5 - QTabWidget' self.left = 0 self.top = 0 self.width = 600 self.height = 400 self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.tab_widget = MyTabWidget(self) self.setCentralWidget(self.tab_widget) self.show() # Creating tab widgets class MyTabWidget(QWidget): def __init__(self, parent): super(QWidget, self).__init__(parent) self.layout = QVBoxLayout(self) # Initialize tab screen self.tabs = QTabWidget() self.tabs.setTabPosition(QTabWidget.East) self.tabs.setMovable(True) self.tab1 = QWidget() self.tabs.resize(600, 400) # Add tabs self.tabs.addTab(self.tab1, "tab1") self.tab1.layout = QVBoxLayout(self) self.tab1.label = QLabel("AAPL") self.tab1.df = yfinance.download('AAPL') self.tab1.fplt_widget = fplt.create_plot_widget(self.window()) fplt.candlestick_ochl(self.tab1.df[['Open', 'Close', 'High', 'Low']]) self.tab1.layout.addWidget(self.tab1.label) self.tab1.layout.addWidget(self.tab1.fplt_widget) self.tab1.setLayout(self.tab1.layout) # Add tabs to widget self.layout.addWidget(self.tabs) self.setLayout(self.layout) if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) 

Answer: The create_plot_widget() function creates a PlotItem that cannot be added to a layout, the solution is to use some QWidget that can display the content of the PlotItem as the PlotWidget: import pyqtgraph as pg # ... self.tab1.df = yfinance.download("AAPL") self.tab1.fplt_widget = pg.PlotWidget( plotItem=fplt.create_plot_widget(self.window()) ) fplt.candlestick_ochl(self.tab1.df[["Open", "Close", "High", "Low"]])
Question: I want to emulate the behavior of most command-line utilities, where optional arguments can be put anywhere in the command line, including between positional arguments, such as in this mkdir example: mkdir before --mode 077 after  In this case, we know that --mode takes exactly 1 argument, so before and after are both considered positional arguments. The optional part, --mode 077, can really be put anywhere in the command line. However, with argparse, the following code does not work with this example: # mkdir.py import argparse parser = argparse.ArgumentParser() parser.add_argument('--mode', nargs=1) parser.add_argument('dirs', nargs='*') args = parser.parse_args()  Running ./mkdir.py before --mode 077 after results in: mkdir.py: error: unrecognized arguments: after  How can I get argparse to accept an optional argument (with a fixed, known number of items) between positional ones?

Answer: Starting from Python 3.7, it seems argparse now supports this kind of Unix-style parsing:  Intermixed parsing ArgumentParser.parse_intermixed_args(args=None, namespace=None) A number of Unix commands allow the user to intermix optional arguments with positional arguments. The parse_intermixed_args() and parse_known_intermixed_args() methods support this parsing style.  There is a caveat, but for "simple" options, it does not affect them:  These parsers do not support all the argparse features, and will raise exceptions if unsupported features are used. In particular, subparsers, argparse.REMAINDER, and mutually exclusive groups that include both optionals and positionals are not supported.  (I posted this FAQ-style question after spending 1 hour trying to understand why the examples in the Python argparse documentation didn't seem to include it, and only by chance found a somewhat unrelated question which contained the mention to this "intermixed" function in a comment, which I am unable to find again to cite it properly.)
Question: I'm trying to understand what 'implicit' and 'explicit' really means in the context of Python. a = [] # my understanding is that this is implicit if not a: print("list is empty") # my understanding is that this is explicit if len(a) == 0: print("list is empty")  I'm trying to follow the Zen of Python rules, but I'm curious to know if this applies in this situation or if I am over-thinking it?

Answer: The two statements have very different semantics. Remember that Python is dynamically typed. For the case where a = [], both not a and len(a) == 0 are equivalent. A valid alternative might be to check not len(a). In some cases, you may even want to check for both emptiness and listness by doing a == []. But a can be anything. For example, a = None. The check not a is fine, and will return True. But len(a) == 0 will not be fine at all. Instead you will get TypeError: object of type 'NoneType' has no len(). This is a totally valid option, but the if statements do very different things and you have to pick which one you want. (Almost) everything has a __bool__ method in Python, but not everything has __len__. You have to decide which one to use based on the situation. Things to consider are:  Have you already verified whether a is a sequence? Do you need to? Do you mind if your if statement crashed on non-sequences? Do you want to handle other falsy objects as if they were empty lists?  Remember that making the code look pretty takes second place to getting the job done correctly.
Question: I have a df with two columns:  y: different numeric values for the y axis days: the names of four different days (Monday, Tuesday, Wednesday, Thursday)  I also have a colormap with four different colors that I made myself and it's a ListedColorMap object. I want to create a bar chart with the four categories (days of the week) in the x axis and their corresponding values in the y axis. At the same time, I want each bar to have a different color using my colormap. This is the code I used to build my bar chart: def my_barchart(my_df, my_cmap): fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.bar(my_df['days'], my_df['y'], color=my_cmap) return fig  However, I get the following error: "object of type 'ListedColormap' has no len()", so it seems that I'm not using my_cmap correctly. If I remove that from the function and run it, my bar chart looks ok, except that all bars have the same color. So my question is: what is the right way to use a colormap with a bar chart?

Answer: Okay, I found a way to do this without having to scale my values: def my_barchart(my_df, my_cmap): fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.bar(my_df['days'], my_df['y'], color=my_cmap.colors) return fig  Simply adding .colors after my_cmap works!
Question: It seems really simple, but I can't get it to work and the couldn't find any questions regarding this particular issue (if there are, please point out in the comments). I am showing an image and want the window to close on a specific key, but strangely, any key causes it to close. This is my simple code for testing: img = cv2.imread("MyImage.png") cv2.imshow('My Image', img) k = cv2.waitKey(0) & 0xFF print(k) if k == 27: # close on ESC key cv2.destroyAllWindows()  (based on what is said here) No matter what key I press, the key code is shown (27 for ESC, 32 for SPACE, ...) and the window closes. The main problem: the if clause is never reached (I checked by putting the print(k) inside it, and nothing is printed). After the key press, the program simply stops running and it doesn't get to checking the key code. (I am on macOS Catalina, with Python 3.8) So, how do I actually make it wait for a specific key?

Answer: From my point of view, your program just terminates, and thus all windows are implicitly closed, regardless of which key you press. One idea might be to put a while True loop around the reading and checking of the pressed key: import cv2 img = cv2.imread('path/to/your/image.png') cv2.imshow('My Image', img) while True: k = cv2.waitKey(0) & 0xFF print(k) if k == 27: cv2.destroyAllWindows() break  Running this, pressing some keys, and finally ESC, I get the following output: 103 100 102 27  Also, all windows are closed, and the program is terminated. ---------------------------------------- System information ---------------------------------------- Platform: Windows-10-10.0.16299-SP0 Python: 3.8.5 OpenCV: 4.4.0 ----------------------------------------
Question: When you import a module in python, the module code is "run". Sometimes it is useful to have branching logic in the module such as checking package versions or platform or whatever. Is there a way to exit the entire module execution before hitting the end of the file, something equivalent to early return in a function? If the module is run as a script you can exit() but that actively raises an exception and kills the whole thing. I just want to say, that's it you are done now, don't run any more code below here. Basically can I transform this if not <condition>: MY_CONSTANT = 3.14 class blah(): ... def foo(x): ... # rest of module....  into if <condition>: return from module MY_CONSTANT = 3.14 class blah(): ... def foo(x): ... # rest of module....  mostly so that I don't have to have lots of code that looks strangely one extra indent level in.

Answer: You can create a custom Loader that special-cases e.g. ImportError (1) as a shortcut to stop module execution. This can be registered via a custom Finder at sys.meta_path. So if you have the following module to be imported: # foo.py x = 1 raise ImportError # stop module execution here y = 2  You can use the following finder/loader to import that module. It will be executed until the point where it hits the raise ImportError. import importlib class Loader(importlib.machinery.SourceFileLoader): def exec_module(self, module): try: super().exec_module(module) except ImportError: # the module chose to stop executing pass class Finder(importlib.machinery.PathFinder): @classmethod def find_spec(cls, fullname, path=None, target=None): spec = super().find_spec(fullname, path, target) if spec is not None: spec.loader = Loader(spec.name, spec.origin) # register the custom loader return spec import sys sys.meta_path.insert(2, Finder()) # from now on the custom finder will be queried for imports import foo print(foo.x) # prints 1 print(foo.y) # raises AttributeError   (1) Using ImportError to indicate the shortcut obviously has its downsides, such as if your module tries to import something else which doesn't exist, this won't be reported as an error but the module just stops executing. So it's better to use some custom exception instead. I'm just using ImportError for the sake of the example.
Question: I am usually using Tornado, and trying to migrate to FastAPI. Let's say, I have a very basic API as follows: @app.post("/add_data") async def add_data(data): return data  When I am running the following Curl request: curl http://127.0.0.1:8000/add_data -d 'data=Hello' I am getting the following error: {"detail":[{"loc":["query","data"],"msg":"field required","type":"value_error.missing"}]} So I am sure I am missing something very basic, but I do not know what that might be.

Answer: Since you are sending a string data, you have to specify that in the router function with typing as from pydantic import BaseModel class Payload(BaseModel): data: str = "" @app.post("/add_data") async def add_data(payload: Payload = None): return payload Example cURL request will be in the form, curl -X POST "http://0.0.0.0:6022/add_data" -d '{"data":"Hello"}'
Question: I just learned that the new walrus operator (:=) can't be used to set instance attributes, it's supposedly invalid syntax (raises a SyntaxError). Why is this? (And can you provide a link to official docs mentioning this?) I looked through PEP 572, and couldn't find if/where this is documented.  Research This answer mentions this limitation without an explanation or source:  you can't use the walrus operator on object attributes   Sample Code class Foo: def __init__(self): self.foo: int = 0 def bar(self, value: int) -> None: self.spam(self.foo := value) # Invalid syntax def baz(self, value: int) -> None: self.spam(temp := value) self.foo = temp def spam(self, value: int) -> None: """Do something with value."""  Trying to import Foo results in a SyntaxError:  self.spam(self.foo := value) ^ SyntaxError: cannot use assignment expressions with attribute 

Answer: PEP 572 describes the purpose of this (emphasis mine):  This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr.  self.foo isn't a variable, it's an attribute of an object. The Syntax and semantics section specifies it further:  NAME is an identifier.  self.foo isn't an identifier, it's two identifiers separated by the . operator. While we often use variables and attributes similarly, and sometimes will sloppily refer to self.foo as a variable, they aren't the same. Assigning to self.foo is actually just a shorthand for setattr(self, 'foo', temp)  This is what allows you to define getters and setters for attributes. It would complicate the specification and implementation of the assignment expression if it had to work with attributes that have customized setters. For instance, if the setter transforms the value that's being assigned, should the value of the assignment expression be the original value or the transformed value? Variables, on the other hand, cannot be customized. Assigning to a variable always has the same, simple semantics, and it's easy for the expression to evaluate to the value that was assigned. Similarly, you can't use the walrus operator with slice assignment. This isn't valid: foo1[2:4] := foo2[1:3]
Question: Iam loading data via pandas read_csv like so: data = pd.read_csv(file_name_item, sep=" ", header=None, usecols=[0,1,2])  which looks like so:  0 1 2 0 257 503 48 1 167 258 39 2 172 242 39 3 172 403 81 4 180 228 39 5 183 394 255 6 192 179 15 7 192 347 234 8 192 380 243 9 192 437 135 10 211 358 234  I would like to pad this data with zeros till a row count of 256, meaning:  0 1 2 0 157 303 48 1 167 258 39 2 172 242 39 3 172 403 81 4 180 228 39 5 183 394 255 6 192 179 15 7 192 347 234 8 192 380 243 9 192 437 135 10 211 358 234 11 0 0 0 .. .. .. .. 256 0 0 0  How do I go about doing this? The file could have anything from 1 row to 200 odd rows and I am looking for something generic which pads this dataframe with 0's till 256 rows. I am quite new to pandas and could not find any function to do this.

Answer: reindex with fill_value df_final = data.reindex(range(257), fill_value=0) Out[1845]: 0 1 2 0 257 503 48 1 167 258 39 2 172 242 39 3 172 403 81 4 180 228 39 .. ... ... .. 252 0 0 0 253 0 0 0 254 0 0 0 255 0 0 0 256 0 0 0 [257 rows x 3 columns]
Question: I've been trying to scrape some information of this real estate website with selenium. However when I access the website I need to accept cookies to continue. This only happens when the bot accesses the website, not when I do it manually. When I try to find the corresponding element either by xpath or id, as I find it when I inspect the page manually I get following error. selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="uc-btn-accept-banner"]"} from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC PATH = "/usr/bin/chromedriver" driver = webdriver.Chrome(PATH) driver.get("https://www.immoweb.be/en/search/house/for-sale?countries=BE&page=1&orderBy=relevance") driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()  Does anyone know how to get around this? Why can't I find the element? Below is an image of the accept cookies popup.  This is the HTML corresponding to the button "Keep browsing". The XPATH is as above. <button aria-label="Keep browsing" id="uc-btn-accept-banner" class="uc-btn-new uc-btn-accept">Keep browsing <span id="uc-optin-timer-display"></span></button> 

Answer: You were very close! If you open your page in a new browser you'll note the page fully loads, then, a moment later your popup appears. The default wait strategy in selenium is just that the page is loaded. That draw delay between page loaded and display appearing is causing your scripts to fail. You have two good synchronisation options. 1/ Include an implicit wait for your driver. This is done once per script and affects all objects. This waits 10 seconds before throwing any error, or continues when it's ready: PATH = "/usr/bin/chromedriver" driver = webdriver.Chrome(PATH) driver.implicitly_wait(10) driver.get("https://www.immoweb.be/en/search/house/for-sale?countries=BE&page=1&orderBy=relevance") driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()  2/ Do a explicit wait on your object only: PATH = "/usr/bin/chromedriver" driver = webdriver.Chrome(PATH) driver.get("https://www.immoweb.be/en/search/house/for-sale?countries=BE&page=1&orderBy=relevance") WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="uc-btn-accept-banner"]'))).click()  More info on the wait strategies is here
Question: I am trying to install a package which uses PEP 517. The newest version of Pip won't allow me to install it due to an error involving building wheels for PEP 517. In the past, I've solved this issue by downgrading Pip, installing the package and upgrading Pip back to the latest version. However, after I downgrade pip in my virtualenv, if I try to run pip install black I get the error  No module named 'pip._internal.cli.main'  How can I solve this?

Answer: The easiest solution to deal with the error "Could not build wheels for ____ which use PEP 517 and cannot be installed directly"  is the following: sudo pip3 install _____ --no-binary :all:  Where ____ is obviously the name of the library you want to install.
Question: When I was studying Redis for my database, I learned that 'Zset' means 'Sorted Set'. What does 'Zset' actually stand for? I couldn't figure out why it also means 'Sorted Set'. It could be simple or too broad question, but I want to understand exactly what I learned.

Answer: A similar question is asked before on Redis's github page and the creator of Redis answered it  Hello. Z is as in XYZ, so the idea is, sets with another dimension: the order. It's a far association... I know :)   Set commands start with s Hash commands start with h List commands start with l Sorted set commands start with z Stream commands start with x Hyperloglog commands start with pf
Question: Can you please explain why this happens in Python v3.8? a=round(2.3) b=round(2.4) print(a,b) print(type(a),type(b)) print(a is b) print(id(a)) print(id(b))  Output: 2 2 <class 'int'> <class 'int'> False 2406701496848 2406701496656 >>>  2 is within the range of the small integer caching. So why are there different objects with the same value?

Answer: Looks like in 3.8, PyLong_FromDouble (which is what float.__round__ ultimately delegates to) explicitly allocates a new PyLong object and fills it in manually, without normalizing it (via the IS_SMALL_INT check and get_small_int cache lookup function), so it doesn't check the small int cache to resolve to the canonical value. This will change in 3.9 as a result of issue 37986: Improve perfomance of PyLong_FromDouble(), which now has it delegate to PyLong_FromLong when the double is small enough to be losslessly represented as a C long. By side-effect, this will use the small int cache, as PyLong_FromLong reliably normalizes for small values.
Question: Using pd.date_range like dr = pd.date_range('2020', freq='15min', periods=n_obs) will produce this DateTimeIndex with a 15 minute interval or frequency: DatetimeIndex(['2020-01-01 00:00:00', '2020-01-01 00:15:00', '2020-01-01 00:30:00', '2020-01-01 00:45:00', '2020-01-01 01:00:00'], dtype='datetime64[ns]', freq='15T')  You can use this to set up a pandas dataframe like: import pandas as pd import numpy as np # data np.random.seed(10) n_obs = 10 daterange = pd.date_range('2020', freq='15min', periods=n_obs) values = np.random.uniform(low=-1, high=1, size=n_obs).tolist() df = pd.DataFrame({'time':daterange, 'value':values}) df = df.set_index('time')  And now you can use pd.infer_freq(df.index) to retreive the frequency '15T' again for further calculations. Taking a closer look at help(pd.infer_freq()) lets us know that pd.infer_freq will:  Infer the most likely frequency given the input index. If the frequency is uncertain, a warning will be printed.   My understanding of this would be that it would be possible to retrieve '15T' if a few observations were missing, leading to an irregular time index. But when I remove a few of the observations using: dropped = df.index[[1,3]] df = df.drop(dropped)  Then pd.infer_freq(df.index) returns None. This also happens if we set n_obs = 100. So it would seem that I was hoping for a bit too much when I thought that [...] infer the most likely frequency [...] meant that pd.infer_freq() could infer that this was in fact an index with a 15 minute frequency with only a few missing values. Is there any other approach I could use to programmatically infer an index frequency from a somewhat irregular time series using pandas?

Answer: You could compute the minimum time difference of values in the index (here min_delta), try to find 3 consecutive values in the index, each with this minimum time difference between them, and then call infer_freq on these consecutive values of the index: diffs = (df.index[1:] - df.index[:-1]) min_delta = diffs.min() mask = (diffs == min_delta)[:-1] & (diffs[:-1] == diffs[1:]) pos = np.where(mask)[0][0] idx = df.index print(pd.infer_freq(idx[pos: pos + 3]))  This retrieves "15T".