eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I am trying to assign different types of text fonts to my application with PyQt5, but I don't know how to assign a different one to the standard one, for example in my application I could only assign it 'Roboto', but if I want to change to Roboto-MediumItalic, I don't know how to specify that font type to it, i'm newbie to python and pyqt5 QFontDatabase.addApplicationFont("Static/fonts/Roboto-Light.ttf") label2.setFont(QFont('Roboto',12))  folders 

Answer: You have to use the styles and QFontDatabase to use Roboto-MediumItalic. You can also set the italic weight style through QFont. import os import sys from pathlib import Path from PyQt5.QtCore import Qt, QDir from PyQt5.QtGui import QFont, QFontDatabase from PyQt5.QtWidgets import QApplication, QLabel CURRENT_DIRECTORY = Path(__file__).resolve().parent def load_fonts_from_dir(directory): families = set() for fi in QDir(directory).entryInfoList(["*.ttf"]): _id = QFontDatabase.addApplicationFont(fi.absoluteFilePath()) families |= set(QFontDatabase.applicationFontFamilies(_id)) return families def main(): app = QApplication(sys.argv) font_dir = CURRENT_DIRECTORY / "Static" / "fonts" families = load_fonts_from_dir(os.fspath(font_dir)) print(families) db = QFontDatabase() styles = db.styles("Roboto") print(styles) font = db.font("Roboto", "Medium Italic", 12) # OR # font = QFont("Roboto", pointSize=12, weight=QFont.Medium, italic=True) label = QLabel(alignment=Qt.AlignCenter) label.setFont(font) label.setText("Hello world!!") label.resize(640, 480) label.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
Question: I encountered very annoying problem. I have created my own AdminSite like this: from django.contrib import admin from django.template.response import TemplateResponse from django.urls import path class MyAdminSite(admin.AdminSite): def get_urls(self): urls = super().get_urls() my_urls = [ path('statistics/', self.admin_view(self.statistics), name='statistics'), ] return urls + my_urls def statistics(self, request): context = dict( self.each_context(request), ) return TemplateResponse(request, 'admin/statistics.html', context)  I have created my own AdminConfig and assigned it into my INSTALLED_APPS, created html file, then in my root urls added it like this:  urlpatterns = [ url(r'^admin/', admin.site.urls), ]  I have logged in into my admin page and when I'm trying to open localhost:8000/admin/statistics I receive this: Page not found (404) Request URL: http://localhost:8000/admin/statistics/  Why this is happening? Did I miss something? Update I have added print on my get_urls and it showed this.(I removed unnecessary urls): [ <URLPattern '' [name='index']>, <URLPattern 'login/' [name='login']>, <URLPattern 'logout/' [name='logout']>, <URLPattern 'password_change/' [name='password_change']>, <URLPattern 'password_change/done/' [name='password_change_done']>, <URLPattern 'autocomplete/' [name='autocomplete']>, <URLPattern 'jsi18n/' [name='jsi18n']>, <URLPattern 'r/<int:content_type_id>/<path:object_id>/' [name='view_on_site']>, <URLResolver <URLPattern list> (None:None) 'auth/group/'>, <URLPattern '(?P<url>.*)$'>, <URLPattern 'statistics/' [name='statistics']> ]  Using python manage.py show_urls | grep statistics shows me this: /admin/statistics/ project.admin.statistics admin:statistics 

Answer: Well. I'm going to answer to my own question, in order to help other people. The solution of this problem was to switch returning url addition like this:  return my_urls + urls  my_urls comes first and the other urls. Why this is happening? Because urls' last path contains some kind of big wildcard url that just overwrites my own. That is why I needed to add first my new urls. Thanks for @lucascavalcante
Question: I was simulating the solar system (Sun, Earth and Moon). When I first started working on the project, I used the base units: meters for distance, seconds for time, and metres per second for velocity. Because I was dealing with the solar system, the numbers were pretty big, for example the distance between the Earth and Sun is 150·10⁹ m. When I numerically integrated the system with scipy.solve_ivp, the results were completely wrong. Here is an example of Earth and Moon trajectories.  But then I got a suggestion from a friend that I should use standardised units: astronomical unit (AU) for distance and years for time. And the simulation started working flawlessly! My question is: Why is this a generally valid advice for problems such as mine? (Mind that this is not about my specific problem which was already solved, but rather why the solution worked.)

Answer: Most, if not all integration modules work best out of the box if:  your dynamical variables have the same order of magnitude; that order of magnitude is 1; the smallest time scale of your dynamics also has the order of magnitude 1.  This typically fails for astronomical simulations where the orders of magnitude vary and values as well as time scales are often large in typical units. The reason for the above behaviour of integrators is that they use step-size adaption, i.e., the integration step is adjusted to keep the estimated error at a defined level. The step-size adaption in turn is governed by a lot of parameters like absolute tolerance, relative tolerance, minimum time step, etc. You can usually tweak these parameters, but if you don’t, there need to be some default values and these default values are chosen with the above setup in mind. Digression You might ask yourself: Can these parameters not be chosen more dynamically? As a developer and maintainer of an integration module, I would roughly expect that introducing such automatisms has the following consequences:  About twenty in a thousand users will not run into problems like yours. About fifty a thousand users (including the above) miss an opportunity to learn rudimentary knowledge about how integrators work and reading documentations. About one in thousand users will run into a horrible problem with the automatisms that is much more difficult to solve than the above. I need to introduce new parameters governing the automatisms that are even harder to grasp for the average user. I spend a lot of time in devising and implementing the automatisms.
Question: This is the code I write right now: a = 1 if (a := a + 1) == 2: print(a)  I am wondering if something like this exists: a = 1 if (a +:= 1) == 2: print(a) 

Answer: PEP-527 defined the new walrus operator. The section discussing differences between assignment statements and expressions explicitly states:   Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax)     In the section explaining why = is still necessary with :=, we find:  The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.  This strongly implies that there is no intention of supporting a merge of walrus and in-place operators of any kind.
Question: I'm literally using the same code as the official Betfair Developer example, the only difference is that I'm putting the APP_KEY_HERE and SESSION_TOKEN data. But unlike the site, Visual Studio Code is giving me an error and a crash in the terminal.  Terminal response: line 11 print json.dumps(json.loads(response.text), indent=3) ^ SyntaxError: invalid syntax  https://docs.developer.betfair.com/display/1smk3cen4v3lu3yomq5qye0ni/Getting+Started  What am I missing and what do I need to change to solve this problem?

Answer: In python 3.x, you have to enclose the arguments in (). print(json.dumps(json.loads(response.text), indent=3))
Question: The following code from rich.console import Console console = Console() console.print("ciao-16S-123")  will print the number 123 highlighted (in blue, in my terminal). This happens on many strings with numbers, what could be the problem that causes this unwanted formatting, and how to prevent it? 

Answer: As per Rich documentation, "Rich can apply styles to patterns in text which you print() or log(). With the default settings, Rich will highlight things such as numbers, strings, collections, booleans, None, and a few more exotic patterns such as file paths, URLs and UUIDs." You can disable it like this: console.print("ciao-16S-123", highlight=False)  You can also define a custom highlighter better suited for your needs.
Question: Original URL ▶ https://www.exeam.org/index.html I want to extract exeam.org/ or exeam.org from original URL. To do this, I used urllib the most powerful parser in Python that I know, but unfortunately urllib (url.scheme, url.netloc ...) couldn't give me the type of format I wanted.

Answer: to extract the domain name from a url using `urllib): from urllib.parse import urlparse surl = "https://www.exam.org/index.html" urlparsed = urlparse(surl) # network location from parsed url print(urlparsed.netloc) # ParseResult Object print(urlparsed)  this will give you www.exam.org, but you want to further decompose this to registered domain if you are after just the exam.org part. so besides doing simple splits, which could be sufficient, you could also use library such as tldextract which knows how to parse subdmains, suffixes and more: from tldextract import extract ext = extract(surl) print(ext.registered_domain)  this will produce: exam.org
Question: I have a df as: df: col1 col2 col3 col4 col5 0 1.36 4.31 7.66 2 2 1 2.62 3.30 2.48 2 1 2 5.19 3.58 1.62 0 2 3 2.06 3.16 3.50 1 1 4 2.19 2.98 3.38 1 1  I want col6 to return 1 when (col4 > 1 and col5 > 1) else 0 and col7 to return 1 when (col4 > 1 and col5 > 1 and col 4 + col5 > 2) else 0 I am trying df.loc[df['col4'] > 0, df['col5'] > 0, 'col6'] = '1'  however I am getting the error: File "pandas\_libs\index.pyx", line 269, in pandas._libs.index.IndexEngine.get_indexer File "pandas\_libs\hashtable_class_helper.pxi", line 5247, in pandas._libs.hashtable.PyObjectHashTable.lookup TypeError: unhashable type: 'Series'  How can I perform this operation?

Answer: You can simple use bitwise operators: df['col6'] = ((df["col4"]>1) & (df["col5"]>1))*1 df['col7'] = ((df["col4"]>1) & (df["col5"]>1) & (df['col4']+df['col5']>2))*1 >>> df col1 col2 col3 col4 col5 col6 col7 0 1.36 4.31 7.66 2 2 1 1 1 2.62 3.30 2.48 2 1 0 0 2 5.19 3.58 1.62 0 2 0 0 3 2.06 3.16 3.50 1 1 0 0 4 2.19 2.98 3.38 1 1 0 0
Question: So I have been browsing through online sites to read a file line by line and I come to this part of this code: print("Line {}: {}".format(linecount, line))  I am quite confused as to what is happening here. I know that it is printing something, but it shows: "Line{}"  I do not understand what this means. I know that you could write this: foo = "hi" print(f"{foo} bob")  But I don't get why there are empty brackets.

Answer: Empty braces are equivalent to numeric braces numbered from 0: >>> '{}: {}'.format(1,2) '1: 2' >>> '{0}: {1}'.format(1,2) '1: 2'  Just a shortcut. But if you use numerals you can control the order: >>> '{1}: {0}'.format(1,2) '2: 1'  Or the number of times something is used: >>> '{0}: {0}, {1}: {1}'.format(1,2) '1: 1, 2: 2'  Which you cannot do with empty braces.
Question: So I'm learning fastapi right now and I was trying to separate my project into multiple files but when I do I get this error. ModuleNotFoundError: No module named 'app.routes' I have read This multiple times and I'm pretty sure I did everything right can anyone tell me what I did wrong? app │ main.py │ __init__.py │ └───routes auth.py __init__.py  main.py from fastapi import FastAPI from app.routes import auth app = FastAPI() app.include_router(auth.router)  auth.py from fastapi import APIRouter router = APIRouter() @router.get("/test") async def test(): return {"test": "test"}  I ran uvicorn main:app --reload

Answer: Your uvicorn command is slightly off. From whatever directory is above app run -- uvicorn app.main:app --reload
Question: I'm type hinting like this: some_kwarg: Tuple[Callable] = ()  but mypy raises error: Incompatible default for argument "some_kwarg" (default has type "Tuple[]", argument has type "Tuple[Callable[..., Any]]")  I wouldn't want to put a dummy callable in the default kwarg so what's the right thing to do?

Answer: You are type annotating it to accept a tuple of size exactly 1. Use: Tuple[Callable, ...]  To indicate a homogeneous tuple of any size.
Question: I want to convert this list: [1,2,3,4,5]  Into this dict: { 1 : { 2 : { 3 : { 4 : 5 }}}}  This doesn't sound too complicated but I'm stumped when it's time to assign a value to a key deeper than the surface. I have a recursive function for finding how deep my dictionary goes but I don't know how to tell my algorithm to "add the new key here".

Answer: You are looking for a recursive function that builds a dictionary with the first list element as a key and the transformed rest of the list as the value: l = [1, 2, 3, 4, 5] def l2d(l): if len(l) < 2: # Not good raise Exception("The list is too short") if len(l) == 2: # Base case return {l[0]: l[1]} # Recursive case return {l[0]: l2d(l[1:])} l2d(l) # {1: {2: {3: {4: 5}}}}  Another interesting approach is to use functools.reduce: from functools import reduce reduce(lambda tail,head: {head: tail}, reversed(l)) # {1: {2: {3: {4: 5}}}}  It progressively applies a dictionary construction function to the first element of the list and the rest of it. The list is reversed first, so the construction naturally starts at the end. If the list is too short, the function returns its first element, which may or may not be desirable. The "reduce" solution is MUCH FASTER, by about two orders of magnitude. The bottom line: avoid recursion.
Question: How can we parse a file which contains multiple configs and which are separated by --- in python.  I've config file which looks like File name temp.yaml %YAML 1.2 --- name: first cmp: - Some: first top: top_rate: 16000 audio_device: "pulse" --- name: second components: - name: second parameters: always_on: true timeout: 200000  When I read it with import yaml with open('./temp.yaml', 'r') as f: temp = yaml.load(f)  I am getting following error  temp = yaml.load(f) Traceback (most recent call last): File "temp.py", line 4, in <module> temp = yaml.load(f) File "/home/pranjald/.local/lib/python3.6/site-packages/yaml/__init__.py", line 114, in load return loader.get_single_data() File "/home/pranjald/.local/lib/python3.6/site-packages/yaml/constructor.py", line 41, in get_single_data node = self.get_single_node() File "/home/pranjald/.local/lib/python3.6/site-packages/yaml/composer.py", line 43, in get_single_node event.start_mark) yaml.composer.ComposerError: expected a single document in the stream in "./temp.yaml", line 3, column 1 but found another document in "./temp.yaml", line 10, column 1 

Answer: Your input is composed of multiple YAML documents. For that you will need yaml.load_all() or better yet yaml.safe_load_all(). (The latter will not construct arbitrary Python objects outside of data-like structures such as list/dict.) import yaml with open('temp.yaml') as f: temp = yaml.safe_load_all(f)  As hinted at by the error message, yaml.load() is strict about accepting only a single YAML document. Note that safe_load_all() returns a generator of Python objects which you'll need to iterate over. >>> gen = yaml.safe_load_all(f) >>> next(gen) {'name': 'first', 'cmp': [{'Some': 'first', 'top': {'top_rate': 16000, 'audio_device': 'pulse'}}]} >>> next(gen) {'name': 'second', 'components': [{'name': 'second', 'parameters': {'always_on': True, 'timeout': 200000}}]}
Question: How do I define a Python protocol for a type that is:  Callable with any number of keyword arguments of any type that returns a value of a specified type  This is my attempt: from typing import Any, Protocol, TypeVar T = TypeVar("T", covariant=True) class Operation(Protocol[T]): def __call__(self, **kwargs: Any) -> T: pass # some example functions that should be a structural sub-type of "Operation[str]" def sumint(*, x: Any, y: Any) -> str: return f"{x} + {y} = {x + y}" def greet(*, name: Any = "World") -> str: return f"Hello {name}" # an example function that takes an "Operation[str]" as an argument def apply_operation(operation: Operation[str], **kwargs: Any) -> str: return operation(**kwargs) if __name__ == "__main__": print(apply_operation(sumint, x=2, y=2)) # prints: 2 + 2 = 4 print(apply_operation(greet, name="Stack")) # prints: Hello Stack  However, mypy produces the error: example.py:26: error: Argument 1 to "apply_operation" has incompatible type "Callable[[NamedArg(Any, 'x'), NamedArg(Any, 'y')], str]"; expected "Operation[str]" example.py:28: error: Argument 1 to "apply_operation" has incompatible type "Callable[[DefaultNamedArg(Any, 'name')], str]"; expected "Operation[str]" Found 2 errors in 1 file (checked 1 source file)  What am I doing wrong? How do I make mypy happy?

Answer: I can't answer your question about exactly why MyPy isn't happy — but here's a different approach that MyPy does seem to be happy with: from typing import Any, Callable, TypeVar T = TypeVar("T", covariant=True) Operation = Callable[..., T] # some example functions that should be a structural sub-type of "Operation[str]" def sumint(*, x: int = 1, y: int = 2) -> str: return f"{x} + {y} = {x + y}" def greet(*, name: str = "World") -> str: return f"Hello {name}" # an example function that takes an "Operation[str]" as an argument def apply_operation(operation: Operation[str], **kwargs: Any) -> str: return operation(**kwargs) if __name__ == "__main__": print(apply_operation(sumint, x=2, y=2)) # prints: 2 + 2 = 4 print(apply_operation(greet, name="Stack")) # prints: Hello Stack
Question: I have a 2D Numpy Array, and I want to apply a function to each of the rows and form a new column (the new first column) with the results. For example, let M = np.array([[1,0,1], [0,0,1]])  and I want to apply the sum function on each row and get array([[2,1,0,1], [1,0,0,1]])  So the first column is [2,1], the sum of the first row and the second row.

Answer: You can generally append arrays to each other using np.concatenate when they have similar dimensionality. You can guarantee that sum will retain dimensionality regardless of axis using the keepdims argument: np.concatenate((M.sum(axis=1, keepdims=True), M), axis=1)  This is equivalent to np.concatenate((M.sum(1)[:, None], M), axis=1)
Question: I have a data frame that contains a column with long texts. To demonstrate how it looks (note the ellipses "..." where text should continue): id text group 123 My name is Benji and I ... 2  The above text is actually longer than that phrase. For example it could be:  My name is Benji and I am living in Kansas.  The actual text is much longer than this. When I try to subset the text column only, it only shows the partial text with the dots "...". I need to make sure full text is shown for text sumarization later. But I'm not sure how to show the full text when selecting the text column. My df['text'] output looks something like this: 1 My name is Benji and I ... 2 He went to the creek and ...  How do I show the full text and without the index number?

Answer: You can convert to a list an join with newlines ("\n"): import pandas as pd text = """The bullet pierced the window shattering it before missing Danny's head by mere millimeters. Being unacquainted with the chief raccoon was harming his prospects for promotion. There were white out conditions in the town; subsequently, the roads were impassable. The hawk didn’t understand why the ground squirrels didn’t want to be his friend. Nobody loves a pig wearing lipstick.""" df = pd.DataFrame({"id": list(range(5)), "text": text.splitlines()})  Original output: print(df["text"])  Yields: 0 The bullet pierced the window shattering it be... 1 Being unacquainted with the chief raccoon was ... 2 There were white out conditions in the town; s... 3 The hawk didn’t understand why the ground squi... 4 Nobody loves a pig wearing lipstick.  Desired output: print("\n".join(df["text"].to_list()))  Yields: The bullet pierced the window shattering it before missing Danny's head by mere millimeters. Being unacquainted with the chief raccoon was harming his prospects for promotion. There were white out conditions in the town; subsequently, the roads were impassable. The hawk didn’t understand why the ground squirrels didn’t want to be his friend. Nobody loves a pig wearing lipstick.
Question: I have a matrix: t = torch.rand(2,3) print(t) >>>tensor([[0.5164, 0.3651, 0.0882], [0.4488, 0.9824, 0.4067]])  I'm following this introduction to norms and want to try it in PyTorch. It seems like the:  norm of a vector is "the size or length of a vector is a nonnegative number that describes the extent of the vector in space, and is sometimes referred to as the vector’s magnitude or the norm" 1-Norm is "the sum of the absolute vector values, where the absolute value of a scalar uses the notation |a1|. In effect, the norm is a calculation of the Manhattan distance from the origin of the vector space." 2-Norm is "the distance of the vector coordinate from the origin of the vector space. The L2 norm is calculated as the square root of the sum of the squared vector values."  I currently only know of this: print(torch.linalg.norm(t, dim=1)) >>>tensor([0.6385, 1.1541])  But I can't figure out which one of the three (norm, 1-norm, 2-norm) from here it is calculating, and how to calculate the rest

Answer: To compute the 0-, 1-, and 2-norm you can either use torch.linalg.norm, providing the ord argument (0, 1, and 2 respectively). Or directly on the tensor: Tensor.norm, with the p argument. Here are the three variants: manually computed, with torch.linalg.norm, and with Tensor.norm.  0-norm >>> x.norm(dim=1, p=0) >>> torch.linalg.norm(x, dim=1, ord=0) >>> x.ne(0).sum(dim=1)   1-norm >>> x.norm(dim=1, p=1) >>> torch.linalg.norm(x, dim=1, ord=1) >>> x.abs().sum(dim=1)   2-norm >>> x.norm(dim=1, p=2) >>> torch.linalg.norm(x, dim=1, ord=2) >>> x.pow(2).sum(dim=1).sqrt()
Question: I have a dataset, df, where I would like to groupby two columns, take the sum and count of another column as well as list the strings in a separate column Data id date pwr type aa q321 10 hey aa q321 1 hello aa q425 20 hi aa q425 20 no bb q122 2 ok bb q122 1 cool bb q422 5 sure bb q422 5 sure bb q422 5 ok  Desired id date pwr count type aa q321 11 2 hey hello aa q425 40 2 hi no bb q122 3 2 ok cool bb q422 15 3 sure sure ok  Doing g = df.groupby(['id', 'date'])['pwr'].sum().reset_index() g['count'] = g['id'].map(df['id'].value_counts())  This works ok, except, I am not sure how to display the string output of column 'type' Any suggestion is appreciated.

Answer: You can use .GroupBy.transform() to set the values for columns pwr and count. Then .set_index() on the 4 columns except type to get a layout similar to the desired output: df['pwr'] = df.groupby(['id', 'date'])['pwr'].transform('sum') df['count'] = df.groupby(['id', 'date'])['pwr'].transform('count') df.set_index(['id', 'date', 'pwr', 'count'])  Output:  type id date pwr count aa q321 11 2 hey 2 hello q425 40 2 hi 2 no bb q122 3 2 ok 2 cool q422 15 3 sure 3 sure 3 ok