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
73,295,856
2022-8-9
https://stackoverflow.com/questions/73295856/dataproc-errors-when-reading-and-writing-data-from-bigquery-using-pyspark
I am trying to read some BigQuery data, (ID: my-project.mydatabase.mytable [original names protected]) from a user-managed Jupyter Notebook instance, inside Dataproc Workbench. What I am trying is inspired in this, and more specifically, the code is (please read some additional comments, on the code itself): from pyspa...
Key points found during the discussion: Add the BigQuery connector as a dependency through spark.jars=<gcs-uri> or spark.jars.packages=com.google.cloud.spark:spark-bigquery-with-dependencies_<scala-version>:<version>. Specify the correct table name in <project>.<dataset>.<table> format. The default mode for datafram...
4
6
73,259,393
2022-8-6
https://stackoverflow.com/questions/73259393/retrying-failed-futures-in-pythons-threadpoolexecutor
I want to implement retry logic with Python's concurrent.futures.ThreadPoolExecutor. I would like the following properties: A new future is added to the work queue as soon as it fails. A retried future can be retried again, either indefinitely or up to a maximum retry count. A lot of existing code I found online basi...
Retry using as_completed Simple way Loop with wait(..., return_when=FIRST_COMPLETED) instead of as_completed(...). Trade-offs: Overhead of pending futures (re-adding waiter, building new_futures). Troublesome if want to specify overall timeout. with concurrent.futures.ThreadPoolExecutor() as executor: futures = {exec...
4
3
73,216,605
2022-8-3
https://stackoverflow.com/questions/73216605/add-background-color-to-cells-reportlab-python
summary = [['Metrics','Status']] try: for i in output['responsetimes']: if i['metric'] == 'ResponseTime': k = i['value'].split(' ') if int(k[0])<1000: temp = ['Response Times','Green'] summary.append(temp) else: temp = ['Response Times','Red'] summary.append(temp) except: summary.append(['Response Times','NA']) try: f...
Found the answer myself after some more searching stackoverflow questions. Might help someone else.. In my case, list summary has the heading by default which is ['Metrics','Status'] and I'm appending the rest of the values based on validations like this, for i in output['responsetimes']: if i['metric'] == 'ResponseTi...
4
3
73,291,228
2022-8-9
https://stackoverflow.com/questions/73291228/add-route-to-fastapi-with-custom-path-parameters
I am trying to add routes from a file and I don't know the actual arguments beforehand so I need to have a general function that handles arguments via **kwargs. To add routes I am using add_api_route as below: from fastapi import APIRouter my_router = APIRouter() def foo(xyz): return {"Result": xyz} my_router.add_api_r...
This will generate a function with a new signature (I assume every parameter is a string): from fastapi import APIRouter import re import inspect my_router = APIRouter() def generate_function_signature(route_path: str): args = {arg: str for arg in re.findall(r'\{(.*?)\}', route_path)} def new_fn(**kwargs): return {"Res...
4
3
73,247,204
2022-8-5
https://stackoverflow.com/questions/73247204/black-not-respecting-extend-exclude-in-pyproject-toml
In VSCode, with Python 3.9 and black==22.6.0, I have a project structure like: --- root ------src ---------module0.py ---------module1.py ------tests ---------test_folder0 ------------test_file0.py ------------test_file1.py ---------test_folder1 ---------etc. In pyproject.toml I can't get the extend-exlude part to act...
Maintainer of Black here :wave: OK, so I actually missed a few points in my comments. To address the main question, this is 100% expected behaviour. Your regex is fine. The thing is that when you ask VSCode to format your file on save, it calls Black passing the filepath to your current file (you just saved) directly. ...
6
16
73,293,535
2022-8-9
https://stackoverflow.com/questions/73293535/install-newer-version-of-sqlite3-on-aws-lambda-for-use-with-python
I have a Python script running in a Docker container on AWS Lambda. I'm using the recommended AWS image (public.ecr.aws/lambda/python:3.9), which comes with SQLite version 3.7.17 (from 2013!). When I test the container locally on my M1 Mac, I see this: $ docker run --env-file .env --entrypoint bash -ti my-image bash-4....
The problem was that I was running Docker locally to do my testing, on an M1 Mac. Hence the aarch64 architecture. Lambda does allow you to use ARM, but thankfully it still defaults to x86_64. I confirmed that my Lambda function was running x86_64, which is what the binary wheel uses, so that's good: So I needed to do ...
5
1
73,279,086
2022-8-8
https://stackoverflow.com/questions/73279086/converting-32-bit-tiff-to-8-bit-tiff-while-retaining-metadata-and-tags-in-python
I would like to convert several TIFF files with 32-bit pixel depth into 8-bit pixel depth TIFFs while retaining metadata and TIFF tags. The 32-bit TIFFs are four-dimensional ImageJ-hyperstacks with TZYX axes (i.e. time, z-depth, y-coordinate, x-coordinate) and values in the range of [0, 1]. I can convert to 8-bit and c...
Copy the resolution and resolutionunit properties and add the axes order of the image array to the imagej_metadata dict: import numpy import tifffile with tifffile.TiffFile('imagej_float32.tif') as tif: data = tif.asarray() imagej_metadata = tif.imagej_metadata imagej_metadata['axes'] = tif.series[0].axes resolution = ...
5
5
73,251,559
2022-8-5
https://stackoverflow.com/questions/73251559/x-ref-the-python-standard-library-with-intersphinx-while-omitting-the-module-nam
EDIT: Other answers than the one I provided are welcome! Consider the following function: from pathlib import Path from typing import Union def func(path: Union[str, Path]) -> None: """My super function. Parameters ---------- path : str | Path path to a super file. """ pass When documenting with sphinx, I would like t...
numpydoc can do this through x-ref aliases: https://numpydoc.readthedocs.io/en/latest/ In the configuration conf.py: numpydoc_xref_param_type = True numpydoc_xref_aliases = { "Path": "pathlib.Path", } It might try to match other words from the parameters types of the Parameters, Other Parameters, Returns and Yields se...
4
0
73,238,617
2022-8-4
https://stackoverflow.com/questions/73238617/passing-argument-key-pair-to-vscode-python-debugger-separated-with-an-equal-sign
For management of my config files, I'm using Hydra which requires passing additional arguments using a plus and then an equal sign between the argument and its value, e.g. python evaluate.py '+model_path="logs/fc/version_1/checkpoints/epoch=1-step=2.ckpt"' Above I'm also using quotes to escape the equal signs in the v...
This may not be the most elegant solution but it works if we pass everything as a single argument (no comma inbetween) like this: "args" : ["+model_path='logs/fc/version_7/checkpoints/epoch=19-step=3700.ckpt'"]
4
1
73,242,764
2022-8-4
https://stackoverflow.com/questions/73242764/how-to-efficiently-calculate-membership-counts-by-month-and-group
I have to calculate in Python the number of unique active members by year, month, and group for a large dataset (N ~ 30M). Membership always starts at the beginning of the month and ends at the end of the month. Here is a very small subset of the data. print(df.head(6)) member_id type start_date end_date 1 10 A 2021-12...
Updated answer that avoids melt. Maybe faster? Uses the same idea as before where we don't actually care about member ids, we are just keeping track of start/end counts #Create multiindexed series for reindexing later months = pd.date_range( start=df.start_date.min(), end=df.end_date.max(), freq='MS', ).to_period('M') ...
6
2
73,280,922
2022-8-8
https://stackoverflow.com/questions/73280922/python-how-to-type-hint-tf-keras-object-in-functions
This example function returns a dictionary of keras tensors: import pandas as pd import tensorflow as tf def create_input_tensors(data: pd.DataFrame) -> Dict[str,tf.keras.engine.keras_tensor.KerasTensor]: """Turns each dataframe column into a keras tensor and returns them as a dict""" tensors = {} for name, column in d...
This works like a charm for me: import typing from keras.engine.keras_tensor import KerasTensor def f() -> typing.Dict[str, KerasTensor]: return {"a": tf.keras.Input(shape=(1, ),)} f()
4
2
73,275,978
2022-8-8
https://stackoverflow.com/questions/73275978/how-do-i-solve-userwarning-dataframe-columns-are-not-unique-some-columns-will
i have a dataframe of 2 columns. i tried converting it into a dictionary using df2.set_index('pay').T.to_dict('list'). As there are duplicated keys, some columns were omitted. Is there any way to resolve this issue or an alternative method? pay score 500 1 700 4 1000 5 700 3 I would like to achieve th...
IIUC use: d = df2.T.to_dict('list') print (d) {0: [500, 1], 1: [700, 4], 2: [1000, 5], 3: [700, 3]}
4
2
73,274,305
2022-8-8
https://stackoverflow.com/questions/73274305/can-i-assign-the-result-of-a-function-on-multiple-lines-python
Lets say I have a function that return a lot of variables: def func(): return var_a, var_b, var_c, var_d, var_e, var_f, var_g, var_h, var_i, Using this function results in very long lines var_a, var_b, var_c, var_d, var_e, var_f, var_g, var_h, var_i = func() Ideally, I would like to use the line breaker \, e.g. a = v...
You can wrap the variables in round brackets (var_a, var_b, var_c, var_d, var_e, var_f, var_g, var_h, var_i) = func()
5
6
73,257,454
2022-8-6
https://stackoverflow.com/questions/73257454/filter-shapely-polygons-by-centroid-clip-or-something-else
I drew this flower of life by buffering points to polygons. I wanted each overlapping region to be its own polygon, so I used union and polygonize on the lines. I have filtered the polygons by area to eliminate sliver polygons, and now I'd like to filter them again and am stuck. I only want to keep the circles that ar...
Is this what you wanted? I used the x^2 + y^2 = r^2 circle formula to filter. complete_polys = [polygon for polygon in filtered_polys if (polygon.centroid.x**2 + polygon.centroid.y**2 < 4**2)] plot_polys(complete_polys, colors)
4
3
73,273,628
2022-8-8
https://stackoverflow.com/questions/73273628/find-a-element-in-bs4-by-partial-class-name-not-working
I want to find an a element in a soup object by a substring present in its class name. This particular element will always have JobTitle inside the class name, with random preceding and trailing characters, so I need to locate it by its substring of JobTitle. You can see the element here: It's safe to assume there is ...
To find an element with partial class name you need to use select, not find. The will give you the <a> tag, the href will be in it job_url = soup.select_one('a[class*="JobTitle"]')['href'] print(job_url) # /pagead/clk?mo=r&ad=-6NYlbfkN0CpFJQzrgRR8WqXWK1qKKEqALWJw739KlKqr2H-MSI4eoBlI4EFrmor2FYZMP3muM35UEpv7D8dnBwRFuIf8X...
4
2
73,271,056
2022-8-7
https://stackoverflow.com/questions/73271056/hydra-install-on-python-3-10-fails-due-to-vs-build-tools
I'm trying to install Hydra 2.5 on a Windows 10 system. I have Visual Studio Build Tools 2022 installed with the desktop C++ development option. When I use pip I get the error attached below. I've tried it with both python 3.10 and 3.9. I've tried a fresh conda environment. I've also tried to install Mingw-w64 to see i...
The package name is hydra-core :).
12
42
73,270,890
2022-8-7
https://stackoverflow.com/questions/73270890/how-do-i-convert-a-torch-tensor-to-an-image-to-be-returned-by-fastapi
I have a torch tensor which I need to convert to a byte object so that I can pass it to starlette's StreamingResponse which will return a reconstructed image from the byte object. I am trying to convert the tensor and return it like so: def some_unimportant_function(params): return_image = io.BytesIO() torch.save(some_...
Converting PyTorch Tensor to the PIL Image object using torchvision.transforms.ToPILImage() module and then treating it as PIL Image as your second function would work. Here is an example. def some_unimportant_function(params): tensor = # read the tensor from disk or whatever image = torchvision.transforms.ToPILImage()...
7
5
73,271,404
2022-8-7
https://stackoverflow.com/questions/73271404/how-to-find-the-average-of-the-differences-between-all-the-numbers-of-a-python-l
I have a python list like this, arr = [110, 60, 30, 10, 5] What I need to do is actually find the difference of every number with all the other numbers and then find the average of all those differences. So, for this case, it would first find the difference between 110 and then all the remaining elements, i.e. 60, 30,...
I'll just give the formula first: n = len(arr) out = np.sum(arr * np.arange(n-1, -n, -2) ) / (n*(n-1) / 2) # 52 Explanation: You want to find the mean of a[0] - a[1], a[0] - a[2],..., a[0] - a[n-1] a[1] - a[2],..., a[1] - a[n-1] ... there, your `a[0]` occurs `n-1` times with `+` sign, `0` with `-` -> `n-1` times `a[1...
20
36
73,267,809
2022-8-7
https://stackoverflow.com/questions/73267809/run-playwright-in-interactive-mode-in-python
I was using playwright to scrape pages using Python. I know how to do the same using a script, but I was trying this in an interactive mode. from playwright.sync_api import Playwright, sync_playwright, expect import time def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) conte...
Use the .start() method: >>> from playwright.sync_api import Playwright, sync_playwright, expect >>> playwright = sync_playwright().start() >>> browser = playwright.chromium.launch(headless=False) >>> page = browser.new_page() Alternatively, if you just want an interactive browser, and don't care about an interactive ...
5
13
73,270,707
2022-8-7
https://stackoverflow.com/questions/73270707/functools-singledispatchmethod-with-own-class-as-arg-type
I would like to use functools.singledispatchmethod to overload the binary arithmetic operator methods of a class called Polynomial. The problem I have is that I can't find a way to register method calls where other is a Polynomial. Perhaps better explained with a simple example: from __future__ import annotations from ...
The alternative is to add the methods after the class definition: from __future__ import annotations from functools import singledispatchmethod class Polynomial: pass @singledispatchmethod def __add__(self, other): return NotImplemented @__add__.register def _(self, other: Polynomial): return NotImplemented Polynomial....
5
2
73,227,632
2022-8-3
https://stackoverflow.com/questions/73227632/matplotlib-chart-not-animating-pandas-data-issue
I'm experimenting with Matplotlib animated charts currently. Having an issue where, using a public dataset, the data isn't animating. I am pulling data from a public CSV file following some of the guidance from this post (which has to be updated a bit for things like the URL of the data). I've tested my Matplotlib inst...
Actually, your code is fine. I can successfully run it as a script without making any changes. Here's my environment: python 3.8.5 pandas 1.1.3 matplotlib 3.3.2 But I suspect, that you are working in Jupyter-Notebook. In this case you have to make some changes. First, set up matplotlib to work interactively in the not...
4
3
73,264,498
2022-8-7
https://stackoverflow.com/questions/73264498/how-to-divide-an-array-in-several-sections
I have an array with approximately 12000 length, something like array([0.3, 0.6, 0.3, 0.5, 0.1, 0.9, 0.4...]). Also, I have a column in a dataframe that provides values like 2,3,7,3,2,7.... The length of the column is 48, and the sum of those values is 36. I want to distribute the values, which means the 12000 lengths ...
import pandas as pd import numpy as np # mock some data a = np.random.random(12000) df = pd.DataFrame({'col': np.random.randint(1, 5, 48)}) indices = (len(a) * df.col.to_numpy() / sum(df.col)).cumsum() indices = np.concatenate(([0], indices)).round().astype(int) res = [] for s, e in zip(indices[:-1], indices[1:]): res....
4
2
73,255,282
2022-8-5
https://stackoverflow.com/questions/73255282/min-of-given-keys-from-python-defaultdictionary
I got a defaultdict with lists as values and tuples as keys (ddict in the code below). I want to find the min and max of values for a given set of keys. The keys are given as a numpy array. The numpy array is a 3D array containing the keys. Each row of the 3D array is the block of keys for which we need to find the min...
Here is what I think you're after: import numpy as np # I've reformatted your example data, to make it a bit clearer # no change in content though, just different whitespace # whether d is a dict or defaultdict doesn't matter d = { (1.0, 1.0): [1, 2, 3, 4], (1.0, 2.5): [2, 3, 4, 5], (1.0, 3.75): [], (1.5, 1.0): [8, 9, ...
4
3
73,225,265
2022-8-3
https://stackoverflow.com/questions/73225265/how-to-insert-bulk-data-into-cosmos-db-in-python
I'm developing an application in Python which uses Azure Cosmos DB as the main database. At some point in the app, I need to insert bulk data (a batch of items) into Cosmos DB. So far, I've been using Azure Cosmos DB Python SDK for SQL API for communicating with Cosmos DB; however, it doesn't provide a method for bulk ...
The Cosmos DB service does not provide this via its REST API. Bulk mode is implemented at the SDK layer and unfortunately, the Python SDK does not yet support bulk mode. It does however support asynchronous IO. Here's an example that may help you. from azure.cosmos.aio import CosmosClient import os URL = os.environ['AC...
5
4
73,258,013
2022-8-6
https://stackoverflow.com/questions/73258013/python-pandas-data-frame-error-while-trying-to-print-it-within-single-df
I see dataframe error while trying to print it within single df[ _ , _ ] form. Below are the code lines #Data Frames code import numpy as np import pandas as pd randArr = np.random.randint(0,100,20).reshape(5,4) df =pd.DataFrame(randArr,np.arange(101,106,1),['PDS','Algo','SE','INS']) print(df['PDS','SE']) errors: Trac...
Do you mean to do this? Need to indicate the column names when creating the dataframe, and also need double square brackets df[[ ]] when extracting a slice of the dataframe import numpy as np import pandas as pd randArr = np.random.randint(0,100,20).reshape(5,4) df = pd.DataFrame(randArr, columns=['PDS', 'SE', 'ABC', '...
4
2
73,257,192
2022-8-6
https://stackoverflow.com/questions/73257192/convert-a-list-of-dictionary-of-dictionaries-to-a-dataframe
I have a list of "dictionary of dictionaries" that looks like this: lis = [{'Health and Welfare Plan + Change Notification': {'evidence_capture': 'null', 'test_result_justification': 'null', 'latest_test_result_date': 'null', 'last_updated_by': 'null', 'test_execution_status': 'Not Started', 'test_result': 'null'}}, {'...
Let us do dict comp to flatten the list of dictionaries pd.DataFrame({k.split(' + ')[1]: v for d in lis for k, v in d.items()}).T evidence_capture test_result_justification latest_test_result_date last_updated_by test_execution_status test_result Change Notification null null null null Not Started null Computations ...
4
5
73,244,027
2022-8-5
https://stackoverflow.com/questions/73244027/character-set-utf8-unsupported-in-python-mysql-connector
I'm trying to connect my database to a python project using the MySQL connector. However, when using the code below, import mysql.connector mydb = mysql.connector.MySQLConnection( host="localhost", user="veensew", password="%T5687j5IiYe" ) print(mydb) I encounter the following error: mysql.connector.errors.Programmin...
I ran into the same issue. There were apparently some changes in version 8.0.30 to the way utf8_ collations are handled (see MySQL Connector release notes). I installed version 8.0.29 which fixed the issue for me. pip3 install mysql-connector-python==8.0.29
16
34
73,251,012
2022-8-5
https://stackoverflow.com/questions/73251012/put-logo-and-title-above-on-top-of-page-navigation-in-sidebar-of-streamlit-multi
I am using the new multipage feature and would like to style my multipage app and put a logo with a title on top of/before the page navigation. Here's a small example tested on Python 3.9 with streamlit==1.11.1 in the following directory structure: /Home.py /pages/Page_1.py /pages/Page_2.py Home.py: import streamlit a...
One option is to do it via CSS, with a function like this: def add_logo(): st.markdown( """ <style> [data-testid="stSidebarNav"] { background-image: url(http://placekitten.com/200/200); background-repeat: no-repeat; padding-top: 120px; background-position: 20px 20px; } [data-testid="stSidebarNav"]::before { content: "M...
9
12
73,247,210
2022-8-5
https://stackoverflow.com/questions/73247210/how-to-plot-a-gantt-chart-using-timesteps-and-not-dates-using-plotly
So I found this code online that would make a Gantt chart: import plotly.express as px import pandas as pd df = pd.DataFrame([ dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"), dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Resource="Alex"), dict(Task="Job C", Start='2009-02-20'...
You can do this using plotly.figure_factory gantt chart and forcing the x-axis to show numbers. There are few examples here, if you need to know more about this. The code output is as shown below. import pandas as pd import plotly.figure_factory as ff df = pd.DataFrame([ dict(Task="Job A", Start=0, Finish=10, Resource=...
4
4
73,245,007
2022-8-5
https://stackoverflow.com/questions/73245007/socketexception-connection-refused-os-error-connection-refused-errno-111
In my flutter app I am using the flask server for testing purpose. I started my server and run the API url in my flutter app. But SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164. error is showing. var headers = {'Content-Type': 'application/json'}; var ...
This happens because the localhost (or 127.0.0.1) on the device is only accessible to the device itself. Solution 1 You can reverse-proxy a localhost port to the Android device/emulator running adb reverse on the command prompt like so: adb reverse tcp:5000 tcp:5000 Solution 2 Use the machine's IP address where the AP...
5
7
73,236,048
2022-8-4
https://stackoverflow.com/questions/73236048/is-there-no-faster-way-to-convert-bgr-opencv-image-to-cmyk
I have an OpenCV image, as usual in BGR color space, and I need to convert it to CMYK. I searched online but found basically only (slight variations of) the following approach: def bgr2cmyk(cv2_bgr_image): bgrdash = cv2_bgr_image.astype(float) / 255.0 # Calculate K as (1 - whatever is biggest out of Rdash, Gdash, Bdash...
There are several things you should do: shake the math use integer math where possible optimize beyond what numpy can do Shaking the math Given RGB' = RGB / 255 K = 1 - max(RGB') C = (1-K - R') / (1-K) M = (1-K - G') / (1-K) Y = (1-K - B') / (1-K) You see what you can factor out. RGB' = RGB / 255 J = max(RGB') K = 1...
5
3
73,240,620
2022-8-4
https://stackoverflow.com/questions/73240620/the-right-way-to-type-hint-a-coroutine-function
I cannot wrap my head around type hinting a Coroutine. As far as I understand, when we declare a function like so: async def some_function(arg1: int, arg2: str) -> list: ... we effectively declare a function, which returns a coroutine, which, when awaited, returns a list. So, the way to type hint it would be: f: Calla...
As the docs state: Coroutine objects and instances of the Coroutine ABC are all instances of the Awaitable ABC. And for the Coroutine type: A generic version of collections.abc.Coroutine. The variance and order of type variables correspond to those of Generator. Generator in turn has the signature Generator[YieldTy...
44
27
73,239,270
2022-8-4
https://stackoverflow.com/questions/73239270/numpy-rounding-issue
Can someone explain to me why is numpy round acting strange with this exact number rounding: df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]}) df = np.round(df['c'], 8) Result: 121921117.71499997 445.0 22.0 Expected: 121921117.71499999 445.0 22.0 It's obvious that the first number is not rounded well, any...
Check the small print 2 in the documentation of round aka around. The short answer is that round "uses a fast but sometimes inexact algorithm" and to use format_float_positional if you want to see the correct result. >>> import pandas as pd >>> df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]}) >>> df["c"]...
4
3
73,234,081
2022-8-4
https://stackoverflow.com/questions/73234081/print-a-string-which-has-the-reverse-order
Assignment: Print a string which has the reverse order 'Python love We. Science Data love We' I tried this: strg = We love Data Science. We love Python words = strg.split(" ") words.reverse() new_strg = " ".join(words) print(new_strg) >>> Python love We Science. Data love We But the answer isn't as expected because ...
Is this the output you need? Python love We. Science Data love We Then the code is strg = 'We love Data Science. We love Python' pos = len(strg) - strg.index('.') - 2 words = [e.strip('.') for e in strg.split()] words.reverse() new_strg = ' '.join(words) print(new_strg[:pos] + '.' + new_strg[pos:]) Or another way to ...
4
2
73,234,979
2022-8-4
https://stackoverflow.com/questions/73234979/how-to-check-if-element-is-present-or-not-using-playwright-and-timeout-parameter
I need to find a specific element in my webpage. The element may be in the page or not. This code is giving me error if the element is not visible: error_text = self.page.wait_for_selector( self.ERROR_MESSAGE, timeout=7000).inner_text() How can I look for the element using timeout, and get a bool telling me if the ele...
You have to use the page.is_visible(selector, **kwargs) for this as this returns a boolean value. Playwright Docs, bool = page.is_visible(selector, timeout=7000) print(bool) #OR if page.is_visible(selector, timeout=7000): print("Element Found") else: print("Element not Found") You can also use expect assertion if you ...
4
7
73,229,993
2022-8-4
https://stackoverflow.com/questions/73229993/how-to-upload-a-specific-file-to-google-colab
I have a file on my computer that I want to upload to Google Colab. I know there are numerous ways to do this, including a from google.colab import files uploaded = files.upload() or just uploading manually from the file system. But I want to upload that specific file without needing to choose that file myself. Someth...
Providing a file path directly rather than clicking through the GUI for an upload requires access to your local machine's file system. However, when your run cell IPython magic commands such as %pwd in Google collab, you'll notice that the current working directory shown is that of the notebook environment - not that o...
4
1
73,228,173
2022-8-3
https://stackoverflow.com/questions/73228173/how-to-aggregate-a-subset-of-rows-in-and-append-to-a-multiindexed-pandas-datafra
Problem Setup & Goal I have a Multindexed Pandas DataFrame that looks like this: import pandas as pd df = pd.DataFrame({ 'Values':[1, 3, 4, 8, 5, 2, 9, 0, 2], 'A':['A1', 'A1', 'A1', 'A1', 'A2', 'A2', 'A3', 'A3', 'A3'], 'B':['foo', 'bar', 'fab', 'baz', 'foo', 'baz', 'qux', 'baz', 'bar'] }) df.set_index(['A','B'], inplac...
Here is one way which resets the index for just B, performs a replace and aggregates the values. agg_list = ['bar', 'baz'] (df.reset_index(level=1) .replace({'B':{'|'.join(agg_list):'other'}},regex=True) .groupby(['A','B']).sum()) Another way is to create a new MultiIndex with bar and baz being replaced with other. (d...
4
2
73,217,036
2022-8-3
https://stackoverflow.com/questions/73217036/how-to-set-required-fields-in-patch-api-in-swagger-ui
I'm using drf-spectacular and here's code in settings.py SPECTACULAR_SETTINGS = { 'TITLE': 'TITLE', 'VERSION': '1.0.0', 'SCHEMA_PATH_PREFIX_TRIM': True, 'PREPROCESSING_HOOKS': ["custom.url_remover.preprocessing_filter_spec"], } in serializers.py class ChangePasswordSerilaizer(serializers.Serializer): current_password ...
change your SPECTACULAR_SETTINGS SPECTACULAR_SETTINGS = { 'TITLE': 'APP NAME', 'VERSION': '1.0.0', 'SCHEMA_PATH_PREFIX_TRIM': True, 'PREPROCESSING_HOOKS': ["custom.url_remover.preprocessing_filter_spec"], 'COMPONENT_SPLIT_PATCH': False, } by default COMPONENT_SPLIT_PATCH is true in SPECTACULAR_SETTINGS so you can sim...
4
5
73,193,006
2022-8-1
https://stackoverflow.com/questions/73193006/how-to-add-a-column-to-a-polars-dataframe-using-with-columns
I am currently creating a new column in a polars data frame using predictions = [10, 20, 30, 40, 50] df['predictions'] = predictions where predictions is a numpy array or list containing values I computed with another tool. However, polars throws a warning, that this option will be deprecated. How can the same result ...
You can now also pass numpy arrays in directly. E.g, df = pl.DataFrame({"x": [0, 1, 2, 3, 4]}) p1 = [10, 20, 30, 40, 50] p2 = np.array(p1) df.with_columns( p1=pl.Series(p1), # For python lists, construct a Series p2=p2, # For numpy arrays, you can pass them directly ) # shape: (5, 3) # ┌─────┬─────┬─────┐ # │ x ┆ p1 ┆ ...
26
4
73,181,243
2022-7-31
https://stackoverflow.com/questions/73181243/warningtensorflowlayers-in-a-sequential-model-should-only-have-a-single-input
I have copy past code from tensorflow website's introduction to autoencoder first examplefollowing code works with mnist fashion dataset but not mine.This gives me a very long warning.Please tell me what is worng with my dataset the warning screen short of same error here x_train is my dataset: tf.shape(x_train) output...
The model.fit() is given a list of arrays as input. A list of arrays is generally passed to fit() when a model has multiple inputs. In this case, the fit() method is treating each array as an input, resulting in the error. Please convert the data to a tensor as follows and try again. x_train=tf.convert_to_tensor(x_trai...
4
4
73,135,157
2022-7-27
https://stackoverflow.com/questions/73135157/redis-timeseries-with-python-responseerror-unknown-command-ts-create
I am trying to create a timeseries in Redis using python like so: import redis connection_redis = redis.Redis(host='127.0.0.1', port=6379) connection_redis.ts().create('ts', retention_msecs=0) but I get the following error: ResponseError: unknown command 'TS.CREATE'. I have been searching for a way to solve this prob...
The Redis docker image does not contain any Redis module. You can use the Redis Stack docker image. redis/redis-stack-server contains the RediSearch, RedisJSON, RedisGraph, RedisTimeSeries, and RedisBloom modules. redis/redis-stack also contains RedisInsight. Update, October 2024 From a Redis Blog Post: Redis 8 introd...
5
8
73,150,560
2022-7-28
https://stackoverflow.com/questions/73150560/get-the-name-of-all-fields-in-a-dataclass
I am trying to write a function to log dataclasses I would like to get the name of all fields in the dataclass and print the value to each (similar to how you might write a function to print a dictionary) i.e. import dataclasses @dataclasses.dataclass class Test: a: str = "a value" b: str = "b value" test = Test() def ...
This example shows only a name, type and value, however, __dataclass_fields__ is a dict of Field objects, each containing information such as name, type, default value, etc. Using dataclasses.fields() Using dataclasses.fields() you can access fields you defined in your dataclass. fields = dataclasses.fields(dataclass_i...
17
27
73,176,563
2022-7-30
https://stackoverflow.com/questions/73176563/python-polars-join-on-column-with-greater-or-equal
I have two polars dataframe, one dataframe df_1 with two columns start and end the other dataframe df_2 one with a column dates and I want to do a left join on df_2 under the condition that the dates column is in between the start and end column. To make it more obvious what I want to do here is an example DATA import ...
(I'm going to assume that your intervals in df_1 do not overlap for a particular id - otherwise, there may not be a unique value that we can assign to the id/dates combinations in df_2.) One way to do this is with join_asof. The Algorithm ( df_2 .sort("dates") .join_asof( df_1.sort("start"), by="id", left_on="dates", r...
4
4
73,212,628
2022-8-2
https://stackoverflow.com/questions/73212628/retrieve-date-from-datetime-column-in-polars
Currently when I try to retrieve date from a polars datetime column, I have to write something similar to: import polars as pl import datetime as dt df = pl.DataFrame({ 'time': [dt.datetime.now()] }) df = df.with_columns( pl.col("time").map_elements(lambda x: x.date()).alias("date") ) shape: (1, 2) ┌──────────────────...
You can use .dt.date() import datetime import polars as pl df = pl.DataFrame({ "time": [datetime.datetime.now()] }) df.with_columns( pl.col("time").dt.date().alias("date") ) shape: (1, 2) ┌────────────────────────────┬────────────┐ │ time ┆ date │ │ --- ┆ --- │ │ datetime[μs] ┆ date │ ╞════════════════════════════╪═══...
14
17
73,187,905
2022-8-1
https://stackoverflow.com/questions/73187905/shuffling-two-2d-tensors-in-pytorch-and-maintaining-same-order-correlation
Is it possible to shuffle two 2D tensors in PyTorch by their rows, but maintain the same order for both? I know you can shuffle a 2D tensor by rows with the following code: a=a[torch.randperm(a.size()[0])] To elaborate: If I had 2 tensors a = torch.tensor([[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3]]) b = torch....
You can use the function torch.randperm to get a set of indices that act as a random permutation. The following is a small example of getting a random permutation, then applying it to both the a and b tensors: indices = torch.randperm(a.size()[0]) a=a[indices] b=b[indices]
4
8
73,191,533
2022-8-1
https://stackoverflow.com/questions/73191533/using-conftest-py-vs-importing-fixtures-from-dedicate-modules
I have been familiarizing with pytest lately and on how you can use conftest.py to define fixtures that are automatically discovered and imported within my tests. It is pretty clear to me how conftest.py works and how it can be used, but I'm not sure about why this is considered a best practice in some basic scenarios....
There's not a huge amount of difference, it's mainly just down to preference. I mainly use conftest.py to pull in fixures that are required, but not directly used by your test. So you may have a fixture that does something useful with a database, but needs a database connection to do so. So you make the db_connection f...
16
14
73,154,451
2022-7-28
https://stackoverflow.com/questions/73154451/configure-vscode-to-autocomplete-from-two-python-projects
I have read and tried a lot but am still struggeling with correctly configuring IntelliSense, ie, VSCode's autocomplete for my Python projects. It works fine within a single Python project. But I have a workspace with two of my projects open at the same time since one of them is imported and used inside the other. For ...
it wasn't working for me until i added the path to "python.analysis.extraPaths" as well: "python.analysis.extraPaths": [ "path\\to\\directory" ], "python.autoComplete.extraPaths": [ "path\\to\\directory" ]
4
7
73,198,957
2022-8-1
https://stackoverflow.com/questions/73198957/how-to-exclude-optional-unset-values-from-a-pydantic-model-using-fastapi
I have this model: class Text(BaseModel): id: str text: str = None class TextsRequest(BaseModel): data: list[Text] n_processes: Union[int, None] So I want to be able to take requests like: {"data": ["id": "1", "text": "The text 1"], "n_processes": 8} and {"data": ["id": "1", "text": "The text 1"]}. Right now in the ...
Since Pydantic >= 2.0 deprecates model.dict() use model.model_dump(...) instead. You can use exclude_none param of Pydantic's model.dict(...): class Text(BaseModel): id: str text: str = None class TextsRequest(BaseModel): data: list[Text] n_processes: Optional[int] request = TextsRequest(**{"data": [{"id": "1", "text"...
14
5
73,200,382
2022-8-1
https://stackoverflow.com/questions/73200382/using-typevartuple-with-inner-typevar-variadic-generics-transformation
How would I use TypeVarTuple for this example? T = TypeVar("T") Ts = TypeVarTuple("Ts") @dataclass class S(Generic[T]): data: T def data_from_s(*structs: ??) -> ??: return tuple(x.data for x in structs) a = data_from_s(S(1), S("3")) # is type tuple[int, str]
I don't see any way to do this with the current spec. The main issue I see is that TypeVarTuple does not support bounds. You can't constrain the types referred to by Ts to be bounded to S. You need to translate somehow tuple[S[T1], S[T2], ...] -> tuple[T1, T2, ...], but you have no way to know that the types contained ...
5
4
73,132,769
2022-7-27
https://stackoverflow.com/questions/73132769/what-is-the-right-way-to-get-unit-vector-to-index-elasticsearch-ann-dot-product
I am trying to index word embedding vectors to Elasticsearch V8 ann dense_vector dot_product. I can successfully index vec to cosine, so I converted it to unit vector with numpy for dot_product. unit_vector = vec / np.linalg.norm(vec) but I get an 400 error saying like this. The [dot_product] similarity can only be u...
I was confronted with the exact same problem and I found a solution after much experimentation. In my case, when indexing lots of embeddings to Elasticsearch (dense_vector with similarity parameter set to dot_product), most of them got indexed properly and a small percentage of them failed with The [dot_product] simila...
4
5
73,144,451
2022-7-27
https://stackoverflow.com/questions/73144451/modulenotfounderror-no-module-named-setuptools-command-build
I am trying to pip install sentence transformers. I am working on a Macbook pro with an M1 chip. I am using the following command: pip3 install -U sentence-transformers When I run this, I get this error/output and I do not know how to fix it... Defaulting to user installation because normal site-packages is not write...
I posted this as an issue to the actual Sentence Transformers GitHub page. Around 4 days ago I was given this answer by a "Federico Viticci" which resolved the issue and allowed me to finally install the library: "For what it is worth, I was having the exact issue. Installing it directly from source using pip install g...
10
0
73,143,854
2022-7-27
https://stackoverflow.com/questions/73143854/linking-opencv-python-to-opencv-cuda-in-arch
I'm trying to to get OpenCV with CUDA to be used in Python open-cv on Arch Linux, but I'm not sure how to link it. Arch provides a package opencv-cuda, which provides these files. Guides I've found said to link the python cv2.so to the one provided, but the package doesn't provide that. My python site_packages has cv2....
On Arch, opencv-cuda provides opencv=4.6.0, but you still need the python bindings. Fortunately though, installing python-opencv after installling opencv-cuda works, since it leverages it. I just set up my Python virtual environment to allow system site packages (python -m venv .venv --system-site-packages), and it wor...
6
6
73,165,109
2022-7-29
https://stackoverflow.com/questions/73165109/what-is-the-type-of-sum
I want to express that the first parameter is a "list" of the second parameter, and that the result has the same type as the second parameter. This mysum (ie. not the standard lib sum) should work equally well with int/float/str/list, and any other type that supports +=. Naively: def mysum(lst: list[T], start: T) -> T:...
You can make a generic type bound to a protocol that supports __add__ instead: Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types from typing import TypeVar, Protocol T = TypeVar('T', bound='Addable') class Addable(Protocol): def __add__(self: T, other: T) -> T...
4
7
73,212,759
2022-8-2
https://stackoverflow.com/questions/73212759/append-rows-to-dataset-if-missing-from-declared-dictionary-in-python
I have a dataset where I would like to add or append rows with values listed in dictionary (if these values are missing from original dataset) Data ID Date Type Cost Alpha Q1 2022 ok 1 Alpha Q2 2022 ok 1 Alpha Q3 2022 hi 1 Alpha Q4 2022 hi 2 Desired ID Date Type Cost Alpha Q1 2022 ok 1 Alpha Q2 2022 ok 1 Alpha Q3 2022...
Let us create a delta dataframe from the items of dictionary, then do a outer merge to append distinct rows delta = pd.DataFrame(values.items(), columns=['ID', 'Date']) df.merge(delta, how='outer') ID Date Type Cost 0 Alpha Q1 2022 ok 1.0 1 Alpha Q2 2022 ok 1.0 2 Alpha Q3 2022 hi 1.0 3 Alpha Q4 2022 hi 2.0 4 Gamma Q...
4
4
73,203,318
2022-8-2
https://stackoverflow.com/questions/73203318/how-to-transform-spark-dataframe-to-polars-dataframe
I wonder how i can transform Spark dataframe to Polars dataframe. Let's say i have this code on PySpark: df = spark.sql('''select * from tmp''') I can easily transform it to pandas dataframe using .toPandas. Is there something similar in polars, as I need to get a polars dataframe for further processing?
Context Pyspark uses arrow to convert to pandas. Polars is an abstraction over arrow memory. So we can hijack the API that spark uses internally to create the arrow data and use that to create the polars DataFrame. TLDR Given an spark context we can write: import pyarrow as pa import polars as pl sql_context = SQLConte...
14
36
73,204,179
2022-8-2
https://stackoverflow.com/questions/73204179/how-to-scrape-video-media-with-scrapy-or-other-pythons-libraries
Concretely I want to extract videos from this website: equidia. The first problem is when I launch scrapy shell https://www.equidia.fr/courses/2022-07-31/R1/C1 -s USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36". I inspected with view(respo...
Here is a fully working solution by using scrapy-playwright, I got the idea the following issue 61 and the users profile @lime-n. We download the xhr requests sent and store these into a dict with both the playwright tools and scrapy-playwright. I include the playwright_page_event_handlers to integrate playwright tools...
6
1
73,195,338
2022-8-1
https://stackoverflow.com/questions/73195338/how-to-avoid-database-connection-pool-from-being-exhausted-when-using-fastapi-in
I use FastAPI for a production application that uses asyncio almost entirely except when hitting the database. The database still relies on synchronous SQLAlchemy as the async version was still in alpha (or early beta) at the time. While our services do end up making synchronous blocking calls when it hits the database...
Fastapi uses Starlette as an underlying framework. Starlette provides a mechanism for starting def path operations in the thread pool for which it uses anyio. Therefore, we can limit the number of threads which can be executed simultaneously by setting property total_tokens of anyio's CapacityLimiter. Example below: im...
6
7
73,209,565
2022-8-2
https://stackoverflow.com/questions/73209565/strange-behaviour-during-multiprocess-calls-to-numpy-conjugate
The attached script evaluates the numpy.conjugate routine for varying numbers of parallel processes on differently sized matrices and records the corresponding run times. The matrix shape only varies in it's first dimension (from 1,64,64 to 256,64,64). Conjugation calls are always made on 1,64,64 sub matrices to ensure...
The problem is due to at least a combination of two complex effects: cache-thrashing and frequency-scaling. I can reproduce the effect on my 6 core i5-9600KF processor. Cache thrashing The biggest effect comes from a cache-thrashing issue. It can be easily tracked by looking at the RAM throughput. Indeed, it is 4 GiB/...
5
2
73,166,250
2022-7-29
https://stackoverflow.com/questions/73166250/why-does-a-recursive-python-program-not-crash-my-system
I've written an R.py script which contains the following two lines: import os os.system("python3 R.py") I expected my system to run out of memory after running this script for a few minutes, but it is still surprisingly responsive. Does someone know, what kind of Python interpreter magic is happening here?
Preface os.system() is actually a call to C’s system(). Here is what the documentation states: The system() function shall behave as if a child process were created using fork(), and the child process invoked the sh utility using execl() as follows: execl(, "sh", "-c", command, (char *)0); where is an unspecified path...
7
3
73,157,370
2022-7-28
https://stackoverflow.com/questions/73157370/pyspark-to-azure-sql-database-connection-issue
I'm trying to connect to Azure SQL Database from Azure Synapse workspace Notebook using PySpark. Also I would like to use Active Directory integrated authentication. So what I've tried: jdbc_df = spark.read \ .format("com.microsoft.sqlserver.jdbc.spark") \ .option("url", "jdbc:sqlserver://my_server_name.database.window...
Finally I have found the solution! First of all there should be created working Linked service to Azure SQL database in your Synapse Analytics that uses Authentication type "System Assigned Managed Identity". Than you can reference it in your PySpark Notebook. And don't be confused that method getConnectionString is us...
4
4
73,205,546
2022-8-2
https://stackoverflow.com/questions/73205546/spacy-how-not-to-remove-not-when-cleaning-the-text-with-space
I use this spacy code to later apply it on my text, but i need the negative words to stay in the text like "not". nlp = spacy.load("en_core_web_sm") def my_tokenizer(sentence): return [token.lemma_ for token in tqdm(nlp(sentence.lower()), leave = False) if token.is_stop == False and token.is_alpha == True and token.lem...
"not" is actually a stop word and in your code if a token is removed if it's a stopword. You can see this either by looking at the list of Spacy stopwords "not" in spacy.lang.en.stop_words.STOP_WORDS or by looping over the tokens of your doc object for tok in nlp(text.lower()): print(tok.text, tok.is_stop, tok.lemma_...
4
4
73,206,939
2022-8-2
https://stackoverflow.com/questions/73206939/heroku-postgres-postgis-django-releases-fail-with-relation-spatial-ref-sys
Heroku changed their PostgreSQL extension schema management on 01 August 2022. (https://devcenter.heroku.com/changelog-items/2446) Since then every deployment to Heroku of our existing django 4.0 application fails during the release phase, the build succeeds. Has anyone experienced the same issue? Is there a workaround...
I've worked around it by overwriting the postgis/base.py engine, I've put the following in my app under db/base.py from django.contrib.gis.db.backends.postgis.base import ( DatabaseWrapper as PostGISDatabaseWrapper, ) class DatabaseWrapper(PostGISDatabaseWrapper): def prepare_database(self): # This is the overwrite - w...
32
3
73,212,039
2022-8-2
https://stackoverflow.com/questions/73212039/pyside6-app-crashes-when-using-qpainter-drawline
On Windows 10, python3.10, PySide6 (or PyQt6) QApplication crashes when calling QPainter.drawLine() . The terminal just displays : Process finished with exit code -1073741819 (0xC0000005) Please find below the code: import sys from PySide6.QtCore import QPoint, Qt from PySide6.QtGui import QColor, QPainter, QPen, QPi...
This is caused by a slight (and not well documented) change in the API that happened starting with Qt5.15. Until Qt5, pixmap() returned a direct pointer to the current pixmap of the label, while in Qt6 it returns an implicit copy of the pixmap. The difference is highlighted only for the latest Qt5 documentation of the ...
4
2
73,206,785
2022-8-2
https://stackoverflow.com/questions/73206785/logging-snakemakes-own-console-output-how-to-change-what-file-snakemake-logs
I'm trying to save Snakemake's own console output (not the logs generated by the individual jobs) to an arbitrary file while still having it written to stdout/stderr. (Unfortunately, my setup means I can't just use tee.) It looks to me like Snakemake should provide that functionality, given it saves the log output to ...
The file name/path is hardcoded in setup_logfile. It's a hack, but one option is to copy the log file to the desired location using onsuccess/onerror (note that there is no oncompletion, so the log copying should probably apply to both cases): onsuccess: shell("cp -v {log} some_path_for_log_copy.log") onerror: shell("c...
4
4
73,200,080
2022-8-1
https://stackoverflow.com/questions/73200080/assign-line-a-color-by-its-angle-in-matplotlib
I'm looking for a way to assign color to line plots in matplotlib in a way that's responsive to the line's angle. This is my current code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline horz = [[0.5,0.6,0.8],[0.1,0.8,0.9],[0.2,0.5,0.9]] vert = [[0.1,0.2,0.3],[0.05,0.1,0.15],[0.2,0.3,0.35]] f = pl...
Managed to solve it myself. Used pretty simple formulas for calculating the lines' slopes and distances and then used these as input for the color mapping and alpha transparency attribute. import geopandas as gpd import pandas as pd import matplotlib.pyplot as plt from matplotlib import cm import matplotlib.colors as c...
5
1
73,199,376
2022-8-1
https://stackoverflow.com/questions/73199376/requestsdependencywarning-urllib3-1-26-11-or-chardet-3-0-4-doesnt-match-a
I have this script to acess my internet modem and reboot the device, but stop to work some weeks ago. Here my code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager service ...
This error message... /usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.11) or chardet (3.0.4) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " ...implies that the requests module is backdated hence not in sync and...
10
23
73,206,810
2022-8-2
https://stackoverflow.com/questions/73206810/faker-python-generating-chinese-pinyin-names
I am trying to generate random chinese names using Faker (Python), but it generates the names in chinese characters instead of pinyin. I found this : and it show that it generates them in pinyin, while when I try the same code, it gives me only chinese characters. how to get the pinyin ??
fake.romanized_name() worked for me. I got lucky by looking through dir(fake). Doesn't seem to have a method for pinyin address that I can see...
6
4
73,202,494
2022-8-2
https://stackoverflow.com/questions/73202494/how-do-i-type-hint-a-function-that-returns-a-zip-object
I've got a function that takes an arbitrary amount of lists (or any iterables, for that matter) and sorts them as one. The code looks like this: def sort_as_one(*args): return zip(*sorted(zip(*args))) def main(): list1 = [3, 1, 2, 4] list2 = ["a", "b", "d", "e"] list3 = [True, False, True, False] result = sort_as_one(l...
A zip object is an iterator - it follows the iterator protocol. Idiomatically, you would probably just typing hint it as such. In this case, you want to type hint it as a generic using a type variable: import typing T = typing.TypeVar("T") def sort_as_one(*args: T) -> typing.Iterator[T]: return zip(*sorted(zip(*args)))...
5
7
73,200,378
2022-8-1
https://stackoverflow.com/questions/73200378/typeerror-float-argument-must-be-a-string-or-a-number-not-natype
I have a column in my dataframe that contains nan values and int values. The original dType was float64, but I was trying to change it to int6, and change nan values to np.nan. now I get this error: TypeError: float() argument must be a string or a number, not 'NAType' when trying to run imputation on it. In the follow...
Use df['age'] = df['age'].astype(dtype='Int64') with extension datatype Int64 (with a capitalized I) rather than the default dtype which is int64 (lower case i). The latter throws an IntCastingNaNError while the former works smoothly. This functionality was added to Pandas 0.24 and mentioned in this thread.
8
7
73,198,894
2022-8-1
https://stackoverflow.com/questions/73198894/which-magic-method-does-hasattr-call
Which magic method method does hasattr call? getattr(__o, name) can also be called as __o.__getattr__(name) setattr(__o, name) can also be called as __o.__setattr__(name) But what is the equivalent for hasattr? I know the associated magic method for the in keyword is __contains__.
There is no specific dunder method for hasattr(). It's essentially equivalent to: def hasattr(object, name): try: getattr(object, name) return True except AttributeError: return False So it's dependent on the same dunder methods used by getattr().
5
5
73,186,539
2022-7-31
https://stackoverflow.com/questions/73186539/dynamic-enum-values-on-nested-classes-with-python
Consider the following enum class: from enum import Enum class Namespace: class StockAPI(Enum): ITEMS = "{url}/items" INVENTORY = "{url}/inventory" class CustomerAPI(Enum): USERS = "{url}/users" PURCHASES = "{url}/purchases" def __init__(self, url): self.url = url I am trying to make url a dynamic value for each enum ...
I did it the following way, while keeping the inner enum classes: from enum import Enum class Namespace: class StockAPI(Enum): ITEMS = "{url}/items" INVENTORY = "{url}/inventory" class CustomerAPI(Enum): USERS = "{url}/users" PURCHASES = "{url}/purchases" def __init__(self, url: str): attrs = (getattr(self, attr) for a...
4
4
73,183,974
2022-7-31
https://stackoverflow.com/questions/73183974/how-to-get-a-class-and-definitions-diagram-from-python-code
I have a large multi-file Python application I'd like to document graphically. But first, I made a small "dummy" app to test out different UML packages. (Note: I do have graphviz installed and in the path). Here's my "dummy" code: class User: def __init__(self, level_security=0): self.level_security = level_security de...
pyreverse aims to produce a class diagram. It will show you classes, and non-filtered class members (see option -f), as well as associations that can be detected. In this regard, the diagram seems complete. Instances (objects) at top level are not part of a class diagram. This is why pyreverse doesn't show them. Free s...
4
3
73,195,438
2022-8-1
https://stackoverflow.com/questions/73195438/openai-gyms-env-step-what-are-the-values
I am getting to know OpenAI's GYM (0.25.1) using Python3.10 with gym's environment set to 'FrozenLake-v1 (code below). According to the documentation, calling env.step() should return a tuple containing 4 values (observation, reward, done, info). However, when running my code accordingly, I get a ValueError: Problemati...
From the code's docstrings: Returns: observation (object): this will be an element of the environment's :attr:`observation_space`. This may, for instance, be a numpy array containing the positions and velocities of certain objects. reward (float): The amount of reward returned as a result of taking the action. termin...
18
6
73,191,999
2022-8-1
https://stackoverflow.com/questions/73191999/when-to-use-prepare-data-vs-setup-in-pytorch-lightning
Pytorch's docs on Dataloaders only say, in the code def prepare_data(self): # download ... and def setup(self, stage: Optional[str] = None): # Assign train/val datasets for use in dataloaders Please explain the intended separation between prepare_data and setup, what callbacks may occur between them, and why put some...
If you look at the pseudo for the Trainer.fit function provided in the documentation page of LightningModule at § Hooks, you can read: def fit(self): if global_rank == 0: # prepare data is called on GLOBAL_ZERO only prepare_data() ## <-- prepare_data configure_callbacks() with parallel(devices): # devices can be GPUs, ...
4
6
73,179,592
2022-7-30
https://stackoverflow.com/questions/73179592/show-a-dataframe-with-all-rows-that-have-null-values
I am new to pyspark and using Dataframes what I am trying to do is get the subset of all the columns with Null value(s). Most examples I see online show me a filter function on a specific column. Is it possible to filter the entire data frame and show all the rows that contain at least 1 null value?
If you don't care about which columns are null, you can use a loop to create a filtering condition: from pyspark.sql import SparkSession from pyspark.sql import functions as func q1_df = spark\ .createDataFrame([(None, 1, 2), (3, None, 4), (5, 6, None), (7, 8, 9)], ['a', 'b', 'c']) q1_df.show(5, False) +----+----+----+...
4
3
73,186,315
2022-7-31
https://stackoverflow.com/questions/73186315/openai-command-not-found-mac
I'm trying to follow the fine tuning guide for Openai here. I ran: pip install --upgrade openai Which install without any errors. But even after restarting my terminal, i still get zsh: command not found: openai Here is the output of echo $PATH: /bin:/usr/bin:/usr/local/bin:/Users/nickrose/Downloads/google-cloud-sdk/...
Basically pip installs the packages under its related python directory, in a directory called site-packages (most likely, I'm not a python expert tbh). This is not included in the path you provided. First, ask pip to show the location to the package: pip show openai The output would be something like this: Name: opena...
6
7
73,183,197
2022-7-31
https://stackoverflow.com/questions/73183197/opencv-not-installing-on-anaconda-prompt
In order to download OpenCV on through Anaconda prompt, I run the following: conda install -c conda-forge opencv However, whenever I try to download, there I get the messages of failed with initial frozen solve. Retrying with flexible solve. Failed with repodata from current_repodata.json, will retry with next repodata...
Please note that to import cv2, the library/package to install is called opencv-python. From Jupyter notebook, you can try !pip install opencv-python If you're using anaconda, you can try conda install -c conda-forge opencv-python
5
4
73,176,562
2022-7-30
https://stackoverflow.com/questions/73176562/how-to-load-a-zip-file-with-pyscript-and-save-into-the-virtual-file-system
I am trying to load a zip file and save it in the virtual file system for further processing with pyscript. In this example, I aim to open it and list its content. As far as I got: See the self standing html code below, adapted from tutorials (with thanks to the author, btw) It is able to load Pyscript, lets the user s...
You were very close with your code. The problem was in converting the file data to the correct data type. The requirement is to convert the arrayBuffer to Uint8Array and then to a bytearray. Import the required function: from js import Uint8Array Read the file data into an arrayBuffer and copy it to a new Uint8Array d...
4
4
73,177,807
2022-7-30
https://stackoverflow.com/questions/73177807/unable-to-build-vocab-for-a-torchtext-text-classification
I'm trying to prepare a custom dataset loaded from a csv file in order to use in a torchtext text binary classification problem. It's a basic dataset with news headlines and a market sentiment label assigned "positive" or "negative". I've been following some online tutorials on PyTorch to get this far but they've made ...
The very small length of vocabulary is because under the hood, build_vocab_from_iterator uses a Counter from the Collections standard library, and more specifically its update function. This function is used in a way that assumes that what you are passing to build_vocab_from_iterator is an iterable wrapping an iterable...
4
3
73,176,227
2022-7-30
https://stackoverflow.com/questions/73176227/how-to-get-first-element-of-list-or-none-when-list-is-empty
I can do it like this but there has to be better way: arr = [] if len(arr) > 0: first_or_None = arr[0] else: first_or_None = None If I just do arr[0] I get IndexError. Is there something where I can give default argument?
I think the example you give is absolutely fine - it is very readable and would not suffer performance issues. You could use the ternary operator python equivalent, if you really want it to be shorter code: last_or_none = arr[0] if len(arr) > 0 else None
6
12
73,170,578
2022-7-29
https://stackoverflow.com/questions/73170578/python-code-blocks-not-rendering-with-readthedocs-and-sphinx
I'm building docs for a python project using Sphinx and readthedocs. For some reason, the code blocks aren't rendering after building the docs, and inline code (marked with backticks) appears italic. I've checked the raw build, there was a warning that the exomagpy module couldn't be found which I resolved by changing ...
As @mzjn pointed out, a blank line is required between the code-block directive and the code that is supposed to be highlighted. https://raw.githubusercontent.com/quasoph/exomagpy/main/docs/tutorials.rst .. code-block:: python import exomagpy.predictExo exomagpy.predictExo.tess() exomagpy.predictExo.kepler() Additiona...
5
4
73,172,760
2022-7-30
https://stackoverflow.com/questions/73172760/github-action-couldnt-find-environment-variable-for-django
I was trying to use the environment variable in my Django application where I use the django-environ package with the .env file in my local machine. But I can't use the .env file in my GitHub action. I've configured action secret variables manually from my project settings. Here is my local machine code: import environ...
You need to configure env for your run step, something like this: - name: Run Tests run: | python manage.py test env: POSTGRES_DB_NAME: ${{ secrets.POSTGRES_DB_NAME }} POSTGRES_USER: ${{ secrets.POSTGRES_USER }} POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }} POSTGRES_PO...
4
3
73,170,302
2022-7-29
https://stackoverflow.com/questions/73170302/ordinal-encoding-in-pandas
Is there a way to have pandas.get_dummies output the numerical representation in one column rather than a separate column for each option? Concretely, currently when using pandas.get_dummies it gives me a column for every option: Size Size_Big Size_Medium Size_Small Big 1 0 0 Medium 0 1 0 Small 0 0 1 Bu...
You don't want dummies, you want factors/categories. Use pandas.factorize: df['Size_Numerical'] = pd.factorize(df['Size'])[0] + 1 output: Size Size_Numerical 0 Big 1 1 Medium 2 2 Small 3
4
9
73,162,991
2022-7-29
https://stackoverflow.com/questions/73162991/can-i-disable-mypys-cannot-find-implementation-or-library-stub-for-module-name
There are many threads regarding Cannot find implementation or library stub for module named... error, but there's no associated error code. I'd like to disable this completely. How might I go about doing that?
To disable the warning: Pass the --ignore-missing-imports flag on the CLI. Or if using a config file: For mypy.ini or setup.cfg [mypy] ignore_missing_imports = true For pyproject.toml [tool.mypy] ignore_missing_imports = true This will disable warning for all modules. You can set it on a per module basis, but you'll ...
4
11
73,166,964
2022-7-29
https://stackoverflow.com/questions/73166964/python-3-match-values-based-on-column-name-similarity
I have a dataframe of the following form: Year 1 Grade Year 2 Grade Year 3 Grade Year 4 Grade Year 1 Students Year 2 Students Year 3 Students Year 4 Students 60 70 80 100 20 32 18 25 I would like to somehow transpose this table to the following format: Year Grade Students 1 60 20 2 70 32 3 80 18...
Here's one way to do it. Feel free to ask questions about how it works. import pandas as pd cols = ["Year 1 Grade", "Year 2 Grade", "Year 3 Grade" , "Year 4 Grade", "Year 1 Students", "Year 2 Students", "Year 3 Students", "Year 4 Students"] vals = [60,70,80,100,20,32,18,25] vals = [[v] for v in vals] df = pd.DataFrame(...
4
1
73,165,967
2022-7-29
https://stackoverflow.com/questions/73165967/how-to-suppress-a-warning-in-one-line-for-pylint-and-flake8-at-the-same-time
I would like to ignore a specific line in static code analysis. For Flake8, I'd use the syntax # noqa: F401. For pylint, I'd use the syntax # pylint: disable=unused-import. As I am working on a code generation framework, I would like the code to support both linters. Is there a way to combine both directives such that ...
both of these combinations work for me: import os # noqa: F401 # pylint:disable=unused-import import sys # pylint:disable=unused-import # noqa: F401
14
21
73,166,298
2022-7-29
https://stackoverflow.com/questions/73166298/cant-do-python-imports-from-another-dir
I'm unable to import from Python file in another directory. Directory structure: some_root/ - __init__.py - dir_0/ - __init__.py - dir_1/ - __init__.py - file_1.py - dir_2/ - __init__.py - file_2.py file_1.py has some exported member: # file_1.py def foo(): pass file_2.py tries to import member from file_1.py: # file...
Don't mess with the search path You are right not messing around with sys.path. This is not recommended and always just an ugly workaround. There are better solutions for this. Restructure your folder layout See official Python docs about packaging. Distinguish between project folder and package folder. We assume your ...
5
5
73,165,636
2022-7-29
https://stackoverflow.com/questions/73165636/no-module-named-importlib-metadata
I'm trying to install Odoo 15.0 on mac (python 3.7) when i come to run the command: pip3 install -r requirements.txt I got this error message: Traceback (most recent call last): File "/usr/local/opt/python@3.7/bin/pip3", line 10, in <module> from importlib.metadata import distribution ModuleNotFoundError: No module na...
Try installing this lib manually, using : pip install importlib-metadata or pip3 install importlib-metadata
13
20
73,164,169
2022-7-29
https://stackoverflow.com/questions/73164169/multiplying-a-list-of-integer-with-a-list-of-string
Suppose there are two lists: l1 = [2,2,3] l2 = ['a','b','c'] I wonder how one finds the product of the two such that the output would be: #output: ['a','a','b','b','c','c','c'] if I do: l3 = [] for i in l2: for j in l1: l3.append(i) I get: ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'] which is wrong, I wonder where...
The loop for j in l1: will iterate 3 times every time (because you have 3 items in list l1). Try: out = [b for a, b in zip(l1, l2) for _ in range(a)] print(out) Prints: ['a', 'a', 'b', 'b', 'c', 'c', 'c']
5
4
73,136,808
2022-7-27
https://stackoverflow.com/questions/73136808/aws-glue-error-invalid-input-provided-while-running-python-shell-program
I have Glue job, a python shell code. When I try to run it I end up getting the below error. Job Name : xxxxx Job Run Id : yyyyyy failed to execute with exception Internal service error : Invalid input provided It is not specific to code, even if I just put import boto3 print('loaded') I am getting the error right aft...
I think Quatermass is right, the jobs started working out of the blue the next day without any changes.
6
2
73,159,836
2022-7-28
https://stackoverflow.com/questions/73159836/vectorized-way-to-contract-numpy-array-using-advanced-indexing
I have a Numpy array of dimensions (d1,d2,d3,d4), for instance A = np.arange(120).reshape((2,3,4,5)). I would like to contract it so as to obtain B of dimensions (d1,d2,d4). The d3-indices of parts to pick are collected in an indexing array Idx of dimensions (d1,d2). Idx provides, for each couple (x1,x2) of indices alo...
Times for 3 alternatives: In [91]: %%timeit ...: B = np.zeros((2,3,5),A.dtype) ...: for i in range(2): ...: for j in range(3): ...: B[i,j,:] = A[i,j,Idx[i,j],:] ...: 11 µs ± 48.8 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) In [92]: timeit A[np.arange(2)[:,None],np.arange(3),Idx] 8.58 µs ± 44 ns per loo...
4
2
73,160,583
2022-7-29
https://stackoverflow.com/questions/73160583/difference-between-filter-and-where-in-sqlalchemy
I've seen a few variations of running a query with SQLAlchemy. For example, here is one version: posts = db.query(models.Post).filter(models.Post.owner_id==user.id).all() What would be the difference between using the above or using .where? Why are there two variations here?
According to the documentation, there is no difference. method sqlalchemy.orm.Query.where(*criterion) A synonym for Query.filter(). It was added in version 1.4 by this commit. According to the commit message the reason to add it was to Convert remaining ORM APIs to support 2.0 style. You can read more about "2.0 styl...
17
30
73,155,924
2022-7-28
https://stackoverflow.com/questions/73155924/inheritance-subclassing-issue-in-pydantic
I came across a code snippet for declaring Pydantic Models. The inheritance used there has me confused. class RecipeBase(BaseModel): label: str source: str url: HttpUrl class RecipeCreate(RecipeBase): label: str source: str url: HttpUrl submitter_id: int class RecipeUpdate(RecipeBase): label: str I am not sure what's ...
I’d say it is an oversight from the tutorial. There is no benefit and only causes confusion. Typically, Base is used for all overlapping fields, and they are only overloaded when they change type (for example, XyzBase has name: str whereas XyzCreate has name: str|None because it doesn’t has to be provided when updating...
9
6
73,157,702
2022-7-28
https://stackoverflow.com/questions/73157702/attributeerror-tuple-object-has-no-attribute-sort
Here is my code, and i am getting an AttributeError: 'tuple' object has no attribute 'sort. I am trying to do an image alignment and found this standard image alignment code in an article. I am learning openCV and python which i am really new too, I am able to do basic stuff with openCV right now i am trying to learn i...
You're getting a tuple returned, not a list. You can't just matches.sort(...) that. OpenCV, since v4.5.4, exhibits this behavior in its Python bindings generation. You have to use this instead: matches = sorted(matches, ...) This creates a new list, which contains the sorted elements of the original tuple. Related iss...
4
4
73,157,383
2022-7-28
https://stackoverflow.com/questions/73157383/how-do-you-create-a-fully-fledged-python-package
When creating a Python package, you can simply write the code, build the package, and share it on PyPI. But how do you do that? How do you create a Python package? How do you publish it? And then, what if you want to go further? How do you set up CI/CD for it? How do you test it and check code coverage? How do you l...
Preamble When you've published dozens of packages, you know how to answer these questions in ways that suit your workflow(s) and taste. But answering these questions for the first time can be quite difficult, time consuming, and frustrating! That's why I spent days researching ways of doing these things, which I then p...
6
8
73,155,460
2022-7-28
https://stackoverflow.com/questions/73155460/how-to-get-the-cookies-from-an-http-request-using-fastapi
Is it possible to get the cookies when someone hits the API? I need to read the cookies for each request. @app.get("/") async def root(text: str, sessionKey: str = Header(None)): print(sessionKey) return {"message": text+" returned"} if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=5001 ,reload=T...
You can do it in the same way you are accessing the headers in your example (see docs): from fastapi import Cookie @app.get("/") async def root(text: str, sessionKey: str = Header(None), cookie_param: int | None = Cookie(None)): print(cookie_param) return {"message": f"{text} returned"}
11
2
73,151,382
2022-7-28
https://stackoverflow.com/questions/73151382/how-to-interperet-the-num-layers-line-when-using-keras-tuner
I'm reading an article about tuning hyperparameters in keras tuner. It includes code to build a model that has this code: def build_model(hp): """ Builds model and sets up hyperparameter space to search. Parameters ---------- hp : HyperParameter object Configures hyperparameters to tune. Returns ------- model : keras m...
If you see the docs, the 2 and 6 are referring to the min and max values respectively. Also note: [...] max_value is included in the possible values this parameter can take on So this line: for i in range(1, hp.Int("num_layers", 2, 6)): basically means: generate a x number of Dense layers, where x is between 1 and 5...
5
3
73,146,024
2022-7-28
https://stackoverflow.com/questions/73146024/sqlalchemy-method-to-get-orm-object-as-dict
Take the following code: from sqlalchemy import create_engine from sqlalchemy.orm import declarative_base from sqlalchemy import Column, Integer, String engine = create_engine('postgresql://postgres:password@localhost:5432/db', echo=True, echo_pool='debug') Base = declarative_base() class Item(Base): __tablename__ = 'i...
Here would be one way to do it: class MyBase(Base): __abstract__ = True def to_dict(self): return {field.name:getattr(self, field.name) for field in self.__table__.c} class Item(MyBase): # as before item = Item(name="computer") item.to_dict() # {'id': None, 'name': 'computer'} Also, a lot of these usability simplifica...
7
12
73,144,724
2022-7-27
https://stackoverflow.com/questions/73144724/python-vs-c-precision
I am trying to reproduce a C++ high precision calculation in full python, but I got a slight difference and I do not understand why. Python: from decimal import * getcontext().prec = 18 r = 0 + (((Decimal(0.95)-Decimal(1.0))**2)+(Decimal(0.00403)-Decimal(0.00063))**2).sqrt() # r = Decimal('0.0501154666744709107') C++:...
The origin of the discrepancy is that Python Decimal follows the more modern IBM's General Decimal Arithmetic Specification. In C++ however there too exist support available for 80-bit "extended precision" through the long double format. For reference, the standard IEEE-754 floating point doubles contain 53 bits of pre...
4
4
73,141,350
2022-7-27
https://stackoverflow.com/questions/73141350/override-global-dependency-for-certain-endpoints-in-fastapi
I have a FastAPI server that communicates with a web app. My web app also has 2 types of users, Users (non-admins) and Admins. I added a global dependency to FastAPI to verify the user. I want the verify dependency to only allow Admins to access endpoints by default, and have some decorator (or something similar) to al...
You cannot have conditional global dependencies. You either have them on all endpoints of your app, or on none of them. My recommendation is to split your endpoints in two routers, and only add routes to the respective routers. Then you can add a global dependency to only one of the routers like this: from fastapi impo...
10
12