eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Try to run a test code for stable baselines gym import gym from stable_baselines3 import A2C env = gym.make("CartPole-v1") model = A2C("MlpPolicy", env, verbose=1) model.learn(total_timesteps=10_000) obs = env.reset() for i in range(100): action, _state = model.predict(obs, deterministic=True) obs, reward, done, info = env.step(action) env.render() if done: obs = env.reset()  found the error "NameError: name 'glPushMatrix' is not defined" Traceback (most recent call last): File "test_cart_pole.py", line 14, in <module> env.render() File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/gym/core.py", line 295, in render return self.env.render(mode, **kwargs) File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/gym/envs/classic_control/cartpole.py", line 229, in render return self.viewer.render(return_rgb_array=mode == "rgb_array") File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/gym/envs/classic_control/rendering.py", line 126, in render self.transform.enable() File "/Users/xxx/opt/anaconda3/lib/python3.8/site-packages/gym/envs/classic_control/rendering.py", line 232, in enable glPushMatrix() NameError: name 'glPushMatrix' is not defined  I tried "pip install PyOpenGL PyOpenGL_accelerate", which didn't help also uninstall pyglet and install again , did't work too Any Idea???

Answer: Just had the same problem. Fixed it by installing an older version of pyglet: $ pip install pyglet==1.5.27  I don't know if this is the latest version that avoids the problem, but it works.
Question: I have a set which contains objects which I have the __eq__ and __hash__ functions defined for. I would like to be able to check if an object with the same hash is in the set and if it is in the set to return the object from the set as I need the reference to the object. class SetObject(): def __init__( self, a: int, b: int, c: int ): self.a = a self.b = b self.c = c def __repr__(self): return f"SetObject ({self.a} {self.b} {self.c}) (id: {id(self)}" def __eq__(self, other): return isinstance(other, SetObject) \ and self.__hash__() == other.__hash__() def __hash__(self): # Hash only depends on a, b return hash( (self.a,self.b) ) x = SetObject(1,2,3) y = SetObject(4,5,6) object_set = set([x,y]) print(f"{object_set=}") z = SetObject(1,2,7) print(f"{z=}") if z in object_set: print("Is in set") # Get the object in set which is equal to z for element in object_set: if element == z: print(element) z = element print(f"{z=}") 

Answer: Instead of using a set, use a dictionary where the keys and values are the same element. Then you can look use the value as a key and return the element. x = SetObject(1,2,3) y = SetObject(4,5,6) object_set = dict([(x, x),(y, y)]) print(f"{object_set=}") z = SetObject(1,2,7) print(f"{z=}") if z in object_set: print("Is in set") z = object_set[z] print(f"{z=}")  If you want to simplify this, you could define a subclass of dict that automatically makes the values the same as the keys.
Question: I have a function, that accepts inputs of different types, and they all have default values. For example, def my_func(a: str = 'Hello', b: bool = False, c: int = 1): return a, b, c  What I want to do is define the non-default kwargs in a dictionary, and then pass this to the function. For example, input_kwargs = {'b': True} result = my_func(**input_kwargs)  This works fine in that it gives me the output I want. However, mypy complains giving me an error like: error: Argument 1 to "my_func" has incompatible type "**Dict[str, bool]"; expected "str".  Is there any way to get around this. I don't want to manually enter the keywords each time, as these input_kwargs would be used multiple times across different functions.

Answer: You can create a class (by inheriting from TypedDict) with class variables that match with my_func parameters. To make all these class variables as optional, you can set total=False. Then use this class as the type for input_kwargs to make mypy happy :) from typing import TypedDict class Params(TypedDict, total=False): a: str b: bool c: int def my_func(a: str = 'Hello', b: bool = False, c: int = 1): return a, b, c input_kwargs: Params = {'b': True} result = my_func(**input_kwargs)
Question: I am just checking where is the limit of changing python using python (without modifying interpreter and/or C code). I know that I can basically monkey patch every builtin function like this: import builtins int(1) # 1 def new_int(number): return number + 1 builtins.int = new_int int(1) # 2  I know I can turn python classes upside down using special methods like __new__, __get__ etc. and that I can overload any operator. but is there any way to monkey patch parentheses? so that instead of creating list, python will do something else with elements between [...] like creating tuple. # normal old = [1,2,3,4] print(old) # [1, 2, 3, 4] type(old) # <class 'list'> # some strange code that monkeypatches [] so that instead of list, it creates tuple def monkey_patch_list(values): return tuple(values) [] = monkey_patch_list # of course it is wrong # new new = [1,2,3,4] print(new) # (1, 2, 3, 4) type(old) # <class 'tuple'>  Probably there is no way to do it just in python but maybe somewhere hidden in python code there is a definition of handling [] so that I can mess it up. If there is anyone crazy like me and knows how to do it I will appreciate help. Disclaimer: Don't worry just for fun, thanks ;)

Answer: This can be done as a function decorator as long as the lists to be replaced as tuples are defined in a function. To do that, use ast.NodeTransformer to replace any ast.List node with an equivalent ast.Tuple node in the function's AST: import ast import inspect from textwrap import dedent class ForceTuples(ast.NodeTransformer): def visit_List(self, node): return ast.Tuple(**vars(node)) # remove 'force_tuples' from the function's decorator list to avoid re-decorating during exec def visit_FunctionDef(self, node): node.decorator_list = [ decorator for decorator in node.decorator_list if not isinstance(decorator, ast.Name) or decorator.id != 'force_tuples' ] self.generic_visit(node) return node def force_tuples(func): tree = ForceTuples().visit(ast.parse(dedent(inspect.getsource(func)))) ast.fix_missing_locations(tree) scope = {} exec(compile(tree, inspect.getfile(func), 'exec'), func.__globals__, scope) return scope[func.__name__]  so that: @force_tuples def foo(): bar = [1, 2, 3, 4] print(bar) print(type(bar)) foo()  outputs: (1, 2, 3, 4) <class 'tuple'>  Demo: https://replit.com/@blhsing/MellowLinearSystemsanalysis
Question: import requests from bs4 import BeautifulSoup import openai #write each line of nuclear.txt to a list with open('nuclear.txt', 'r') as f: lines = f.readlines() #remove the newline character from each line lines = [line.rstrip() for line in lines] #gather the text from each website and add it to a new txt file for line in lines: r = requests.get(line) soup = BeautifulSoup(r.text, 'html.parser') text = soup.get_text() with open('nuclear_text.txt', 'a') as f: f.write(text)  I'm trying to import openai, however it keeps throwing the error module not found. I have done pip install openai and it downloads, but it appears to be the wrong version of python. How do I select the correct one for pip to install to? I am using VSCode pip install openai

Answer: Follow the steps below to install the openai package for the current interpreter  run the following code import sys print(sys.executable)   get the current interpreter path   Copy the path and install openai using the following command in the terminal C:\WorkSpace\pytest10\.venv\Scripts\python.exe -m pip install openai  Modify the path in the above command to the interpreter path you got.
Question: given a dictionary dictionary = {'Animal 1': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Black'}, 'Animal 2': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Brown'}, 'Animal 3': {'Dog': 'No', 'Cat': 'Yes', 'Color': 'Grey'}}  How do I select the Animals that are dogs? expected output ['Animal 1','Animal 2'] I could use: pd.DataFrame.from_dict(dictionary).T.loc[pd.DataFrame.from_dict(dictionary).T["Dog"]=='Yes',:].index.to_list()  but it looks very ugly

Answer: You can use list comprehension: dictionary = { "Animal 1": {"Dog": "Yes", "Cat": "No", "Color": "Black"}, "Animal 2": {"Dog": "Yes", "Cat": "No", "Color": "Brown"}, "Animal 3": {"Dog": "No", "Cat": "Yes", "Color": "Grey"}, } out = [k for k, d in dictionary.items() if d.get("Dog") == "Yes"] print(out)  Prints: ['Animal 1', 'Animal 2']
Question: I was reading about how functions become bound methods when being set as class atrributes. I then observed that this is not the case for functions that are wrapped by functools.partial. What is the explanation for this? Simple example: from functools import partial def func1(): print("foo") func1_partial = partial(func1) class A: f = func1 g = func1_partial a = A() a.f() # TypeError: func1() takes 0 positional arguments but 1 was given a.g() # prints "foo"  I kind of expected them both to behave in the same way.

Answer: The trick that allows functions to become bound methods is the __get__ magic method. To very briefly summarize that page, when you access a field on an instance, say foo.bar, Python first checks whether bar exists in foo's __dict__ (or __slots__, if it has one). If it does, we return it, no harm done. If not, then we look on type(foo). However, when we access the field Foo.bar on the class Foo through an instance, something magical happens. When we write foo.bar, assuming there is no bar on foo's __dict__ (resp. __slots__), then we actually call Foo.bar.__get__(foo, Foo). That is, Python calls a magic method asking the object how it would like to be retrieved. This is how properties are implemented, and it's also how bound methods are implemented. Somewhere deep down (probably written in C), there's a __get__ function on the type function that binds the method when accessed through an instance. functools.partial, despite looking a lot like a function, is not an instance of the type function. It's just a random class that happens to implement __call__, and it doesn't implement __get__. Why doesn't it? Well, they probably just didn't think it was worth it, or it's possible nobody even considered it. Regardless, the "bound method" trick applies to the type called function, not to all callable objects.  Another useful resource on magic methods, and __get__ in particular: https://rszalski.github.io/magicmethods/#descriptor
Question: After looking at this question I learned that the type hints are, by default, not enforced whilst executing Python code. One can detect some discrepancies between the type hints and actual argument types using a slightly convoluted process of running pyannotate to generate stubs whilst running Python code, and scanning for differences after applying these stubs to the code. However, it would be more convenient/faster to directly raise an exception if an incoming argument is not of the type included in the type hint. This can be achieved by manually including: if not isinstance(some_argument, the_type_hint_type): raise TypeError("Argument:{argument} is not of type:{the_type_hint_type}")  However, that is quite labour intensive. Hence, I was curious, is it possible to make Python raise an error if a type-hint is violated, using an CLI argument or pip package or something like that?

Answer: The edit queue for the Answer by @Surya_1897 is full, hence I will include a more detailed description of the solution here. Typeguard does exactly what I was looking for. The following requirements apply:  Install typeguard with:  pip install typeguard   Import typeguard into each script, and add the @typechecked property above each function. Example: Change:  """Some file description.""" def add_two(x:int): """Adds two to an incoming int.""" return x+2 somevar:float=42.1 add_two(somevar)  To: """Some file description.""" from typeguard import typechecked @typechecked def add_two(x:int): """Adds two to an incoming int.""" return x+2 somevar:float=42.1 add_two(somevar)  The latter will than throw an err:  TypeError: type of argument "x" must be int; got float instead
Question: For example, let's consider the following numpy array: [1, 5, 0, 5, 4, 6, 1, -1, 5, 10]  Also, let's suppose that the threshold is equal to 3. That is to say that we are looking for sequences of at least two consecutive values that are all above the threshold. The output would be the indices of those values, which in our case is: [[3, 4, 5], [8, 9]]  If the output array was flattened that would work as well! [3, 4, 5, 8, 9]   Output Explanation In our initial array we can see that for index = 1 we have the value 5, which is greater than the threshold, but is not part of a sequence (of at least two values) where every value is greater than the threshold. That's why this index would not make it to our output. On the other hand, for indices [3, 4, 5] we have a sequence of (at least two) neighboring values [5, 4, 6] where each and every of them are above the threshold and that's the reason that their indices are included in the final output!  My Code so far I have approached the issue with something like this: (arr > 3).nonzero()  The above command gathers the indices of all the items that are above the threshold. However, I cannot determine if they are consecutive or not. I have thought of trying a diff on the outcome of the above snippet and then may be locating ones (that is to say that indices are one after the other). Which would give us: np.diff((arr > 3).nonzero())  But I'd still be missing something here.

Answer: If you convolve a boolean array with a window full of 1 of size win_size ([1] * win_size), then you will obtain an array where there is the value win_size where the condition held for win_size items: import numpy as np def groups(arr, *, threshold, win_size, merge_contiguous=False, flat=False): conv = np.convolve((arr >= threshold).astype(int), [1] * win_size, mode="valid") indexes_start = np.where(conv == win_size)[0] indexes = [np.arange(index, index + win_size) for index in indexes_start] if flat or merge_contiguous: indexes = np.unique(indexes) if merge_contiguous: indexes = np.split(indexes, np.where(np.diff(indexes) != 1)[0] + 1) return indexes arr = np.array([1, 5, 0, 5, 4, 6, 1, -1, 5, 10]) threshold = 3 win_size = 2 print(groups(arr, threshold=threshold, win_size=win_size)) print(groups(arr, threshold=threshold, win_size=win_size, merge_contiguous=True)) print(groups(arr, threshold=threshold, win_size=win_size, flat=True))  [array([3, 4]), array([4, 5]), array([8, 9])] [array([3, 4, 5]), array([8, 9])] [3 4 5 8 9]
Question: I have a pandas dataframe filled with time-stamped data. It is out of order; and I am trying to sort by date, hours and minutes. The pandas dataframe will organize by date, but not by hours and minutes. My dataframe is loaded in ('df'), and the column 'dttime' was changed it into a dateframe from integer numbers. df['dttime'] = pd.to_datetime(df['dttime'], format='%y%m%d%H%M%S')  I resort it with: df.sort_values(by='dttime')  but that does not seem to have the right ordering of the hour minutes and seconds.

Answer: I tried with some dummy data and it doesn't look like an issue to me. Please check the below code. import pandas as pd data = ['221011141200', '221011031200', '221011191200', '221011131600'] df = pd.DataFrame(data, columns=['dttime']) df['dttime'] = pd.to_datetime(df['dttime'], format='%y%m%d%H%M%S') # Before sorting print(df) # After sorting df = df.sort_values(by='dttime') print(df)  Output is as follows:  dttime 0 2022-10-11 14:12:00 1 2022-10-11 03:12:00 2 2022-10-11 19:12:00 3 2022-10-11 13:16:00 dttime 1 2022-10-11 03:12:00 3 2022-10-11 13:16:00 0 2022-10-11 14:12:00 2 2022-10-11 19:12:00
Question: Here is my code: def del_rep_vow(s): ''' >>> del_rep_vow('adaptation') 'adpttion' >>> del_rep_vow('repetitions') 'reptitons' >>> del_rep_vow('kingkong') 'kingkong' >>> del_rep_vow('aeiouaeiou') 'aeiou' ''' final_list = [] for i in s: if i not in final_list: final_list.append(i) return ''.join(final_list) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)  I don't know how to make the restriction that only repeated vowels have to be deleted once they are in the list. Any help will be very welcome. Output of 'adaptation' must be 'adpttion', for example.

Answer: You should maintain a Python set of vowel characters already seen. For each new encountered letter as you walk down the string, only append a vowel if it is not in the set. def del_rep_vow(s): vowels_seen = set() final_list = [] for i in s: if i in ['a', 'e', 'i', 'o', 'u']: if i not in vowels_seen: final_list.append(i) vowels_seen.add(i) else: final_list.append(i) return ''.join(final_list) print(del_rep_vow('adaptation')) # 'adpttion' print(del_rep_vow('repetitions')) # 'reptitons' print(del_rep_vow('kingkong')) # 'kingkong' print(del_rep_vow('aeiouaeiou')) # 'aeiou'
Question: My dataframe has 4 columns (one dependent variable and 3 independent). Here's a sample:  My desired output is a contingency table, as follows:  I can only seem to get a contingency table using one independent variable- using the following code (my df is called 'table') pd.crosstab(index=table['Dvar'],columns=table['Var1'])  I can't seem to be able to add any other variables to this...Is the only way to achieve this to do make a separate contingency table for each var (1 to 3) and then merge/ join them?

Answer: First of all, contingency table is for showing correlation between features. If you want to probably see correlation between independent and dependent features, go through this code: pd.crosstab([table['Var1'],table['Var2'],table['Var3']], table['Dvar'], margins = False)  But, as you mention, to get your desired output for that use pandas.DataFrame.groupby statement as: table.groupby('Dvar').sum()
Question: I've been spending a few days trying to figure out how best to build a Python Lambda bundle when using Poetry. I found a few blogs that that outline the same technique but those didn't work in my situation. The solution provided in the blogs is to use pip install to install the needed dependencies into a specific directory and zip it up. poetry run pip install -t dist/lambda . cd dist/lambda zip -r ../lambda.zip .  However, this doesn't work if you use path dependencies with Poetry. You get an error from pip stating pip._vendor.pkg_resources.RequirementParseError: Invalid URL:  for any local dependency. I did run into the Poetry Bundle Plugin and it looked promising. Using it did work in that it installed the needed dependencies and the project itself into the chosen target directory. poetry self add poetry-plugin-bundle poetry bundle venv .venv-lambda cd .venv-lambda/lib/python*/site-packages/ zip -r ../../../../dist/lambda.zip .  The problem with this approach is that it installs more than just the mainline dependencies, but also the dev and test dependencies. There is no option to specify which dependency group to include or exclude. There is an open issue with a PR that is waiting to be merged to resolve this. Once that is resolved, this is likely the ideal solution. Until then, I need something different/better.

Answer: Ultimately I found this documentation from AWS for how to create a lambda archive from a Python virtual environment. Using Poetry's install command, I was able to install just the main runtime dependencies into the Poetry projects created virtual environment, including any local path based dependencies. However, this doesn't install the project itself so the source code needs to be copied in before being archived. In my case, I use a dedicated source directory/module for my code. poetry install --only main --sync mkdir -p dist/lambda-package cp --recursive .venv/lib/python*/site-packages/* dist/lambda-package/ cp --recursive my_project_source_directory dist/lambda-package/ cd dist/lambda-package zip -r ../dist/lambda.zip .  The above commands are what I use on my CI build. The local .venv directory is used because the following Poetry setting virtualenvs.in-project is set to true. The other thing necessary for this to work is to not use editable path based dependencies, or at least just do that locally during development. Marking them as editable will not install the dependency into the virtual environment, but will rather just create a link to the project source code. This will not get picked up when creating the zip file. This isn't perfect as there is likely more that gets bundled than necessary but it does remove any dev and test dependencies from the Poetry plugin solution. Also, because on my CI build server, I cache the installed dependencies in the virtual environment, this means at the end of my build, none of the dev or test dependencies are present to be cached and get installed on every run. I hope this helps someone else in a similar situation.
Question: This is my Code ` from attr import attr import requests from bs4 import BeautifulSoup import csv datas = [] key = 'sepatu' jenis = 'teplek' url = 'https://website.com/search/?term={}+{}'.format(key,jenis) headers = { 'user-agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0' } req = requests.get(url, headers=headers) soup = BeautifulSoup (req.text, 'html.parser') sepatu = soup.find_all('div', 'element_1') for it in sepatu: harga = it.find('div','element').__str__ datas.append([harga]) hasil = ['Harga'] write = csv.writer(open('result/{}_{}.csv'.format(key,jenis), 'w', newline='')) write.writerow (hasil) for d in datas: write.writerow(d)  this is Output from this code     Column A     <bound method Tag.unicode of Rp 88.000 >   <bound method Tag.unicode of Rp 200.000 >    how to turn that output to this output     Column A     Rp 88.000   Rp 200.000     i was try harga = it.find('div','element').__str__ to harga = it.find('div','element').text but i got error AttributeError: 'NoneType' object has no attribute 'text' i try to learn web scraping python selenium but i got block by output into text and i expecting i want all the output into text

Answer: You can add .text in this line harga = soup.find("div", {"class": "db gM ei b hE be f16-360-o ff vb uT ellipsis-1"}).text  Then you will get an output like this     Nama Sepatu Harga     Sepatu A Rp.24.000
Question: I need to sort a list of strings, of the form: ["ccc_3.23", "b_0.00", "b_-1.10", "aa_-2.37", "aa_3.05", "aa_-2.11", "ccc_9.8"]  first by prefix, then by suffix, such that the sorted list is: ["aa_-2.37", "aa_-2.11", "aa_3.05", "b_-1.17", "b_0.00", "ccc_3.23", "ccc_9.8"]  The prefixes only contain standard english letters, and can be of any length. The suffixes, on the other hand, are always signed floats, with potentially varying numbers of digits. -1.3232, 0.0, and 7.98 are all valid suffixes. The list needs to be sorted without altering any of its elements in the process. I've tried a number of different approaches from accross the web, but none seem to cover every edge case here. Unfortunately, the list is formatted as-is, and I cannot do anything about it. Is there any way that I could go about doing this?

Answer: You need to use key in sort a = ["ccc_3.23", "b_0.00", "b_-1.10", "aa_-2.37", "aa_3.05", "aa_-2.11", "ccc_9.8"] a.sort(key=lambda x: (x.split("_")[0], float(x.split("_")[1]))) a # output : ['aa_-2.37', 'aa_-2.11', 'aa_3.05', 'b_-1.10', 'b_0.00', 'ccc_3.23', 'ccc_9.8']