question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
72,880,426 | 2022-7-6 | https://stackoverflow.com/questions/72880426/how-to-get-list-of-entities-in-python-wikidata | I need to get all the info about some writers in wikidata For example - https://www.wikidata.org/wiki/Q39829 My code from wikidata.client import Client client = Client() entity = client.get('Q39829', load=True) # Spouse spouse_prop = client.get('P26') spouse = entity[spouse_prop] print('Mother: ', spouse.label) # Child... | From the docs for Wikidata: Although it implements Mapping[EntityId, object], it [entity] actually is multidict. See also getlist() method. Which means you can do: >>> [c.label for c in entity.getlist(child_prop)] [m'Joe Hill', m'Owen King', m'Naomi King'] | 4 | 5 |
72,801,333 | 2022-6-29 | https://stackoverflow.com/questions/72801333/how-to-pass-url-as-a-path-parameter-to-a-fastapi-route | I have created a simple API using FastAPI, and I am trying to pass a URL to a FastAPI route as an arbitrary path parameter. from fastapi import FastAPI app = FastAPI() @app.post("/{path}") def pred_image(path:str): print("path",path) return {'path':path} When I test it, it doesn't work and throws an error. I am testin... | Option 1 You could simply use Starlette's path convertor to capture arbitrary paths. As per Starlette documentation, path returns the rest of the path, including any additional / characters. However, if your URL includes query parameters as well, you should append the query string to the path, as shown below: from fast... | 6 | 14 |
72,815,386 | 2022-6-30 | https://stackoverflow.com/questions/72815386/python-get-the-source-code-of-the-line-that-called-me | Using the python inspect module, in a function, I would like to get the source code of the line that called that function. So in the following situation: def fct1(): # Retrieve the line that called me and extract 'a' return an object containing name='a' a = fct1() I would like to retrieve the string "a = fct1()" in fc... | A really dumb solution would be to capture a stack trace and take the 2nd line: import traceback def fct1(): stack = traceback.extract_stack(limit=2) print(traceback.format_list(stack)[0].split('\n')[1].strip()) # prints "a = fct1()" return None a = fct1() @jtlz2 asked for it in a decorator import traceback def add_ca... | 7 | 7 |
72,868,550 | 2022-7-5 | https://stackoverflow.com/questions/72868550/how-to-perform-an-elementwise-maximum-of-two-columns-in-a-python-polars-expressi | How can I calculate the elementwise maximum of two columns in Polars inside an expression? Polars version = 0.13.31 Problem statement as code: import polars as pl import numpy as np df = pl.DataFrame({ "a": np.arange(5), "b": np.arange(5)[::-1] }) # Produce a column with the values [4, 3, 2, 3, 4] using df.select([ ...... | You can use .max_horizontal() df = pl.select( a = pl.int_range(0, 5), b = pl.int_range(0, 5).reverse(), ) shape: (5, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 0 ┆ 4 │ │ 1 ┆ 3 │ │ 2 ┆ 2 │ │ 3 ┆ 1 │ │ 4 ┆ 0 │ └─────┴─────┘ df.with_columns( pl.max_horizontal('a', 'b').alias('max(a, b)') ) s... | 5 | 14 |
72,821,244 | 2022-6-30 | https://stackoverflow.com/questions/72821244/polars-get-grouped-rows-where-column-value-is-maximum | So consider this snippet import polars as pl df = pl.DataFrame({'class': ['a', 'a', 'b', 'b'], 'name': ['Ron', 'Jon', 'Don', 'Von'], 'score': [0.2, 0.5, 0.3, 0.4]}) df.group_by('class').agg(pl.col('score').max()) This gives me: shape: (2, 2) ┌───────┬───────┐ │ class ┆ score │ │ --- ┆ --- │ │ str ┆ f64 │ ╞═══════╪════... | You can use a sort_by expression to sort your observations in each group by score, and then use the last expression to take the last observation. For example, to take all columns: df.group_by('class').agg( pl.all().sort_by('score').last(), ) shape: (2, 3) ┌───────┬──────┬───────┐ │ class ┆ name ┆ score │ │ --- ┆ --- ┆... | 9 | 13 |
72,868,256 | 2022-7-5 | https://stackoverflow.com/questions/72868256/chromedrivermanager-install-doesnt-work-webdriver-manager | I tried code below in TEST.py:32 print("ChromeDriverManager().install() :", ChromeDriverManager().install()) [WDM] - ====== WebDriver manager ====== 2022-07-05 19:49:04,445 INFO ====== WebDriver manager ====== Traceback (most recent call last): File "d:\Python\PYTHONWORKSPACE\repo\Auto-booking-master\src\TEST.py", lin... | May be your web driver manager is outdated. Uninstall your web driver manager by... pip uninstall webdriver_manager ...then again install... pip install webdriver_manager Install webdriver-manager: pip install webdriver-manager, pip install selenium And then: # selenium 4 from selenium import webdriver from seleniu... | 7 | 16 |
72,859,535 | 2022-7-4 | https://stackoverflow.com/questions/72859535/pytest-print-traceback-immediately-in-live-log-not-at-the-end-in-summary | Given test.py import logging log = logging.getLogger("mylogger") def test(): log.info("Do thing 1") log.info("Do thing 2") raise Exception("This is deeply nested in the code") log.info("Do thing 3") assert True def test_2(): log.info("Nothing interesting here") When I run pytest --log-cli-level NOTSET test.py I get th... | I don't know if it's "official" or not, but I did find this answer in the Pytest dev forums, recommending the use of pytest-instafail. It's a maintained plugin, so it might do what you're looking to do. It met my needs; now I can see tracebacks in the live-log output, and not have to wait till the end of a test suite t... | 4 | 4 |
72,842,597 | 2022-7-2 | https://stackoverflow.com/questions/72842597/why-is-aexit-not-fully-executed-when-it-has-await-inside | This is the simplified version of my code: main is a coroutine which stops after the second iteration. get_numbers is an async generator which yields numbers but within an async context manager. import asyncio class MyContextManager: async def __aenter__(self): print("Enter to the Context Manager...") return self async... | This is not specific to __aexit__ but to all async code: When an event loop shuts down it must decide between cancelling remaining tasks or preserving them. In the interest of cleanup, most frameworks prefer cancellation instead of relying on the programmer to clean up preserved tasks later on. This kind of shutdown cl... | 14 | 8 |
72,813,575 | 2022-6-30 | https://stackoverflow.com/questions/72813575/when-to-use-query-over-loc-in-pandas-dataframe | Question What is the correct or best way to query a pandas DataFrame? Is it depending on the use case or can you say "always use .query()" or "never use .query()"? My primary concern is robustness or error-proof-ness of the code, but of course performance is also relevant. In this post the query method is stated to be ... | I don't think there is a hard answer for this question. To answer your question regarding should you always use query, the simple answer is no. The query method uses eval behind the scenes, which makes it less performant. So when should you use query? You should use query if the condition you're trying to filter is inc... | 7 | 6 |
72,804,395 | 2022-6-29 | https://stackoverflow.com/questions/72804395/adding-timedelta-to-local-datetime-unexpected-behaviour-accross-dst-shift | I just stumbled accross this surprising behaviour with Python datetimes while creating datetimes accross DST shift. Adding a timedelta to a local datetime might not add the amount of time we expect. import datetime as dt from zoneinfo import ZoneInfo # Midnight d0 = dt.datetime(2020, 3, 29, 0, 0, tzinfo=ZoneInfo("Europ... | The rationale is : timedelta arithmetic is wall time arithmetic. That is, it includes the DST transition hours (or excludes, depending on the change). See also P. Ganssle's blog post on the topic . An illustration: import datetime as dt from zoneinfo import ZoneInfo # Midnight d0 = dt.datetime(2020, 3, 29, 0, 0, tzinfo... | 6 | 3 |
72,795,799 | 2022-6-29 | https://stackoverflow.com/questions/72795799/how-to-solve-403-error-with-flask-in-python | I made a simple server using python flask in mac. Please find below the code. from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def hello(): print("request received") return "Hello world!" if __name__ == "__main__": app.run(debug=True) I run it using python3 main.py command. While ... | Mac OSX Monterey (12.x) currently uses ports 5000 and 7000 for its Control centre hence the issue. Try running your app from port other than 5000 and 7000 use this: if __name__ == "__main__": app.run(port=8000, debug=True) and then run your flask file, eg: app.py python app.py You can also run using the flask command ... | 50 | 112 |
72,871,480 | 2022-7-5 | https://stackoverflow.com/questions/72871480/when-should-a-static-method-be-a-function | I am writing a class for an image processing algorithm which has some methods, and notably a few static methods. My IDE keeps telling me to convert static methods to function which leads me to the following question: When should a static method be turned into a function? When shouldn't it? | There are no set rules in python regarding this decision, but there are style-guides defined e.g. by companies that look to solve the ambiguity of when to use what. One popular example of this would be the Google Python Style Guide: Never use staticmethod unless forced to in order to integrate with an API defined in a... | 7 | 12 |
72,794,483 | 2022-6-29 | https://stackoverflow.com/questions/72794483/pytest-alembic-initialize-database-with-async-migrations | The existing posts didn't provide a useful answer to me. I'm trying to run asynchronous database tests using Pytest (db is Postgres with asyncpg), and I'd like to initialize my database using my Alembic migrations so that I can verify that they work properly in the meantime. My first attempt was this: @pytest.fixture(s... | I got this up and running pretty easily with the following env.py - the main idea here is that the migration can be run synchronously import asyncio from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config from sqlalchemy import pool from sqlalchemy.ext.asyncio import ... | 8 | 13 |
72,796,594 | 2022-6-29 | https://stackoverflow.com/questions/72796594/attributeerror-module-httpcore-has-no-attribute-synchttptransport | While importing googletrans I am getting this error: AttributeError: module 'httpcore' has no attribute 'SyncHTTPTransport | googletrans==3.0.0 use very old httpx (0.13.3) and httpcore version. You just need to update httpx and httpcore to latest version and go to googletrans source directory in Python310/Lib/site-packages. In the file client.py, fix 'httpcore.SyncHTTPTransport' to 'httpcore.AsyncHTTPProxy'. And done, perfect. Even, Async, a... | 5 | 20 |
72,814,364 | 2022-6-30 | https://stackoverflow.com/questions/72814364/django-tenants-python-shell-with-specific-tenant | I want to use "./manage.py shell" to run some Python commands with a specific tenant, but the code to do so is quite cumbersome because I first have to look up the tenant and then use with tenant_context(tenant)): and then write my code into this block. I thought that there should be a command for that provided by djan... | I've just looked at this myself and this will work, where tenant1 is your chosen tenant: python3 manage.py tenant_command shell --schema=tenant1 | 8 | 10 |
72,876,146 | 2022-7-5 | https://stackoverflow.com/questions/72876146/handling-gil-when-calling-python-lambda-from-c-function | The question Is pybind11 somehow magically doing the work of PyGILState_Ensure() and PyGILState_Release()? And if not, how should I do it? More details There are many questions regarding passing a python function to C++ as a callback using pybind11, but I haven't found one that explains the use of the GIL with pybind11... | In general pybind11 tries to do the Right Thing and the GIL will be held when pybind11 knows that it is calling a python function, or in C++ code that is called from python via pybind11. The only time that you need to explicitly acquire the GIL when using pybind11 is when you are writing C++ code that accesses python a... | 11 | 13 |
72,844,458 | 2022-7-3 | https://stackoverflow.com/questions/72844458/mysql-to-mongodb-data-migration | We know that MongoDB has two ways of modeling relationships between relations/entities, namely, embedding and referencing (see difference here). Let's say we have a USER database with two tables in mySQL named user and address. An embedded MongoDB document might look like this: { "_id": 1, "name": "Ashley Peacock", "ad... | Denormalization First, for canonical reference, the question of "embedded" vs. "referenced" data is called denormalization. Mongo has a guide describing when you should denormalize. Knowing when and how to denormalize is a very common hang-up when moving from SQL to NoSQL and getting it wrong can erase any performance ... | 5 | 4 |
72,827,460 | 2022-7-1 | https://stackoverflow.com/questions/72827460/creating-google-credentials-object-for-google-drive-api-without-loading-from-fil | I am trying to create a google credentials object to access google drive. I have the tokens and user data stored in a session thus I am trying to create the object without loading them from a credentials.json file. I am handling the authentication when a user first logs in the web app and storing the tokens inside the ... | The object was build correctly, there was no issue with building the object this way access_token = request.session['access_token'] gCreds = GoogleCredentials( access_token, os.getenv('GOOGLE_CLIENT_ID'), os.getenv('GOOGLE_CLIENT_SECRET'), refresh_token=None, token_expiry=None, token_uri=GOOGLE_TOKEN_URI, user_agent='P... | 5 | 1 |
72,862,224 | 2022-7-4 | https://stackoverflow.com/questions/72862224/stripe-metadata-working-properly-but-not-showing-up-on-stripe-dashboard | I've implemented Stripe checkout on a Django app and it's all working correctly except that it's not showing up on the Stripe Dashboard, even though it's showing in the event data on the same page. Have I formatted it incorrectly or am I overlooking something obvious? This is how I added meta data: checkout_session = ... | The metadata field you set is for Checkout Session alone, but not on Payment Intent (which is the Dashboard page you are at). To have metadata shown at the Payment Intent, I'd suggest also setting payment_intent_data.metadata [0] in the request when creating a Checkout Session. For example, session = stripe.checkout.Se... | 5 | 12 |
72,876,190 | 2022-7-5 | https://stackoverflow.com/questions/72876190/rolling-windows-in-pandas-how-to-wrap-around-with-datetimeindex | I have a DataFrame where the index is a DatetimeIndex with a daily frequency. It contains 365 rows, one for each day of the year. When computing rolling sums, the first few elements are always NaN (as expected), but I'd like them to have actual values. For example, if using a rolling window of 3 samples, the value for ... | You're basically asking for a circular data object which has no start or end. Not sure that exists! The best work-around I can think of is to repeat the end of the series before the beginning. n = 3 rolling_fake_data = ( pd.concat([fake_data[-n:], fake_data]) ).rolling(n).sum()[n:] # Test assert(rolling_fake_data.loc["... | 5 | 2 |
72,874,936 | 2022-7-5 | https://stackoverflow.com/questions/72874936/how-to-split-a-row-into-two-rows-in-python-based-on-delimiter-in-python | I have the following input file in csv A,B,C,D 1,2,|3|4|5|6|7|8,9 11,12,|13|14|15|16|17|18,19 How do I split column C right in the middle into two new rows with additional column E where the first half of the split get "0" in Column E and the second half get "1" in Column E? A,B,C,D,E 1,2,|3|4|5,9,0 1,2,|6|7|8,9,1 11,... | Here's how to do it without Pandas: import csv with open("input.csv", newline="") as f_in, open("output.csv", "w", newline="") as f_out: reader = csv.reader(f_in) header = next(reader) # read header header += ["E"] # modify header writer = csv.writer(f_out) writer.writerow(header) for row in reader: a, b, c, d = row # ... | 4 | 3 |
72,873,986 | 2022-7-5 | https://stackoverflow.com/questions/72873986/functions-in-sas | I have a function that converts a value in one format to another. It's analogous to converting Fahrenheit to Celsius for example. Quite simply, the formula is: l = -log(20/x) I am inheriting SAS code from a colleague that has the following hardcoded for a range of values of x: "if x= 'a' then x=l;" which is obviously... | If you are interested in writing your own functions, as Joe said, proc fcmp is one way to do it. This will let you create functions that behave like SAS functions. It's about as analogous to Python functions as you'll get. It takes a small bit of setup, but it's really nice in that the functions are all saved in a SAS ... | 4 | 5 |
72,873,362 | 2022-7-5 | https://stackoverflow.com/questions/72873362/how-to-rotate-90-deg-of-2d-array-inside-3d-array | I have a 3D array consist of 2D arrays, I want to rotate only the 2D arrays inside the 3D array without changing the order, so it will become a 3D array consist of rotated 3D arrays. For example, I have a 3D array like this. foo = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) print(foo) >>> array([[[ 1,... | You can use numpy.rot90 by setting axes that you want to rotate. foo = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) rotated_foo = np.rot90(foo, axes=(2,1)) print(rotated_foo) Output: array([[[ 4, 1], [ 5, 2], [ 6, 3]], [[10, 7], [11, 8], [12, 9]]]) | 4 | 2 |
72,865,725 | 2022-7-5 | https://stackoverflow.com/questions/72865725/how-to-copy-both-folder-and-files-in-python | I am aware that using shutil.copy(src,dst) copies files and shutil.copytree(src,dst) is used for copying directories. Is there any way so I don't have to differentiate between copying folders and copying files? Tysm | You might want to take a look to this topic, where the same question was answered. https://stackoverflow.com/a/1994840/17595642 Functions can be written to do so. Here is the one implemented in the other topic : import shutil, errno def copyanything(src, dst): try: shutil.copytree(src, dst) except OSError as exc: # pyt... | 5 | 5 |
72,831,076 | 2022-7-1 | https://stackoverflow.com/questions/72831076/how-can-i-use-a-sequence-of-numbers-to-predict-a-single-number-in-tensorflow | I am trying to build a machine learning model which predicts a single number from a series of numbers. I am using a Sequential model from the keras API of Tensorflow. You can imagine my dataset to look something like this: Index x data y data 0 np.ndarray(shape (1209278,) ) numpy.float32 1 np.ndarray(shape (1... | Try something like this: import numpy as np import tensorflow as tf # add additional dimension for lstm layer x_train = np.asarray(train_set["x data"].values))[..., None] y_train = np.asarray(train_set["y data"]).astype(np.float32) model = tf.keras.Sequential() model.add(tf.keras.layers.LSTM(units=32)) model.add(tf.ker... | 6 | 3 |
72,866,716 | 2022-7-5 | https://stackoverflow.com/questions/72866716/pandas-how-to-get-the-postition-number-of-row-of-a-value | I have my pandas dataframe and i need to find the index of a certain value. But the thing is, this df does from an other one where i had to cut some part using the df.loc, so it ends up like : index value 1448 31776 1449 32088 1450 32400 1451 32712 1452 33024 Let's say i need to find the index of the value '32400', wi... | First idea is create default index starting by 0 by DataFrame.reset_index with drop=True: df = df.reset_index(drop=True) idx = df.index[df.value == 32400] print (idx) Int64Index([2], dtype='int64') Or use numpy - e.g. by numpy.where with condition for positions of match: idx = np.where(df.value == 32400)[0] print (idx... | 4 | 4 |
72,863,564 | 2022-7-5 | https://stackoverflow.com/questions/72863564/subtract-last-timestamp-from-first-timestamp-for-each-id-in-pandas-dataframe | I have a dataframe (df) with the following structure: retweet_datetime tweet_id tweet_datetime 2020-04-24 03:33:15 85053699 2020-04-24 02:28:22 2020-04-24 02:43:35 85053699 2020-04-24 02:28:22 2020-04-18 04:24:03 86095361 2020-04-18 00:06:01 2020-04-18 00:19:08 86095361 2020-04-18 00:06:01 2020-04-18 00... | Use named aggregation with subtract column with Series.sub, DataFrame.pop is used for drop column tmp after processing: df1 = (df.groupby('tweet_id', as_index=False) .agg(retweet_datetime=('retweet_datetime','first'), tmp = ('retweet_datetime','last'), tweet_datetime = ('tweet_datetime','last'))) df1['lifetime1'] = df1... | 3 | 4 |
72,850,849 | 2022-7-4 | https://stackoverflow.com/questions/72850849/need-help-speeding-up-numpy-code-that-finds-number-of-coincidences-between-two | I am looking for some help speeding up some code that I have written in Numpy. Here is the code: def TimeChunks(timevalues, num): avg = len(timevalues) / float(num) out = [] last = 0.0 while last < len(timevalues): out.append(timevalues[int(last):int(last + avg)]) last += avg return out ### chunk i can be called by out... | This is 17X faster and more correct using a custom made numba_histogram function that beats the generic np.histogram. Note that you are computing and comparing histograms of two different series separately, which is not accurate for your purpose. So, in my numba_histogram function I use the same bin edges to compute th... | 5 | 3 |
72,852,853 | 2022-7-4 | https://stackoverflow.com/questions/72852853/how-to-efficiently-find-pairs-of-numbers-where-the-square-of-one-equals-the-cube | I need to find the pairs (i,j) and number of pairs for a number N such that the below conditions are satisfied: 1 <= i <= j <= N and also i * i * i = j * j. For example, for N = 50, number of pairs is 3 i.e., (1,1), (4,8), (9,27). I tried the below function code but it takes too much time for a large number like N = 10... | Let k be the square root of some integer i satisfying i*i*i == j*j, where j is also an integer. Since k is the square root of an integer, k*k is integer. From the equation, we can solve that j is equal to k*k*k, so that is also an integer. Since k*k*k is an integer and k*k is an integer, it follows by dividing these tw... | 3 | 7 |
72,860,558 | 2022-7-4 | https://stackoverflow.com/questions/72860558/import-module-error-when-building-a-docker-container-with-python-for-aws-lambda | I'm trying to build a Docker container that runs Python code on AWS Lambda. The build works fine, but when I test my code, I get the following error: {"errorMessage": "Unable to import module 'function': No module named 'utils'", "errorType": "Runtime.ImportModuleError", "stackTrace": []} I basically have two python s... | The Dockerfile statement COPY . . copies all files to the working directory, which given your previous WORKDIR, is /. To resolve the Python import issue, you need to move the Python module to the right directory: COPY utils.py ${LAMBDA_TASK_ROOT} | 7 | 2 |
72,825,203 | 2022-7-1 | https://stackoverflow.com/questions/72825203/how-to-set-up-properly-package-data-in-setup-py | I am facing an error like No such file or directory.... Could anyone help me with this out? I'd really appreciate it! This is the directory: And this is the setup.py code: from setuptools import setup setup( name='raw-microsoft-wwi', version='1.0.0', package_dir={"":"src"}, packages=[ "raw_microsoft_wwi", "raw_microso... | Setuptools expects package_data to be a dictionary mapping from Python package names to a list of file name patterns. This means that the keys in the dictionary should be similar to the values you listed in the packages configuration (instead of paths). I think you can try the following: Add the missing raw_microsoft_... | 4 | 5 |
72,858,984 | 2022-7-4 | https://stackoverflow.com/questions/72858984/mkl-service-package-failed-to-import-therefore-intelr-mkl-initialization-ensu | When I go to run a python code directly through the terminal it gives me this error, I've already tried to reinstall numpy and it didn't work! And I tried to install mlk service returns the same error. Can someone help me ? UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensurin... | Can be solved by resetting package configuration by force reinstall of numpy. conda install numpy --force-reinstall | 8 | 8 |
72,858,633 | 2022-7-4 | https://stackoverflow.com/questions/72858633/detect-mouse-scroll | How do I detect Mouse scroll up and down in python using pygame? I have created a way to detect it, but it doesn't give me any information about which way I scrolled the mouse as well as being terrible at detecting mouse scrolls where only 1 in 20 are getting detected. for event in pygame.event.get(): if event.type == ... | The MOUSEWHEEL event object has x and y components (see pygame.event module). These components indicate the direction in which the mouse wheel was rotated (for horizontal and vertical wheel): for event in pygame.event.get(): if event.type == pygame.MOUSEWHEEL: print(event.x, event.y) | 9 | 10 |
72,851,576 | 2022-7-4 | https://stackoverflow.com/questions/72851576/corner-detection-in-opencv | I was trying to detect all the corners in the image using harris corner detection in opencv(python). But due to the thickness of the line , I am getting multiple corners in a single corner . Is there something I can do to make this right. code import numpy as np import cv2 as cv filename = 'Triangle.jpg' img = cv.imrea... | If your expectation is to obtain a single corner point at every line intersection, then the following is a simple approach. Current scenario: # visualize the corners mask = np.zeros_like(gray) mask[dst>0.01*dst.max()] = 255 In the above, there are many (supposedly) corner points close to each other. Approach: The ide... | 5 | 2 |
72,854,648 | 2022-7-4 | https://stackoverflow.com/questions/72854648/generic-detection-of-subimages-in-images-with-opencv | Disclaimer: I'm a computer vision rookie. I have seen a lot of stack overflow posts of how to find a specific sub-image in a larger image. My usecase is a bit different since I don't want it to be specific and I'm not sure how I can do this (if it's even possible, but I have a feeling it should). I have a large dataset... | Use cv.Sobel or other derivative kernel (with cv.filter2D) to find edges Sum along pixel columns to score each for "edginess". np.sum or np.mean do that. Some thresholding and np.argsort and indexing to find best candidates. cut (take slices out of array) edge map: edgy plot: slices to take: array([[ 0, 578], [ 578... | 4 | 3 |
72,852,694 | 2022-7-4 | https://stackoverflow.com/questions/72852694/why-do-i-get-the-loop-of-ufunc-does-not-support-argument-0-of-type-numpy-ndarra | First, I used np.array to perform operations on multiple matrices, and it was successful. import numpy as np import matplotlib.pyplot as plt f = np.array([[0.35, 0.65]]) e = np.array([[0.92, 0.08], [0.03, 0.97]]) r = np.array([[0.95, 0.05], [0.06, 0.94]]) d = np.array([[0.99, 0.01], [0.08, 0.92]]) c = np.array([[0, 1],... | You can't create a batch of matrices e from the variable t using the construct e = np.array([[1-t, t], [0.03, 0.97]]) as this would create a ragged array due to [1-t, t] and [0.03, 0.97] having different shapes. Instead, you can create e by repeating [0.03, 0.97] to match the shape of [1-t, t], then stack them togethe... | 4 | 2 |
72,847,737 | 2022-7-3 | https://stackoverflow.com/questions/72847737/sqlalchemy-session-commit-exception-handing-with-rollback | I am trying to figure out the preferred way to manage session if exceptiion occurs while doing operation or committing the session. But a few examples in the document confuses me a little bit. The doc says to frame out a commit/rollback block, you can do something like this: # verbose version of what a context manager ... | Both examples accomplish nearly the same thing. The transaction will be committed if there is no error, and rolled back if there is an error. The difference is that if there is an exception on the commit itself, the second example will roll back. It's uncommon to get an exception on the commit, but it's possible. | 4 | 3 |
72,846,862 | 2022-7-3 | https://stackoverflow.com/questions/72846862/unable-to-assert-length-of-list-with-pytest | I am learning Python and I'm using Pytest to check my code as I learn. Here is some sample code I have running: str = "I love pizza" str_list = list(str) print(str_list) print(len(str_list)) With expected result printed to stdout: ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'z', 'z', 'a'] 12 But if I run this test:... | Try making method name and test file starts with test_ | 3 | 6 |
72,845,828 | 2022-7-3 | https://stackoverflow.com/questions/72845828/priority-of-tuple-unpacking-with-inline-if-else | Apologies in advance for the obscure title. I wasn't sure how to phrase what I encountered. Imagine that you have a title of a book alongside its author, separated by -, in a variable title_author. You scraped this information from the web so it might very well be that this item is None. Obviously you would like to sep... | title, author = title_author.split("-", 1) if title_author else None, None is the same as: title, author = (title_author.split("-", 1) if title_author else None), None Therefore, author is always None Explaination: From official doc An assignment statement evaluates the expression list (remember that this can be a ... | 4 | 4 |
72,836,985 | 2022-7-2 | https://stackoverflow.com/questions/72836985/ipython-passwd-not-able-to-import-with-new-2022-anaconda-download | I am simply trying to do this from IPython.lib import passwd but I get this error In [1]: from IPython.lib import passwd --------------------------------------------------------------------------- ImportError Traceback (most recent call last) Input In [1], in <cell line: 1>() ----> 1 from IPython.lib import passwd Impo... | I am facing the same issue with IPython version 8.4. It seems to me that the security lib is not present anymore. If you are using version 7x you should be able to import it with from IPython.lib.security import passwd as denoted in https://ipython.readthedocs.io/en/7.x/api/generated/IPython.lib.security.html?highligh... | 5 | 6 |
72,845,443 | 2022-7-3 | https://stackoverflow.com/questions/72845443/branching-in-apache-airflow-using-taskflowapi | I can't find the documentation for branching in Airflow's TaskFlowAPI. I tried doing it the "Pythonic" way, but when ran, the DAG does not see task_2_execute_if_true, regardless of truth value returned by the previous task. @dag( schedule_interval=None, start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), catchup=False,... | There's an example DAG in the source code: https://github.com/apache/airflow/blob/f1a9a9e3727443ffba496de9b9650322fdc98c5f/airflow/example_dags/example_branch_operator_decorator.py#L43. The syntax is: from airflow.decorators import task @task.branch(task_id="branching_task_id") def random_choice(): return "task_id_to_r... | 4 | 6 |
72,842,563 | 2022-7-2 | https://stackoverflow.com/questions/72842563/how-to-activate-a-python-virtual-environment-automatically-on-login | I have a Python virtual environment named venv in the user home directory. I would like to activate this virtual environment on login. I don't want to type source venv/bin/activate each time after login. I want to type python something.py and have it always use the virtual environment. How can I do this in the user's l... | There might be better ways of doing this but the simplest way I can think of is modifying .bashrc file if you are using an OS Like Ubuntu. In your .bashrc file you can add a line to start your virtual environment. An example could be adding the following to the bottom of your .bashrc file: source myvenv/bin/activate | 5 | 6 |
72,818,247 | 2022-6-30 | https://stackoverflow.com/questions/72818247/streamlit-config-toml-file-not-changing-the-theme-of-the-web-app | I would like to change the theme of my streamlit application that I am working on. I read that I should make a directory called .streamlit/ with a file called config.toml, after creating the .toml file, it does not update the appearance of my web application. Here is the link to the app itself: https://jensen-holm-spor... | I just ran into the same problem. What I found out is that I had selected the "Dark" option via the hamburger menu at some point before creating the custom config file in the project directory. If you've done the same, the default order of precedence is overwritten and that choice is preserved. Otherwise, the default p... | 4 | 6 |
72,840,669 | 2022-7-2 | https://stackoverflow.com/questions/72840669/append-only-if-item-isnt-already-appended | In my Python application, I have the following lines: for index, codec in enumerate(codecs): for audio in filter(lambda x: x['hls']['codec_name'] == codec, job['audio']): audio['hls']['group_id'].append(index) How can I only trigger the append statement if the index hasn't been already appended previously? | Simply test if your index not in your list: for index, codec in enumerate(codecs): for audio in filter(lambda x: x['hls']['codec_name'] == codec, job['audio']): if index not in audio['hls']['group_id']: audio['hls']['group_id'].append(index) | 5 | 3 |
72,839,263 | 2022-7-2 | https://stackoverflow.com/questions/72839263/access-python-interpreter-in-vscode-version-controll-when-using-pre-commit | I'm using pre-commit for most of my Python projects, and in many of them, I need to use pylint as a local repo. When I want to commit, I always have to activate python venv and then commit; otherwise, I'll get the following error: black....................................................................Passed pylint...... | you have ~essentially two options here -- neither are great (language: system is kinda the unsupported escape hatch so it's on you to make those things available on PATH) you could use a specific path to the virtualenv entry: venv/bin/pylint -- though that will reduce the portability. or you could start vscode with you... | 10 | 8 |
72,804,712 | 2022-6-29 | https://stackoverflow.com/questions/72804712/how-to-accelerate-numpy-unique-and-provide-both-counts-and-duplicate-row-indices | I am attempting to find duplicate rows in a numpy array. The following code replicates the structure of my array which has n rows, m columns, and nz non-zero entries per row: import numpy as np import random import datetime def create_mat(n, m, nz): sample_mat = np.zeros((n, m), dtype='uint8') random.seed(42) for row i... | Step 1: bit packing Since your matrix only contains binary values, you can aggressively pack the bits into uint64 values so to perform a much more efficient sort then. Here is a Numba implementation: import numpy as np import numba as nb @nb.njit('(uint8[:,::1],)', parallel=True) def pack_bits(mat): n, m = mat.shape re... | 8 | 8 |
72,831,952 | 2022-7-1 | https://stackoverflow.com/questions/72831952/how-do-i-integrate-custom-exception-handling-with-the-fastapi-exception-handling | Python version 3.9, FastAPI version 0.78.0 I have a custom function that I use for application exception handling. When requests run into internal logic problems, i.e I want to send an HTTP response of 400 for some reason, I call a utility function. @staticmethod def raise_error(error: str, code: int) -> None: logger.e... | Your custom exception can have any custom attributes that you want. Let's say you write it this way: class ExceptionCustom(HTTPException): pass in your custom handler, you can do something like def exception_404_handler(request: Request, exc: HTTPException): return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, c... | 8 | 11 |
72,817,748 | 2022-6-30 | https://stackoverflow.com/questions/72817748/scipy-has-no-attribute-signal | I have a file which imports a function from another file, like shown below. file1.py: # import scipy.signal import file2 file2.foo() file2.py: import scipy def foo(): scipy.signal.butter(2, 0.01, 'lowpass', analog=False) When I run file1.py I get the following error: File "file2.py", line 5, in foo scipy.signal.butt... | With scipy, you need to import the submodule directly with either import scipy.signal or from scipy import signal. Many submodule won't work if you just import scipy. You can read about the scipy api here | 4 | 7 |
72,827,704 | 2022-7-1 | https://stackoverflow.com/questions/72827704/how-to-customize-ttk-checkbutton-colors | I am looking for a way to change the background color (and the active color) of the tickbox of the ttk.Checkbutton Optimally, the background color of the box should match the background's color? What is the command to modify this in the style.configure() method? | It is possible to change the colors of the tickbox using the options indicatorbackground and indicatorforeground. style.configure("TCheckbutton", indicatorbackground="black", indicatorforeground="white", background="black", foreground="white") To change the active colors, you need to use style.map() instead of style.c... | 3 | 6 |
72,824,468 | 2022-7-1 | https://stackoverflow.com/questions/72824468/pip-installing-environment-yml-as-if-its-a-requirements-txt | I have an environment.yml file, but don't want to use Conda: name: foo channels: - defaults dependencies: - matplotlib=2.2.2 Is it possible to have pip install the dependencies inside an environment.yml file as if it's a requirements.txt file? I tried pip install -r environment.yml and it doesn't work with pip==22.1.2... | No, pip does not support this format. The format it expects for a requirements file is documented here. You'll have to convert the environment.yml file to a requirements.txt format either manually or via a script that automates this process. However, keep in mind that not all packages on Conda will be available on PyPI... | 19 | 7 |
72,819,980 | 2022-6-30 | https://stackoverflow.com/questions/72819980/python-selenium-beta-chrome-driver-uses-wrong-binary-path | I'm currently switching from chrome 102 to 104 Beta (since 103 has an unfixed error for my use case with a python - selenium script) I installed the Chrome Beta 104 + the 104 chrome driver. When I start up the script it recognizes that it's a 104 driver but the driver itself searches for the chrome.exe application with... | In that case, you should specify where selenium has to look to find your chrome executer with binary_location inside the Options class. Try this one out: Assuming your chromedriver.exe and python file are on the same folder, otherwise you'll have to specify the path of the chromedriver.exe as well. from selenium import... | 3 | 6 |
72,813,077 | 2022-6-30 | https://stackoverflow.com/questions/72813077/can-i-insert-a-table-name-by-using-a-query-parameter | I have an SQL Alchemy engine where I try to insert parameters via sqlalchemy.sql.text to protect against SQL injection. The following code works, where I code variables for the condition and conditions values. from sqlalchemy import create_engine from sqlalchemy.sql import text db_engine = create_engine(...) db_engine.... | Any ideas why this does not work? Query parameters are used to supply the values of things (usually column values), not the names of things (tables, columns, etc.). Every database I've seen works that way. So, despite the ubiquitous advice that dynamic SQL is a "Bad Thing", there are certain cases where it is simply ... | 8 | 9 |
72,805,719 | 2022-6-29 | https://stackoverflow.com/questions/72805719/bytesio-downloading-file-object-from-s3-but-bytestream-is-empty | See update at bottom - question slightly changed I'm trying to download a file from s3 to a file-like object using boto3's .download_fileobj method, however when I try to inspect the downloaded bytestream, it's empty. I'm not sure what I'm doing wrong however: client = boto3.client('s3') data = io.BytesIO() client.down... | Thank you for this, I was running into the same problem. :o) The reason this works is that file buffer objects work with an internal pointer to the current spot to read from or write to. This is important when you pass the read() method a number of bytes to read, or to continually write to the next section of the file.... | 8 | 8 |
72,816,567 | 2022-6-30 | https://stackoverflow.com/questions/72816567/how-to-select-rows-in-pandas-dataframe-based-on-between-from-another-column | I have a dataframe organised like so: x y e A 0 0.0 1.0 0.01 1 0.1 0.9 0.03 2 0.2 1.3 0.02 ... B 0 0.0 0.5 0.02 1 0.1 0.6 0.02 2 0.2 0.9 0.04 ... etc. I would like to select rows of a A/B/etc. that fall between certain values in x. This, for example, works: p,q=0,1 indices=df.loc[("A"),"x"].between(p,q) df.loc[("A"),... | You can merge your 2 lines of code by using a lambda function. >>> df.loc['A'].loc[lambda A: A['x'].between(p, q), 'y'] 1 0.9 2 1.3 Name: y, dtype: float64 The output of your code: indices=df.loc[("A"),"x"].between(p,q) output=df.loc[("A"),"y"][indices] print(output) # Output 1 0.9 2 1.3 Name: y, dtype: float64 | 4 | 2 |
72,813,425 | 2022-6-30 | https://stackoverflow.com/questions/72813425/order-of-execution-for-multiple-contextmanagers-in-python | I couldn't find the answer for this question maybe someone could help me please? Is the order of execution defined in case of using two contexts like that? with open('a.txt', 'w') as f1, open('b.txt', 'w') as f2: <some operation> Am I guaranteed that the first context (here opening 'a.txt') will be executed before se... | According to the language reference: with A() as a, B() as b: SUITE is semantically equivalent to: with A() as a: with B() as b: SUITE So yes, since A() will execute before the body is executed. | 4 | 4 |
72,809,395 | 2022-6-30 | https://stackoverflow.com/questions/72809395/pandas-how-can-i-move-certain-columns-into-rows | Suppose I have the df below. I would like to combine the price columns and value columns so that all prices are in one column and all volumes are in another column. I would also like a third column that identified the price level. For example, unit1, unit2 and unit3. import numpy as np import pandas as pd df = pd.DataF... | You can form two dataframe using pd.melt first and combine it back to become one dataframe. df1 = df.melt(id_vars=['uid', 'location'], value_vars=['unit1_price', 'unit2_price', 'unit3_price'],var_name='unit',value_name='price') df2 = df.melt(id_vars=['uid', 'location'], value_vars=['unit1_vol', 'unit2_vol', 'unit3_vol'... | 12 | 3 |
72,799,623 | 2022-6-29 | https://stackoverflow.com/questions/72799623/xticks-different-interval | How do i set xticks to 'a different interval' For instance: plt.plot(1/(np.arange(0.1,3,0.1))) returns: If I would like the x axis to be on a scale from 0 to 3, how can i do that? I've tried plt.xticks([0,1,2]) but that returns: | You want to learn about plt.xlim and adjacent functions. This causes the X axis to have limits (minimum, maximum) that you specify. Otherwise Matplotlib decides for you based on the values you try to plot. y = 1 / np.arange(0.1,3,0.1) plt.plot(y) plt.xlim(0, 3) # minimum 0, maximum 3 plt.show() Your plot uses only Y ... | 4 | 1 |
72,794,939 | 2022-6-29 | https://stackoverflow.com/questions/72794939/how-to-quickly-identify-if-a-rule-in-snakemake-needs-an-input-function | I'm following the snakemake tutorial on their documentation page and really got stuck on the concept of input functions https://snakemake.readthedocs.io/en/stable/tutorial/advanced.html#step-3-input-functions Basically they define a config.yaml as follows: samples: A: data/samples/A.fastq B: data/samples/B.fastq and t... | SultanOrazbayev has a good answer already. Here's another typical example. Often, the input and output files share the same pattern (wildcards). For example, if you want to sort a file you may do: input: {name}.txt -> output: {name}.sorted.txt. Sometimes however the input files are not linked to the output by a simple ... | 3 | 4 |
72,803,062 | 2022-6-29 | https://stackoverflow.com/questions/72803062/converting-a-dictionary-of-lists-to-a-pandas-dataframe-using-predefined-headers | I have a dictionary that looks like the following: date_pair_dict = { "15-02-2022 15-02-2022": ["key 1 val 1", "key 1 val 2", "key 1 val 3"], "15-02-2022 16-02-2022": ["key 2 val 1", "key 2 val 2", "key 2 val 3"], "16-02-2022 16-02-2022": ["key 3 val 1", "key 3 val 2", "key 3 val 3"], "16-02-2022 17-02-2022": ["key 4 v... | Like you said you can use a comprehension on your dict key/value pairs: import pandas as pd date_pair_dict = { "15-02-2022 15-02-2022": ["key 1 val 1", "key 1 val 2", "key 1 val 3"], "15-02-2022 16-02-2022": ["key 2 val 1", "key 2 val 2", "key 2 val 3"], "16-02-2022 16-02-2022": ["key 3 val 1", "key 3 val 2", "key 3 va... | 4 | 3 |
72,801,110 | 2022-6-29 | https://stackoverflow.com/questions/72801110/sorting-a-list-of-chromosomes-in-the-correct-order | A seemingly simple problem, but one that's proving a bit vexing. I have a list of chromosomes (there are 23 chromosome - chromosomes 1 to 21, then chromosome X and chromosome Y) like so: ['chr11','chr14','chr16','chr13','chr4','chr13','chr2','chr1','chr2','chr3','chr14','chrX',] I would like to sort this in the followi... | You can use natsorted, what you want is natural sorting after all ;) l = ['chr11','chr14','chr16','chr13','chr4','chr13','chr2', 'chr1','chr2','chr3','chr14','chrX','chrY'] from natsort import natsorted out = natsorted(l) output: ['chr1', 'chr2', 'chr2', 'chr3', 'chr4', 'chr11', 'chr13', 'chr13', 'chr14', 'chr14', 'ch... | 5 | 7 |
72,798,967 | 2022-6-29 | https://stackoverflow.com/questions/72798967/how-to-ignore-some-errors-with-sentry-not-to-send-them | I have a project based on django (3.2.10) and sentry-sdk (1.16.0) There is my sentry-init file: from os import getenv SENTRY_URL = getenv('SENTRY_URL') if SENTRY_URL: from sentry_sdk import init from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.redis import RedisIntegration from ... | You can pass a function that filters the errors to be sent: from os import getenv SENTRY_URL = getenv('SENTRY_URL') if SENTRY_URL: from sentry_sdk import init from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.redis import RedisIntegration from sentry_sdk.integrations.celery impor... | 4 | 3 |
72,796,680 | 2022-6-29 | https://stackoverflow.com/questions/72796680/numpy-valueerror-cannot-convert-float-nan-to-integer-python | I want to insert NaN at specific locations in A. However, there is an error. I attach the expected output. import numpy as np from numpy import NaN A = np.array([10, 20, 30, 40, 50, 60, 70]) C=[2,4] A=np.insert(A,C,NaN,axis=0) print("A =",[A]) The error is <module> A=np.insert(A,C,NaN,axis=0) File "<__array_function__... | Designate a type for your array of float32 (or float16, float64, etc. as appropriate) import numpy as np A = np.array([10, 20, 30, 40, 50, 60, 70], dtype=np.float32) C=[2,4] A=np.insert(A,C,np.NaN,axis=0) print("A =",[A]) A = [array([10., 20., nan, 30., 40., nan, 50., 60., 70.], dtype=float32)] | 4 | 4 |
72,796,364 | 2022-6-29 | https://stackoverflow.com/questions/72796364/how-to-convert-dictionary-to-pandas-dataframe-in-python-when-dictionary-value-is | I want to convert Python dictionary into DataFrame. Dictionary value is a List with different length. Example: import pandas as pd data = {'A': [1], 'B': [1,2], 'C': [1,2,3]} df = pd.DataFrame.from_dict(data) But, the above code doesn't work with the following error: ValueError: All arrays must be of the same length ... | You can use: df = pd.DataFrame({'name':data.keys(), 'value':data.values()}) print (df) name value 0 A [1] 1 B [1, 2] 2 C [1, 2, 3] df = pd.DataFrame(data.items(), columns=['name','value']) print (df) name value 0 A [1] 1 B [1, 2] 2 C [1, 2, 3] Also working Series: s = pd.Series(data) print (s) A [1] B [1, 2] C [1, 2... | 5 | 10 |
72,750,043 | 2022-6-24 | https://stackoverflow.com/questions/72750043/add-timedelta-to-a-date-column-above-weeks | How would I add 1 year to a column? I've tried using map and apply but I failed miserably. I also wonder why pl.date() accepts integers while it advertises that it only accepts str or pli.Expr. A small hack workaround is: col = pl.col('date').dt df = df.with_columns(pl.when(pl.col(column).is_not_null()) .then(pl.date(c... | Polars allows to do addition and subtraction with python's timedelta objects. However above week units things get a bit more complicated as we have to take different days of the month and leap years into account. For this polars has offset_by under the dt namespace. (pl.DataFrame({ "dates": pl.datetime_range(pl.datetim... | 5 | 6 |
72,720,235 | 2022-6-22 | https://stackoverflow.com/questions/72720235/requirements-txt-for-pytorch-for-both-cpu-and-gpu-platforms | I am trying to create a requirements.txt to use pytorch but would like it to work on both GPU and non-GPU platforms. I do something like on my Linux GPU system: --find-links https://download.pytorch.org/whl/cu113/torch_stable.html torch==1.10.2+cu113 torchvision==0.11.3+cu113 pytorch-lightning==1.5.10 This works fine ... | February 2024 update Check https://pytorch.org/. You will see that "CUDA is not available on MacOS, please use default package". However, you can still get performance boosts (this will depend on your hardware) by installing the MPS accelerated version of pytorch by: # MPS acceleration is available on MacOS 12.3+ pip3 ... | 5 | 7 |
72,773,206 | 2022-6-27 | https://stackoverflow.com/questions/72773206/selenium-python-attributeerror-webdriver-object-has-no-attribute-find-el | I am trying to get Selenium working with Chrome, but I keep running into this error message (and others like it): AttributeError: 'WebDriver' object has no attribute 'find_element_by_name' The same problem occurs with find_element_by_id(), find_element_by_class(), etc. I also could not call send_keys(). I am just run... | Selenium just removed that method in version 4.3.0. See the CHANGES: https://github.com/SeleniumHQ/selenium/blob/a4995e2c096239b42c373f26498a6c9bb4f2b3e7/py/CHANGES Selenium 4.3.0 * Deprecated find_element_by_* and find_elements_by_* are now removed (#10712) * Deprecated Opera support has been removed (#10630) * Fully ... | 135 | 194 |
72,774,135 | 2022-6-27 | https://stackoverflow.com/questions/72774135/how-to-type-hint-a-staticmethodabstractmethodproperty-using-mypy-in-python | Given this code: from abc import ABC, abstractmethod from typing import TYPE_CHECKING class Foo(ABC): @property @staticmethod @abstractmethod def name() -> str: pass class Bar(Foo): name = "bar" class Baz(Foo): name = "baz" instances = [Bar(), Baz()] print(instances[0].name) if TYPE_CHECKING: reveal_type(instances[0].n... | Python 3.11 disallowed wrapping of @property using class decorators such as @classmethod and @staticmethod (see GH#89519). This means the provided snippet shouldn't be considered as valid Python code, and latest versions of Mypy actually warns about it: main.py:6: error: Only instance methods can be decorated with @pro... | 4 | 0 |
72,779,926 | 2022-6-28 | https://stackoverflow.com/questions/72779926/gunicorn-cuda-cannot-re-initialize-cuda-in-forked-subprocess | I am creating an inference service with torch, gunicorn and flask that should use CUDA. To reduce resource requirements, I use the preload option of gunicorn, so the model is shared between the worker processes. However, this leads to an issue with CUDA. The following code snipped shows a minimal reproducing example: f... | Reason for the Error As correctly stated in the comments by @Newbie, the issue isn't the model itself, but the CUDA context. When new child processes are forked, the parent's memory is shared read-only with the child, but the CUDA context doesn't support this sharing, it must be copied to the child. Hence, it reports a... | 22 | 14 |
72,710,857 | 2022-6-22 | https://stackoverflow.com/questions/72710857/figure-show-works-only-for-figures-managed-by-pyplot | There's bug reported about using matplotlib.pyplot for matplotlib 3.5.1, so I am trying to use matplotlib.figure.Figure to draw figure and it work fine. How can I view the graph in matplotlib for the Figure when I cannot call plt.show? Calling fig.show will give the following exception: Traceback (most recent call last... | It's not clear if your final goal is: simply to use fig.show() or to use fig.show() specifically with a raw Figure() object 1. If you simply want to use fig.show() Then the first code block with plt.subplots() will work just fine by replacing plt.show() with fig.show(): fig, ax = plt.subplots(figsize=(5, 4)) # if yo... | 5 | 2 |
72,782,100 | 2022-6-28 | https://stackoverflow.com/questions/72782100/for-loop-in-c-vs-for-loop-in-python | I was writing a method that would calculate the value of e^x. The way I implemented this in python was as follows. import math def exp(x): return sum([ x**n/math.factorial(n) for n in range(0, 100) ]) This would return the value of e^x very well. But when I tried to implement the same method in c#, it didn't output th... | What you're likely running into here is integer overflow with the C# version of the Factorial function (at least your implementation of it, or wherever its coming from). In C#, an int is a numerical type stored in 32 bits of memory, which means it's bounded by -2^31 <= n <= 2^31 - 1 which is around +/- 2.1 billion. You... | 14 | 20 |
72,729,999 | 2022-6-23 | https://stackoverflow.com/questions/72729999/python-is-it-a-good-practice-to-rely-on-import-to-execute-code | In Python, is it a good practice to rely on import to execute code, like in the example below? The code in mod.py is supposed to load some config, and needs to be executed once only. It can use more complex logic, but its purpose is to establish values of some parameters, later used as configuration by main.py. # --- m... | Defining things in an additional module is perfectly fine - variables, classes, functions etc. When the module is imported, as long as you don't use from ... import * your namespace does not get cluttered and you can extract a standalone and/or repeated fragments to have cleaner code. It's pretty much an intended use f... | 6 | 9 |
72,712,342 | 2022-6-22 | https://stackoverflow.com/questions/72712342/how-to-use-pyupdater | I Have a main.py file for my Tkinter app. I export it to a standalone.exe with Pyinstaller. I want that when I start the .exe to update the .exe if a new version was deployed in the directory where I export my program. Apparently we can do that with PyUpdater but I didn't find how on StackOverflow. | If you're trying to push updates/patches to a frozen python program, read this explanation in the PyUpdater documentation. Instead of attempting make your app auto-update (i.e. push updates to frozen apps) a much more straightforward approach would be to use Inno Setup. | 5 | 0 |
72,777,873 | 2022-6-27 | https://stackoverflow.com/questions/72777873/how-to-add-multiple-embedded-images-to-an-email-in-python | This question is really a continuation of this answer https://stackoverflow.com/a/49098251/19308674. I'm trying to add multiple embedded images (not just one) to the email content. I want to do it in a way that I loop through a list of images, in addition, there will be different text next to each image. Something like... | If I'm able to guess what you are trying to ask, the solution is simply to generate a unique cid for each image. from email.message import EmailMessage from email.utils import make_msgid # import mimetypes msg = EmailMessage() msg["Subject"] = "Hello there" msg["From"] = "ABCD <abcd@example.com>" msg["To"] = "PQRS <pqr... | 4 | 7 |
72,781,458 | 2022-6-28 | https://stackoverflow.com/questions/72781458/how-do-i-wait-for-ray-on-actor-class | I am developing Actor class and ray.wait() to collect the results. Below is the code and console outputs which is collecting the result for only 2 Actors when there are 3 Actors. import time import ray @ray.remote class Tester: def __init__(self, param): self.param = param def run(self): return self.param params = [0,1... | The script you provided is using ray.wait incorrectly. The following code does what you want: import time import ray @ray.remote class Tester: def __init__(self, param): self.param = param def run(self): return self.param params = [0, 1, 2] # I use list comprehensions instead of for loops for terseness. testers = [Test... | 4 | 2 |
72,753,582 | 2022-6-25 | https://stackoverflow.com/questions/72753582/virtualenv-cannot-find-newly-installed-python-version | I'm running Ubuntu 20.04 and I want to start a project using Python 3.10. I used an install guide for Python 3.10 (this one), installed it using the deadsnakes PPA, and that was fine: $ python3.10 Python 3.10.5 (main, Jun 11 2022, 16:53:24) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more ... | I was running into the same issue with a fresh python3.7 install. I managed to fix it by installing distutils. sudo apt-get install python3.7-distutils | 5 | 7 |
72,766,397 | 2022-6-27 | https://stackoverflow.com/questions/72766397/abbreviation-similarity-between-strings | I have a use case in my project where I need to compare a key-string with a lot many strings for similarity. If this value is greater than a certain threshold, I consider those strings "similar" to my key and based on that list, I do some further calculations / processing. I have been exploring fuzzy matching string si... | You can use a recursive algorithm, similar to sequence alignment. Just don't give penalty for shifts (as they are expected in abbreviations) but give one for mismatch in first characters. This one should work, for example: def abbreviation(abr,word,penalty=1): if len(abr)==0: return 0 elif len(word)==0: return penalty*... | 7 | 0 |
72,719,556 | 2022-6-22 | https://stackoverflow.com/questions/72719556/how-to-add-virtualenv-to-pythonnet | I am not able to load a virtual environment I have using virtual-env in the same directory as the C# file. Here is my code var eng = IronPython.Hosting.Python.CreateEngine(); var scope = eng.CreateScope(); // Load Virtual Env ICollection<string> searchPaths = eng.GetSearchPaths(); searchPaths.Add(@"/Users/Desktop/CShar... | You may need to try this way of setting up the PythonEngine.PythonPath: string pathToVirtualEnv = /path/to/venv/; var path = Environment.GetEnvironmentVariable("PATH").TrimEnd(';'); path = string.IsNullOrEmpty(path) ? pathToVirtualEnv : path + ";" + pathToVirtualEnv; Environment.SetEnvironmentVariable("PATH", path, Env... | 6 | 2 |
72,756,419 | 2022-6-25 | https://stackoverflow.com/questions/72756419/mypy-incompatible-type-for-virtual-class-inheritance | Demo code #!/usr/bin/env python3 from abc import ABCMeta, abstractmethod class Base(metaclass = ABCMeta): @classmethod def __subclasshook__(cls, subclass): return ( hasattr(subclass, 'x') ) @property @abstractmethod def x(self) -> float: raise NotImplementedError class Concrete: x: float = 1.0 class Application: def __... | Result After running some tests and more research i am sure, that the actual problem is the behaviour of Protocol to silently overwrite the defined __init__ method. Conclusion Seems logical, since Protocols are not intended to be initiated. But sometimes it's required to define an __init__ method, because in my opinion... | 6 | 0 |
72,753,255 | 2022-6-25 | https://stackoverflow.com/questions/72753255/how-to-detect-the-amount-of-almost-repetition-in-a-text-file | I am a programming teacher, and I would like to write a script that detects the amount of repetition in a C/C++/Python file. I guess I can treat any file as pure text. The script's output would be the number of similar sequences that repeat. Eventually, I am only interested in a DRY's metric (how much the code satisfie... | I would build a system based on compressibility, because that is essentially what things being repeated means. Modern compression algorithms are already looking for how to reduce repetition, so let's piggy back on that work. Things that are similar will compress well under any reasonable compression algorithm, eg LZ. ... | 9 | 4 |
72,790,002 | 2022-6-28 | https://stackoverflow.com/questions/72790002/improve-performance-of-combinations | Hey guys I have a script that compares each possible user and checks how similar their text is: dictionary = { t.id: ( t.text, t.set, t.compare_string ) for t in dataframe.itertuples() } highly_similar = [] for a, b in itertools.combinations(dictionary.items(), 2): if a[1][2] == b[1][2] and not a[1][1].isdisjoint(b[1]... | It is slightly complicated to reason about the data since you have not attached it, but we can see multiple places that might provide an improvement: First, let's rewrite the code in a way which is easier to reason about than using the indices: dictionary = { t.id: ( t.text, t.set, t.compare_string ) for t in datafram... | 5 | 4 |
72,783,608 | 2022-6-28 | https://stackoverflow.com/questions/72783608/creating-tensorflow-dataset-for-mulitple-time-series | I have a multiple time series data that looks something like this: df = pd.DataFrame({'Time': np.tile(np.arange(5), 2), 'Object': np.concatenate([[i] * 5 for i in [1, 2]]), 'Feature1': np.random.randint(10, size=10), 'Feature2': np.random.randint(10, size=10)}) Time Object Feature1 Feature2 0 0 1 3 3 1 1 1 9 2 2 2 1 6 ... | Hmm, maybe just create two separate dataframes and then concatenate after windowing. That way, you will not have any overlapping: import tensorflow as tf import pandas as pd import numpy as np df = pd.DataFrame({'Time': np.tile(np.arange(5), 2), 'Object': np.concatenate([[i] * 5 for i in [1, 2]]), 'Feature1': np.random... | 7 | 3 |
72,781,400 | 2022-6-28 | https://stackoverflow.com/questions/72781400/getting-black-python-code-formatter-to-align-comments | Yes, I'm, of the understanding that black gives very little leeway in getting it to act differently but I was wondering about the best way to handle something like this (my original code): @dataclass class Thing1: property1: int # The first property. property2: typing.List[int] # This is the second property # and the c... | You can wrap your block with # fmt: on/off, so Black doesn't touch it. # fmt: off @dataclass class Thing1: property1: int # The first property. property2: typing.List[int] # This is the second property # and the comment crosses multiple lines. # fmt: on I usually prefer to relocate the comments and stick with default ... | 6 | 7 |
72,793,916 | 2022-6-28 | https://stackoverflow.com/questions/72793916/how-can-i-import-watershed-function-from-scikit-image | Using Napari Image Analysis GUI to run the Allen Cell Segmenter (no response in Napari github or Allen Cell Forum, thought I'd try here) and getting the following error when I attempt to run the watershed for cutting function: ImportError: cannot import name 'watershed' from 'skimage.morphology' (C:\Users\Murryadmin\an... | watershed was moved from skimage.morphology to skimage.segmentation in version 0.17. There was a pointer from morphology to the new function in segmentation in 0.17 and 0.18, but it was removed in 0.19. The Allen Cell Segmenter needs to be updated to match the more modern scikit-image version, so I would raise an issue... | 4 | 9 |
72,791,043 | 2022-6-28 | https://stackoverflow.com/questions/72791043/how-would-i-fix-the-issue-of-the-python-extension-loading-and-extension-activati | I keep on getting these messages on the bottom right corner of my screen when opening up VS code. Any idea on how to get rid of it? I can still write code and run the code fine but I don't understand why this is happening. I've tried by deleting the python extension and anything related to python in the video extensi... | Please update the python extension to the latest version or install the pre-release version directly. ( may be more useful to you ) this will basically solve your problem. If the error continues, follow these steps: Uninstall Python extension (if you have pylance uninstall it first). Uninstall any other extension t... | 5 | 17 |
72,793,974 | 2022-6-28 | https://stackoverflow.com/questions/72793974/groupby-column-and-create-lists-for-other-columns-preserving-order | I have a PySpark dataframe which looks like this: Id timestamp col1 col2 abc 789 0 1 def 456 1 0 abc 123 1 0 def 321 0 1 I want to group by or partition by ID column and then the lists for col1 and col2 should be created based on the order of timestamp. Id timestamp col1 col2 abc [123,789] [1,0] [0,1] def [321,456] [0... | I don't think the order can be reliably preserved using groupBy aggregations. So window functions seems to be the way to go. Setup: from pyspark.sql import functions as F, Window as W df = spark.createDataFrame( [('abc', 789, 0, 1), ('def', 456, 1, 0), ('abc', 123, 1, 0), ('def', 321, 0, 1)], ['Id', 'timestamp', 'col1'... | 4 | 5 |
72,781,500 | 2022-6-28 | https://stackoverflow.com/questions/72781500/trouble-getting-accurate-binary-image-opencv | Using the threshold functions in open CV on an image to get a binary image, with Otsu's thresholding I get a image that has white spots due to different lighting conditions in parts of the image or with adaptive threshold to fix the lighting conditions, it fails to accurately represent the pencil-filled bubbles that Ot... | Problems with your approach: The methods you have tried out: Otsu threshold is decided based on all the pixel values in the entire image (global technique). If you look at the bottom-left of your image, there is a gray shade which can have an adverse effect in deciding the threshold value. Adaptive threshold: here is ... | 3 | 4 |
72,791,487 | 2022-6-28 | https://stackoverflow.com/questions/72791487/error-when-installing-microsoft-playwright | I'm getting this error: At line:1 char:1 + playwright install + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (playwright:String) [],CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I'm installing it using pip, for use in python | You need playwright added to your PATH. However, a better way to do this (if python is added to your path) without adding it to your PATH is by running: python -m playwright install This runs the playwright module as a script. Use python -h for more information on these flags, and python -m playwright for more informa... | 3 | 17 |
72,712,965 | 2022-6-22 | https://stackoverflow.com/questions/72712965/does-the-src-folder-in-pypi-packaging-have-a-special-meaning-or-is-it-only-a-co | I'm learning how to package Python projects for PyPI according to the tutorial (https://packaging.python.org/en/latest/tutorials/packaging-projects/). For the example project, they use the folder structure: packaging_tutorial/ ├── LICENSE ├── pyproject.toml ├── README.md ├── src/ │ └── example_package_YOUR_USERNAME_HER... | There is an interesting blog post about this topic; basically, using src prevents that when running tests from within the project directory, the package source folder gets imported instead of the installed package (and tests should always run against installed packages, so that the situation is the same as for a user).... | 20 | 18 |
72,790,215 | 2022-6-28 | https://stackoverflow.com/questions/72790215/sqlalchemy-2-x-with-specific-columns-makes-scalars-return-non-orm-objects | This question is probably me not understanding architecture of (new) sqlalchemy, typically I use code like this: query = select(models.Organization).where( models.Organization.organization_id == organization_id ) result = await self.session.execute(query) return result.scalars().all() Works fine, I get a list of model... | My understanding so far was that in new sqlalchemy we should always call scalars() on the query That is mostly true, but only for queries that return whole ORM objects. Just a regular .execute() query = select(Payment) results = sess.execute(query).all() print(results) # [(Payment(id=1),), (Payment(id=2),)] print(ty... | 13 | 32 |
72,789,188 | 2022-6-28 | https://stackoverflow.com/questions/72789188/can-i-use-yt-dlp-to-extract-only-one-video-info-from-a-playlist | Here's my code using Python (simplified version): import yt_dlp YDL_OPTIONS = { 'format': 'bestaudio*', 'noplaylist': True, } with yt_dlp.YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) The problem comes up when the url directs to a playlist (e.g. https://www.youtube.com/playlist?list=PLlrA... | noplaylist: Download single video instead of a playlist if in doubt. Source: github.com/yt-dlp/yt-dlp What you shared with us isn't a playlist of a single video so, according to me, there isn't any doubt here. You can request yt_dlp to treat only the first video of the playlist by adding 'playlist_items': '1' to YDL_... | 5 | 3 |
72,788,512 | 2022-6-28 | https://stackoverflow.com/questions/72788512/how-to-remove-index-column-when-getting-latex-string-from-pandas-dataframe | Originally, you could simply pass an argument in the to_latex method of the Pandas DataFrame object. Now you get a warning message about signature changes. Example: >>> import pandas as pd >>> import numpy as np >>> data = {f'Column {i + 1}': np.random.randint(0, 10, size=(10, )) for i in range(5)} >>> df = pd.DataFram... | It is possible to use the hide() method of the style attribute of a Pandas dataframe. The following code will produce a LaTeX table without the values of the index: import pandas as pd import numpy as np data = {f'Column {i + 1}': np.random.randint(0, 10, size=(10, )) for i in range(5)} df = pd.DataFrame(data) lat_new ... | 10 | 10 |
72,776,557 | 2022-6-27 | https://stackoverflow.com/questions/72776557/generate-a-list-of-all-possible-patterns-of-letters | I'm trying to find a way to generate all possible "patterns" of length N out of a list of K letters. I've looked at similar questions but they all seem to be asking about combinations, permutations, etc. which is not exactly what I'm after. For example, let K = 3 and N = 2. That is, I want all 2-letter "patterns" that ... | One of the comments, from @JacobRR, was very close to what we need. Each "pattern" actually corresponds to partitioning of set {1, 2, ..., N} into K subsets. Each subset (even empty!) corresponds to the positions where letter l_k should be placed (l_1 = A, l_2 = B etc.). There's a demo here. https://thewebdev.info/2021... | 4 | 2 |
72,782,410 | 2022-6-28 | https://stackoverflow.com/questions/72782410/building-wheel-for-gevent-pyproject-toml-did-not-run-successfully | I got an error when install dependencies for my project! OS : WinDow 11 Python: 3.10.4 (64bit) Pip: 22.1.2 Building wheel for django-admin-sortable2 (setup.py) ... done Created wheel for django-admin-sortable2: filename=django_admin_sortable2-0.7.5-py3-none-any.whl size=69989 sha256=0a4ff29d0c9b0422611dde61c6c1665dd36... | tl;dr: use python3.8 or update requirement.txt versions. More info: The combination of (A) gevent==20.9, (B) windows 10, and (C) python3.10 does not have a prebuilt wheel. You can check this kind of stuff by going to pypi and looking what is offered for downloads (https://pypi.org/project/gevent/20.9.0/#files) I'm assu... | 10 | 5 |
72,781,651 | 2022-6-28 | https://stackoverflow.com/questions/72781651/how-does-this-discouraging-python-one-liner-that-displays-the-mandlebrot-set-wor | Could you please explain how it works. In particular: where do a,c,n,s,z come from? And how to convert this to regular functions and their calls? x=10 y=5 abs( (lambda a: lambda z, c, n: a(a, z, c, n)) (lambda s, z, c, n: z if n == 0 else s(s, z*z+c, c, n-1)) (0, 0.02*x+0.05j*y, 10) ) It was even longer, but I figured... | This function (lambda a: lambda z, c, n: a(a, z, c, n)) can be rewritten as def apply_function_to_itself(funk): def inner(arg1, arg2, arg3): funk(funk, arg1, arg2, arg3) return inner This is a functional thing that calls a function with itself as the first argument. This is necessary for recursion in functional langu... | 4 | 4 |
72,741,543 | 2022-6-24 | https://stackoverflow.com/questions/72741543/how-to-reconnect-to-an-existing-jupyter-notebook-session-in-vs-code | I remember I was able to reconnect to an existing Jupyter Notebook session in VS code before by changing the kernel for a notebook. Now the option to reconnect to an existing session is gone, see: How do I reconnect to an existing Jupyter Notebook session in VS code? To be clear, the sessions were never shut down. In ... | If you would like to connect to an existing jupyter server can you do so by going into the command Jupyter: Specify Jupyter Server for Connections and selecting the appropriate remote server from the list. If the required server is not on that list, then you can select it. | 11 | 3 |
72,757,575 | 2022-6-25 | https://stackoverflow.com/questions/72757575/error-no-matching-distribution-found-and-error-could-not-find-a-version-that-s | I'm trying to install the requirements of a GitHub clone in a virtual environment created by py -m virtualenv objectremoval command, but I always encounter the "Could not find a version that satisfies the requirement" Error. After cloning the repo, I performed the following lines; D:\test1\Deep-Object-Removal>py -m vir... | The chosen package called Deep-Object-Removal seems to be very outdated (last commit 4years ago) and not maintained any longer, i would suggest to search for any currently supported alternative. If you try to install this version of opencv_python in a clean python venv (with python3.10) you get an error: pip install op... | 7 | 6 |
72,769,282 | 2022-6-27 | https://stackoverflow.com/questions/72769282/how-to-split-list-data-and-populate-to-a-dataframe | I have a list of items and want to clean the data with certain conditions and the output is a dataframe. Here's the list: [ "Onion per Pack|500 g|Rp18,100|Rp3,700 / 100 g|Add to cart", "Shallot per Pack|250 g|-|49%|Rp22,300|Rp11,300|Rp4,600 / 100 g|Add to cart", "Spring Onion per Pack|250 g|Rp7,000|Rp2,800 / 100 g|Add ... | I'd using a map; try: ids = { 5: [0, 2, -1, 3, 4], 8: [0, 2, 4, 6, 7] } datas = pd.DataFrame() for i in item: i = i.split("|") long = len(i) data = { "name": i[ids[long][0]], "unit": i[ids[long][1]], "discount": i[ids[long][2]] if ids[long][2] != -1 else "", "price": i[ids[long][3]], "unit price": i[ids[long][4]], } da... | 4 | 0 |
72,732,058 | 2022-6-23 | https://stackoverflow.com/questions/72732058/match-case-invalid-syntax-with-spyder | I am using Spyder 5.3.1 and Python 3.10.4 within a virtual environment, on Windows 10. I know that with Python 3.10 came the match statement. However, whenever I use the match keyword inside a script, the following error appears: Code Analysis Invalid syntax (pyflakes E) But I can run the script correctly without any ... | It's not so much an issue with Spyder as it is with the Pyflakes system it uses for linting code. match is a new (soft) keyword in Python 3.10. Pyflakes 2.4.0 only supports up to Python 3.8 currently. Pyflakes 2.5.0 is not out yet, but will cover up to Python 3.11, and should lint the new match keyword properly. | 5 | 3 |
72,764,752 | 2022-6-26 | https://stackoverflow.com/questions/72764752/how-do-i-create-a-an-annualized-growth-rate-for-gdp-column-in-my-dataframe | I basically want to apply this formula: ((New/Old)^4 - 1) * 100. To a data frame I have and create a new column called "Annualized Growth Rate" I have been working off of the FRED GDP data set. I have a data set that looks something like this (not the real numbers) Index GDP 0 100 1 101 2 103 3 107 I ... | You can use shift to access the previous row and vectorial operations for subtraction, division, power, multiplication: df['Annualized_Growth_Rate'] = df['GDP'].div(df['GDP'].shift()).pow(4).sub(1).mul(100) Output: Index GDP Annualized_Growth_Rate 0 0 100 NaN 1 1 101 4.060401 2 2 103 8.159184 3 3 107 16.462528 | 4 | 3 |
72,764,625 | 2022-6-26 | https://stackoverflow.com/questions/72764625/using-both-or-and-in-an-if-statement-python | def alarm_clock(day, vacation): if day == 0 or day == 6 and vacation != True: return "10.00" else: return "off" print(alarm_clock(0, True)) Why does this return "10.00"? In my mind it should return "off". Yes, day is equal to 0, but vacation is True, and the IF-statements first line states that it should only be execu... | In Python and binds tighter than or. So your statement is equivalent to this: if day == 0 or (day == 6 and vacation != True): To get the correct result you must parenthesize the precedence yourself: if (day == 0 or day == 6) and vacation != True: | 6 | 22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.