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 |
|---|---|---|---|---|---|---|
75,384,141 | 2023-2-8 | https://stackoverflow.com/questions/75384141/python-polars-find-the-length-of-a-string-in-a-dataframe | I am trying to count the number of letters in a string in Polars. I could probably just use an apply method and get the len(Name). However, I was wondering if there is a polars specific method? import polars as pl df = pl.DataFrame({ "start_date": ["2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05"], "Name": ["John... | You can use .str.len_bytes() that counts number of bytes in the UTF8 string .str.len_chars() that counts number of characters df.with_columns( pl.col("Name").str.len_bytes().alias("bytes"), pl.col("Name").str.len_chars().alias("chars") ) shape: (4, 4) ┌────────────┬───────┬───────┬───────┐ │ start_date ┆ Name ┆ byte... | 3 | 6 |
75,445,290 | 2023-2-14 | https://stackoverflow.com/questions/75445290/poetry-no-file-folder-for-package | I have a simple project layout myproject on main [$!?] is 📦 v1.0.0 via v18.14.0 via 🐍 v3.10.9 ❯ tree -L 1 . ├── build ├── deploy ├── Dockerfile ├── poetry.lock ├── pyproject.toml ├── README.md ├── scripts.py └── src The pyproject.toml is: [tool.poetry] name = "myproject" version = "0.1.0" description = "" author... | Short answer: The directory where your pyproject.toml file sits needs to be share the same name, e.g., if the name config in pyproject.toml is name = "myproject", the directory needs to be also named myproject. Therefore, you must either: Rename the directory to match your name configuration in the pyproject.toml or M... | 11 | 10 |
75,383,650 | 2023-2-8 | https://stackoverflow.com/questions/75383650/how-to-limit-rows-in-pandas-dataframe | How to limit number of rows in pandas dataframe in python code. I needed last 1000 rows the rest need to delete. For example 1000 rows, in pandas dataframe -> 1000 rows in csv. I tried df.iloc[:1000] I needed autoclean pandas dataframe and saving last 1000 rows. | With df.iloc[:1000] you get the first 1000 rows. Since you want to get the last 1000 rows, you have to change this line a bit to df_last_1000 = df.iloc[-1000:] To safe it as a csv file you can use pandas' to_csv() method: df_last_1000.to_csv("last_1000.csv") Update - Speed Comparison: Both .tail(1000) and .iloc[-1000:... | 3 | 7 |
75,391,653 | 2023-2-8 | https://stackoverflow.com/questions/75391653/importerror-cannot-import-name-association-proxy-from-sqlalchemy-ext-associa | I am working on a small flask API using flask-admin and flask-sqlalchemy. The api runs well but whenever I install a new package I am faced with an error. Error: While importing 'app', an ImportError was raised: Traceback (most recent call last): File "/Users/brandoncreed/.local/share/virtualenvs/management-System-Wyc_... | This issue has been fixed in Flask-Admin v1.6.1, which can be installed like this: python3 -m pip install --upgrade flask-admin Flask-Admin versions earler than v1.6.1 are not compatible with SQLAlchemy 2.0. The was an issue for this specific problem. The recommended workaround was to install an earlier version of SQL... | 3 | 8 |
75,453,995 | 2023-2-14 | https://stackoverflow.com/questions/75453995/pandas-plot-vars-argument-must-have-dict-attribute | It was working perfectly earlier but for some reason now I am getting strange errors. pandas version: 1.2.3 matplotlib version: 3.7.0 sample dataframe: df cap Date 0 1 2022-01-04 1 2 2022-01-06 2 3 2022-01-07 3 4 2022-01-08 df.plot(x='cap', y='Date') plt.show() df.dtypes cap int64 Date datetime64[ns] dtype: object I... | In fact, this problem may be caused by running your code like default script (or in PyCharm interactive console), not in Jupyter. If it is true, you can fix this error by setting up backend directly in your file with use function: import matplotlib as mpl import matplotlib.pyplot as plt mpl.use('TkAgg') # !IMPORTANT fi... | 11 | 15 |
75,394,143 | 2023-2-9 | https://stackoverflow.com/questions/75394143/openai-api-error-no-module-named-openai-embeddings-utils-openai-is-not-a | I want to use openai.embeddings_utils import get_embeddings So already install openai Name: openai Version: 0.26.5 Summary: Python client library for the OpenAI API Home-page: https://github.com/openai/openai-python Author: OpenAI Author-email: support@openai.com License: Location: /Users/lima/Desktop/Paprika/Openai/.v... | For my case, check the version of openai. openai.embeddings_utils does not exist in latest openai 1.2.0, but exists in 0.27.7 | 10 | 8 |
75,440,354 | 2023-2-13 | https://stackoverflow.com/questions/75440354/why-does-pandas-read-excel-fail-on-an-openpyxl-error-saying-readonlyworksheet | This bug suddenly came up literally today after read_excel previously was working fine. Fails no matter which version of python3 I use - either 10 or 11. Do folks know the fix? File "/Users/aizenman/My Drive/code/daily_new_clients/code/run_daily_housekeeping.py", line 38, in <module> main() File "/Users/aizenman/My Dr... | Currently, we face the issue on python3.8 environment (Rocky 8.8 OS). We downgrade the openpyxl module to 3.0.9 to fix this issue. sudo pip3 install openpyxl==3.0.9 Enjoy it! | 13 | 0 |
75,442,308 | 2023-2-14 | https://stackoverflow.com/questions/75442308/how-to-calculate-the-month-begin-and-end-month-date-from-date-in-polars | Is there an efficient way to get the month end date on a date column. Like if date =‘2023-02-13” to return “2023-02-28”, also beginning of the month would be great as well. Thanks! df = pl.DataFrame({'DateColumn': ['2022-02-13']}) test_df = df.with_columns([ pl.col('DateColumn').str.strptime(pl.Date).cast(pl.Date) ] ) ... | [Update]: Polars has since added .month_start() and .month_end() methods. See the answer from @n-maks You could use .truncate and .offset_by test_df.with_columns( MonthStart = pl.col("DateColumn").dt.truncate("1mo"), MonthEnd = pl.col("DateColumn").dt.offset_by("1mo").dt.truncate("1mo").dt.offset_by("-1d") ) shape: (... | 3 | 7 |
75,406,182 | 2023-2-10 | https://stackoverflow.com/questions/75406182/pyexcel-get-book-and-get-records-functions-throw-exceptions-for-xlsx-files | I'm trying to open an XLSX file using pyexcel. But it fails for both get_book and get_records with the following error. However if I try to read the same file converted to xls it does work. I get the files uploaded by users: so can not restrict uploading files in XLSX format. >>> import pyexcel >>> workbook = pyexcel.g... | You can downgrade openpyxl to 3.0.10 for now. I referenced your issue here: https://foss.heptapod.net/openpyxl/openpyxl/-/issues/1960 Pyexcel uses openpyxl to open xlsx files. The commands are: pip uninstall openpyxl pip install openpyxl==3.0.10 | 3 | 11 |
75,382,340 | 2023-2-8 | https://stackoverflow.com/questions/75382340/python-pandas-read-excel-error-value-must-be-either-numerical-or-a-string-conta | I dont know why this error occurs. pd.read_excel('data/A.xlsx', usecols=["B", "C"]) Then I get this error: "Value must be either numerical or a string containing a wild card" So i change my code use nrows all data pd.read_excel('data/A.xlsx', usecols=["B","C"], nrows=172033) Then there is no error and a dataframe is... | This problem is unique to the latest version of the Openpyxl library, v3.1.2. Downgrading to v.3.0.10 will fix this issue. | 14 | 24 |
75,424,730 | 2023-2-12 | https://stackoverflow.com/questions/75424730/what-type-hint-should-i-write-when-the-return-type-is-uncertain | For example, if I define this function: def open_pkl(src: str) -> ?: with open('serialized.pkl', 'rb') as f: data = pickle.load(f) return data what type hint should I write for the return value? Now, I write the function as: def open_pkl(src: str): with open('serialized.pkl', 'rb') as f: data = pickle.load(f) return d... | There are two options: object and typing.Any. Returning an object signals to the caller of the function that nothing can be assumed about the returned object (since everything is an object, saying that something is an object gives no information). So, if a user were to do def open_pkl(src: str) -> object: ... something... | 3 | 4 |
75,418,252 | 2023-2-11 | https://stackoverflow.com/questions/75418252/how-to-create-3d-torus-from-circle-revolved-about-x-2r-r-is-the-radius-of-circl | I need help to create a torus out of a circle by revolving it about x=2r, r is the radius of the circle. I am open to either JULIA code or Python code. Whichever that can solve my problem the most efficient. I have Julia code to plot circle and the x=2r as the axis of revolution. using Plots, LaTeXStrings, Plots.PlotMe... | My take with Makie: using GLMakie Base.@kwdef mutable struct Torus R::Float64 = 2 r::Float64 = 1 end function generate_torus(torus::Torus, resolution=100; upto=1.0) u = range(0, stop=2π*upto, length=resolution) v = range(0, stop=2π*upto, length=resolution) x = [ ( torus.R + torus.r*cos(vᵢ) ) * cos(uᵢ) for vᵢ in v, uᵢ i... | 4 | 1 |
75,392,950 | 2023-2-9 | https://stackoverflow.com/questions/75392950/how-does-python-version-affect-azure-functions | I'm developing Azure Functions using Python 3.10.10 on my machine, deploying the Function through Azure DevOps which is building the artifact using Python 3.6.8, and the Python Version shown for the Function App host is 3.8. There was a recent update of Azure Functions Runtime which deprecated Python 3.6. (see breaking... | Alignment Always keep in Azure DevOps a version of python venv that matches the App host and also keep the same dependencies within a requirements.txt file so that you don't have conflicts from different libraries. On your local you should also have a python venv that matches the same version of the host. I would sug... | 3 | 3 |
75,419,693 | 2023-2-11 | https://stackoverflow.com/questions/75419693/transparent-textures-being-rendered-as-black-in-opengl | I have a texture with transparent parts, but instead of being rendered transparent they're black. To test if the RGBA values get passed on correctly to the shader, I made everything render in greyscale. And as I thought the alpha values weren't getting passed on correctly. So anyway here is how the textures get loade... | From glTexImage2D: glTexImage2D( GL_TEXTURE_2D, // Target 0, // Level 3, // Internalformat -> 3 -> GL_RGB -> no alpha // Framebuffer does not necessarily // need an alpha channel. // But if you want transparent textures // you have to specify one, // E.g. GL_RGBA (or any other format // from Table 2 with alpha). ix, //... | 3 | 2 |
75,395,892 | 2023-2-9 | https://stackoverflow.com/questions/75395892/writing-a-tuple-search-with-django-orm | I'm trying to write a search based on tuples with the Django ORM syntax. The final sql statement should look something like: SELECT * FROM mytable WHERE (field_a,field_b) IN ((1,2),(3,4)); I know I can achieve this in django using the extra keyword: MyModel.objects.extra( where=["(field_a, field_b) IN %s"], params=[((... | For reference and inspired from akshay-jain proposal, I managed to write something that works: from django.db.models import Func,Value def ValueTuple(items): return tuple(Value(i) for i in items) class Tuple(Func): function = '' qs = ( MyModel.objects .alias(a=Tuple('field_a', 'field_b')) .filter(a__in=ValueTuple([(1, ... | 5 | 4 |
75,426,868 | 2023-2-12 | https://stackoverflow.com/questions/75426868/tensorflow-gpu-problem-libnvinfer-so-7-and-libnvinfer-so-7-could-not-load | I installed TensorFlow under WSL 2, Ubuntu 22.04 (Jammy Jellyfish), I followed the instructions in Install TensorFlow with pip. *I also installed Nvidia drivers for Windows and in my other WSL 2, I use GPU-supported simulation program. Everything seemed OK. I didn't get any error message during installation, but when I... | I changed version and the problem was solved: pip install --upgrade tensorflow==2.8 Note: When I use v2.10, I get the same error message. v2.8 is stable now. | 3 | 8 |
75,451,239 | 2023-2-14 | https://stackoverflow.com/questions/75451239/how-to-reference-input-in-params-section-of-snakemake-rule | I need to process my input file values, turning them into a comma-separated string (instead of white space) in order to pass them to a CLI program. To do this, I want to run the input files through a Python function. How can I reference the input files of a rule in the params section of the same rule? This is what I've... | Turns out I need to explicitly add input to the lambda w: part: rule a: input: foo="a.txt", bar=expand({build}.txt,build=config["build"]), output: baz=result.txt, params: joined_bar=lambda w, input: ",".join(input.bar), # ', input' was added shell: """ qux --comma-separated-files {params.joined_bar} \ --foo {input.foo}... | 4 | 7 |
75,407,052 | 2023-2-10 | https://stackoverflow.com/questions/75407052/installing-test-files-with-pyproject-toml-and-setuptools | I'm migrating an old python project to the new pyproject.toml based system and am having trouble with getting files that are required by tests to install. Inside the pyproject.toml I have: [tool.setuptools] package-data = {"my_pkg_name" = ["tests/*.sdf", "tests/*.urdf", "tests/*.xml", "tests/meshes/*.obj"]} [build-syst... | Looking more into this, specifically: https://setuptools.pypa.io/en/stable/userguide/datafiles.html#non-package-data-files my problem is that these files are not part of the default found packages which are just the ones under src. It is also not clear whether test files should be installed or not - many projects expli... | 3 | 3 |
75,439,401 | 2023-2-13 | https://stackoverflow.com/questions/75439401/child-class-from-magicmock-object-has-weird-spec-str-and-cant-use-or-mock-met | When a class is created deriving from a MagicMock() object it has an unwanted spec='str'. Does anyone know why this happens? Does anyone know any operations that could be done to the MagicMock() object in this case such that it doesn't have the spec='str' or can use methods of the class? from unittest.mock import Magic... | In Python, classes are actually instances of the type class. A class statement like this: class c(a): @staticmethod def x(): return 1 is really syntactic sugar of calling type with the name of the class, the base classes and the class members: c = type('c', (a,), {'x': staticmethod(lambda: 1)}) The above statement wo... | 3 | 2 |
75,442,675 | 2023-2-14 | https://stackoverflow.com/questions/75442675/lxml-fails-to-import-with-error-symbol-not-found-in-flat-namespace-xsltdocde | With the code: from lxml.etree import HTML, XML I get the traceback: Traceback (most recent call last): File "/Users/username/code/project/lxml-test.py", line 3, in <module> from lxml.etree import HTML, XML ImportError: dlopen(/Users/username/.virtualenvs/project-venv/lib/python3.11/site-packages/lxml/etree.cpython-31... | I solved my problem by cloning lxml, building it, and installing it via pip install -e /path/to/lxml | 3 | 1 |
75,427,538 | 2023-2-12 | https://stackoverflow.com/questions/75427538/regulargridinterpolator-excruciatingly-slow-compared-to-interp2d | Consider the following code example: # %% import numpy from scipy.interpolate import interp2d, RegularGridInterpolator x = numpy.arange(9000) y = numpy.arange(9000) z = numpy.random.randint(-1000, high=1000, size=(9000, 9000)) f = interp2d(x, y, z, kind='linear', copy=False) f2 = RegularGridInterpolator((x, y), z, "lin... | There is no problem with your code, it's probably a bug in scipy. I've reported it on github | 4 | 3 |
75,414,955 | 2023-2-10 | https://stackoverflow.com/questions/75414955/how-to-view-runtime-warnings-in-pycharm-when-running-tests-using-pytest | When running tests in PyCharm 2022.3.2 (Professional Edition) using pytest (6.2.4) and Python 3.9 I get the following result in the PyCharm console window: D:\cenv\python.exe "D:/Program Files (x86)/JetBrains/PyCharm 2022.3.2/plugins/python/helpers/pycharm/_jb_pytest_runner.py" --path D:\tests\test_k.py Testing starte... | The solution is a combination of two things: Setting 'do not add "--no-header --no-summary -q"' in advanced settings as @Override12 suggested. When the same warning is issued multiple times, only the first time is displayed. In my case solving the first warning reduced the number of warnings from 278 to 2. | 8 | 9 |
75,433,179 | 2023-2-13 | https://stackoverflow.com/questions/75433179/how-to-form-an-opcua-connection-in-python-from-server-ip-address-port-security | I have never used OPC-UA before, but now faced with a task where I have to pull data from a OPC-UA machine to push to a SQL database using python. I can handle the database part, but how to basically connect to the OPCUA server when I have only the following fields available? IP address 192.168.38.94 Port 8080 Securit... | You need to know which protocol is used. Then you can create the URLs by using the IP address as domain: OPC UA binary: opc.tcp://ip:port https https://ip:port OPC UA WebSockets opc.wss://ip:port http http://ip:port (Deprecated in Version 1.03) In your example this could be opc.tcp://192.168.38.94:8080 or https://192... | 3 | 2 |
75,449,889 | 2023-2-14 | https://stackoverflow.com/questions/75449889/check-if-request-is-coming-from-swagger-ui | Using Python and Starlette or FastAPI, How can I know if the request is coming from the Swagger UI or anywhere else (Postman, Frontend app)? I tried to see if there's something in Request object which I can use: from fastapi import Request @app.get("/") async def root(request: Request): # request.client.host just retur... | You could always use the referer header of the request: from fastapi import Request @app.get("/") async def root(request: Request): request_from_swagger = request.headers['referer'].endswith(app.docs_url) if request_from_swagger: return {"message": "Hello Swagger UI"} return {"message": "Hello World"} | 4 | 3 |
75,424,120 | 2023-2-12 | https://stackoverflow.com/questions/75424120/tensorflow-nvidia-gpu-not-detected | Hi I'm struggling to get Tensorflow V2.11 to find my eGPU (RTX 3060 Ti) I am currently on Windows 11 CUDA version is 12 I am currently downloading CUDA 11 as well as CUDnn as I've heard it is recommended I have tried the following code: import tensorflow as tf tf.config.list_physical_devices('GPU') which outputs: [] ... | Tensorflow 2.11 is not supporting GPU on Windows machine. TensorFlow 2.10 was the last TensorFlow release that supported GPU on native-Windows. So you can try by installing Tensorflow 2.10 for the GPU setup. Also you need to install the specific version of CUDA and cuDNN for GPU support in your system which is CUDA 11.... | 6 | 5 |
75,446,123 | 2023-2-14 | https://stackoverflow.com/questions/75446123/cant-correctly-dump-ansible-vault-into-yaml-with-python | I have a python dictionary with an Ansible vault as a value. I can't seem to be able to correctly dump it into a yaml output with the correct formatting. I'm using the ansible-vault package to generate the encrypted data as follows: from ansible_vault import Vault import yaml vault = Vault('secretpassword') data = "sec... | The !vault in your expected output YAML document is a tag. Tags start with an exclamation mark, and if you dump a string to YAML that starts with an exclacmation mark, that string needs to be quoted. In a similar vein, the pipe (|) indicates you want a literal style scalar, and including that in your string, will not g... | 3 | 5 |
75,446,361 | 2023-2-14 | https://stackoverflow.com/questions/75446361/run-short-python-code-directly-on-snakemake | I have a snakemake pipeline where I need to do a small step of processing the data (applying a rolling average to a dataframe). I would like to write something like this: rule average_df: input: # script = , df_raw = "{sample}_raw.csv" params: window = 83 output: df_avg = "{sample}_avg.csv" shell: """ python import pan... | This can be achieved via run directive: rule average_df: input: # script = , df_raw = "{sample}_raw.csv" params: window = 83 output: df_avg = "{sample}_avg.csv" run: import pandas as pd df=pd.read_csv(input.df_raw) df=df.rolling(window=params.window, center=True, min_periods=1).mean() df.to_csv(output.df_avg) Note tha... | 3 | 2 |
75,439,217 | 2023-2-13 | https://stackoverflow.com/questions/75439217/error-debugging-python-in-vs-code-pythonpath-is-not-valid-if-python-is-spec | I get a prompt with: Invalid Message: "pythonPath" is not valid if "python" is specified and the option to open launch.json. But my launch.json doesn't contain anything that says "pythonPath": { "configurations": [ { "name": "Docker: Python - General", "type": "docker", "request": "launch", "preLaunchTask": "docker-ru... | Your code is fine. It's VSCode / Python Extension that got updated to version 1.75 and 2023.02 respectively and hence this error is new. Please refer to this issue for constant development on the bug. As for now, uninstall VSCode and re-install 1.74, and re-install the python extension before 2023.02 and you should be ... | 4 | 9 |
75,434,681 | 2023-2-13 | https://stackoverflow.com/questions/75434681/type-hint-decorator-for-sync-async-functions | How can I type hint decorator that is meant to be used for both sync & async functions? I've tried something like below, but mypy raises errors: x/decorator.py:130: error: Incompatible types in "await" (actual type "Union[Awaitable[Any], R]", expected type "Awaitable[Any]") [misc] x/decorator.py:136: error: Incompatibl... | Say you want to write a function decorator that performs some actions before and/or after the actual function call. Let's call that surrounding context my_context. If you want the decorator to be applicable to both asynchronous and regular functions, you'll need to accommodate both types in it. How can we properly anno... | 4 | 6 |
75,416,108 | 2023-2-10 | https://stackoverflow.com/questions/75416108/polars-yyyy-week-into-a-date | Does anyone know how to parse YYYY Week into a date column in Polars? I have tried this code but it throws an error. import polars as pl pl.DataFrame({ "week": [201901, 201902, 201903, 201942, 201943, 201944] }).with_columns(pl.col("week").cast(pl.String).str.to_date("%Y%U").alias("date")) InvalidOperationError: conve... | This seems like a bug (although one with the underlying rust package chrono rather than polars itself). I tried using base python's strptime and it ignores the %U and just gives the first of the year for all cases so you can either do string manipulation and math like this (assuming you don't need an exact response) pl... | 3 | 4 |
75,438,567 | 2023-2-13 | https://stackoverflow.com/questions/75438567/r-style-formulas-when-implementing-a-power-i-e-square-in-a-glm-misbehaves | In the python code below, the glm model specification does not include the third power in the in model1 but it does in model2: model1 = glm(formula="wage ~ workhours + workhours**3 + C(gender)", data=df, family=sm.families.Gaussian()) model2 = glm(formula="wage ~ workhours + np.power(workhours, 3) + C(gender)", data=df... | ** in a formula is treated as a formula operator, not as regular exponentiation. (This is similar to how ^ works in an R formula.) (a+b+c+d)**3 means that the model should include a, b, c, d, and all interactions between these variables up to 3rd order. workhours**3 means that the model should include workhours and all... | 3 | 6 |
75,433,717 | 2023-2-13 | https://stackoverflow.com/questions/75433717/module-keras-utils-generic-utils-has-no-attribute-get-custom-objects-when-im | I am working on google colab with the segmentation_models library. It worked perfectly the first week using it, but now it seems that I can't import the library anymore. Here is the error message, when I execute import segmentation_models as sm : -------------------------------------------------------------------------... | Encountered the same issue sometimes. How I solved it: open the file keras.py, change all the 'init_keras_custom_objects' to 'init_tfkeras_custom_objects'. the location of the keras.py is in the error message. In your case, it should be in /usr/local/lib/python3.8/dist-packages/efficientnet/ | 7 | 6 |
75,431,587 | 2023-2-13 | https://stackoverflow.com/questions/75431587/type-hinting-with-unions-and-collectables-3-9-or-greater | I've been on Python 3.8 for quite some time. I usually type hint with the convention: from typing import List, Union some_stuff: List[Union[int, str, float, List[str]]] = [98, "Fido", -34.925, ["Phantom", "Tollbooth"]] I understand that with python 3.9 or greater you can type hint lists and collectible like: some_ints... | PEP 604, which was implemented in Python 3.10 allows Union types to be formed using the | operator (which has existed with exclusively numeric meanings for most of Python's history). So in sufficiently recent versions of Python, you can write your type hint like this, with no imports required from typing: some_stuff: l... | 5 | 4 |
75,430,161 | 2023-2-12 | https://stackoverflow.com/questions/75430161/cursor-count-gives-attributeerror-in-pymongo-4-3-3 | As the title suggests, I am trying to use count() with a find() on a collection but it keeps throwing the error AttributeError: 'Cursor' object has no attribute 'count'. For reference, I went through this question but count_documents() seems to be tehre for colelctions themselves, and not cursors. The other option ment... | list() will exhaust the cursor, but save its ouput to a variable and you can access it multiple times, e.g. records = list(col.find()) num_records = len(records) for record in records: # do stuff | 4 | 3 |
75,420,574 | 2023-2-11 | https://stackoverflow.com/questions/75420574/as-of-2023-is-there-any-way-to-line-profile-cython-at-all | Something has substantially changed with the way that line profiling Cython works, such that previous answers no longer work. I am not sure if something subtle has changed, or if it is simply totally broken. For instance, here is a very highly upvoted question about this from about 8 years ago. The notebook in there no... | The current status is: line_profiler v4 and Cython don't get on (for reasons that haven't yet been diagnosed but could be on either end). The line_profiler tests run as part of Cython's CI test-suite have line_profiler pinned to <4. It obviously isn't the long-term plan to leave this version pin, but if you need to it ... | 3 | 3 |
75,425,406 | 2023-2-12 | https://stackoverflow.com/questions/75425406/creating-video-from-images-using-pyav | I am trying to write a function that creates a new MP4 video from a set of frames taken from another video. The frames will be given in PIL.Image format and is often cropped to include only a part of the input video, but all images will have the same dimension. What I have tried: def modify_image(img): return img test_... | Using add_stream(template=in_stream) is only documented in the Remuxing example. It's probably possible to use template=in_stream when re-encoding, but we have to set the time-base, and set the PTS timestamp of each encoded packet. I found a discussion here (I didn't try it). Instead of using template=in_stream, we may... | 3 | 5 |
75,393,856 | 2023-2-9 | https://stackoverflow.com/questions/75393856/tqdm-4-27-distribution-was-not-found-error-while-executing-a-exe-file-create | I am trying to create a application which checks for sentence similarity. .exe file got created. I get the below error message while executing .exe file after giving required inputs. Error Message The 'tqdm>=4.27' distribution was not found and is required by this application. Try: pip install transformers -U or pip in... | after adding below instructions in spec file I was able to resolve the issue datas += copy_metadata('tqdm') datas += copy_metadata('regex') datas += copy_metadata('requests') datas += copy_metadata('packaging') datas += copy_metadata('filelock') datas += copy_metadata('numpy') datas += copy_metadata('tokenizers') datas... | 3 | 3 |
75,424,785 | 2023-2-12 | https://stackoverflow.com/questions/75424785/case-insensitive-array-any-filter-in-sqlalchemy | I'm migrating some code from SqlAlchemy 1.3 to SqlAlchemy 1.4 with Postgres 12. I found a query that looks like this: session.query(Horse) .filter(Horse.nicknames.any("charlie", operator=ColumnOperators.ilike)) The type of the column nicknames is Column(ARRAY(String(64))). It seems to me that what this is doing is que... | This query seems to have broken in SQLAlchemy version 1.3.20*. In 1.3.0 it generated this SQL (aliases removed for clarity): SELECT id, nicknames FROM horse WHERE 'charlie' ILIKE ANY (nicknames) The docs for any mention that it has been superseded by any_, though it doesn't seem to have been formally deprecated. With ... | 3 | 2 |
75,424,530 | 2023-2-12 | https://stackoverflow.com/questions/75424530/why-does-the-id-function-in-python-return-the-same-value-for-different-integer-o | I have a function to retrieve an object in Python using the ctypes module: import ctypes def object_at_addr(obj_addr): try: val = ctypes.cast(obj_addr, ctypes.py_object).value except: return None return val I know that the id of an object shows the memory address the object is at (for the most part as far as I've seen... | The id is always the memory address in the CPython implementation. The reason that you saw numbers with the same id here is that memory addresses can be re-used. The id is only guaranteed to be unique for the lifetime of the object, and since nothing else was holding a reference to the integer 4343595216 it got deleted... | 3 | 7 |
75,424,382 | 2023-2-12 | https://stackoverflow.com/questions/75424382/use-different-values-of-expandtabs-in-the-same-string-python | How can we define several tab lengths in a python string? For example, we want to print the keys, value types and values of a dict nicely aligned (with varying sizes of keys and types): my_dict = { "short_key": 4, "very_very_very_very_very_long_keys": 5.0 } formatted_string_1 = '\n'.join([f"{k}:\t({type(v).__name__})\t... | Don't use tabs for alignment. You can specify your desired widths directly in the f-string's format spec: print( '\n'.join( f"{f'{k}:':40}" f"{f'({type(v).__name__})':10}" f"{v:<}" for k, v in my_dict.items() ) ) outputs short_key: (int) 4 very_very_very_very_very_long_keys: (float) 5.0 You can even use variable widt... | 4 | 3 |
75,423,382 | 2023-2-11 | https://stackoverflow.com/questions/75423382/how-to-remove-carriage-return-characters-from-string-as-if-it-was-printed | I would like to remove all occurrences of \r from a string as if it was printed via print() and store the result in another variable. Example: >>> s = "hello\rworld" >>> print(s) world In this example, how do I "print" s to a new variable which then contains the string "world"? Background: I am using the subprocess mo... | Using a regex: import re s = "hello\rworld" out = re.sub(r'([^\r]+)\r([^\r\n]+)', lambda m: m.group(2)+m.group(1)[len(m.group(2)):], s) Output: 'world' More complex example: import re s = "hello\r..\nworld" out = re.sub(r'([^\r]+)\r([^\r\n]+)', lambda m: m.group(2)+m.group(1)[len(m.group(2)):], s) Output: ..llo world... | 4 | 1 |
75,418,560 | 2023-2-11 | https://stackoverflow.com/questions/75418560/how-do-i-format-both-a-string-and-variable-in-an-f-string | I'm trying to move both the "$" and totalTransactionCost to the right side of the field. My current code is : print(f"Total Cost Of All Transactions: ${totalTransactionCost:>63,.2f}") The code is able to move the totalTransactionCost to the right side of the field, but how can I include the "$" too? | You can use nested f-strings, which basically divides formatting into two steps: first, format the number as a comma-separated two-decimal string, and attach the $, and then fill the whole string with leading spaces. >>> totalTransactionCost = 10000 >>> print(f"Total Cost Of All Transactions: {f'${totalTransactionCost:... | 3 | 5 |
75,417,119 | 2023-2-10 | https://stackoverflow.com/questions/75417119/how-to-find-what-is-the-latest-version-of-python-that-pytorch | When I try pip install torch, I get ERROR: Could not find a version that satisfies the requirement torch (from versions: none) ERROR: No matching distribution found for torch Searching on here stackoverflow I find that the issue is I need an older verson of python, currently I'm using 3.11. That post said 3.8 but was w... | You can always check torch archive or torch nightly to see if your desired version is supported. While the Python3.11 is not officially supported as of now (Feb 11, 2023), if you are on Linux you can install the Python3.11 version of Pytorch 1.13.1: wget https://download.pytorch.org/whl/cu117/torch-1.13.1%2Bcu117-cp311... | 7 | 2 |
75,416,188 | 2023-2-10 | https://stackoverflow.com/questions/75416188/get-evenly-spaced-points-from-a-curved-shape | How may I take a shape that was created with more points at its curves and subdivide it so that the points are distributed more equally along the curve? In my research I thought that numpy's interp might be the right function to use, but I don't know what to use for the parameters (x, xp, fp, left, right, & period). An... | from matplotlib import pyplot as plt import numpy as np x = np.array([1321.4, 598.6, 580.6, 563.8, 548.6, 535.4, 524.5, 516.2, 511, 509.2, 509.2, 511, 516.2, 524.5, 535.4, 548.6, 563.8, 580.6, 598.6, 1321.4, 1339.4, 1356.2, 1371.4, 1384.6, 1395.5, 1403.8, 1409, 1410.8, 1410.8, 1409, 1403.8, 1395.5, 1384.6, 1371.4, 135... | 3 | 5 |
75,411,163 | 2023-2-10 | https://stackoverflow.com/questions/75411163/apache-airflow-create-tasks-using-for-loop-in-one-dag-i-want-tasks-made-of-fo | A task that performs the same task in one dag was created using a for loop. It is hoped to be divided into two branches that depend on the result of this task. However, all tasks created using the for loop return the xcom of the last task. How can tasks created using for loop return each xcom? Each task a,b,c returns x... | I'm unable to reproduce the behavior you describe using classic operators and the TaskFlow API. If you are able to add more context and code of what you are actually executing that would be most helpful. In the meantime, here are the examples I used should it give you some guidance for troubleshooting. I added a task a... | 3 | 4 |
75,387,306 | 2023-2-8 | https://stackoverflow.com/questions/75387306/azure-ml-experiment-using-custom-gpu-cuda-environment | During the last week I have been trying to create a python experiment in Azure ML studio. The job consists on training a PyTorch (1.12.1) Neural Network using a custom environment with CUDA 11.6 for GPU acceleration. However, when attempting any movement operation I get a Runtime Error: device = torch.device("cuda") te... | The problem is indeed sensitive and hard to debug. I suspect it has to do with the underlying hardware on which the docker container is deployed, not with the actual custom Docker container and its corresponding dependencies. Since you have a Tesla K80, I suspect NC series video cards (upon which the environments are d... | 3 | 5 |
75,404,979 | 2023-2-9 | https://stackoverflow.com/questions/75404979/why-does-my-context-manager-not-exit-on-exception | I am learning about context managers and was trying to build one myself. The following is a dummy context manager that opens a file in read mode (I know I can just do with open(...): .... this is just an example I built to help me understand how to make my own context managers): @contextmanager def open_read(path: str)... | The line f.close() is never reached (we exit that frame early due to unhandled exception), and then the exception was "handled" in the outer frame (i.e. within foo). If you want it to close regardless, you'll have to implement it like that: @contextmanager def open_read(path: str): f = open(path, 'r') try: print('open'... | 6 | 7 |
75,392,769 | 2023-2-8 | https://stackoverflow.com/questions/75392769/how-to-use-apache-arrow-ipc-from-multiple-processes-possibly-from-different-lan | I'm not sure where to begin, so looking for some guidance. I'm looking for a way to create some arrays/tables in one process, and have it accessible (read-only) from another. So I create a pyarrow.Table like this: a1 = pa.array(list(range(3))) a2 = pa.array(["foo", "bar", "baz"]) a1 # <pyarrow.lib.Int64Array object at ... | Do I need to wrap the shm.buf with something? Yes, you can use pa.py_buffer() to wrap it: size = calculate_ipc_size(table) shm = shared_memory.SharedMemory(create=True, name=name, size=size) stream = pa.FixedSizeBufferWriter(pa.py_buffer(shm.buf)) with pa.RecordBatchStreamWriter(stream, table.schema) as writer: write... | 9 | 10 |
75,401,197 | 2023-2-9 | https://stackoverflow.com/questions/75401197/pandas-extensions-usage-without-importing-it | I have created pandas extensions as mentioned here. The extending classes are defined in a module named pd_extensions, and I would like to use them in a different module my_module for example. The two modules are in the same package called source. currently to be able to use the extensions Im importing the pd_extension... | I think you can import the extension module in __init__ file since the extension module will first import pandas and then register the accessor therefore the pandas module will be cached in sys.modules and any subsequent import to pandas from other modules will simply retrieve the entry from the cache. here is the simp... | 3 | 2 |
75,401,348 | 2023-2-9 | https://stackoverflow.com/questions/75401348/selenium-chrome-driver-headless-mode-not-working | My code worked perfectly until yesterday when I updated Google Chrome to version 110.0.5481.77. Now it's not working in headless mode: options.add_argument("--headless") I even tried adding options.add_argument("--window-size=1280,700") but still not working. Although if I remove the headless option it again works cor... | Accroding to this answer and Google Chrome release notes you should add the headless mode option like below: options.add_argument("--headless=new") and no need to specify the window size | 6 | 19 |
75,387,685 | 2023-2-8 | https://stackoverflow.com/questions/75387685/files-not-being-included-by-hatchling-when-specified-in-pyproject-toml | I am trying to package my tool with Hatch and want to include some extra files found in /docs in the below directory tree: this_project │ .gitattributes │ .gitignore │ LICENSE │ MANIFEST.in │ pyproject.toml │ README.md │ ├───docs │ default.primers │ └───ribdif __init__.py __main__.py I am installing the tool with pip ... | When installing from github using pip I believe I am populating my site-packages with the content of the produced wheel and given that I need the extra files at run time I need to add to the wheel and not the source distribution. [tool.hatch.build.targets.wheel.force-include] "ribdif" = "ribdif" "docs/default.primers" ... | 4 | 1 |
75,393,757 | 2023-2-9 | https://stackoverflow.com/questions/75393757/how-to-escape-dot-in-a-key-to-get-json-value-with-redis-py | I had some JSON data containing dot(.) in keys that are written to redis using redis-py like this: r = redis.Redis() r.json().set(_id, "$", {'First.Last': "John.Smith"}) It works if reading the whole JSON data like r.json().get(_id) but error throws if directly getting the value with a path containing the dot: r.json... | RedisJSON path supports both dot and bracket notation https://redis.io/docs/stack/json/path/, so you could use this r.json().get(_id, '["First.Last"]') | 4 | 4 |
75,388,906 | 2023-2-8 | https://stackoverflow.com/questions/75388906/how-to-rotate-and-translate-an-image-with-opencv-without-losing-off-screen-data | I'm trying to use opencv to perform subsequent image transformations. I have an image that I want to both rotate and translate while keeping the overall image size constant. I've been using the warpAffine function with rotation and translation matrixes to perform the transformations, but the problem is that after perfo... | Chaining the rotation and translation transformations is what you are looking for. Instead of applying the rotation and translation one after the other, we may apply cv2.warpAffine with the equivalent chained transformation matrix. Using cv2.warpAffine only once, prevents the corner cutting that resulted by the interme... | 3 | 6 |
75,387,904 | 2023-2-8 | https://stackoverflow.com/questions/75387904/how-to-exclude-tests-folder-from-the-wheel-of-a-pyproject-toml-managed-lib | I try my best to move from a setup.py managed lib to a pure pyproject.toml one. I have the following folder structure: tests └── <files> docs └── <files> sepal_ui └── <files> pyproject.toml and in my pyproject.toml the following setup for file and packages discovery: [build-system] requires = ["setuptools>=61.2", "whe... | Fun fact, it was working from the start.... Small debugging workflow for the next person that does not want to spend hours for nothing. configuration of the pyproject.toml the following configuration is the minimal to remove files from a docs/ and tests/ folders that are at the root of the repository. If you disseminat... | 18 | 17 |
75,389,166 | 2023-2-8 | https://stackoverflow.com/questions/75389166/how-to-match-an-empty-dictionary | Python supports Structural Pattern Matching since version 3.10. I came to notice that matching an empty dict doesn't work by simply matching {} as it does for lists. According to my naive approach, non-empty dicts are also matched (Python 3.10.4): def match_empty(m): match m: case []: print("empty list") case {}: print... | Using a mapping (dict) as the match pattern works a bit differently than using a sequence (list). You can match the dict's structure by key-value pairs where the key is a literal and the value can be a capture pattern so it is used in the case. You can use **rest within a mapping pattern to capture additional keys in t... | 4 | 1 |
75,382,397 | 2023-2-8 | https://stackoverflow.com/questions/75382397/python-write-bytes-to-file-using-redirect-of-print | using perl, $ perl -e 'print "\xca"' > out now $ xxd out we have 00000000: ca But with Python, I tried $ python3 -c 'print("\xca", end="")' > out $ xxd out what I got is 00000000: c38a I'm not sure what is going on. | So in Python, a str object is a series of unicode code points. How this is printed to the screen depends on the encoding of your sys.stdout. This is picked based on your locale (or possibly various environment variables can affect this, but by default, it is your locale). So yours must be set to UTF-8. That's my defaul... | 5 | 3 |
75,366,567 | 2023-2-6 | https://stackoverflow.com/questions/75366567/how-do-i-use-a-custom-pip-conf-in-a-docker-image | How can I configure a Docker container to use a custom pip.conf file? This does not (seem to) work for me: from python:3.9 COPY pip.conf ~/.config/pip/pip.conf where pip.conf is a copy of the pip configuration that points to a proprietary package repository. | The problem is the ~ expansion. This is a shell feature, and it's not working in a Dockerfile. Just define like this, using the dest path explicitly: from python:3.9 COPY pip.conf /root/.config/pip/pip.conf If you want to use something other than /root/.config then consider to add a WORKDIR instruction and specify pat... | 6 | 7 |
75,310,143 | 2023-2-1 | https://stackoverflow.com/questions/75310143/polars-adding-days-to-a-date | I am using Polars in Python to try and add thirty days to a date I run the code, get no errors but also get no new dates Can anyone see my mistake? import polars as pl df = pl.DataFrame( {"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"]}) df = df.with_columns( pl.col("start_date").str.to_date() ) # Generate the... | You're supposed to call .alias on the entire operation pl.col('start_date') + pl.duration(days=30). Instead you're only alias-ing on pl.duration(days=30). So the correct way would be: import polars as pl df = pl.DataFrame({"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"]}) df = df.with_columns(pl.col("start_dat... | 3 | 4 |
75,313,457 | 2023-2-1 | https://stackoverflow.com/questions/75313457/openai-api-openai-api-key-os-getenv-not-working | I am just trying some simple functions in Python with OpenAI APIs but running into an error: I have a valid API secret key which I am using. Code: >>> import os >>> import openai >>> openai.api_key = os.getenv("I have placed the key here") >>> response = openai.Completion.create(model="text-davinci-003", prompt="Say th... | Option 1: OpenAI API key not set as an environment variable Change this... openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx') ...to this. openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx' Option 2: OpenAI API key set as an environment variable (recommended) There are two ways to set the OpenAI API key as an environment va... | 3 | 15 |
75,378,025 | 2023-2-7 | https://stackoverflow.com/questions/75378025/how-to-complete-a-self-join-in-python-polars-vs-pandas-sql | I am trying to use python polars over pandas sql for a large dataframe as I am running into memory errors. There are two where conditions that are utilized in this dataframe but can't get the syntax right. Here is what the data looks like: Key Field DateColumn 1234 Plumb 2020-02-01 1234 Plumb 2020-03-01 123... | Let's accomplish everything using Polars. import polars as pl df = ( pl.DataFrame(d) .with_columns( pl.col('DateColumn').str.to_date() ) ) ( df .join( df .with_columns(pl.col('DateColumn').alias('PreviousDate')) .rename({'Field': 'PreviousField'}), left_on=['Key', 'DateColumn'], right_on=['Key', pl.col('DateColumn').dt... | 3 | 4 |
75,352,810 | 2023-2-5 | https://stackoverflow.com/questions/75352810/how-to-web-scrap-economic-calendar-data-from-tradingview-and-load-into-dataframe | I want to load the Economic Calendar data from TradingView link and load into Dataframe ? Link: https://in.tradingview.com/economic-calendar/ Filter-1: Select Data for India and United States Filter-2: Data for This Week | Update: 2024-07-04: you have to specify 'Origin' as headers You can request this url: https://economic-calendar.tradingview.com/events import pandas as pd import requests url = 'https://economic-calendar.tradingview.com/events' today = pd.Timestamp.today().normalize() headers = { 'Origin': 'https://in.tradingview.com' ... | 4 | 13 |
75,372,275 | 2023-2-7 | https://stackoverflow.com/questions/75372275/importerror-cannot-import-name-gdal-array-from-osgeo | I create a fresh environment, install numpy, then install GDAL. GDAL imports successfully and I can open images using gdal.Open(, but I get the ImportError: cannot import name '_gdal_array' from 'osgeo' error when trying to use ReadAsRaster. pip list returns: GDAL 3.6.2 numpy 1.24.2 pip 23.0 setuptools 65.6.3 wheel 0.3... | Pip is most likely caching and reinstalling your bad version of GDAL over and over, even though you installed numpy. Here's what fixed it for me: pip3 install --no-cache-dir --force-reinstall 'GDAL[numpy]==3.6.2' Installing without --no-cache-dir causes pip to reuse the compiled wheel: % pip3 install --force-reinstall ... | 9 | 16 |
75,324,341 | 2023-2-2 | https://stackoverflow.com/questions/75324341/yolov8-get-predicted-bounding-box | I want to integrate OpenCV with YOLOv8 from ultralytics, so I want to obtain the bounding box coordinates from the model prediction. How do I do this? from ultralytics import YOLO import cv2 model = YOLO('yolov8n.pt') cap = cv2.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) while True: _, frame = cap.read() img = cv2.... | This will: Loop through each frame in the video Pass each frame to Yolov8 which will generate bounding boxes Draw the bounding boxes on the frame using the built in ultralytics' annotator: from ultralytics import YOLO import cv2 from ultralytics.utils.plotting import Annotator # ultralytics.yolo.utils.plotting is de... | 14 | 29 |
75,312,537 | 2023-2-1 | https://stackoverflow.com/questions/75312537/sqlalchemy-is-biginteger-identity-column-possible-in-orm | I want to create BigInteger Identity column in SQLAlchemy ORM. Documentation does not have any example of either ORM Identity or BigInteger Identity. Is this possible at all? I don't see any parameter for Identity type that would allow specifying inner integer type How to do this? Do I have to create custom type and p... | This seems to work: import sqlalchemy as sa from sqlalchemy.orm import mapped_column, Mapped, DeclarativeBase class Base(DeclarativeBase): pass class Test(Base): __tablename__ = 't75312537' id: Mapped[int] = mapped_column( sa.BigInteger, sa.Identity(), primary_key=True ) engine = sa.create_engine('postgresql+psycopg2:/... | 6 | 11 |
75,367,828 | 2023-2-7 | https://stackoverflow.com/questions/75367828/runtimeerror-reentrant-call-inside-io-bufferedwriter-name-stdout | I'm writing a program which starts one thread to generate "work" and add it to a queue every N seconds. Then, I have a thread pool which processes items in the queue. The program below works perfectly fine, until I comment out/delete line #97 (time.sleep(0.5) in the main function). Once I do that, it generates a Runtim... | It's because you called the print() in the signal handler, stop_app(). A signal handler is executed in a background thread in C, but in Python it is executed in the main thread. (See the reference.) In your case, while executing a print() call, another print() was called, and the term 'reentrant' fits perfectly here. A... | 3 | 5 |
75,314,250 | 2023-2-1 | https://stackoverflow.com/questions/75314250/python-weakkeydictionary-for-unhashable-types | As raised in cpython issue 88306, python WeakKeyDictionary fails for non hashable types. According to the discussion in the python issue above, this is an unnecessary restriction, using ids of the keys instead of hash would work just fine: In this special case ids are unique identifiers for the keys in the WeakKeyDicti... | There is a way which does not rely on knowing the internals of WeakKeyDictionary: from weakref import WeakKeyDictionary, WeakValueDictionary class Id: def __init__(self, key): self._id = id(key) def __hash__(self): return self._id def __eq__(self, other): return self._id == other._id class WeakUnhashableKeyDictionary: ... | 7 | 3 |
75,305,169 | 2023-2-1 | https://stackoverflow.com/questions/75305169/decoding-hidden-layer-embeddings-in-t5 | I'm new to NLP (pardon the very noob question!), and am looking for a way to perform vector operations on sentence embeddings (e.g., randomization in embedding-space in a uniform ball around a given sentence) and then decode them. I'm currently attempting to use the following strategy with T5 and Huggingface Transforme... | Much easier than anticipated! For anyone else looking for an answer, this page in HuggingFace's docs wound up helping me the most. Below is an example with code based heavily on that page. First, to get the hidden layer embeddings: encoder_input_ids = self.tokenizer(encoder_input_str, return_tensors="pt").input_ids em... | 4 | 1 |
75,353,488 | 2023-2-5 | https://stackoverflow.com/questions/75353488/modulenotfounderror-no-module-named-numpy-but-numpy-module-already-installed | Error: I have already installed numpy module(pip show numpy): this how it shows when i try to install numpy again I tried to import numpy module which is already installed but it throws ModuleNotFoundError | if you are using vs code you need to select the Python interpreter explicitly: press ctrl+shift+p to open the editor command then Search Python: Select Interpreter then you can choose the appropriate Python interpreter | 4 | 1 |
75,316,998 | 2023-2-1 | https://stackoverflow.com/questions/75316998/disable-logging-bad-requests-while-unittest-django-app | I have a tests in my Django app. They're working well, but i want to disable showing console logging like .Bad Request: /api/v1/users/register/ One of my tests code def test_user_register_username_error(self): data = { 'username': 'us', 'email': 'mail@mail.mail', 'password': 'pass123123', 'password_again': 'pass123123... | You can log only errors during the tests, and after they complete, return the normal logging level. class SampleTestCase(TestCase): def setUp(self) -> None: """Reduce the log level to avoid messages like 'bad request'""" logger = logging.getLogger("django.request") self.previous_level = logger.getEffectiveLevel() logge... | 3 | 2 |
75,323,732 | 2023-2-2 | https://stackoverflow.com/questions/75323732/how-to-download-streamlit-output-data-frame-as-excel-file | I want to know if there is any way to download the output dataframe of streamlit as an Excel file using the streamlit button? | I suggest you edit your question to include a minimal reproducible example so that it's easier for people to understand your question and to help you. Here is the answer if I understand you correctly. Basically it provides 2 ways to download your data df as either csv or xlsx. IMPORTANT: You need to install xlsxwriter ... | 4 | 8 |
75,306,422 | 2023-2-1 | https://stackoverflow.com/questions/75306422/how-to-solve-python-c-api-error-this-is-an-issue-with-the-package-mentioned-abo | I'm trying to implement an algorithm in the form of the C programming language into my system that runs using the python programming language. I'm trying to implement the Python C API with the intention that my algorithm will run in a python environment. As a result it produces an error which I have been trying to fix ... | According to [Python.Docs]: Extending Python with C or C++ - The Module’s Method Table and Initialization Function (emphasis is mine): This structure, in turn, must be passed to the interpreter in the module’s initialization function. The initialization function must be named PyInit_name(), where name is the name of t... | 3 | 3 |
75,310,294 | 2023-2-1 | https://stackoverflow.com/questions/75310294/github-actions-poetry-installs-black-but-ci-workflow-does-not-find-it | I am setting up a python code quality workflow locally (pre-commit) and on Github Actions (GHA). Environment is managed with poetry. While the local precommit works fine, the remote GHA workflow fails, saying it does not find black, while looking at the workflow logs it seems it was installed just fine. Workflow was la... | Since the dependencies are installed in a virtual environment managed by Poetry, you need to use Poetry to run Black: - name: Format with black run: poetry run black ./src | 3 | 5 |
75,349,025 | 2023-2-4 | https://stackoverflow.com/questions/75349025/vs-code-jupyter-notebook-iprogress-not-found | I'm attempting to run a very simple tqdm script: from tqdm.notebook import tqdm for i in tqdm(range(10)): time.sleep(1) but am met with: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html My ipywidgets is v8.0.4 and jupyter v1.0.0... does tqdm ... | I had the same problem. Using this post I resolved it by running: %pip install --upgrade jupyter ipywidgets %jupyter nbextension enable --py widgetsnbextension # removed !pip on the recommendation of a comment. import time from tqdm.notebook import tqdm for i in tqdm(range(10)): time.sleep(0.1) | 6 | 7 |
75,364,863 | 2023-2-6 | https://stackoverflow.com/questions/75364863/folders-included-in-the-tar-gz-not-in-the-wheel-setuptools-build | The automatic discovery of setuptools.build_meta includes top-level folders into the tarball that shouldn't be included. We were trying to build a python package with python3 -m build. Our project has a src-layout and we are using setuptools as the backend for the build. According to the documentation, the automatic di... | Full answer: https://github.com/pypa/setuptools/issues/3883#issuecomment-1494308302 Summary: These files are included by default in the sdist. The set of files included in a wheel is smaller. Thus, the behavior described above is expected. If you want to exclude e.g. the tests and the docs folder from the sdist, add t... | 7 | 4 |
75,363,018 | 2023-2-6 | https://stackoverflow.com/questions/75363018/how-to-resolve-typeerror-init-missing-1-required-positional-argument-up | I want to create a Telegram bot that checks for a new post on a website (currently every 15s for testing purposes). If so, it should send a message with content from the post into the Telegram channel. For this I already have the following "code skeleton": (The fine work in terms of formatting and additions comes later... | You probably have the wrong telegram version. I am a bit old fashion, but for me version 13 still works great. So simply replace your library version by running: pip install python-telegram-bot==13.13 | 6 | 3 |
75,365,431 | 2023-2-6 | https://stackoverflow.com/questions/75365431/mediapipe-display-body-landmarks-only | I have installed Mediapipe (0.9.0.1) using Python (3.7.0) on windows 11. I have been able to successfully get Mediapipe to generate landmarks (for face and body); for an image, video, and webcam stream. I would like to now get Mediapipe to only draw body specific landmarks (i.e. exclude facial landmarks). I understand ... | You can try the following approach: import cv2 import mediapipe as mp import numpy as np from mediapipe.python.solutions.pose import PoseLandmark from mediapipe.python.solutions.drawing_utils import DrawingSpec mp_drawing = mp.solutions.drawing_utils mp_drawing_styles = mp.solutions.drawing_styles mp_pose = mp.solution... | 3 | 7 |
75,330,032 | 2023-2-2 | https://stackoverflow.com/questions/75330032/unable-to-start-jupyter-notebook-kernel-in-vs-code | I am trying to run a Jupyter Notebook in VS Code. However, I'm getting the following error message whenever I try to execute a cell: Failed to start the Kernel. Jupyter server crashed. Unable to connect. Error code from Jupyter: 1 usage: jupyter.py [-h] [--version] [--config-dir] [--data-dir] [--runtime-dir] [--paths] ... | This sounds like it might be a bug that found in the 2023.1 version of the Jupyter extension that affects MacOS users: Starting a Jupyter server kernel fails (when zmq does not work) #12714 (duplicates: Failed to start the Kernel, version v2023.1.2000312134 #12726, Jupyter server crashed. Unable to connect. #12746) The... | 6 | 12 |
75,312,569 | 2023-2-1 | https://stackoverflow.com/questions/75312569/error-backend-subprocess-exited-when-trying-to-invoke-get-requires-for-build-sdi | I was creating a Python library, I needed to compile the pyproject.toml file. I runned this command: pip-compile pyproject.toml --resolver=backtracking I got: Backend subprocess exited when trying to invoke get_requires_for_build_wheel Failed to parse .\pyproject.toml My pyproject.toml: [build-system] requires = ["setu... | Try adding [tools.setuptools] packages = ["src"] to your pyproject.toml See the following page for details, major thanks to Keith R. Petersen on this one :) | 7 | 4 |
75,326,238 | 2023-2-2 | https://stackoverflow.com/questions/75326238/how-to-omit-dependency-when-exporting-requirements-txt-using-poetry | I have a Python3 Poetry project with a pyproject.toml file specifying the dependencies: [tool.poetry.dependencies] python = "^3.10" nltk = "^3.7" numpy = "^1.23.4" scipy = "^1.9.3" scikit-learn = "^1.1.3" joblib = "^1.2.0" [tool.poetry.dev-dependencies] pytest = "^5.2" I export those dependencies to a requirements.txt... | The colorama dependency is required by pytest. I suppose your Docker image is for production use, so it doesn't have to contain pytest which is clearly a development dependency. You can use poetry export --without-hashes --without dev -f requirements.txt -o requirements.txt to prevent your dev packages to be exported t... | 11 | 6 |
75,380,003 | 2023-2-7 | https://stackoverflow.com/questions/75380003/clean-setup-of-pip-tools-doesnt-compile-very-basic-pyproject-toml | Using a completely new pip-tools setup always results in a Backend subprocess exited error. pyproject.toml: [project] dependencies = [ 'openpyxl >= 3.0.9, < 4', ] Running pip-tools in an empty directory that only contains the above pyproject.toml: % python -m venv .venv % source .venv/bin/activate % python -m pip inst... | Your pyproject.toml most likely is invalid, try pip install -e . and you'll see a detailed explanation. For now, pip-tools can't show a nice error message, but work is in progress. | 5 | 12 |
75,376,359 | 2023-2-7 | https://stackoverflow.com/questions/75376359/how-to-use-my-own-python-packages-modules-with-pyscript | Question I came across pyscript hoping to use it to document python code with mkdocs. I have looked into importing my own module. Individual files work. How do I import my own module using pyscript instead? Requirements for running the example: python package numpy ($ pip install numpy) python package matplotlib ($ p... | The folder structure you want to achieve wasn't possible in PyScipt Alpha - <py-env>'s paths functionality was fairly limited. Thankfully, it is possible in PyScript 2022.12.1, the latest version at time of writing. First, you'll want want to point your <script> and <link> tags at the newest release: <script defer src=... | 7 | 6 |
75,333,570 | 2023-2-3 | https://stackoverflow.com/questions/75333570/generate-unique-id-code-in-faker-data-set | im trying to create a data set with a unique id code but i get a 'ValueError not enough values to unpack (expected 6, got 5)' on line 8, basically, I am trying to: generate a unique 6 digit id code append dataset value with 'ID' ex: ID123456 UPDATE: fixed the error and ID append, now how do i make sure the generate... | To answer the question: now how do I make sure the generated id is unique in the dataset? You have to use: unique.random_int So, your code will be like this as you see below: from faker import Faker import random import pandas as pd Faker.seed(0) random.seed(0) fake = Faker("en_US") fixed_digits = 6 concatid = 'ID' i... | 3 | 5 |
75,313,204 | 2023-2-1 | https://stackoverflow.com/questions/75313204/correct-way-to-append-to-string-in-python | I've read this reply which explains that CPython has an optimization to do an in-place append without copy when appending to a string using a = a + b or a += b. I've also read this PEP8 recommendation: Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython,... | In "loop3" you bypass a lot of the gain of join() by continuously calling it in an unneeded way. It would be better to build up the full list of characters then join() once. Check out: import time iterations = 100_000 ##---------------- s = "" start_time = time.time() for i in range(iterations): s = s + "." + '3' end_t... | 3 | 7 |
75,324,072 | 2023-2-2 | https://stackoverflow.com/questions/75324072/pandas-json-orient-autodetection | I'm trying to find out if Pandas.read_json performs some level of autodetection. For example, I have the following data: data_records = [ { "device": "rtr1", "dc": "London", "vendor": "Cisco", }, { "device": "rtr2", "dc": "London", "vendor": "Cisco", }, { "device": "rtr3", "dc": "London", "vendor": "Cisco", }, ] data_i... | TL;DR When using pd.read_json() with orient=None, the representation of the data is automatically determined through pd.DataFrame(). Explanation The pandas documentation is a bit misleading here. When not specifying orient, the parser for 'columns' is used, which is self.obj = pd.DataFrame(json.loads(json)). So pd.read... | 6 | 2 |
75,334,838 | 2023-2-3 | https://stackoverflow.com/questions/75334838/is-there-any-downside-in-using-multiple-n-jobs-1-statements | In the context of model selection for a classification problem, while running cross validation, is it ok to specify n_jobs=-1 both in model specification and cross validation function in order to take full advantage of the power of the machine? For example, comparing sklearn RandomForestClassifier and xgboost XGBClassi... | Specifying n_jobs twice does have an effect, though whether it has a positive or negative effect is complicated. When you specify n_jobs twice, you get two levels of parallelism. Imagine you have N cores. The cross-validation function creates N copies of your model. Each model creates N threads to run fitting and predi... | 3 | 4 |
75,349,276 | 2023-2-5 | https://stackoverflow.com/questions/75349276/python-pandas-vectorized-way-of-cleaning-buy-and-sell-signals | I'm trying to simulate financial trades using a vectorized approach in python. Part of this includes removing duplicate signals. To elaborate, I've developed a buy_signal column and a sell_signal column. These columns contain booleans in the form of 1s and 0s. Looking at the signals from the top-down, I don't want to t... | As I said earlier (in a comment about a response since then deleted), one must consider the interaction between buy and sell signals, and cannot simply operate on each independently. The key idea is to consider a quantity q (or "position") that is the amount currently held, and that the OP says would like bounded to [0... | 3 | 3 |
75,333,571 | 2023-2-3 | https://stackoverflow.com/questions/75333571/get-aerospike-hyperlogloghll-intersection-count-of-multiple-hll-unions | I have 2 or more HLLs that are unioned, I want to get the intersection count of that unions. I have used the example from here hll-python example Following is my code ops = [hll_ops.hll_get_union(HLL_BIN, records)] _, _, result1 = client.operate(getKey(value), ops) ops = [hll_ops.hll_get_union(HLL_BIN, records2)] _, _,... | Was able to figure out the solutions (with the help of Aerospike support, the same question was posted here and discussed more elaboratively aerospike forum). Posting my code for others having the same issue. Intersection of HLLs is not supported in Aerospike. However, If I am to get intersection of multiple HLLs I wil... | 3 | 2 |
75,372,032 | 2023-2-7 | https://stackoverflow.com/questions/75372032/in-python-what-is-the-difference-between-async-for-x-in-async-iterator-and-f | The subject contains the whole idea. I came accross code sample where it shows something like: async for item in getItems(): await item.process() And others where the code is: for item in await getItems(): await item.process() Is there a notable difference in these two approaches? | TL;DR While both of them could theoretically work with the same object (without causing an error), they most likely do not. In general those two notations are not equivalent at all, but invoke entirely different protocols and are applied to very distinct use cases. Different protocols Iterable To understand the differ... | 7 | 6 |
75,354,384 | 2023-2-5 | https://stackoverflow.com/questions/75354384/why-is-b-pop0-over-200-times-slower-than-del-b0-for-bytearray | Letting them compete three times (a million pops/dels each time): from timeit import timeit for _ in range(3): t1 = timeit('b.pop(0)', 'b = bytearray(1000000)') t2 = timeit('del b[0]', 'b = bytearray(1000000)') print(t1 / t2) Time ratios (Try it online!): 274.6037053753368 219.38099365582403 252.08691226683823 Why is... | When you run b.pop(0), Python moves all the elements back by one as you might expect. This takes O(n) time. When you del b[0], Python simply increases the start pointer of the object by 1. In both cases, PyByteArray_Resize is called to adjust the size. When the new size is smaller than half the allocated size, the allo... | 57 | 82 |
75,379,958 | 2023-2-7 | https://stackoverflow.com/questions/75379958/error-int-object-is-not-subscriptable-when-using-lambda-in-reduce-function | When running the following code, I get the following Error: Traceback (most recent call last): File "/Users/crosseyedbum/Documents/Visual Studio Code/Fundamentals of Python_5.py", line 127, in <module> sumo = reduce(lambda a, b : a[1] + b[1], exp) File "/Users/crosseyedbum/Documents/Visual Studio Code/Fundamentals of P... | The issue is that the a parameter to your lambda function is not what you think it is. From the functools.reduce docs: The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable In your case, x is a and y is b due to how you named your parameters. So, a is not a tu... | 3 | 2 |
75,379,184 | 2023-2-7 | https://stackoverflow.com/questions/75379184/plotly-range-slider-without-showing-line-in-small | I want to use Plotly to generate a line chart with a range slider. the range slider shows the displayed line again. this code is just an example. in my case, I have a lot of subplots and everything is shown twice. is it possible to show nothing or only the date in the range slider? import plotly.express as px import yf... | Looking through the rangeslider documentation, there aren't any arguments that can directly impact the rangeslider line because I believe that line will have all of the same properties as the line in the figure (including color, visibility, thickness). The best workaround I can come up with is to change the background ... | 4 | 3 |
75,378,987 | 2023-2-7 | https://stackoverflow.com/questions/75378987/unable-to-install-cx-oracle-with-pip | I am currently using the latest version of Python and attempting to install cx_Oracle through the command pip install cx_Oracle. On my first attempt, I encountered an error that stated: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools". To address this, I installed both Microsof... | Nice effort. Unfortunately, pre-compiled binaries for Python 3.11 are not currently available. To utilize this version, you can either wait for their release or configure your system properly to build them from source. Alternatively, you could consider downgrading to a previous version of Python, although this is not r... | 4 | 4 |
75,378,406 | 2023-2-7 | https://stackoverflow.com/questions/75378406/how-to-repeat-the-inner-row-of-a-3d-matrixnxmxv-to-get-a-new-matrixnx2mxv-us | Here is an example of what I want: original matrix: [[[5 1 4]] [[0 9 5]] [[8 0 9]]] matrix I want: [[[5 1 4] [5 1 4]] [[0 9 5] [0 9 5]] [[8 0 9] [8 0 9]]] I have tried np.repeat(A, 2, axis=0), which apparently does not work since it gives the output: [[[5 1 4]] [[5 1 4]] [[0 9 5]] [[0 9 5]] [[8 0 9]]] | You want to repeat on axis=1: np.repeat(A, 2, axis=1) Output: array([[[5, 1, 4], [5, 1, 4]], [[0, 9, 5], [0, 9, 5]], [[8, 0, 9], [8, 0, 9]]]) NB. remember to check the shape of your arrays: A.shape -> (3, 1, 3). You want to make it (3, 2, 3), not (6, 1, 3). | 3 | 5 |
75,370,436 | 2023-2-7 | https://stackoverflow.com/questions/75370436/keras-categoryencoding-layer-with-time-sequences | For a LSTM, I create time sequences by means of tensorflow.keras.utils.timeseries_dataset_from_array(). For some of the features, I would like to do one-hot encoding by means of Keras preprocessing layers. I have the following code: n_timesteps = 20 n_categorical_features = 1 from tensorflow.keras.layers import Input, ... | Please try to use TimeDistributed layer: encoder = tf.keras.layers.TimeDistributed(CategoryEncoding(num_tokens=index.vocabulary_size(), output_mode = "one_hot"))(cat_inp) It will apply CategoryEncoding to each item in your time sequence. Please see https://keras.io/api/layers/recurrent_layers/time_distributed/ for mor... | 3 | 4 |
75,373,164 | 2023-2-7 | https://stackoverflow.com/questions/75373164/is-there-something-like-python-setup-py-version-for-pyproject-toml | With a simple setup.py file: from setuptools import setup setup( name='foo', version='1.2.3', ) I can do $> python setup.py --version 1.2.3 without installing the package. Is there similar functionality for the equivalent pyproject.toml file: [project] name = "foo" version = "1.2.3" | With Python 3.11+, something like this should work: python3.11 -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])" This parses the TOML file directly, and assumes that version is not dynamic. In some cases, version is declared dynamic in pyproject.toml, so it can not be parsed... | 6 | 3 |
75,370,815 | 2023-2-7 | https://stackoverflow.com/questions/75370815/pylint-specifying-exception-names-in-the-overgeneral-exceptions-option-without | pylint: Command line or configuration file:1: UserWarning: Specifying exception names in the overgeneral-exceptions option without module name is deprecated and support for it will be removed in pylint 3.0. Use fully qualified name (maybe 'builtins.BaseException' ?) instead. Getting PyLint error. I dont have any Exce... | This is just a warning for future pylint releases, you can ignore it. If you want to address it now you will need to open your .pylintrc configuration file (should be located at ~/.pylintrc) and replace: overgeneral-exceptions=BaseException, Exception with: overgeneral-exceptions=builtins.BaseException, builtins.Excep... | 26 | 50 |
75,365,839 | 2023-2-6 | https://stackoverflow.com/questions/75365839/mypy-with-dictionarys-get-function | I have some code that looks like this: di: dict[str, float] max_val = max(di, key=di.get) When running mypy on it, it complains error: Argument "key" to "max" has incompatible type overloaded function; expected "Callable[[str], Union[SupportsDunderLT[Any], SupportsDunderGT[Any]]]" My guess is that this is because the... | The dunder (double underscore) member function __getitem__ of a dict object is what you want here: max(di, key=di.__getitem__) raises no complains from mypy. The reason your lambda works is because it precisely emulates the intent of __getitem__, which is to implement evaluation of self[key], as explained in the docum... | 4 | 3 |
75,342,160 | 2023-2-4 | https://stackoverflow.com/questions/75342160/partition-of-a-list-of-integers-into-k-sublists-with-equal-sum | Similar questions are 1 and 2 but the answers didn't help. Assume we have a list of integers. We want to find K disjoint lists such that they completely cover the given list and all have the same sum. For example, if A = [4, 3, 5, 6, 4, 3, 1] and K = 2 then the answer should be: [[3, 4, 6], [1, 3, 4, 5]] or [[4, 4, 5],... | Here is a solution that deals with duplicates. First of all the problem of finding any solution is, as noted, NP-complete. So there are cases where this will churn for a long time to realize that there are none. I've applied reasonable heuristics to limit how often this happens. The heuristics can be improved. But be w... | 6 | 4 |
75,363,733 | 2023-2-6 | https://stackoverflow.com/questions/75363733/sqlalchemy-2-0-orm-model-datetime-insertion | I am having some real trouble getting a created_date column working with SQLAlchemy 2.0 with the ORM model. The best answer so far I've found is at this comment: https://stackoverflow.com/a/33532154 however I haven't been able to make that function work. In my (simplified) models.py file I have: import datetime from sq... | Posting an answer to my own question to note what actually did work (actual problem still exists, but a simplified variation does work just dandy the way I expect it to.) import datetime from sqlalchemy import Integer, String, DateTime from sqlalchemy import create_engine from sqlalchemy.sql import func from sqlalchemy... | 17 | 10 |
75,357,653 | 2023-2-6 | https://stackoverflow.com/questions/75357653/how-to-resume-a-pytorch-training-of-a-deep-learning-model-while-training-stopped | Actually i am training a deep learning model and want to save checkpoint of the model but its stopped when power is off then i have to start from that point from which its interrupted like 10 epoches completed and want to resume/start again from epoch 11 with that parameters | In PyTorch, you can resume from a specific point by using epoch key from the checkpoint dictionary as follows: # Load model checkpoint checkpoint = torch.load("checkpoint.pth") model.load_state_dict(checkpoint['model']) epoch = checkpoint['epoch'] # Resume training from a specific epoch for epoch in range(epoch + 1, nu... | 5 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.