question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
76,895,565 | 2023-8-13 | https://stackoverflow.com/questions/76895565/python-dunder-methods-wrapped-as-property | I stumbled upon this code that I found weird as it seems to violate the fact that python builtins call dunder methods directly from the class of the object. Using __call__ as an example, if we define class A as following: class A: @property def __call__(self): def inner(): return 'Called.' return inner a = A() a() # re... | Yes, but it respects the way to retrieve a method from a given function - We can see that the __get__ method is called: On the code bellow, I just replaced property with a simpler descriptor that will retrieve its "func" - and used it as the __call__ method. In [34]: class X: ...: def __init__(self, func): ...: self.f... | 6 | 2 |
76,895,027 | 2023-8-13 | https://stackoverflow.com/questions/76895027/pythonic-way-to-find-index-of-certain-char-in-a-circular-manner | Let's say I have a string like: 'abcdefgha' I'd like to find the index of the next character a after the index 2 (in a circular manner). Meaning it should find index 7 in this case (via mystr.index('a', 2)); however, in this case: 'abcdefgh' it should return index 0. Is there any such built-in function? | There isn't a builtin for this, but you can easily write a function: def index_circular(s: str, sub: str, n: int) -> int: try: # Search starting from n return s.index(sub, n) except ValueError: # Wrap around and search from the start, until n return s.index(sub, 0, n+len(sub)-1) In use: >>> n = 2 >>> c = 'a' >>> index... | 5 | 5 |
76,886,238 | 2023-8-11 | https://stackoverflow.com/questions/76886238/valueerror-when-using-custom-new-in-python-enum | I'm encountering an issue with the following Python code where a ValueError is raised when trying to create an instance of an Enum with a value that doesn't correspond to any defined enum member: from enum import Enum class Option(Enum): OPTION_1 = "Option 1" OPTION_2 = "Option 2" NONE = "" def __new__(cls, value): try... | The __new__ method is used during enum class creation; after that Enum.__new__ is swapped in, and it only does look-ups. To handle situations like these, use the _missing_ method: @classmethod def _missing_(cls, value): return cls.NONE Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and th... | 3 | 4 |
76,894,477 | 2023-8-13 | https://stackoverflow.com/questions/76894477/regular-expression-for-identical-characters-despite-line-breaks-and-spaces | How can I create a regular expression in python that matches consecutive identical characters, regardless of whether line breaks or spaces are in between? The number of identical characters should be adjustable. examples (e can be any character except newline or space): match: eee, e e e, e e e no match: ebe, e b e, e ... | You may use this regex: \A\s*(\S)(?:\s*\1\s*)+\Z RegEx Demo RegEx Details: \A: asserts position at start of the string \s*: Match 0 or more whitespaces (\S): Match any non-whitespace character and capture in group #1 (?:\s*\1\s*)+: Match same value we captured in group #1 surrounded with 0 or more whitespaces on eith... | 3 | 2 |
76,893,383 | 2023-8-13 | https://stackoverflow.com/questions/76893383/python-remove-part-of-a-string-based-on-non-case-sensitive-content | I'm learning python so I'm not an expert. I have a string like the following one (the line break is \n): test1 test2 othertext test3 test4 I would like to remove the othertext line but I can't figure out how to do it. I want this: test1 test2 test3 test4 Othertext is a text written by hand so I have to consider the p... | Case insensitivity doesn't ignore spaces. So you have to first remove the spaces yourself (with .replace(" ", "") then do the comparison. For comparison part, use .lower() to convert the text into its lowercase version. text = """test1 test2 otHeR teXT test3 test4""" def remove_line(text: str, word: str) -> str: return... | 2 | 2 |
76,893,273 | 2023-8-13 | https://stackoverflow.com/questions/76893273/shared-variable-between-parent-and-child-in-python | I have a global configuration pp that changes at runtime and needs it to be shared across all parent/child objects. class Config: pp = 'Init' def __init__(self): pass class Child(Config): def __init__(self, name): self.cc = name par = Config() print(f"Parent: {par.pp}") par.pp = "123" print(f"Parent: {par.pp}") child =... | In your example, the parent of Child is not par (which is an instance of Config, but it is the class Config. So you could change the value directly on the class, like that: class Config: pp = 'Init' def __init__(self): pass class Child(Config): def __init__(self, name): self.cc = name print(f"Parent: {Config.pp}") Conf... | 2 | 2 |
76,892,500 | 2023-8-13 | https://stackoverflow.com/questions/76892500/how-to-call-databricks-rest-api-to-list-jobs-run | I am currently developing a Python script to retrieve a comprehensive list of all the jobs that were executed yesterday. However, I'm encountering an issue with the script's pagination mechanism using tokens. Despite my attempts to loop through the pagination process, the resulting output remains unchanged. Here is the... | I noticed that the value of next_token wasn't changing in API response and then figured that you have a very small error in your code. The parameter to be passed in request is page_token and not next_page_token. As per documentation at https://docs.databricks.com/api/workspace/jobs/list, page_token string Use next_page... | 3 | 3 |
76,891,904 | 2023-8-13 | https://stackoverflow.com/questions/76891904/why-does-this-threadpoolexecutor-execute-futures-way-before-they-are-called | Why does this ThreadPoolExecutor execute futures way before they are called? import concurrent.futures import time def sleep_test(order_number): num_seconds = 0.5 print(f"Order {order_number} - Sleeping {num_seconds} seconds") time.sleep(num_seconds) print(f"Order {order_number} - Slept {num_seconds} seconds") if order... | Short Answer: It appears that ThreadPoolExecutor.shutdown has no mechanism to prevent this, based on the CPython implementation. It is difficult to completely avoid this, but if you have a list of futures, you can at least avoid having them executed out of order by canceling them manually in reverse order as below. for... | 4 | 2 |
76,891,209 | 2023-8-12 | https://stackoverflow.com/questions/76891209/how-do-i-create-a-new-dataframe-based-on-row-values-of-multiple-columns-in-pytho | I have multiple columns that contained only 0s or 1s. Apple Orange Pear 1 0 1 0 0 1 1 1 0 I would like to count and input the number of 0s (in "Wrong" column) and 1s (in "Correct" column) of each column in the new dataframe, and total them up into a table that looks like the following. Fruit Correct... | Try this: df.apply(pd.Series.value_counts).rename(index={0:'Wrong', 1:'Correct'}).T Use pd.DataFrame.apply to "apply" pd.Series.value_counts to each column of the dataframe, then rename the index values using a dictionary for 0 and 1 to Wrong and Correct. Lastly, use T to transpose the dataframe. Output: Wrong Correc... | 3 | 2 |
76,888,669 | 2023-8-12 | https://stackoverflow.com/questions/76888669/401-unauthorized-from-https-test-pypi-org-legacy | I am using this cmd on windows to upload my package in testpypi twine upload -r testpypi dist/* but it's showing this error. so how to upload in testpypi and pypi when 2FA is enable ? Uploading mypackage-0.1.0-py3-none-any.whl 100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.5/8.5 kB • 00:00 • ? WARNING Error during upl... | create API token from your pypi account then give username =__token__ and password=APITokenafter cmd twine upload -r testpypi dist/* or if you are using Twine to upload your projects to PyPI, set up your $HOME/.pypirc file like this: [testpypi] username = __token__ password = API Token | 3 | 4 |
76,886,126 | 2023-8-11 | https://stackoverflow.com/questions/76886126/how-to-create-a-gantt-chart-in-python-with-plotly-including-tasks-of-a-duratio | I am trying to create a Gantt chart in Python. Some of the tasks that I have to include in the chart have a duration of 0 days, meaning they have to be completed on the same day. I've tried this code which I've found online that creates a basic Gantt chart with plotly: df = pd.DataFrame([ dict(Task="1", Start='2023-03-... | The example below provides similar functionality using matplotlib. It is adapted from the similar case at https://stackoverflow.com/a/76836805/21896093 . When there's a task that has a duration of 0 days, a small duration is assigned (0.1 days) so that it shows up. You can adjust it as desired. Output: import pandas a... | 3 | 4 |
76,887,365 | 2023-8-12 | https://stackoverflow.com/questions/76887365/how-to-modify-a-behavior-of-pathlib-path | I want pathlib.Path to automatically output logs for some destructive commands such as path.rename(new_path). I made a subclass of pathlib.Path with logging functions, and replaced from pathlib import Path to from mylib import MyPath as Path. But it does not affect to the existing subclasses of pathlib.Path such as pat... | Just do some monkeypatching: from pathlib import Path Path.oldrename = Path.rename def rename(self,b): print("Inside my rename") self.oldrename(b) Path.rename = rename p = Path('./x.c') p.rename('y.c') | 2 | 3 |
76,887,165 | 2023-8-11 | https://stackoverflow.com/questions/76887165/elementwise-multiplication-of-dataframes-in-python | I have a dataframe which represents features of a linear regression model. df1 = pd.DataFrame({'yyyyww': ['2022-01','2022-02','2022-03', '2022-04','2022-05','2022-06','2022-07','2022-08','2022-09','2022-10'], 'feature1': [1000,2000,4000,3000,5000,2000,8000,2000,4000,3000], 'feature2': [9000,7000,3000,1000,2000,3000,600... | Try this using pandas intrinsic data alignment tenet: df1.set_index('yyyyww').mul(df2.set_index('feature')['coefficient']) Output: feature1 feature2 feature3 yyyyww 2022-01 -1000.0 18000.0 1500.0 2022-02 -2000.0 14000.0 500.0 2022-03 -4000.0 6000.0 1000.0 2022-04 -3000.0 2000.0 2500.0 2022-05 -5000.0 4000.0 4500.0 20... | 3 | 3 |
76,871,981 | 2023-8-10 | https://stackoverflow.com/questions/76871981/trying-to-get-the-5-most-collinear-points-out-of-multiple-points-gives-wrong-res | Let's say I have a list of 15 different points with x and y coordinates. How can I find the 5 most collinear points? They don't need to be perfectly collinear but they should reliably be the most collinear points of all possible combinations. My current approach: Get all possible combinations using itertools.combinati... | A simple algorithm is to find the two extreme points of the set (find the average M, then the point A most distant from M and then the point B most distant from A). Then as score use the sum of squared distances from the line passing through A and B. In code: # gg is the candidate group avg = ((sum(x for x, y in gg)/5)... | 3 | 2 |
76,885,853 | 2023-8-11 | https://stackoverflow.com/questions/76885853/apply-a-function-over-last-two-dimensions | How can I apply a function over last two dimensions? E.g. I generated an array below of (2,3,3) dimensions, the resulting array should have the same dimenstions where the function is apply to a[0,:,:] and a[1,:,:]. I understand I can go with a for loop, but might there be an in-built function specially for these type o... | Assuming a 3D array, you can directly map your function on the array, this will loop over the first dimension and apply the function on the remaining dimensions: out = np.array(list(map(np.linalg.pinv, a))) NB. this is not vectorized. Output: array([[[-5.55555556e-01, -1.66666667e-01, 2.22222222e-01], [-5.55555556e-02... | 2 | 2 |
76,885,758 | 2023-8-11 | https://stackoverflow.com/questions/76885758/only-update-readme-for-a-package-on-pypi | I published a package on PyPI and then realised I should change a few details in the attached README.md. Is it possible to change the readme without uploading a new version of the whole package? And if not, what is the most correct way to update the README on PyPI? I am using poetry to manage the package, and when I ch... | Unfortunately, no it isn't, because when you go to publish, the versions are immutable. This is by design. My suggestion would be to increment a minor version z on x.y.z in order to publish the latest version with updates to the README. So something like: 0.0.9 -> 0.0.10 or 2.1.0 -> 2.1.1 | 2 | 4 |
76,885,099 | 2023-8-11 | https://stackoverflow.com/questions/76885099/should-dataclass-use-fields-for-attributes-with-only-defaults | When a python dataclass has a simple attribute that only needs a default value, it can be defined either of these ways. from dataclasses import dataclass, field @dataclass class ExampleClass: x: int = 5 @dataclass class AnotherClass: x: int = field(default=5) I don't see any advantage of one or the other in terms of f... | No, if all you need is a field with a default value and no other special behavior, assigning the value directly to the class variable is equivalent to a field with only a default parameter. x: int = field(default=5) x: int = 5 In fact, Python goes way out of its way to make sure the two behave equivalently. From PEP 5... | 3 | 3 |
76,878,564 | 2023-8-10 | https://stackoverflow.com/questions/76878564/is-there-a-way-to-multithread-or-batch-rest-api-calls-in-python | I've got a very long list of keys, and I am calling a REST API with each key to GET some metadata about it. The API can only accept one key at a time, but I wondered if there was a way I could batch or multi-thread the calls from my side? | The other reply to this looks like ChatGPT so it should be ignored. I did, however, use its code as a base to write a function that does what I want. import requests from concurrent.futures import ThreadPoolExecutor API_ENDPOINT = 'https://api.example.com/metadata' def get_metadata_for_key(key): url = f"{API_ENDPOINT}/... | 3 | 3 |
76,882,047 | 2023-8-11 | https://stackoverflow.com/questions/76882047/drop-duplicates-in-a-dataframe-and-keep-the-one-with-a-specific-column-value | I am having a dataframe df: columnA columnB columnC columnD columnE A B 10 C C A B 10 D A B C 20 A A B A 20 D A B A 20 D C I want to drop the duplicates if there are duplicates entries for columnA, columnB, columnC in my case the duplicates are: columnA columnB columnC columnD columnE A B 10 C C A B 10 D A B A 20 D A ... | You can use DataFrame.sort_values for prefer C values first with DataFrame.drop_duplicates and or original order add DataFrame.sort_index: out = (df.sort_values('columnE', key=lambda x: x.ne('C')) .drop_duplicates(['columnA','columnB','columnC']) .sort_index()) print (out) columnA columnB columnC columnD columnE 0 A B ... | 3 | 3 |
76,879,923 | 2023-8-10 | https://stackoverflow.com/questions/76879923/why-is-name-startswitha-returning-true-on-the-name-barry | I am trying to learn how to use the .startswith() method and also the filter() function. For some reason I am not getting the result I expected. I don't know if I am misunderstanding 'startswith' or 'filter'. here is the code i used names = ['aaron','anthony','tom','henry','barry'] def start_a(names): for name in names... | start_a() is looping over the characters in the name, because it just receives one list element as its parameter. So it's actually checking whether the name contains a, not whether it starts with a. filter() does the looping over the list for you, you don't need another loop in the function. def start_a(name): return n... | 2 | 3 |
76,879,889 | 2023-8-10 | https://stackoverflow.com/questions/76879889/conda-package-not-found-how-to-install-conda-packages-on-apple-m1-m2-chips-whi | Let's say I want to install pybox2d (but this applies to other packages as well), and I can see on the Anaconda website that this package obviously exists, but it cannot be found when trying to install it on my new Macbook (one of the ones with the new Apple M1 or M2 CPUs). What should I do? conda search pybox2d -c con... | If you look at the linked webpage above (at the time of writing), you can see that osx-arm64 is not listed under the "Installers". However, in the output above we can see that we are only searching in osx-arm64, and not in osx-64. The explanation for this is that this package is not built for our new Apple architecture... | 3 | 7 |
76,877,041 | 2023-8-10 | https://stackoverflow.com/questions/76877041/how-does-python3-11s-strenums-mro-work-differently-for-str-and-repr | Python3.11 introduced StrEnum and IntEnum which inherit str or int respectively, and also inherit ReprEnum, which in turn inherits Enum. ReprEnum's implementation is actually empty. >>> print(inspect.getsource(ReprEnum)) class ReprEnum(Enum): """ Only changes the repr(), leaving str() and format() to the mixed-in type.... | The __repr__ method comes the normal way, inherited from Enum (via StrEnum) >>> Strings.__repr__ is StrEnum.__repr__ is Enum.__repr__ True For the __str__ method, the metaclass EnumType checks for the presence of ReprEnum and "hoists up" the str and format handling of the mixed-in data type into the class namespace at... | 5 | 4 |
76,876,323 | 2023-8-10 | https://stackoverflow.com/questions/76876323/can-regex-identify-characters-interspersed-with-a-limit | I am new to using regex but I feel my pattern may be too complex. I am looking for a pattern of a minimum number of brackets with a maximum number of dots interspersed. I can't see a way for regex to count the numbers of dots in the overall pattern instead of sequentially. For example: ...((((((((.(((..((..((((.(((((((... | I think you can use a combination of regex and string manipulation in python like this for example : import re #sample data text = "...((((((((.(((..((..((((.(((((((.(..(((((.(((.(((...))).))).)))))..)..))))))).))))..))..))).))))))))(((.((.(((((...((........))))))))))))............" #to match everything between the out... | 2 | 1 |
76,872,744 | 2023-8-10 | https://stackoverflow.com/questions/76872744/connect-to-gmail-using-email-address-and-password-with-python | I am trying to connect to my Gmail account using Python. I want to connect to it using both SMTP and IMAP. I am aware that it is possible to use an app password to make this connection, but is there a way to use the actual email password instead? I have been reading this particular article, https://support.google.com/... | I am aware that it is possible to use an app password to make this connection, but is there a way to use the actual email password instead? No there is not, you need to do one of two things. enable 2fa on the account and create an apps password Use Xoauth2 and request authorization of the user to access their accoun... | 3 | 2 |
76,871,473 | 2023-8-9 | https://stackoverflow.com/questions/76871473/transposing-each-row-data-to-column-for-each-id-in-dataframe | My Dataframe looks like this. id age Gender snapshot_1 performance_13 snapshot_5 performance_17 snapshot_7 performance_19 1 34 M 80 30 40 30 2 42 F 65 55 60 15 25 45 ALL Id's data need to be grouped for snapshot/performance with ID repetition like below. For Snapshot and its corresponding performance wi... | Using a MultiIndex to reshape, to handle an arbitrary number of categories: tmp = df.set_index(['id', 'age', 'Gender']) idx = (tmp.columns.to_series().str.split('_', n=1, expand=True) .assign(n=lambda x: x.groupby(0).cumcount()) ) out = (tmp .set_axis(pd.MultiIndex.from_frame(idx[[0, 'n']]), axis=1) .stack(dropna=Fals... | 3 | 2 |
76,867,554 | 2023-8-9 | https://stackoverflow.com/questions/76867554/fastapi-how-to-access-bearer-token | I'm using FastAPI to create a simple api for automating my emails. I want to protect certain routes and I'm using this class: import time import jwt from fastapi import HTTPException, Request from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer #if you need to try it out just swap the following from ex... | I was going to suggest returning the token within your auth function, but then I saw you figured it out. I'd also recommend using FastAPI-Another-JWT-Auth. It speeds things up, declutters everything, and has most of the functions you might need built in. It's a fork of the old main one which is deprecated and no longer... | 4 | 1 |
76,869,803 | 2023-8-9 | https://stackoverflow.com/questions/76869803/get-longest-distance-from-series-containing-comma-separated-strings-with-multipl | I'll preface by saying I have a solution, but it feels overly complicated and inefficient and I'm looking to improve on it. I have a series inside a dataframe that looks like: >>> df = pd.DataFrame({'Distance':[None,None,'13',None,'38.12','5NW','1N,3SW,8.3E',None,'2,7']}) >>> df Distance 0 None 1 None 2 13 3 None 4 38.... | Try: import re df = pd.DataFrame( {"Distance": [None, None, "13", None, "38.12", "5NW", "1N,3SW,8.3E", None, "2,7"]} ) pat = re.compile(r"^\d+\.?\d*") mask = df["Distance"].isna() x = ( df.loc[~mask, "Distance"] .apply( lambda x: sorted( x.split(","), key=lambda k: float(pat.search(k).group(0)), reverse=True, ), ) .to_... | 3 | 3 |
76,864,397 | 2023-8-9 | https://stackoverflow.com/questions/76864397/how-to-replicate-a-conda-environment | I have successfully installed some python code on a Win10 machine using Anaconda and conda environments and would like to install exactly the same environment on another computer, also Win10. This page indicates that you can save a file that contains the environment info on computer 1, then recall it on computer 2, us... | try using export -- Computer 1 - conda env export > spec-file.yml Computer 2 - conda env create -f spec-file.yml | 4 | 1 |
76,866,138 | 2023-8-9 | https://stackoverflow.com/questions/76866138/how-to-effectively-use-pandas-to-change-values-based-unique-identifier-and-one-c | I have the following data frame: identifier loan_identifier cashflow_date cashflow_type amount 0 1 a111 15/07/2023 funding -195.71 1 2 a111 01/07/2023 interest_repayment 3.11 2 3 a111 15/07/2023 interest_repayment 0.04 3 4 a111 20/07/2023 interest_repayment 0.04 4 5 a111 11/06/2023 principal_repayment 195.33 5 6 b222 ... | You can use boolean indexing: # ensure datetime df['cashflow_date'] = pd.to_datetime(df['cashflow_date'], dayfirst=True) # get rows with "funding" # NB. if more than one per ID, you need to drop duplicates m1 = df['cashflow_type'].eq('funding') # get reference date per ID ref = df['loan_identifier'].map(df.loc[m1].set_... | 2 | 4 |
76,817,818 | 2023-8-2 | https://stackoverflow.com/questions/76817818/how-can-i-perform-operations-between-a-list-and-scalar-column-in-polars | In python polars, I was wondering if it will be possible to use .eval() to perform an operation between an element and a column. For example, given the following dataframe: import polars as pl df = pl.DataFrame({"list": [[2, 2, 2], [3, 3, 3]], "scalar": [1, 2]}) Is it possible to subtract each element of the list colu... | I think that native functionality for this is on the roadmap (see this github issue https://github.com/pola-rs/polars/issues/8006) but you can do this as follows: df.with_row_index().pipe( lambda df: df.join( df.explode("list") .with_columns(sub=pl.col("list") - pl.col("scalar")) .group_by("index") .agg(pl.col("sub")),... | 5 | 3 |
76,835,610 | 2023-8-4 | https://stackoverflow.com/questions/76835610/tiktok-oauth-api-authorization-code-request-always-expired | I'm trying to use to oAuth of the TikTok API. From what I got from their website, you first need to send the user to a particular link, with your client_key and redirect_uri, then the user need to log in. After he's logged in, there will be a code in the return URL that you can use to get the access_token of the user. ... | As Michal pointed out, you need to decode the code you get before using it. Here is how you can do it (Edit of you manual_test() function) : def manual_test(): # Generate authorization URL print("Generating authorization URL...") url, state = generate_auth_url() print("URL:", url) print("State:", state) # Prompt user f... | 3 | 2 |
76,854,735 | 2023-8-7 | https://stackoverflow.com/questions/76854735/how-to-increase-row-output-limit-in-duckdb-in-python | I'm working with DuckDB in Python (in a Jupyter Notebook). How can I force DuckDB to print all rows in the output rather than truncating rows? I've already increased output limits in the Jupyter Notebook. This would be the equivalent of setting .maxrows in the CLI, but I can't find how to do this in Python. | You can use show: duckdb.sql("select * from range(100)").show(max_rows=100) | 3 | 5 |
76,861,309 | 2023-8-8 | https://stackoverflow.com/questions/76861309/find-number-of-months-between-today-and-a-dataframe-date-field-in-python-polars | I'd like to find the number of months between today and a date field in a python polars dataframe. How do you do that? (datetime.today() - pl.col('mydate')).dt.days() returns it only in days. | I figured out a way to do it using the pl.date_ranges() function. This mimics the Excel DATEDIF formula. Essentially, you are creating a list of unique months between the start date and the end dates, then calculating the length of the list to find the months. df.with_columns(diffInMonths=(pl.date_ranges(pl.col('Start ... | 2 | 2 |
76,855,616 | 2023-8-7 | https://stackoverflow.com/questions/76855616/how-can-i-get-hover-info-in-vs-code-for-google-sphinx-style-python-class-attribu | I'm trying to document instance variables in my Python classes so they show up in VS Code when I hover over them. I've found that this works: class TsCity: def __init__(self) -> None: self.name: str = "" """The city name.""" But this is pretty ugly. I would ideally like to use the Google-style docstring instead: self.... | This (#: lorem ipsum) is the Sphinx/Google style of attribute documentation (as opposed to the pep-0224 style (""" lorem ipsum """)) I asked the maintainers of the Python extension about whether there's an existing feature request issue ticket asking for Sphinx-style attribute documentation at https://github.com/micros... | 3 | 3 |
76,849,092 | 2023-8-7 | https://stackoverflow.com/questions/76849092/pyscript-always-download-pyodide-everytime-html-page-is-refreshed-leading-to-slo | I'm trying to run PyScript in a webpage, where I intended it to run and produce the output of a python code to a div element. I've succeeded in doing this. However I noticed it always produces the splashscreen "Downloading Pyodide Python Startup" every time I refreshed the webpage. It's taking significantly longer wait... | Sorry, Reza, but that's just the way it works. The whole environment has to be downloaded before any code runs. Pyscript Next (2023.11.1) may improve your situation, especially if you can use Micropython. Check out Jeff Glass's blog - https://jeff.glass/post/whats-new-pyscript-2023-11-1/. | 2 | 1 |
76,837,908 | 2023-8-4 | https://stackoverflow.com/questions/76837908/azure-function-v2-python-deployed-functions-are-not-showing | Locally the functions debug just fine, if I deploy via vscode to my azure function I get No HTTP Triggers found and the devops pipeline does not deploy triggers either. I have "AzureWebJobsFeatureFlags": "EnableWorkerIndexing" set locally and as a function app setting. Code is appropriately decorated @app.route(route="... | I tried to reproduce the same in my environment. I could see the deployed function in Azure function app. Created a test default Python v2 function and deployed to Azure function app. Local: Make sure you added the setting "AzureWebJobsFeatureFlags": "EnableWorkerIndexing" in local.settings.json: { "IsEncrypted": ... | 6 | 3 |
76,825,089 | 2023-8-3 | https://stackoverflow.com/questions/76825089/loss-increasing-to-extremely-high-numbers-during-training | I'm trying to fit my Tensorflow model on my Macbook Pro (M1). This model works completely fine on my other system, running Ubuntu on WSL2 with the same python version, where the loss steadily decreases to around 0.05, but somehow when I run it on my Mac, the loss numbers increase to ridiculously large numbers, at one p... | I have a similar issue on my Apple Silicon M2 Max. The Keras folks confirmed this is a problem. It will be fixed in TensorFlow 2.15 For now, you can use tf-nightly which doesn't have the same issue. pip install tf-nightly https://github.com/keras-team/keras/issues/18370 | 3 | 1 |
76,857,722 | 2023-8-8 | https://stackoverflow.com/questions/76857722/huggingface-sft-for-completion-only-not-working | I have a project where I am trying to finetune Llama-2-7b on a dataset for Parameter extraction, which is linked here: <GalaktischeGurke/parameter_extraction_1500_mail_contract_invoice>. The problem with the dataset is that the context for a response is very big, meaning that training on the entire dataset with context... | I have a similar issue. I think you're forgetting to add formatting_func function. Also, by default setting dataset_text_field overrides the use of the collator, so try without that argument. Here's how I call it. It runs and stores things to wandb, but my problem is my loss is always NaN. Lemme know if you found the i... | 3 | 1 |
76,824,794 | 2023-8-3 | https://stackoverflow.com/questions/76824794/how-can-i-get-an-arrow-to-center-align-with-text-in-matplotlib | I have a chart that I'm annotating some text and would like to draw an arrow to a point, however I cannot get the arrow to center align with the text. It always aligns to the left of the text. I came across this article which shows an arrow tail center aligned with the text and points to the area of concern. This is wh... | Set xycoords='data' and xytext=(0, y)* and both the horizontal & vertical alignment parameters to "center" for always text-centered [arrow] annotations *Where y corresponds to the apparent height¹ of the arrow. ¹ (In this example, measured in units of "offset points" - which will be dependent on the set DPI. [default... | 3 | 1 |
76,856,317 | 2023-8-8 | https://stackoverflow.com/questions/76856317/creating-an-iceberg-table-on-s3-using-pyiceberg-and-glue-catalog | I am attempting to create an Iceberg Table on S3 using the Glue Catalog and the PyIceberg library. My goal is to define a schema, partitioning specifications, and then create a table using PyIceberg. However, despite multiple attempts, I haven't been able to achieve this successfully and keep encountering an error rela... | I came across this post in LinkedIn that had an example of how to accomplish this - thanks dipankar mazumdar!!! Removed the boto3 library, instantiated the glue catalog with the proper syntax, and created a properly formed catalog.create_table command. Here is the adjusted working code: from pyiceberg.catalog import lo... | 6 | 4 |
76,853,836 | 2023-8-7 | https://stackoverflow.com/questions/76853836/match-a-row-with-the-rows-of-another-table-to-be-able-to-classify-the-row-in-dat | How can I Classify the values of the Clients table with the values of the rows of the Combinations table? I decide to create a combinations table to develop all combinations from main row (Clients Table). I am planning to check that the row of the customers coincides with a row of the combinations table to classify it ... | Idea I assume that "x" in the posted data example works like a boolean trigger. So why not to replace it with True and empty space with False? After that, we can apply logical operators directly to data. For example, what does it mean that the client's days do not fit in the "Sector B" pattern? Schematically it means a... | 4 | 0 |
76,862,713 | 2023-8-8 | https://stackoverflow.com/questions/76862713/sqlalchemy-2-0-orm-filter-show-wrong-type-in-pycharm | I'm using Pycharm to develop an app with SQLAlchemy 2.0. When I attempt to query some table using ORM approach. Pycharm always display type error in the filter query. For example, in the code snippet below: with Session(engine) as session: session.scalars(select(Albums.AlbumId).where(Albums.Id > user_last_sync_id)) ^^... | PyCharm assumes that expressions of the form a > b evaluate to bool when no other type information is available. Most likely, SQLAlchemy isn't providing rich enough type hints and/or stubfiles for PyCharm to correctly infer the type of that expression. To resolve that warning, you can inform PyCharm about the true type... | 7 | 17 |
76,860,320 | 2023-8-8 | https://stackoverflow.com/questions/76860320/plotting-a-pandas-dataframe-with-rgb-values-and-coordinates | I have a pandas DataFrame with the columns ["x", "y", "r", "g", "b"] where x and y denote the coordinates of a pixel and r, g, b denote its RGB value. The rows contain entries for each coordinate of a grid of pixels and are unique. How can I display this DataFrame using matplotlibs's imshow()? This requires reshaping t... | There exists an easy way to do this. First, you make sure the DataFrame is sorted by x- and y-values using df = df.sort_values(by=['x', 'y']). Next, you select only the three columns for r, g and b from the DataFrame by calling df[['r', 'g', 'b']]. You convert the values into a numpy array by calling df[['r', 'g', 'b']... | 2 | 6 |
76,860,119 | 2023-8-8 | https://stackoverflow.com/questions/76860119/append-first-item-to-end-of-iterable-in-python | I need to append the first item of a (general) iterable as the final item of that iterable (thus "closing the loop"). I've come up with the following: from collections.abc import Iterable from itertools import chain def close_loop(iterable: Iterable) -> Iterable: iterator = iter(iterable) first = next(iterator) return ... | Here is a version which doesn't use itertools def close_loop(iterable): iterator = iter(iterable) first = next(iterator) yield first yield from iterator yield first | 3 | 6 |
76,859,963 | 2023-8-8 | https://stackoverflow.com/questions/76859963/how-can-i-log-sql-queries-in-the-sqlmodel | How could I see/log queries sent by sqlmodel to database. | Since sqlmodel uses Sqlalchemy as backend ORM engine, we can use Sqlalchemy logging answer like answer here: import logging logging.basicConfig() logger = logging.getLogger('sqlalchemy.engine') logger.setLevel(logging.DEBUG) # run sqlmodel code after this You should be able to see sql queries in the console. | 2 | 4 |
76,858,406 | 2023-8-8 | https://stackoverflow.com/questions/76858406/relationship-between-python-asyncio-loop-and-executor | I generally understand the concept of async vs threads/processes, I am just a bit confused when I am reading about the event loop of asyncio. When you use asyncio.run() I presume it creates an event loop? Does this event loop use an executor? The link above says the event loop will use the default executor, which after... | When you use asyncio.run() I presume it creates an event loop? Yes, from https://docs.python.org/3/library/asyncio-runner.html#asyncio.run: This function always creates a new event loop and closes it at the end. Does this event loop use an executor? The event loop provides single-threaded concurrency for IO-boun... | 2 | 3 |
76,858,513 | 2023-8-8 | https://stackoverflow.com/questions/76858513/python-pytz-zoneinfo-and-daylight-savings-time | I am currently attempting to migrate a code base from using pytz to using Python's zoneinfo library. I've run into an issue with how zoneinfo handles daylight saving time transitions when compared to how pytz handles them. Suppose I have a naive datetime object: >>> import datetime >>> start = datetime.datetime(2021, 1... | In addition to @deceze's comment (CET specifies a UTC offset, not a time zone), note that timedelta arithmetic in Python is wall time arithmetic. from datetime import datetime, timedelta from zoneinfo import ZoneInfo eu_berlin_tz = ZoneInfo("Europe/Berlin") start = datetime(2021, 10, 30, 23, 0, tzinfo=eu_berlin_tz) dur... | 3 | 3 |
76,858,143 | 2023-8-8 | https://stackoverflow.com/questions/76858143/is-there-a-simple-way-to-extract-variable-values-given-a-formatted-f-string-and | Assume we have an f-string-style template: "{kid} ate {number} {fruit}" and a formatted version of that: "Jack ate 42 apples" How could I, very generally, extract "Jack", "42", and "apples" from this string based on the fact that they match kid, number, and fruit respectively? Assume that the f-string could be anything... | You can do this with regex and match group like this: To create a group with name: (?'name') Match any characters unlimited times: .+ import re pattern = r"(?P<name>.+) ate (?P<number>.+) (?P<fruit>.+)" text = "John ate 3 apples" match = re.match(pattern, text) if match: name = match.group('name') number = match.grou... | 2 | 2 |
76,858,073 | 2023-8-8 | https://stackoverflow.com/questions/76858073/printing-slowly-to-mimic-typing | I'm trying to make a text based game and I want the text to print out slowly to simulate typing. I also want it to be an input. Is it possible to do this? I saw someone else use this code(bolded is what i added): import sys,time def sinput(str): for c in str + '\n': sys.stdout.write(c) sys.stdout.flush() time.sleep(4./... | You can assign input() to slowtest. sinput() function is not returning anything. Once you print slowly you can use input() for slowtest variable then check the if condition. import sys,time def sinput(str): for c in str + '\n': sys.stdout.write(c) sys.stdout.flush() time.sleep(4./90) sinput('Does it work? ') slowtest =... | 3 | 3 |
76,855,796 | 2023-8-8 | https://stackoverflow.com/questions/76855796/how-can-i-slice-a-numpy-array-into-another-numpy-array-of-different-size | I'm trying to broadcast the contents of one array into another array like this: A = np.array([[1, 3], [2, 4]]) A_broadcast = np.array([[1, 0, 3, 0], [0, 2, 0, 4], [1, 2, 3, 4]]) My current approach is by initializing A_broadcast with np.zeros((3, 4)) and slicing the contents of A into A_broadcast one line at a time li... | Your 2 arrays: In [86]: A = np.array([[1, 3], [2, 4]]) ...: A_broadcast = np.array([[1, 0, 3, 0], [0, 2, 0, 4], [1, 2, 3, 4]]) In [88]: A Out[88]: array([[1, 3], [2, 4]]) In [89]: A_broadcast Out[89]: array([[1, 0, 3, 0], [0, 2, 0, 4], [1, 2, 3, 4]]) the blank: In [87]: res = np.zeros((3,4),int) The first row of A go... | 2 | 1 |
76,855,609 | 2023-8-7 | https://stackoverflow.com/questions/76855609/automatically-send-all-elements-in-list-inside-of-a-for-loop-list-comprehension | I access a function via this list comprehension and have made it work by explicitly creating a variable for each element of the list_of_lists. I want a better way to access the elements in the function in a list comprehension. Example: list_of_lists = [[0, 1, 2, 3], [0, 1, 2, 3], ...] [function(i, j, k, l) for i, j, k,... | You're looking for * to unpack the list https://peps.python.org/pep-3132/ [function(*sublist) for sublist in list_of_lists] >>> def foo(a, b, c, d): ... return a + b + c + d ... >>> lst = [1, 2, 3, 4] >>> foo(*lst) # iterable unpack 10 >>> d = {'a':1, 'b':2, 'c':3, 'd':4} >>> foo(**d) # dict unpack 10 | 2 | 4 |
76,849,633 | 2023-8-7 | https://stackoverflow.com/questions/76849633/selenium-4-11-2-with-chromedriver-and-chrome | I'm trying to run this simple code.. But I get a error that I can not fix. Can someone help me ? Chrome driver is installed I check: pi@Rpi:~ $ chromedriver --version ChromeDriver 92.0.4515.98 (564abd8de2c05f45308eec14f9110a10aff40ad9-refs/branch-heads/4515@{#1501}) Code: from selenium import webdriver driver=webdrive... | I put the Chromedriver in the Same directory as the Python project As you are using Selenium v4.11.2 you don't need to explicitly download ChromeDriver, GeckoDriver or any browser drivers or even need use webdriver_manager any more. You just need to ensure that the desired browser client i.e. google-chrome, firefox... | 3 | 1 |
76,853,872 | 2023-8-7 | https://stackoverflow.com/questions/76853872/slicestart-stop-none-vs-slicestart-stop-1 | I was surprised to read here that The start and step arguments default to None since it also says: slice(start, stop, step=1) Return a slice object representing the set of indices specified by range(start, stop, step). So I expected the default argument value for the step parameter to be 1. I know that slice(a, b,... | Slice's step indeed defaults to None, but using step 1 and None should be equivalent for all practical purposes. That's because in the C code where the step is actually used, there are checks which transform None into 1 anyway: int PySlice_GetIndices(PyObject *_r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop,... | 10 | 7 |
76,851,676 | 2023-8-7 | https://stackoverflow.com/questions/76851676/using-the-same-template-recursively-in-jinja2 | Suppose I have a tree-like data structure in Python: class Node: def __init__(self, name: str, neighbors: Optional[Iterable[Node]] = None) -> None: self.name = name self.neghbors = neighbors or [] grand_child1 = Node("grand_child1") grand_child2 = Node("grand_child1") child = Node("child", [grand_child1, grand_child2])... | Turns out you can define macros in jinja which work like functions. Something like this will do the trick: {% macro make_ul(roots) -%} <ul> {% for root in roots %} <li>{{ root.name }}</li> {{ make_ul(root.neighbors) }} {% endfor %} </ul> {%- endmacro %} {{ make_ul(roots) }} This way the macro will call itself recursiv... | 3 | 3 |
76,835,264 | 2023-8-4 | https://stackoverflow.com/questions/76835264/memory-leak-in-multithreaded-python-project | I have a small project of mine (please keep in mind that I'm just a python beginner). This project consists of few smaller .py files. First there is main.py that looks like this: from Controller import Controller import config as cfg if __name__ == "__main__": for path in cfg.paths.values(): if not os.path.exists(path)... | It's not clear to me where the memory leak is occurring. If it's in "some_faulty_unix_program" being run in AM.test_func, then you would need to find or create a replacement for it. But I believe there are some simplifications/optimizations that could be made to the code to reduce the likelihood of a memory leak if it ... | 5 | 1 |
76,846,418 | 2023-8-6 | https://stackoverflow.com/questions/76846418/twitter-x-login-using-selenium-triggers-anti-bot-detection | I am currently working on automating the login process for my Twitter account using Python and Selenium. However, I'm facing an issue where Twitter's anti-bot measures seem to detect the automation and immediately redirect me to the homepage when clicking the next button. I have attempted to use send_keys and ActionCh... | You may try this to log in to Twitter: import time from selenium import webdriver from selenium.webdriver import ChromeOptions, Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait options = ChromeOpti... | 2 | 3 |
76,845,743 | 2023-8-6 | https://stackoverflow.com/questions/76845743/numpy-polynomial-fit-returns-unrealistic-values | I would like to fit a polynomial to a series of x/y-datapoints and evaluate it at arbitrary x-values. I am using the new numpy polynomial API: import matplotlib.pyplot as plt import numpy as np x = [50.0, 150.0, 250.0, 400.0, 600.0, 850.0, 1000.0] y = [3.2, 10.1, 16.3, 43.7, 69.1, 45.2, 10.8] mypol = np.polynomial.poly... | Numpy's polyval should be evaluated at the x-points, not the y-points. On top of that, the coefficients should be given in order of highest to lowest degree. That said, mypol.coef does not necessarily return the expanded polynomial coefficients, so mypol.coef may be useless for np.polyval. Instead, the numpy.polynomial... | 2 | 2 |
76,847,159 | 2023-8-6 | https://stackoverflow.com/questions/76847159/is-it-possible-to-open-browser-with-webbrowser-open-and-somehow-take-over-by-sel | I'm wondering if it's possible to use webbrowser.open() method, open the browser, get its handler (?), and use it in driver = webdriver.Chrome() command somehow (webdriver is from selenium)? Is it feasible at all? I'm using Python. | No, webbrowser.open() is from another package unrealted to Selenium. To interact with Selenium you have to use a Selenium driven WebDriver initiated Browsing Context. | 2 | 3 |
76,822,673 | 2023-8-2 | https://stackoverflow.com/questions/76822673/langchain-querying-a-document-and-getting-structured-output-using-pydantic-with | I am trying to get a LangChain application to query a document that contains different types of information. To facilitate my application, I want to get a response in a specific format, so I am using Pydantic to structure the data as I need, but I am running into an issue. Sometimes ChatGPT doesn't respect the format f... | I managed to solve my issue and here is what I did to solve them. try/except block First, I added a try/except block around the chain execution code to catch those naughty errors without stopping my execution. Cleaning vectorstore I also noticed that the vectorstore variable was not getting "cleaned" on each run I woul... | 4 | 1 |
76,845,690 | 2023-8-6 | https://stackoverflow.com/questions/76845690/how-to-expand-columns-from-web-scraping | I am trying to web scrape a site with tis code: import requests import pandas as pd import numpy as np from bs4 import BeautifulSoup import json import numpy as np url = 'https://www.quantalys.com/Categories' soup = BeautifulSoup(requests.get(url).content, "html.parser") data = soup.select_one("#DataCatsWithPerfs")["va... | import requests import pandas as pd from bs4 import BeautifulSoup import json url = 'https://www.quantalys.com/Categories' soup = BeautifulSoup(requests.get(url).content, "html.parser") data = soup.select_one("#DataCatsWithPerfs")["value"] data = json.loads(data) df = pd.DataFrame(data) for index, row in df.iterrows():... | 3 | 2 |
76,843,614 | 2023-8-5 | https://stackoverflow.com/questions/76843614/python-move-parts-of-rows-to-previous-row-based-on-matching-rows-from-another-da | I have two data frames df1: Name Month Amount Status 0 Bill Apr 0 1 Bill May 0 2 Bill Jun 100 member 3 Sally Apr 0 4 Sally May 0 5 Sally Jun 200 member 6 Tom Apr 0 7 Tom May 300 member 8 Tom Jun 0 and df2: Name Month 0 Bill Jun 1 Tom May I am looking to update df1 whenever there is a match in df2 on Name and Month ... | Try: # merge to find rows with Name, Month in df2 exist = df1[['Name','Month']].merge(df2.assign(exist=1), how='left')['exist'].notna() # find the previous rows prev_rows = exist.groupby(df1['Name']).shift(-1, fill_value=False) # fill the previous rows df1.loc[prev_rows, ['Amount','Status']] = df1.loc[exist, ['Amount',... | 2 | 2 |
76,842,824 | 2023-8-5 | https://stackoverflow.com/questions/76842824/auxilary-space-complexity-across-iterations | Suppose we have the function below: def ReverseStr(s, k): """ s: list of characters (length n) k: integer """ for i in range(0, len(s), 2*k): s = s[:i] + s[i:i+k][::-1] + s[i+k:] return s In this function, each iteration involves creating four distinct sublists. First, we create a sub-list of length i. Then, we create... | each iteration involves creating four distinct sublists. In fact, there are also the lists that are created by executing the + operator (list concatenation) So, in total, we create sub-lists with a total space of i + k + k + n - (i + k) or, simplified, n + k. When determining auxiliary space complexity, it is commo... | 3 | 3 |
76,838,859 | 2023-8-4 | https://stackoverflow.com/questions/76838859/dataframe-column-with-quoted-csv-to-named-dataframe-columns | I am pulling some JSON formatted log data out of my SEIM and into a pandas dataframe. I am able to easily convert the JSON into multiple columns within the dataframe, but there is a "message" field in the JSON that contains a quoted CSV, like this. # dummy data dfMyData = pd.DataFrame({"_raw": [\ """{"timestamp":169109... | Update Actually all you need is to pass your data into a csv-reader, which in turn is an appropriate data type for pandas.DataFrame: pd.DataFrame(csv.reader(dfMyData['_raw.message'], quotechar="'"), columns=columns) Previous answer We can try to convert the data into a csv and read them back with appropriate paramete... | 3 | 1 |
76,825,015 | 2023-8-3 | https://stackoverflow.com/questions/76825015/cython-execution-speed-vs-msvc-and-gcc-versions | Intro I have a fairly simple Cython module - which I simplified even further for the specific tests I have carried on. This module has only one class, which has only one interesting method (named run): this method accepts as an input a Fortran-ordered 2D NumPy array and two 1D NumPy arrays, and does some very, very sim... | This is a partial answer providing the generated C code produced by Cython once it has been simplified a bit to be shorter, more human-readable and easy to compile without any Cython, Python, or NumPy dependencies (the transformations are not expected to drastically impact the timings). It also show the generated assem... | 4 | 2 |
76,837,612 | 2023-8-4 | https://stackoverflow.com/questions/76837612/good-way-to-view-matrices-and-higher-dimensional-arrays-in-vscode | When working with PyTorch/numpy and similar packages, is there a good way to view matrices (or, in general, arrays with two or more dimensions) in debug mode, similar to the way Matlab (or even pyCharm if I remember correctly) present it? This is, for example, a PyTorch tensor, which is very confusing -- opening H here... | Yes, make sure you have the Jupyter extension installed and then simply right click the variable in the Debug menu and select the View Value in Data Viewer option. | 6 | 3 |
76,816,186 | 2023-8-2 | https://stackoverflow.com/questions/76816186/interpreting-an-array-of-values-using-skfuzzy | I am using Skfuzzy to interpret two arrays: 1. distances to a stream [dist]; 2. Strahler order[order]. I then want to calculate the consequent (a vulnerability value) for each stream distance and Strahler order pairs using a set of custom membership values I have created for the antecedents and consequent. I have the p... | One can iterate down an array through the use of a for loop as shown below. First ensure that your array is converted to float type using 'numpy.asfarray'. # Convert to float array dist_x = np.asfarray(strm_dist) order_x = np.asfarray(strm_order) # iterate down an array of input values strm_vul = [] for i in range(len(... | 3 | 1 |
76,836,793 | 2023-8-4 | https://stackoverflow.com/questions/76836793/jupyter-notebook-cannot-import-pyldavis-sklearn | I am using Jupyter Notebook to run python code. I already did the following: !pip install pyldavis I can successfully import pyLDAvis via the following codes: import pyLDAvis pyLDAvis.enable_notebook() However, I cannot import pyLDAvis.sklearn via the following codes: import pyLDAvis.sklearn It returns: ModuleNotFo... | It looks like there has been a change in how the software handles this pattern. This issue posted here in May of this year (2023) that looks to be the same as yours. It links over to a solution that details how the use of the software has recently developed: "pyLDAvis v 3.4.0 no longer has the file sklearn.py in the p... | 5 | 7 |
76,836,454 | 2023-8-4 | https://stackoverflow.com/questions/76836454/avoid-for-loops-over-colum-values-in-a-pandas-dataframe-with-a-function | I have the following structur of a dataframe: df = pd.DataFrame({'Level': ["a","b", "c"], 'Kontogruppe': ["a", "a", "b"], 'model': ["alpha", "beta", "alpha"], 'MSE': [0, 1 ,1], 'actual_value': [1,2,3], 'forecast_value': [2,2,2]}) For this dataframe I run severel functions, for example: def metrics(df): df_map= pd.Data... | If I understand correctly, you might just want a simple groupby.sum with a bit of post-processing. Because you only care about the existing combinations, there is no need to loop over all of them and assign a large value. (df.groupby(['Level', 'Kontogruppe', 'model'], as_index=False) [['actual_value', 'forecast_value']... | 3 | 1 |
76,836,403 | 2023-8-4 | https://stackoverflow.com/questions/76836403/typeerror-when-using-super-in-a-dataclass-with-slots-true | I have a dataclass with (kind of) a getter method. This code works as expected: from dataclasses import dataclass @dataclass() class A: def get_data(self): # get some values from object's fields # do some calculations return "a calculated value" @dataclass() class B(A): def get_data(self): data = super().get_data() ret... | slots: If true (the default is False), __slots__ attribute will be generated and new class will be returned instead of the original one. If __slots__ is already defined in the class, then TypeError is raised. https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass Taking this as an example: @dataclas... | 9 | 2 |
76,832,124 | 2023-8-3 | https://stackoverflow.com/questions/76832124/where-was-python-installed | How can I find out where Python was installed in a Windows 11 machine, so that I can use the address to add Python to the PATH variable? The documentation I have found on this assumes that the user can already use the python command in the cli. But in this case, the cli cannot find python yet because python has not bee... | The default install location for user installations on Windows uses the LOCALAPPDATA variable. This typically points towards C:\users\<username>\Appdata\Local\Programs\Python\Python<XY>\ where <XY> are the major and minor versions. In your case this would be C:\users\Administrator\Appdata\Local\Programs\Python\Python31... | 5 | 4 |
76,833,042 | 2023-8-4 | https://stackoverflow.com/questions/76833042/how-to-get-a-list-of-all-the-methods-of-a-class-and-its-parameters | I have a requirement where i need to generate a list of all the methods and its parameters belonging to the Python class passed as argument. I want something like this class MyClass: def __init__(self,attr1): pass def method1(self,param1,param2): pass def method2(self,param3): pass def method3(self): pass def get_all_m... | You can use the .co_varnames attribute of the code object: def get_all_methods_details(class_name): return [ (m, getattr(class_name, m).__code__.co_varnames) for m in dir(class_name) if not m.startswith("__") ] This should return: [('method1', ('self', 'param1', 'param2')), ('method2', ('self', 'param3')), ('method3',... | 3 | 1 |
76,829,328 | 2023-8-3 | https://stackoverflow.com/questions/76829328/align-text-in-the-center-of-the-bounding-box | I'm trying to create some labels manually which should align exactly with the tick locations. However, when plotting text ha='center' aligns the bounding box of the text in the center, but the text itself within the bounding box is shifted to the left. How can I align the text itself in the center? I found this questio... | You can set the transform parameter of the text object with an actual matplotlib transform, e.g.: import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.transforms as transforms mpl.rcParams['figure.dpi'] = 300 # mpl.use("TkAgg") print(mpl.__version__) # 3.5.3 fig, ax = plt.subplots() dx, dy = 5.5 /... | 4 | 1 |
76,823,121 | 2023-8-2 | https://stackoverflow.com/questions/76823121/reduce-amount-of-silence-needed-for-pythons-speechrecognition-to-stop-capturing | I'm using Python's SpeechRecognition to geenerate captions for a livestream. I noticed that when I listen to mic input, recognizer would need a couple of seconds of silence in order to stop capturing audio. Is there a way to reduce that amount of silence needed to say .5 seconds? I'm open to using other methods/librari... | From the source code of the SpeechRecognition library, the parameter you need is pause_threshold, which is a parameter taken by the Recognizer object. self.pause_threshold = 0.8 # seconds of non-speaking audio before a phrase is considered complete In your code above, it would be passed like: recognizer = sr.Recognize... | 3 | 2 |
76,831,468 | 2023-8-3 | https://stackoverflow.com/questions/76831468/keep-items-with-same-keys-in-two-dictionary-and-discard-other-items | I am trying to remove all non-matching items (values with different keys) in two dicts dict_a and dict_b. What is a better way of achieving this? Example: dict_a = {key1: x1, key2: y1, key4: z1} dict_b = {key1: x2, key3: y2, key4: w1} # becomes: # dict_a = {key1: x1, key4: z1} # dict_b = {key1: x2, key4: w1} My attemp... | You can do: d1 = {"key1": "x1", "key2": "y1", "key4": "z1"} d2 = {"key1": "x2", "key3": "y2", "key4": "w1"} common_keys = d1.keys() & d2.keys() d1 = {k: d1[k] for k in common_keys} d2 = {k: d2[k] for k in common_keys} print(d1) print(d2) Prints: {'key1': 'x1', 'key4': 'z1'} {'key1': 'x2', 'key4': 'w1'} | 3 | 2 |
76,830,702 | 2023-8-3 | https://stackoverflow.com/questions/76830702/is-there-a-way-of-getting-the-inset-axes-by-asking-the-axes-it-is-embedded-in | I have several subplots, axs, some of them with embedded inset axes. I would like to get the data plotted in the insets by iterating over the main axes. Let's consider this minimal reproducible example: fig, axs = plt.subplots(1, 3) x = np.array([0,1,2]) for i, ax in enumerate(axs): if i != 1: ins = ax.inset_axes([.5,.... | You could use get_children and a filter to retrieve the insets: from matplotlib.axes import Axes def get_insets(ax): return [c for c in ax.get_children() if isinstance(c, Axes)] for ax in fig.axes: print(get_insets(ax)) Output: [<Axes:label='inset_axes'>] [] [<Axes:label='inset_axes'>] For your particular example: da... | 4 | 2 |
76,828,644 | 2023-8-3 | https://stackoverflow.com/questions/76828644/python-pandas-select-all-nan-row-and-fill-with-previous-row | I have a dataframe look like this, pd.DataFrame([list(range(8))+[np.nan]*2, [np.nan]*len(range(10)), range(10), [np.nan]*2+list(range(8)), range(10)]) Out[31]: 0 1 2 3 4 5 6 7 8 9 0 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 NaN NaN 1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 3 NaN NaN 0.0 ... | IIUC, you can do: mask = df.isna().all(axis=1) df.loc[mask, :] = df.loc[mask.shift(-1).fillna(False), :].values print(df) Prints: 0 1 2 3 4 5 6 7 8 9 0 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 NaN NaN 1 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 NaN NaN 2 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 3 NaN NaN 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 ... | 2 | 3 |
76,826,939 | 2023-8-3 | https://stackoverflow.com/questions/76826939/python-count-number-of-occurrences-based-on-other-columns-dictionary-words | Here is an example of my dataframe: text name1 name2 name3 count_name barbie and ken live in a house barbie ken sophie 2 bond is preparing a bond movie bond james NaN 2 homer likes donuts homer bart NaN 1 where does mary live peter NaN NaN 0 i am travelling with john john NaN NaN 1 barbie ken barbieken barbie ken NaN 2... | Using a regex: import re cols = ['name1', 'name2', 'name3'] # or # cols = list(df.filter(regex=r'name\d+')) pat = df[cols].stack().groupby(level=0).agg('|'.join) df['count_name'] = [len(re.findall(p, t)) for t, p in zip(df['text'], pat)] To account for full words only: df['count_name'] = [len(re.findall(fr'\b(?:{p})\b... | 2 | 2 |
76,818,020 | 2023-8-2 | https://stackoverflow.com/questions/76818020/select-specific-range-of-elements-from-a-python-dictionary-based-on-condition | I have the following dictionary: ip_dict = { "doc_1" : { "img_1" : ("FP","some long text"), "img_2" : ("LP", "another long text"), "img_3" : ("Others", "long text"), "img_4" : ("Others", "some loong text"), "img_5" : ("FP", "one more text"), "img_6" : ("FP", "another one"), "img_7" : ("LP", "ANOTHER ONE"), "img_8" : ("... | With extended sequential logic: def select_page_ranges(d: dict): def _del_excess_items(): # if previous block was not closed and has excess entries if start and last_mark != 'FP': res[pk][-1] = {start_key: res[pk][-1][start_key]} res = {} for pk, v in ip_dict.items(): res[pk] = [] start, start_key, last_mark = None, No... | 2 | 3 |
76,820,218 | 2023-8-2 | https://stackoverflow.com/questions/76820218/finding-matching-elements-in-arrays-of-different-lengths | I have 2 arrays of different lengths. For each element in array_1, I want to find the position of the matching element in array_2. This includes duplicates in array_1. For example: array_1 = np.array([555, 641, 1000, 641, 4, 641]) array_2 = np.array([4, 555, 641, 1000]) The desired output would be: out = [1,2,3,2,0,2]... | Assuming that all unique items are present in both arrays. if array_2 is sorted, then it's not even needed to use it, numpy.unique is sufficient. out = np.unique(array_1, return_inverse=True)[1] Output: array([1, 2, 3, 2, 0, 2]) If array_2 is not sorted, then one needs a bit of post-processing with numpy.argsort: # le... | 4 | 2 |
76,821,158 | 2023-8-2 | https://stackoverflow.com/questions/76821158/specify-that-a-typevar-supports-the-operator-among-its-values | Basically, I want to say that I have a type T which has a T.__sub__(self, other: T) -> T defined. I can currently make it typecheck as if it has a T.__sub__(self, other: Any) -> Any defined, but only works if T is a class I defined myself. I'm trying to type the following class from typing import TypeVar, Generic from... | Check out typing.Self. That way you can specify that the value being subtracted must be the same type as self. from typing import Protocol, TypeVar, Self, Generic from dataclasses import dataclass E = TypeVar('E') class SupportsSub(Protocol): @abstractmethod def __sub__(self, other: Self) -> Self: pass T = TypeVar('T'... | 3 | 2 |
76,817,600 | 2023-8-2 | https://stackoverflow.com/questions/76817600/effective-way-to-add-time-dimension-to-two-dimensional-x-y-netcdf-file-whi | I had CSV file with x and y coordinates, as well as variable values for three different time steps as follows: x, y, var_t1, var_t2, var_t3, 1, 1, 8, 8, 6 1, 2, 6, 1, 2 2, 1, 5, 3, 7 2, 2, 7, 2, 6 I have learned to create a NetCDF file with the following method: import xarray as xr xr.Dataset.from_dataframe(df.set_ind... | Say you have the dataframe df: >> df x y var_t1 var_t2 var_t3 0 1 1 8 8 6 1 1 2 6 1 2 2 2 1 5 3 7 3 2 2 7 2 6 You can set x,y as an index, convert it to xarray, merge the variables var_t1... to a new dimension and set new_times as the coordinates of the time dimension: >> ds = df.set_index(["x", "y"]).to_xarray() >> d... | 3 | 2 |
76,817,633 | 2023-8-2 | https://stackoverflow.com/questions/76817633/python-pandas-np-where-value-from-another-column | I am trying to apply different value to a df from another column using: df['url']= np.where(df['client'] == 'xyz', "/s?k={query}&s=relevanceblender&page=%s".format(query=df['keyword']), "other") however query is replaced by all values of df['keyword'], not only the row in question. thanks for your help. | Assuming this input: df = pd.DataFrame({'client': ['abc', 'abc', 'xyz', 'xyz'], 'keyword': ['kw1', 'kw2', 'kw3', 'kw4'] }) You could use: df['url'] = np.where(df['client'] == 'xyz', df['keyword'].apply("/s?k={}&s=relevanceblender&page=%s".format), 'other') Notice how {query} was changed to {}. Or, if you cannot chang... | 2 | 2 |
76,817,132 | 2023-8-2 | https://stackoverflow.com/questions/76817132/what-does-mean-parameter-offset-in-function-get-inline-bot-results | I cannot understand what parameter offset did in this function and what's kind of values accept? I try use integers but there is no effect. from pyrogram import Client, filters import time app = Client( "my_account", api_id=api_id, api_hash=api_hash, ) async def main(): async with app: bot_results = await app.get_inlin... | The documentation states: offset (str, optional) – Offset of the results to be returned. Which is not super helpful but from the Telegram Docs shows that it is used for pagination: offset - If the user scrolls past the first len(results) results, and next_offset field is set, the inline query should be repeated with... | 3 | 1 |
76,796,808 | 2023-7-30 | https://stackoverflow.com/questions/76796808/what-is-support-in-classification-report-within-sklearn | I have been wrote a code and the result was a report which you can seen blow. the code is about the number of people who survived or died in titanic. my question is what is "Support" in this report? precision recall f1-score support 0 0.78 0.87 0.82 154 1 0.79 0.67 0.72 114 accuracy 0.78 268 macro avg 0.79 0.77 0.77 2... | support is how many samples are in each class. In your case, 154 samples are in class 0, and 114 samples are in class 1. The total number of samples is 268. It uses the ground truth labels, which represent the actual class of each sample. You might be interested in seeing how these values can be manually calculated - s... | 4 | 6 |
76,788,727 | 2023-7-28 | https://stackoverflow.com/questions/76788727/how-can-i-change-the-debug-level-and-format-for-the-quart-i-e-hypercorn-logge | I'm trying to set the level and format for the loggers used by the Quart module the way I did it successfully for other 'foreign' loggers: by running basicConfig and implicitly setting up the root-logger or later by running logging.getLogger("urllib3.connectionpool").setLevel(logging.INFO) to get and modify an existin... | I had the same issue recently, and it was a real headache to find how to solve it, but here is my solution: First, for clarity, I defined a function that takes a logger as an input and that patches the logger how I want it. import logging def patch_logger(logger_: logging.Logger): logger_.handlers = [] # Clear any exis... | 5 | 2 |
76,807,787 | 2023-8-1 | https://stackoverflow.com/questions/76807787/python-polars-how-to-build-a-supersession-conversion-table | The scenario is as follow: At my store I sell items that can be replaced by other items (i.e. have supersession). For example, until a certain date I may had for sale the item 'A' which was eventually replaced by a new item 'B'. These supersessions can happen successively. This means that 'A' can be replaced by 'B', ... | This is more of a directed acyclic graph problem than Polars natively. Your old_code and new_code lists effectively define the edges between the vertices of such a graph: old_codes = ['A', 'B', 'C', 'K'] new_codes = ['B', 'C', 'D', 'C'] edges = {e1 : e2 for e1,e2 in zip(old_codes, new_codes)} From here, since every ve... | 2 | 3 |
76,781,053 | 2023-7-27 | https://stackoverflow.com/questions/76781053/fastapi-generates-incorrect-openapi-3-0-1-specification | I am currently designing a REST API with FastAPI and using the generated openapi.json specification to generate a client. The client generator I am currently trying to use is limited to OpenAPI 3.0.x. The generator is complaining about "null" being generated as a possible type for a parameter, which makes sense as that... | Looks like they don't support it in the code base as described here The version string of OpenAPI. FastAPI will generate OpenAPI version 3.1.0, and will output that as the OpenAPI version. But some tools, even though they might be compatible with OpenAPI 3.1.0, might not recognize it as a valid. So you could override ... | 9 | 4 |
76,783,239 | 2023-7-27 | https://stackoverflow.com/questions/76783239/is-it-safe-to-use-python-str-format-method-with-user-submitted-templates-in-serv | I am working on project where users must be able to submit templates containing placeholders to be later rendered to generate dynamic content. For example, a user might submit a template like: "${item.price} - {item.description} / {item.release_date}" that would be after formatted with the real values. Using a template... | No, it is not safe in general to use str.format with user-provided format strings. Format strings are capable to executing a limited form of Python code. This limited code is just powerful enough to pose significant denial of service (DOS) and data breach risks. The main factors that make using untrusted format strings... | 2 | 4 |
76,771,858 | 2023-7-26 | https://stackoverflow.com/questions/76771858/ruff-does-not-autofix-line-too-long-violation | I have a python project and I am configuring latest version of ruff for that project for linting and formating purpose. I have the below settings in my pyproject.toml file: [tool.ruff] select = ["E", "F", "W", "Q", "I"] ignore = ["E203"] # Allow autofix for all enabled rules (when `--fix`) is provided. fixable = ["ALL"... | It seems like Ruff has released Ruff Python Formatter as part of v0.0.289 and is currently in alpha state - https://github.com/astral-sh/ruff/blob/main/crates/ruff_python_formatter/README.md We are currently using v0.0.280 which does not have this feature so we used a combination of Black and Ruff as per our project re... | 16 | 1 |
76,789,641 | 2023-7-28 | https://stackoverflow.com/questions/76789641/dash-multi-page-app-using-dbc-navigation-bar | I'm trying to replicate "multi_page_example1" from https://github.com/AnnMarieW/dash-multi-page-app-demos/tree/main. This uses a drop-down menu to navigate to different pages. However, I want to adjust the navbar options to be the standard links as in the first example here: https://dash-bootstrap-components.opensource... | Here's a simple single app.py file example demonstrating a multi-page Dash web app For example, using the code you provide and combining it into a single file: Note: You can of course extend this approach with >1 files, as you wish, so long as ensuring correct modularization & importing (e.g., of the dash.Dash app ob... | 2 | 3 |
76,777,287 | 2023-7-27 | https://stackoverflow.com/questions/76777287/how-to-provide-two-different-ways-to-instantiate | Let's say I have a class AmbiguousClass which has two attributes, a and b (let's say they are both int, but it could be more general). They are related by some invertible equation, so that I can calculate a from b and reciprocally. I want to give the user the possibility to instantiate an AmbiguousClass by providing ei... | I would enforce using custom constructors that only take a single parameter and clearly indicate which parameter is provided, thus avoiding ambiguity. class AmbiguousClass: def __init__(self, a, b, _is_from_cls=False): if not _is_from_cls: raise TypeError( "Cannot instantiate AmbiguousClass directly." " Use classmethod... | 2 | 4 |
76,798,643 | 2023-7-30 | https://stackoverflow.com/questions/76798643/quantizing-normally-distributed-floats-in-python-and-numpy | Let the values in the array A be sampled from a Gaussian distribution. I want to replace every value in A with one of n_R "representatives" in R so that the total quantization error is minimized. Here is NumPy code that does linear quantization: n_A, n_R = 1_000_000, 256 mu, sig = 500, 250 A = np.random.normal(mu, sig,... | K-means K-means clustering might be better but seem to be too slow to be practical on large arrays. For the 1D clustering case, there are algorithms faster than K-means. See https://stats.stackexchange.com/questions/40454/determine-different-clusters-of-1d-data-from-database I picked one of those algorithms, Jenks Na... | 2 | 3 |
76,780,411 | 2023-7-27 | https://stackoverflow.com/questions/76780411/use-data-matrix-as-a-fiducial-to-obtain-angle-of-rotation | I have a bunch of images such as the one above. They each contain a data matrix, but do not guarantee that it is oriented to an axis. Nevertheless, I can read these matrices with libdmtx pretty reliably regardless of their rotation. However, I also need to rotate the image so that the label is oriented right-side-up. ... | Thank you to @flakes for the suggestion. Combining code from the PR and issue, I created the following solution: from pylibdmtx.pylibdmtx import _region, _decoder, _image, _pixel_data, _decoded_matrix_region from pylibdmtx.wrapper import c_ubyte_p, DmtxPackOrder, DmtxVector2, dmtxMatrix3VMultiplyBy, DmtxUndefined from ... | 4 | 3 |
76,796,990 | 2023-7-30 | https://stackoverflow.com/questions/76796990/module-not-found-error-in-virtual-environment | I'm a newbie with Python and been trying to install modules using pip unsuccessfully in my small project. Following advice online, I've created my own virtual environment and imported my first module cowsay fine. I can definitely see the module being installed in my project: BUT, when attempting to run the file in my ... | As far as the output of the command which python pip is python: aliased to /usr/bin/python3 /Users/sr/Sites/python-virtual-env/env/bin/pip we can say that you are running the python not from your environment. So it cannot see by default any package installed in this env. Remove the alias python (in bash, the command u... | 5 | 3 |
76,788,010 | 2023-7-28 | https://stackoverflow.com/questions/76788010/twitter-api-v2-follows-lookup | I am trying to retrieve a list of who a Twitter account follows using Python. After realizing that the free tier API access did not provide this endpoint I upgraded my developer account to the basic plan (for $100 a month) as it clearly states that once signed up, you can retrieve an accounts followers or following. I ... | My original post here provided the code (now removed) that I wrote for the question Tweepy get followers list on April 18, 2023. After your comment, I did some more research into the error message: tweepy.errors.Forbidden: 403 Forbidden When authenticating requests to the Twitter API v2 endpoints, you must use keys an... | 2 | 4 |
76,799,021 | 2023-7-30 | https://stackoverflow.com/questions/76799021/unable-to-use-py-binary-target-as-executable-in-a-custom-rule | I have a py_binary executable target, and want to use this from a custom rule. I am able to get this to work, but only by duplicating the dependencies of my py_binary target with my custom rule. Is there any way to avoid this duplication and automatically include the dependencies of the py_binary? I have simplified my ... | You need to correctly collect the runfiles of the _greet binary. Instead of just using the _greet binary itself, try the following to include its dependencies (and data dependencies) aswell: DefaultInfo( executable = shell_script, runfiles = ctx._greet[DefaultInfo].default_runfiles ) See also: https://bazel.build/exte... | 2 | 4 |
76,774,415 | 2023-7-26 | https://stackoverflow.com/questions/76774415/vectorized-sum-and-product-with-list-of-pandas-data-frames | I have a list of Data Frames, each corresponding to a different time period t from 0 to N. Each data frame has multiple types, I need to preform the calculation below for each type in the data frame. An example data set would be as follows, I made each df in the list the same values for simplicity but the calculation w... | Assuming I've understood your intent correctly, you could try something along these lines. sums = {} x_col_idx = df.columns.get_loc('x') for s, tdf in df.groupby('type'): sums[s] = np.dot(tdf['x'], tdf['y']) * np.prod(2 - tdf['x'].iloc[1:]) This gets the same results on your example and a few other examples I tried as... | 3 | 2 |
76,815,232 | 2023-8-1 | https://stackoverflow.com/questions/76815232/difference-between-pandas-na-and-nan-for-numeric-columns | I have a data frame column as float64 full of NaN values, If I cast it again to float64 they got substituted for <NA> values which are not the same. I know that the <NA> values are pd.NA, while NaN values are np.nan , so they are different things. So why casting an already float64 column to float64 changed NaN to <Na> ... | Yes, you are correct. float64 and Float64 are two different data types in pandas. The difference is that Float64 is an extension type that can hold missing values using a special sentinel, while float64 is a native numpy type that uses NaN to represent missing values. Under the hood, Float64 uses a numpy array with dt... | 2 | 4 |
76,814,661 | 2023-8-1 | https://stackoverflow.com/questions/76814661/how-do-i-import-a-module-within-the-same-directory-or-subdirectory | I have the following directory for a project: photo_analyzer/ │ ├── main.py # Main script to run the photo analyzer ├── gui/ # Directory for GUI-related files │ ├── __init__.py # Package initialization │ ├── app.py # Tkinter application class and main GUI logic │ ├── widgets.py # Custom Tkinter widgets (if needed) │ ├─... | It is a tricky one. Normally python imports from their sibling files or childs of sibling folders. Here if you want to import from a file that are from same parent then you have to use sys.path.append('.') Secondly it also depends on the terminal current working directory. If your current working directory is "photo_an... | 4 | 3 |
76,772,509 | 2023-7-26 | https://stackoverflow.com/questions/76772509/llama-2-7b-hf-repeats-context-of-question-directly-from-input-prompt-cuts-off-w | Context: I am trying to query Llama-2 7B, taken from HuggingFace (meta-llama/Llama-2-7b-hf). I give it a question and context (I would guess anywhere from 200-1000 tokens), and ask it to answer the question based on the context (context is retrieved from a vectorstore using similarity search). Here are my two problems:... | This is a common issue with pre-trained base models like Llama. My first thought would be to select a model that has some sort of instruction tuning done to it i.e https://huggingface.co/meta-llama/Llama-2-7b-chat. Instruction tuning impacts the model's ability to solve tasks reliably, as opposed to the base model, whi... | 7 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.