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
74,743,233
2022-12-9
https://stackoverflow.com/questions/74743233/what-happens-behind-the-scenes-if-i-call-none-x-in-python
I am learning and playing around with Python and I came up with the following test code (please be aware that I would not write productive code like that, but when learning new languages I like to play around with the language's corner cases): a = None print(None == a) # I expected True, I got True b = 1 print(None == ...
In fact, None's type does not have its own __eq__ method; within Python we can see that it apparently inherits from the base class object: >>> type(None).__eq__ <slot wrapper '__eq__' of 'object' objects> But this is not really what's going on in the source code. The implementation of None can be found in Objects/obje...
9
8
74,730,142
2022-12-8
https://stackoverflow.com/questions/74730142/priniting-16bit-minimal-float-looks-not-consistent
Can someone explain why printing float16 minimal produces different results below? Is it by design or a bug? In [87]: x=np.finfo(np.float16).min In [88]: x_array_single=np.array([x]) In [89]: x Out[89]: -65500.0 In [90]: x_array_single Out[90]: array([-65504.], dtype=float16)
EDIT: Note that you would also get this issue if you printed the first value of the array: >>> x_array[0] -65500.0 In the NumPy 1.14.0 Release Notes, it has been written that: Floating-point arrays and scalars use a new algorithm for decimal representations, giving the shortest unique representation. This will usuall...
3
4
74,719,898
2022-12-7
https://stackoverflow.com/questions/74719898/how-to-transform-a-polars-dataframe-to-a-pyspark-dataframe
How to correctly transform a Polars DataFrame to a pySpark DataFrame? More specifically, the conversion methods which I've tried all seem to have problems parsing columns containing arrays / lists. create spark dataframe data = [{"id": 1, "strings": ['A', 'C'], "floats": [0.12, 0.43]}, {"id": 2, "strings": ['B', 'B'], ...
What about spark.createDataFrame(pldf.to_dicts()) Alternatively you could do: spark.createDataFrame({x:y.to_list() for x,y in pldf.to_dict().items()}) Since the to_dict method returns polars Series instead of lists, I'm using a comprehension to convert the Series into regular lists which spark comprehends.
4
1
74,725,366
2022-12-8
https://stackoverflow.com/questions/74725366/has-anyone-used-polars-and-seaborn-or-matplotlib-together
Has anyone used a Polars dataframe with Seaborn to graph something? I've been working through a notebook on Kaggle that used Pandas, and I wanted to refactor it to Polars. The dataframe I'm working with looks like this: PassengerID (i64) Survived (i64) Pclass (i64) Name (str) ... Ticket (str) Fare (f64) Cabin (str)...
seaborn doesn't accept a polars dataframe as an input. You just have to use to_pandas() so change g = sns.FacetGrid(train_df, col='Survived') to g = sns.FacetGrid(train_df.to_pandas(), col='Survived')
5
5
74,728,651
2022-12-8
https://stackoverflow.com/questions/74728651/can-i-force-pip-to-install-a-package-even-with-a-version-conflict
During an installation, pip is throwing an error due to version conflicts ERROR: Could not find a version that satisfies the requirement XXX==1.2.1 This is due to a package made by the company for witch I work ( not open source work ). The reason for witch it is blocking is because it is locked in python version 3.6 a...
I haven't tried it myself yet, but according to the documentation, pip install has the following argument that may help to bypass it: --ignore-requires-python Ignore the Requires-Python information. https://pip.pypa.io/en/stable/cli/pip_install/#cmdoption-ignore-requires-python
4
3
74,717,007
2022-12-7
https://stackoverflow.com/questions/74717007/why-does-a-python-function-work-in-parallel-even-if-it-should-not
I am running this code using the healpy package. I am not using multiprocessing and I need it to run on a single core. It worked for a certain amount of time, but, when I run it now, the function healpy.projector.GnomonicProj.projmap takes all the available cores. This is the incriminated code block: def Stacking () : ...
In this thread they recommend to set the environment variable OMP_NUM_THREADS accordingly: Worked with: import os os.environ['OMP_NUM_THREADS'] = '1' import healpy as hp import numpy as np os.environ['OMP_NUM_THREADS'] = '1' have to be done before import numpy and healpy libraries. As to the why: probably they use s...
6
6
74,722,533
2022-12-7
https://stackoverflow.com/questions/74722533/python-is-there-a-way-to-insert-a-json-in-a-super-column-in-redshift-without-es
I'm trying to save data returned from an API as JSON in a SUPER type column in a table on Redshift. My request: data = requests.get(url=f'https://economia.awesomeapi.com.br/json/last/USD-BRL' I have a function to insert the data that runs like this: QUERY = f"""INSERT INTO {schema}.{table}(data) VALUES (%s)""" conn =...
INSERT is an anti-pattern with Redshift; basically, inserts are very slow. And in this case, it's the conversion from JSON to string and back that's getting you. You want to use COPY when bulk-inserting data. Redshift's COPY takes a format parameter, and JSON is one of many supported formats. Docs. Note that to be copi...
3
1
74,718,300
2022-12-7
https://stackoverflow.com/questions/74718300/how-to-reorder-columns-in-pyarrow-table
I have pyarrow table which have column order ['A', 'B', 'C', 'D'] I want to change the order of this pyarrow table to ['B', 'D', 'C', 'A'] can we reorder pyarrows table like pandas dataframe ?
You can use pyarrow.Table.select import pyarrow as pa table_a_b = pa.table({ "A": [1,2,3], "B": [4,5,6] }) table_b_a = table_a_b.select(['B', 'A']) B A 4 1 5 2 6 3
3
4
74,717,893
2022-12-7
https://stackoverflow.com/questions/74717893/how-to-efficiently-search-for-similar-substring-in-a-large-text-python
Let me try to explain my issue with an example, I have a large corpus and a substring like below, corpus = """very quick service, polite workers(cory, i think that's his name), i basically just drove there and got a quote(which seems to be very fair priced), then dropped off my car 4 days later(because they were fully ...
You don't actually need to fuzzy match all that much, at least for the example given; text can only change in spaces within substring, and it can only change by adding at least one non-alphabetic character (which can replace a space, but the space can't be deleted without a replacement). This means you can construct a ...
8
3
74,719,447
2022-12-7
https://stackoverflow.com/questions/74719447/find-first-and-last-integers-in-a-list-of-series-of-numbers
I'm working with lists that look as follows: [2,3,4,5,6,7,8,13,14,15,16,17,18,19,20,30,31,32,33,34,35] In the end I want to extract only the first and last integer in a consecutive series, as such: [(2,8),(13,20),(30,35)] I am new to working with Python, below my code for trying to solve this problem helix = [] singl...
You could do something like this: foo = [2,3,4,5,6,7,8,13,14,15,16,17,18,19,20,30,31,32,33,34,35] series = [] result = [] for i in foo: # if the series is empty or the element is consecutive if (not series) or (series[-1] == i - 1): series.append(i) else: # append a tuple of the first and last item of the series result...
4
3
74,716,030
2022-12-7
https://stackoverflow.com/questions/74716030/what-is-the-difference-between-python-xlib-python3-xlib-pyxlib-and-xlib-in-pyt
I individually installed (and posterior uninstalled): python-xlib python3-xlib pyxlib xlib via pip (un)install and could execute from Xlib import X, display, Xutil from Xlib.ext import randr d = display.Display() with all of them with Python 3.8.10. – What is the difference between them? Pip definitively downloads a...
Use only python-xlib The other three python3-xlib pyxlib xlib are (seemingly) from two individuals (one holds pyxlib and xlib the other holds python3-xlib) with either broken homepage links or pointing to python-xlib. Nothing in python-xlib points to pyxlib or python3-xlib. In the best case these are just outdated ...
3
3
74,655,669
2022-12-2
https://stackoverflow.com/questions/74655669/python-unittests-used-in-a-project-structure-with-multiple-directories
I need to use unittest python library to execute tests about the 3 functions in src/arithmetics.py file. Here is my project structure. . ├── src │ └── arithmetics.py └── test └── lcm ├── __init__.py ├── test_lcm_exception.py └── test_lcm.py src/arithmetics.py def lcm(p, q): p, q = abs(p), abs(q) m = p * q while True: ...
A file __init__.py is missing I think that the problem is the missing of file __init__.py in the folder test. Try to add this (empty) file in that folder as I show you below: test_lcm ├── src │ └── arithmetics.py └── test └── __init__py <---------------- add this file └── lcm ├── __init__.py ├── test_lcm_exception.py └...
3
3
74,631,205
2022-11-30
https://stackoverflow.com/questions/74631205/jupyter-notebook-does-not-run-in-pycharm
When I try to run the server when I'm using PyCharm brings me this error Jupyter server process exited with code 1 usage: jupyter.py [-h] [--version] [--config-dir] [--data-dir] [--runtime-dir] [--paths] [--json] [--debug] [subcommand] Jupyter: Interactive Computing positional arguments: subcommand the subcommand to ...
I didn't manage to solve this, but I found a workaround Go to PyCharm Settings and search for Jupyter Servers Open a Terminal, and start Jupyter notebook, typically: python3 -m notebook Copy the URL with the token to the Configured Server field in Pycharm, click OK You should now be able to run and debug Jupyter c...
25
10
74,638,652
2022-12-1
https://stackoverflow.com/questions/74638652/render-latex-symbols-in-plotly-graphs-in-vscode-interactive-window
I am trying to get Latex symbols in titles and labels of a Plotly figure. I am using VSCode and I run the code in Interactive Window. Latex usage looks really simple in Jupyter Notebook, from what I saw in other posts, but I can't get it to work within this environment. My env: python 3.10.4 plotly 5.9.0 vscode 1.62.3 ...
This is a known issue with Plotly in Jupyter notebooks in VSCode (e.g. issues #7801 and #8131). Tomas Mazak shared a workaround in #8131: import plotly import plotly.graph_objs as go from IPython.display import display, HTML ## Tomas Mazak's workaround plotly.offline.init_notebook_mode() display(HTML( '<script type="t...
6
6
74,705,127
2022-12-6
https://stackoverflow.com/questions/74705127/how-to-fix-error-module-lib-has-no-attribute-x509-v-flag-cb-issuer-check
On my WSL im getting the error AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK' whenever I try to use pip e.g. pip list, python3 -m pip, etc. Is there a way to reinstall pip or uninstall packages without using pip? I tried following the solutions in related Questions but none of them work bec...
The solution that worked for me was mentioned here. you have to remove the line: CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK from this file: /usr/lib/python3/dist-packages/OpenSSL/crypto.py and then you can use pip again: $ pip uninstall cryptography $ pip install --upgrade cryptography==36.0.2
5
20
74,661,044
2022-12-2
https://stackoverflow.com/questions/74661044/add-a-custom-javascript-to-the-fastapi-swagger-ui-docs-webpage-in-python
I want to load my custom javascript file or code to the FastAPI Swagger UI webpage, to add some dynamic interaction when I create a FastAPI object. For example, in Swagger UI on docs webpage I would like to <script src="custom_script.js"></script> or <script> alert('worked!') </script> I tried: api = FastAPI(docs_url...
If you take a look at the get_swagger_ui_html function that is imported from fastapi.openapi.docs, you will see that the HTML for the docs page is constructed manually via string interpolation/concatenation. It would be trivial to modify this function to include an additional script element, as shown below: # custom_sw...
5
4
74,680,849
2022-12-4
https://stackoverflow.com/questions/74680849/save-keras-tuner-results-as-pandas-dataframe
Is there a possibility of saving the results of keras-tuner as Dataframe? All I can find are printing functions like result_summary(), but I cannot access the printed content. The example below both prints print None, while the result_summary() still prints the best results. It looks like I will have to access the tria...
If you don't need to store "score" with the hyperparameters, this should do what you want. You need to get the hyperparameters (HPs). The HPs are stored in hp.get_config() under ["values"] key. You collect a list of dicts with the HPs and convert them into DataFrame and to csv file. best_hps = optimizer.get_best_hyperp...
3
4
74,689,457
2022-12-5
https://stackoverflow.com/questions/74689457/overriding-fastapi-dependencies-that-have-parameters
I'm trying to test my FastAPI endpoints by overriding the injected database using the officially recommended method in the FastAPI documentation. The function I'm injecting the db with is a closure that allows me to build any desired database from a MongoClient by giving it the database name whilst (I assume) still wor...
My case involved an HTTP client wrapper, instead of a DB. I think it could be applied to your case as well. Context: I want to inject values for a FastAPI handler's dependency to test various scenarios. We have a handler with its dependencies @router.get("/{foo}") async def get(foo, client = Depends(get_client)): # get...
8
1
74,631,751
2022-11-30
https://stackoverflow.com/questions/74631751/python-runs-older-version-after-installing-updated-version-on-mac
I am currently running python 3.6 on my Mac, and installed the latest version of Python (3.11) by downloading and installing through the official python releases. Running python3.11 opens the interpreter in 3.11, and python3.11 --version returns Python 3.11.0, but python -V in terminal returns Python 3.6.1 :: Continuum...
What you want to do is overwrite a python symlink. After installing python via homebrew, you can see that python3.11 is just symlink. cd /usr/local/bin; ls -l | grep python3.11 The result is: lrwxr-xr-x 1 user admin 43 Nov 7 15:43 python3.11@ -> ../Cellar/python@3.11/3.11.0/bin/python3.11 So let's just overwrite it. ...
4
7
74,695,915
2022-12-6
https://stackoverflow.com/questions/74695915/apply-a-function-over-the-columns-of-a-dask-array
What is the most efficient way to apply a function to each column of a Dask array? As documented below, I've tried a number of things but I still suspect that my use of Dask is rather amateurish. I have a quite wide and quite long array, in the region of 3,000,000 x 10,000. I want to apply the ecdf function to each col...
As far as I can tell, your code looks correct (see the explanation below for why the performance of map over columns by slicing is misleadingly fast). With some minor refactoring, the "dask-y" version might be: from dask.array.random import random from numpy import zeros from statsmodels.distributions.empirical_distrib...
5
3
74,680,359
2022-12-4
https://stackoverflow.com/questions/74680359/tensorflow-compat-v2-internal-tracking-has-no-attribute-trackablesaver-er
I got this error after installing Tensorflow.js. Previously this program was working. Could it be a problem with the versions? I'm really curious as to what's causing it. Thanks in advance. File ~\OneDrive\Masaüstü\Bitirme Proje\neural_network(sinir_ağları).py:61 model = build_model() File ~\OneDrive\Masaüstü\Bitirme P...
Update keras with pip install 'keras>=2.9.0' for keras-team/keras@af70910. - self._trackable_saver = saver_with_op_caching(self) + self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
4
3
74,697,284
2022-12-6
https://stackoverflow.com/questions/74697284/do-architectures-built-using-tf-keras-models-sequential-run-more-slowly-and-accu
I just compared 2 (I thought) equivalent VGG-ish architectures. One was constructed using tf.keras.Models.Sequential, the other used Tensorflow's functional API. Each was attempting to solve the cats_vs_dogs dataset. After 10 training epochs, the Sequential model had these runtimes and accuracies: Epoch 10/10 703/703 [...
The reason for the differences in these two nets lie in the differences in the way they are padded (the sequential model used valid padding, the functional API model used same padding) and in the strides they used. The sequential model used strides of 1 for the conv layer and 2 for the pooling layer, while the function...
3
0
74,674,688
2022-12-4
https://stackoverflow.com/questions/74674688/google-colab-notebook-using-ijava-stuck-at-connecting-after-installation-ref
All of my notebooks stopped connecting, after the initial IJava installation and browser page refresh. What used to work Execute this first cell !wget https://github.com/SpencerPark/IJava/releases/download/v1.3.0/ijava-1.3.0.zip !unzip ijava-1.3.0.zip !python install.py --sys-prefix Wait for the Installed java kern...
At some point colab changed the default transport to ipc (from the default tcp) which is not supported by IJava. /usr/bin/python3 /usr/local/bin/jupyter-notebook --ip=... --transport=ipc --port=... The kernel starts but never properly connects and doesn't send the initial kernel info message that jupyter is waiting f...
5
4
74,673,048
2022-12-4
https://stackoverflow.com/questions/74673048/github-actions-setup-python-stopped-working
Below is my workflow file, which worked previously forever and I've not changed anything. env: PYTHON_VERSION: '3.8.9' jobs: build: name: build 🔧 runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v3 with: python-version: ${{ env.PYTHON_VERSION }} - run: mkdir file-icons product-ico...
Resolved. GitHub actions recently updated ubuntu-latest from 20.04 to 22.04 https://github.blog/changelog/2022-08-09-github-actions-ubuntu-22-04-is-now-generally-available-on-github-hosted-runners/ https://github.com/actions/runner-images/issues/6399 certain versions of python is not yet supported by setup-python act...
4
3
74,670,915
2022-12-3
https://stackoverflow.com/questions/74670915/axis-labels-in-line-with-tick-labels-in-matplotlib
For space reasons, I sometimes make plots in the following style: fig, ax = plt.subplots(figsize=(3, 3)) ax.plot([0,1], [1000, 1001]) ax.set_xticks([0, 1]) ax.set_yticks([1000, 1001]) ax.set_xlabel("x", labelpad=-8) ax.set_ylabel("y", labelpad=-18) Here, I've kept just ticks marking the boundaries of the X/Y domains,...
The path you were going down with ax.{x,y}axis.set_label_coords was pretty much there! All you need to do is wrap the transAxes transform in an offset_copy and then provide an offset that is a combination of the current length of the ticks + any space around the tick bbox. Using Transforms import matplotlib.pyplot as p...
4
2
74,656,397
2022-12-2
https://stackoverflow.com/questions/74656397/attributeerror-function-object-has-no-attribute-register-when-using-functoo
Goal: create a single-dispatch generic function; as per functools documentation. I want to use my_func() to calculate dtypes: int or list, in pairs. Note: I've chosen to implement type hints and to raise errors for my own test cases, outside of the scope of this post. For many argument data type hints; this post uses m...
Functions must be uniquely named Credit to @Bijay Regmi for pointing this out. @typechecked is placed above only the polymorphed @my_func.register functions; not above the @singledispatch function. Note: you still invoke my_func(); I am just testing the polymorphed functions. from functools import singledispatch from t...
3
2
74,692,201
2022-12-5
https://stackoverflow.com/questions/74692201/aggregation-calculation-method-for-treemap-in-plotly-express-python
Thanks by advance for people who will try to help me. This is the first time I ask a question as I have been struggling for days on this one! Eternal glory to the one helping me out with this! Let me explain my problem with a few lines of codes and screens. I want to create a treemap showing the growth of values betwee...
I couldn't find a way to get the data across as you're trying to depict it. However, I did come up with a workaround. This requires the use of plotly.io. I want to point out that the nice contrast you have with the colors is lost, when you change the parent to 20% from 183.333333--- essentially that parent is nearly th...
3
2
74,706,620
2022-12-6
https://stackoverflow.com/questions/74706620/python-pytest-in-azure-devops-modulenotfounderror-no-module-named-core
I have my DevOps pipeline which is using pytest to execute unit tests found in Python code. I'm using a root folder called "core" for the main python functionality, and reference it using the following format: import unittest from core.objects.paragraph import Paragraph from core.objects.sentence import Sentence Runni...
Please make sure the directory/home/vsts/work/1/s/tests/has a __init__.pyfile.
3
2
74,709,683
2022-12-6
https://stackoverflow.com/questions/74709683/combine-a-row-with-column-in-dataframe-and-show-the-corresponding-values
So I want to show this data in just two columns. For example, I want to turn this data Year Jan Feb Mar Apr May Jun 1997 3.45 2.15 1.89 2.03 2.25 2.20 1998 2.09 2.23 2.24 2.43 2.14 2.17 1999 1.85 1.77 1.79 2.15 2.26 2.30 2000 2.42 2.66 2.79 3.04 3.59 4.29 into this Date Price Jan-1977 3.45 Feb-1977 2.15 Mar-1977 1.8...
Another possible solution, which is based on pandas.DataFrame.stack: out = df.set_index('Year').stack() out.index = ['{}_{}'.format(j, i) for i, j in out.index] out = out.reset_index() out.columns = ['Date', 'Value'] Output: Date Value 0 Jan_1997 3.45 1 Feb_1997 2.15 2 Mar_1997 1.89 3 Apr_1997 2.03 4 May_1997 2.25 .....
3
2
74,703,727
2022-12-6
https://stackoverflow.com/questions/74703727/how-to-call-async-function-from-sync-funcion-and-get-result-while-a-loop-is-alr
I have a asyncio running loop, and from the coroutine I'm calling a sync function, is there any way we can call and get result from an async function in a sync function tried below code, it is not working want to print output of hel() in i() without changing i() to async function is it possible, if yes how? import asyn...
This is one of the most commonly asked type of question here. The tools to do this are in the standard library and require only a few lines of setup code. However, the result is not 100% robust and needs to be used with care. This is probably why it's not already a high-level function. The basic problem with running an...
9
8
74,708,868
2022-12-6
https://stackoverflow.com/questions/74708868/how-to-create-a-loop-to-takes-an-existing-df-and-creates-a-randomized-new-df
I am trying to build a tool that will essentially scramble a dataset while maintaining the same elements. For example, if I have the table below 1 2 3 4 5 6 0 ABC 1234 NL00 Paid VISA 1 BCD 2345 NL01 Unpaid AMEX 2 CDE 3456 NL02 Unpaid VISA I want it to then look go through each column, pick a random value, and paste t...
Here's an easy solution: df.apply(pd.Series.sample, replace=True, ignore_index=True, frac=1) Output (potential): 1 2 3 4 5 6 0 2 CDE 3456 NL00 Paid VISA 1 2 BCD 3456 NL01 Paid VISA 2 0 CDE 3456 NL01 Paid VISA pd.DataFrame.apply applies pd.Series.sample method to each column of the dataframe with resampling (replace=...
3
2
74,707,663
2022-12-6
https://stackoverflow.com/questions/74707663/remove-duplicates-based-on-combination-of-two-columns-in-pandas
I need to delete duplicated rows based on combination of two columns (person1 and person2 columns) which have strings. For example person1: ryan and person2: delta or person 1: delta and person2: ryan is same and provides the same value in messages column. Need to drop one of these two rows. Return the non duplicated r...
Try as follows: res = (df[~df.filter(like='person').apply(frozenset, axis=1).duplicated()] .reset_index(drop=True)) print(res) person1 person2 messages 0 0 ryan delta 1 1 2 delta alpha 2 2 3 delta bravo 3 3 5 alpha ryan 9 Explanation First, we use df.filter to select just the columns with person*. For these columns o...
6
5
74,696,410
2022-12-6
https://stackoverflow.com/questions/74696410/generic-iterator-annotations-python
I am trying to annotate an Iterator which only returns two values, T and cls[T]. Currently I have it annotated like this: from __future__ import annotations import typing class Node(typing.Generic[T]): def __init__(self, value: T, next: typing.Optional[Node[T]] = None) -> None: self.value = value self.next = next def _...
This is not possible to annotate using the generic Iterator. It is a class expecting exactly one type argument. (current typeshed source) That means every value returned by its __next__ method necessarily has the same type. You are invoking the iterator protocol on that tuple of self.value, self.next. A tuple has an ar...
4
1
74,706,249
2022-12-6
https://stackoverflow.com/questions/74706249/when-does-class-attribute-initialization-code-run-in-python
There is a class attribute spark in our AnalyticsWriter class: class AnalyticsWriter: spark = SparkSession.getActiveSession() # this is not getting executed I noticed that this code is not being executed before a certain class method is run. Note: it has been verified that there is already an active SparkSession avail...
Class attributes are initialized at the moment they are hit, during class definition, so the line containing the getActiveSession() call is run before the class is even fully defined. class AnalyticsWriter: spark = SparkSession.getActiveSession() # The code has been run here # ... other definitions that occur after spa...
3
5
74,702,540
2022-12-6
https://stackoverflow.com/questions/74702540/how-to-map-a-ms-sql-server-table-that-has-a-uniqueidentifier-primary-key
Using sqlalchemy 1.4, I want to map a class to a table that has a UNIQUEIDENTIFIER primary key. Using sqlalchemy.String does not work (complains about the fact that you cannot increment it). Checking dialects, I tried to used sqlalchemy.dialects.mssql.UNIQUEIDENTIFIER, however this does not work either: class Result(Ba...
Specifying primary_key=True and server_default=text("newid()") is sufficient to let SQLAlchemy know that the server will take case of assigning the PK value: from sqlalchemy import Column, String, create_engine, select, text from sqlalchemy.dialects.mssql import UNIQUEIDENTIFIER from sqlalchemy.orm import Session, decl...
4
3
74,687,769
2022-12-5
https://stackoverflow.com/questions/74687769/typeerror-getattr-attribute-name-must-be-string-in-pytorch-diffusers-how
I am trying the diffusers of Pytorch to generate pictures in my Mac M1. I have a simple syntax like this: modelid = "CompVis/stable-diffusion-v1-4" device = "cuda" pipe = StableDiffusionPipeline.from_pretrained(modelid, revision="fp16", torch_dtype=torch.float16, use_auth_token=auth_token) pipe.to(device) when I run m...
The device should be mps (device='mps'). Mac M1 has no inbuilt Nvidia GPU. Also, I would suggest you check How to use Stable Diffusion in Apple Silicon (M1/M2) HG blog and make sure all the requirements are satisfied. Also, check for your installed diffusers version. import diffusers print(diffusers.__version__) If it...
5
2
74,700,723
2022-12-6
https://stackoverflow.com/questions/74700723/python-subprocess-or-bat-script-splits-argument-on-equal-sign
How do I add this: -param:abc=def as a SINGLE command line argument? Module subprocess splits this up in TWO arguments by replacing the equal sign with a space. Here is my python script: import subprocess pa=['test.bat', '--param:abc=def'] subprocess.run(pa) Here is the test program test.bat: @echo off echo Test.bat e...
Welcome to .bat file hell To preserve equal sign, you'll have to quote your argument (explained here Preserving "=" (equal) characters in batch file parameters) ('"--param:abc=def"'), but then subprocess will escape the quotes Test.bat Arg0: test.bat Arg1: \"--param:abc=def\" Arg2: Good old os.system won't do that imp...
3
1
74,683,670
2022-12-5
https://stackoverflow.com/questions/74683670/how-to-get-the-extracted-feature-vector-from-transfer-learning-models-python
I am trying to implement a classification model with ResNet50. I know, CNN or transfer learning models extract the features themselves. How can I get the extracted feature vector from the image dataset in python? Code Snippet of model training: base_model = ResNet152V2( input_shape = (height, width, 3), include_top=Fal...
Once you have trained your model, you can save it (or just directly use it in the same file) then cut off the top layer. model = load_model("xxx.h5") #Or use model directly #Use functional model from tensorflow.keras.models import Model featuresModel = Model(inputs=model.input,outputs=model.layers[-3].output) #Get rids...
3
1
74,683,994
2022-12-5
https://stackoverflow.com/questions/74683994/how-to-query-azure-sql-database-using-python-async
I'm stuck and can't figure out a workable way to connect asynchronously to an Azure SQL database using Python. I've tried asyncio, pyodbc and asyncpg to no avail. I think this is close... import asyncio import pyodbc async def query_azure_sql_db(): connection_string = 'Driver={ODBC Driver 17 for SQL Server};Server=tcp:...
The problem is that pyodbc.connect is a function and does not implement async context manager, so why you are getting the AttributeError. I recommend using aioodbc instead of pyodbc as it provides the same functionality as async methods. You can also make it work with async with by implementing the __aenter__ and __aex...
5
6
74,672,979
2022-12-4
https://stackoverflow.com/questions/74672979/upload-a-python-package-to-azure-artifacts-using-a-github-action
I have a repository on Github for a private Python package for my organization, and I would like to publish this package in a private Azure Artifacts feed using Github actions for automated CI/CD. It seems like none of the documentation around publishing to Azure Artifacts is for this exact scenario; the documentation ...
You can save the authentication information in the project file of Repository, and then run Publish Python packages from the command line in your Github Actions.
4
0
74,682,391
2022-12-5
https://stackoverflow.com/questions/74682391/python-get-the-cache-dictionary-of-lru-cache-wrapper-object
I have this simple cache decorator demo here @functools.cache def cached_fib(n): assert n > 0 if n <= 2: return 1 return cached_fib(n - 1) + cached_fib(n - 2) t1 = time.perf_counter() cached_fib(400) t2 = time.perf_counter() print(f"cached_fib: {t2 - t1}") # 0.0004117000003134308 I want to access the actual cache dict...
The internals of the cache are encapsulated for thread safety and to allow the underlying implementation details to change. The three public attributes are, some statistics in cache_info: >>> cached_fib.cache_info() CacheInfo(hits=0, misses=0, maxsize=None, currsize=0) >>> cached_fib(123) 22698374052006863956975682 >>>...
3
3
74,678,931
2022-12-4
https://stackoverflow.com/questions/74678931/how-to-improve-julias-performance-using-just-in-time-compilation-jit
I have been playing with JAX (automatic differentiation library in Python) and Zygote (the automatic differentiation library in Julia) to implement Gauss-Newton minimisation method. I came upon the @jit macro in Jax that runs my Python code in around 0.6 seconds compared to ~60 seconds for the version that does not use...
Your Julia code doing a number of things that aren't idiomatic and are worsening your performance. This won't be a full overview, but it should give you a good idea to start. The first thing is passing params as a Vector is a bad idea. This means it will have to be heap allocated, and the compiler doesn't know how long...
4
6
74,660,176
2022-12-2
https://stackoverflow.com/questions/74660176/using-visualstudio-python-how-to-handle-overriding-stdlib-module-pylancer
When running ipynbs in VS Code, I've started noticing Pylance warnings on standard library imports. I am using a conda virtual environment, and I believe the warning is related to that. An example using the glob library reads: "env\Lib\glob.py" is overriding the stdlib "glob" modulePylance(reportShadowedImports) So fa...
The reason you find nothing by searching is because this check has just been implemented recently (see Github). I ran into the same problem as you because code.py from Micropython/Circuitpython also overrides the module "code" in stdlib. The solution is simple, though you then loose out on this specific check. Just add...
20
36
74,673,076
2022-12-4
https://stackoverflow.com/questions/74673076/can-you-explain-me-the-output
I was in class section of python programming and I am confused here. I have learned that super is used to call the method of parent class but here Employee is not a parent of Programmer yet it's called (showing the result of getLanguage method). What I am missing? This is the code, class Employee: company= "Google" lan...
You've bumped into one of the reasons why super exists. From the docs, super delegates method calls to a parent or sibling class of type. Python bases class inheritance on a dynamic Method Resolution Order (MRO). When you created a class with multiple inheritance, those two parent classes became siblings. The left most...
4
3
74,667,621
2022-12-3
https://stackoverflow.com/questions/74667621/get-full-article-in-google-sheet-using-openai
I'm trying to get full article in Google Sheet using Openai API. In column A I just mention the topic and want to get full article in column B. Here is what I'm trying /** * Use GPT-3 to generate an article * * @param {string} topic - the topic for the article * @return {string} the generated article * @customfunction...
Modification points: When I saw the official document of OpenAI API, in your endpoint of https://api.openai.com/v1/completions, it seems that the following value is returned. Ref { "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", "object": "text_completion", "created": 1589478378, "model": "text-davinci-003", "choices": [ { "t...
3
3
74,663,224
2022-12-3
https://stackoverflow.com/questions/74663224/passing-a-functions-output-as-a-parameter-of-another-function
I'm having a hard time figuring out how to pass a function's return as a parameter to another function. I've searched a lot of threads that are deviations of this problem but I can't think of a solution from them. My code isn't good yet, but I just need help on the line where the error is occurring to start with. Instr...
You're almost there, a few subtleties to consider: The datetime object must be assigned to a variable and returned. Your code was not assigning the datetime object, but returning a str object for input into func2. Which would have thrown an attribute error as a str has no year attribute. Simply subtracting the years w...
3
1
74,660,595
2022-12-2
https://stackoverflow.com/questions/74660595/further-optimizing-the-ising-model
I've implemented the 2D ISING model in Python, using NumPy and Numba's JIT: from timeit import default_timer as timer import matplotlib.pyplot as plt import numba as nb import numpy as np # TODO for Dict optimization. # from numba import types # from numba.typed import Dict @nb.njit(nogil=True) def initialstate(N): ''...
The computation of the exponential is not really an issue. The main issue is that generating random numbers is expensive and a huge number of random values are generated. Another issue is that the current computation is intrinsically sequential. Indeed, for N=32, mcmove tends to generate about 3000 random values, and t...
3
4
74,668,215
2022-12-3
https://stackoverflow.com/questions/74668215/error-with-tatsu-does-not-recognize-the-right-grammar-pattern
I am getting started with tatsu and I am trying to implement a grammar for the miniML language. Once my grammar successfully parsed, I tried to parse some little expressions to check that it was working ; however I discovered Tatsu was unable to recognize some of the expected patterns. Here is the code : ` grammar=""" ...
It seems the failure of assign comes from a conflict with the varname rule; to solve it, simply place |assign BEFORE |variable in your expression rule. A now obsolete workaround, that I'll leave anyway: # I added a negative lookahead for '=' so it will not conflict with the assign rule varname = /[a-z]+/!'=' ; assign...
3
2
74,666,784
2022-12-3
https://stackoverflow.com/questions/74666784/try-to-understand-class-and-instance-variable-annotations-in-pep-526
It seems to me that I misunderstand the PEP 526 in the context of annotating class and instance variables. Based on the example in the PEP document here the object bar should be an instance variable with default value 7: class Foo: bar: int = 7 def __init__(self, bar): self.bar = bar But testing that with Python it se...
There is no conflict, and the PEP does explain what is going on. First of all: An instance variable is just a name set on an instance (usually via self.[name] = ...), and class variables are just names set on a class (usually by assigning to a name within the class ... statement body. They are not mutually exclusive. W...
3
6
74,660,993
2022-12-2
https://stackoverflow.com/questions/74660993/python-find-x-and-y-values-of-a-2d-gaussian-given-a-value-for-the-function
I have a 2D gaussian function f(x,y). I know the values x₀ and y₀ at which the peak g₀ of the function occurs. But then I want to find xₑ and yₑ values at which f(xₑ, yₑ) = g₀ / e¹. I know there are multiple solutions to this, but at least one is sufficient. So far I have def f(x, y, g0,x0,y0,sigma_x,sigma_y,offset): r...
There are an infinite number of possibilities (or possibly 1 trivial or none in special cases regarding the value of g0). A solution can be computed analytically in constant time using a direct method. No need for approximations or iterative methods to find roots of a given function. It is just pure maths. Gaussian ker...
3
2
74,661,959
2022-12-2
https://stackoverflow.com/questions/74661959/why-does-numpy-matrix-multiply-computation-time-increase-by-an-order-of-magnitud
When computing A @ a where A is a random N by N matrix and a is a vector with N random elements using numpy the computation time jumps by an order of magnitude at N=100. Is there any particular reason for this? As a comparison the same operation using torch on the cpu has a more gradual increase Tried it with python3.1...
numpy tries to use threads when multiplying matricies of size 100 or larger, and the default CBLAS implementation of threaded multiplication is ... sub optimal, as opposed to other backends like intel-MKL or ATLAS. if you force it to use only 1 thread using the answers in this post you will get a continuous line for nu...
20
17
74,655,787
2022-12-2
https://stackoverflow.com/questions/74655787/match-case-statement-with-multiple-or-conditions-in-each-case
Is there a way to assess whether a case statement variable is inside a particular list? Consider the following scenario. We have three lists: a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] Then I want to check whether x is in each list. Something like this (of course this is a Syntax Error but I hope you get the point): ma...
As it seems cases accept a "guard" clause starting with Python 3.10, which you can use for this purpose: match x: case w if w in a: # this was the "case in a" in the question case w if w in b: # this was the "case in b" in the question ... the w here actually captures the value of x, part of the syntax here too, but i...
14
22
74,643,203
2022-12-1
https://stackoverflow.com/questions/74643203/how-to-mock-a-function-which-makes-a-mutation-on-an-argument-that-is-necessary-f
I want to be able to mock a function that mutates an argument, and that it's mutation is relevant in order for the code to continue executing correctly. Consider the following code: def mutate_my_dict(mutable_dict): if os.path.exists("a.txt"): mutable_dict["new_key"] = "new_value" return True def function_under_test():...
With the help of Peter i managed to come up with this final test: def mock_mutate_my_dict(my_dict): my_dict["new_key"] = "new_value" return True def test_function_under_test(): with patch("stack_over_flow.mutate_my_dict") as mutate_my_dict_mock: mutate_my_dict_mock.side_effect = mock_mutate_my_dict result = function_un...
4
1
74,653,913
2022-12-2
https://stackoverflow.com/questions/74653913/group-columns-if-coordinates-are-not-more-distant-than-a-threshold
Sps Gps start end SP1 G1 2 322 SP1 G1 318 1368 SP1 G1 21125 22297 SP2 G2 2 313 SP2 G2 334 1359 SP2 G2 11716 11964 SP2 G2 20709 20885 SP2 G2 21080 22297 SP3 G3 2 313 SP3 G3 328 1368 SP3 G3 21116 22294 SP4 G4 346 1356 SP4 G4 21131 22282 and I would like to add a new columns Threshold_gps for each Sps and Gps that have s...
I believe you might want: df['Threshold_gps'] = (df .groupby(['Sps', 'Gps'], group_keys=False) .apply(lambda d: (s:=d['end'].shift().rsub(d['start']) .gt(500)) .cumsum().add(1-s.iloc[0]) .astype(str).radd('G') ) ) for python <3.8: def get_group(g): s = g['end'].shift().rsub(g['start']).gt(500) return s.cumsum().add(1-...
3
4
74,655,149
2022-12-2
https://stackoverflow.com/questions/74655149/what-is-the-current-correct-format-for-python-docstrings-according-to-pep-stan
I've been looking all over the web for the current standards for Python Docstrings and I've come across different answers for different scenarios. What is the currently most-accepted and wide-spread docstring format that I should use? These are the ones that I've found so far: Sphinx format (1): :param type name: descr...
The most widely accepted and standardized format for Python docstrings is the one defined in the PEP 257 - Docstring Conventions. This format is supported by most IDEs, including VS Code and PyCharm, and is also used by the Sphinx and NumPy documentation tools. The PEP 257 format for documenting function parameters is ...
7
-1
74,642,594
2022-12-1
https://stackoverflow.com/questions/74642594/why-does-stablediffusionpipeline-return-black-images-when-generating-multiple-im
I am using the StableDiffusionPipeline from the Hugging Face Diffusers library in Python 3.10.2, on an M2 Mac (I tagged it because this might be the issue). When I try to generate 1 image from 1 prompt, the output looks fine, but when I try to generate multiple images using the same prompt, the images are all either bl...
Apparently it is indeed an Apple Silicon (M1/M2) issue, of which Hugging Face is not yet sure why this is happening, see this GitHub issue for more details.
4
2
74,646,115
2022-12-1
https://stackoverflow.com/questions/74646115/merge-all-excel-files-into-one-file-with-multiple-sheets
i would like some help. I have multiple excel files, each file only has one sheet. I would like to combine all excel files into just one file but with multiple sheets one sheet per excel file keeping the same sheet names. this is what i have so far: import pandas as pd from glob import glob import os excelWriter = pd.E...
import pandas as pd import os output_excel = r'/home/bera/Desktop/all_excels.xlsx' #List all excel files in folder excel_folder= r'/home/bera/Desktop/GIStest/excelfiles/' excel_files = [os.path.join(root, file) for root, folder, files in os.walk(excel_folder) for file in files if file.endswith(".xlsx")] with pd.ExcelWr...
4
6
74,638,479
2022-12-1
https://stackoverflow.com/questions/74638479/check-unique-value-when-define-concrete-class-for-abstract-variable-in-python
Suppose that I have this architecture for my classes: # abstracts.py import abc class AbstractReader(metaclass=abc.ABCMeta): @classmethod def get_reader_name(cl): return cls._READER_NAME @classmethod @property @abc.abstractmethod def _READER_NAME(cls): raise NotImplementedError # concretes.py from .abstracts import Abs...
You can create a metaclass with a constructor that uses a set to keep track of the name of each instantiating class and raises an exception if a given name already exists in the set: class UniqueName(type): names = set() def __new__(metacls, cls, bases, classdict): name = classdict['_READER_NAME'] if name in metacls.na...
4
1
74,645,811
2022-12-1
https://stackoverflow.com/questions/74645811/how-to-crop-square-inscribed-in-partial-circle
I have frames of a video taken from a microscope. I need to crop them to a square inscribed to the circle but the issue is that the circle isn't whole (like in the following image). How can I do it? My idea was to use contour finding to get the center of the circle and then find the distance from each point over the w...
Let's start with an illustration of the problem to help with the explanation. Of course, we have to begin with loading the image. Let's also grab its width and height, since they will be useful later on. img = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR) height, width = img.shape[:2] First, let's convert the image to ...
3
4
74,641,489
2022-12-1
https://stackoverflow.com/questions/74641489/how-to-override-a-mock-for-an-individual-test-within-a-class-that-already-has-a
I have a test class that has a mock decorator, and several tests. Each test receives the mock, because mock is defined on the class level. Great. Here's what it looks like: @mock.patch("foo", bar) class TestMyThing(TestCase): def test_A(self): assert something def test_B(self): assert something def test_C(self): assert...
Yes! You can leverage the setUp/tearDown methods of the unittest.TestCase and the fact that unittest.mock.patch in its "pure" form (i.e. not as context manager or decorator) returns a "patcher" object that has start/stop methods to control when exactly it should do its magic. You can call on the patcher to start inside...
5
3
74,641,988
2022-12-1
https://stackoverflow.com/questions/74641988/pandas-keyerror-in-get-loc-when-calling-entries-from-dataframe-in-for-loop
I am using a pandas data-frame and for some reason when trying to access one entry after another in a for loop it does gives me an error. Here is my (simplified) code snippet: df_original = pd.read_csv(csv_dataframe_filename, sep='\t', header=[0, 1], encoding_errors="replace") df_original.columns = ['A', 'B', 'Count_N...
This is the answer focusing on the UPDATE section you have provided. The first thing you need to understand between normal indexing of DataFrame and using iloc. iloc basically use position indexing (just like in lists we have positions of elements 0, 1, ... len(list)-1), but the normal indexing, in your case [x] matche...
3
4
74,635,994
2022-12-1
https://stackoverflow.com/questions/74635994/pytorchs-share-memory-vs-built-in-pythons-shared-memory-why-in-pytorch-we
Trying to learn about the built-in multiprocessing and Pytorch's multiprocessing packages, I have observed a different behavior between both. I find this to be strange since Pytorch's package is fully-compatible with the built-in package. Concretely, I'm refering to the way variables are shared between processes. In Py...
pytorch has a simple wrapper around shared memory, python's shared memory module is only a wrapper around the underlying OS dependent functions. the way it can be done is that you don't serialize the array or the shared memory themselves, and only serialize what's needed to create them by using the __getstate__ and __s...
6
4
74,628,777
2022-11-30
https://stackoverflow.com/questions/74628777/why-does-gpu-memory-increase-when-recreating-and-reassigning-a-jax-numpy-array-t
When I recreate and reassign a JAX np array to the same variable name, for some reason the GPU memory nearly doubles the first recreation and then stays stable for subsequent recreations/reassignments. Why does this happen and is this generally expected behavior for JAX arrays? Fully runnable minimal example: https://c...
The reason for this behavior comes from the interaction of several things: Without pre-allocation, the GPU memory usage will grow as needed, but will not shrink when buffers are deleted. When you reassign a python variable, the old value still exists in memory until the Python garbage collector notices it is no longe...
3
3
74,633,504
2022-11-30
https://stackoverflow.com/questions/74633504/how-to-stretch-out-a-bounding-box-given-from-minarearect-function-in-opencv
I wish to run a line detector between two known points on an image but firstly I need to widen the area around the line so my line detector has more area to work with. The main issue it stretch the area around line with respect to the line slope. For instance: white line generated form two points with black bounding bo...
A minAreaRect() gives you a center point, the size of the rectangle, and an angle. You could just add to the shorter side length of the rectangle. Then you have a description of a "wider rectangle". You can then do with it whatever you want, such as call boxPoints() on it. padding = 42 rect = cv.minAreaRect(input_to_mi...
4
3
74,633,074
2022-11-30
https://stackoverflow.com/questions/74633074/how-to-type-hint-a-generic-numpy-array
Is there any way to type a Numpy array as generic? I'm currently working with Numpy 1.23.5 and Python 3.10, and I can't type hint the following example. import numpy as np import numpy.typing as npt E = TypeVar("E") # Should be bounded to a numpy type def double_arr(arr: npt.NDArray[E]) -> npt.NDArray[E]: return arr * ...
Looking at the source, it seems the generic type variable used to parameterize numpy.dtype of numpy.typing.NDArray is bounded by numpy.generic (and declared covariant). Thus any type argument to NDArray must be a subtype of numpy.generic, whereas your type variable is unbounded. This should work: from typing import Typ...
4
8
74,628,389
2022-11-30
https://stackoverflow.com/questions/74628389/cant-install-tensorflow-text-2-11-0
I got a warning something like warnings.warn( No local packages or working download links found for tensorflow-text~=2.11.0 error: Could not find suitable distribution for Requirement.parse('tensorflow-text~=2.11.0') and if I run pip install 'tensorflow-text~=2.11.0' I got : ERROR: Could not find a version that satisf...
As per their note, they have dropped building for Windows with v2.11.0. So, you'll need to build from source or seek a third-party build.
3
7
74,623,917
2022-11-30
https://stackoverflow.com/questions/74623917/how-to-tokenize-block-of-text-as-one-token-in-python
Recently I am working on a genome data set which consists of many blocks of genomes. On previous works on natural language processing, I have used sent_tokenize and word_tokenize from nltk to tokenize the sentences and words. But when I use these functions on genome data set, it is not able to tokenize the genomes corr...
You just need to concatenate the lines between two ids apparently. There should be no need for nltk or any tokenizer, just a bit of programming ;) patterns = {} with open('data', "r") as f: id = None current = "" for line0 in f: line= line0.rstrip() if line[0] == '>' : # new pattern if len(current)>0: # print("adding ...
3
3
74,624,626
2022-11-30
https://stackoverflow.com/questions/74624626/type-narrowing-of-class-attributes-in-python-typeguard-without-subclassing
Consider I have a python class that has a attributes (i.e. a dataclass, pydantic, attrs, django model, ...) that consist of a union, i.e. None and and a state. Now I have a complex checking function that checks some values. If I use this checking function, I want to tell the type checker, that some of my class attribut...
TL;DR: You cannot narrow the type of an attribute. You can only narrow the type of an object. As I already mentioned in my comment, for typing.TypeGuard to be useful it relies on two distinct types T and S. Then, depending on the returned bool, the type guard function tells the type checker to assume the object to be e...
7
2
74,622,588
2022-11-30
https://stackoverflow.com/questions/74622588/sudoku-backtracking-python-to-find-multiple-solutions
I have a code to solve a Sudoku recursively and print out the one solution it founds. But i would like to find the number of multiple solutions. How would you modify the code that it finds all possible solutions and gives out the number of solutions? Thank you! :) code: board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,...
As asked: How would you modify the code that it finds all possible solutions and gives out the number of solutions? If you don't want to return ("give out") the solutions themselves, but the number of solutions, then you need to maintain a counter, and use the count you get back from the recursive call to update the ...
4
1
74,624,111
2022-11-30
https://stackoverflow.com/questions/74624111/application-runs-with-uvicorn-but-cant-find-module-no-module-named-app
. ├── __pycache__ │ └── api.cpython-310.pyc ├── app │ ├── __pycache__ │ │ └── main.cpython-310.pyc │ ├── api_v1 │ │ ├── __pycache__ │ │ │ └── apis.cpython-310.pyc │ │ ├── apis.py │ │ └── endpoints │ │ ├── __pycache__ │ │ │ └── message_prediction.cpython-310.pyc │ │ └── message_prediction.py │ ├── config.py │ ├── main.p...
python app/main.py will make app/ the first entry in sys.path, so app imports within won't work. Do python -m app.main to run app/main.py as a module without having Python touch sys.path.
3
2
74,607,041
2022-11-28
https://stackoverflow.com/questions/74607041/how-to-do-with-pydantic-regex-validation
I'm trying to write a validator with usage of Pydantic for following strings (examples): 1.1.0, 3.5.6, 1.1.2, etc.. I'm failing with following syntax: install_component_version: constr(regex=r"^[0-9]+.[0-9]+.[0-9]$") install_component_version: constr(regex=r"^([0-9])+.([0-9])+.([0-9])$") install_component_version: cons...
The error you are facing is due to type annotation. As per https://github.com/pydantic/pydantic/issues/156 this is not yet fixed, you can try using pydantic.Field and then pass the regex argument there like so install_component_version: str = Field(regex=r"^[0-9]+.[0-9]+.[0-9]$") This way you get the regex validation ...
8
10
74,589,610
2022-11-27
https://stackoverflow.com/questions/74589610/whats-pylints-typevar-name-specification
Pylint gives a warning whenever something like this happens: import typing SEQ_FR = typing.TypeVar("SEQ_FR") #^^^^^ gets underlined with the warning The warning is like this: Type variable name "SEQ_FR" doesn't conform to predefined naming style. pylint(invalid-name) I tried searching through Pylint's documentations w...
You can find the rule used in the Pylint messages documentation; this error is named invalid-name, so the specific documentation can be found on the invalid-name / C0103 page, which has a TypeVar rule in the Predefined Naming Patterns section: Name type: typevar Good Names: T, _CallableT, _T_co, AnyStr, DeviceTypeT, I...
9
12
74,606,984
2022-11-28
https://stackoverflow.com/questions/74606984/how-are-small-sets-stored-in-memory
If we look at the resize behavior for sets under 50k elements: >>> import sys >>> s = set() >>> seen = {} >>> for i in range(50_000): ... size = sys.getsizeof(s) ... if size not in seen: ... seen[size] = len(s) ... print(f"{size=} {len(s)=}") ... s.add(i) ... size=216 len(s)=0 size=728 len(s)=5 size=2264 len(s)=19 size...
set object in Python is represented by the following C structure: typedef struct { PyObject_HEAD Py_ssize_t fill; /* Number of active and dummy entries*/ Py_ssize_t used; /* Number of active entries */ /* The table contains mask + 1 slots, and that's a power of 2. * We store the mask instead of the size because the mas...
13
7
74,563,511
2022-11-24
https://stackoverflow.com/questions/74563511/should-you-decorate-dataclass-subclasses-if-not-making-additional-fields
If you don't add any more fields to your subclass is there a need to add the @dataclass decorator to it and would it do anything? If there is no difference, which is the usual convention? from dataclasses import dataclass @dataclass class AAA: x: str y: str ... # decorate? class BBB(AAA): ...
From documentation, dataclasses source code and experimenting with class instances, I don't see any difference, even if new fields are added to a subclass1. If we are talking conventions, then I would advise against decorating a subclass. Class BBB's definition is supposed to say "this class behaves just like AAA, but ...
5
5
74,608,905
2022-11-29
https://stackoverflow.com/questions/74608905/single-source-of-truth-for-python-project-version-in-presence-of-pyproject-toml
The pyproject.toml specification affords the ability to specify the project version, e.g. [project] name = "foo" version = "0.0.1" However, it is also a common Python idiom to put __version__ = "0.0.1" in foo/__init__.py so that users can query it. Is there a standard way of extracting the version from the pyproject.t...
There are two approaches you can take here. Keep version in pyproject.toml and get it from the package metadata in the source code. So, in your mypkg/__init__.py or wherever: from importlib.metadata import version __version__ = version("mypkg") importlib.metadata.version is available since Python 3.8. For earlier Pyt...
13
20
74,551,520
2022-11-23
https://stackoverflow.com/questions/74551520/not-able-to-copy-file-in-docker-file-which-is-downloaded-in-github-actions
I can able to see the .pkl which is downloaded using actions/download-artifact@v3 action in work directory along with Dockerfile as shown below, When I try to COPY file inside Dockefile, I get a file not found error. How to copy the files inside docker image that are downloaded(through github actions) before building...
In your workflow file, you're not specifying the context: - name: Build container image uses: docker/build-push-action@v2 with: push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile By default, that means that docker/build-push-action uses a git context. Tha...
4
8
74,565,844
2022-11-24
https://stackoverflow.com/questions/74565844/typeerror-cannot-join-tz-naive-with-tz-aware-datetimeindex
all! I am trying to generate results of this repo https://github.com/ArnaudBu/stock-returns-prediction for stocks price prediction based on financial analysis. Running the very first step 1_get_data.py I come across an error: TypeError: Cannot join tz-naive with tz-aware DatetimeIndex The code is # -*- coding: utf-...
I just found that the issue was related to the full_data[ticker] in line 49. Once I checked its type and data inside, I found it as dataframe and as: The issue was with the time under the index column Date. So, to remove those I used this line full_data[ticker] = full_data[ticker].tz_localize(None) of code under the ...
3
5
74,616,238
2022-11-29
https://stackoverflow.com/questions/74616238/seaborn-object-interface-custom-title-and-facet-with-2-or-more-variables
I am using seaborn object interface and I want to go a little further in graph customization. Here is a case with facet plot on 2 observations: df = pd.DataFrame( np.array([['A','B','A','B'],['odd','odd','even','even'], [1,2,1,2], [2,4,1.5,3],]).T , columns= ['kind','face','Xs','Ys'] ) ( so.Plot(df,x='Xs' , y='Ys') .fa...
It's probably not what you are looking for. But with a 2-D Seaborn facet (columns and rows), it doesn't seem too bad to do it in pandas if you want to avoid defining a custom function. df = pd.DataFrame( np.array([['A','B','A','B'],['odd','odd','even','even'], [1,2,1,2], [2,4,1.5,3],]).T , columns= ['kind','face','Xs',...
3
1
74,550,915
2022-11-23
https://stackoverflow.com/questions/74550915/pulling-real-time-data-and-update-in-streamlit-and-asyncio
The goal is to pulling real time data in the background (say every 5 seconds) and pull into the dashboard when needed. Here is my code. It kinda works but two issues I am seeing: 1. if I move st.write("TESTING!") to the end, it will never get executed because of the while loop. Is there a way to improve? I can imagine ...
From my experience, the trick to using asyncio is to create your layout ahead of time, using empty widgets where you need to display async info. The async coroutine would take in these empty slots and fill them out. This should help you create a more complex application. Then the asyncio.run command can become the last...
10
8
74,598,670
2022-11-28
https://stackoverflow.com/questions/74598670/how-to-get-complete-fundamental-f0-frequency-extraction-with-python-lib-libros
I am running librosa.pyin on a speech audio clip, and it doesn't seem to be extracting all the fundamentals (f0) from the first part of the recording. librosa documentation: https://librosa.org/doc/main/generated/librosa.pyin.html sr: 22050 fmin=librosa.note_to_hz('C0') fmax=librosa.note_to_hz('C7') f0, voiced_flag, vo...
TL;DR It seems like it's all about the parameters tweaking. Here are some results that I've got playing with the example, it would be better to open it in a separate tab: The bottom plot shows a phonetic transcription (well, kinda) of the example file. Some conclusions I've made to myself: There are some words/parts ...
3
4
74,580,811
2022-11-26
https://stackoverflow.com/questions/74580811/circularity-calculation-with-perimeter-area-of-a-simple-circle
Circularity signifies the comparability of the shape to a circle. A measure of circularity is the shape area to the circle area ratio having an identical perimeter (we denote it as Circle Area) as represented in equation below. Sample Circularity = Sample Area / Circle Area Let the perimeter of shape be P, so P = 2 * p...
As I mentioned in this recent answer to a related question, OpenCV's perimeter estimate is not good enough to compute the circularity feature. OpenCV computes the perimeter by adding up all the distances between vertices of the polygon built from the edge pixels of the image. This length is typically larger than the ac...
3
4
74,601,283
2022-11-28
https://stackoverflow.com/questions/74601283/plotly-imshow-reversing-y-labels-reverses-the-image
I'd like to visualize a 20x20 matrix, where top left point is (-10, 9) and lower right point is (9, -10). So the x is increasing from left to right and y is decreasing from top to bottom. So my idea was to pass x labels as a list: [-10, -9 ... 9, 9] and y labels as [9, 8 ... -9, -10]. This worked as intended in seaborn...
You should use origin : origin (str, 'upper' or 'lower' (default 'upper')) – position of the [0, 0] pixel of the image array, in the upper left or lower left corner. The convention ‘upper’ is typically used for matrices and images. import numpy as np import plotly.express as px img = np.arange(20**2).reshape((20, 20)...
10
11
74,612,555
2022-11-29
https://stackoverflow.com/questions/74612555/django-login-payload-visible-in-plaintext-in-chrome-devtools
This is weird. I have created login functions so many times but never noticed this thing. When we provide a username and password in a form and submit it, and it goes to the server-side as a Payload like this, I can see the data in the Chrome DevTools network tab: csrfmiddlewaretoken: mHjXdIDo50tfygxZualuxaCBBdKboeK2R8...
It's supposed to be in the encrypted format right? No. What you're seeing in Chrome DevTools is the username and password before they get encrypted. If you were to run tcpdump or Wireshark when you make the request, you'd see that it is encrypted over the network. In order for the data to be usable by anyone, it has ...
4
7
74,605,877
2022-11-28
https://stackoverflow.com/questions/74605877/how-do-i-get-the-position-of-my-python-flet-window
I've been working with the python flet package for a while and I'd like to know how to get my window's position. Does anyone know anything? I googled but found nothing.
I haven't used this package before, but looking at the docs it seems that window_top and window_left on the root Page instance are what you're after (assuming this is a desktop app). See relevant docs here: https://flet.dev/docs/controls/page#window_top.
3
2
74,546,855
2022-11-23
https://stackoverflow.com/questions/74546855/mock-flask-sqlalchemy-query
I'm getting an error of Module not found when trying to create a test function to mock the get method of sqlalchemy query (with pytest) example: from mock import patch @patch('flask_sqlalchemy._QueryProperty.__get__') def test_get_all(queryMock): assert True When running pytest i get an error: ModuleNotFoundError: No ...
Use flask_sqlalchemy.model._QueryProperty.__get__ instead of flask_sqlalchemy._QueryProperty.__get__. This will resolve your issue as _QueryProperty class has been moved into model. from mock import patch @patch('flask_sqlalchemy.model._QueryProperty.__get__') def test_get_all(queryMock): assert True
3
5
74,606,902
2022-11-28
https://stackoverflow.com/questions/74606902/django-sending-post-request-using-a-nested-serializer-with-many-to-many-relati
I'm fairly new to Django and I'm trying to make a POST request with nested objects. This is the data that I'm sending: { "id":null, "deleted":false, "publishedOn":2022-11-28, "decoratedThumbnail":"https://t3.ftcdn.net/jpg/02/48/42/64/360_F_248426448_NVKLywWqArG2ADUxDq6QprtIzsF82dMF.jpg", "rawThumbnail":"https://t3.ftcd...
I would consider changing the serializer as below, class VideoManageSerializer(serializers.ModelSerializer): video_tag_id = serializers.PrimaryKeyRelatedField( many=True, queryset=VideoTag.objects.all(), write_only=True, ) tags = VideoVideoTagSerializer(many=True, read_only=True) class Meta: model = Video fields = "__a...
3
4
74,619,476
2022-11-29
https://stackoverflow.com/questions/74619476/how-to-compile-tkinter-as-an-executable-for-macos
I'm trying to compile a Tkinter app as an executable for MacOs. I tried to use py2app and pyinstaller. I almost succeed using py2app, but it returns the following error: Traceback The Info.plist file must have a PyRuntimeLocations array containing string values for preferred Python runtime locations. These strings shou...
The problem was that you need to give an executable path for the python framework you have on your MacOs. So I modify the setup.py setup.py from setuptools import setup class CONFIG: VERSION = 'v1.0.1' platform = 'darwin-x86_64' executable_stub = '/opt/homebrew/Frameworks/Python.framework/Versions/3.10/lib/libpython3.1...
5
1
74,616,757
2022-11-29
https://stackoverflow.com/questions/74616757/why-does-defining-new-class-sometimes-call-the-init-function-of-objects-th
I'm trying to understand what actually happens when you declare a new class which inherits from a parent class in python. Here's a very simple code snippet: # inheritance.py class Foo(): def __init__(self, *args, **kwargs): print("Inside foo.__init__") print(args) print(kwargs) class Bar(Foo): pass print("complete") I...
Python is using foo to determine the metaclass to use for Bar. No explicit metaclass is given, so the "most derived metaclass" must be determined. The metaclass of a base class is its type; usually, that's type itself. But in this case, the type of the only base "class", foo, is Foo, so that becomes the most derived me...
4
6
74,608,872
2022-11-29
https://stackoverflow.com/questions/74608872/error-failure-while-executing-cp-pr-private-tmp-d20221129-9397-882a6m-ca-ce
When i install python by brew, it shows error: cp: /private/tmp/d20221129-9397-882a6m/ca-certificates/./2022-10-11: unable to copy ACL to /usr/local/Cellar/ca-certificates/./2022-10-11: Permission denied cp: utimensat: /usr/local/Cellar/ca-certificates/.: Permission denied Error: Failure while executing; `cp -pR /priva...
I had the same issue and managed to fix it the following way: I saw that the upgrade script tried to copy files from /private/tmp/d20221130-21318-e53mkn/ca-certificates/./2022-10-11 to /usr/local/Cellar/ca-certificates/./2022-10-11 and I got a Permission denied meaning - I (the current mac user) could not edit/create f...
4
6
74,591,919
2022-11-27
https://stackoverflow.com/questions/74591919/how-to-catch-segfault-in-python-as-exception
Sometimes Python not only throws exception but also segfaults. Through many years of my experience with Python I saw many segfaults, half of them where inside binary modules (C libraries, i.e. .so/.pyd files), half of them where inside CPython binary itself. When segfault is issued then whole Python program finishes wi...
The simplest way is to have a "parent" process which launches your app process, and check its exit value. -11 means the process received the signal 11 which is SEGFAULTV (cf) import subprocess SEGFAULT_PROCESS_RETURNCODE = -11 segfaulting_code = "import ctypes ; ctypes.string_at(0)" # https://codegolf.stackexchange.com...
4
8
74,605,279
2022-11-28
https://stackoverflow.com/questions/74605279/python-3-11-worse-optimized-than-3-10
I run this simple loop with Python 3.10.7 and 3.11.0 on Windows 10. import time a = 'a' start = time.time() for _ in range(1000000): a += 'a' end = time.time() print(a[:5], (end-start) * 1000) The older version executes in 187ms, Python 3.11 needs about 17000ms. Does 3.10 realize that only the first 5 chars of a are n...
TL;DR: you should not use such a loop in any performance critical code but ''.join instead. The inefficient execution appears to be related to a regression during the bytecode generation in CPython 3.11 (and missing optimizations during the evaluation of binary add operation on Unicode strings). General guidelines Thi...
25
28
74,619,283
2022-11-29
https://stackoverflow.com/questions/74619283/reference-parameter-in-figure-caption-with-quarto
Is there a way to reference a parameter in a Quarto figure or table caption? In the example below, I am able to reference my input parameter txt in a regular text block, but not in a figure caption. In the figure caption, only the raw text is displayed: --- title: "example" format: html params: txt: "example" --- ## I ...
Try with !expr ```{r} #| label: fig-example #| fig-cap: !expr params$txt plot(1:10, 1:10) ``` -output If we need to add some text, either paste or use glue #| fig-cap: !expr glue::glue("This should be {params$txt}")
6
10
74,618,499
2022-11-29
https://stackoverflow.com/questions/74618499/is-there-an-easy-way-to-construct-a-pandas-dataframe-from-an-iterable-of-datacla
One can do that with dataclasses like so: from dataclasses import dataclass import pandas as pd @dataclass class MyDataClass: i: int s: str df = pd.DataFrame([MyDataClass("a", 1), MyDataClass("b", 2)]) that makes the DataFrame df with columns i and s as one would expect. Is there an easy way to do that with an attrs c...
You can access the dictionary at the heart of a dataclass like so a = MyDataClass("a", 1) a.__dict__ this outputs: {'i': 'a', 's': 1} Knowing this, if you have an iterable arr of type MyDataClass, you can access the __dict__ attribute and construct a dataframe arr = [MyDataClass("a", 1), MyDataClass("b", 2)] df = pd....
4
6
74,607,032
2022-11-28
https://stackoverflow.com/questions/74607032/vs-code-cursor-bug-in-terminal
Cursor repeating and remaining in the Integrated Terminal in VS Code I encountered this bug in my terminal while doing Python tutorial so downloaded and reinstalled the same version (latest version of VS Code) but the problem persists. I looked about for some answers but only found this tutorial which is not related. ...
Turned off GPU acceleration in the Terminal of VS Code. That has seemed to resolve the matter; No longer cursor trails. Settings > Type 'Render' > Go to Terminal › Integrated: Gpu Acceleration. Setting controls whether the terminal will leverage the GPU to do its rendering. Switch 'off' in dropdown menu
3
4
74,614,332
2022-11-29
https://stackoverflow.com/questions/74614332/is-unpacking-a-type-hint-possible-or-its-workarounds
Is there a way to unpack a tuple type alias? For example, ResultTypeA = tuple[float, float, dict[str, float]] ResultTypeB = tuple[*ResultTypeA, str, str] So that ResultTypeB evaluates to tuple[float, float, dict[str, float], str, str] instead of tuple[tuple[float, float, dict[str, float]], str, str] If not possibl...
What you are looking for may be the new typing.TypeVarTuple as proposed by PEP 646. Due to how new it is (Python 3.11+) and how big of a change this produces, many static type checkers still do not fully support it (see this mypy issue for example). Maybe typing.Unpack is actually more applicable in this case, but agai...
3
3
74,612,809
2022-11-29
https://stackoverflow.com/questions/74612809/why-are-attributes-defined-outside-init-in-popular-packages-like-sqlalchemy
I'm modifying an app, trying to use Pydantic for my application models and SQLAlchemy for my database models. I have existing classes, where I defined attributes inside the __init__ method as I was taught to do: class Measure: def __init__( self, t_received: int, mac_address: str, data: pd.DataFrame, battery_V: float =...
Defining attributes of a class in the class namespace directly is totally acceptable and is not special per se for the packages you mentioned. Since the class namespace is (among other things) essentially a blueprint for instances of that class, defining attributes there can actually be useful, when you want to e.g. pr...
3
2
74,613,853
2022-11-29
https://stackoverflow.com/questions/74613853/python-regular-expression-re-sub-to-replace-matches
I am trying to analyze an earnings call using python regular expression. I want to delete unnecessary lines which only contain the name and position of the person, who is speaking next. This is an excerpt of the text I want to analyze: "Questions and Answers\nOperator [1]\n\n Shannon Siemsen Cross, Cross Research LLC -...
The first argument to re.sub is treated as a regular expression, so the square brackets get a special meaning and don't match literally. You don't need a regular expression for this replacement at all though (and you also don't need the loop counter i): for name_line in name_lines: text = text.replace(name_line, '')
4
4
74,597,855
2022-11-28
https://stackoverflow.com/questions/74597855/where-does-pip3-install-package-binaries
It see that depending on system and configuration, packages are installed in different places. Example: Machine 1: pip3 install fb-idb pip3 show fb-idb > ... > /opt/homebrew/lib/python3.9/site-packages Machine 2: pip3 install fb-idb pip3 show fb-idb > ... > /us/local/lib/python3.10/site-packages Now the problem I hav...
pip3 show --files fb-idb shows where pip has installed all the files of the package. Run pip3 show --files fb-idb | grep -F /bin/ to extract the directory where pip installed scripts and entry points (On Windows it's \Scripts\). The directories are related to the header Location: so either do grep -F Location: separat...
3
6
74,611,317
2022-11-29
https://stackoverflow.com/questions/74611317/enable-pyenv-virtualenv-prompt-at-terminal
I just installed pyenv and virtualenv following: https://realpython.com/intro-to-pyenv/ After completing installation I was prompted with: pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior I added export PYENV_VIRTUALENV...
Borrowing a solution from here, the following works (added to .bashrc or .bash_aliases): export PYENV_VIRTUALENV_DISABLE_PROMPT=1 export BASE_PROMPT=$PS1 function updatePrompt { if [[ "$(pyenv virtualenvs)" == *"* $(pyenv version-name) "* ]]; then export PS1='($(pyenv version-name)) '$BASE_PROMPT else export PS1=$BASE_...
3
6
74,608,230
2022-11-29
https://stackoverflow.com/questions/74608230/no-artists-with-labels-found-to-put-in-legend-error-when-changing-the-legend
I want to make my legend size bigger in Pyplot. I used this answer to do that. Here is my code. import matplotlib.pyplot as plt import seaborn as sns sns.set_style("whitegrid") plt.rcParams['figure.figsize'] = [15, 7] lst = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,4,5,6] plt.plot(lst) plt.legend(fontsize="x-large") # Here I make...
"Artist" is a term from matplotlib: https://matplotlib.org/stable/tutorials/intermediate/artists.html Presumably the error message means that there are no items in the legend whose font size can be changed. Maybe pass the fontsize argument to the same plt.legend call in which you create the legend, or call plt.legend(f...
21
17