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 |
|---|---|---|---|---|---|---|
70,664,467 | 2022-1-11 | https://stackoverflow.com/questions/70664467/invalid-python-sdk-in-pycharm | Since this morning, I'm no longer able to run projects in PyCharm. When generating a new virtual environment, I get an "Invalid Python SDK" error. Cannot set up a python SDK at Python 3.11... The SDK seems invalid. What I noticed: No matter what base interpreter I select (3.8, 3.9, 3.10) Pycharm always generates a Pyth... | Dealt with the same issue despite using python and pycharm without issue for months. Recently kept giving me the error despite changing the PATH variable of my system and even manually pathing within pycharm. After hours of reinstalling pycharm, python and even jumping around versions with no success it turned out it w... | 23 | 7 |
70,658,151 | 2022-1-10 | https://stackoverflow.com/questions/70658151/how-to-log-production-database-changes-made-via-the-django-shell | I would like to automatically generate some sort of log of all the database changes that are made via the Django shell in the production environment. We use schema and data migration scripts to alter the production database and they are version controlled. Therefore if we introduce a bug, it's easy to track it back. Bu... | This solution logs all commands in the session if any database changes were made. How to detect database changes Wrap execute_sql of SQLInsertCompiler, SQLUpdateCompiler and SQLDeleteCompiler. SQLDeleteCompiler.execute_sql returns a cursor wrapper. from django.db.models.sql.compiler import SQLInsertCompiler, SQLUpdateC... | 9 | 6 |
70,608,619 | 2022-1-6 | https://stackoverflow.com/questions/70608619/how-to-get-message-from-logging-function | I have a logger function from logging package that after I call it, I can send the message through logging level. I would like to send this message also to another function, which is a Telegram function called SendTelegramMsg(). How can I get the message after I call the funcion setup_logger send a message through logg... | Implement a custom logging.Handler: class TelegramHandler(logging.Handler): def emit(self, record): message = self.format(record) SendTelegramMsg(message) # SendTelegramMsg(message, record.levelno) # Passing level # SendTelegramMsg(message, record.levelname) # Passing level name Add the handler: def setup_logger(teleg... | 7 | 9 |
70,603,855 | 2022-1-6 | https://stackoverflow.com/questions/70603855/how-to-set-python-function-as-callback-for-c-using-pybind11 | typedef bool (*ftype_callback)(ClientInterface* client, const Member* member ,int member_num); struct Member{ char x[64]; int y; }; class ClientInterface { public: virtual int calc()=0; virtual bool join()=0; virtual bool set_callback(ftype_callback on_member_join)=0; }; It is from SDK which I can call the client from... | You need a little C++ to get things going. I'm going to use a simpler structure to make the answer more readable. In your binding code: #include <pybind11/pybind11.h> #include <functional> #include <string> namespace py = pybind11; struct Foo { int i; float f; std::string s; }; struct Bar { std::function<bool(const Foo... | 6 | 5 |
70,598,913 | 2022-1-5 | https://stackoverflow.com/questions/70598913/problem-resizing-plot-on-tkinter-figure-canvas | Python 3.9 on Mac running OS 11.6.1. My application involves placing a plot on a frame inside my root window, and I'm struggling to get the plot to take up a larger portion of the window. I thought rcParams in matplotlib.pyplot would take care of this, but I must be overlooking something. Here's what I have so far: imp... | try something like this: fig.subplots_adjust(left=0.05, bottom=0.07, right=0.95, top=0.95, wspace=0, hspace=0) this is output, figure now takes more screen area % [ | 6 | 4 |
70,626,218 | 2022-1-7 | https://stackoverflow.com/questions/70626218/how-to-find-the-nearest-linestring-to-a-point | How do I fund the nearest LINESTRING near a point? First I have a list of LINESTRING and point value. How do I have the nearest LINESTRING to the POINT (5.41 3.9) and maybee the distance? from shapely.geometry import Point, LineString line_string = [LINESTRING (-1.15.12 9.9, -1.15.13 9.93), LINESTRING (-2.15.12 8.9, -2... | your sample geometry is invalid for line strings, have modified it's simple to achieve with sjoin_nearest() import geopandas as gpd import shapely.wkt import shapely.geometry line_string = ["LINESTRING (-1.15.12 9.9, -1.15.13 9.93)", "LINESTRING (-2.15.12 8.9, -2.15.13 8.93)"] # fix invalid wkt string... line_string ... | 9 | 4 |
70,651,053 | 2022-1-10 | https://stackoverflow.com/questions/70651053/how-can-i-send-dynamic-website-content-to-scrapy-with-the-html-content-generated | I am working on certain stock-related projects where I have had a task to scrape all data on a daily basis for the last 5 years. i.e from 2016 to date. I particularly thought of using selenium because I can use crawler and bot to scrape the data based on the date. So I used the use of button click with selenium and now... | The 2 solutions are not very different. Solution #2 fits better to your question, but choose whatever you prefer. Solution 1 - create a response with the html's body from the driver and scraping it right away (you can also pass it as an argument to a function): import scrapy from selenium import webdriver from selenium... | 7 | 3 |
70,673,065 | 2022-1-11 | https://stackoverflow.com/questions/70673065/where-is-conda-env-documented | I am wondering why the official documentation of conda does not mention anything about the command conda env? That makes me wonder if it would be possible to do every operation of conda env with the commands listed here and which one is recommended to use in practice. Right now I would assume that conda env creates an ... | The reason why the conda env commands are not similarly documented is historical. Namely, after conda was developed, others then developed an add-on package called conda-env that provided some convenience methods for operating on whole environments rather than package operations within environments. Eventually, the con... | 5 | 4 |
70,672,108 | 2022-1-11 | https://stackoverflow.com/questions/70672108/airflow-s3hook-read-files-in-s3-with-pandas-read-csv | I'm trying to read some files with pandas using the s3Hook to get the keys. I'm able to get the keys, however I'm not sure how to get pandas to find the files, when I run the below I get: No such file or directory: Here is my code: def transform_pages(company, **context): ds = context.get("execution_date").strftime('... | The format you are looking for is the following: filepath = f"s3://{bucket_name}/{key}" So in your specific case, something like: for file in keys: filepath = f"s3://s3_bucket/{file}" df = pd.read_csv(filepath, sep='\t', skiprows=1, header=None) Just make sure you have s3fs installed though (pip install s3fs). | 6 | 3 |
70,670,079 | 2022-1-11 | https://stackoverflow.com/questions/70670079/get-indexes-of-pandas-rolling-window | I would like to get the indexes of the elements in each rolling window of a Pandas Series. A solution that works for me is from this answer to an existing question: I get the window.index for each window obtained from the rolling function described in the answer. I am only interested in step=1 for the aforementioned fu... | The apply function after rolling must return a numeric value for each window. One possible workaround is to use a list comprehension to iterate over each window and apply the custom transformation as required: [[*l.index] for l in s.rolling(3) if len(l) == 3] Alternatively you can also use sliding_window_view to accom... | 6 | 5 |
70,658,955 | 2022-1-10 | https://stackoverflow.com/questions/70658955/how-do-i-display-bar-plot-for-values-that-are-zero-in-plotly | How do I make the bar appear when one of the value of y is zero? It just leaves a gap by default. Is there a way I can enable it to plot for zero values? I am able to see a line on the x-axis at y=0 for the same if just plotted using go.Box. I would like to see this in the Bar plot as well. So far, I set the base to ze... | Bar charts come with a line around the bars that by default are set to the same color as the background. In your case '#E5ECF6'. If you change that, the line will appear as a border around each bar that will remain visible even when y = 0 for any given x. fig.update_traces(marker_line_color = 'blue', marker_line_width ... | 6 | 6 |
70,648,325 | 2022-1-10 | https://stackoverflow.com/questions/70648325/saving-the-progress-of-a-python-script-through-reboot | I'd like to start by saying that I'm very new to Python, and I started this project for fun. Specifically, it’s simply a program which sends compliments to you as notifications periodically throughout the day. This is not for school, and I was actually just trying to make it for my girlfriend while introducing myself t... | You can simply save the count (which is the index of the last compliment line) as an integer in a pickle file, or easier in a text file and read from it every time your script starts after reboot. import datetime import time from plyer import notification Compliment = None compliment_index = 0 try: with open('C:/Users/... | 5 | 6 |
70,630,962 | 2022-1-8 | https://stackoverflow.com/questions/70630962/finding-2nd-order-relations-sqlalchemy-throws-please-use-the-select-from-m | I have a User model, a Contact model, and a Group model. I'm looking to find all of the 2nd-order User's Groups given a particular user in a single query. That is, I'd like to: Use all contacts of a particular user... ... to get all the users who are also a contact of the given user, and use that to... ... get all gro... | The problem here was two-fold. We've got to alias a table every time we use it (not just the 2nd time onward) and, when using with_entities, we've got to use all columns that we compare on—even if we don't intend on using their data in the end. My final code looked something like this: from sqlalchemy.orm import aliase... | 9 | 7 |
70,655,157 | 2022-1-10 | https://stackoverflow.com/questions/70655157/how-can-i-alias-a-pytest-fixture | I have a few pytest fixtures I use from third-party libraries and sometimes their names are overly long and cumbersome. Is there a way to create a short alias for them? For example: the django_assert_max_num_queries fixture from pytest-django. I would like to call this max_queries in my tests. | You cannot just add an alias in the form of max_queries = django_assert_max_num_queries because fixtures are looked up by name at run-time and not imported (and even if they can be imported in some cases, this is not recommended). But you can always write your own fixture that just yields another fixture: @pytest.fixt... | 6 | 5 |
70,656,932 | 2022-1-10 | https://stackoverflow.com/questions/70656932/how-to-test-python-file-with-pytest-having-if-name-main-with-argum | I want to test a python file with pytest which contains a if __name__ == '__main__': it also has arguments parsed in it. the code is something like this: if __name__ == '__main__': parser = argparse.ArgumentParser(description='Execute job.') parser.add_argument('--env', required=True, choices=['qa', 'staging', 'prod'])... | Command line arguments are an input/output mechanism like any other. The key is to isolate it in a "boundary layer", and have your main program not depend on them directly. In this case, rather than making your program access sys.argv directly (which is essentially a global variable), make it so your program is wrapped... | 5 | 4 |
70,656,586 | 2022-1-10 | https://stackoverflow.com/questions/70656586/how-to-clear-oled-display-in-micropython | I'm doing this on esp8266 with micro python and there is a way to clear OLED display in Arduino but I don't know how to clear display in micropython i used ssd1306 library to control my OLED and this is my error I've written a code that prints on OLED from a list loop, but OLED prints it on the text that was printed be... | The fill() method is used to clean the OLED screen: oled.fill(0) oled.show() | 5 | 9 |
70,654,589 | 2022-1-10 | https://stackoverflow.com/questions/70654589/python-poetry-and-script-entrypoints | Im trying to use Poetry and the scripts option to run a script. Like so: pyproject.toml [tool.poetry.scripts] xyz = "src.cli:main" Folder layout . ├── poetry.lock ├── pyproject.toml ├── run-book.txt └── src ├── __init__.py └── cli.py I then perform an install like so: ❯ poetry install Installing dependencies from lo... | Poetry is likely installing the script in your user local directory. On Ubuntu, for example, this is $HOME/.local/bin. If that directory isn't in your path, your shell will not find the script. A side note: It is generally a good idea to put a subdirectory with your package name in the src directory. It's generally bet... | 13 | 9 |
70,649,979 | 2022-1-10 | https://stackoverflow.com/questions/70649979/migrate-to-arm64-on-aws-lambda-show-error-unable-to-import-module-encryptor-la | I have a lambda function runs on Python 3.7 with architecture x86_64 before. Now I would like to migrate it to arm64 to use the Graviton processor and upgrade to Python 3.9 as well. While I success to create the Python 3.9 virtual environment layer with the dependencies that I need, which is aws-encryption-sdk, when I ... | Libraries like aws-encryption-sdk-python sometimes contain code/dependencies that are not pure Python and need to be compiled. When code needs to be "compiled" it is usually compiled for a target architecture (like ARM or x86) to run properly. You can not run code compiled for one architecture on different architectur... | 5 | 5 |
70,624,600 | 2022-1-7 | https://stackoverflow.com/questions/70624600/faiss-how-to-retrieve-vector-by-id-from-python | I have a faiss index and want to use some of the embeddings in my python script. Selection of Embeddings should be done by id. As faiss is written in C++, swig is used as an API. I guess the function I need is reconstruct : /** Reconstruct a stored vector (or an approximation if lossy coding) * * this function may not ... | This is the only way I found manually. import faiss import numpy as np a = np.random.uniform(size=30) a = a.reshape(-1,10).astype(np.float32) d = 10 index = faiss.index_factory(d,'Flat', faiss.METRIC_L2) index.add(a) xb = index.xb print(xb.at(0) == a[0][0]) Output: True You can get any vector with a loop required_vec... | 5 | 4 |
70,644,434 | 2022-1-9 | https://stackoverflow.com/questions/70644434/mypy-using-unions-in-mapping-types-does-not-work-as-expected | Consider the following code: def foo(a: dict[str | tuple[str, str], str]) -> None: pass def bar(b: dict[str, str]) -> None: foo(b) def baz(b: dict[tuple[str, str], str]) -> None: foo(b) foo({"foo": "bar"}) foo({("foo", "bar"): "bar"}) When checked with mypy in strict mode it produces the following errors: file.py:6: e... | A dict[str | tuple[str, str], str] isn't just a dict with either str or tuple[str, str] keys. It's a dict you can add more str or tuple[str, str] keys to. You can't add str keys to a dict[tuple[str, str], str], and you can't add tuple[str, str] keys to a dict[str, str], so those types aren't compatible. If you pass a l... | 6 | 4 |
70,643,142 | 2022-1-9 | https://stackoverflow.com/questions/70643142/repeat-values-of-an-array-on-both-the-axes | Say I have this array: array = np.array([[1,2,3],[4,5,6],[7,8,9]]) Returns: 123 456 789 How should I go about getting it to return something like this? 111222333 111222333 111222333 444555666 444555666 444555666 777888999 777888999 777888999 | You'd have to use np.repeat twice here. np.repeat(np.repeat(array, 3, axis=1), 3, axis=0) # [[1 1 1 2 2 2 3 3 3] # [1 1 1 2 2 2 3 3 3] # [1 1 1 2 2 2 3 3 3] # [4 4 4 5 5 5 6 6 6] # [4 4 4 5 5 5 6 6 6] # [4 4 4 5 5 5 6 6 6] # [7 7 7 8 8 8 9 9 9] # [7 7 7 8 8 8 9 9 9] # [7 7 7 8 8 8 9 9 9]] | 15 | 17 |
70,640,923 | 2022-1-9 | https://stackoverflow.com/questions/70640923/countvectorizer-object-has-no-attribute-get-feature-names-out | Why do i keep getting this error? I tried different versions of anaconda 3 but did not manage to get it done. What should i install to work it properly? I used sklearn versions from 0.20 - 0.23. Error message: Code: import pandas as pd import matplotlib.pyplot as plt import plotly.express as px from sklearn.feature_ex... | You are using an old version of scikit-learn. If I'm not mistaken, get_feature_names_out() was only introduced in version 1.0. Upgrade to a newer version, or, to get similar functionality in an earlier version, you can use get_feature_names(). | 12 | 34 |
70,639,443 | 2022-1-9 | https://stackoverflow.com/questions/70639443/convert-a-bytes-iterable-to-an-iterable-of-str-where-each-value-is-a-line | I have an iterable of bytes, such as bytes_iter = ( b'col_1,', b'c', b'ol_2\n1', b',"val', b'ue"\n', ) (but typically this would not be hard coded or available all at once, but supplied from a generator say) and I want to convert this to an iterable of str lines, where line breaks are unknown up front, but could be an... | Use the io module to do most of the work for you: class ReadableIterator(io.IOBase): def __init__(self, it): self.it = iter(it) def read(self, n): # ignore argument, nobody actually cares # note that it is *critical* that we suppress the `StopIteration` here return next(self.it, b'') def readable(self): return True th... | 8 | 6 |
70,636,801 | 2022-1-8 | https://stackoverflow.com/questions/70636801/map-unique-values-in-2-columns-to-integers | I have a dataframe with 2 categorical columns (col1, col2). col1 col2 0 A DE 1 A B 2 B BA 3 A A 4 C C I want to map the unique string values to integers, for example (A:0, B:1, BA:2, C:3, DE:4) col1 col2 ideal1 ideal2 0 A DE 0 4 1 A B 0 1 2 B BA 1 2 3 A A 0 0 4 C C 3 3 I am have tried to use factorize or category, ... | To get the same categories across columns you need to reshape to a single dimension first. Then use factorize and restore the original shape. Here is an example using stack/unstack: x = df.stack() x[:] = x.factorize()[0] df2 = x.unstack() Output: col1 col2 0 0 1 1 0 2 2 2 3 3 0 0 4 4 4 Joining to the original data: ... | 5 | 5 |
70,586,483 | 2022-1-5 | https://stackoverflow.com/questions/70586483/returning-array-from-recursive-binary-tree-search | Hi I've made a simple Binary Tree and added a pre-order traversal method. After throwing around some ideas I got stuck on finding a way to return each value from the traverse_pre() method in an array. class BST: def __init__(self, val): self.value = val self.left = None self.right = None def add_child(self, val): if se... | I would not recommend copying the entire tree to an intermediate list using .append or .extend. Instead use yield which makes your tree iterable and capable of working directly with many built-in Python functions - class BST: # ... def preorder(self): # value yield self.value # left if self.left: yield from self.left.p... | 6 | 0 |
70,602,290 | 2022-1-6 | https://stackoverflow.com/questions/70602290/google-app-engine-deployment-fails-error-while-finding-module-specification-for | We are using command prompt c:\gcloud app deploy app.yaml, but get the following error: Running "python3 -m pip install --requirement requirements.txt --upgrade --upgrade-strategy only-if-needed --no-warn-script-location --no-warn-conflicts --force-reinstall --no-compile (PIP_CACHE_DIR=/layers/google.python.pip/pipcach... | I had the same issue when deploying a Google Cloud Function. The error cloud function Error while finding module specification for 'pip' (AttributeError: module 'main' has no attribute 'file'); Error ID: c84b3231 appeared after commenting out some packages in the requirements.txt, but that was nothing important and l... | 18 | 1 |
70,632,673 | 2022-1-8 | https://stackoverflow.com/questions/70632673/fastapi-is-not-loading-static-files | So, I'm swapping my project from node.js to python FastAPI. Everything has been working fine with node, but here it says that my static files are not present, so here's the code: from fastapi import FastAPI, Request, WebSocket from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from f... | Here: app.mount("/static", StaticFiles(directory="../static"), name="static") You mount your static directory under /static path. That means, if you want access static files in your html you need to use static prefix, e.g. <img src="static/img/separator.png"/> | 6 | 4 |
70,631,807 | 2022-1-8 | https://stackoverflow.com/questions/70631807/python-pandas-pivot-of-two-columns-columnname-and-value | I have a Panda dataframe that contains two columns, as well as a default index. The first columns is the intended 'Column Name' and the second column the required value for that column. name returnattribute 0 Customer Name Customer One Name 1 Customer Code CGLOSPA 2 Customer Name Customer Two Name 3 Customer Code COTH... | You can also pass directly the new index to pivot_table, use aggfunc='first' as you have non numeric data: df.pivot_table(index=df.index//2, columns='name', values='returnattribute', aggfunc='first') output: name Customer Code Customer Name 0 CGLOSPA Customer One Name 1 COTHABA Customer Two Name 2 CGLOADS Customer Thr... | 5 | 2 |
70,630,932 | 2022-1-8 | https://stackoverflow.com/questions/70630932/how-to-use-tweepy-for-twitter-api-v2-in-getting-user-id-by-username | I'm trying to replicate this snippet from geeksforgeeks, except that it uses the oauth for Twitter API v1.1 while I the API v2. # the screen name of the user screen_name = "PracticeGfG" # fetching the user user = api.get_user(screen_name) # fetching the ID ID = user.id_str print("The ID of the user is : " + ID) OUTPUT:... | get_user have the following signature. Client.get_user(*, id, username, user_auth=False, expansions, tweet_fields, user_fields) Notice the *. * is used to force the caller to use named arguments. For example, This won't work. >>> def add(first, *, second): ... print(first, second) ... >>> add(1, 2) Traceback (most rec... | 6 | 6 |
70,617,258 | 2022-1-7 | https://stackoverflow.com/questions/70617258/session-object-in-fastapi-similar-to-flask | I am trying to use session to pass variables across view functions in fastapi. However, I do not find any doc which specifically says of about session object. Everywhere I see, cookies are used. Is there any way to convert the below flask code in fastapi? I want to keep session implementation as simple as possible. fro... | Take a look at Starlette's SessionMiddleware. FastAPI uses Starlette under the hood so it is compatible. After you register SessionMiddleware, you can access Request.session, which is a dictionary. Documentation: SessionMiddleware An implementation in FastAPI may look like: @app.route("/a") async def a(request: Request... | 8 | 13 |
70,627,163 | 2022-1-7 | https://stackoverflow.com/questions/70627163/how-to-work-with-regex-in-pathlib-correctly | I want find all images and trying to use pathlib, but my reg expression don't work. where I went wrong? from pathlib import Path FILE_PATHS=list(Path('./photos/test').rglob('*.(jpe?g|png)')) print(len(FILE_PATHS)) FILE_PATHS=list(Path('./photos/test').rglob('*.jpg'))#11104 print(len(FILE_PATHS)) 0 11104 | Get list of files using Regex import re p = Path('C:/Users/user/Pictures') files = [] for x in p.iterdir(): a = re.search('.*(jpe?g|png)',str(x)) if a is not None: files.append(a.group()) | 8 | 7 |
70,620,319 | 2022-1-7 | https://stackoverflow.com/questions/70620319/plotting-pd-df-with-datetime-index-in-matplotlib-results-in-valueerror-due-to-wr | I am trying to plot a pandas.DataFrame, but getting an unexplainable ValueError. Here is sample code causing the problem: import pandas as pd import matplotlib.pyplot as plt from io import StringIO import matplotlib.dates as mdates weekday_fmt = mdates.DateFormatter('%a %H:%M') test_csv = 'datetime,x1,x2,x3,x4,x5,x6\n'... | Thanks to the comments by Jody Klymak and MrFuppes, I found the answer to simply be ax = test_df.plot(x_compat=True). For anybody stumbling upon this in future, here comes the full explanation of what is happening: When using the plot-function, pandas takes over the formatting of x-tick (and possibly other features). T... | 7 | 10 |
70,623,704 | 2022-1-7 | https://stackoverflow.com/questions/70623704/enumerate-causes-incompatible-type-mypy-error | The following code: from typing import Union def process(actions: Union[list[str], list[int]]) -> None: for pos, action in enumerate(actions): act(action) def act(action: Union[str, int]) -> None: print(action) generates a mypy error: Argument 1 to "act" has incompatible type "object"; expected "Union[str, int]" Howe... | enumerate.__next__ needs more context than is available to have a return type more specific than Tuple[int, Any], so I believe mypy itself would need to be modified to make the inference that enumerate(actions) produces Tuple[int,Union[str,int]] values. Until that happens, you can explicitly cast the value of action be... | 5 | 4 |
70,610,919 | 2022-1-6 | https://stackoverflow.com/questions/70610919/installing-python-in-dockerfile-without-using-python-image-as-base | I have a python script that uses DigitalOcean tools (doctl and kubectl) I want to containerize. This means my container will need python, doctl, and kubectl installed. The trouble is, I figure out how to install both python and DigitalOcean tools in the dockerfile. I can install python using the base image "python:3" a... | just add this with any other thing you want to apt-get install: RUN apt-get update && apt-get install -y \ python3.6 &&\ python3-pip &&\ in alpine it should be something like: RUN apk add --update --no-cache python3 && ln -sf python3 /usr/bin/python &&\ python3 -m ensurepip &&\ pip3 install --no-cache --upgrade pip se... | 9 | 8 |
70,589,218 | 2022-1-5 | https://stackoverflow.com/questions/70589218/can-python-cursor-execute-accept-multiple-queries-in-one-go | Can the cursor.execute call below execute multiple SQL queries in one go? cursor.execute("use testdb;CREATE USER MyLogin") I don't have python setup yet but want to know if above form is supported by cursor.execute? import pyodbc # Some other example server values are # server = 'localhost\sqlexpress' # for a named in... | Multiple SQL statements in a single string is often referred to as an "anonymous code block". There is nothing in pyodbc (or pypyodbc) to prevent you from passing a string containing an anonymous code block to the Cursor.execute() method. They simply pass the string to the ODBC Driver Manager (DM) which in turn passes ... | 5 | 2 |
70,608,096 | 2022-1-6 | https://stackoverflow.com/questions/70608096/conda-install-different-packages-from-different-channels-in-one-line | When using conda install, is it possible to install different packages from different channels in one line? For example could one do something like this? conda install -c <channel_1> <package_1> -c <channel_2> <package_2> ...? | The --channel argument The --channel, -c flag tells Conda where to search for packages, but does not necessarily constrain where a specific package should be sourced. Moreover, the order that channels are specified applies to the whole solving process, and has no contextual relationship with adjacent package specificat... | 10 | 19 |
70,610,001 | 2022-1-6 | https://stackoverflow.com/questions/70610001/pandas-method-chaining-when-df-not-assigned-yet | Is it possible to do method chaining in pandas when no variable refering to the dataframe has been assigned, yet AND the method needs to refer to the dataframe? Example: here data frame can be referred to by variable name. df = pd.DataFrame({"a":[1,2,3], "b":list("abc")}) df = (df .drop(df.tail(1).index) #.other_meth... | You need some reference to the dataframe in order to use it in multiple independent places. That means binding a reusable name to the value returned by pd.DataFrame. A "functional" way to create such a binding is to use a lambda expression instead of an assignment statement. df = (lambda df: df.drop(df.tail(1).index)..... | 5 | 5 |
70,608,253 | 2022-1-6 | https://stackoverflow.com/questions/70608253/why-does-mypy-fail-with-incompatible-type-in-enum-classmethod | In my Enum, i have defined a classmethod for coercing a given value to an Enum member. The given value may already be an instance of the Enum, or it may be a string holding an Enum value. In order to decide whether it needs conversion, i check if the argument is an instance of the class, and only pass it on to int() if... | It's because int cannot be constructed from Enum. From documentation of int(x) If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base So to make it work you can make your Enum inherit from str class MyEnum(str, Enum): A = 0 B = 1 ... | 6 | 6 |
70,603,144 | 2022-1-6 | https://stackoverflow.com/questions/70603144/how-to-read-a-file-in-julia-like-python | Why is there a difference between these?: # Python f = open("./text.txt", "r") for i in f.readlines(): for l in i: print(print(l == "\n", ":", l)) f.close() # ----------------------------- # Julia f = open("./text.txt", "r") while !eof(f) for l in readline(file) println(l == '\n', " : ", l) end end close(f) The Python... | You can do this: # Julia f = open("./text.txt", "r") while !eof(f) for l in readline(file, keep=true) println(l == '\n', " : ", l) end end close(f) By default, it discards \n's, but you can keep them by adding keep=true. | 5 | 7 |
70,602,796 | 2022-1-6 | https://stackoverflow.com/questions/70602796/pytorch-gpu-memory-keeps-increasing-with-every-batch | I'm training a CNN model on images. Initially, I was training on image patches of size (256, 256) and everything was fine. Then I changed my dataloader to load full HD images (1080, 1920) and I was cropping the images after some processing. In this case, the GPU memory keeps increasing with every batch. Why is this hap... | As suggested here, deleting the input, output and loss data helped. Additionally, I had the data as a dictionary. Just deleting the dictionary isn't sufficient. I had to iterate over the dict elements and delete all of them. | 7 | 5 |
70,601,601 | 2022-1-6 | https://stackoverflow.com/questions/70601601/how-can-i-use-a-value-in-a-dataframe-to-look-up-an-attribute | Say I have the 2 Dataframes below; one with a list of students and test scores, and different student sessions that made up of the students. Say I want to add a new column, "Sum", to df with the sum of the scores for each session and a new column for the number of years passed since the most recent year that either stu... | Using apply method: import pandas as pd data1 = {'Student': ['John','Kim','Adam','Sonia'], 'Score': [92,100,76,82], 'Year': [2015,2013,2016,2018]} df_students = pd.DataFrame(data1, columns=['Student','Score','Year']) data2 = {'Session': [1,2,3,4], 'Student1': ['Sonia','Kim','John','Adam'], 'Student2': ['Adam','Sonia','... | 5 | 1 |
70,588,461 | 2022-1-5 | https://stackoverflow.com/questions/70588461/simpler-way-to-return-functions-in-python | so - I have built a bit of a rules engine in python - but I'm fairly new to python... my engine is fairly nice to use - but adding a new rule is pretty ugly, and I'm wondering if there's a way to clean it up. The key thing to remember is that rules have side-effects, rules can be combined with ands, ors, etc - and you ... | Instead of defining multi-line lambdas (which python doesn't allow), you could define multiple lambdas in a list and then use all lambdas in the list as required: class Rule: def __init__(self, checks=None, actions=None): self.checks = checks if checks else [] self.actions = actions if actions else [] def apply_to(self... | 5 | 1 |
70,598,062 | 2022-1-5 | https://stackoverflow.com/questions/70598062/codility-oddoccurrencesinarray-problem-recursion-and-python | I am trying to use recursion to solve the OddOccurrencesInArray Problem in Codility, in which we are given an array with N elements, N is always odd all of the elements of the array except for one has a total even number of occurrences we need to write code that returns the one unpaired value For example, if the arra... | I would suggest a different approach altogether. A recursive approach is not incorrect, however repeated calls to sorted is highly inefficient, especially if the input is significantly large. def solve(t): s = set() for v in t: s.add(v) if v not in s else s.remove(v) return list(s) input = [9, 3, 9, 3, 7, 9, 9] solve(... | 4 | 12 |
70,596,809 | 2022-1-5 | https://stackoverflow.com/questions/70596809/can-a-class-attribute-shadow-a-built-in-in-python | If have some code like this: class Foo(): def open(self, bar): # Doing some fancy stuff here, i.e. opening "bar" pass When I run flake8 with the flake8-builtins plug-in I get the error A003 class attribute "open" is shadowing a python builtin I don't understand how the method could possibly shadow the built-in open-f... | Not really a practical case, but your code would fail if you wanted to use the built-it functions on the class level after your shadowed function has been initialized: class Foo: def open(self, bar): pass with open('myfile.txt'): print('did I get here?') >>> TypeError: open() missing 1 required positional argument: 'ba... | 6 | 6 |
70,595,450 | 2022-1-5 | https://stackoverflow.com/questions/70595450/cant-install-numba-on-python-3-10 | Python 3.10 on Mac running OS 11.6.1 I uninstalled Python 3.9 from my machine and upgraded to version 3.10. No problems installing standard packages such as pandas, scipy, etc. However one package, epycom, requires numba. When I enter pip3 install numba, I receive the lengthy error message below with the key phrase Fil... | Based on the historical issues submited on Github numba is slow in adoption of a new Python version; my guess would be that it currently does not support Python 3.10. Reference: https://github.com/numba/llvmlite/issues/621 https://github.com/numba/llvmlite/issues/531 | 6 | 8 |
70,588,917 | 2022-1-5 | https://stackoverflow.com/questions/70588917/django-migrations-calculate-new-fields-value-based-on-old-fields-before-deletin | We are intenting to rework one of our models from old start-end date values to use starting date and length. However, this does pose a challenge in that we want to give default values to our new fields. In this case, is it possible to run migration where we create new field, give it a value based on models old start-en... | What I would do is create a custom migration and define the following series of operations there: Add length field. Update length field with calculations. Remove old field. So you can create a custom migration with: python manage.py makemigrations --name migration_name app_name --empty And then define there the seri... | 5 | 10 |
70,591,591 | 2022-1-5 | https://stackoverflow.com/questions/70591591/how-to-make-a-character-jump-in-pygame | I want to make my character jump. In my current attempt, the player moves up as long as I hold down SPACEv and falls down when I release SPACE. import pygame pygame.init() window = pygame.display.set_mode((300, 300)) clock = pygame.time.Clock() rect = pygame.Rect(135, 220, 30, 30) vel = 5 run = True while run: clock.t... | To make a character jump you have to use the KEYDOWN event, but not pygame.key.get_pressed(). pygame.key.get_pressed () is for continuous movement when a key is held down. The keyboard events are used to trigger a single action or to start an animation such as a jump. See alos How to get keyboard input in pygame? pygam... | 5 | 10 |
70,587,271 | 2022-1-5 | https://stackoverflow.com/questions/70587271/is-there-a-pythonic-way-of-filtering-substrings-of-strings-in-a-list | I have a list with strings as below. candidates = ["Hello", "World", "HelloWorld", "Foo", "bar", "ar"] And I want the list to be filtered as ["HelloWorld", "Foo", "Bar"], because others are substrings. I can do it like this, but don't think it's fast or elegant. def filter_not_substring(candidates): survive = [] for a... | How about: candidates = ["Hello", "World", "HelloWorld", "Foo", "bar", "ar"] result = [c for c in candidates if not any(c in o and len(o) > len(c) for o in candidates)] print(result) Counter to what was suggested in the comments: from timeit import timeit def filter_not_substring(candidates): survive = [] for a in can... | 6 | 7 |
70,585,611 | 2022-1-4 | https://stackoverflow.com/questions/70585611/how-to-add-python-and-pip-or-conda-packages-to-ddev | I need to execute a Python script inside the Ddev web docker image, but am having trouble figuring out what Debian python libraries are required to get Python binary with additional py package dependencies working. | Most of this is obsolete, because from DDEV v1.23.0 you can't easily get python 2 on DDEV at all, since it's been dropped from upstream. However, see @stasadev answer below for a great add-on that solves this. ddev add-on get stasadev/ddev-python2, see https://github.com/stasadev/ddev-python2. Python 2 on Ddev You real... | 9 | 9 |
70,584,730 | 2022-1-4 | https://stackoverflow.com/questions/70584730/how-to-use-a-reserved-keyword-in-pydantic-model | I need to create a schema but it has a column called global, and when I try to write this, I got an error. class User(BaseModel): id:int global:bool I try to use another name, but gives another error when try to save in db. | It looks like you are using a pydantic module. You can't use the name global because it's a reserved keyword so you need to use this trick to convert it. pydantic v1: class User(BaseModel): id: int global_: bool class Config: fields = { 'global_': 'global' } or pydantic v1 & v2: class User(BaseModel): id: int global_:... | 11 | 34 |
70,565,965 | 2022-1-3 | https://stackoverflow.com/questions/70565965/error-failed-building-wheel-for-numpy-error-could-not-build-wheels-for-numpy | I`m using python poetry(https://python-poetry.org/) for dependency management in my project. Though when I`m running poetry install, its giving me below error. ERROR: Failed building wheel for numpy Failed to build numpy ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects... | I solved it by doing the following steps:- I updated the pyproject.toml(This file contains all the library/dependency/dev dependency)with the numpy version that I installed using pip install numpy command. Run poetry lock to update poetry.lock file(contains details information about the library) Run poetry install... | 54 | 14 |
70,515,542 | 2021-12-29 | https://stackoverflow.com/questions/70515542/adding-comma-to-bar-labels | I have been using the ax.bar_label method to add data values to the bar graphs. The numbers are huge such as 143858918. How can I add commas to the data values using the ax.bar_label method? I do know how to add commas using the annotate method but if it is possible using bar_label, I am not sure. Is it possible using ... | Is it possible using the fmt keyword argument of ax.bar_label? Yes, but only in matplotlib 3.7+. Prior to 3.7, fmt only accepted % formatters (no comma support), so labels was needed to f-format the container's datavalues. If matplotlib ≥ 3.7, use fmt: for c in ax.containers: ax.bar_label(c, fmt='{:,.0f}') # ≥ 3.7 #... | 6 | 14 |
70,541,710 | 2021-12-31 | https://stackoverflow.com/questions/70541710/pandas-df-to-stata-dataframe-object-has-no-attribute-dtype | Until now the pandas function df.to_stata() worked just fine with my datasets. I am trying to export a dataframe that includes 29,778 rows and 37 to a Stata file using the following code: df.to_stata("Stata_File.dta", write_index=False, version=118) However, I receive the following error message: AttributeError: 'Data... | It's possible that this error arises when you have multiple columns with the same name in your dataframe | 8 | 5 |
70,583,166 | 2022-1-4 | https://stackoverflow.com/questions/70583166/how-do-i-write-an-efficient-pair-matching-algorithm | I need help with an algorithm that efficiently groups people into pairs, and ensures that previous pairs are not repeated. For example, say we have 10 candidates; candidates = [0,1,2,3,4,5,6,7,8,9] And say we have a dictionary of previous matches such that each key-value pair i.e. candidate:matches represents a candida... | If you are in charge of the tournament from the beginning, then the simplest solution is to organise the pairings according to a round-robin tournament. If you have no control on the pairings of the first rounds, and must organise the following rounds, here is a solution using module networkx to compute a maximum match... | 5 | 3 |
70,558,558 | 2022-1-2 | https://stackoverflow.com/questions/70558558/how-to-mask-environment-variables-created-in-github-when-running-a-workflow | I created a Github workflow that runs a python script with a cron schedule. On every run of the workflow an access_token is generated, which is required during the next run. To save the token the python script writes the token to the GITHUB_ENV file. In the next step, I use the hmanzur/actions-set-secret@v2.0.0 action ... | Your usage of "::add-mask::" is wrong (not your fault, I hate GHA doc). What you need to do is: echo "::add-mask::$ACCESS_TOKEN" echo "ACCESS_TOKEN=$ACCESS_TOKEN" >> $GITHUB_ENV | 14 | 16 |
70,552,618 | 2022-1-1 | https://stackoverflow.com/questions/70552618/vscode-fails-to-export-jupyter-notebook-to-html-jupyter-nbconvert-not-found | I keep on getting error message: Available subcommands: 1.0.0 Jupyter command `jupyter-nbconvert` not found. I've tried to reinstall nbconvert using pip to no use. I've also tried the tip from this thread with installing pip install jupyter in vscode terminal but it shows that "Requirement already satisfied" VSCode fa... | Unsure exactly what fixed the issue but heres a summary. Updated to python 3.10 Installed pandoc and miktex Powershell reinstall nbconvert Received warning that nbconvert script file is installed in a location not in Path. Copied said location to System Properties - Envionment Variables - Path Restart and install ... | 13 | 3 |
70,524,028 | 2021-12-29 | https://stackoverflow.com/questions/70524028/importerror-cannot-import-name-force-text-from-django-utils-encoding-usr | I get the error below when I add 'graphene_django' inside INSTALLED_APPS in the settings.py. After running python3 manage.py runserver graphene_django is installed successfully using pip install django graphene_django This is full error that I get: Watching for file changes with StatReloader Exception in thread djang... | force_text is removed from Django 4.0 You can add this code to top of your settings.py : import django from django.utils.encoding import force_str django.utils.encoding.force_text = force_str | 7 | 11 |
70,585,068 | 2022-1-4 | https://stackoverflow.com/questions/70585068/how-do-i-get-libpq-to-be-found-by-ctypes-find-library | I am building a simple DB interface in Python (3.9.9) and I am using psycopg (3.0.7) to connect to my Postgres (14.1) database. Until recently, the development of this app took place on Linux, but now I am using macOS Monterey on an M1 Mac mini. This seems to be causing some troubles with ctypes, which psycopg uses ext... | I had this problem but the solution was suggested to me by this answer to a related question: try setting envar DYLD_LIBRARY_PATH to the path you identified. NB, to get it working myself, I: used the path /Applications/Postgres.app/Contents/Versions/latest/lib and had to install Python 3.9 | 9 | 2 |
70,524,577 | 2021-12-29 | https://stackoverflow.com/questions/70524577/how-can-i-create-a-script-to-switch-between-my-arm-conda-and-x86-conda | I am on an apple silicon M1 MacBook Pro. I would like to have a native ARM python environment, and an environment that runs on x86 architecture with rosetta 2. I have installed two mini forge distributions, both in the home directory: miniforge3 for the native ARM installation and miniforge3_x86_64 for the x86 installa... | So far, the best solution I've found is to start the terminal with Rosetta 2, then run a function I have saved in .zshrc to initialize the correct conda installation so that I can use the correct architecture for my needs depending on the situation. My current solution is the following function named x86: x86 () { cond... | 4 | 6 |
70,565,357 | 2022-1-3 | https://stackoverflow.com/questions/70565357/paramiko-authentication-fails-with-agreed-upon-rsa-sha2-512-pubkey-algorithm | I have a Python 3 application running on CentOS Linux 7.7 executing SSH commands against remote hosts. It works properly but today I encountered an odd error executing a command against a "new" remote server (server based on RHEL 6.10): encountered RSA key, expected OPENSSH key Executing the same command from the sys... | Imo, it's a bug in Paramiko. It does not handle correctly absence of server-sig-algs extension on the server side. Try disabling rsa-sha2-* on Paramiko side altogether: ssh_client.connect( server, username=ssh_user, key_filename=ssh_keypath, disabled_algorithms=dict(pubkeys=["rsa-sha2-512", "rsa-sha2-256"])) (note tha... | 24 | 41 |
70,561,769 | 2022-1-3 | https://stackoverflow.com/questions/70561769/apache-beam-cloud-dataflow-streaming-stuck-side-input | I'm currently building PoC Apache Beam pipeline in GCP Dataflow. In this case, I want to create streaming pipeline with main input from PubSub and side input from BigQuery and store processed data back to BigQuery. Side pipeline code side_pipeline = ( p | "periodic" >> PeriodicImpulse(fire_interval=3600, apply_windowin... | Here you have a working example: mytopic = "" sql = "SELECT station_id, CURRENT_TIMESTAMP() timestamp FROM `bigquery-public-data.austin_bikeshare.bikeshare_stations` LIMIT 10" def to_bqrequest(e, sql): from apache_beam.io import ReadFromBigQueryRequest yield ReadFromBigQueryRequest(query=sql) def merge(e, side): for i ... | 9 | 7 |
70,573,108 | 2022-1-4 | https://stackoverflow.com/questions/70573108/speeding-up-the-loops-or-different-ideas-for-counting-primitive-triples | def pythag_triples(n): i = 0 start = time.time() for x in range(1, int(sqrt(n) + sqrt(n)) + 1, 2): for m in range(x+2,int(sqrt(n) + sqrt(n)) + 1, 2): if gcd(x, m) == 1: # q = x*m # l = (m**2 - x**2)/2 c = (m**2 + x**2)/2 # trips.append((q,l,c)) if c < n: i += 1 end = time.time() return i, end-start print(pythag_triples... | This new answer brings the total time for big_n down to 4min 6s. An profiling of my initial answer revealed these facts: Total time: 1h 42min 33s Time spent factorizing numbers: almost 100% of the time In contrast, generating all primes from 3 to sqrt(2*N - 1) takes only 38.5s (using Atkin's sieve). I therefore decid... | 8 | 3 |
70,573,780 | 2022-1-4 | https://stackoverflow.com/questions/70573780/unknown-opencv-exception-while-using-easyocr | Code: import easyocr reader = easyocr.Reader(['en']) result = reader.readtext('R.png') Output: CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU. cv2.error: Unknown C++ exception from OpenCV code I would truly appreciate any support! | The new version of OpenCV has some issues. Uninstall the newer version of OpenCV and install the older one using: pip install opencv-python==4.5.4.60 | 5 | 6 |
70,583,652 | 2022-1-4 | https://stackoverflow.com/questions/70583652/grabbing-video-title-from-yt-dlp-command-line-output | from yt_dlp import YoutubeDL with YoutubeDL() as ydl: ydl.download('https://youtu.be/0KFSuoHEYm0') this is the relevant bit of code producing the output. what I would like to do is grab the 2nd last line from the output below, specifying the video title. I have tried a few variations of output = subprocess.getoutput(y... | Credits: answer to question: How to get information from youtube-dl in python ?? Modify your code as follows: from yt_dlp import YoutubeDL with YoutubeDL() as ydl: info_dict = ydl.extract_info('https://youtu.be/0KFSuoHEYm0', download=False) video_url = info_dict.get("url", None) video_id = info_dict.get("id", None) vi... | 9 | 16 |
70,556,110 | 2022-1-2 | https://stackoverflow.com/questions/70556110/how-to-remove-the-background-from-an-image | I want to remove the background, and draw the outline of the box shown in the image(there are multiple such images with a similar background) . I tried multiple methods in OpenCV, however I am unable to determine the combination of features which can help remove background for this image. Some of the approaches tried ... | The Concept This is one of the cases where it is really useful to fine-tune the kernels of which you are using to dilate and erode the canny edges detected from the images. Here is an example, where the dilation kernel is np.ones((4, 2)) and the erosion kernel is np.ones((13, 7)): The Code import cv2 import numpy as np... | 8 | 22 |
70,557,824 | 2022-1-2 | https://stackoverflow.com/questions/70557824/python-itterate-down-dictionairy-move-down-tree-conditionally | I have a some python code below that walk down a tree but I want it to work down a tree checking taking some paths conditioally based on values. I want to get the LandedPrice for branches of tree based on condition and fulfillmentChannel parsed_results['LowestLanded'] = sku_multi_sku['Summary']['LowestPrices']['LowestP... | You can use list comprehensions with conditional logic for your purposes like this: my_dict = { "LowestPrices": { "value": "\n ", "LowestPrice": [{ "value": "\n ", "condition": { "value": "new" }, "fulfillmentChannel": { "value": "Amazon" }, "LandedPrice": { "value": "\n ", "CurrencyCode": { "value": "USD" }, "Amount":... | 4 | 7 |
70,575,617 | 2022-1-4 | https://stackoverflow.com/questions/70575617/memory-efficiency-of-nested-functions-in-python | Let's say we have the following functions: def functionA(b, c): def _innerFunction(b, c): return b + c return _innerFunction(b, c) def _outerFunction(b, c): return b + c def functionB(b, c): return _outerFunction(b, c) functionA and functionB will do the same. _outerFunction is globally available, while _innerFunction... | Regarding memory, both of them have almost the same memory footprint. A function is comprised of a code object, containing the actual compiled code, and a function object containing the closure, the name and other dynamic variables. The code object is compiled for all functions, inner and outer, before the code is run.... | 4 | 9 |
70,584,497 | 2022-1-4 | https://stackoverflow.com/questions/70584497/ti-is-not-defined-while-pulling-xcom-variable-in-s3toredshiftoperator | I am using S3ToRedshiftOperator to load csv file into Redshift database. Kindly help to pass xcom variable to S3ToRedshiftOperator. How can we push xcom without using custom function? Error: NameError: name 'ti' is not defined Using below code: from airflow.operators.s3_to_redshift_operator import S3ToRedshiftOperato... | The error message tells the problem. ti is not defined. When you set provide_context=True, Airflow makes Context available for you in the python callable. One of the attributes is ti (see source code). So you need to extract it from kwargs or set it in the function signature. Your code should be: def export_db_fn(**kwa... | 4 | 5 |
70,583,230 | 2022-1-4 | https://stackoverflow.com/questions/70583230/union-of-generic-types-that-is-also-generic | Say I have two types (one of them generic) like this from typing import Generic, TypeVar T = TypeVar('T') class A(Generic[T]): pass class B: pass And a union of A and B like this C = A|B Or, in pre-Python-3.10/PEP 604-syntax: C = Union[A,B] How do I have to change the definition of C, so that C is also generic? e.g.... | Rereading the mypy documentation I believe I have found my answer: Type aliases can be generic. In this case they can be used in two ways: Subscripted aliases are equivalent to original types with substituted type variables, so the number of type arguments must match the number of free type variables in the generic ty... | 10 | 4 |
70,586,364 | 2022-1-4 | https://stackoverflow.com/questions/70586364/how-to-elegantly-generate-all-prefixes-of-an-iterable-cumulative-iterable | From an iterable, I'd like to generate an iterable of its prefixes (including the original iterable itself). for prefix in prefixes(range(5)): print(tuple(prefix)) should result in (0,) (0, 1) (0, 1, 2) (0, 1, 2, 3) (0, 1, 2, 3, 4) or in () (0,) (0, 1) (0, 1, 2) (0, 1, 2, 3) (0, 1, 2, 3, 4) and for prefix in prefixe... | It may be considered elegant to write the prefixes function in any generalized way that works, put it in a module, and then import it in the code where it is needed, so that it doesn't matter how it is implemented. On the other hand, requiring an extra import can be perceived as less elegant than a short local function... | 6 | 3 |
70,537,825 | 2021-12-30 | https://stackoverflow.com/questions/70537825/problem-dealing-with-a-space-when-moving-json-to-python | I am high school math teacher who is teaching myself programming. My apologies in advance if I don't phrase some of this correctly. I am collecting CSV data from the user and trying to move it to a SQLite database via Python. Everything works fine unless one of the values has a space in it. For example, here is part of... | The problem was the way I was sending the JSON string -- it wasn't in quotes so anytime there was a space in a value, there was a problem. To fix it: I got the JSON from the answer above, then before sending the JSON string via a POST request, I enclosed it in quotes. send_data = JSON.stringify(json); send_data = "'" +... | 5 | 0 |
70,583,705 | 2022-1-4 | https://stackoverflow.com/questions/70583705/matplotlib-share-x-axis-between-imshow-and-plot | I am trying to plot two imshow and one plot above each other sharing their x-axis. The figure layout is set up using gridspec. Here is a MWE: import matplotlib as mpl from matplotlib import pyplot as plt import numpy as np fig = plt.figure(figsize=(10,8)) gs = fig.add_gridspec(3,2,width_ratios=(1,2),height_ratios=(1,2... | Constrained_layout was specifically designed with this case in mind. It will work with your gridspec solution above, but more idiomatically: import datetime as dt import matplotlib as mpl from matplotlib import pyplot as plt import numpy as np import pandas as pd fig, axs = plt.subplot_mosaic([['.', 'plot'], ['empty1',... | 4 | 6 |
70,583,980 | 2022-1-4 | https://stackoverflow.com/questions/70583980/i-am-unable-to-create-a-new-virtualenv-in-ubuntu | So, I installed virtualenv in ubuntu terminal. I installed using the following commands: sudo apt install python3-virtualenv pip install virtualenv But when I try creating a new virtualenv using: virtualenv -p python3 venv I am getting the following error: AttributeError: module 'virtualenv.create.via_global_ref.buil... | You don't need to use virtualenv. You can use this: python3 -m venv ./some_env | 17 | 16 |
70,570,165 | 2022-1-3 | https://stackoverflow.com/questions/70570165/how-to-solve-importerror-with-pytest | There were already questions regarding this topic. Sometimes programmers put some __init__.py at some places, often it is said one should use absolute paths. However, I don't get it to work here: How do I import a class from a package so that tests in pytest run and the code can be used? At the moment I get pytest or t... | The self-named module testingonly and file name of testingonly.py may be causing some issues with the way the modules are imported. Remove the __init__.py from the tests directory. Ref this answer . Try renaming testingonly.py to mytest.py and then importing it into your project again. In the cli.py, it should be: from... | 9 | 2 |
70,579,291 | 2022-1-4 | https://stackoverflow.com/questions/70579291/create-new-column-using-str-contains-and-based-on-if-else-condition | I have a list of names 'pattern' that I wish to match with strings in column 'url_text'. If there is a match i.e. True the name should be printed in a new column 'pol_names_block' and if False leave the row empty. pattern = '|'.join(pol_names_list) print(pattern) 'Jon Kyl|Doug Jones|Tim Kaine|Lindsey Graham|Cory Booker... | From this toy Dataframe : >>> import pandas as pd >>> from io import StringIO >>> df = pd.read_csv(StringIO(""" ... id,url_text ... 1,Tim Kaine ... 2,Tim Kain ... 3,Tim ... 4,Lindsey Graham.com ... """), sep=',') >>> df id url_text 0 1 Tim Kaine 1 2 Tim Kain 2 3 Tim 3 4 Lindsey Graham.com From pol_names_list, we build... | 5 | 2 |
70,573,362 | 2022-1-4 | https://stackoverflow.com/questions/70573362/tensorflow-how-to-extract-attention-scores-for-graphing | If you have a MultiHeadAttention layer in Keras, then it can return attention scores like so: x, attention_scores = MultiHeadAttention(1, 10, 10)(x, return_attention_scores=True) How do you extract the attention scores from the network graph? I would like to graph them. | Option 1: If you want to plot the attention scores during training, you can create a Callback and pass data to it. It can be triggered for example, after every epoch. Here is an example where I am using 2 attention heads and plotting them after every epoch: import tensorflow as tf import seaborn as sb import matplotlib... | 4 | 9 |
70,574,499 | 2022-1-4 | https://stackoverflow.com/questions/70574499/how-do-i-make-a-decorator-to-wrap-an-async-function-with-a-try-except-statement | Let's say I have an async function like this: async def foobar(argOne, argTwo, argThree): print(argOne, argTwo, argThree) I want to make a decorator and use it on this function in a way that it wraps the above code in a try except statement like this: try: print(argOne, argTwo, argThree) except: print('Something went ... | because wrapper called first, we should also define it as a async function: async def wrap(*arg, **kwargs): import asyncio def decorator(f): async def wrapper(*arg, **kwargs): try: await f(*arg, **kwargs) except Exception as e: print('Something went wrong.', e) return wrapper @decorator async def foobar(argOne, argTwo,... | 11 | 13 |
70,534,207 | 2021-12-30 | https://stackoverflow.com/questions/70534207/how-to-use-intel-oneapi-in-right-way | Today, I'm wondering what the difference between Conda in oneAPI and Conda in Anaconda is and how to use the oneAPI in the right way to get the maximum usage of the latest Intel Core gen 12. After installing oneAPI, they also contain conda. However, I cannot use this as a normal condition when: -It does not contain con... | Conda executable in one api does not support all the features supported by conda in anaconda. Conda executable in one api can be used to download both intel optimized packages as well as anaconda packages. Conda executable in one api gives performance improvement for intel optimized packages. Since setvars is not s... | 5 | 1 |
70,573,066 | 2022-1-4 | https://stackoverflow.com/questions/70573066/conditional-counting-in-pandas-df | I have a dataframe of stock prices: df = pd.DataFrame([100, 101, 99, 100,105,104,106], columns=['P']) I would like to create a counter column, that counts either if the current price is higher than the previous row's price, BUT if the current price is lower than the previous row's price, only counts again, once that p... | Algorithm: Find what current maximum previously observed value was at each row (inclusive of the current row). See what the maximum previously observed value was for the preceding row. Each time a difference exists between these two values, we know that a new water mark has been hit within the current row. Calculat... | 4 | 3 |
70,552,775 | 2022-1-2 | https://stackoverflow.com/questions/70552775/multiprocess-inherently-shared-memory-in-no-longer-working-on-python-3-10-comin | I understand there are a variety of techniques for sharing memory and data structures between processes in python. This question is specifically about this inherently shared memory in python scripts that existed in python 3.6 but seems to no longer exist in 3.10. Does anyone know why and if it's possible to bring this ... | In short, since 3.8, CPython uses the spawn start method on MacOs. Before it used the fork method. On UNIX platforms, the fork start method is used which means that every new multiprocessing process is an exact copy of the parent at the time of the fork. The spawn method means that it starts a new Python interpreter fo... | 6 | 10 |
70,566,660 | 2022-1-3 | https://stackoverflow.com/questions/70566660/parquet-with-null-columns-on-pyarrow | I'm reading a table on PostgreSQL using pandas.read_sql, then I'm converting it as a Pyarrow table and saving it partitioned in local filesystem. # Retrieve schema.table data from database def basename_file(date_partition): basename_file = f"{table_schema}.{table_name}-{date}.parquet" return basename_file def get_table... | If you can post the exact error message that might be more helpful. I did some experiments with pyarrow 6.0.1 and I found that things work ok as long as the first file contains some valid values for all columns (pyarrow will use this first file to infer the schema for the entire dataset). The "first" file is not techni... | 4 | 7 |
70,567,344 | 2022-1-3 | https://stackoverflow.com/questions/70567344/easyocr-segmentation-fault-core-dumped | I got this issue pip install easyocr on python env import easyocr reader = easyocr.Reader(['en']) result = reader.readtext('./reports/dilate/NP6221833_126.png', workers=1) finally Segmentation fault (core dumped) | Solved downgrading to the nov 2021 version of opencv pip install opencv-python-headless==4.5.4.60 | 6 | 10 |
70,563,360 | 2022-1-3 | https://stackoverflow.com/questions/70563360/grouping-aggregating-on-level-1-index-assigning-different-aggregation-functi | I have a dataframe df: 2019 2020 2021 2022 A 1 10 15 15 31 2 5 4 7 9 3 0.3 0.4 0.4 0.7 4 500 600 70 90 B 1 10 15 15 31 2 5 4 7 9 3 0.3 0.4 0.4 0.7 4 500 600 70 90 C 1 10 15 15 31 2 5 4 7 9 3 0.3 0.4 0.4 0.7 4 500 600 70 90 D 1 10 15 15 31 2 5 4 7 9 3 0.3 0.4 0.4 0.7 4 500 600 70 90 I am trying to group by the level 1... | You could use apply with a custom function as follows: import numpy as np aggs = {1: np.sum, 2: np.mean, 3: np.mean, 4: np.sum} def f(x): func = aggs.get(x.name, np.sum) return func(x) df.groupby(level=1).apply(f) The above code uses sum by default so 1 and 4 could be removed from aggs without any different results. I... | 5 | 4 |
70,520,120 | 2021-12-29 | https://stackoverflow.com/questions/70520120/attributeerror-module-setuptools-distutils-has-no-attribute-version | I was trying to train a model using tensorboard. While executing, I got this error: $ python train.py Traceback (most recent call last): File "train.py", line 6, in <module> from torch.utils.tensorboard import SummaryWriter File "C:\Users\91960\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\utils\tensor... | This command did the trick for me: python3 -m pip install setuptools==59.5.0 pip successfully installed this version: Successfully installed setuptools-60.1.0 instead of setuptools-60.2.0 | 44 | 42 |
70,554,095 | 2022-1-2 | https://stackoverflow.com/questions/70554095/counting-triangles-in-a-graph-by-iteratively-removing-high-degree-nodes | Computing nx.triangles(G) on an undirected graph with about 150 thousand nodes and 2 million edges, is currently very slow (on the scale of 80 hours). If the node degree distribution is highly skewed, is there any problem with counting triangles using the following procedure? import networkx as nx def largest_degree_no... | Assuming the graph is not directed (ie. G.is_directed() == False), the number of triangles can be efficiently found by finding nodes that are both neighbors of neighbors and direct neighbors of a same node. Pre-computing and pre-filtering the neighbors of nodes so that each triangle is counted only once helps to improv... | 5 | 2 |
70,556,229 | 2022-1-2 | https://stackoverflow.com/questions/70556229/how-should-we-type-a-callable-with-additional-properties | As a toy example, let's use the Fibonacci sequence: def fib(n: int) -> int: if n < 2: return 1 return fib(n - 2) + fib(n - 1) Of course, this will hang the computer if we try to: print(fib(100)) So we decide to add memoization. To keep the logic of fib clear, we decide not to change fib and instead add memoization vi... | To describe something as "a callable with a memory attribute", you could define a protocol (Python 3.8+, or earlier versions with typing_extensions): from typing import Protocol class Wrapper(Protocol): memory: dict[int, int] def __call__(self, n: int) -> int: ... In use, the type checker knows that a Wrapper is valid... | 7 | 3 |
70,545,797 | 2021-12-31 | https://stackoverflow.com/questions/70545797/finding-straight-lines-from-tightly-coupled-lines-and-noise-curvy-lines | I have this image for a treeline crop. I need to find the general direction in which the crop is aligned. I'm trying to get the Hough lines of the image, and then find the mode of distribution of angles. I've been following this tutorialon crop lines, however in that one, the crop lines are sparse. Here they are densel... | You can use a 2D FFT to find the general direction in which the crop is aligned (as proposed by mozway in the comments). The idea is that the general direction can be easily extracted from centred beaming rays appearing in the magnitude spectrum when the input contains many lines in the same direction. You can find mor... | 6 | 4 |
70,546,198 | 2021-12-31 | https://stackoverflow.com/questions/70546198/python-beautiful-soup-get-correct-column-headers-for-each-table | The following code gets player data but each dataset is different. The first data it sees is the quarterback data, so it uses these columns for all the data going forward. How can I change the header so that for every different dataset it encounters, the correct headers are used with the correct data? import pandas as ... | As mentioned expected result is not that clear, but if you just wanna read the tables use pandas.read_html to achieve your goal - index_col=0 avoids that the first column, that has no header is named Unnamed_0. pd.read_html('https://www.espn.com/nfl/boxscore/_/gameId/401326313',index_col=0) Example import pandas as pd... | 5 | 1 |
70,534,339 | 2021-12-30 | https://stackoverflow.com/questions/70534339/adding-nodes-to-a-disconnected-graph-in-order-to-fully-connect-the-graph-compone | I have a graph where each node has a spatial position given by (x,y), and the edges between the nodes are only connected if the euclidean distance between each node is sqrt(2) or less. Here's my example: import networkx G=nx.Graph() G.add_node(1,pos=(1,1)) G.add_node(2,pos=(2,2)) G.add_node(3,pos=(1,2)) G.add_node(4,po... | I am quite convinced that this problem is NP-hard. The closest problem I know is the geometric Steiner tree problem with octilinear metric. I have two, rather quick-and-dirty, suggestions. Both are heuristic. 1st idea: Formulate the problem as an Euclidean Steiner tree problem (https://en.wikipedia.org/wiki/Steiner_tre... | 7 | 1 |
70,546,823 | 2022-1-1 | https://stackoverflow.com/questions/70546823/pandas-how-to-save-a-styled-dataframe-to-image | I have styled a dataframe output and have gotten it to display how I want it in a Jupyter Notebook but I am having issues find a good way to save this as an image. I have tried https://pypi.org/project/dataframe-image/ but the way I have this working it seem to be a NoneType as it's a styler object and errors out when ... | Was able to change how I was using dataframe-image on the styler object and got it working. Passing it into the export() function rather than calling it off the object directly seems to be the right way to do this. The .render() did get the HTML but was often losing much of the styling when converting it to image or wh... | 7 | 2 |
70,542,577 | 2021-12-31 | https://stackoverflow.com/questions/70542577/from-base64-encoded-public-key-in-der-format-to-cose-key-in-python | I have a base64-encoded public key in DER format. In Python, how can I convert it into a COSE key? Here is my failed attempt: from base64 import b64decode from cose.keys import CoseKey pubkeyder = "...==" decCborData.key = CoseKey.decode(b64decode(pubkeyder)) | The posted key is an EC key for curve P-256 in X.509 format. With an ASN.1 parser (e.g. https://lapo.it/asn1js/) the x and y coordinates can be determined: x: 0x1AF1EA7FB498B65BDEBCEC80FE7A3E8B5FD67264B46CE60FD5B80FFA92538D39 y: 0x013A9422F9FEC87BAE35E56165F5AA2ACCC98A449984E94AF81FE6FD55B6BB14 Then the COSE key can b... | 5 | 4 |
70,543,710 | 2021-12-31 | https://stackoverflow.com/questions/70543710/pythons-enumerate-equivalent-in-c | I am learning C# and have been taking a lot of online courses. I am looking for a simpler/neater way to enumerate a list within a list. In python we can do something like this in just one line: newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])] Does it have to involve lambda and Linq in C#? if so, what wo... | Just a constructor will be enough: List<List<string>> familyListss = new List<List<string>>() { new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" }, new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" }, new List<string> { "John", "John_sister... | 4 | 6 |
70,541,783 | 2021-12-31 | https://stackoverflow.com/questions/70541783/the-simplest-way-to-check-for-nans-in-columns-r | I'm python user learning R. Frequently, I need to check if columns of a dataframe contain NaN(s). In python, I can simply do import pandas as pd df = pd.DataFrame({'colA': [1, 2, None, 3], 'colB': ['A', 'B', 'C', 'D']}) df.isna().any() giving me colA True colB False dtype: bool In R I'm struggling to find an easy sol... | You can use anyNA: Checks for NA in a vector df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) sapply(df, anyNA) colA colB TRUE FALSE Edit jay.sf is right. This will check for NaNs. df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) anyNAN <- function(x) { any(is.nan(x)) } sapply(d... | 5 | 8 |
70,539,415 | 2021-12-31 | https://stackoverflow.com/questions/70539415/is-onedrive-sdk-python-api-still-alive | The author from python-onedrive python-onedrive warns that his library is achrived and obsoleted by official library from microsoft and refers to its git repo sdk What perplexes me is that the archived obsoleted library is being maintained while the official repo is dead since 6 years ago. What's going on? Thanks. | It appears the project was written before Microsoft authored their own SDK that solves the goal the creator originally had - namely that there was no Python SDK for OneDrive. Looking at the commit history, there's been no meaningful changes in six years. The only changes were typos in the documentation, which was clean... | 6 | 3 |
70,537,488 | 2021-12-30 | https://stackoverflow.com/questions/70537488/cannot-import-name-registermattype-from-cv2-cv2 | I got below error message when I run model_main_tf2.py on Object Detection API: Traceback (most recent call last): File "/content/models/research/object_detection/model_main_tf2.py", line 32, in <module> from object_detection import model_lib_v2 File "/usr/local/lib/python3.7/dist-packages/object_detection/model_lib_v2... | The same thing occurred to me yesterday when I used Colab. A possible reason may be that the version of opencv-python(4.1.2.30) does not match opencv-python-headless(4.5.5.62). Or the latest version 4.5.5 may have something wrong... I uninstalled opencv-python-headless==4.5.5.62 and installed 4.1.2.30 and it fixed. | 51 | 76 |
70,534,875 | 2021-12-30 | https://stackoverflow.com/questions/70534875/typeerror-init-got-an-unexpected-keyword-argument-service-error-using-p | I've been struggling with this problem for sometime, but now I'm coming back around to it. I'm attempting to use selenium to scrape data from a URL behind a company proxy using a pac file. I'm using Chromedriver, which my browser uses the pac file in it's configuration. I've been trying to use desired_capabilities, but... | If you are still using Selenium v3.x then you shouldn't use the Service() and in that case the key executable_path is relevant. In that case the lines of code will be: driver = webdriver.Chrome(executable_path='C:\Program Files\Chrome Driver\chromedriver.exe') Else, if you are using selenium4 then you have to use Ser... | 16 | 20 |
70,535,336 | 2021-12-30 | https://stackoverflow.com/questions/70535336/how-to-ignore-function-arguments-with-cachetools-ttl-cache | I'm exploiting the cachetools @ttl_cache decorator (not @cached). I need to ignore some params in the cache key. E.g,. @ttl_cache(maxsize=1024, ttl=600) def my_func(foo, ignore_bar, ignore_baz): # do stuff Working that way, I get this: >>> my_func("foo", "ignore_bar", "ignore_baz") # cache miss >>> my_func("foo", "ign... | I haven't used cachetools, but I've looked at the docs out of interest. Apparently, there's no built-in way. If you really need this functionality, I can suggest a hack like the following: class PackedArgs(tuple): def __hash__(self): return hash(self[0]) def __eq__(self, other): if isinstance(other, self.__class__): re... | 6 | 2 |
70,536,166 | 2021-12-30 | https://stackoverflow.com/questions/70536166/improving-performance-of-finding-out-how-many-possible-triangles-can-be-made-wit | I am doing an assessment that is asking by the given "n" as input which is a length of a stick; how many triangles can you make? (3 < n < 1,000,000) For example: input: N=8 output: 1 explanation: (3,3,2) input: N=12 output: 3 explanation: (4,4,4) (4,5,3) (5,5,2) Now the codes I wrote are returning 33 % accuracy as the... | This is an intuitive O(n) algorithm I came up with: def main(): n = int(input()) if n < 3: print(0) return ans = n % 2 for a in range(2, n//2+1): diff = n - a if diff // 2 < a: break if diff % 2 == 0: b = diff // 2 else: b = diff // 2 + 1 b = max(b - a // 2, a) c = n - b - a if abs(b - c) >= a: b += 1 c -= 1 ans += abs... | 5 | 1 |
70,527,241 | 2021-12-30 | https://stackoverflow.com/questions/70527241/python-pandas-dataframe-assign-a-list-to-multiple-cells | I have a DataFrame like name col1 col2 a aa 123 a bb 123 b aa 234 and a list [1, 2, 3] I want to replace the col2 of every row with col1 = 'aa' with the list like name col1 col2 a aa [1, 2, 3] a bb 123 b aa [1, 2, 3] I tried something like df.loc[df[col1] == 'aa', col2] = [1, 2, 3] but it gives me the error: ValueE... | import pandas as pd df = pd.DataFrame({"name":["a","a","b"],"col1":["aa","bb","aa"],"col2":[123,123,234]}) l = [1,2,3] df["col2"] = df.apply(lambda x: l if x.col1 == "aa" else x.col2, axis =1) df | 7 | 2 |
70,523,639 | 2021-12-29 | https://stackoverflow.com/questions/70523639/store-formatted-strings-pass-in-values-later | I have a dictionary with a lot of strings. Is it possible to store a formatted string with placeholders and pass in a actual values later? I'm thinking of something like this: d = { "message": f"Hi There, {0}" } print(d["message"].format("Dave")) The above code obviously doesn't work but I'm looking for something simi... | You use f-string; it already interpolated 0 in there. You might want to remove f there d = { # no f here "message": "Hi There, {0}" } print(d["message"].format("Dave")) Hi There, Dave | 7 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.