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
72,400,867
2022-5-27
https://stackoverflow.com/questions/72400867/installing-python-on-ish
Not long ago my computer broke and I am stuck on an iPad. I installed iSH from the AppStore. Now I want to download Python and make sure pip works. I have tried apk add python, which lead to the pip issue, but pip installing is important for me. I have also found other ways using yam or apt(-get), but I do not know how...
According information that you provided iSH using virtual environment with Alpine Linux x86 under the hood (I little bit simplify explanation, so it is not 100% correct. You can see details here). So if you want to install pip you have to search how to install pip in Alpine Linux. You will find many answers like that: ...
4
6
72,414,481
2022-5-28
https://stackoverflow.com/questions/72414481/error-in-anyjson-setup-command-use-2to3-is-invalid
#25 3.990 × python setup.py egg_info did not run successfully. #25 3.990 │ exit code: 1 #25 3.990 ╰─> [1 lines of output] #25 3.990 error in anyjson setup command: use_2to3 is invalid. #25 3.990 [end of output] This is a common error which the most common solution to is to downgrade setuptools to below version 58. Thi...
Downgrading setuptools worked for me pip install "setuptools<58.0.0" And then pip install django-celery
48
110
72,398,203
2022-5-26
https://stackoverflow.com/questions/72398203/concatenate-2-arrays-in-pyproject-toml
I'm giving a shot to the pyproject.toml file, and I'm stuck on this simple task. Consider the following optional dependencies: [project.optional-dependencies] style = ["black", "codespell", "isort", "flake8"] test = ["pytest", "pytest-cov"] all = ["black", "codespell", "isort", "flake8", "pytest", "pytest-cov"] Is the...
There is no such feature directly in the toml markup. However, there is a tricky way to do this in Python packaging by depending on yourself: [project.optional-dependencies] style = ["black", "codespell", "isort", "flake8"] test = ["pytest", "pytest-cov"] all = ["myproject[style]", "myproject[test]"] Source: Circular...
5
9
72,409,563
2022-5-27
https://stackoverflow.com/questions/72409563/unsupported-hash-type-ripemd160-with-hashlib-in-python
After a thorough search, I have not found a complete explanation and solution to this very common problem on the entire web. All scripts that need to encode with hashlib give me error: Python 3.10 import hashlib h = hashlib.new('ripemd160') return: Traceback (most recent call last): File "<stdin>", line 1, in <module>...
Hashlib uses OpenSSL for ripemd160 and apparently OpenSSL disabled some older crypto algos around version 3.0 in November 2021. All the functions are still there but require manual enabling. See issue 16994 of OpenSSL github project for details. To quickly enable it, find the directory that holds your OpenSSL config fi...
14
29
72,454,393
2022-5-31
https://stackoverflow.com/questions/72454393/does-python-oracledb-thin-mode-have-any-performance-implications-compared-to-the
cx_Oracle was renamed to python-oracledb in the May 2022 release. It now comes with two modes, thin and thick. Thick mode uses the Oracle client libraries to connect to Oracle, while thin mode can connect directly. cx_Oracle previously always required using the Oracle client libraries. Is there any performance implicat...
Yes, there is, but it can vary depending on your workload. In our own tests we saw basic fetching and inserting performing with thin mode between 10% and 30% faster than thick mode. The main reason for the difference is the elimination of a copy/conversion step that is required in thick mode. Some more discussion can b...
6
9
72,373,093
2022-5-25
https://stackoverflow.com/questions/72373093/how-to-define-python-requires-in-pyproject-toml-using-setuptools
Setuptools allows you to specify the minimum python version as such: from setuptools import setup [...] setup(name="my_package_name", python_requires='>3.5.2', [...] However, how can you do this with the pyproject.toml? The following two things did NOT work: [project] ... # ERROR: invalid key python_requires = ">=3" #...
According to PEP 621, the equivalent field in the [project] table is requires-python. More information about the list of valid configuration fields can be found in: https://packaging.python.org/en/latest/specifications/declaring-project-metadata/. The equivalent pyproject.toml of your example would be: [project] name =...
18
22
72,450,373
2022-5-31
https://stackoverflow.com/questions/72450373/all-permutations-of-numbers-1-n-using-list-comprehension-without-itertools
I am currently using Python 3.7.7, and I posed a coding challenge for myself. I would like to list all permutations of integers from 1 to N using a one-line code (perhaps a list comprehension). I cannot use itertools (or other packages which solve this with one function). For N <= 9, I found "cheaty" method: N = 3 prin...
A not-so-simple functional one-liner without any "outside" variable assignment except N. N = 3 (lambda n: (lambda f, n: f(f, n))(lambda f, n: [p[:i]+[n]+p[i:] for p in f(f, n-1) for i in range(len(p)+1)] if n > 1 else [[1]], n))(N) Output [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]]
3
4
72,454,228
2022-5-31
https://stackoverflow.com/questions/72454228/error-could-not-load-file-or-assembly-microsoft-azure-webjobs-script-abstracti
I'm trying to run an Azure Function locally following the Microsoft guide: https://learn.microsoft.com/nl-nl/azure/azure-functions/create-first-function-cli-python?tabs=azure-cli%2Cbash%2Cbrowser#create-venv Whatever I try I get the same error over and over again when i try to start the function using "func start": Fo...
I came across this too. Not sure what caused it. But what fixed it for me was to download, uninstall, and reinstall the Azure Functions Core Tools (using 'repair' just returned a generic "Failed due to error", and I had to kill PowerToys) Not sure if it's necessary, but I also cleared my nuget cache dotnet nuget local...
5
6
72,452,403
2022-5-31
https://stackoverflow.com/questions/72452403/cross-reference-between-numpy-arrays
I have a 1d array of ids, for example: a = [1, 3, 4, 7, 9] Then another 2d array: b = [[1, 4, 7, 9], [3, 7, 9, 1]] I would like to have a third array with the same shape of b where each item is the index of the corresponding item from a, that is: c = [[0, 2, 3, 4], [1, 3, 4, 0]] What's a vectorized way to do that us...
Effectively, this solution is a one-liner. The only catch is that you need to reshape the array before you do the one-liner, and then reshape it back again: import numpy as np a = np.array([1, 3, 4, 7, 9]) b = np.array([[1, 4, 7, 9], [3, 7, 9, 1]]) original_shape = b.shape c = np.where(b.reshape(b.size, 1) == a)[1] c =...
6
1
72,370,894
2022-5-25
https://stackoverflow.com/questions/72370894/stream-image-from-android-with-ffmpeg
I'm currently receiving images from an external source as byte array and I would like to send it as raw video format via ffmpeg to a stream URL, where I have a RTSP server that receives RTSP streams (a similar unanswered question). However, I haven't worked with FFMPEG in Java, so i can't find an example on how to do i...
Here is a JAVA implementation that resembles the Python code: The example writes raw video frames (byte arrays) to stdin pipe of FFmpeg sub-process: _____________ ___________ ________ | JAVA byte | | | | | | Array | stdin | FFmpeg | | Output | | BGR (format)| --------> | process | -------------> | stream | |__________...
4
6
72,418,933
2022-5-28
https://stackoverflow.com/questions/72418933/find-boundary-points-of-xy-coordinates
I have a text file with xy-coordinates called xy.txt. 29.66150677 -98.39336541 29.66150677 -98.39337576 29.66150651 -98.39336541 29.66150328 -98.39337576 29.66150677 -98.39336475 29.66150677 -98.39338611 29.66150393 -98.39338611 29.66150677 -98.39339646 29.66150659 -98.39339646 29.66150677 -98.39339693 29.66151576 -98...
When I try to reproduce your code the convexHull function works perfectly. I changed your code so that the positions of black and red circles are rounded in the same way. And I reduced the radius of the red circles so you can better see if everything fits. import numpy as np import matplotlib.pyplot as plt from scipy i...
3
9
72,444,301
2022-5-31
https://stackoverflow.com/questions/72444301/calculate-percentage-change-between-values-of-column-in-pandas-dataframe
I have a dataframe with some price indices across 5 years, from 2017 to 2021. It looks like this: Country Industry Year Index US Agriculture 2017 83 US Agriculture 2018 97.2 US Agriculture 2019 100 US Agriculture 2020 112 US Agriculture 2021 108 Japan Mining 2017 88 Japan Mining 2018 93 Japan Mini...
pct_change is computing a change relative to the previous value (which is why 2017 is NaN), and this doesn't seem to be what you want. If you want to compute a percentage change relative to 2019, as 2019 is already normalized to 100, simply subtract 100: df['Percentage_Change'] = df['Index'].sub(100) output: Country ...
4
6
72,443,312
2022-5-31
https://stackoverflow.com/questions/72443312/what-is-the-most-efficient-way-to-open-osm-pbf-with-lowest-memory-consumption
Here's what I did from pyrosm import OSM # Initialize the OSM parser object osm = OSM('/DATA/user/nabih/indonesia-latest.osm.pbf') # Read all drivable roads drive_net = osm.get_network(network_type="driving") But it is memory error
https://osmcode.org/pyosmium/ provides a library to parse a osm.pbf. From what I remember, they keep the memory consumption to the minimum and provide different modes of parsing. Checkout their documentation for basic usage tutorial and references. The README of their GitHubprovides installation instructions.
4
4
72,440,803
2022-5-30
https://stackoverflow.com/questions/72440803/compare-rows-of-two-dataframes-in-pandas
I have two dataframes, the first is the data I currently have in the database, the second would be a file that might have changed fields: name and/or cnpj and/or create_date Based on that, I need to create a third dataframe with only the rows that have undergone some kind of change, as in the example of the expected ou...
If the data has same columns, but different number of rows, this is one possible solution: res = (pd.concat([df1,df2]) .drop_duplicates(keep=False) .drop_duplicates(subset='id_account', keep='last') ) Output: id_account name cnpj create_date 0 10 Supermarket Carol 80502030 2022-05-30 3 40 Supermarket Magical 60304050...
4
3
72,438,984
2022-5-30
https://stackoverflow.com/questions/72438984/unit-testing-init-subclass-method-in-python-3-x
I am trying to unit test an inherited class for which its base class implements __init_subclass__ method. Code is the following: quick_test.py import unittest from unittest.mock import create_autospec class Parent(): PROPERTY = NotImplemented def __init_subclass__(cls, **kwargs): if cls.PROPERTY is NotImplemented: rai...
You can create the class inside the assertRaises block. with self.assertRaises(NotImplementedError): class ChildNoProp(Parent): pass If the class declaration inside of a method makes you uncomfortable, you can use the type constructor directly. with self.assertRaises(NotImplementedError): type("ChildNoProp", (Parent,)...
4
3
72,408,128
2022-5-27
https://stackoverflow.com/questions/72408128/typing-decorators-that-can-be-used-with-or-without-arguments
I have a decorator that can be called either without or with arguments (all strings): @decorator def fct0(a: int, b: int) -> int: return a * b @decorator("foo", "bar") # any number of arguments def fct1(a: int, b: int) -> int: return a * b I am having a hard time providing appropriate type hints so that type checkers ...
The issue comes from the first overload (I should have read the pyright message twice!): @overload def decorator(arg: F) -> F: ... This overload accepts a keyword parameter named arg, while the implementation does not! Of course this does not matter in the case of a decorator used with the @decorator notation, but cou...
5
4
72,411,825
2022-5-27
https://stackoverflow.com/questions/72411825/jupyter-notebook-in-vscode-with-virtual-environment-fails-to-import-tensorflow
I'm attempting to create an isolated virtual environment running tensorflow & tf2onnx using a jupyter notebook in vscode. The tf2onnx packge recommends python 3.7, and my local 3.7.9 version usually works well with tensorflow projects, so I have local and global versions set to 3.7.9 using pyenv. The following is my se...
A recent change in protobuf is causing TensorFlow to break. Downgrading before installing TensorFlow might not work because TensorFlow might be bumping up the version itself. Check if that is what happens during the installation. You might want to either: Downgrade with pip install --upgrade "protobuf<=3.20.1" after i...
8
16
72,422,403
2022-5-29
https://stackoverflow.com/questions/72422403/python-syntaxerror-f-string-unmatched
from fastapi import FastAPI from fastapi.params import Body app = FastAPI() @app.post("/createposts") def create_posts(payload: dict = Body(...)): print(payload) return {"new_post" : f"title {payload["title"]} content: {payload["content"]}"} I'm trying to create an API with Fastapi, but every time I run the code I get...
Please change return {"new_post" : f"title {payload["title"]} content: {payload["content"]}"} to return {"new_post" : f"title {payload['title']} content: {payload['content']}"} You can't have " quotes inside f"..." The error says that after the first [ the string stops and breaks.
3
11
72,422,968
2022-5-29
https://stackoverflow.com/questions/72422968/finding-the-max-value-in-accordance-with-other-columns
I have students names, scores in different subjects, subjects names. I want to add a column to the data frame, which contains the subject in which each student had the highest score. Here is the data: Input data would be: Output data (the result data frame) would be : My try at this (didn't work obviously): Data['Sub...
Sort the values by Scores, then group the dataframe by Names and transform the column Subject with last df['S(max)'] = df.sort_values('Scores').groupby('Names')['Subject'].transform('last') Alternatively, we can group the dataframe by Names then transform Scores with idxmax to broadcast the indices corresponding to ro...
5
1
72,421,952
2022-5-29
https://stackoverflow.com/questions/72421952/how-to-stop-selenium-from-printing-webdriver-manager-messages-in-python
Each time that I initiate a new webdriver the following text is written to the console: [WDM] - ====== WebDriver manager ====== [WDM] - Current google-chrome version is 102.0.5005 [WDM] - Get LATEST chromedriver version for 102.0.5005 google-chrome [WDM] - Driver [C:\Users\klaas\.wdm\drivers\chromedriver\win32\102.0.50...
These are webdriver-manager logs. You can either uninstall it if you are not using or disable logging as below import os os.environ['WDM_LOG'] = "false" You can also try import logging logging.getLogger('WDM').setLevel(logging.NOTSET)
4
4
72,412,077
2022-5-28
https://stackoverflow.com/questions/72412077/how-can-i-count-comma-separated-values-in-my-dataframe
I am trying to figure out how to get value_counts from how many times a specific text value is listed in the column. Example data: d = {'Title': ['Crash Landing on You', 'Memories of the Alhambra', 'The Heirs', 'While You Were Sleeping', 'Something in the Rain', 'Uncontrollably Fond'], 'Cast' : ['Hyun Bin,Son Ye Jin,Se...
You should use the .explode method to "unpack" each list in different rows. Then .value_counts will work as intended in the original code: import pandas as pd d = {'Title': ['Crash Landing on You', 'Memories of the Alhambra', 'The Heirs', 'While You Were Sleeping', 'Something in the Rain', 'Uncontrollably Fond'], 'Cast...
4
10
72,411,999
2022-5-27
https://stackoverflow.com/questions/72411999/how-to-print-as-a-string-a-callable-object
I think there should be a question like this already, but I haven't found it. It could be because I don't know the exact concepts/words about what I'm looking for, but here is the example: I have this code: group_1 = ['Hello', 'world', '!'] group_2 = [1,23,4,2,5,2] group_3 = ['A', 'K', 'L'] all_groups = [group_1, group...
Restructure your code so that it uses a dictionary to store the group names. I would not recommend approaches that use anything related to reflection, the inspect module, or locals(), as described (or linked to) in the comments. The names of the variables in all_groups list aren't preserved when you add them to all_gro...
5
5
72,408,888
2022-5-27
https://stackoverflow.com/questions/72408888/pytorch-why-does-running-output-modelimages-use-so-much-gpu-memory
In trying to understand why my maximum batch size is limited for my PyTorch model, I noticed that it's not the model itself nor loading the tensors onto the GPU that uses the most memory. Most memory is used up when generating a prediction for the first time, e.g. with the following line in the training loop: output = ...
This is normal: The key here is that all intermediate tensors (the whole computation graph) have to be stored if you want to compute the gradient via backward-mode differentiation. You can aviod that by using the .no_grad context manager: with torch.no_grad(): output = model(images) You will observe that a lot less me...
4
5
72,406,597
2022-5-27
https://stackoverflow.com/questions/72406597/how-to-avoid-bot-detection-on-websites-using-selenium-python
We are trying to automate process using selenium python for a website but as we proceed with the process the bot gets detected every time and a captcha comes up. Even though a human solve that captcha the website does not allow to move forward and continuously keeps detecting the bot and again and again shows the captc...
There is something called "Undetected ChromeDriver" you can check out! Optimized Selenium Chromedriver patch which does not trigger anti-bot services like Distill Network / Imperva / DataDome / Botprotect.io Automatically downloads the driver binary and patches it. here is the link Here is another useful website you ca...
4
4
72,383,861
2022-5-25
https://stackoverflow.com/questions/72383861/how-to-declare-a-class-variable-without-a-value-in-a-way-that-suppresses-pylance
I love the typechecker in Pylance (VS Code), but there seems to be a situation that I must choose between ignoring a Pylance warning and best practice for class variable declaration. Many times, class variables are initialized using a None type in the class constructor, and the variable is set later. For example: class...
update: This is so obvious I assume it won't work in your case, but it is the "natural thing to do" If you arte annotating instance attributes, and don't want them to be able to read "None" or other sentinel value, simply do not fill in a sentinel value, just declare the attribute and its annotation. That is, do not tr...
3
4
72,405,196
2022-5-27
https://stackoverflow.com/questions/72405196/append-1-for-the-first-occurence-of-an-item-in-list-p-that-occurs-in-list-s-and
I want this code to append 1 for the first occurence of an item in list p that occurs in list s, and append 0 for the other occurence and other items in s. That's my current code below and it is appending 1 for all occurences, I want it to append 1 for the first occurence alone. Please, help s = [20, 39, 0, 87, 13, 0, ...
The simplest solution is to remove the item from list p if found: s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13] p = [0, 13] out = [] for i in s: if i in p: out.append(1) p.remove(i) else: out.append(0) print(out) Prints: [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]
6
5
72,403,062
2022-5-27
https://stackoverflow.com/questions/72403062/seaborn-displot-normalize-kdes-for-two-different-sample-batches
I was wondering if there is a quick way to normalize the KDE curves (such that the integral of each curve is equal to one) for two displayed sample batches (see figure below). So far I use: sb.displot(data=proc, x="TPSA", hue="Data", kind="kde", legend=False) Giving me the following plot: non-normalized KDE Plot. Than...
When the hue parameter is set, seaborn by default normalises with respect to the area of all kde curves combined. If you'd like to normalise each curve independently (so the area under each curve is 1), you should provide the displot/kdeplot with common_norm=False. e.g. in your case sb.displot(data=proc, x="TPSA", hue=...
3
9
72,400,524
2022-5-27
https://stackoverflow.com/questions/72400524/why-the-location-of-python-list-is-not-being-changed-if-the-size-is-increased
As far as I know, python list is a dynamic array. So when we reach a certain size, the capacity of that list will be increased automatically. But the problem is, unlike dynamic array of c or c++, even after increasing the capacity of list instance, the location is not being changed. Why is it happening? I've tested thi...
In CPython (the implementation written in C distributed by python.org), a Python object never moves in memory. In the case of a list object, two pieces of memory are actually allocated: a basic header struct common to all variable-size Python container objects (containing things like the reference count, a pointer to t...
3
10
72,397,740
2022-5-26
https://stackoverflow.com/questions/72397740/issues-with-spacy-model-en-core-web-lg-how-to-prevent-the-package-from-downloa
I am using spacy and its model en_core_web_lg, to perform summarisation in python. The code is running perfectly and there is no error at all. Except that, I am trying to find a way of making sure that the en_core_web_lg doesn't keep downloading in an environment if it already has it. I have googled a lot to find a per...
spaCy doesn't automatically download models at all, so this must be a bug with your code that checks if the model is already installed. Looking at this code: try: nlp_lg = spacy.load("en_core_web_lg") except ModuleNotFoundError: download(model="en_core_web_lg") nlp_lg = spacy.load("en_core_web_lg") The issue is that i...
5
3
72,398,163
2022-5-26
https://stackoverflow.com/questions/72398163/returning-default-members-when-enum-member-does-not-exist
I have an Enum where I would like a default member to be returned when a member does not exist inside of it. For example: class MyEnum(enum.Enum): A = 12 B = 24 CUSTOM = 1 print(MyEnum.UNKNOWN) # Should print MyEnum.CUSTOM I know I can use a metaclass like so: class MyMeta(enum.EnumMeta): def __getitem__(cls, name): t...
Add a definition for __getattr__ to the metaclass: class MyMeta(enum.EnumMeta): def __getitem__(cls, name): try: return super().__getitem__(name) except KeyError as error: return cls.CUSTOM def __getattr__(cls, name): try: return super().__getattr__(name) except AttributeError as error: return cls.CUSTOM Then, your co...
6
4
72,396,233
2022-5-26
https://stackoverflow.com/questions/72396233/why-write-async-code-in-python-while-gil-exists
I am wondering, if python GIL allow only a single thread / process to run at once, why should I use asyncio, I get that switching between threads is expensive but, thats it? this is the only advantage of asyncio in python?
Threading in Python is inefficient because of the GIL (Global Interpreter Lock) which means that multiple threads cannot be run in parallel as you would expect on a multi-processor system. Plus you have to rely on the interpreter to switch between threads, this adds to the inefficiency. asyc/asyncio allows concurrency ...
5
7
72,392,884
2022-5-26
https://stackoverflow.com/questions/72392884/fastest-way-to-check-if-a-list-of-sets-has-any-containment-relationship
I hava a list of 10,000 random sets with different lengths: import random random.seed(99) lst = [set(random.sample(range(1, 10000), random.randint(1, 1000))) for _ in range(10000)] I want to know the fastest way to check if there is any set that is a subset of another set (or equivalently if there is any set that is a...
Seems to be faster to sort by length and then try small sets as subset first (and for each, try large sets as superset first). Times in ms from ten cases, data generated like you did but without seeding: agree yours mine ratio result True 2.24 2.98 0.75 True True 146.25 3.10 47.19 True True 121.66 2.90 41.91 True True ...
4
6
72,380,478
2022-5-25
https://stackoverflow.com/questions/72380478/can-a-python-script-using-xlwings-be-deployed-on-a-server
We currently have a python script launched locally that periodically generates dozens of Excel files using Xlwings. How can it be deployed on a cloud server as an ETL that would be linked to a job scheduler, so that no human action is needed anymore? My concern is that Xlwings requires an Excel license (and a GUI?), wh...
The only way that you can currently do what you have in mind is to install Excel, Python, and xlwings on a Windows Server: xlwings was built for interactive workflows. You might want to look into OpenPyXL and XlsxWriter to see if you can create the reports by writing the Excel file directly, as opposed to automating th...
6
4
72,384,268
2022-5-25
https://stackoverflow.com/questions/72384268/does-polars-support-creating-a-dataframe-from-a-nested-dictionary
I'm trying to create a polars dataframe from a dictionary (mainDict) where one of the values of mainDict is a list of dict objects (nestedDicts). When I try to do this I get an error (see below) that I don't know the meaning of. However, pandas does allow me to create a dataframe using mainDict. I'm not sure whether I'...
The error you are receiving is because your list of dictionaries does not conform to the expectations for a Series of struct in Polars. More specifically, your two dictionaries {'D1':'D2'} and {'DD1':'DD2'} are mapped to two different types of structs in Polars and thus are incompatible for inclusion in the same Series...
5
5
72,380,087
2022-5-25
https://stackoverflow.com/questions/72380087/is-it-possible-to-unpack-a-list-of-classes-for-use-in-a-union-type-annotation
I have a number of SQLAlchemy ORM classes that map to a database. I've written quite a few functions that utilise a number of these classes in different combinations. For example I might want to get the first from the Tournament table or the first record from the Player table. I only need one query for this as the quer...
I think it's not possible to do literally what you're asking for here: tables = [Tournament, Player] Tables = Type[Union[*tables]] # no bueno :( See these other questions for more detail: Create Union type without hard-coding in Python3 typing typing: Dynamically Create Literal Alias from List of Valid Values How do ...
4
1
72,382,501
2022-5-25
https://stackoverflow.com/questions/72382501/how-to-interpret-mape-in-python-sklearn
I am trying to interpret the value that I get out of sklearn.metrics.mean_absolute_percentage_error(y_true, y_pred), but have difficulty to understand the interpretation. I need to interpret the result based on below accepted (?) schema Based on the official Python explanation: Note here that the output is not a perce...
If you look at the source code for the mape calculation in sklearn you will see the value is not multiplied by 100, so it is not a percentage. Therefore, while interpreting your results, you should multiply the mape value by a 100 to have it in percentage. You must also pay a close attention to your actual data if ther...
4
7
72,374,146
2022-5-25
https://stackoverflow.com/questions/72374146/histogram-equalization-on-specific-area-using-mask
I am working with images that I need to process. However, only specific areas of these images are of interest so for each image I have a corresponding mask (that can be of any shape, not a bounding box or anything specific). I would like to do Histogram Equalization but only on the "masked surface" as I am not interest...
This is possible. Here is a simple approach: Flow: You can perform histogram equalization for a given region with the help of the mask. Using the mask, store coordinates where pixels are in white. Store pixel intensities from these coordinates present in the grayscale image Perform histogram equalization on these stor...
4
5
72,372,635
2022-5-25
https://stackoverflow.com/questions/72372635/importerror-cannot-import-name-re-path-from-django-conf-urls
I'm following a Django tutorial and trying to update a urls.py file with the following code: from django.contrib import admin from django.urls import path from django.conf.urls import re_path, include urlpatterns=[ path('admin/', admin.site.urls), re_path(r'^',include('EmployeeApp.urls')) ] When I run the server with ...
I needed to change from django.conf.urls import re_path, include to: from django.conf.urls import include from django.urls import re_path Now the error has stopped. (Documentation)
6
11
72,368,336
2022-5-24
https://stackoverflow.com/questions/72368336/what-is-a-meshloop-in-the-blender-python-api
I'm currently making a custom render engine for Blender 3.0+. I'm programming in C++(core engine) and Python(Blender API). In the past I have made two other render engines, where the data stored for meshes are polygons, edges and vertices, which is quite usual. Blender uses a different structure, where a polygon refere...
What the MeshLoop is in Blender API You're undoubtedly right about official documentation, even in 2024 it sucks. But the answer to your question is obvious. MeshLoop objects are tiny "utilities" in Blender that help you not only describe a 3D geometry but also store a color data for each vertex. There are four main ar...
6
1
72,352,725
2022-5-23
https://stackoverflow.com/questions/72352725/how-to-increase-values-of-polars-dataframe-column-by-index
I have a data frame as follow ┌────────────┬──────────┬──────────┬──────────┬──────────┐ │ time ┆ open ┆ high ┆ low ┆ close │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │ ╞════════════╪══════════╪══════════╪══════════╪══════════╡ │ 1649016000 ┆ 46405.49 ┆ 47444.11 ┆ 46248.84 ┆ 46407.35 │ │ 1649030400...
Let me see if we can build on @ritchie46 response and nudge you closer to the finish line. Data I've concatenated the 'open', 'high', and 'low' columns in your sample data, just to give us some data to work with. I've also added an index column, just for discussion. (It won't be used in any calculations whatsoever, so ...
4
4
72,294,299
2022-5-18
https://stackoverflow.com/questions/72294299/multiple-top-level-packages-discovered-in-a-flat-layout
I am trying to install a library from the source that makes use of Poetry, but I get this error error: Multiple top-level packages discovered in a flat-layout: ['tulips', 'fixtures']. To avoid accidental inclusion of unwanted files or directories, setuptools will not proceed with this build. If you are trying to create...
Based on this comment on a GitHub issue, adding the following lines to your pyproject.toml might solve your problem: [tool.setuptools] py-modules = [] (For my case, the other workaround provided in that comment, i.e. adding py_modules=[] as a keyword argument to the setup() function in setup.py worked) See Package Dis...
88
92
72,345,536
2022-5-23
https://stackoverflow.com/questions/72345536/how-to-avoid-mypy-checking-explicitly-excluded-but-imported-modules-without-ma
In the following MWE, I have two files/modules: main.py which is and should be checked with mypy and importedmodule.py which should not be type checked because it is autogenerated. This file is autogenerated, I don't want to add type:ignore. MyPy Command $ mypy main.py --exclude '.*importedmodule.*' $ mypy --version...
Here is SUTerliakov's comment on your question written as an answer. In the pyproject.toml file you can insert the following below your other mypy config [[tool.mypy.overrides]] module = "importedmodule" ignore_errors = true With this config you will ignore all errors coming from the mentioned module. By using a wildc...
12
10
72,295,812
2022-5-18
https://stackoverflow.com/questions/72295812/python-match-case-by-type-of-value
I came across a weird issue while using the new match/case syntax in Python3.10. The following example seems like it should work, but throws an error: values = [ 1, "hello", True ] for v in values: match type(v): case str: print("It is a string!") case int: print("It is an integer!") case bool: print("It is a boolean!"...
Rather than match type(v), match v directly: values = [ 1, "hello", True, ] for v in values: match v: case str(): print("It is a string!") case bool(): print("It is a boolean!") case int(): print("It is an integer!") case _: print(f"It is a {type(v)}!") Note that I've swapped the order of bool() and int() here, so tha...
43
50
72,360,442
2022-5-24
https://stackoverflow.com/questions/72360442/pydantic-transform-a-value-before-it-is-assigned-to-a-field
I have the following model class Window(BaseModel): size: tuple[int, int] and I would like to instantiate it like this: fields = {'size': '1920x1080'} window = Window(**fields) Of course this fails since the value of 'size' is not of the correct type. However, I would like to add logic so that the value is split at x...
Pydantic 2.x (edit) Pydantic 2.0 introduced the field_validator decorator which lets you implement such a behaviour in a very simple way. Given the original parsing function: from pydantic import BaseModel, field_validator class Window(BaseModel): size: tuple[int, int] @field_validator("size", mode="before") @classmeth...
18
30
72,298,911
2022-5-19
https://stackoverflow.com/questions/72298911/where-to-locate-virtual-environment-installed-using-poetry-where-to-find-poetr
I installed poetry using the following command:- (Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python - To know more about it refer this. Now I wanted to create a virtual environment, that I created it using the following command:- poetr...
There are 2 commands that can find where the virtual environment is located. poetry show -v The first line of this command will tell you where the virtual environment is located. And the rest will tell you which packages are installed in it. poetry env info -p The above command will give you just the location of the ...
35
58
72,343,232
2022-5-23
https://stackoverflow.com/questions/72343232/pip-install-confluent-kafka-gives-error-in-mac
When i tried pip install confluent-kafka got the following error #include <librdkafka/rdkafka.h> ^~~~~~~~~~~~~~~~~~~~~~ 1 error generated. error: command '/usr/bin/gcc' failed with exit code 1 I'm using python version 3.9 and macOs Monterey
Install the librdkafka library brew install librdkafka Set the environment variables export C_INCLUDE_PATH=/usr/local/Cellar/librdkafka/2.2.0/include export LIBRARY_PATH=/usr/local/Cellar/librdkafka/2.2.0/lib Then you can install it through pip install
4
12
72,352,528
2022-5-23
https://stackoverflow.com/questions/72352528/how-to-fix-winerror-206-the-filename-or-extension-is-too-long-error
I'm facing this error while installing the setup for Tensorflow Object Detection API. How to fix this error? Error: Could not install packages due to an OSError: [WinError 206] The filename or extension is too long: ```
Error: Could not install packages due to an OSError: [WinError 206] The filename or extension is too long: To fix this error on your Windows machine on regedit and navigate to Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem and edit LongPathsEnabled and set value from 0 to 1
12
24
72,360,709
2022-5-24
https://stackoverflow.com/questions/72360709/how-to-serialize-custom-type-that-extends-builtin-type-in-pydantic
currently I'm working with FastAPI and pydantic as serializer. Problem is, we're using snowflake id on the server side, which means we need to convert those ids to string before sending to client (javascript) because the id is larger than JS's MAX SAFE INTEGER. So I tried to create a new class which extends python's in...
Yes it is! json_encoders is a good try, however under the hood pydantic calls json.dumps. So for serializable types (like your SnowflakeId) it won't care about additional json_encoders. What you can do is to override dumps method: def my_dumps(v, *, default): for key, value in v.items(): if isinstance(value, SnowflakeI...
9
4
72,306,836
2022-5-19
https://stackoverflow.com/questions/72306836/airflow-branch-operator-and-task-group-invalid-task-ids
I have a simple dag that uses a branch operator to check if y is False. If it is, the dag is supposed to move on to the say_goodbye task group. If True, it skips and goes to finish_dag_step. Here's the dag: def which_step() -> str: y = False if not y: return 'say_goodbye' else: return 'finish_dag_step' with DAG( 'my_te...
You can't create task dependencies to a TaskGroup. Therefore, you have to refer to the tasks by task_id, which is the TaskGroup's name and the task's id joined by a dot (task_group.task_id). Your branching function should return something like def branch(): if condition: return [f'task_group.task_{i}' for i in range(0,...
4
7
72,338,356
2022-5-22
https://stackoverflow.com/questions/72338356/how-to-show-values-in-pandas-pie-chart
I would like to visualize the amount of laps a certain go-kart has driven within a pie chart. To achive this i would like to count the amount of laptime groupedby kartnumber. I found there are two ways to create such a pie chart: 1# df.groupby('KartNumber')['Laptime'].count().plot.pie() 2# df.groupby(['KartNumber']).c...
Complete awswer: autopct=lambda x: '{:.0f}'.format(x * (df['Laptime'].count()) / 100))
4
1
72,352,491
2022-5-23
https://stackoverflow.com/questions/72352491/how-to-plot-errorbars-on-seaborn-barplot
I have the following dataframe: data = {'Value':[6.25, 4.55, 4.74, 1.36, 2.56, 1.4, 3.55, 3.21, 3.2, 3.65, 3.45, 3.86, 13.9, 10.3, 15], 'Name':['Peter', 'Anna', 'Luke', 'Peter', 'Anna', 'Luke', 'Peter', 'Anna', 'Luke', 'Peter', 'Anna', 'Luke', 'Peter', 'Anna', 'Luke'], 'Param': ['Param1', 'Param1', 'Param1', 'Param2', ...
The bars in ax.patches come ordered by hue value. To get the bars and the dataframe in the same order, the dataframe could be sorted first by Name and then by Param: from matplotlib import pyplot as plt import seaborn as sns import pandas as pd data = {'Value': [6.25, 4.55, 4.74, 1.36, 2.56, 1.4, 3.55, 3.21, 3.2, 3.65,...
8
11
72,352,801
2022-5-23
https://stackoverflow.com/questions/72352801/migration-from-setup-py-to-pyproject-toml-how-to-specify-package-name
I'm currently trying to move our internal projects away from setup.py to pyproject.toml (PEP-518). I'd like to not use build backend specific configuration if possible, even though I do specify the backend in the [build-system] section by require'ing it. The pyproject.toml files are more or less straight-forward transl...
Turning @AKX's comments into an answer so that other people can find it more easily. The problem may be an outdated pip/setuptools on the system. Apparently, version 19.3.1 which I have on my system cannot install a version of setuptools that can handle PEP621 metadata correctly. You cannot require a new pip from withi...
13
3
72,350,835
2022-5-23
https://stackoverflow.com/questions/72350835/how-to-plot-loss-when-using-hugginfaces-trainer
While finetuning a model using HF's trainer. training_args = TrainingArguments(output_dir=data_dir + "test_trainer") metric = load_metric("accuracy") def compute_metrics(eval_pred): logits, labels = eval_pred predictions = np.argmax(logits, axis=-1) return metric.compute(predictions=predictions, references=labels) trai...
It is possible to get a list of losses. You can access the history of logs after training is complete with: trainer.state.log_history
7
4
72,313,080
2022-5-20
https://stackoverflow.com/questions/72313080/how-to-check-for-unit-root-in-panel-data-using-python
I am working on time series analysis and I have sales data (lets call it df_panel as we panel data structure) for 700 individual areas for each month of 2021. e.g. Area Month Sales Area 1 January 1000 Area 1 February 2000 Area 1 Marts 3000 Area 2 January 1000 Area 2 February 2000 Area 2 Marts 1400 A...
The SAS documentation website HERE tells us that the IPS method uses the average of the ADF test statistics across groups/panels. The ADF test is available from the package "statsmodel" library HERE, so you can simply calculate the tau-statistics yourself, take the average, and calculate the p-value using a t-test. # p...
4
2
72,331,816
2022-5-21
https://stackoverflow.com/questions/72331816/how-to-connect-to-an-existing-firefox-instance-using-selenium-python
Is there any way to open a Firefox browser and then connect to it using selenium? I know this is possible on chrome by launching it in the command line and using --remote-debugging-port argument like this: import subprocess from selenium import webdriver from selenium.webdriver.chrome.options import Options subprocess....
CMD: C:\Program Files\Mozilla Firefox\ firefox.exe -marionette -start-debugger-server 2828 //only use 2828 Python Script: from selenium import webdriver driver = webdriver.Firefox(executable_path = "YOUR GECKODRIVER PATH", service_args = ['--marionette-port', '2828', '--connect-existing'] ) pageSource = driver.page_so...
6
5
72,325,242
2022-5-20
https://stackoverflow.com/questions/72325242/type-object-base-has-no-attribute-decl-class-registry
I am upgrading a library to a recent version of SQLAlchemy and I am getting this error type object 'Base' has no attribute '_decl_class_registry' On line Base = declarative_base(metadata=metadata) Base._decl_class_registry How can I solve this?
Had the same problem. Because of my upgrade of sqlalchemy looks like there is a change in the base code. use this instead to accomplish the same Base.registry._class_registry.values()
8
12
72,363,601
2022-5-24
https://stackoverflow.com/questions/72363601/how-to-interpret-the-package-would-be-ignored-warning-generated-by-setuptools
I work on several python packages that contain data within them. I add them via the MANIFEST.in file, passing include_package_data=True to setup. For example: # MANIFEST.in graft mypackage/plugins graft mypackage/data Up to now, this has worked without warnings as far as I know. However, in setuptools 62.3.0, I get th...
The TL;DR is that in Python since PEP 420, directories count as packages, even if they don't have a __init__.py file. The main difference is that directories without __init__.py are called "namespace packages". Accordingly, if a project wants to distribute directories without a __init__.py file, it should use packages=...
20
15
72,309,492
2022-5-19
https://stackoverflow.com/questions/72309492/how-do-i-install-the-same-pip-dependencies-locally-as-are-installed-in-my-cloud
I'm trying to set up a local development environment in VS Code where I'd get code completion for the packages Cloud Composer/Apache Airflow uses. I've been successful so far using a virtual environment (created with python -m venv .venv) and a very minimal requirements.txt file that contains just the Airflow package, ...
So the two incompatibilities in Cloud Composer dependencies as listed on the official website are apache-airflow and apache-airflow-providers-google (or apache-airflow-backport-providers-google if you are using Cloud Composer v1). What you need to do is to replace these two dependencies with the correct pins. For exam...
7
6
72,366,034
2022-5-24
https://stackoverflow.com/questions/72366034/code-duplication-in-api-design-for-url-route-functions-vs-real-world-object-met
I have code duplication in my API design for the object methods vs. the URL routing functions: # door_model.py class Door: def open(self): # "Door.open" written once... ... # http_api.py (the HTTP server is separated from the real-world object models) @app.route('/api/door/open') # ... written twice def dooropen(): # ...
If we declare a route for every model action and do the same things for each (in your case, call the corresponding method with or without parameter), it will duplicate the code. Commonly, people use design patterns (primarily for big projects) and algorithms to avoid code duplications. And I want to show a simple examp...
4
3
72,320,478
2022-5-20
https://stackoverflow.com/questions/72320478/pyinstaller-every-joblib-parallel-call-creates-a-new-tkinter-window-on-macos
Here is the code which can reproduce the problem (it is just for reproducing the problem, so what it does is a bit meaningless): from joblib import Parallel, delayed import tkinter as tk def f(): print('func call') if __name__ == '__main__': root = tk.Tk() button = tk.Button(root, command=lambda: Parallel(n_jobs=-1, ba...
The problem is solved by adding multiprocessing.freeze_support() to the code. The fixed version of code is as below: import multiprocessing multiprocessing.freeze_support() from joblib import Parallel, delayed import tkinter as tk def f(): print('func called') if __name__ == '__main__': root = tk.Tk() button = tk.Butto...
4
4
72,361,314
2022-5-24
https://stackoverflow.com/questions/72361314/504-gateway-timeout-only-in-django-function
I have a very mind-boggling problem and my team has struggled to solve it. We do have it narrowed down but not 100%. Introduction We are trying to implement LTI in a Django app with the Vue frontend. To fetch the token from the URL the backend makes a POST request to the URL with data and should receive a token or erro...
After days of trying to figure it out, we deployed the project with Production settings and it worked. Upon investigation on why it was not working on staging we found the following: Front end sends a POST request to the back end Backend then encoded the data using the private key and sent it to a 3rd party server Bec...
4
3
72,369,250
2022-5-24
https://stackoverflow.com/questions/72369250/weird-datetime-utcnow-bug
Consider this simple Python script: $ cat test_utc.py from datetime import datetime for i in range(10_000_000): first = datetime.utcnow() second = datetime.utcnow() assert first <= second, f"{first=} {second=} {i=}" When I run it from the shell like python test_utc.py it finishes w/o errors, just as expected. However,...
utcnow refers to now refers to today refers to fromtimestamp refers to time, which says: While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. The utcnow code also shows its usage of time: def utcnow(cl...
7
9
72,367,342
2022-5-24
https://stackoverflow.com/questions/72367342/selecting-items-on-a-matrix-based-on-indexes-given-by-an-array
Consider this matrix: [0.9, 0.45, 0.4, 0.35], [0.4, 0.8, 0.3, 0.25], [0.5, 0.45, 0.9, 0.35], [0.2, 0.18, 0.8, 0.1], [0.6, 0.45, 0.4, 0.9] and this list: [0,1,2,3,3] I want to create a list that looks like the following: [0.9, 0.8, 0.9, 0.1, 0.9] To clarify, for each row, I want the element of the matrix whose column...
Zip the two lists together as below a=[[0.9, 0.45, 0.4, 0.35],[0.4, 0.8, 0.3, 0.25],[0.5, 0.45, 0.9, 0.35],[0.2, 0.18, 0.8, 0.1],[0.6, 0.45, 0.4, 0.9]] b=[0,1,2,3,3] [i[j] for i,j in zip(a,b)] Result [0.9, 0.8, 0.9, 0.1, 0.9] This basically pairs up each sublist in the matrix with the element of your second list in o...
4
3
72,362,774
2022-5-24
https://stackoverflow.com/questions/72362774/understanding-gradient-computation-using-backward-in-pytorch
I'm trying to understand the basic pytorch autograd system: x = torch.tensor(10., requires_grad=True) print('tensor:',x) x.backward() print('gradient:',x.grad) output: tensor: tensor(10., requires_grad=True) gradient: tensor(1.) since x is a scalar constant and no function is applied to it, I expected 0. as the gradi...
Whenever you are using value.backward(), you compute the derivative value (in your case value == x) with respect to all your parameters (in your case that is just x). Roughly speaking, this means all tensors that are somehow involved in your computation that have requires_grad=True. So this means x.grad = dx / dx = 1 ...
4
6
72,362,566
2022-5-24
https://stackoverflow.com/questions/72362566/access-previous-dataframe-during-pandas-method-chaining
Method chaining is a known way to improve code readability and often referred to as a Fluent API [1, 2]. Pandas does support this approach as multiple method calls can be chained like: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd d = {'col1': [1, 2, 3, 4], 'col2': [5, np.nan, 7,...
Use pipe: dropped = ( pd .concat([df_1, df_2], axis=1) .pipe(lambda d: d.dropna(how='any', subset=[c for c in d.columns if c != 'col4'])) ) output: col1 col2 col3 col4 col10 col20 col30 0 1 5.0 9.0 NaN 10 50.0 90.0 2 3 7.0 11.0 NaN 30 70.0 110.0 NB. alternative syntax for the dropna: lambda d: d.dropna(how='any', su...
4
3
72,360,040
2022-5-24
https://stackoverflow.com/questions/72360040/how-to-find-the-frequency-of-the-most-frequent-value-mode-of-a-series-in-polar
import polars as pl df = pl.DataFrame({ "tags": ["a", "a", "a", "b", "c", "c", "c", "c", "d"] }) This is how to compute the most frequent element of the column using the .mode expression: df.select([ pl.col("tags").mode().alias("mode"), ]) How can I display also the frequency/count of that mode?
There is a value_counts expression. This expression will return a Struct datatype where the first field is the unique value and the second field is the count of that value. df.select([ pl.col("tags").value_counts() ]) shape: (4, 1) ┌───────────┐ │ tags │ │ --- │ │ struct[2] │ ╞═══════════╡ │ {"c",4} │ ├╌╌╌╌╌╌╌╌╌╌╌┤ │ ...
4
4
72,351,552
2022-5-23
https://stackoverflow.com/questions/72351552/vs-code-debugging-prompting-for-arguments-and-also-setting-the-working-directory
I know how to pass fixed arguments in the launch.json, e.g. In Visual Studio Code, how to pass arguments in launch.json . What I really need is a prompt where I can give a value for an argument that changes. In addition, my argument is a (data) directory for which there is a very ugly long absolute path. I'd really lik...
You can use input variables { "version": "0.2.0", "configurations": [ { "name": "Python: Current File with arguments", "type": "python", "request": "launch", "program": "${file}", "args": [ "--dir", "/some/fixed/dir/${input:enterDir}" ] } ], "inputs": [ { "id": "enterDir", "type": "promptString", "description": "Subdir...
10
19
72,339,128
2022-5-22
https://stackoverflow.com/questions/72339128/cython-error-while-building-extension-microsoft-visual-c-14-0-or-greater-is
Short Description: I'm trying to build an example cython script, but when I run the python setup.py build_ext --inplace command, I get an error saying that I need MS Visual C++ version 14.0 or greater. I've tried a lot of the things on related SO threads and other forums but to no avail in resolving the issue. Longer D...
Both the main python issue and the secondary CLion thing that I mentioned were resolved with this one solution (the issues were connected after all!) Clear the registry key that is mentioned in this SO thread: https://stackoverflow.com/a/64389979/15379178 This error had nothing to do with python (sort of) or msvc, in s...
5
2
72,323,871
2022-5-20
https://stackoverflow.com/questions/72323871/in-plotly-dash-how-do-i-source-a-local-image-file-to-dash-html-img
This is how to source a local image file to the <img> element in html: <html> <h1>This is an image</h1> <img src="file:///C:/Users/MyUser/Desktop/Plotly_Dash_logo.png" alt="image"></img> </html> This displays the image as expected. But when I try to make the same page using the plotly dash wrapper elements, it does no...
After some more searching, I found that I could place my image file in a folder named "assets/", then reference it relative to the app folder. html.Img(src=r'assets/Plotly_Dash_logo.png', alt='image') I could also use a special method of the app instance dash.Dash.get_asset_url(). html.Img(src=app.get_asset_url('my-im...
4
9
72,338,808
2022-5-22
https://stackoverflow.com/questions/72338808/how-to-calculate-per-document-probabilities-under-respective-topics-with-bertopi
I am trying to use BERTopic to analyze the topic distribution of documents, after BERTopic is performed, I would like to calculate the probabilities under respective topics per document, how should I did it? # define model model = BERTopic(verbose=True, vectorizer_model=vectorizer_model, embedding_model='paraphrase-Min...
First, to compute probabilities, you have to add to your model definition calculate_probabilities=True (this could slow down the extraction of topics if you have many documents, > 100000). # define model model = BERTopic(verbose=True, vectorizer_model=vectorizer_model, embedding_model='paraphrase-MiniLM-L3-v2', min_top...
4
6
72,343,944
2022-5-23
https://stackoverflow.com/questions/72343944/cv2-imshow-doesnt-work-when-easyocr-installed
I installed easyocr in a newly created python environment using pip install easyocr. Then i installed opencv-python. when i try to execute the code - import cv2 img = cv2.imread('2.jpg') cv2.imshow('sd',img) cv2.waitKey(0) It's giving error OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\win...
Problem: If you already have an existing OpenCV version in your system/environment; installing easyOCR can alter that. Going through the requirements.txt file of easyOCR, opencv-python-headless gets installed. The following excerpt is taken from opencv-python-headless documentation: Packages for server (headless) envi...
6
7
72,345,302
2022-5-23
https://stackoverflow.com/questions/72345302/save-jalalihijri-shamsi-datetime-in-database-in-django
I have a Django project, and I want to save created_at datetime in the database. I generate datetime.now with jdatetime (or Khayyam) python package and try to save this in DateTimeField. But sometimes it raises error because the Gregorian(miladi) date of the entry does not exist. what can I do about this?
In my idea, you can save two model fields. One is DateTimeField contains gregorian datetime, and another one, CharField contains converted Jalali to a String value and save it. The DateTimeField for functionality, e.g., filter between to datetime. The StringField for representing in response(without overload).
4
4
72,344,392
2022-5-23
https://stackoverflow.com/questions/72344392/how-to-split-column-of-type-intervalint64-right-onto-two-columns-in-pandas
Given a df as follow time_interval dvalue 0 (0, 5] 1 1 (5, 10] 2 2 (10, 15] 4 3 (15, 20] 5 4 (20, 25] 6 5 (25, 30] 7 6 (30, 35] 8 I would like to split the column time_interval, which of type interval[int64, right] as the following dvalue l u 0 1 0 5 1 2 5 10 2 4 10 15 3 5 15 20 4 6 20 25 5 7 25 30 6 8 30 35 The fu...
Use Interval.left and Interval.right: df['l'] = df['time_interval'].apply(lambda x: x.left) df['u'] = df['time_interval'].apply(lambda x: x.right) df['l'] = df['time_interval'].map(lambda x: x.left) df['u'] = df['time_interval'].map(lambda x: x.right) Or first convert to IntervalIndex: idx = pd.IntervalIndex(df['tim...
4
2
72,338,204
2022-5-22
https://stackoverflow.com/questions/72338204/flask-show-loading-page-while-another-time-consuming-function-is-running
Hi everyone. I'm developing my first flask project and I got stuck on the following problem: I have a simple Flask app: from flask import Flask, render_template import map_plotting_test as mpt app = Flask(__name__) @app.route('/') def render_the_map(): mpt.create_map() return render_template("map.html") if __name__ == ...
Finally I found the solution! Thanks to Laurel's answer. I'll just make it more nice and clear. What I've done I redesigned my Flask app, so it looks like this: from flask import Flask, render_template import map_plotting_module as mpm app = Flask(__name__) @app.route('/') def loading(): return render_template("loadi...
5
10
72,324,669
2022-5-20
https://stackoverflow.com/questions/72324669/playwright-download-via-print-to-pdf
I'm seeking to scrape a web page using Playwright. I load the page, and click the download button with Playwright successfully. This brings up a print dialog box with a printer selected. I would like to select "Save as PDF" and then click the "Save" button. Here's my current code: with sync_playwright() as p: browser ...
Thanks very much to @KJ in the comments, who suggested that with headless=True, Chromium won't even put up a print dialog box in the first place.
5
2
72,339,545
2022-5-22
https://stackoverflow.com/questions/72339545/attributeerror-cant-pickle-local-object-locals-lambda
I am trying to pickle a nested dictionary which is created using: collections.defaultdict(lambda: collections.defaultdict(int)) My simplified code goes like this: class A: def funA(self): #create a dictionary and fill with values dictionary = collections.defaultdict(lambda: collections.defaultdict(int)) ... #then pick...
pickle records references to functions (module and function name), not the functions themselves. When unpickling, it will load the module and get the function by name. lambda creates anonymous function objects that don't have names and can't be found by the loader. The solution is to switch to a named function. def cre...
21
19
72,335,807
2022-5-22
https://stackoverflow.com/questions/72335807/pip3-install-grpcio-fails-on-alpine-linux
I use Alpine Linux by Docker on my Mac (12.3.1) and try to run pip3 install grpcio but this command always fails. I tried info here, but nothing worked until now. Unable to install grpcio using pip install grpcio --> Upgrade to the latest setuptools https://github.com/grpc/grpc/issues/24390 --> Run export GRPC_PYTHON_B...
The build environment for Alpine Linux is not installed by default. You need to install the header files - apk add linux-headers. This was in found in this github issue: grpcio can't be installed on alpine
4
8
72,336,254
2022-5-22
https://stackoverflow.com/questions/72336254/negative-huge-loss-in-tensorflow
I am trying to predict price values from datasets using keras. I am following this tutorial: https://keras.io/examples/structured_data/structured_data_classification_from_scratch/, but when I get to the part of fitting the model, I am getting a huge negative loss and very small accuracy Epoch 1/50 1607/1607 [==========...
You seem to be quite confused by the components of your model. Binary cross entropy is a classification loss, your problem is regression -> use MSE. Also "accuracy" makes no sense for regression, change it to MSE too. You data is huge and thus your loss is huge. You have a price of 113109.14 in the data, what if your ...
6
4
72,336,173
2022-5-22
https://stackoverflow.com/questions/72336173/make-a-get-request-with-a-multiple-value-param-in-django-requests-module
I have a webservice that give doc list. I call this webservice via get_doc_list. but when I pass 2 values to id__in, it return one mapping object. def get_doc_list(self, id__in): config = self.configurer.doc params = { "id__in": id__in, } response = self._make_request( token=self.access_token, method='get', proxies=sel...
You can add this two lines before make_request: string_id_in = [str(i) for i in id_in] id_in = ",".join(string_id_in)
5
4
72,334,642
2022-5-22
https://stackoverflow.com/questions/72334642/importerror-cannot-import-name-img-to-array-from-keras-preprocessing-image
Im new here. I have problem with this code, #Library import numpy as np import pickle import cv2 from os import listdir from sklearn.preprocessing import LabelBinarizer from keras.models import Sequential from keras.layers import BatchNormalization from keras.layers.convolutional import Conv2D from keras.layers.convolu...
In Keras Documentation V2.9.0, In tf version 2.9.0 the img_to_array moved to utlis Insted of, from keras.preprocessing.image import img_to_array Try this, from tensorflow.keras.utils import img_to_array
12
33
72,332,222
2022-5-21
https://stackoverflow.com/questions/72332222/how-do-i-json-normalize-a-specific-field-within-a-df-and-keep-the-other-column
So here's my simple example (the json field in my actual dataset is very nested so I'm unpacking things one level at a time). I need to keep certain columns on the dataset post json_normalize(). https://pandas.pydata.org/docs/reference/api/pandas.json_normalize.html Start: Expected (Excel mockup): Actual: import jso...
as you're dealing with a pretty simple json along a structured index you can just normalize your frame then make use of .join to join along your axis. from ast import literal_eval df.join( pd.json_normalize(df['report_json'].map(literal_eval)) ).drop('report_json',axis=1) report_id start_date name age disease 0 100 202...
6
7
72,331,707
2022-5-21
https://stackoverflow.com/questions/72331707/socket-io-returns-127-0-0-1-as-host-address-and-not-192-168-0-on-my-device
When I run the following code to determine my device's local IP address, I get 127.0.0.1 instead of 192.168.0.101. import socket import threading PORT = 8080 HOST_NAME = socket.gethostname() print(HOST_NAME) SERVER = socket.gethostbyname(HOST_NAME) print(SERVER) The output i get on the console is MyDeviceName.local 12...
127.0.0.1 is localhost address, it is right. If you want your device's address do this: import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(s.getsockname()[0])
4
6
72,313,046
2022-5-20
https://stackoverflow.com/questions/72313046/pycharm-project-cannot-add-poetry-interpreter
OS: win10 PyCharm version: PyCharm Professional 2021.2.2 Poetry version: 1.1.13 Poetry plugin version: 1.1.5-212 (from koudai aono) I have tried to build a new PyCharm project by poetry environment, while setting up it showed and cannot setup the interpreter. Have anyone got the similar problem before and know how ...
Alright, I have fixed this problem. Below is my debug steps, hope it can help those who are struggling in the same situation: Posting a support report to PyCharm team with no responce Searching for a lot of posts from communities Creating a poetry project by terminal Inside the project directory, I tried poetry env in...
7
11
72,327,987
2022-5-21
https://stackoverflow.com/questions/72327987/mypy-how-to-declare-the-return-type-of-a-method-returning-self-in-a-generic-cla
This answer does not seem to work for generics. Mypy complains about "error: Missing type parameters for generic type A" when checking the following code. I have tried using 'A[T]' for the TypeVar but then mypy says "error: Type variable T is unbound." I have also tried using AnyA[T] as return type of get but that prod...
I know of three ways of typing here: Declaring an inner self-type This approach is described in mypy docs, see Precise typing of alternative constructors. class A(typing.Generic[T]): _Self = typing.TypeVar('_Self', bound='A[T]') def __init__(self, val: T) -> None: self.val = val def get(self: _Self) -> _Self: return se...
5
10
72,324,239
2022-5-20
https://stackoverflow.com/questions/72324239/sort-elements-to-maximise-amount-of-positive-differences
I have a list of integers. Numbers can be repeated. I would like "sort" them in that way to get as many "jumps" (difference from the very next element to the current one is positive) as possible. Examples: [10, 10, 10, 20, 20, 20] # only one "jump" from 10 to 20 [10, 20, 10, 20, 10, 20] # three jumps (10->20, 10->20, 1...
I think this should be equivalent and only take O(n log n) time for sorting and O(n) time for the rest. from collections import Counter, OrderedDict arr = [11, 16, 8, 9, 4, 1, 2, 17, 4, 15, 9, 11, 11, 7, 19, 16, 19, 5, 19, 11] d = OrderedDict(Counter(sorted(arr))) ans = [] while d: ans += d for x in list(d): d[x] -= 1 ...
4
2
72,322,295
2022-5-20
https://stackoverflow.com/questions/72322295/how-to-use-django-f-expression-in-update-for-jsonfield
I have around 12 million records that I need to update in my postgres db (so I need to do it in an efficient way). I am using Django. I have to update a jsonfield column (extra_info) to use values from a different column (related_type_id which is an integer) in the same model. Trying to do it with an update. This seems...
The Django database function JSONObject should work, it returns a valid JSON object from key-value pairs and may be passed F objects from django.db.models import F, Value from django.db.models.functions import JSONObject Person.objects.all().update(extra_info=JSONObject( type=Value('Human'), id=F('related_type_id') ))
4
4
72,322,120
2022-5-20
https://stackoverflow.com/questions/72322120/vscode-import-x-could-not-be-resolved-even-though-listed-under-helpmodules
I'm on day 1 of Python and trying to import SciPy into a project. I installed it via pip install on ElementaryOS (an Ubuntu derivative). I have verified it's existence via: $ python >>> help("modules") The exact error I'm getting is: Import "scipy" could not be resolved Pylance (reportMissingImports) When searching ...
The issue was indeed with Pylance. It was missing an "additional path" to where pip had installed the projects I wanted to import. To solve the issue: First make sure you know the location of your import; you can find it with: $ python >>> import modulename >>> print(modulename.__file__) Then, once you know the locati...
24
64
72,294,311
2022-5-18
https://stackoverflow.com/questions/72294311/what-is-numpy-ndarray-flags-contiguous-about
While experimenting with Numpy, I found that the contiguous value provided by numpy.info may differ from numpy.ndarray.data.contiguous (see the code and screenshot below). import numpy as np x = np.arange(9).reshape(3,3)[:,(0,1)] np.info(x) print(f''' {x.data.contiguous = } {x.flags.contiguous = } {x.data.c_contiguous ...
In the source code of numpy.info, we can see the subroutine for processing ndarray: def info(object=None, maxwidth=76, output=None, toplevel='numpy'): ... elif isinstance(object, ndarray): _info(object, output=output) ... def _info(obj, output=None): """Provide information about ndarray obj""" bp = lambda x: x ... prin...
4
3
72,312,594
2022-5-20
https://stackoverflow.com/questions/72312594/pandas-forward-fill-but-only-between-equal-values
I have two data frames: main and auxiliary. I am concatenating auxiliary to the main. It results in NaN in a few rows and I want to fill them, not all. Code: df1 = pd.DataFrame({'Main':[00,10,20,30,40,50,60,70,80]}) df1 = Main 0 0 1 10 2 20 3 30 4 40 5 50 6 60 7 70 8 80 df2 = pd.DataFrame({'aux':['aa','aa','bb','bb']},...
If I understand correctly, what you want can be done like this. You want to fill the NaNs where backfill and forward fill give the same value. ff = df.aux.ffill() bf = df.aux.bfill() df.aux = ff[ff == bf]
6
10
72,319,355
2022-5-20
https://stackoverflow.com/questions/72319355/space-in-f-string-leads-to-valueerror-invalid-format-specifier
A colleague and I just stumbled across an interesting problem using an f-string. Here is a minimal example: >>> f"{ 42:x}" '2a' Writing a space after the hexadecimal type leads to a ValueError: >>> f"{ 42:x }" Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Invalid format specifier ...
Per the link you shared: For ease of readability, leading and trailing whitespace in expressions is ignored. This is a by-product of enclosing the expression in parentheses before evaluation. The expression is everything[1] before the colon (:), while the format specifier is everything afterwards. { 42 : x } inside a...
4
7
72,314,928
2022-5-20
https://stackoverflow.com/questions/72314928/most-efficient-way-of-checking-if-a-string-matches-a-pattern-in-python
I have a string format that can be changed by someone else (just say) sample = f"This is a {pet} it has {number} legs" And I have currently two string a = "This is a dog it has 4 legs" b = "This was a dog" How to check which string satisfies this sample format? I can use python's string replace() on sample and create...
I liked the approaches but I found a two liner solution: (I don't know the performance aspect of this, but it works!) def pattern_match(input, pattern): regex = re.sub(r'{[^{]*}','(.*)', "^" + pattern + "$") if re.match(regex, input): print(f"'{input}' matches the pattern '{pattern}'") pattern_match(a, sample) pattern...
4
3
72,312,099
2022-5-19
https://stackoverflow.com/questions/72312099/discord-py-button-responses-interaction-failed-after-a-certain-time
I have an extremely basic script that pops up a message with a button with the command ?place Upon clicking this button the bot replies Hi to the user who clicked it. If the button isn't interacted with for > approx 3 minutes it then starts to return "interaction failed". after that the button becomes useless. I assum...
Explanation By default, Views in discord.py 2.0 have a timeout of 180 seconds (3 minutes). You can fix this error by passing in None as the timeout when creating the view. Code @bot.command(name='place') async def hello(ctx): view = discord.ui.View(timeout=None) References discord.ui.View.timeout
5
12
72,306,585
2022-5-19
https://stackoverflow.com/questions/72306585/brighten-only-dark-areas-of-image-in-python
I am trying to process images and I would like to brighten the dark areas of my image. I tried Histogram Equalization, however as there are also some bright areas in the image, the result is not satisfying. This is why I am looking for a way to brighten only the dark areas of the image. As an example, Input image is on...
If you want to avoid colour distortions, you could: convert to HSV colourspace, split the channels, bump up the V (Value) channel recombine the channels save That might go something like this: from PIL import Image # Open the image im = Image.open('hEHxh.jpg') # Convert to HSV colourspace and split channels for ease ...
6
7
72,306,979
2022-5-19
https://stackoverflow.com/questions/72306979/client-get-bucket-returns-error-api-request-got-an-unexpected-keyword-argum
I'm trying to store a newline-delimited JSON string in a GCS bucket using a cloud function, but seeing an error. I start by converting a dataframe to ndjson, then attempt to upload this to my GCS bucket as below. There is more code above this, but not relevant to my problem: import pandas as pd from google.cloud import...
I worked out the answer to my own question. It was indeed a module version issue as I suspected. Specifying google.cloud.storage==1.44.0 in my requirements.txt file solved the problem, as my code is seemingly not compatible with the latest version of that module (for reasons that escape me).
5
5
72,299,007
2022-5-19
https://stackoverflow.com/questions/72299007/how-to-create-a-class-with-multiple-inheritance
I have this code: class Person: def __init__(self, name, last_name, age): self.name = name self.last_name = last_name self.age = age class Student(Person): def __init__(self, name, last_name, age, indexNr, notes): super().__init__(name, last_name, age) self.indexNr = indexNr self.notes = notes class Employee(Person): d...
Instead of explicit classes, use super() to pass arguments along the mro: class Person: def __init__(self, name, last_name, age): self.name = name self.last_name = last_name self.age = age class Student(Person): def __init__(self, name, last_name, age, indexNr, notes, salary, position): # since Employee comes after Stu...
9
10
72,293,719
2022-5-18
https://stackoverflow.com/questions/72293719/pytest-cannot-be-executed-from-python-3-10-4
I already saw one old post regarding this topic - An error while trying to execute tests on python 3.10 with pytest, I am having the same problem, Python 3.10.4 and pytest 7.1.2, when I start command: $ pipenv run pytest I get an error: $ pipenv run pytest ============================= test session starts =============...
As per comment from Marco Bonelli, pytest had no correct version. So command: pipenv update pytest fixed the issue.
4
1
72,291,290
2022-5-18
https://stackoverflow.com/questions/72291290/how-to-create-new-column-dynamically-in-pandas-like-we-do-in-pyspark-withcolumn
from statistics import mean import pandas as pd df = pd.DataFrame(columns=['A', 'B', 'C']) df["A"] = [1, 2, 3, 4, 4, 5, 6] df["B"] = ["Feb", "Feb", "Feb", "May", "May", "May", "May"] df["C"] = [10, 20, 30, 40, 30, 50, 60] df1 = df.groupby(["A","B"]).agg(mean_err=("C", mean)).reset_index() df1["threshold"] = df1["A"] * ...
Option 1: DataFrame.eval (df.groupby(['A', 'B'], as_index=False) .agg(mean_err=('C', 'mean')) .eval('threshold = A * mean_err')) Option 2: DataFrame.assign (df.groupby(['A', 'B'], as_index=False) .agg(mean_err=('C', 'mean')) .assign(threshold=lambda x: x['A'] * x['mean_err'])) A B mean_err threshold 0 1 Feb 10.0 10...
6
7
72,288,401
2022-5-18
https://stackoverflow.com/questions/72288401/how-to-concat-lists-integers-and-strings-into-one-string
I have the following variables: a = [1, 2, 3] b = "de" # <-- not a (usual) list ! c = 5 # <-- not a list ! d = [4, 5, 23, 11, 5] e = ["dg", "kuku"] Now I want to concat all a, b, c, d, e to one list: [1, 2, 3, "de", 5, 4, 5, 23, 11, 5, "dg", "kuku"] I have tried itertools.chain but it didn't work. Please advise how c...
chain works with iterables. What you mean is: concatenate these lists and raw values. I see two steps: def ensure_list(x): if isinstance(x, list): return x return [x] lists = map(ensure_list, (a, b, c, d, e)) concatenated = list(itertools.chain.from_iterable(lists))
5
4
72,283,998
2022-5-18
https://stackoverflow.com/questions/72283998/is-it-possible-to-save-boolean-numpy-arrays-on-disk-as-1bit-per-element-with-mem
Is it possible to save numpy arrays on disk in boolean format where it takes only 1 bit per element? This answer suggests to use packbits and unpackbits, however from the documentation, it seems that this may not support memory mapping. Is there a way to store 1bit arays on disk with memmap support? Reason for memmap r...
numpy does not support 1 bit per element arrays, I doubt memmap has such a feature. However, there is a simple workaround using packbits. Since your case is not bitwise random access, you can read it as 1 byte per element array. # A binary mask represented as an 1 byte per element array. full_size_mask = np.random.rand...
6
2
72,284,064
2022-5-18
https://stackoverflow.com/questions/72284064/regex-expressions-deprecation-warning
The following fragment of code comes from my github repository found here. It opens a binary file, and extracts the text within <header> tags. These are the crucial lines: gbxfile = open(filename,'rb') gbx_data = gbxfile.read() gbx_header = b'(<header)((?s).*)(</header>)' header_intermediate = re.findall(gbx_header, gb...
You can check the Python bug tacker Issue 39394, the warning was introduced in Python 3.6. The point is that the Python re now does not allow using inline modifiers not at the start of string. In Python 2.x, you can use your pattern without any problem and warnings as (?s) is silently applied to the whole regular expre...
5
2