question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
74,328,303 | 2022-11-5 | https://stackoverflow.com/questions/74328303/cannot-import-name-pagecoroutine-from-scrapy-playwright-page | I am trying to use scrapy and playwright to scrape dynamic webpages, I installed scrapy and playwright, however, when I try to run my spider, i get this error. ImportError: cannot import name 'PageCoroutine' from 'scrapy_playwright.page' (C:\Ali\DataCamp\Web Scraping in Python\Scrapy\venv\lib\site-packages\scrapy_playw... | PageCoroutine is deprecated/obsolute. Use playwright_page_methods instead. Working code as an example: import scrapy from scrapy_playwright.page import PageMethod class TestSpider(scrapy.Spider): name = "test" def start_requests(self): yield scrapy.Request( url="https://shoppable-campaign-demo.netlify.app/#/", callback... | 3 | 6 |
74,316,151 | 2022-11-4 | https://stackoverflow.com/questions/74316151/color-correction-using-least-square-method | I have tried color correcting an image using the least square method. I don't understand why it doesn't work, this is supposed to be the standard way of color calibration. First I pull in the above image in CR3 format, convert it to RGB space then crop out the four color patches using the OpenCV boundingRect and inRang... | Ignoring the fact that the image ICC profile is not properly decoded here, this is the expected result given your reference RGB values and using Colour: import colour import numpy as np # Reference values a likely non-linear 8-bit sRGB values. # "colour.cctf_decoding" uses the sRGB EOTF by default. REFERENCE_RGB = colo... | 3 | 4 |
74,324,986 | 2022-11-5 | https://stackoverflow.com/questions/74324986/can-i-set-the-index-value-of-a-list-to-a-changing-variable-in-this-example | I am a total beginner to Python and recently had a question while experimenting with lists. I have a for loop that increases a variable 'x' and generates a random number every time. I want to add this random number to a list, but when I try assigning the index value of the random number to x, I get this error message: ... | import random as number values = [number.randint(1,91) for _ in range(9)] | 3 | 3 |
74,324,901 | 2022-11-5 | https://stackoverflow.com/questions/74324901/how-does-inheritance-of-class-variables-work-in-python | I'm trying to get back to Python but I don't get why the following code doesn't work as intended. class Cat: age = 0 class Dog(Cat): pass Dog.age = 1 Cat.age = 2 print(Dog.age, Cat.age) My output is: 1 2 But why doesn't Dog.age equals 2? Dog is a subclass of Cat and modifying the class variable of the superclass Cat ... | Any property of Dog will override a property inherited from Cat. You can re-define a value in Cat, but it won't matter because it has already been overridden by the child. For example: class Cat: age = 0 # Cat.age = 0 class Dog(Cat): pass # Dog.age = Cat.age = 0 Dog.age=1 # Dog.age = 1, and Dog.age no longer points to ... | 5 | 3 |
74,314,778 | 2022-11-4 | https://stackoverflow.com/questions/74314778/nameerror-name-glpushmatrix-is-not-defined | Try to run a test code for stable baselines gym import gym from stable_baselines3 import A2C env = gym.make("CartPole-v1") model = A2C("MlpPolicy", env, verbose=1) model.learn(total_timesteps=10_000) obs = env.reset() for i in range(100): action, _state = model.predict(obs, deterministic=True) obs, reward, done, info =... | Just had the same problem. Fixed it by installing an older version of pyglet: $ pip install pyglet==1.5.27 I don't know if this is the latest version that avoids the problem, but it works. | 20 | 45 |
74,322,894 | 2022-11-4 | https://stackoverflow.com/questions/74322894/get-item-from-set-python | I have a set which contains objects which I have the __eq__ and __hash__ functions defined for. I would like to be able to check if an object with the same hash is in the set and if it is in the set to return the object from the set as I need the reference to the object. class SetObject(): def __init__( self, a: int, b... | Instead of using a set, use a dictionary where the keys and values are the same element. Then you can look use the value as a key and return the element. x = SetObject(1,2,3) y = SetObject(4,5,6) object_set = dict([(x, x),(y, y)]) print(f"{object_set=}") z = SetObject(1,2,7) print(f"{z=}") if z in object_set: print("Is... | 5 | 5 |
74,316,523 | 2022-11-4 | https://stackoverflow.com/questions/74316523/kwarg-unpacking-with-mypy | I have a function, that accepts inputs of different types, and they all have default values. For example, def my_func(a: str = 'Hello', b: bool = False, c: int = 1): return a, b, c What I want to do is define the non-default kwargs in a dictionary, and then pass this to the function. For example, input_kwargs = {'b': ... | You can create a class (by inheriting from TypedDict) with class variables that match with my_func parameters. To make all these class variables as optional, you can set total=False. Then use this class as the type for input_kwargs to make mypy happy :) from typing import TypedDict class Params(TypedDict, total=False):... | 4 | 4 |
74,311,394 | 2022-11-4 | https://stackoverflow.com/questions/74311394/is-there-any-way-to-monkey-patch-builtin-parentheses-behaviour-in-p | I am just checking where is the limit of changing python using python (without modifying interpreter and/or C code). I know that I can basically monkey patch every builtin function like this: import builtins int(1) # 1 def new_int(number): return number + 1 builtins.int = new_int int(1) # 2 I know I can turn python cl... | This can be done as a function decorator as long as the lists to be replaced as tuples are defined in a function. To do that, use ast.NodeTransformer to replace any ast.List node with an equivalent ast.Tuple node in the function's AST: import ast import inspect from textwrap import dedent class ForceTuples(ast.NodeTran... | 4 | 3 |
74,311,319 | 2022-11-4 | https://stackoverflow.com/questions/74311319/adjusting-the-plotly-colorbar-for-each-subplot-according-to-their-min-and-max | I wanted to find out how to have three different colorbars for my plotly 3 subplots and be able to adjust each of the three colorbars according to their min and max. (attached snapshot). Does anyone know how to have each colorbar on the right side of each subplot? Also, for some reasons, the plot sizes are not perfec... | To display a color bar for each subplot, the x-axis position must be set for each subplot. Also, for the subplot titles, the top margin is set to 0, which hides the text display area, so I set the top margin to 50. Finally, there does not seem to be a way to synchronize the zoom of the subplots at this time; the plotly... | 3 | 4 |
74,311,275 | 2022-11-4 | https://stackoverflow.com/questions/74311275/modulenotfounderror-no-module-named-openai | import requests from bs4 import BeautifulSoup import openai #write each line of nuclear.txt to a list with open('nuclear.txt', 'r') as f: lines = f.readlines() #remove the newline character from each line lines = [line.rstrip() for line in lines] #gather the text from each website and add it to a new txt file for line ... | Follow the steps below to install the openai package for the current interpreter run the following code import sys print(sys.executable) get the current interpreter path Copy the path and install openai using the following command in the terminal C:\WorkSpace\pytest10\.venv\Scripts\python.exe -m pip install openai... | 6 | 14 |
74,310,338 | 2022-11-3 | https://stackoverflow.com/questions/74310338/get-keys-of-dictionary-based-on-rules | given a dictionary dictionary = {'Animal 1': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Black'}, 'Animal 2': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Brown'}, 'Animal 3': {'Dog': 'No', 'Cat': 'Yes', 'Color': 'Grey'}} How do I select the Animals that are dogs? expected output ['Animal 1','Animal 2'] I could use: pd.DataFrame.f... | You can use list comprehension: dictionary = { "Animal 1": {"Dog": "Yes", "Cat": "No", "Color": "Black"}, "Animal 2": {"Dog": "Yes", "Cat": "No", "Color": "Brown"}, "Animal 3": {"Dog": "No", "Cat": "Yes", "Color": "Grey"}, } out = [k for k, d in dictionary.items() if d.get("Dog") == "Yes"] print(out) Prints: ['Animal ... | 3 | 3 |
74,307,236 | 2022-11-3 | https://stackoverflow.com/questions/74307236/python-why-do-functools-partial-functions-not-become-bound-methods-when-set-as | I was reading about how functions become bound methods when being set as class atrributes. I then observed that this is not the case for functions that are wrapped by functools.partial. What is the explanation for this? Simple example: from functools import partial def func1(): print("foo") func1_partial = partial(func... | The trick that allows functions to become bound methods is the __get__ magic method. To very briefly summarize that page, when you access a field on an instance, say foo.bar, Python first checks whether bar exists in foo's __dict__ (or __slots__, if it has one). If it does, we return it, no harm done. If not, then we l... | 9 | 7 |
74,294,527 | 2022-11-2 | https://stackoverflow.com/questions/74294527/what-do-line2d-objects-returned-by-seaborn-lineplot-with-hue-represent | import seaborn as sns import matplotlib.pyplot as plt import numpy as np import pandas as pd # generate data rng = np.random.default_rng(12) x = np.linspace(0, np.pi, 50) y1, y2 = np.sin(x[:25]), np.cos(x[25:]) cat = rng.choice(["a", "b", "c"], 50) data = pd.DataFrame({"x": x , "y" : y1.tolist() + y2.tolist(), "cat": c... | These are dummy lines used to create the legend. Seaborn's legends can be quite complex, due to the many options. You might want to check out this github issue to get an idea about Seaborn trying to create more elaborate legends than what matplotlib currently allows. If you change the properties of these dummy lines af... | 5 | 4 |
74,304,457 | 2022-11-3 | https://stackoverflow.com/questions/74304457/raise-an-error-if-type-hint-is-violated-ignored-in-python | After looking at this question I learned that the type hints are, by default, not enforced whilst executing Python code. One can detect some discrepancies between the type hints and actual argument types using a slightly convoluted process of running pyannotate to generate stubs whilst running Python code, and scanning... | The edit queue for the Answer by @Surya_1897 is full, hence I will include a more detailed description of the solution here. Typeguard does exactly what I was looking for. The following requirements apply: Install typeguard with: pip install typeguard Import typeguard into each script, and add the @typechecked prop... | 5 | 2 |
74,301,529 | 2022-11-3 | https://stackoverflow.com/questions/74301529/how-to-get-the-indices-of-at-least-two-consecutive-values-that-are-all-greater-t | For example, let's consider the following numpy array: [1, 5, 0, 5, 4, 6, 1, -1, 5, 10] Also, let's suppose that the threshold is equal to 3. That is to say that we are looking for sequences of at least two consecutive values that are all above the threshold. The output would be the indices of those values, which in o... | If you convolve a boolean array with a window full of 1 of size win_size ([1] * win_size), then you will obtain an array where there is the value win_size where the condition held for win_size items: import numpy as np def groups(arr, *, threshold, win_size, merge_contiguous=False, flat=False): conv = np.convolve((arr ... | 5 | 4 |
74,301,098 | 2022-11-3 | https://stackoverflow.com/questions/74301098/python-tempfile-temporarydirectory-cleanup-crashes-with-permissionerror-and-no | Premise I'm trying to convert some PDF to images via pdf2image and poppler, to then run some computervision tasks on. The conversion itself works fine. However, the conversion creates some artifacts for each page in the pdf as it is being converted, which I would like to be deleted at the end of the function. To facili... | While experimenting some more and writing this question, I found a working solution: with tempfile.TemporaryDirectory() as path: images_from_path: [Image] = convert_from_path( os.path.join(path_superfolder, f"calibration_target_{exam_type}.pdf"), size=(2480, 3508), output_folder=path, poppler_path=r'E:\poppler-22.04.0... | 4 | 1 |
74,298,091 | 2022-11-3 | https://stackoverflow.com/questions/74298091/pandas-sorting-by-datetime | I have a pandas dataframe filled with time-stamped data. It is out of order; and I am trying to sort by date, hours and minutes. The pandas dataframe will organize by date, but not by hours and minutes. My dataframe is loaded in ('df'), and the column 'dttime' was changed it into a dateframe from integer numbers. df['d... | I tried with some dummy data and it doesn't look like an issue to me. Please check the below code. import pandas as pd data = ['221011141200', '221011031200', '221011191200', '221011131600'] df = pd.DataFrame(data, columns=['dttime']) df['dttime'] = pd.to_datetime(df['dttime'], format='%y%m%d%H%M%S') # Before sorting p... | 6 | 10 |
74,296,722 | 2022-11-2 | https://stackoverflow.com/questions/74296722/delete-repeated-vowels-in-string | Here is my code: def del_rep_vow(s): ''' >>> del_rep_vow('adaptation') 'adpttion' >>> del_rep_vow('repetitions') 'reptitons' >>> del_rep_vow('kingkong') 'kingkong' >>> del_rep_vow('aeiouaeiou') 'aeiou' ''' final_list = [] for i in s: if i not in final_list: final_list.append(i) return ''.join(final_list) if __name__ ==... | You should maintain a Python set of vowel characters already seen. For each new encountered letter as you walk down the string, only append a vowel if it is not in the set. def del_rep_vow(s): vowels_seen = set() final_list = [] for i in s: if i in ['a', 'e', 'i', 'o', 'u']: if i not in vowels_seen: final_list.append(i... | 3 | 3 |
74,294,107 | 2022-11-2 | https://stackoverflow.com/questions/74294107/python-pandas-making-a-contingency-table-with-multiple-variables | My dataframe has 4 columns (one dependent variable and 3 independent). Here's a sample: My desired output is a contingency table, as follows: I can only seem to get a contingency table using one independent variable- using the following code (my df is called 'table') pd.crosstab(index=table['Dvar'],columns=table['Var... | First of all, contingency table is for showing correlation between features. If you want to probably see correlation between independent and dependent features, go through this code: pd.crosstab([table['Var1'],table['Var2'],table['Var3']], table['Dvar'], margins = False) But, as you mention, to get your desired output... | 3 | 3 |
74,292,510 | 2022-11-2 | https://stackoverflow.com/questions/74292510/how-to-create-a-deployable-python-lamba-zip-using-poetry | I've been spending a few days trying to figure out how best to build a Python Lambda bundle when using Poetry. I found a few blogs that that outline the same technique but those didn't work in my situation. The solution provided in the blogs is to use pip install to install the needed dependencies into a specific direc... | Ultimately I found this documentation from AWS for how to create a lambda archive from a Python virtual environment. Using Poetry's install command, I was able to install just the main runtime dependencies into the Poetry projects created virtual environment, including any local path based dependencies. However, this d... | 6 | 6 |
74,285,167 | 2022-11-2 | https://stackoverflow.com/questions/74285167/how-to-make-output-from-web-scraping-python-selenium-in-div-class-to-output-text | This is my Code ` from attr import attr import requests from bs4 import BeautifulSoup import csv datas = [] key = 'sepatu' jenis = 'teplek' url = 'https://website.com/search/?term={}+{}'.format(key,jenis) headers = { 'user-agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0' } req = request... | You can add .text in this line harga = soup.find("div", {"class": "db gM ei b hE be f16-360-o ff vb uT ellipsis-1"}).text Then you will get an output like this Nama Sepatu Harga Sepatu A Rp.24.000 | 4 | 1 |
74,284,758 | 2022-11-2 | https://stackoverflow.com/questions/74284758/how-to-sort-python-strings-both-alphabetically-by-prefix-and-numerically-by-suff | I need to sort a list of strings, of the form: ["ccc_3.23", "b_0.00", "b_-1.10", "aa_-2.37", "aa_3.05", "aa_-2.11", "ccc_9.8"] first by prefix, then by suffix, such that the sorted list is: ["aa_-2.37", "aa_-2.11", "aa_3.05", "b_-1.17", "b_0.00", "ccc_3.23", "ccc_9.8"] The prefixes only contain standard english lette... | You need to use key in sort a = ["ccc_3.23", "b_0.00", "b_-1.10", "aa_-2.37", "aa_3.05", "aa_-2.11", "ccc_9.8"] a.sort(key=lambda x: (x.split("_")[0], float(x.split("_")[1]))) a # output : ['aa_-2.37', 'aa_-2.11', 'aa_3.05', 'b_-1.10', 'b_0.00', 'ccc_3.23', 'ccc_9.8'] | 3 | 7 |
74,261,401 | 2022-10-31 | https://stackoverflow.com/questions/74261401/how-to-get-routes-name-using-fastapi-starlette | How can I get the name of a route/endpoint using FastAPI/Starlette? I have access to the Request object and I need this information in one of my middlewares. For example, if I hit services/1, I should then be able to get the abc name. Is this possible in FastAPI? @app.get("/services/{service}", name="abc") async def li... | Option 1 You can get the name value inside an endpoint as follows: from fastapi import FastAPI,Request app = FastAPI() @app.get('/', name='abc') def get_name(request: Request): return request.scope['route'].name Option 2 Inside a middleware, make sure to get the route's name after calling call_next(request), otherwise... | 5 | 6 |
74,209,110 | 2022-10-26 | https://stackoverflow.com/questions/74209110/how-to-convert-date-to-timezone-aware-datetime-in-polars | Let's say I have df = pl.DataFrame({ "date": pl.Series(["2022-01-01", "2022-01-02"]).cast(pl.Date) }) How do I localize that to a specific timezone and make it a datetime? I tried: df.select(pl.col('date').cast(pl.Datetime(time_zone='America/New_York'))) but that gives me shape: (2, 1) ┌──────────────────────────────... | As of polars 0.16.3, you can do: df.select( pl.col('date').cast(pl.Datetime).dt.replace_time_zone("America/New_York") ) | 3 | 9 |
74,231,254 | 2022-10-28 | https://stackoverflow.com/questions/74231254/how-to-filter-empty-strings-from-a-list-column-of-python-polars-dataframe | I have a python polars dataframe as- df_pol = pl.DataFrame({'test_names':[['Mallesham','','Bhavik','Jagarini','Jose','Fernando'], ['','','','ABC','','XYZ']]}) I would like to get a count of elements from each list in test_names field not considering the empty values. df_pol.with_columns(pl.col('test_names').list.len()... | You can use list.eval to run any polars expression on the list's elements. In an list.eval expression, you can pl.element() to refer to the lists element and then apply an expression. Next we simply use a filter expression to prune the values we don't need. df = pl.DataFrame({ "test_names":[ ["Mallesham","","Bhavik","J... | 4 | 2 |
74,280,212 | 2022-11-1 | https://stackoverflow.com/questions/74280212/polars-scan-s3-multi-part-parquet-files | I have a multipart partitioned parquet on s3. Each partition contains multiple parquet files. The below code narrows in on a single partition which may contain somewhere around 30 parquet files. When I use scan_parquet on a s3 address that includes *.parquet wildcard, it only looks at the first file in the partition. I... | New Answer polars can natively load files from AWS, Azure, GCP, or plain old http and no longer uses fsspec (very much, if at all). Instead, it uses the object_store under the hood. The syntax to use it is. pl.scan_parquet( "s3://some_bucket/some_parquet/some_partion=123/*.parquet", storage_options= dict_of_credentials... | 6 | 6 |
74,206,034 | 2022-10-26 | https://stackoverflow.com/questions/74206034/how-do-uvicorn-workers-work-and-how-many-do-i-need-for-a-slim-machine | The application I deploy is FastAPI with Uvicorn under K8s. While trying to understand how I want to Dockerize the application I understood I want to implement Uvicorn without Gunicorn and to add a system of scale up/down by the load of the requests the application is getting. I did a lot of load testing and discovered... | When using uvicorn and applying the --workers argument greater than 1, then uvicorn will spawn subprocesses internally using multiprocessing. You have to remember that uvicorn is asynchronous and that HTTP servers generally are bottle necked by network latency instead of computation. So, it could be that your workloads... | 9 | 16 |
74,267,784 | 2022-10-31 | https://stackoverflow.com/questions/74267784/i-cant-authorize-gmail-api-application-in-google-colaboratory | I'm running the quickstart code from https://developers.google.com/people/quickstart/python in a colab notebook. # \[START people_quickstart\] from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthl... | today I came across the same problem and the way I found to fix it was running the code in a Jupyter Notebook and then saving the token it was generated there and uploading it to colab. I ran the code bellow and then a json file named 'token' was generated in the folder where my notebook is located: import os.path impo... | 4 | 2 |
74,275,058 | 2022-11-1 | https://stackoverflow.com/questions/74275058/importerror-missing-optional-dependency-openpyxl-use-pip-or-conda-to-install | I am trying to run the following pandas code to create a df by reading an excel. However I receive the error below. (I pip-installed the openpyxl but I get the same error.) import pandas as pd import numpy as np df = pd.read_excel("test.xlsx") return _bootstrap._gcd_import(name[level:], package, level) File "<frozen im... | Jupyter (with anaconda) is using a specific python environment independent from the local python installation in your computer. First make sure your are installing the packages in the correct interpreter if you want to install it into anaconda (jUPYTER NOTEBOOK) try: conda activate pip install openpyxl otherwise just ... | 19 | 9 |
74,253,820 | 2022-10-30 | https://stackoverflow.com/questions/74253820/cannot-catch-requests-exceptions-connectionerror-with-try-except | It feels like I am slowly losing my sanity. I am unable to catch a connection error in a REST-API request. I read at least 20 similar questions on stackoverflow, tried every possible except statement I could think of and simplified the code as much as I could to rule out certain other libraries. I am using Python 3.7 a... | Okay, I could figure it out myself. Kind of. A huge problem was that the traceback doesn't point to the line of my code where the exception is raised. I still don't know why that is and if this should be considered a bug in requests or not. But in any case: requests raises a ConnectionError in adapters.py but the origi... | 6 | 5 |
74,229,178 | 2022-10-27 | https://stackoverflow.com/questions/74229178/stable-baselines3-runtimeerror-mat1-and-mat2-must-have-the-same-dtype | I am trying to implement SAC with a custom environment in Stable Baselines3 and I keep getting the error in the title. The error occurs with any off policy algorithm not just SAC. Traceback: File "<MY PROJECT PATH>\src\main.py", line 70, in <module> main() File "<MY PROJECT PATH>\src\main.py", line 66, in main model.le... | Change the inputs to float32 , default the loader set the type as float64. inputs = inputs.to(torch.float32) | 9 | 21 |
74,262,112 | 2022-10-31 | https://stackoverflow.com/questions/74262112/dataclasses-how-to-ignore-default-values-using-asdict | I would like to ignore the default values after calling asdict() @dataclass class A: a: str b: bool = True so if I call a = A("1") result = asdict(a, ignore_default=True) assert {"a": "1"} == result # the "b": True should be deleted | The dataclasses module doesn't appear to have support for detecting default values in asdict(), however the dataclass-wizard library does -- via skip_defaults argument. Example: from dataclasses import dataclass from dataclass_wizard import asdict @dataclass class A: a: str b: bool = True a = A("1") result = asdict(a, ... | 8 | 3 |
74,226,436 | 2022-10-27 | https://stackoverflow.com/questions/74226436/hdf5-error-when-opening-nc-files-in-python-with-xarray | I'm attempting to open MERRA-2 files using xarray, as my title suggests. The specific error I am encountering occurs when I attempt to view the values in a certain variable using a print statement. The error is as follows: HDF5-DIAG: Error detected in HDF5 (1.12.2) thread 5: #000: H5A.c line 528 in H5Aopen_by_name(): c... | This error occurs due to conflicting non-python (e.g. fortran/C/C++) dependencies. This commonly happens when you install packages using conda with conflicting channels. This happens a lot when using Anaconda. Anaconda is a nice place to start, because it gives you a pre-built bundle (or "distribution") of data science... | 6 | 6 |
74,248,955 | 2022-10-29 | https://stackoverflow.com/questions/74248955/how-to-display-the-coordinates-of-the-points-clicked-on-the-image-in-google-cola | I need to locate the mouse click location on an image in a google colab notebook. I tried the following script but nothing happened. The following code should work in Jupyter notebooks but it doesn't work on google colab: import matplotlib matplotlib.use('TKAgg') import matplotlib.pyplot as plt import matplotlib.image ... | You need to use an interactive IPython backend, e.g. ipympl: Installation in Colab: !pip install ipympl from google.colab import output output.enable_custom_widget_manager() setup matplotlib to use it: %matplotlib ipympl test it: import matplotlib import matplotlib.pyplot as plt fig, ax = plt.subplots() def onc... | 3 | 4 |
74,244,578 | 2022-10-29 | https://stackoverflow.com/questions/74244578/how-can-i-reshape-a-2d-array-into-1d-in-python | Let me edit my question again. I know how flatten works but I am looking if it possible to remove the inside braces and just simple two outside braces just like in MATLAB and maintain the same shape of (3,4). here it is arrays inside array, and I want to have just one array so I can plot it easily also get the same res... | First answer If I understood correctly your question (and 4 other answers say I didn't), your problem is not how to flatten() or reshape(-1) an array, but how to ensure that even after reshaping, it still display with 4 elements per line. I don't think you can, strictly speaking. Arrays are just a bunch of elements. Th... | 6 | 0 |
74,273,757 | 2022-11-1 | https://stackoverflow.com/questions/74273757/pipenv-packages-do-not-match-the-hashes-from-the-requirements-file | Pipfile I recently installed O365 and shortuuid packages using following command, which got executed with no problems on Mac M1. pipenv install --keep-outdated o365 shortuuid [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] black = "*" [packages] django = "~=3.2" djangorestframe... | The package pyrsistent is a dependency of jsonschema, which is pinned to version 4.4.0 in your Pipfile. There are several possible explanations for a hash mismatch when installing from PyPI. One way to simply fix the error would be to regenerate your Pipfile.lock: % pipenv lock And then reinstall all packages specifie... | 3 | 3 |
74,281,446 | 2022-11-1 | https://stackoverflow.com/questions/74281446/pyarrow-is-not-installed-snowpark-stored-procedure-with-python | I have created this basic stored procedure to query a Snowflake table based on a customer id: CREATE OR REPLACE PROCEDURE SP_Snowpark_Python_Revenue_2(site_id STRING) RETURNS STRING LANGUAGE PYTHON RUNTIME_VERSION = '3.8' PACKAGES = ('snowflake-snowpark-python') HANDLER = 'run' AS $$ from snowflake.snowpark.functions i... | You need to ask for pyarrow as a package: PACKAGES = ('snowflake-snowpark-python', 'pyarrow') But to get these packages, someone in your org will need to approve the Anaconda terms of service, or you'll get the following error: SQL compilation error: Anaconda terms must be accepted by ORGADMIN to use Anaconda 3rd part... | 3 | 2 |
74,278,889 | 2022-11-1 | https://stackoverflow.com/questions/74278889/how-can-i-count-occurrences-of-words-specified-in-an-array-in-python | I am working on a small program in which the user enters text and I would like to check how many times the given words occur in the given input. # Read user input print("Input your code: \n") user_input = sys.stdin.read() print(user_input) For example, the text that I input in a program is: a=1 b=3 if (a == 1): print(... | I think the best option is to use the tokenize built-in module of python: # Let's say this is tokens.py import sys from collections import Counter from io import BytesIO from tokenize import tokenize # Get input from stdin code_text = sys.stdin.read() # Tokenize the input as python code tokens = tokenize(BytesIO(code_t... | 3 | 3 |
74,276,093 | 2022-11-1 | https://stackoverflow.com/questions/74276093/how-to-get-all-the-indexes-of-leading-zeroes-using-regex-in-python | Using Regex in Python (library re (only)), I want to create a function that gives me the position of all leading 0s in a string. For example, if the string was: My house has 01 garden and 003 rooms. I would want me the function to return 13, 27 and 28. I tried for example: import re string = "My house has 01 garden and... | You can do the following: import re text = "My house has 01 garden and 003 rooms." pattern = re.compile(r"\b0+") def leading_zeros_index(s: str) -> list: return [i for m in pattern.finditer(s) for i in range(m.start(), m.end())] print(leading_zeros_index(text)) output: [13, 27, 28] Basically you use .finditer() in or... | 3 | 5 |
74,275,522 | 2022-11-1 | https://stackoverflow.com/questions/74275522/count-the-arrays-in-a-large-array | I wrote the following code but when the rows are large it is slow import numpy as np array = np.array([ [1,2],[1,2],[2,3], [1,2],[2,3],[5,2]]) d={} for l in array: t = tuple(l) if t in d: d[t]+=1 else: d[t]=1 print(d) result: `{(1, 2): 3, (2, 3): 2, (5, 2): 1}` Is there a faster way to do this? | Use np.unique elements, counts = np.unique(array, axis=0, return_counts=True) In your case, elements will be [[1, 2], [2, 3], [5, 2]] and counts will be [3, 2, 1] | 3 | 4 |
74,268,552 | 2022-10-31 | https://stackoverflow.com/questions/74268552/how-to-sort-pandas-crosstab-columns-by-sum-of-values | I have a crosstab table with 4 rows and multiple columns, containing numeral values (representing the number of dataset elements on the crossing of two factors). I want to sort the order of columns in the crosstab by the sum of values in each column. e.g. I have: ct = pd.crosstab(df_flt_reg['experience'], df_flt_reg['r... | Calculate the sum and sort the values. Once you have the sorted series get the index and reorder your columns with it. sorted_df = ct[ct.sum().sort_values(ascending=False).index] d e b c a 0 3 6 0 7 1 1 5 4 4 1 2 2 7 2 5 0 3 3 9 1 3 1 1 | 3 | 5 |
74,260,802 | 2022-10-31 | https://stackoverflow.com/questions/74260802/different-aggregate-function-based-on-value-of-column-pandas | I have the following dataframe import pandas as pd test = pd.DataFrame({'y':[1,2,3,4,5,6], 'label': ['bottom', 'top','bottom', 'top','bottom', 'top']}) y label 0 1 bottom 1 2 top 2 3 bottom 3 4 top 4 5 bottom 5 6 top I would like to add a new column, agg_y, which would be the the max(y) if label=="bottom" and min(y) i... | Your solution in one line solution is: test['agg_y'] = np.where(test.label == "bottom", test.groupby('label').y.transform('max'), test.groupby('label').y.transform('min')) Solution without groupby, thank you @ouroboros1: test['agg_y'] = np.where(test.label == 'bottom', test.loc[test.label.eq('bottom'), 'y'].max(), tes... | 3 | 4 |
74,260,188 | 2022-10-31 | https://stackoverflow.com/questions/74260188/adding-key-and-value-inside-a-list-of-lists-python | I have data that looks like this [[{'title': 'Line'}], [{'title': 'asd'}]]. I want to add a new key and value for every list inside of lists. I have tried this but I'm having an error 'list' object is not a mapping. Any suggestion? data = [[{'title': 'Line'}], [{'title': 'asd'}]] titleID = [{'id': 373}, {'id': 374}] co... | Try this list comphrehension and unpacking data = [[{'title': 'Line'}], [{'title': 'asd'}]] titleID = [{'id': 373}, {'id': 374}] [[{**i[0], **j}] for i,j in zip(data, titleID)] Output [[{'title': 'Line', 'id': 373}], [{'title': 'asd', 'id': 374}]] | 3 | 1 |
74,257,818 | 2022-10-31 | https://stackoverflow.com/questions/74257818/how-to-redirect-logged-in-user-with-url-params | In my Django project I am trying to make the http://127.0.0.1:8000/ which is the home page to redirect to the Login in Page if user is not logged in however there is a user who is logged in I want http://127.0.0.1:8000/ to become http://127.0.0.1:8000/username/ I have tried different answers but nothing specific lead t... | You can use settings.LOGIN_URL and settings.LOGIN_REDIRECT_URL so: class LoginView(LoginView): template_name = 'login.html' login_url='login' def get_success_url(self): user=self.request.user.username return reverse('home', args=(user)) In settings.py: LOGIN_URL='some_app_name:login' #Redirect to login page if not log... | 5 | 5 |
74,237,285 | 2022-10-28 | https://stackoverflow.com/questions/74237285/dimension-error-by-using-patch-embedding-for-video-processing | I am working on one of the transformer models that has been proposed for video classification. My input tensor has the shape of [batch=16 ,channels=3 ,frames=16, H=224, W=224] and for applying the patch embedding on the input tensor it uses the following scenario: patch_dim = in_channels * patch_size ** 2 self.to_patch... | The input tensor has shape [batch=16, channels=3, frames=16, H=224, W=224], while Rearrange expects dimensions in order [ b t c h w ]. You expect channels but pass frames. This leads to a last dimension of (p1 * p2 * c) = 16 * 16 * 16 = 4096. Please try to align positions of channels and frames: from torch import torch... | 4 | 5 |
74,245,043 | 2022-10-29 | https://stackoverflow.com/questions/74245043/find-palindrome-python-space-complexity | Given the following code in python which checks whether an string of n size is palindromic: def is_palindromic(s): return all(s[i] == s[~i] for i in range(len(s) // 2)) What is the space complexity of this code? Is it O(1) or O(n)? The all function gets an iterable as a parameter; So does it mean the s[i] == s[~i] for... | You are using a generator expression, which only needs enough memory to store one item at a time. The other parts, len, range and the all function itself are all O(1) too, so your suggestion that "it behaves like an iterator that computes and returns the values one by one without any additional space" is correct. If yo... | 3 | 2 |
74,252,768 | 2022-10-30 | https://stackoverflow.com/questions/74252768/missinggreenlet-greenlet-spawn-has-not-been-called | I am trying to get the number of rows matched in a one to many relationship. When I try parent.children_count I get : sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s) ... | I think the problem here is that by default SQLAlchemy lazy-loads relationships, so accessing parent.children_count implicitly triggers a database query leading to the reported error. One way around this would be to specify a load strategy other than "lazy" in the relationship definition. Using SQLModel, this would loo... | 28 | 46 |
74,255,173 | 2022-10-30 | https://stackoverflow.com/questions/74255173/how-can-i-use-a-seed-inside-a-loop-to-get-the-same-random-samples-everytime-the | I want to generate data using random numbers and then generate random samples with replacement using the generated data. The problem is that using random.seed(10) only fixes the initial random numbers for the generated data but it does not fix the random samples generated inside the loop, everytime I run the code I get... | Fixing the seed for np.random doesn't fix the seed for random... So adding a simple line for fixing both seeds will give you reproducible results: import numpy as np import random np.random.seed(10) random.seed(10) data = list(np.random.binomial(size=215, n=1, p=0.3)) sample_mean = [] for i in range(1000): sample = ran... | 3 | 3 |
74,254,642 | 2022-10-30 | https://stackoverflow.com/questions/74254642/how-to-install-pipenv-on-windows | I need to install pipenv on Windows and I use this tutorial. However I get an error. I use Python 3.9.13 and pip 22.3. I installed pipenv with this command pip install pipenv, then I have to do this: but I didn`t get it. So I passed it and entered this command pipenv -h. Finaly I got this error: Could you help me ple... | You must add the Scripts directory to PATH environment variable as in the example below: | 3 | 4 |
74,252,067 | 2022-10-30 | https://stackoverflow.com/questions/74252067/efficiently-sample-batches-from-only-one-class-at-each-iteration-with-pytorch | I want to train a classifier on ImageNet dataset (1000 classes) and I need each batch to contain 64 images from the same class and consecutive batches from different classes. So far based on @shai's suggestion and this post I have import torchvision.transforms as transforms import torchvision.datasets as datasets from ... | You should write your own batch_sampler class for the DataLoader. | 5 | 2 |
74,242,076 | 2022-10-29 | https://stackoverflow.com/questions/74242076/way-to-simplify-enum | Is there a better way to initialize all this boilerplate? class Type(Enum): Null=auto() Bool=auto() Int=auto() Float=auto() Decimal=auto() String=auto() Bytes=auto() Date=auto() Time=auto() Datetime=auto() Timestamp=auto() Interval=auto() Struct=auto() Array=auto() Json=auto() I wanted to do something like the followi... | I can't speak for Pylance, but if you want auto implementations, you can just pass your list of types directly to the Enum function. Type = Enum('Type', ['Null','Bool','Int','Float','Decimal','String','Bytes', 'Date','Time','Datetime','Timestamp','Interval','Struct', 'Array','Json']) | 5 | 4 |
74,237,517 | 2022-10-28 | https://stackoverflow.com/questions/74237517/is-there-a-way-to-draw-borders-around-a-figure-in-plotly | I have the following bar chart. I would like to put it around a border. Does anyone know how to do it? data = {'Programming Languages': ['Python', 'C#', 'Java', 'Ruby', 'C++', 'C', 'JavaScript', 'PHP', 'TypeScript', 'Haskell', 'Closure', 'Kotlin'], 'Responses': [12,11,10,5,3,2,2,1,1,1,1,1]} df = pd.DataFrame(data, colu... | fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=True) fig.update_yaxes(showline=True, linewidth=1, linecolor='black', mirror=True) fig.show() | 4 | 7 |
74,209,148 | 2022-10-26 | https://stackoverflow.com/questions/74209148/automatically-generate-api-reference-for-all-subpackages-modules | I am using mkdocs with the mkdocstrings plugin to generate the documentation of my Python package. My package is organized in a standard fashion - setup.py - mkdocs.yaml - docs/ - mypackage/ - __init__.py - module1.py - module2.py - subpackage1/ - __init__.py - submodule1.py - submodule2.py - [...] in mkdocs.yml: plug... | Ah, it's because by default submodules are not rendered. Try setting the show_submodules option to true. Globally: plugins: - mkdocstrings: handlers: python: options: show_submodules: true Locally: ::: mypackage options: show_submodules: true | 7 | 9 |
74,229,470 | 2022-10-28 | https://stackoverflow.com/questions/74229470/i-have-issue-at-install-scikit-image-with-python-3-11-what-should-i-do | Good evening everyone, I have an issue with scikit-image while installing this package I installed python 3.11 on windows 11 pip install scikit-image I got these issues as below in the screenshot got previous issue EDIT: I installed Microsoft C++ 14 but I got another issue at the below screenshot enter image descripti... | The issue is that no wheels are available for scikit-image for Python 3.11 Python libraries can have code that is not written in Python (like C, C++, FORTRAN, Rust, ...) and in order to use those, you need to compile that code for your version of Python, your OS and CPU architecture. Fortunately, Python offers a packag... | 4 | 4 |
74,232,611 | 2022-10-28 | https://stackoverflow.com/questions/74232611/how-to-apply-operations-on-each-array-item-in-a-column-in-presto | We want to check if the array items in text_array column start with "a" in the input table, and store the results into the third column, so we get the following output table. My first question is: Is there any way to get output table from input table using presto? In python we can define a function for it, like: def m... | You can use transform from array functions: - sample data with dataset(id, text_array) AS ( values (1, array['ax', 'by']), (2, array['ax', 'ay', 'cz']) ) -- query select *, transform(text_array, el -> el like 'a%') starts_with_a from dataset; Output: id text_array starts_with_a 1 [ax, by] [true, false] 2 [ax... | 3 | 3 |
74,209,534 | 2022-10-26 | https://stackoverflow.com/questions/74209534/check-which-decorator-was-applied-to-a-function | Following this question I have an idea how to check whether my function was decorated or not. Only that I need further information, namely the decorators that were actually applied onto the function (or called when the function was called if it suits better). For being safe from the danger mentioned in this answer, I a... | TL;DR Roll your own @wraps. import functools def update_wrapper(wrapper, wrapped, decorator, **kwargs): wrapper = functools.update_wrapper(wrapper, wrapped, **kwargs) if decorator is not None: __decorators__ = getattr(wrapper, "__decorators__", []) setattr(wrapper, "__decorators__", __decorators__ + [decorator]) return... | 5 | 1 |
74,233,332 | 2022-10-28 | https://stackoverflow.com/questions/74233332/dataclass-optional-field-that-is-inferred-if-missing | I want my dataclass to have a field that can either be provided manually, or if it isn't, it is inferred at initialization from the other fields. MWE: from collections.abc import Sized from dataclasses import dataclass from typing import Optional @dataclass class Foo: data: Sized index: Optional[list[int]] = None def _... | Use NotImplemented from collections.abc import Sized from dataclasses import dataclass @dataclass class Foo: data: Sized index: list[int] = NotImplemented def __post_init__(self): if self.index is NotImplemented: self.index = list(range(len(self.data))) | 4 | 2 |
74,227,476 | 2022-10-27 | https://stackoverflow.com/questions/74227476/groupby-with-condition-count-mean | im having the dataframe: test = pd.DataFrame({'Date': [2020 - 12 - 30, 2020 - 12 - 30, 2020 - 12 - 30, 2020 - 12 - 31, 2020 - 12 - 31, 2021 - 0o1 - 0o1, 2021 - 0o1 - 0o1], 'label': ['Positive', 'Positive', 'Negative', 'Negative','Negative', 'Positive', 'Positive'], 'score': [70, 80, 50, 50, 30, 90, 70]}) Output: Date... | Another possible solution, which is based on the following ideas: Doing a pivot table indexing only on Date and aggregating with sum and count. Using the pivot table to construct a dataframe with the wanted result. aux = df.pivot_table(index=['Date'], columns='label', values='score', aggfunc=[ 'sum', 'count'], fill... | 5 | 1 |
74,224,196 | 2022-10-27 | https://stackoverflow.com/questions/74224196/pythonmodelcontext-object-returned-from-mlflow-pyfunc-load-model-how-to-retr | I am creating a custom myflow.pyfunc object that I would like to save to MLFlow and retrieve later. I don't understand the relationship between the object that is saved with mlflow.pyfunc.save_model(), and the one that is retrieved with mlflow.pyfunc.load_model(). The loaded model is a 'PythonModelContext' object rathe... | If you take a close look at the signature of the abstract method predict() in the mlflow.pyfunc.PythonModel class that you are extending, you will see that has 3 parameters: def predict(self, context, model_input): So, if you change your simple class to have the extra parameter context, your example should work: class... | 4 | 2 |
74,229,371 | 2022-10-27 | https://stackoverflow.com/questions/74229371/how-to-get-previous-min-and-max-values-in-new-columns-for-each-group | In each new row of dataframe, I need to keep track of min and max values for a previous group of records. Create dataframe with input data: import pandas as pd columns = ['timestamp','groupid','value'] data = [['2022-10-14 11:47:38',1000,200], ['2022-10-14 11:47:39',1000,210], ['2022-10-14 11:47:40',1000,220], ['2022... | Maybe not the prettiest solution: df["tmp"] = (df["groupid"] != df["groupid"].shift()).cumsum() grps = df.groupby("groupid")["value"] df["min"] = grps.transform("min") df["max"] = grps.transform("max") mapper = df.drop_duplicates("tmp").set_index("tmp")[["min", "max"]] tmp1 = df["tmp"] - 1 tmp2 = df["tmp"] - 2 df["pmin... | 3 | 1 |
74,230,719 | 2022-10-28 | https://stackoverflow.com/questions/74230719/how-to-use-unique-constraint-for-same-models | I want to create only one object for the same users. class MyModel(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL,...) user2 = models.ForeignKey(settings.AUTH_USER_MODEL,...) class Meta: constraints = [ UniqueConstraint( fields=['user1', 'user2'], name='user_unique', ), # UniqueConstraint( # fields=[... | Since Django 4.0 constraints now support expressions, this allows us to use database functions in our constraints allowing us to create a unique constraint with sorted fields: from django.db.models.functions import Least, Greatest class MyModel(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL,...) user... | 5 | 3 |
74,202,814 | 2022-10-26 | https://stackoverflow.com/questions/74202814/in-python-create-index-from-flat-representation-of-nested-structure-in-a-list | I have lists where each entry is representing a nested structure, where / represents each level in the structure. ['a','a/b/a','a/b','a/b/d',....] I want to take such a list and return an index list where each level is sorted in alphabetical order. If we had the following list ['a','a/b','a/b/a','a/c','a/c/a','b'] It... | Since the goal is to simply convert the paths to indices according to their respective positions against other paths of the same prefix, there is no need to build a tree at all. Instead, iterate over the paths in alphabetical order while using a dict of sets to keep track of the prefixes at each level of paths, and joi... | 5 | 1 |
74,214,343 | 2022-10-26 | https://stackoverflow.com/questions/74214343/minimum-amount-of-numbers-to-change-inside-of-nn-matrix-to-make-it-symmetrical | There is a n*n matrix made of numbers 0 - 9. For example: 6 0 0 8 9 6 1 5 1 6 8 1 1 0 4 2 1 3 7 1 5 8 8 6 6 2 5 2 7 9 4 6 9 6 4 1 4 7 8 5 3 8 9 4 8 3 9 2 9 I need to find the minimum amount of numbers to change (inside the matrix) to make it symmetrical about multiple lines (/, \, -, |) at once. I made four functions ... | You can try this: import numpy as np import scipy a = np.array([[6, 0, 0, 8, 9, 6, 1], [5, 1, 6, 8, 1, 1, 0], [4, 2, 1, 3, 7, 1, 5], [8, 8, 6, 6, 2, 5, 2], [7, 9, 4, 6, 9, 6, 4], [1, 4, 7, 8, 5, 3, 8], [9, 4, 8, 3, 9, 2, 9]]) def symm(a, pattern="hvdc"): b = np.stack([np.rot90(a, k=i) for i in range(4)]) b = np.concate... | 4 | 2 |
74,228,995 | 2022-10-27 | https://stackoverflow.com/questions/74228995/how-to-pass-a-json-or-dict-into-a-dataframe-with-pandas | I have this JSON/DICT in Python and I need to pass it to a datframe: { "filters": [ { "field": "example1", "operation": "like", "values": [ "Completed" ] }, { "field": "example2", "operation": "like", "values": [ "value1", "value2", "value3", ] } ] } DF that i need: example1 example2 Completed ["value1","value... | Try: dct = { "filters": [ {"field": "example1", "operation": "like", "values": ["Completed"]}, { "field": "example2", "operation": "like", "values": [ "value1", "value2", "value3", ], }, ] } df = pd.DataFrame( [ { f["field"]: f["values"][0] if len(f["values"]) == 1 else f["values"] for f in dct["filters"] } ] ) print(d... | 3 | 3 |
74,225,875 | 2022-10-27 | https://stackoverflow.com/questions/74225875/functools-cache-notify-that-the-result-is-cached | import functools @functools.cache def get_some_results(): return results Is there a way to notify the user of the function that the results they are getting are a cached version of the original for any other time they are calling the function? | This isn't a perfect approach, but you could use a custom decorator instead of @functools.cache which would then wrap your function with functools.cache and gather the cache stats before and after the call to determine if the lookup resulted in a cache hit. This was hastily thrown together but seems to work: def cache_... | 3 | 5 |
74,226,092 | 2022-10-27 | https://stackoverflow.com/questions/74226092/how-to-unpack-a-variable-in-a-lambda-function | Given an input tuple, the goal is to produce a dictionary with some pre-defined keys, e.g. in this case, we have an add_header lambda and use the unpacking inside when calling the function. >>> z = (2, 1) >>> add_header = lambda x, y: {"EVEN": x, "ODD": y} >>> add_header(*z) {'EVEN': 2, 'ODD': 1} My question is, is th... | You can try using dict() with zip(): z = (2, 1) add_header = lambda tpl: dict(zip(("EVEN", "ODD"), tpl)) print(add_header(z)) Prints: {'EVEN': 2, 'ODD': 1} | 3 | 2 |
74,222,179 | 2022-10-27 | https://stackoverflow.com/questions/74222179/how-to-split-a-numpy-array-of-integers-into-chunks-that-have-successive-values | I have the following numpy array with positive integers, in ascending order: import numpy as np arr = np.array([222, 225, 227, 228, 230, 232, 241, 243, 244, 245, 252, 253, 258]) I want to split it, into parts, where at each part, each number has maximum difference of 2 from the next one. So the following array should ... | You can compute the diff, get the indices of differences above threshold with flatnonzero, and split with array_split: threshold = 2 out = np.array_split(arr, np.flatnonzero(np.diff(arr)>threshold)+1) output: [array([222]), array([225, 227, 228, 230, 232]), array([241, 243, 244, 245]), array([252, 253]), array([258])]... | 4 | 5 |
74,221,419 | 2022-10-27 | https://stackoverflow.com/questions/74221419/pandas-merging-two-dfs-with-different-amount-of-rows | I have two dataframes that both have a column that can have the same number/value in it. One 'small df with ~300 rows (which is my leading file) and 1 df with ~ 5000 rows. I want to merge on 1 column but I cannot get the same amount of rows when I print the data. first (small) dataframe (left): import pandas as pd df1 ... | Try dataframe.join you can specify how='left which is by default import pandas as pd df = pd.DataFrame({"a": [0,0,1,1,2,2,2,]}) df2 = pd.DataFrame({"a": [0, 1,2,3,4,5,6,7,8,9], "b": list("abcdefghij")}) df.join(df2, on="a", lsuffix="df_a", rsuffix="df_b") # output adf_a adf_b b 0 0 0 a 1 0 0 a 2 1 1 b 3 1 1 b 4 2 2 c 5... | 4 | 5 |
74,206,978 | 2022-10-26 | https://stackoverflow.com/questions/74206978/why-does-this-specific-code-run-faster-in-python-3-11 | I have the following code in a Python file called benchmark.py: source = """ for i in range(1000): a = len(str(i)) """ import timeit print(timeit.timeit(stmt=source, number=100000)) When I tried to run with multiple python versions I am seeing a drastic performance difference. C:\Users\Username\Desktop>py -3.10 benchm... | There's a big section in the "what's new" page labeled "faster runtime". It looks like the most likely cause of the speedup here is PEP 659, which is a first start towards JIT optimization (perhaps not quite JIT compilation, but definitely JIT optimization). Particularly, the lookup and call for len and str now bypass ... | 6 | 7 |
74,214,619 | 2022-10-26 | https://stackoverflow.com/questions/74214619/how-to-use-tkinter-after-method-to-delay-a-loop-instead-time-sleep | I´m trying to create a simple thing: a loop with a delay of x seconds between iterations, triggered by a Tkinter button command. The obvious answer is to use time.sleep(), however, this actually freezes the mainloop process, avoiding other events to be captured. I´ve searched and the recommendation is to use the tkinte... | I would suggest you to use the tksleep for this task. While @Bryan Oakley's answer is the canonical and produces lesser overhead, tksleep can ease things out by a lot. You can have a control flow over multiple for-loops or even while loops are possible with this technique. Take this example text here: example = ''' Lor... | 4 | 2 |
74,217,557 | 2022-10-27 | https://stackoverflow.com/questions/74217557/the-precision-of-decimal-library-in-python | From the documentation page of Decimal, I thought that once we use decimal to compute, it'll be a correct result without any floating error. But when I try this equation from decimal import Decimal, getcontext getcontext().prec = 250 a = Decimal('6') b = Decimal('500000') b = a ** b print('prec: ' + str(getcontext().pr... | The Documentation clearly show the parameters of getcontext() when you simply execute getcontext() it can show its built-in parameters. Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]) When you can change getcontex... | 6 | 2 |
74,214,488 | 2022-10-26 | https://stackoverflow.com/questions/74214488/check-that-function-return-types-match-the-def-statements-in-pr-test-in-python | I have a Github Action that runs unit tests on each Pull Request (PR). It effectively runs pytest. Seeing that we leverage the type hints introduced in PEP 484, I'd like a method like this to cause a PR check fail: def return_an_int() -> int: return 'not an int' Is there a simple way to run such a "compilation" test (... | This is the kind of type checking that mypy does, so you could include running mypy in your Action workflow. If your module and its dependencies are already installed in your workflow, this step should do the trick: - name: Run mypy run: | # needed if mypy isn't already installed pip install mypy # "mypy somedir" look... | 4 | 4 |
74,215,857 | 2022-10-27 | https://stackoverflow.com/questions/74215857/how-to-set-a-pandas-periodindex-with-yearly-frequency | I am able to create quarterly and monthly PeriodIndex like so: idx = pd.PeriodIndex(year=[2000, 2001], quarter=[1,2], freq="Q") # quarterly idx = pd.PeriodIndex(year=[2000, 2001], month=[1,2], freq="M") # monthly I would expect to be able to create a yearly PeriodIndex like so: idx = pd.PeriodIndex(year=[2000, 2001], ... | month and year are both required "fields" due to the current implementation (through pandas 1.5.1 at least). Most other field values will be configured with a default value, however, neither month or year will be defined if a value is not provided. Therefore, in this case, month will remain None which causes the error ... | 3 | 3 |
74,214,615 | 2022-10-26 | https://stackoverflow.com/questions/74214615/how-to-update-python-version-in-terminal | I've updated my version of Python to 3.11, but Terminal is printing different versions, depending on what command I enter. Entering python3 --version prints Python 3.9.13. Entering python --version prints Python 3.9.6. When I go to the actual Python framework, I can see that 3.11 is installed and is the current version... | I think you might be missing some foundational knowledge about how versions are selected from a terminal. You'll want to do some learning about PATH environment variable and how that relates to python versions. https://www.tutorialspoint.com/python/python_environment.htm#:~:text=The%20path%20is%20stored%20in,sensitive%... | 9 | -1 |
74,210,613 | 2022-10-26 | https://stackoverflow.com/questions/74210613/upgrading-python-version-to-3-9-on-macos-now-gives-variable-not-defined-error | I just upgraded from Python 3.7 to 3.9.14 and it now gives a variable not defined error. The same code works fine locally and remotely where Python 3.9.2 is installed but now locally it gives an error in Python 3.9.14 version. Below is the code: def check(url): result = None product = Product(url, user_agents) if produ... | You must be on OS-X. On that OS, Python changed across this versions the default method to spawn sub-processes - that also explains why it "works on Python 3.9 remotely": the remote deploy must be on a Linux or other Unix than MacOS - Bear with me: the default child-process creation method used to be "fork" for all Uni... | 3 | 7 |
74,209,153 | 2022-10-26 | https://stackoverflow.com/questions/74209153/pandas-split-column-if-condition-else-null | I want to split a column. If it has a letter (any letter) at the end, this will be the value for the second column. Otherwise, the second column should be null import pandas as pd data = pd.DataFrame({"data": ["0.00I", "0.01E", "99.99", "0.14F"]}) desired result: a b 0 0.00 I 1 0.01 E 2 99.99 None 3 0.14 F | You can use str.extract with the (\d+(?:\.\d+)?)(\D)? regex: out = data['data'].str.extract(r'(\d+(?:\.\d+)?)(\D)?').set_axis(['a', 'b'], axis=1) Or, if you want to remove the original 'data' column while adding new columns in place: data[['a', 'b']] = data.pop('data').str.extract('(\d+(?:\.\d+)?)(\D)?') output: a b... | 3 | 3 |
74,207,589 | 2022-10-26 | https://stackoverflow.com/questions/74207589/how-to-make-a-pyramid-using-recursion-in-python | I need to make a pyramid in python using recursion. Already made it, but I need help making it with recursion. def pyramid(n): for i in range(0, n): for j in range(0, i+1): print("* ",end="") print("\r") pyramid(5) | Recursion = the repeated application of a recursive procedure. Code: def pyramid(n): if n==0: return else: pyramid(n-1) print("* "*n) n = 10 pyramid(n) This just repeats the function until n = 0. | 3 | 5 |
74,201,826 | 2022-10-26 | https://stackoverflow.com/questions/74201826/return-day-of-the-year-with-a-for-loop-that-takes-the-month-day-as-input | I need to write a function called day_of_the_year that takes a month and day as input and returns the associated day of the year. Let the month by a number from 1 (representing January) to 12 (representing December). For example: day_of_the_year(1, 1) = 1 day_of_the_year(2, 1) = 32 day_of_the_year(3, 1) = 60 Use a loo... | Yes, you are exiting your loop on the first pass every time. What you should do is define the total variable outside of the for loop and then increment it on each iteration. You also only need to iterate to the month that is specified so use the range function to loop. And since day_of_the_year is the name of the funct... | 4 | 1 |
74,201,807 | 2022-10-26 | https://stackoverflow.com/questions/74201807/numpy-reshape-the-matrix | Does anyone can tell me how to use Numpy to reshape the Matrix [1,2,3,4] [5,6,7,8] [9,10,11,12] [13,14,15,16] to [16,15,14,13] [12,11,10,9] [8,7,6,5] [4,3,2,1] Thanks:) python 3.8 numpy 1.21.5 an example of my matrixs: [[ 1.92982258e+00 1.96782439e+00 2.00233048e-01 3.95128552e-01 4.21665915e-01 -1.10885581e-01 3.159... | You can rotate the matrix with numpy.rot90(). To get two rotations as your example, pass in k=2: import numpy as np a = np.array([ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], ]) np.rot90(a, k=2) returning: array([[16, 15, 14, 13], [12, 11, 10, 9], [ 8, 7, 6, 5], [ 4, 3, 2, 1]]) Note the docs that say it return... | 3 | 4 |
74,168,582 | 2022-10-23 | https://stackoverflow.com/questions/74168582/how-to-read-the-request-body-using-orjson-library-in-fastapi | I am writing code to receive a JSON payload in FastAPI. Here is my code: from fastapi import FastAPI, status, Request from fastapi.responses import ORJSONResponse import uvicorn import asyncio import orjson app = FastAPI() @app.post("/", status_code = status.HTTP_200_OK) async def get_data(request: Request): param = aw... | Reading request data using orjson When calling await request.json(), FastAPI (actually Starlette) first reads the body (using the .body() method of the Request object), and then calls json.loads() (using the standard json library of Python) to return a dict/list object to you inside the endpoint—it doesn't use json.dum... | 7 | 9 |
74,200,120 | 2022-10-25 | https://stackoverflow.com/questions/74200120/how-to-use-a-polars-column-with-offset-string-to-add-to-another-date-column | Suppose you have df=pl.DataFrame( { "date":["2022-01-01", "2022-01-02"], "hroff":[5,2], "minoff":[1,2] }).with_columns(pl.col('date').str.to_date()) and you want to make a new column that adds the hour and min offsets to the date column. The only thing I saw was the dt.offset_by method. I made an extra column df=df.wi... | Use pl.duration: import polars as pl df = pl.DataFrame({ "date": pl.Series(["2022-01-01", "2022-01-02"]).str.to_date(), "hroff": [5, 2], "minoff": [1, 2] }) print(df.select( pl.col("date") + pl.duration(hours=pl.col("hroff"), minutes=pl.col("minoff")) )) shape: (2, 1) ┌─────────────────────┐ │ date │ │ --- │ │ datetim... | 3 | 4 |
74,183,293 | 2022-10-24 | https://stackoverflow.com/questions/74183293/how-do-i-add-the-result-of-an-apply-map-rows-as-a-new-column-in-polars | I have a wide dataframe, and I'm applying some custom logic to some columns to generate a new column. This works, and returns a dataframe with a single column with my desired values. How can I get this as a new column in the original dataframe? I tried various forms of .with_columns but none did the trick; and without ... | If you want to apply a function over multiple columns you need to pack them into a struct type. This packing is free, but is needed to suffice the expression rules, that every expressions input only consist of a single datatype. E.g. an expression is Fn(Expr) -> Expr. Below shows an example of using map_elements to com... | 3 | 7 |
74,165,901 | 2022-10-22 | https://stackoverflow.com/questions/74165901/polars-add-substract-utc-offset-from-datetime-object | I wanted to add/subtract the UTC offset (usually in hours) to/from the datetime object in polars but I don't seem to see a way to do this. the UTC offset can be dynamic given there's Day Light Saving period comes into play in a calendar year. (e.g., EST/EDT maps to 5/4 hours of UTC offset respectively). from datetime i... | It seems you're looking for convert_time_zone. Ex: from datetime import date import polars as pl df = pl.DataFrame( pl.datetime_range( start=date(2022, 1, 3), end=date(2022, 9, 30), interval="5m", time_unit="ns", time_zone="UTC", eager=True ).alias("timestamp") ) us_df = df.with_columns( pl.col("timestamp").dt.convert_... | 3 | 5 |
74,126,454 | 2022-10-19 | https://stackoverflow.com/questions/74126454/how-to-get-only-the-index-in-numpy-where-instead-of-a-tuple | I have an array of strings arr in which I want to search for elements and get the index of element. Numpy has a method where to search element and return index in a tuple form. arr = numpy.array(["string1","string2","string3"]) print(numpy.where(arr == "string1") It prints: (array([0], dtype=int64),) But I only want ... | TL;DR Use: try: i = numpy.where(arr == "string1")[0][0] except IndexError: # handle the case where "string1" was not found in arr or indices = list(numpy.where(arr == "string1")[0]) Details Finding elements in NumPy arrays is not intuitive the first time you try to do it. Let's decompose the operation: >>> arr = nump... | 4 | 4 |
74,184,818 | 2022-10-24 | https://stackoverflow.com/questions/74184818/pandas-type-object-is-not-subscriptable | I am trying to type a a function which receives a Series from typing import Any from pandas import Series def func(w: Series[Any], v: Series[Any]) -> int: However I got the error TypeError: 'type' object is not subscriptable What I am doing wrong? | Adding quotes around the type will fix this issue. In the code you provided: from typing import Any from pandas import Series def func(w: 'Series[Any]', v: 'Series[Any]') -> int: # your code pass Modern editors will identify the type and raise appropriate warnings or errors if violated. You are not doing anything "wro... | 7 | 1 |
74,179,020 | 2022-10-24 | https://stackoverflow.com/questions/74179020/the-unique-method-must-be-invoked-on-this-result-exception-raised-after-sqlalc | I have an issue with SQLAlchemy and I cannot figure out the cause of this error: so my class definition is: class PricingFrequency(enum.Enum): month = 'month' year = 'year' class PlanPricing(Base): __tablename__ = "PlansPricing" pricing_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) ..... subscri... | You are getting this error: sqlalchemy.exc.InvalidRequestError: The unique() method must be invoked on this Result, as it contains results that include joined eager loads against collections Reason: Quoting the documentation in Joined Eager Loading: When including joinedload() in reference to a one-to-many or many-to-... | 16 | 20 |
74,139,174 | 2022-10-20 | https://stackoverflow.com/questions/74139174/how-to-mock-mongo-with-python | How to create a mocked mongo db object to test my software using python? I tried https://pytest-mock-resources.readthedocs.io/en/latest/mongo.html but got error. First, i tried the code below: def insert_into_customer(mongodb_connection): collection = mongodb_connection['customer'] to_insert = {"name": "John", "address... | import mongomock client = mongomock.MongoClient() database = client.__getattr__(database_name) collection = database.__getattr__(collection_name) You can define as many as client, database and collections you need at the same time. | 5 | 4 |
74,120,614 | 2022-10-19 | https://stackoverflow.com/questions/74120614/how-to-play-sound-in-an-android-app-created-by-beeware-using-python | I used the BeeWare environment to create a simple MahJong game (find & click pairs to remove them) using Python (with Toga as layout tool) for Android. Now I would like to have some buttons give a "click sound" when pressed: Anyone have a helping hint (or even working example)? | If you're using Briefcase 0.3.10 or newer (which uses Chaquopy to support Python on Android), then you could use the Chaquopy Python API to play audio files using SoundPool. For example, the code from this answer could be written in Python as follows: from android.media import AudioManager, SoundPool from os.path impor... | 4 | 4 |
74,127,871 | 2022-10-19 | https://stackoverflow.com/questions/74127871/how-do-i-detect-an-ean-13-5-supplement-barcode-using-python-or-nodejs | I'm trying to find a way to get the UPC plus the 5 number supplement barcode using Python or NodeJS. So far I've tried using pyzbar in Python via this code. img = Image.open(requests.get(url, stream=True).raw) img = ImageOps.grayscale(img) results = decode(img) That only returns the main UPC code. Not the supplementa... | Install the dependencies (on mac + python): $ brew install zbar $ pip install pyzbar $ pip install opencv-python You can define the symbols to ZBar. Please try this python code: import cv2 import pyzbar.pyzbar as pyzbar from pyzbar.wrapper import ZBarSymbol img = cv2.imread('barcode.png') gray = cv2.cvtColor(img, cv2.... | 4 | 12 |
74,163,185 | 2022-10-22 | https://stackoverflow.com/questions/74163185/send-premium-emoji-with-pyrogram | I need to send a premium emoji on the user's account using Pyrogram. I tried to send with send_message() a list of MessageEntityCustomEmoji and MessageEntity. The first one gave the error 'MessageEntityCustomEmoji' object has no attribute '_client', and the second one sent a message without an emoji. How do I send them... | After lots of research and suffering, the answer was: ... my_emoji_str = "<emoji id=5310129635848103696>✅</emoji> And this is custom emoji in the text" await app.send_message(message.chat.id, my_emoji_str) This is basically a text formatting, here it is in HTML ParseMode of Pyrogram, but Pyrogram supports both Markdow... | 4 | 4 |
74,163,301 | 2022-10-22 | https://stackoverflow.com/questions/74163301/how-to-properly-use-regex-in-cors-middleware-for-fastapi | I have an app that uses a FastAPI backend and a Next.js frontend. In development and on production with stable origins, I am able to use the CORSMiddleware with no issues. However, I have deployed the Next.js frontend with Vercel, and want to take advantage of the automatic Preview deployments that Vercel makes with ea... | Whenever a new deployment is created, Vercel will automatically generate a unique URL that is publicly available, and which is composed of the following pieces: <project-name>-<unique-hash>-<scope-slug>.vercel.app To allow requests from any Vercel deployment, use: allow_origin_regex='https://.*\.vercel\.app' To allow... | 3 | 3 |
74,191,241 | 2022-10-25 | https://stackoverflow.com/questions/74191241/multiple-imshow-on-the-same-plot-with-opacity-slider | With Plotly, I'd like to display two imshow on the same page, at the same place, with opacity. This nearly works: import plotly.express as px, numpy as np from skimage import io img = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg') fig = px.imshow(img) x = np... | As pointed out by the OP, since opacity is a style attribute applied by the client regardless of the trace (data) which is associated to a given image, there is no need to precompute one trace for each image variation, nor to redraw anything when the slider moves. Using simple slider controls, we should be able to appl... | 4 | 2 |
74,134,920 | 2022-10-20 | https://stackoverflow.com/questions/74134920/why-does-my-conda-deactivate-doesnt-work | I am having troubles with my conda installation on a cluster. It seems that i can't deactivate any of my environments. it goes so far, that i have to close my terminal because it froze. I am working on multiple server with a common home directory, so i can access the same conda installation from different servers. Inte... | thanks to @merv I could easily solve the problem. Running conda init bash and restarting the terminal seems to clean something and now it works as well. I can see again my prompt and the environments are closing again. yeroslaviz@hpcl8001:~$ conda init bash modified /fs/home/yeroslaviz/miniconda3/condabin/conda modifie... | 3 | 8 |
74,194,672 | 2022-10-25 | https://stackoverflow.com/questions/74194672/cmake-problems-after-upgrading-to-macos-13-0 | As mentioned on the title, CMake seems to be broken after upgrading to MacOS 13.0. Trying to install something that requires Cmakes takes unusually long then the following pop-up shows up. “CMake” is damaged and can’t be opened. You should move it to the Trash. This file was downloaded on an unknown date. # this txt is... | The pip package is broken on macOS 13 prior to CMake 3.24.2 due to improper code signing. You should upgrade CMake in your virtual environment by running: $ python -m pip install -U pip setuptools wheel $ python -m pip install -U 'cmake>=3.24.2' As CMake is extremely backwards compatible, it should be safe. You can al... | 7 | 4 |
74,186,452 | 2022-10-24 | https://stackoverflow.com/questions/74186452/python-typing-overload-based-on-length-of-tuple-argument | I would like to add overloaded type annotations to an existing API that has semantics something like this: def f(x: Tuple[int, ...]) -> Union[int, List[int]]: if len(x) == 1: return x[0] return list(x) The argument is a tuple, and the return type is either int or List[int] depending on whether the tuple has length 1. ... | The "overlap with incompatible return types" error message can sometimes be a little bit of a lint, as opposed to something broken. If you # type: ignore, mypy will still do what you want. (I'm a maintainer of mypy) | 4 | 1 |
74,155,189 | 2022-10-21 | https://stackoverflow.com/questions/74155189/how-to-log-uncaught-exceptions-in-flask-routes-with-logging | What is the standard way to log uncaught expressions in Flask routes with logging? This nearly works: import logging, sys, flask logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s %(levelname)s %(message)s') sys.excepthook = lambda exctype, value, tb: logging.error("", exc_info=(exctype, value, ... | How to log uncaught exceptions in Flask routes with logging? Flask is a popular web framework for Python that allows you to create web applications easily and quickly. However, sometimes your Flask routes may encounter uncaught exceptions that cause your application to crash or return an error response. To debug and fi... | 5 | 6 |
74,184,794 | 2022-10-24 | https://stackoverflow.com/questions/74184794/how-to-find-a-distribution-function-from-the-max-min-and-average-of-a-sample | Given that I know the, Max, Min and Average of sample (I don't have access to the sample itself). I would like to write a generic function to generate a sample with the same characteristics. From this answer I gather that this is no simple task since many distribuitions can be found with the same characteristics. max, ... | Triangular distribution should perform your desired task since it takes three parameters (min, mode, max) as inputs that match your criteria. You can think of other distributions such as standard, uniform, and so on; however, all of their input parameters either lack or partially take one of the three input parameters ... | 3 | 4 |
74,151,442 | 2022-10-21 | https://stackoverflow.com/questions/74151442/how-to-incorporate-individual-measurement-uncertainties-into-gaussian-process | I have a set of observations, f_i=f(x_i), and I want to construct a probabilistic surrogate, f(x) ~ N[mu(x), sigma(x)], where N is a normal distribution. Each observed output, f_i, is associated with a measurement uncertainty, sigma_i. I would like to incorporate these measurement uncertainties into my surrogate, f_i, ... | Using your second approach, only slightly changing Alpha kernel = 1 * RBF(length_scale=9, length_scale_bounds=(10, 1e3)) gaussian_process = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9, normalize_y=True, alpha=errs**2) gaussian_process.fit((np.atleast_2d(xs).T), (fs)) mu, std = gaussian_process.predic... | 8 | 1 |
74,171,275 | 2022-10-23 | https://stackoverflow.com/questions/74171275/azure-function-not-running-on-m1 | Running import logging import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: retur... | I kept running into problems with python on my M1 Mac until I went completely to Rosetta on the command line. For that, I did the following: Update Rosetta: In a Terminal type: softwareupdate --install-rosetta In Finder, type ⇧⌘G and go to /Applications/Utilities. Then duplicate Terminal: Rename the second Termi... | 5 | 5 |
74,200,729 | 2022-10-25 | https://stackoverflow.com/questions/74200729/is-there-a-way-to-make-an-inherited-abstract-property-a-required-constructor-arg | I'm using Python dataclasses with inheritance and I would like to make an inherited abstract property into a required constructor argument. Using an inherited abstract property as a optional constructor argument works as expected, but I've been having real trouble making the argument required. Below is a minimal workin... | So, the thing is, you declared an abstract property. Not an abstract constructor argument, or an abstract instance dict entry - abc has no way to specify such things. Abstract properties are really supposed to be overridden by concrete properties, but the abc machinery will consider it overridden if there is a non-abst... | 3 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.