question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
76,613,542
2023-7-4
https://stackoverflow.com/questions/76613542/make-a-categorical-column-which-has-categories-a-b-c-in-polars
How do I make a Categorical column which has: elements: ['a', 'b', 'a', 'a'] categories ['a', 'b', 'c'] in polars? In pandas, I would do: In [31]: pd.Series(pd.Categorical(['a', 'b', 'a', 'a'], categories=['a', 'b', 'c'])) Out[31]: 0 a 1 b 2 a 3 a dtype: category Categories (3, object): ['a', 'b', 'c'] I have no ide...
You can use the StringCache with pl.StringCache(): pl.Series(['a', 'b', 'c'], dtype=pl.Categorical()) s = pl.Series(['a', 'b', 'a', 'a','z'], dtype=pl.Categorical()) Everything in the StringCache context will share the same index/value mapping so the first line initialized the mapping with the categories you want. The...
3
2
76,593,284
2023-7-1
https://stackoverflow.com/questions/76593284/delaunay-triangulation-of-a-fibonacci-sphere
I have generated a set of (x,y,z) coordinates on a unit sphere using the Fibonacci sphere algorithm. Plotted with a 3d scatter plot, they look alright: https://i.imgur.com/OsQo0CC.gif I now want to connect them with edges, i.e. a triangulation. As suggested in How do i draw triangles between the points of a fibonacci s...
Fixed it! The issue was that my latitudes were between 0 and pi, whereas stripy.sTriangulation expects them to be between -pi/2 and pi/2. If this happens to anyone else, just know that stripy.sTriangulation expects latitudes between -pi/2 and pi/2, and longitudes between 0 and 2pi. So check if that's what you are provi...
3
1
76,599,694
2023-7-2
https://stackoverflow.com/questions/76599694/what-is-the-fastest-way-to-append-unique-integers-to-a-list-while-keeping-the-li
I need to append values to an existing list one by one, while maintaining the following two conditions at all times: Every value in the list is unique The list is always sorted in ascending order The values are all integers, and there is a huge amount of them (literally millions, no exaggeration), and the list is d...
I like data rather than guessing so I profiled the approaches suggested by @Kelly Bundy from bisect import bisect from sortedcontainers import SortedList, SortedSet class Sorting_List: # The Original def __init__(self): self.data = [] self.unique = set() def add(self, n): if n in self.unique: return self.unique.add(n) ...
6
4
76,595,013
2023-7-1
https://stackoverflow.com/questions/76595013/assertionerror-applications-must-write-bytes-when-streaming-data-using-python
I wrote the following Python code in the app_consumer.py and tasks_consumer.py files to stream data to the consumer.html Jinja template. app_consumer.py from flask import render_template, Response, request from flask_socketio import join_room from init_consumer import app, socketio import tasks_consumer import uuid def...
You should yield only one value at a time. Such as this; yield stock yield stockStatus For more information, you can check this answer.
3
3
76,615,802
2023-7-4
https://stackoverflow.com/questions/76615802/what-are-the-tradeoffs-between-jax-lax-map-and-jax-vmap
This Github issue hints that there are tradeoffs in performance / memory / compilation time when choosing between jax.lax.map and jax.vmap. What are the specific details of these tradeoffs with respect to both GPUs and CPUs?
The main difference is that jax.vmap is a vectorizing transformation, while lax.map is an iterative transformation. Let's look at an example. Example function: vector_dot Suppose you have implemented a simple function that takes 1D vectors as inputs. For simplicity let's make it a simple dot product, but one that asser...
6
10
76,578,147
2023-6-29
https://stackoverflow.com/questions/76578147/dst-temporal-feature-from-timestamp-using-polars
I'm migrating code to polars from pandas. I have time-series data consisting of a timestamp and value column and I need to compute a bunch of features. i.e. from datetime import datetime, timedelta df = pl.DataFrame({ "timestamp": pl.datetime_range( datetime(2017, 1, 1), datetime(2018, 1, 1), timedelta(minutes=15), tim...
With polars>=0.18.5 the following works df = df.with_columns((pl.col("timestamp").dt.dst_offset()==0).cast(pl.Int32).alias("dst"))
3
3
76,582,545
2023-6-29
https://stackoverflow.com/questions/76582545/how-to-export-to-dict-some-properties-of-an-object
I have a python class which has several properties. I want to implement a method which will return some properties as a dict. I want to mark the properties with a decorator. Here's an example: class Foo: @export_to_dict # I want to add this property to dict @property def bar1(self): return 1 @property # I don't want to...
Marking each property forces to_dict to scan all methods/attributes on each invocation, which is slow and inelegant. Here's a self-contained alternative that keeps your example usage identical. Keep a list of exported properties in a class attribute By making export_to_dict a class, we can use __set_name__ (Python 3.6+...
6
2
76,612,163
2023-7-4
https://stackoverflow.com/questions/76612163/what-are-the-advantages-of-a-polars-lazyframe-over-a-dataframe
Python polars are pretty similar to Python pandas. I know in pandas we do not have Lazyframes. We can create Lazyframes just like Dataframes in polars. import polars as pl data = {"a": [1, 2, 3], "b": [5, 4, 8]} lf = pl.LazyFrame(data) I want to know what are the advantages of a Lazyframe over a Dataframe ? If someone...
I think this is very good explained at the Polars docs: With the lazy API Polars doesn't run each query line-by-line but instead processes the full query end-to-end. To get the most out of Polars it is important that you use the lazy API because: the lazy API allows Polars to apply automatic query optimization with th...
4
9
76,613,427
2023-7-4
https://stackoverflow.com/questions/76613427/fastapi-sqlalchemy-return-data-like-dictionary
Learning FastAPI and SQLAlchemy with video tutorial. In video code working correct. Code from tutorial: @router.get("/") async def get_specific_operations(operation_type: str, session: AsyncSession = Depends(get_async_session)): query = select(operation).where(operation.c.type == operation_type) result = await session....
I found a solution that helped me. Just changed "return": @router.get("/") async def get_specific_operations(operation_type: str, session: AsyncSession = Depends(get_async_session)): query = select(operation).where(operation.c.type == operation_type) result = await session.execute(query) return [dict(r._mapping) for r ...
2
2
76,594,818
2023-7-1
https://stackoverflow.com/questions/76594818/indexing-a-searchvector-vs-having-a-searchvectorfield-in-django-when-should-i-u
Clearly I have some misunderstandings about the topic. I would appreciate if you correct my mistakes. So as explained in PostgreSQL documentation, We need to do Full-Text Searching instead of using simple textual search operators. Suppose I have a blog application in Django. Entry.objects.filter(body_text__search="Chee...
I confirm that your statements are correct. Others have already brought performance-related reasons for choosing a scenario, but there are even more practical reasons. The fourth scenario, where you just have a functional index calculating the SearchVector, can almost always be used but has some limitations: the funct...
3
4
76,605,223
2023-7-3
https://stackoverflow.com/questions/76605223/fill-gaps-in-time-intervals-with-other-time-intervals
We have two tables with time intervals. I want to fill gaps in df1 with df2 as in the graph to get df3. df1 is moved to df3 as it is, and only the parts of df2 that lie in the gaps of df1 (difference) are moved to df3. df1 = pd.DataFrame({'Start': ['2023-01-01', '2023-02-01', '2023-03-15', '2023-04-18', '2023-05-15', ...
I think I can get you close: df1 = pd.DataFrame({'Start': ['2023-01-01', '2023-02-01', '2023-03-15'], 'End': ['2023-01-15', '2023-02-20', '2023-04-01']}) df2 = pd.DataFrame({'Start': ['2023-01-02', '2023-01-05', '2023-01-20', '2023-02-25', '2023-03-05'], 'End': ['2023-01-03', '2023-01-10', '2023-02-10', '2023-03-01', '...
2
3
76,613,672
2023-7-4
https://stackoverflow.com/questions/76613672/python-fastest-way-of-checking-if-there-are-more-than-x-files-in-a-folder
I am looking for a very rapid way to check whether a folder contains more than 2 files. I worry that len(os.listdir('/path/')) > 2 may become very slow if there are a lot of files in /path/, especially since this function will be called frequently by multiple processes at a time.
To get the fastest it's probably something hacky. My guess was: def iterdir_approach(path): iter_of_files = (x for x in Path(path).iterdir() if x.isfile()) try: next(iter_of_files) next(iter_of_files) next(iter_of_files) return True except: return False We create a generator and try to exhaust it, catching the thrown...
9
6
76,608,166
2023-7-3
https://stackoverflow.com/questions/76608166/how-do-i-parse-a-list-of-datetimes-with-a-s-resolution-in-pandas-2
I have a csv with a datetime column. However, dates go all the way from 1 AD to 3000 AD. They are out of range for a normal datetime64[ns] dtype. In pandas < 2, my workaround was to have this column with a "period[H]" dtype. I had a custom function doing this, which I passed as a date_parser in pd.read_csv. In pandas >...
I think unit in to_datetime only takes effect if your input is integers - but I think there is work to make it take effect even if the input is strings. Non-nanosecond support is quite new, so not yet too mature. Anyway, here's a solution which you can use until to_datetime can parse non-nanosecond range strings, which...
2
3
76,602,474
2023-7-3
https://stackoverflow.com/questions/76602474/efficient-random-subsample-of-a-pandas-dataframe-based-on-multiple-columns-targe
I am currently working on a project where I have a large DataFrame (500'000 rows) containing polygons as rows, with each polygon representing a geographical area. The columns of the DataFrame represent different landcover classes (34 classes), and the values in the cells represent the area covered by each landcover cla...
The problem description lends itself to solving with a Mixed-Integer-Linear Program (MIP). A convenient library for solving mixed integer problems is PuLP that ships with the built-in Coin-OR suite and in particular the integer solver CBC. Note that I changed the data structure from the DataFrame in the example because...
3
3
76,603,915
2023-7-3
https://stackoverflow.com/questions/76603915/get-polynomial-x-at-y-python-3-10-numpy
I'm attempting to calculate all possible real X-values at a certain Y-value from a polynomial given in descending coefficent order, in Python 3.10. I want the resulting X-values to be provided to me in a list. I've tried using the roots() function of the numpy library, as shown in one of the answers to this post, howev...
You should be making use of the numpy.polynomial.Polynomial class that was added in numpy v1.4 (more information here). With that class, you can create a polynomial object. To find your solution, you can subtract y from the Polynomial object and then call the roots method. Another nice feature is that you can directly ...
3
3
76,607,902
2023-7-3
https://stackoverflow.com/questions/76607902/how-to-replicate-rows-of-a-dataframe-a-fixed-number-of-times
I want to replicate rows of a dataframe as to prepare for the adding of a column. The dataframe contains years column and I want to add a fixed column of months. The idea is to replicate each same year rows exactly 12 times then add a fixed value column (1-12). my code is the following: all_years = dataframe["Year"].u...
How about using groupby. I am assuming each year occurs only once in your data frame: new_dataset = dataframe.groupby("Year").apply(lambda x: pd.concat([x] * 12)).reset_index(drop=True) Or just repeat and sort the values: new_dataset = pd.concat([dataframe] * 12).sort_values("Year").reset_index(drop=True)
3
0
76,593,563
2023-7-1
https://stackoverflow.com/questions/76593563/redis-queue-task-is-queued-but-never-executed
I am having issues getting RQ-python to run. Like in the example of the documentation (https://python-rq.org) I have a function in an external file def createAndSaveIndex(url_list, index_path): print("--------------------------------------started task------------------------------------") index = indexFromURLList(url_l...
Solution: After trying to recreate the error on another computer I finally got it to work: Turns it out the issue was the kind of terminal I used. When creating the redis-server and initializing the rq worker I used my macOs Terminal and to run the code I used the VSCode built in terminal (Which I thought was the same ...
3
0
76,604,223
2023-7-3
https://stackoverflow.com/questions/76604223/combination-optimization-in-python
I need to gather products from warehouse centers for product bundling like this {product:quantity} center_a_products = {1: 8, 2: 4, 3: 12} Every centers has different kinds and quantities of products like this {center:{product:quantity}} product_quantities = {1: {1: 10, 2: 3, 3: 15}, 2: {1: 5, 2: 8, 3: 10}, 3: {1: 12, ...
The problem description lends itself to solving with a Mixed-Integer-Linear Program (MIP). A convenient library for solving mixed integer problems is PuLP that ships with the built-in Coin-OR suite and in particular the integer solver CBC. We formulate a model that describes your problem: import pulp center_a_products ...
2
4
76,603,818
2023-7-3
https://stackoverflow.com/questions/76603818/zipfile-badzipfile-even-when-im-not-reading-zip-file-using-pandas
In the current path there are multiple folders, each folder has multiple folders or xlsx files inside,I want to iterate through each folder and read the xlsx files until there are no more folders or until all xlsx files are read. There are 50+ folders and 2000+ excel files. Below is my code: import os import pandas as ...
You probably have files with the extension .xlsx but which are not real Excel files. To find them, you can use: import pathlib for filename in pathlib.Path.cwd().glob('*.xlsx'): with open(filename, 'rb') as xlsx: sig = xlsx.read(2) if sig != b'PK': print(f'"{filename}" does not appear to be a valid Excel file') Testin...
2
2
76,599,671
2023-7-2
https://stackoverflow.com/questions/76599671/python-pandas-how-to-find-nearest-point-by-latitude-and-longitude
New at pandas, having an issue relating two DataFrames together based on the function of two columns in each DataFrame. I have two DataFrames - one representing road segments, and another with points somewhere near that road. Road Shape DataFrame shape_pt_lat shape_pt_lon shape_pt_sequence 2583910 53.402329 -6.150988 ...
The simplest approach is to use the cdist function from scipy. It calculates the distance between every point in points and every point in road. You have the choice of 20 or so distance functions. After that it's trivial to find the closest point: from scipy.spatial.distance import cdist distance = cdist( points[["lati...
2
3
76,590,705
2023-6-30
https://stackoverflow.com/questions/76590705/format-string-output-to-json
I'm playing around with FastAPI and Structlog and wanted to test and convert log format from plain text/string to JSON format for better readability and processing by the log aggregator platforms. Facing a case where certain log output are available in JSON but rest in plain string. Current Output INFO: 127.0.0.1:62154...
Structlog is an entirely separate logging framework from stdlib logging. It will not configure the stdlib logging framework for you. Uvicorn uses stdlib logging, and you can't change that short of forking and editing the source code to use some other logging framework. You do have some options here, though. The simples...
7
2
76,593,906
2023-7-1
https://stackoverflow.com/questions/76593906/how-to-resolve-cannot-import-name-missingvalues-from-sklearn-utils-param-v
I am trying to import imblearn into my python notebook after installing the required modules. However, I am getting the following error: Additional info: I am using a virtual environment in Visual Studio Code. I've made sure that venv was selected as interpreter and as the notebook kernel. I've reloaded the window and...
I was having the same issue, downgrading to scikit-learn 1.2.2 fixed it for me
9
11
76,593,825
2023-7-1
https://stackoverflow.com/questions/76593825/how-to-fix-none-result-whilst-using-bs4-for-web-scraping
Here I have a simple code that is not seeming to do what I am trying to do. The goal of this code is to retrieve the value of the stock that the user inputs. ticker = input("What stock would you like to track?: (enter the ticker) ") r = requests.get(f"https://www.marketwatch.com/investing/stock/{ticker}?mod=search_symb...
This works. from bs4 import BeautifulSoup import requests ticker = input("What stock would you like to track?: (enter the ticker) ") r = requests.get(f"https://www.marketwatch.com/investing/stock/{ticker}?mod=search_symbol",).text webpage = BeautifulSoup(r, "html.parser") locate = webpage.find(class_="value") stock_pri...
3
1
76,572,824
2023-6-28
https://stackoverflow.com/questions/76572824/why-do-i-get-a-no-matching-distribution-found-error-when-installing-a-package
I am trying to upload my package to PyPi. It uploads successfully every time but when I try to install it, I get the following error: ERROR: Could not find a version that satisfies the requirement Google-Ads-Transparency-Scraper==1.4 (from versions: none) ERROR: No matching distribution found for Google-Ads-Transparenc...
This might be your problem, The file uploaded contains spaces where as when you see the second image, it should not contain spaces By examining that, I come to the conclusion as to what is wrong. Do you have spaces inside your setup.py? If so, remove them, also the github page for your project is incomplete, it does ...
4
1
76,592,108
2023-6-30
https://stackoverflow.com/questions/76592108/how-can-a-pandas-datetimearray-be-sorted
I have a DataFrame which contains a date column. I need to get the unique values of that column and then sort them out. I started with: unique_dates = data['date'].unique() Which works well. Next, I need to sort this unique list of dates. However, I am having issues because unique_values is now of DatetimeArray type, ...
The DatetimeArray is a flavour of ExtensionArray. ExtensionArrays don't have a sort or sort_values method, but they do have argsort, so we can achieve sorting using: unique_dates_sorted = unique_dates[unique_dates.argsort()] i.e. we get the indexes which result in the sorted array, then use those to produce a reordere...
2
2
76,591,838
2023-6-30
https://stackoverflow.com/questions/76591838/space-of-using-rangen
Could you tell me please, if I use for i in range(n), does python creates a range of 0 .. n-1, and iterates elements in this container (O(n) extra space), or it use only 1 vatiable (O(1)) space) From one side, I thought, if we can convert range to list, then using range function creates a container (O(n)).but from the ...
In Python 3, range does not create all the elements, but only returns the current element when you request it. So yes, it's using O(1) space.
2
3
76,587,201
2023-6-30
https://stackoverflow.com/questions/76587201/getting-solution-as-nan-for-mixed-integer-non-linear-programming-problem-with-ob
I wanted to maximize gross profit margin (total profit/total revenue) with binary variables, say whether products will be in the mix or not by that variables will be 1 or 0 (binary), trying to solve with gekko mixed integer non linear programming here is the example for 3 products, where we want to keep any 2 products ...
Try using a different initial guess than 0 for at least one of the variables: x1 = m.Var(value=1,integer=True, lb=0, ub=1) Gekko uses a default starting value of 0. Gradient-based optimizers need to calculate a search direction and the initial guesses of zero lead to an Inf evaluation of the objective function. Here i...
3
1
76,588,693
2023-6-30
https://stackoverflow.com/questions/76588693/plotly-not-displaying-the-y-zero-line
when plotting data using plotly the y-zero line is not shown in the grid (it is blank), creating a weird blank space. I've tried to modify the grid parameters so y-zero and x-zero lines are always displayed, but it hasn't work. I attach the function that plots the data. See the image and how for y=0 there is no grey li...
That took me forever. Apparently the zero line does NOT follow the grid color. It has separate properties, zerolinecolor and zerolinewidth. Yours is currently white on a white background. Change it like this (or another color): fig.update_layout(yaxis=dict(zerolinecolor='black'))
2
5
76,575,878
2023-6-28
https://stackoverflow.com/questions/76575878/python-loguru-output-to-stderr-and-a-file
I have the following line that configures my logger instance logger.add(sys.stderr, level=log_level, format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>", colorize=True, backtrace=True, diagnose=True) I want to configure my...
In the context of logging, a "sink" refers to an output destination for log records. It can be a stream (such as sys.stderr or sys.stdout), a file path, or any custom function that accepts the logged message an input. See documentation for more details. Using Loguru, you can add as many sinks as you like. This means th...
6
8
76,579,783
2023-6-29
https://stackoverflow.com/questions/76579783/rapids-pip-installation-issue
I've been trying to install RAPIDS in my Docker environment, which initially went smoothly. However, over the past one or two weeks, I've been encountering an error. The issue seems to be that pip is attempting to fetch from the default PyPi registry, where it encounters a placeholder project. I'm unsure who placed it ...
The issue has already been reported in the cudf repository and it seems to have existed since version 23.06. I will try the suggested workaround of installing version 23.04 and will report back if this temporarily resolves the problem. Original Issue: https://github.com/rapidsai/cudf/issues/13642 Feedback: Using strict...
2
3
76,581,535
2023-6-29
https://stackoverflow.com/questions/76581535/python-equivalent-for-java-hashcode-function
I have an A/B test split based on the result of Java hashCode() function applied to user's id (a string). I want to emulate that split in my dataframe to analyse the results. Is there a python equivalent for that function? Or maybe a documentation on the specific hashing algorithm inside hashCode() so I can produce tha...
According to java String source code, the hash implementation is: public int hashCode() { if (cachedHashCode != 0) return cachedHashCode; // Compute the hash code using a local variable to be reentrant. int hashCode = 0; int limit = count + offset; for (int i = offset; i < limit; i++) hashCode = hashCode * 31 + value[i...
2
5
76,582,964
2023-6-29
https://stackoverflow.com/questions/76582964/pandas-from-dict-returns-typeerror
I have a dictionary like the following: testProps = {"Key1":[], "Key2":False, "Key3":True, "Key4":[], "Key5":False} I want to convert it to a Pandas DataFrame with newTestProps = pd.DataFrame.from_dict(testProps,orient="index") but it is throwing me the following error. TypeError: object of type 'bool' has no len() W...
To create the dataframe you can use next example: testProps = {"Key1": [], "Key2": False, "Key3": True, "Key4": [], "Key5": False} df = pd.DataFrame({'Index': testProps.keys(), 0: testProps.values()}) print(df) Prints: Index 0 0 Key1 [] 1 Key2 False 2 Key3 True 3 Key4 [] 4 Key5 False
2
3
76,575,991
2023-6-28
https://stackoverflow.com/questions/76575991/safe-way-of-converting-seconds-to-nanoseconds-without-int-float-overflowing
I currently have a UNIX timestamp as a 64-bit float. It's seconds with a few fractions as a float. Such as 1687976937.597064. I need to convert it to nanoseconds. But there's 1 billion nanoseconds in 1 second. And doing a straight multiplication by 1 billion would overflow the 64-bit float. Let's first consider the l...
Floats can have a really large exponent without losing their significant precision. Turns out that floats allow really large multiplication without any issues, as such: >>> 9_000_000_000_000_000_000_000_000_000.0 * 1_000_000_000 9e+36 >>> 9_123_456_789_012_345_678_901_234_567.0 * 1_000_000_000 9.123456789012346e+36 >>>...
4
0
76,582,307
2023-6-29
https://stackoverflow.com/questions/76582307/i-am-using-undetected-chromedriver
I am using undetected_chromedriver, but I am getting the error This version of ChromeDriver only supports Chrome version 114 Current browser version is 103.0.5060.53 My code: import undetected_chromedriver as uc uc.TARGET_VERSION = 103 options = uc.ChromeOptions() options.add_argument('--no-sandbox') options.add_argum...
You can use SeleniumBase's UC Mode to use undetected-chromedriver with any browser version (it automatically downloads the correct driver if missing). First pip install seleniumbase, and then run the following script with python: from seleniumbase import Driver import time driver = Driver(uc=True, incognito=True) drive...
2
3
76,582,211
2023-6-29
https://stackoverflow.com/questions/76582211/what-method-is-called-when-using-dot-notation-in-myclass-my-attribute
I want to print "getting x attr" whenever I use the dot notation to get an attribute. For example class MyClass: my_attribute = "abc" print(MyClass.my_attribute) I'd expect it to output like this: >>> getting my_attribute attr >>> abc I'm not instantiating the class. I tried to add a print statement to MyClass.__geta...
MyClass (the class object) is itself an object. You want to define your custom __getattribute__ method on the class that MyClass is an instance of. To do that, use a metaclass: class MyMeta(type): def __getattribute__(self, item): print(f"getting {item}") return super().__getattribute__(item) class MyClass(metaclass=My...
2
4
76,578,411
2023-6-29
https://stackoverflow.com/questions/76578411/how-to-correct-coordinate-shifting-in-ax-annotate
I tried to annotate a line plot with ax.annotate as follows. import numpy as np import matplotlib.pyplot as plt x_start = 0 x_end = 200 y_start = 20 y_end = 20 fig, ax = plt.subplots(figsize=(5,5),dpi=600) ax.plot(np.asarray([i for i in range(0,1000)])) ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xyco...
By default, the arrow is shrunk by 2 points on both ends (see the doc). You can set shrinkA and shrinkB to 0 to align with your x-axis: import numpy as np import matplotlib.pyplot as plt x_start = 0 x_end = 200 y_start = 20 y_end = 20 fig, ax = plt.subplots(figsize=(5,5),dpi=600) ax.plot(np.asarray([i for i in range(0,...
2
4
76,572,666
2023-6-28
https://stackoverflow.com/questions/76572666/creating-a-custom-pydantic-field-to-accept-str-or-none-values
I want to create a Pydantic custom field. The main goal of this validator is to be able to accept two data types: "str" and "None". If the value is "None", it should return an empty string. I tried to do it as follows: from pydantic import BaseModel class EmptyStringField: @classmethod def __get_validators__(cls): yiel...
If all you want is for the url field to accept None as a special case, but save an empty string instead, you should still declare it as a regular str type field. You can handle the special case in a custom pre=True validator. No need for a custom data type there. from pydantic import BaseModel, validator class Model(Ba...
4
5
76,580,973
2023-6-29
https://stackoverflow.com/questions/76580973/extracting-first-3-elements-from-list-of-strings-in-pandas-df
I want to extract the first 3 elements from a list of strings from the '1/1' column. My df_unique looks like that: 1/1 0/0 count 0 ['P1-12', 'P1-22', 'P1-25', 'P1-26', 'P1-28', 'P1-6', 'P1-88', 'P1-93'] ['P1-89', 'P1-90', 'P1-92', 'P1-95'] 1 1 ['P1-12', 'P1-22', 'P1-25', 'P1-26', 'P1-6', 'P1-89', 'P1-92', 'P1-95'] ['P...
First convert your strings to read lists, then slice with str: import ast df_unique['1/1'] = df_unique['1/1'].apply(ast.literal_eval) df_unique['0/0'] = df_unique['0/0'].apply(ast.literal_eval) df_extract_3 = df_unique['1/1'].str[:3] print(df_extract_3) Or in one shot: df_extract_3 = df_unique['1/1'].apply(lambda x: a...
4
4
76,579,241
2023-6-29
https://stackoverflow.com/questions/76579241/reduce-by-multiple-columns-in-pandas-groupby
Having dataframe import pandas as pd df = pd.DataFrame( { "group0": [1, 1, 2, 2, 3, 3], "group1": ["1", "1", "1", "2", "2", "2"], "relevant": [True, False, False, True, True, True], "value": [0, 1, 2, 3, 4, 5], } ) I wish to produce a target target = pd.DataFrame( { "group0": [1, 2, 2, 3], "group1": ["1","1", "2", "2"...
Sort the values to put True, then highest number last and use a groupby.last: out = (df .sort_values(by=['relevant', 'value']) .groupby(['group0', 'group1'], as_index=False) ['value'].last() ) Output: group0 group1 value 0 1 1 0 1 2 1 2 2 2 2 3 3 3 2 5 Intermediate before aggregation: * selected rows group0 group1 ...
2
2
76,576,074
2023-6-28
https://stackoverflow.com/questions/76576074/how-to-import-a-postscript-file-into-pil-with-a-transparent-background
Using Pillow 9.5.0, Python 3.11.4, Tk 8.6, and Windows 11 (version 22H2) On the program i'm working on, I have a tkinter canvas that saves a postscript file, which is then imported into a PIL Image and shown. The problem is that it always has a white background, even when I changed the canvas background color Here's an...
After opening the image, you can call the load() method with transparency=True to tell ghostscript to load the EPS (Encapsulated PostScript) image with a transparent background: from PIL import Image im = Image.open('a.eps') im.load(transparency=True) # Check we now have RGBA inage print(im.mode) # prints "RGBA"
2
3
76,577,224
2023-6-28
https://stackoverflow.com/questions/76577224/python-does-importing-sys-module-also-import-os-module
I am following this tutorial to see why Python doesn't recognize an environment variable that was set at the Conda prompt (using CMD syntax, as this is an Anaconda installation on Windows 10). It requires the os module, and as part of my getting familiar with Python, I decided to test whether os was already imported. T...
sys uses the os module, but doesn't import it to your code. You can confirm it through the code. In [1]: import sys In [2]: os.getcwd() --------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In [2], line 1 ----> 1 os.getcwd() NameError: name 'os' is ...
3
-1
76,576,150
2023-6-28
https://stackoverflow.com/questions/76576150/filtering-dataframe-based-on-specific-conditions-in-python
I have a DataFrame with the following columns: INVOICE_DATE, COUNTRY, CUSTOMER_ID, INVOICE_ID, DESCRIPTION, USIM, and DEMANDQTY. I want to filter the DataFrame based on specific conditions. The condition is that if the DESCRIPTION column contains the words "kids" or "baby", I want to include all the values from that I...
Suppose the following dataframe: >>> df DESCRIPTION INVOICE_ID 0 kids 123 1 hello 123 2 world 123 3 another 456 4 one 456 You can want to keep INVOICE_ID=123 because 'kids' is in the description of row 0: m = df['DESCRIPTION'].str.contains('kids|baby', case=False, regex=True) filtered_df = df[m.groupby(df['INVOICE_ID'...
3
1
76,575,992
2023-6-28
https://stackoverflow.com/questions/76575992/rounding-down-numbers-to-the-nearest-even-number
I have a dataframe with a column of numbers that look like this: data = [291.79, 499.31, 810.93, 1164.25] df = pd.DataFrame(data, columns=['Onset']) Is there an elegant way to round down the odd numbers to the nearest even number? The even numbers should be rounded to the nearest even integer. This should be the outpu...
I'd use modulo operator: df['Onset_new'] = (i:=df['Onset'].astype(int)) - i % 2 print(df) Prints: Onset Onset_new 0 291.79 290 1 499.31 498 2 810.93 810 3 1164.25 1164
3
2
76,575,762
2023-6-28
https://stackoverflow.com/questions/76575762/how-to-add-multiple-or-queries-in-django
I have 2 models, Item and Category, the model Item has category field as a foreign key In my views.py I get a list of queries from a POST request queries = ['category1', 'category2', 'category3', ...] I don't know the number of the queries I will get from the request, and I want to filter the Item model based on catego...
You can use Q.OR as _connector: from django.db.models import Q from django import views from .models import Category, Item class myView(views.View): def post(self, request): queries = request.POST.get('queries', '') if queries: queryset = Item.objects.filter( *[Q(category__icontains=query) for query in queries.split(',...
2
3
76,575,561
2023-6-28
https://stackoverflow.com/questions/76575561/get-values-of-dataframe-index-column
I have a DataFrame with an index column that uses pandas TimeStamps. How can I get the values of the index as if it were a normal column (df["index"])?
You can get the index values from your dataframe by the following: df.index.values The above will return an array of the index values of your dataframe. You can simply store that in a variable. You can also get the values as a list by the following: list(df.index.values)
2
5
76,574,991
2023-6-28
https://stackoverflow.com/questions/76574991/pandas-compare-values-of-multiple-columns
I want to find out if any of the value in columns mark1, mark2, mark3, mark4 and mark5 are the same, column-wise comparison from a dataframe below, and list result as True or False import pandas as pd df = pd.DataFrame(data=[[7, 2, 3, 7, 7], [3, 4, 3, 2, 7], [1, 6, 5, 2, 7], [5, 5, 6, 3, 1]], columns=["mark1", "mark2",...
No need to use apply or a loop, compare the output of nunique to the number of columns: df['result'] = df.nunique(axis=1).ne(df.shape[1]) Output: mark1 mark2 mark3 mark4 mark5 result 0 7 2 3 7 7 True 1 3 4 3 2 7 True 2 1 6 5 2 7 False 3 5 5 6 3 1 True If you want a more efficient method and assuming a reasonable num...
3
0
76,573,883
2023-6-28
https://stackoverflow.com/questions/76573883/how-to-hide-cmd-window-when-run-perl-in-python
I write the main application with python and build it to windows *.exe file, and now need to call a 3rd party perl script. I use, cmd = "perl fileconverter.pl" subprocess.call(cmd) Everything works well except the cmd window, which will pop up when subprocess.call(cmd) is called. Question is, how to hide the cmd windo...
You can use wperl instead of perl. If your program is running in a console, perl should reuse the same console. >perl -e"system 'perl -Esay+123'" 123 (I don't have Python installed, but the same applies no matter what launches perl.) But maybe the Python is running without a console. Then perl will create itself a co...
3
4
76,573,550
2023-6-28
https://stackoverflow.com/questions/76573550/dictionary-hashmap-implementation-using-double-hashing-is-stuck-in-an-infinite-l
I'm following this formula from wikipedia: H(i, k) = (H1(k) + i*H2(k)) % size and my H1 is Python's built-in hash() function. H2 is: PRIME - (H1(k) % PRIME) Unfortunately it randomly sticks in an infinite loop after a couple of execution. It cannot traverse all the slots in my table. Here is my code but you have to s...
The logic calculating the sequence is flawed. For the configuration you mentioned it just will output 0, 5, 10 forever since the 0, 5, 10 slots are already occupied this will go on forever. You only multiply h2 with i and do the modulo with the size. This will loop quite often through a few specific values and won't co...
4
2
76,570,896
2023-6-28
https://stackoverflow.com/questions/76570896/importerror-cannot-import-name-jsonencoder-from-flask-json
I'm following a course on full-stack with Flask. My init.py looks like: from flask import Flask from config import Config from flask_mongoengine import MongoEngine app = Flask(__name__) app.config.from_object(Config) db = MongoEngine() db.init_app(app) from application import routes However, when importing from flask_...
flask_mongoengine seems to be not currently maintained and does not work with current Flask versions. If you absolutely must use it, you need to downgrade your Flask version, which may (and likely will) get you into other trouble. There is an issue on github regarding your error message: https://github.com/MongoEngine/...
8
3
76,570,857
2023-6-28
https://stackoverflow.com/questions/76570857/how-to-count-number-of-true-and-false-blocks-in-a-column-in-a-pandas-dataframe
I have the following pandas dataframe: col 2023-05-04 10:34:51.002100665 True 2023-05-04 10:34:51.007100513 True 2023-05-04 10:34:51.012100235 True 2023-05-04 10:34:51.017100083 False 2023-05-04 10:34:51.022099789 False 2023-05-04 10:35:23.610740595 False 2023-05-04 10:35:23.615740466 True 2023-05-04 10:35:23.62074022...
Assuming 'col' your column, you can remove the identical successive values with boolean indexing and use value_counts: out = df.loc[df['col'].ne(df['col'].shift()), 'col'].value_counts() Output: col True 3 False 2 dtype: int64 Intermediates: * only those rows will be considered col shift ≠ shift 2023-05-04 10:34:51....
2
3
76,522,582
2023-6-21
https://stackoverflow.com/questions/76522582/how-to-pass-parameters-to-an-endpoint-using-add-route-in-fastapi
I'm developing a simple application with FastAPI. I need a function to be called as endpoint for a certain route. Everything works just fine with the function's default parameters, but wheels come off the bus as soon as I try to override one of them. Example. This works just fine: async def my_function(request=Request,...
Option 1 One way is to make a partial application of the function using functools.partial. As per functools.partial's documentation: functools.partial(func, /, *args, **keywords) Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords...
3
3
76,557,773
2023-6-26
https://stackoverflow.com/questions/76557773/interpolate-based-on-datetimes
In pandas, I can interpolate based on a datetimes like this: df1 = pd.DataFrame( { "ts": [ datetime(2020, 1, 1), datetime(2020, 1, 3, 0, 0, 12), datetime(2020, 1, 3, 0, 1, 35), datetime(2020, 1, 4), ], "value": [1, np.nan, np.nan, 3], } ) df1.set_index('ts').interpolate(method='index') Outputs: value ts 2020-01-01 00...
Update: Expr.interpolate_by was added in Polars 0.20.28 df1.with_columns(pl.col("value").interpolate_by("ts")) shape: (4, 2) ┌─────────────────────┬──────────┐ │ ts ┆ value │ │ --- ┆ --- │ │ datetime[μs] ┆ f64 │ ╞═════════════════════╪══════════╡ │ 2020-01-01 00:00:00 ┆ 1.0 │ │ 2020-01-03 00:00:12 ┆ 2.333426 │ │ 2020-...
2
2
76,548,222
2023-6-24
https://stackoverflow.com/questions/76548222/how-to-get-maps-to-geopandas-after-datasets-are-removed
I have found very easy and useful to load world map from geopandas datasets, as probably many others, for example: import geopandas as gpd world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) However, this gives a FutureWarning that dataset module is deprecated and will be removed in the future. There ar...
You can read it from Nacis : import geopandas as gpd url = "https://naciscdn.org/naturalearth/110m/cultural/ne_110m_admin_0_countries.zip" gdf = gpd.read_file(url) old answer: The simplest solution would be to download/store the shapefile somewhere. That being said, if (for some reason), you need to read it from the ...
7
7
76,564,697
2023-6-27
https://stackoverflow.com/questions/76564697/polars-shuffle-and-split-dataframe-with-grouping
I am using polars for all preprocessing and feature engineering. I want to shuffle the data before performing a train/valid/test split. A training 'example' consists of multiple rows. The number of rows per example varies. Here is a simple contrived example (Note I am actually using a LazyFrame in my code): pl.DataFram...
There must be a far cleaner way of achieving this, hopefully someone can improve on this. Also it requires collecting the dataframe which is not ideal. Either way, it seems to work for now. Thanks @jqurious for the pointer. Grab the unique example_ids, shuffle them and add a row count. example_ids = ( example_df .sel...
3
1
76,523,245
2023-6-21
https://stackoverflow.com/questions/76523245/how-to-get-current-index-of-element-in-polars-list
When evaluating list elements I would like to know and use the current index. Is there already a way of doing it? Something like pl.element().idx() ? import polars as pl data = {"a": [[1,2,3],[4,5,6]]} schema = {"a": pl.List(pl.Int8)} df = pl.DataFrame(data, schema=schema) df = df.with_columns( pl.col("a").list.eval(pl...
The best way (that I know of) is to make a row index, explode, use int_range with a window function to create the idx (I'm calling it j), and then put it back together with group_by/agg ( df .with_row_index('i') .explode('a') .with_columns(j=pl.int_range(pl.len()).over('i')) .with_columns(new=pl.col('a')*pl.col('j')) ....
3
2
76,569,092
2023-6-27
https://stackoverflow.com/questions/76569092/polars-arr-geti-replacement
I have a code df.select([ pl.all().exclude("elapsed_time_linreg"), pl.col("elapsed_time_linreg").arr.get(0).suffix("_slope"), pl.col("elapsed_time_linreg").arr.get(1).suffix("_intercept"), pl.col("elapsed_time_linreg").arr.get(2).suffix("_resid_std"), ]) which unpacked the result of a function @jit def linear_regressi...
The .arr namespace was renamed to .list in v0.18.0 The function is now .list.get()
3
13
76,528,317
2023-6-22
https://stackoverflow.com/questions/76528317/quote-string-value-in-f-string-in-python
I'm trying to quote one of the values I send to an f-string in Python: f'This is the value I want quoted: \'{value}\'' This works, but I wonder if there's a formatting option that does this for me, similar to how %q works in Go. Basically, I'm looking for something like this: f'This is the value I want quoted: {value:...
Use the explicit conversion flag !r: >>> value = 'foo' >>> f'This is the value I want quoted: {value!r}' "This is the value I want quoted: 'foo'" The r stands for repr; the result of f'{value!r}' should be equivalent to using f'{repr(value)}'. Conversion flags are a feature carried over from str.format, which predates...
4
9
76,551,067
2023-6-25
https://stackoverflow.com/questions/76551067/how-to-create-a-langchain-doc-from-an-str
I've searched all over langchain documentation on their official website but I didn't find how to create a langchain doc from a str variable in python so I searched in their GitHub code and I found this : doc=Document( page_content="text", metadata={"source": "local"} ) PS: I added the metadata attribute then I tried...
I had a similar issue and I noticed the API calls for a list, so try doc = Document(page_content=input, metatdata={ "source": "userinput" } ) #db.add_documents(doc) db.add_documents([doc])
27
3
76,531,474
2023-6-22
https://stackoverflow.com/questions/76531474/django-ninja-testing
I am trying to create a test for an API I wrote using Django-Ninja. Here is my Model: class Country(models.Model): created_at = models.DateTimeField(auto_created=True, auto_now_add=True) name = models.CharField(max_length=128, null=False, blank=False) code = models.CharField(max_length=128, null=False, blank=False, uni...
I had {"detail": "Cannot parse request body"} as an error. Turns out, Django-ninja expects your data to be passed as a json, but by default, the content_type is set to multipart/form-data; boundary=BoUnDaRyStRiNg for the test client. When you explicitely mention the content type should be json, it will work. Client().p...
4
4
76,560,788
2023-6-26
https://stackoverflow.com/questions/76560788/how-do-i-annotate-that-a-python-class-should-implement-a-protocol
If I define a Protocol and a class that implements that protocol, I would like to document that the class does/should implement the protocol so that other developers can easily see that the class is supposed to implement the protocol, and so that static analysis tools can verify that the class implements the protocol. ...
I think the answer is on PEP-0544 : "To explicitly declare that a certain class implements a given protocol, it can be used as a regular base class." https://peps.python.org/pep-0544/#explicitly-declaring-implementation Personally I do subclass from protocol often because: my IDE is able to automatically complete me...
3
5
76,554,411
2023-6-26
https://stackoverflow.com/questions/76554411/unable-to-pass-prompt-template-to-retrievalqa-in-langchain
I am new to Langchain and followed this Retrival QA - Langchain. I have a custom prompt but when I try to pass Prompt with chain_type_kwargs its throws error in pydantic StufDocumentsChain. and on removing chain_type_kwargs itt just works. how can pass to the prompt? error File /usr/local/lib/python3.11/site-packages/p...
{context} is missing in template.
3
2
76,557,066
2023-6-26
https://stackoverflow.com/questions/76557066/cannot-run-tensorflow-gpu-on-docker-although-it-seems-to-be-installed-outside-o
Here is my situation I downloaded the tensorflow/tensorflow:latest-gpu image. In order to run it, I run the following command to start the docker image: docker run -it --rm \ --ipc=host \ --gpus all \ --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \ --volume="$(pwd)/://mydir:rw" \ --workdir="/mydir/" \ tensorflow/tensorfl...
It still seems like the Docker container is not able to access the GPUs on the host machine even though you are passing --gpus all as an argument. A few things to try: Make sure the Nvidia container toolkit is installed on the host - this is required for Docker to access Nvidia GPUs. You can install it with: distribu...
5
1
76,533,384
2023-6-22
https://stackoverflow.com/questions/76533384/docker-alpine-build-fails-on-mysqlclient-installation-with-error-exception-can
I'm encountering a problem when building a Docker image using a Python-based Dockerfile. I'm trying to use the mysqlclient library (version 2.2.0) and Django (version 4.2.2). Here is my Dockerfile: FROM python:3.11-alpine WORKDIR /usr/src/app COPY requirements.txt . RUN apk add --no-cache gcc musl-dev mariadb-connector...
I've managed to solve the issue and here's how I did it: Here is the new Dockerfile: FROM python:3.11-alpine WORKDIR /usr/src/app COPY requirements.txt . RUN apk add --no-cache --virtual build-deps gcc musl-dev libffi-dev2 pkgconf mariadb-dev && \ apk add --no-cache mariadb-connector-c-dev && \ pip install --no-cache-d...
30
1
76,556,703
2023-6-26
https://stackoverflow.com/questions/76556703/how-to-authenticate-using-windows-authentication-in-playwright
I need to automate a test that uses Windows Authentication. I know that the the prompt that opens up is not part of the HTML page, yet why my code is not working: login_page.click_iwa() sleep(5) self.page.keyboard.type('UserName') sleep(5) self.page.keyboard.press('Tab') self.page.keyboard.type('Password')
I solved the issue by using a virtual keyboard: from pyautogui import press, typewrite, hotkey def press_key(key): press(key) def type_text(text): typewrite(text) def special_keys(special, normal): hotkey(special, normal) Then, after I implemented the virtual keyboard, I did this: def login_iwa(self, user_name='User32...
4
2
76,562,382
2023-6-27
https://stackoverflow.com/questions/76562382/inserting-data-as-vectors-from-sql-database-to-pinecone
I have a profiles table in SQL with around 50 columns, and only 244 rows. I have created a view with only 2 columns, ID and content and in content I concatenated all data from other columns in a format like this: FirstName: John. LastName: Smith. Age: 70, Likes: Gardening, Painting. Dislikes: Soccer. Then I created the...
I have done some good research on the topic and have some recommendations Consider the following when optimizing code: The specific hardware and software environment in which the code will be run. The specific tasks that the code will be used for. The level of performance that is required. With these factors in mind,...
3
2
76,553,171
2023-6-26
https://stackoverflow.com/questions/76553171/avoiding-extra-next-call-after-yield-from-in-python-generator
Please see the below snippet, run with Python 3.10: from collections.abc import Generator DUMP_DATA = 5, 6, 7 class DumpData(Exception): """Exception used to indicate to yield from DUMP_DATA.""" def sample_gen() -> Generator[int | None, int, None]: out_value: int | None = None while True: try: in_value = yield out_valu...
When you yield from a tuple directly, the built-in tuple_iterator (which sample_gen delegates to) handles an additional "final value" yield before it terminates. It does not have a send method (unlike generators in general) and returns a final value None to sample_gen. The behavior: yield from DUMP_DATA # is equivalent...
3
3
76,567,790
2023-6-27
https://stackoverflow.com/questions/76567790/numpy-matmul-and-einsum-6-to-7-times-slower-than-matlab
I am trying to port some code from MATLAB to Python and I am getting much slower performance from Python. I am not very good at Python coding, so any advise to speed these up will be much appreciated. I tried an einsum one-liner (takes 7.5 seconds on my machine): import numpy as np n = 4 N = 200 M = 100 X = 0.1*np.rand...
First of all np.einsum has a parameter optimize which is set to False by default (mainly because the optimization can be more expensive than the computation in some cases and it is better in general to pre-compute the optimal path in a separate call first). You can use optimal=True to significantly speed-up np.einsum (...
6
9
76,559,814
2023-6-26
https://stackoverflow.com/questions/76559814/python-init-of-derived-singleton-not-called
I was toying around with the Singleton pattern and derivation. Specifically, I had this code: class Singleton: _instance = None init_attempts = 0 def __init__(self): self.init_attempts += 1 def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instanc...
The Python documentation has the answer: If __new__() is invoked during object construction and it returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to the object const...
4
3
76,536,988
2023-6-23
https://stackoverflow.com/questions/76536988/why-flask-python-streaming-data-not-work
Server side: from flask import Flask, request, Response, stream_with_context import time app = Flask(__name__) # Define a route /stream that handles POST requests @app.route('/stream', methods=['POST']) # GET also been tried, no difference def stream(): @stream_with_context def generate(): print('1') yield "Hello\n" ti...
Turned out to be the server setting problem, this post 10 years ago does help. nginx setting is important. Now server side is ok, tested by postman on my local machine, the strange is, the client side code does not go streaming, it prints all data at the same time. Have tried copy postman test header but not help. head...
3
1
76,569,147
2023-6-27
https://stackoverflow.com/questions/76569147/how-can-i-make-vs-code-format-my-python-code
I have following Python code: check_files(original_file = original_file_name, used_file = used_file_name, unused_file = unused_file_name) I want to make it instead to look like: check_files(original_file = original_file_name, used_file = used_file_name, unused_file = unused_file_name) Also I want to correct formattin...
Based on the comments by @starball, @jarmod and additional googling I found that you need to follow those steps: Step 1. Install Python extension from marketplace: https://marketplace.visualstudio.com/items?itemName=ms-python.python Step 2. Install one of the formatter packages for Python. The Python extension suppo...
8
5
76,568,476
2023-6-27
https://stackoverflow.com/questions/76568476/how-to-load-a-pandas-dataframe-from-orm-sqlalchemy-from-an-existing-database
I want to load an entire database table into a Pandas DataFrame using SqlAlchemy ORM. I have successfully queried the number of rows in the table like this: from local_modules import RemoteConnector from sqlalchemy import Integer, Column from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.automap import automap...
The answer is df = pd.read_sql_query(sql=select(Calculations), con=connection.engine) print(df.head()) This does the trick Corralien's answer is much more detailed.
4
2
76,568,086
2023-6-27
https://stackoverflow.com/questions/76568086/non-commutative-expansion-of-brackets-python
I wanted to ask whether there is a method to expand brackets in Python non-commutatively. For example, INPUT (x+y)**2, OUTPUT x**2 + x*y + y*x + y**2, instead of the usual output x**2 + 2*x*y + y**2. SymPy gives this commutative output, but I have seen that a non-commutative output is possible in Mathematica (NonCommut...
You have to create non-commutative symbols: from sympy import * x, y = symbols("x, y", commutative=False) expr = (x+y)**2 expr = expr.expand() print(expr) # out: x*y + x**2 + y*x + y**2
2
4
76,567,692
2023-6-27
https://stackoverflow.com/questions/76567692/hydra-how-to-express-none-in-config-files
I have a very simple Python script: import hydra from omegaconf import DictConfig, OmegaConf @hydra.main(version_base="1.3", config_path=".", config_name="config") def main(cfg: DictConfig) -> None: if cfg.benchmarking.seed_number is None: raise ValueError() if __name__ == "__main__": main() And here the config file: ...
Try null: benchmarking: seed_number: null
10
17
76,533,397
2023-6-22
https://stackoverflow.com/questions/76533397/python-pass-contexvars-from-parent-thread-to-child-thread-spawn-using-threading
I am setting some context variables using contextvars module that can be accessed across the modules running on the same thread. Initially I was creating contextvars.ContextVars() object in each python file hoping that there is only single context shared amongts all the python files of the module running on same thread...
Contextvars work similar as threading.local variables, in that, in each thread, a context var is initially empty. It can take further independent values in the same thread by using the context.run method from a contextvars.Context object, and that is extensively used by the asyncio code, so that each call-stack in a as...
3
3
76,559,257
2023-6-26
https://stackoverflow.com/questions/76559257/theoretically-can-the-ackermann-function-be-optimized
I am wondering if there can be a version of Ackermann function with better time complexity than the standard variation. This is not a homework and I am just curious. I know the Ackermann function doesn't have any practical use besides as a performance benchmark, because of the deep recursion. I know the numbers grow ve...
Solution I recently wrote a bunch of solutions based on the same paper that templatetypedef mentioned. Many use generators, one for each m-value, yielding the values for n=0, n=1, n=2, etc. This one might be my favorite: def A_Stefan_generator_stack3(m, n): def a(m): if not m: yield from count(1) x = 1 for i, ai in enu...
43
27
76,565,954
2023-6-27
https://stackoverflow.com/questions/76565954/regex-pattern-did-not-match-even-though-they-should-pytest
I am trying to match the string in this error: for warning in args: if not isinstance(warning, str): with StaticvarExceptionHandler(): raise TypeError(f"Configure.suppress() only takes string arguments. Current type: {type(warning)}") with the one in this pytest test: with pytest.raises( TypeError, match = "Configure....
Parentheses have a special meaning in Regex, for marking capture groups and a few other things, see https://regex101.com (select "Python" on the left menu to get Python-specific regex explanations, since they vary from language to language). You need to escape them match = "Configure.suppress\\(\\) only takes string ar...
4
8
76,559,939
2023-6-26
https://stackoverflow.com/questions/76559939/getting-error-when-using-clientside-callback-via-java-script-in-dash-python
I've recently asked a question about how to use clientside_callback (see this) and am practicing it on my own dashboard application. In my dashboard, I have a map, a drop down menu, and a button. The user selects states on the map with a click, and can also select them from the drop down menu. However, there is ALL opt...
You don't need to serialize the store data into a JSON string (or by doing so you would have to use JSON.parse() clientside to unserialize them back, but Dash already does it internally) so the first thing is to fix that in the app layout in order to receive proper JS objects in your clientside callback : #Store lists ...
3
1
76,555,620
2023-6-26
https://stackoverflow.com/questions/76555620/submission-and-custom-input-on-geeksforgeeks-gives-different-judge-result-on-sam
I was practicing with a GeeksForGeeks problem Fractional Knapsack: Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note: Unlike 0/1 knapsack, you are allowed to break the item. Example 1: Input: N = 3, W = 50 values[] = {60,100...
This is indeed very confusing! I looked at the Python version that GeeksForGeeks is running your code on, and at the time of writing these versions are different depending on whether you test or submit! When testing the code: Python 3.7.13 When submitting the code: Python 3.5.2 This explains why you get different res...
3
2
76,551,956
2023-6-25
https://stackoverflow.com/questions/76551956/kill-a-future-if-program-stops
I have a ThreadPoolExecutor in my programs which submit()s a task. However, when I end my program, the script "freezes". It seems like the thread is not ended correctly. Is there a solution for this? example: from concurrent.futures import ThreadPoolExecutor from time import sleep def task(): for i in range(3): print(i...
This program does not hang for me and I do not see anything in your code that is violating any published restrictions placed on the use of the concurrent.futures package. So reading the rest of this may be a waste of your time. But that's not to say that you don't have some statements that are not accomplishing anythin...
5
4
76,555,779
2023-6-26
https://stackoverflow.com/questions/76555779/cant-install-or-upgrade-python-3-10-8-in-wsl
I need to specifically install Python 3.10.8 for school, but I can't seem to get a version higher than 3.10.6 sudo apt-get install python3.10 just result in telling me that python3.10 is already the newest version (3.10.6-1~22.04.2ubuntu1.1) Reading package lists... Done Building dependency tree... Done Reading state i...
Step 1: sudo apt update Step 2: sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget Step 3: wget https://www.python.org/ftp/python/3.10.8/Python-3.10.8.tgz Step 4: tar -xf Python-3.10.8.tgz Step 5: cd Python-3.10.8 Step 6: ./configure --enable-o...
2
8
76,554,603
2023-6-26
https://stackoverflow.com/questions/76554603/python-regex-issue-with-optional-substring-in-between
Been bashing my head on this since 2 days. I'm trying to match a packet content with regex API: packet_re = (r'.*RADIUS.*\s*Accounting(\s|-)Request.*(Framed(\s|-)IP(\s|-)Address.*Attribute.*Value: (?P<client_ip>\d+\.\d+\.\d+\.\d+))?.*(Username|User-Name)(\s|-)Attribute.*Value:\s*(?P<username>\S+).*') packet1 = """ IP (...
I suggest using RADIUS.*?Accounting[\s-]Request(?:.*?(Framed[\s-]IP[\s-]Address.*?Attribute(?:.*?Value: (?P<client_ip>\d+\.\d+\.\d+\.\d+))?))?.*User-?[nN]ame[\s-]Attribute.*?Value:\s*(?P<username>\S+) See the regex demo. Note I removed .* on both ends of the pattern as you are using re.search that does not require mat...
4
2
76,548,894
2023-6-25
https://stackoverflow.com/questions/76548894/vs-code-python-debugger-opens-a-new-integrated-terminal-instead-of-reusing-an-ex
When I try to debug a Python file in VS Code, the debugger opens in a new terminal instead of using the existing integrated terminal. I have tried the following: Making sure that I have saved my launch.json configuration file. Restarting VS Code. Trying debugging a different Python file. If I am using a virtual environ...
From googling "github vscode python issues debug reuse terminal", I found this issue ticket: Run Python Debug Console in Existing Terminal #13040, where a maintainer of the VS Code Python extension, @int19h stated this: This would be a great feature, but, unfortunately, we're constrained by VSCode itself here. The deb...
3
4
76,539,324
2023-6-23
https://stackoverflow.com/questions/76539324/pytube-exceptions-regexmatcherror-get-throttling-function-name-could-not-find
def video_downloader(video_url_list: List[str], download_folder: str) -> None: """ Download videos from a list of YouTube video URLs. Args: video_urls (List[str]): The list of YouTube video URLs to download. download_folder (str): The folder to save the downloaded videos. """ successful_downloads = 0 valid_urls: List[s...
The work around in the official github page issue: https://github.com/pytube/pytube/issues/1684 function_patterns = [ # https://github.com/ytdl-org/youtube-dl/issues/29326#issuecomment-865985377 # https://github.com/yt-dlp/yt-dlp/commit/48416bc4a8f1d5ff07d5977659cb8ece7640dcd8 # var Bpa = [iha]; # ... # a.C && (b = a.g...
6
8
76,546,278
2023-6-24
https://stackoverflow.com/questions/76546278/how-we-can-run-python-in-sublime-text3
code doesn't run correctly ctrl + B and search on google, and also I searched on Youtube, Google and I tried several ways. there was some solutions but it didn't work. there is no error but unfortunately, my code doesn't run
Download the portable sublime3, go to: Tools | Build Systems | Python. With "Build" you can run your code. Crtl + B shows your python version, what is in your system environment variable defined: I would anyway suggest Thonny
3
3
76,541,795
2023-6-23
https://stackoverflow.com/questions/76541795/google-drive-ucid-no-longer-works
I am trying to write code to get the direct urls of images in a public Google Drive folder and embed them. Until a few minutes ago everything has been working and using the uc? trick gives the raw image so I can embed it. However now it is sending a download, even when I use &export=view. Here is my code: key = "supers...
In your situation, how about changing the endpoint? When your showing script is modified, please modify raw_link as follows. From: raw_link = f"https://drive.google.com/uc?id={file['id']}" To: raw_link = f"https://drive.google.com/thumbnail?id={file['id']}&sz=w1000" # Please modify w1000 to your actual situation. By...
6
4
76,540,270
2023-6-23
https://stackoverflow.com/questions/76540270/uvicorn-reload-kill-all-created-sub-process-when-auto-reloading
I currently have a fastapi deployed with uvicorn that starts a thread on initialisation (among other things) using threading. This thread is infinite (it's a routine that updates every x seconds). Before I updated to python 3.10, everything was working fine, everytime I changed the code, the server would detect change ...
Fixed by downgrading uvicorn to an older version (0.19.0 works).
5
2
76,532,906
2023-6-22
https://stackoverflow.com/questions/76532906/unrecognized-configuration-parameter-standard-conforming-strings-while-queryin
I am trying to connect to my redshift cluster using Sqlalchemy in a linux environment, but i am facing the following issue. from sqlalchemy import create_engine import pandas as pd conn = create_engine('postgresql://connection string') data_frame = pd.read_sql_query("SELECT * FROM schema.table", conn) sqlalchemy.ex...
I have figured out the answer based on the comment by @Adrian . Just changed the version of Sql alchemy on the linux env to what i have on Windows and it works now.
12
0
76,536,650
2023-6-23
https://stackoverflow.com/questions/76536650/read-json-to-pandas-dataframe
I have a data file in json format downloaded from another system. It can be observed that it contains one row with all the column names as shown as keys in the json string with its values. Metadata for this one row contains another json string. { "createdTime": 1625433352096, "lastUpdatedTime": 1664815053126, "rootId":...
I don't think there is any direct way to do this in a direct manner. However, you can still include metadata into the database manually, and then add metadata manually as a single column. metadata = data.pop('metadata') df2 = pd.json_normalize(data) df2['metadata'] = [metadata] However I'm not able to test the code on...
3
1
76,534,046
2023-6-22
https://stackoverflow.com/questions/76534046/why-is-my-manual-convolution-different-to-scipy-ndimage-convolve
I apologise in advance, I may just not understand convolution. I'm struggling to reconcile the results using scipy.ndimage.convolve with what I get attempting to do it by hand. For the example in the documentation: import numpy as np a = np.array([[1, 2, 0, 0], [5, 3, 0, 4], [0, 0, 0, 7], [9, 3, 0, 0]]) k = np.array([[...
The operation you're performing by hand is cross correlation, not convolution. The process of convolution is similar but "flips" the kernel. You can show that your expected result can be obtained by first flipping your kernel which then gets unflipped during covolution: > ndimage.convolve(a, np.flip(k), mode='constant'...
4
4
76,532,429
2023-6-22
https://stackoverflow.com/questions/76532429/typehint-googleapiclient-discovery-build-returning-value
I create the Google API Resource class for a specific type (in this case blogger). from googleapiclient.discovery import Resource, build def get_google_service(api_type) -> Resource: credentials = ... return build(api_type, 'v3', credentials=credentials) def blog_service(): return get_google_service('blogger') def list...
The problem here is that the Resource class dynamically sets arbitrary attributes/methods based on what collections the underlying API provides. In your case apparently there is a blogs collection, which means the blogs method is dynamically constructed on that Resource object. Expecting static type annotations, when y...
3
2
76,533,178
2023-6-22
https://stackoverflow.com/questions/76533178/corr-results-in-valueerror-could-not-convert-string-to-float
I'm getting this very strange error when trying to follow the following exercise on using the corr() method in Python https://www.geeksforgeeks.org/python-pandas-dataframe-corr/ Specifically, when I try to run the following code: df.corr(method ='pearson') The error message offers no clue. I thought the corr() method w...
When I try to replicate this behavior, the corr() method works OK but spits out a warning (shown below) that warns that the ignoring of non-numeric columns will be removed in the future. Perhaps the future has arrived? I've got pandas version 1.5.3. You may need to just specify which columns to use--which is actually a...
25
3
76,527,086
2023-6-21
https://stackoverflow.com/questions/76527086/find-an-empty-space-in-a-binary-image-that-can-fit-a-shape
I have this image I need to find an empty area that can fit this shape so that the end result is something like this
Here is a simple yet naive solution to this problem. It uses 2D convolution as mentioned by UnquoteQuote. import random import numpy as np import scipy.signal as sig import matplotlib.pyplot as plt import cv2 # load images image = (cv2.imread('image.jpg').mean(axis=2) > 127).astype(np.float32) shape = (cv2.imread('shap...
3
2
76,523,859
2023-6-21
https://stackoverflow.com/questions/76523859/improving-performance-of-resolving-a-solitaire-math-game
A bit of history: Since I was a kid, I have been playing a very easy little solitaire game to which I have never found a solution and honestly, I don't know if there is one, but I would like to find it out with the help of my computer. First, let me explain the rules: First you have to take a grid sheet and draw an ar...
I had a go and implemented Warnsdorff's rule for prioritising moves, and the program immediately found a solution: def print_table(table): print(51*"-") for row in table: for cell in row: print(f"|{cell:>3} " if cell else "| ", end='') print("|\n" + 51*"-") print() def solve(table, x, y): sizey = len(table) sizex = len...
3
2
76,513,289
2023-6-20
https://stackoverflow.com/questions/76513289/how-to-properly-use-gcps-artifact-repository-with-python
Adding Private GCP Repo Breaks normal pip behaviour When using Google Cloud Platform's Artifact Repository, you have to alter your .pypirc file for any uploads (twine) and your pip.conf for any downloads (pip). For the downloads specifically, you have to add something like: [global] extra-index-url = https://<YOUR-LOCA...
I am still not 100% satisfied with my solution, so the question is still relevant and important, IMHO. However, I have resolved it "good enough", and moved on to other tasks. In a thread above, @insidehustle asked if I could describe how I'm doing it. So even though I don't find this a "solution", I wanted to add it to...
4
3
76,475,419
2023-6-14
https://stackoverflow.com/questions/76475419/how-can-i-select-the-proper-openai-api-version
I read on https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/chatgpt?pivots=programming-language-chat-completions: openai.api_version = "2023-05-15" and on https://learn.microsoft.com/en-us/answers/questions/1193969/how-to-integrate-tiktoken-library-with-azure-opena: openai.api_version = "2023-03...
The API Version property depends on the method you are calling in the API: all methods are not supported in all API versions. Details are listed here: https://learn.microsoft.com/en-US/azure/cognitive-services/openai/reference And preview API lifecycle is described here: https://learn.microsoft.com/en-us/azure/ai-servi...
14
18
76,498,857
2023-6-18
https://stackoverflow.com/questions/76498857/what-is-the-difference-between-mapped-column-and-column-in-sqlalchemy
I am new to SQLAlchemy and I see that in the documentation the older version (Column) can be swapped directly with the newer "mapped_column". Is there any advantage to using mapped_column over Column? Could you stick to the older 'Column'?
I think originally Column was used in the lower "core"/sqlalchemy.sql layer AND the higher ORM layer. This created a conflict of purpose. So mapped_column now supersedes Column when using the ORM layer to add more functionality that can't be used by the core layer. The core layer will keep using Column. So I think it i...
41
50
76,500,503
2023-6-18
https://stackoverflow.com/questions/76500503/how-i-can-unpack-typing-typevartuple-with-pattern
How do I get the type tuple[A[int], A[int]] for b.b? import typing T = typing.TypeVar('T') Ts = typing.TypeVarTuple('Ts') class A(typing.Generic[T]): a: T class B(typing.Generic[*Ts]): b: tuple[*A[Ts]] b: B[int, int] = B() typing.reveal_type(b.b) # tuple[A[*tuple[int, int]]] i got # but i need a tuple[A[int], A[int]] ...
Now (Python 3.12) there is no such possibility. But the issue was created on github python/typing. And I hope that they will add such an opportunity! My suggestion: import typing T = typing.TypeVar('T') Ts = typing.TypeVarTuple('Ts') class A[T]: a: T class B[*Ts]: b: tuple[*A[Ts]] b: B[int, int] = B() typing.reveal_typ...
3
0
76,491,448
2023-6-16
https://stackoverflow.com/questions/76491448/runtimeerror-tk-h-version-8-5-doesnt-match-libtk-a-version-8-6
I'm getting an error while using tkinter. I have installed python using pyenv. >>> import tkinter >>> tkinter._test() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/hrj/.pyenv/versions/3.8.16/lib/python3.8/tkinter/__init__.py", line 4557, in _test root = Tk() File "/Users/hrj/.pyenv...
This worked in Python versions 3.7 to 3.11. brew update brew install tcl-tk echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> ~/.zshrc export LDFLAGS="-L/usr/local/opt/tcl-tk/lib" export CPPFLAGS="-I/usr/local/opt/tcl-tk/include" export PKG_CONFIG_PATH="/usr/local/opt/tcl-tk/lib/pkgconfig" brew install pyenv --h...
3
2
76,480,902
2023-6-15
https://stackoverflow.com/questions/76480902/playwright-install-deps-fails-in-dockerfile
I have a small application that uses playwright to scrape data from various websites. The application is Dockerized well and everything worked perfectly until I tried to re-build the Docker image (nothing really changed in the code) and it failed to install the playwright deps (like it used to before). This is the Dock...
Solution: I changed the base image to a newer version and now it is working properly. FROM python:3.10.7 instead of: FROM python:3.9-slim
4
2
76,517,720
2023-6-20
https://stackoverflow.com/questions/76517720/langchain-pandas-agent-unable-to-run-pandas-commands
I'm trying to use langchain's pandas agent on python for some development work but it goes into a recursive loop due to it being unable to take action on a thought, the thought being, having to run some pandas code to continue the thought process for the asked prompt on some sales dataset (sales.csv). here is the below...
Most of the information you provide in Langchain agents is supposed to be for prompt context. Add the below code to provide custom information for your agent. query = "what is the mean of the profit?" query = query + " using tool python_repl_ast" pd_agent.run(query) It worked for me.
4
4