eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I am building a simple GUI with pysimplegui and want to right-justify a button inside a frame. I have found details on how to do this with text but not with buttons. For example, I would like the button below to snap to the right side of the frame with the groove around it. I want this:  To look more like this:  But without having to add in a manually adjusted blank text element to get it close as this often doesn't line up correctly (note the commented out sg.Text("", size=(22, 1)) line below). import sys import PySimpleGUI as sg sg.theme("Light Blue 2") layout = [ [ sg.Text("Target folder", size=(9, 1)), sg.InputText(default_text="Choose a folder...", size=(59, 1)), sg.FolderBrowse(), ], [ sg.Frame( layout=[ [ sg.Text("First parameter", size=(15, 1)), sg.InputText(default_text="2", size=(3, 1),), ], [ sg.Text("Second parameter", size=(15, 1)), sg.InputText(default_text="8", size=(3, 1),), # sg.Text("", size=(22, 1)), sg.Submit("A nice button", size=(23, 1)), ], [sg.ProgressBar(1, orientation="h", size=(50, 20))], ], title="Cool subpanel", relief=sg.RELIEF_GROOVE, ) ], ] window = sg.Window("Test window", layout) while True: event, values = window.read() if event == "Cancel" or event is None: sys.exit() 

Answer: Your question just missed a release of PySimpleGUI that makes this operation trivial. One problem with StackOverflow is - "nothing dies"... including old solutions. It's a genuine problem that I've yet to find a solid solution for. This technique was released in Sept 2021 in version 4.48.0 and uses the, then new, Push element. As the name implies, the Push will push around elements. By putting one between elements, it will push the elements apart. Here's your code with a Push added just before the button you want right justified. import sys import PySimpleGUI as sg sg.theme("Light Blue 2") layout = [ [ sg.Text("Target folder", size=(9, 1)), sg.InputText(default_text="Choose a folder...", size=(59, 1)), sg.FolderBrowse(), ], [ sg.Frame( layout=[ [ sg.Text("First parameter", size=(15, 1)), sg.InputText(default_text="2", size=(3, 1),), ], [ sg.Text("Second parameter", size=(15, 1)), sg.InputText(default_text="8", size=(3, 1),), sg.Push(), sg.Button("A nice button", size=(23, 1)), ], [sg.ProgressBar(1, orientation="h", size=(50, 20))], ], title="Cool subpanel", relief=sg.RELIEF_GROOVE, ) ], ] window = sg.Window("Test window", layout) while True: event, values = window.read() if event == "Cancel" or event is None: sys.exit()  And this is the result:  Note (that's not super important) - I've replaced Submit with Button as using Submit is perhaps confusing. Submit is nothing more than a function that returns a Button element with the text "Submit". It doesn't do anything special and in fact provides less parameter perhaps than just Button.
Question: I have a manual scaling set-up on EC2 where I'm creating instances based on an AMI which already runs my code at boot (using Systemd). I'm facing a fundamental problem: on the main instance (the one I use to create the AMI, the Python code takes 8 seconds to be ready after the image is booted, this includes importing libraries, loading state dicts of models, etc...). Now, on the images I create with the AMI, the code takes 5+ minutes to boot up the first time, it takes especially long to load the state dicts from disk to GPU memory, after the first time the code takes about the same as the main instance to load. The AMI keeps the same pycache folders as the main instance, so it shouldn't take that much time since I think the AMI should include everything, shouldn't it?. So, my question is: Is there any other caching to make CUDA / Python faster that I'm not taking into consideration? I'm only keeping the pycache/ folders, but I don't know if there's anything I could do to make sure it doesn't take that much time to boot everything the first time. This is my main structure: # Import libraries import torch import numpy as np # Import personal models (takes 1 minute) from model1 import model1 from model2 import model2 # Load first model model1_object = model1() model2_object = model2() # Load state dicts (takes 3+ minutes, the first time in new instances, seconds other times) # Note: the models are a bit heavy model1_object.load_state_dict(torch.load("model1.pth")) model2_object.load_state_dict(torch.load("model2.pth"))  Note: I'm using g4dn.xlarge instances, for both the main instance and for newer ones in AWS.

Answer: This was caused because of the high latencies required while restoring AWS EBS snapshots. At first when you restore a snapshot, the latency is extremely high, explaining why the model takes so much to load in my example when the instance is freshly created. Check the initialization section of this article: https://cloudonaut.io/ebs-snapshot-pitfalls/ The only solution that I've found to use an instance fast when it is first created is to enable Fast Snapshot Restore, which costs around 500$ a month: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-fast-snapshot-restore.html If you have time to spare, you can wait until the maximum performance is achieved, or try to warm the volume up beforehand https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-initialize.html
Question: ffmpeg is installed on Anaconda Navigator (in base(root) environment), but when I run import ffmpeg, I got this error message: ModuleNotFoundError: No module named 'ffmpeg'  Why is this module not found and how can I fix this? 

Answer: You need to install the ffmpeg-python module to the environment: pip install ffmpeg-python  or conda install -c conda-forge ffmpeg-python  from there import ffmpeg statements when using the environment should work.
Question: Cross posted on GitHub I'm working with AWS Amplify and pipenv for my python 3.9 lambda. I'm attempting to use pandas to create a dataframe, do some processing and write it back to CSV for sagemaker inference. Reproducing code example: import pandas as pd  (Code immediately fails after this) Error message: Here's the full error message: [ERROR] Runtime.ImportModuleError: Unable to import module 'index': IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.9 from "/var/lang/bin/python3.9" * The NumPy version is: "1.21.2" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: No module named 'numpy.core._multiarray_umath'  I first downloaded with pipenv install pandas which automatically installs numpy To solve I've tried:  pipenv install numpy / pipenv uninstall numpy pipenv uninstall pandas / pipenv install pandas pipenv uninstall setuptools / pipenv install setuptools  Important to note I'm on Windows 10

Answer: I had ran into a similar issue. After much research it looks like the Lambda Layer AWSLambda-Python38-SciPy1x provided by Amazon is your best bet. More Info is here. You can manually add the Layer via the Console like so:  Picture for you  Or you can add the layer via the Amplify CLI. I ran the following commands on an existing lambda function: amplify function update   Then select the Lambda function (serverless function) you'd like to add the layer to.  Go to Lambda layers configuration.  Provide the ARN under Provide existing Lambda Layer ARN.  I used arn:aws:lambda:us-west-2:420165488524:layer:AWSLambda-Python38-SciPy1x:29 amplify push   That should do the trick.
Question: So I have this simple example of a with statement. It works in Python 3.8 and 3.9: class Foo: def __enter__(self, *args): print("enter") def __exit__(self, *args): print("exit") with Foo() as f, Foo() as b: print("Foo")  Output (as expected): enter enter Foo exit exit  But if I add parentheses like this it only works in Python 3.9: class Foo: def __enter__(self, *args): print("enter") def __exit__(self, *args): print("exit") with (Foo() as f, Foo() as b): print("Foo")  Output in 3.8:  File "foo.py", line 8 with (Foo() as f, Foo() as b): ^ SyntaxError: invalid syntax  I know, I could just remove the parentheses but I don't understand why it works in Python 3.9 in the first place. I could not find the relevant change log.

Answer: Parenthesized context managers are mentioned as a new feature in What’s New In Python 3.10. The changelog states:  This new syntax uses the non LL(1) capacities of the new parser. Check PEP 617 for more details.  But PEP 617 was already accepted in Python 3.9, as described in its changelog:  Python 3.9 uses a new parser, based on PEG instead of LL(1). The new parser’s performance is roughly comparable to that of the old parser, but the PEG formalism is more flexible than LL(1) when it comes to designing new language features. We’ll start using this flexibility in Python 3.10 and later.  It was even already part of the Python 3.9 grammar:  with_stmt: | 'with' '(' ','.with_item+ ','? ')' ':' block | 'with' ','.with_item+ ':' [TYPE_COMMENT] block | ASYNC 'with' '(' ','.with_item+ ','? ')' ':' block | ASYNC 'with' ','.with_item+ ':' [TYPE_COMMENT] block with_item: | expression 'as' star_target &(',' | ')' | ':') | expression   My guess is that because the LL1 parser was officially removed in Python 3.10, only then it was considered a new feature, while still being supported in 3.9.
Question: I'm running a websocket listener in a separate thread. I'd like to connect to the websocket then do: while True: msg = sock.wait_for_message() f(msg)  i.e. no async/asyncio Is this stupid? Is there a way to do this?

Answer: In absence of a better answer, I have found https://github.com/websocket-client/websocket-client which prove painless to use.
Question: I'm able to get the desired sheet by using wb["sheet_name"] method but I want to get the first, or let's say the nth sheet, regardless of the name. wb = load_workbook(filename = xlsx_dir) # xlsx_dir is the workbook path ws = wb["Details"] # Details is the sheet name 

Answer: You need to use the worksheets property of the workbook object ws = wb.worksheets[0]
Question: Two similar ways to check whether a list contains an odd number: any(x % 2 for x in a) any(True for x in a if x % 2)  Timing results with a = [0] * 10000000 (five attempts each, times in seconds): 0.60 0.60 0.60 0.61 0.63 any(x % 2 for x in a) 0.36 0.36 0.36 0.37 0.37 any(True for x in a if x % 2)  Why is the second way almost twice as fast? My testing code: from timeit import repeat setup = 'a = [0] * 10000000' expressions = [ 'any(x % 2 for x in a)', 'any(True for x in a if x % 2)', ] for expression in expressions: times = sorted(repeat(expression, setup, number=1)) print(*('%.2f ' % t for t in times), expression)  Try it online!

Answer: The first method sends everything to any() whilst the second only sends to any() when there's an odd number, so any() has fewer elements to go through.
Question: Using SQLModel how to get alembic to recognise the below model? from sqlmodel import Field, SQLModel class Hero(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None  One approach I've been looking at is to import the SQLalchemy model for Alembic but looking through the source code I can't find how to do that. How to make Alembic work with SQLModel models?

Answer: There should be info about that in Advanced user guide soon with better explanation than mine but here is how I made Alimbic migrations work. First of all run alembic init migrations in your console to generate migrations folder. Inside migrations folder should be empty versions subfolder,env.py file, script.py.mako file. In script.py.mako file we should add line import sqlmodel somewhere around these two lines #script.py.mako from alembic import op import sqlalchemy as sa import sqlmodel # added  Then we should edit env.py file #env.py from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context from app.models import * # necessarily to import something from file where your models are stored # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata target_metadata = None # comment line above and instead of that write target_metadata = SQLModel.metadata  While writing came up with an idea that you forgot to import something from your models.py (or anywhere else your models are stored). And that was the main problem Also, an important note would be saving changes in your models by pressing ctrl(CMD) + S - there are some issues with that. Finally,running  alembic revision --autogenerate -m "your message"  should generate a new .py file in versions folder with your changes. And  alembic upgrade head  Applies your changes to DB.
Question: I have a plot with both a colorbar and a legend. I want to place the legend outside of the plot to the right of the colorbar. To accomplish this, I use bbox_to_anchor argument, but this causes the legend to get cut off: import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm _, ax = plt.subplots() extent = np.r_[0, 1, 0, 1] space = np.linspace(0, 1) probs = np.array([[norm.cdf(x + y) for x in space] for y in space]) colormap = ax.imshow(probs, aspect="auto", origin="lower", extent=extent, alpha=0.5) colorbar = plt.colorbar(colormap, ax=ax) colorbar.set_label(f"Probability") ax.scatter( [0.2, 0.4, 0.6], [0.8, 0.6, 0.4], color="r", label="Labeled Points", ) plt.legend(loc="center left", bbox_to_anchor=(1.3, 0.5)) plt.title plt.show()  Plot with legend cut off  To fix the legend, I insert a call to plt.tight_layout() before plt.show(), but this causes the aspect ratio to get distorted: Plot with distorted aspect ratio  How can I show the entire legend and preserve the aspect ratio of the axes?

Answer: You can manage the ratio between axis height and width with matplotlib.axes.Axes.set_aspect. Since you want them to be equal: ax.set_aspect(1)  Then you can use matplotlib.pyplot.tight_layout to fit the legend within the figure. If you want to adjust margins too, you can use matplotlib.pyplot.subplots_adjust. Complete Code import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm _, ax = plt.subplots() extent = np.r_[0, 1, 0, 1] space = np.linspace(0, 1) probs = np.array([[norm.cdf(x + y) for x in space] for y in space]) colormap = ax.imshow(probs, aspect="auto", origin="lower", extent=extent, alpha=0.5) colorbar = plt.colorbar(colormap, ax=ax) colorbar.set_label(f"Probability") ax.scatter([0.2, 0.4, 0.6], [0.8, 0.6, 0.4], color="r", label="Labeled Points",) plt.legend(loc="center left", bbox_to_anchor=(1.3, 0.5)) ax.set_aspect(1) plt.tight_layout() plt.subplots_adjust(left = 0.1) plt.show()
Question: I need a double inheritance for a class that is an Enum but also support my own methods. Here's the context: import abc from enum import Enum class MyFirstClass(abc.ABC): @abc.abstractmethod def func(self): pass class MySecondClass(Enum, MyFirstClass): VALUE_1 = 0 VALUE_2 = 1 def func(self): return 42  The declaration of MySecondClass yields the following error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases  I tried applying this stackoverflow solution by doing: class MyMetaClass(type(Enum), type(MyFirstClass)): pass class MyFinalClass(Enum, MyFirstClass, metaclass=MyMetaClass): VALUE_1 = 0 VALUE_2 = 1 def func(self): return 42  But I get the following error: TypeError: new enumerations should be created as `EnumName([mixin_type, ...] [data_type,] enum_type)`  Is this an issue specific to the Enum type, or am I missing something else regarding metaclasses?

Answer: The solution to your immediate problem is: class MyFinalClass(MyFirstClass, Enum, metaclass=MyMetaClass): pass  Note that Enum is the last regular class listed. For a fully functioning abstract Enum you'll want to use the ABCEnumMeta from this answer -- otherwise missing abstract methods will not be properly flagged.
Question: First, to begin with, I was successfully able to place an order using TWS API. However, for that, as I understood, I need to run the TWS desktop version in the background. But I need to run this on my remote server. So I used a 3rd party API called IBeam and created a gateway using it, in the remote server. Now it is working well and serving the GET requests that I request from the Interactive Brokers. Now, I want to place an order in Interactive Broker, using an API request and found this doc by IB. However, for me it is not clear what they meant by each argument, so as of now I am stuck. I.e, from docs, I need to send a POST request to https://localhost:5000/v1/api/iserver/account/{accountId}/orders (with IB gateway running in localhost:5000) with the request body { "orders": [ { "acctId": "string", "conid": 0, "secType": "secType = 265598:STK", "cOID": "string", "parentId": "string", "orderType": "string", "listingExchange": "string", "isSingleGroup": true, "outsideRTH": true, "price": 0, "auxPrice": null, "side": "string", "ticker": "string", "tif": "string", "referrer": "QuickTrade", "quantity": 0, "fxQty": 0, "useAdaptive": true, "isCcyConv": true, "allocationMethod": "string", "strategy": "string", "strategyParameters": {} } ] }  From what I learn from the TWS API, this was all the information needed to place an order:  contract = Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" order = Order() order.action = "BUY" order.totalQuantity = 10 order.orderType = "MKT"  It would be great if you could help me with a sample code to place a similar order using the REST API of Ineteractive Broker

Answer: I found this article helpful in the process of placing an order. I.e, this is a sample request that you can use to place an order { "orders": [ { "acctId": "DU4299134", "conid": 8314, "secType": "8314:STK", "cOId": "testAlgoOrder", "orderType": "LMT", "price": 142, "side": "BUY", "tif": "DAY", "quantity": 1, "strategy": "Adaptive", "strategyParameters": {"adaptivePriority": "Normal" } } ] }  You can use these URLs to find more info about the strategies, url = f"https://localhost:5000/v1/api/iserver/contract/{conid}/algos" url_more_info = f"https://localhost:5000/v1/api/iserver/contract/{conid}/algos?addDescription=1&addParams=1&algos={algos}"  Further, when you place an order like above, IBKR will ask you to confirm the order, which you can do by url = f"https://localhost:5000/v1/api/iserver/reply/{replyid}" data = '''{ "confirmed": true }''' response = requests.post(url, data=data, headers=headers, verify='path to .pem file')  Note that you have to use the correct header when you are sending a POST requests to IBKR as mentioned here.
Question: EDIT I'm trying to import algosec.models in a file inside the algobot package. I've tried to add --hidden-import algosec, I've also tried to add the path before importing, using sys.path.append(./../algosec) this is the error message I get when I try to run the program: Traceback (most recent call last): File "algobot_packer/algobot.py", line 2, in <module> File "PyInstaller/loader/pyimod03_importers.py", line 546, in exec_module File "algobot/cli/cli.py", line 3, in <module> File "PyInstaller/loader/pyimod03_importers.py", line 546, in exec_module File "algobot/microsoft_teams/mainloop.py", line 9, in <module> File "PyInstaller/loader/pyimod03_importers.py", line 546, in exec_module File "algobot/framework/configuration.py", line 34, in <module> File "PyInstaller/loader/pyimod03_importers.py", line 546, in exec_module File "algobot/framework/commands.py", line 22, in <module> File "PyInstaller/loader/pyimod03_importers.py", line 546, in exec_module File "algobot/framework/bot.py", line 4, in <module> File "PyInstaller/loader/pyimod03_importers.py", line 546, in exec_module File "algobot/framework/responses.py", line 9, in <module> ModuleNotFoundError: No module named 'algosec'  the folder structure is:  algobot  algobot algosec algobot-packer pyucwa    I'm using pyinstaller version 4.2 I didn't make any change in the code since the last time my executable file ran perfectly fine, but now I'm getting this error every time. the thing is - the folder 'algosec' is a subdirectory in my project, and it is noted in the pipfile and again, I didn't make any change in a while and tested it recently (last tested on July 8th)), therefore I believe that it's a dependency issue but not sure which or how to solve. I've tried multiple changes that somehow worked on one run but when I tried to make these changes again it failed on other builds...

Answer: Apparently since I took the highest version of zeep and deprecated without giving a fixed version, it caused issues because of a newer release. I had to add them to setup.py of the algobot package which is the main package of the executable with a fixed version. In addition I had to add a .egg file of the algosec package with --paths in order for pyinstaller to find it.
Question: I have a question I'm new to the python async world and I write some code to test the power of asyncio, I create 10 files with random content, named file1.txt, file2.txt, ..., file10.txt here is my code: import asyncio import aiofiles import time async def reader(pack, address): async with aiofiles.open(address) as file: pack.append(await file.read()) async def main(): content = [] await asyncio.gather(*(reader(content, f'./file{_+1}.txt') for _ in range(10))) return content def core(): content = [] for number in range(10): with open(f'./file{number+1}.txt') as file: content.append(file.read()) return content if __name__ == '__main__': # Asynchronous s = time.perf_counter() content = asyncio.run(main()) e = time.perf_counter() print(f'Take {e - s: .3f}') # Synchronous s = time.perf_counter() content = core() e = time.perf_counter() print(f'Take {e - s: .3f}')  and got this result: Asynchronous: Take 0.011 Synchronous: Take 0.001  why Asynchronous code takes longer than Synchronous code ? where I do it wrong ?

Answer: I post an issue #110 on aiofiles's GitHub and the author of aiofiles answer that:  You're not doing anything wrong. What aiofiles does is delegate the file reading operations to a thread pool. This approach is going to be slower than just reading the file directly. The benefit is that while the file is being read in a different thread, your application can do something else in the main thread.A true, cross-platform way of reading files asynchronously is not available yet, I'm afraid :)  I hope it be helpful to anybody that has the same problem