question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
70,268,140 | 2021-12-7 | https://stackoverflow.com/questions/70268140/could-not-load-dynamic-library-libcublaslt-so-11-dlerror-libcublaslt-so-11 | I just updated my graphics cards drives with sudo apt install nvidia-driver-470 sudo apt install cuda-drivers-470 I decided to install them in this manner because they were being held back when trying to sudo apt upgrade. I mistakenly then did sudo apt autoremove to cleanup old packages. After restarting my computer f... | You can create symlinks inside of /usr/lib/x86_64-linux-gnu directory. I found it by: $ whereis libcudart libcudart: /usr/lib/x86_64-linux-gnu/libcudart.so /usr/share/man/man7/libcudart.7.gz Within this folder you can find other versions of those cuda libraries. Then create symlinks like this. Your specific version th... | 9 | 6 |
70,265,343 | 2021-12-7 | https://stackoverflow.com/questions/70265343/python-fastapi-server-how-to-extend-connection-timeout | I'm using fastAPI python framework to build a simple POST/GET https server. On the client side, i send heartbeat POST messages every 10 seconds and i'd like to keep my connection open during this period. However, for some reason I see that every new heartbeat, my connection get disconnected by the peer, so I need to re... | From the uvicorn docs: --timeout-keep-alive <int> - Close Keep-Alive connections if no new data is received within this timeout. Default: 5. But it‘s probably no great idea to set this to 10 minutes. What is your problem with dropping the connection for a heartbeat? | 8 | 12 |
70,262,199 | 2021-12-7 | https://stackoverflow.com/questions/70262199/different-behavior-between-python-2-and-3-of-vars-in-list-comprehension | I am currently converting a script from Python 2 to Python 3. While debugging it, I stumbled upon a part of the code that behaves differently between both versions. However, I am unable to explain this difference. Here is a reproducer: variable_1 = "x" variable_2 = "y" list_of_variables = ['variable_1', 'variable_2'] e... | It's working in both: it's just working differently. In Python 3, list comprehensions create their own local scope to avoid leaking variable names into the calling scope. The call to vars() inside the list comprehension is just returning the variables defined in the list comprehension's own scope, not the scope where t... | 4 | 10 |
70,259,880 | 2021-12-7 | https://stackoverflow.com/questions/70259880/how-to-capture-messages-written-to-stderr-by-opencv | In case of invalid parameters, cv2.VideoWriter writes stuff to stderr. here is a minimal example: import cv2 cv2.VideoWriter("foo.mp4", cv2.VideoWriter_fourcc(*"mp4v"), 90000, (240, 240)) Running like so python3 video_verification/verification.py 2> err.txt one can see the expected errors in err.txt: [mpeg4 @ 0x13e46... | I've found the wurlitzer library, which can do exactly that, i.e., capture the streams written to by a C library: import cv2 from wurlitzer import pipes with pipes() as (out, err): cv2.VideoWriter("foo.mp4", cv2.VideoWriter_fourcc(*"mp4v"), 90000, (240, 240)) print(f"stderr: {err.read()}") | 5 | 4 |
70,259,852 | 2021-12-7 | https://stackoverflow.com/questions/70259852/what-is-the-difference-between-pathlib-and-os-path | Reading official documentation of both libraries: os.path See also The pathlib module offers high-level path objects. pathlib See also For low-level path manipulation on strings, you can also use the os.path module. So os.path is for low-level use and path lib for high level use. But what it means? I don't understa... | I see it as "Use pathlib if you are interested in working with the path as an abstract entity" , use "os.path" if you're really interested in the resources represented by that path; in most cases you are interested in the using the 'path' to learn about or handle resources. High level being 'the path as an abstract ent... | 7 | 4 |
70,254,535 | 2021-12-7 | https://stackoverflow.com/questions/70254535/how-to-list-all-packages-in-apples-conda-channel | I know Apple provides tensorflow-metal on their conda -c apple channel. How do I see the rest of the packages in that channel? The "answers" I found online address finding a package to install, like conda search *tensorflow* but this is not what I want. Instead, I would like to see what packages Apple has in their -c a... | Web Browser You can browse all packages in an Anaconda Cloud channel by visiting: https://anaconda.org/<channel_name>/repo For the apple channel, the tensorflow-deps package is the only package (right now). Conda CLI Alternatively, one can also use conda search with something like: $ conda search --override-channels -... | 5 | 4 |
70,241,246 | 2021-12-6 | https://stackoverflow.com/questions/70241246/is-it-possible-to-fit-a-scikit-learn-model-in-a-loop-or-with-an-iterator | Usually people use scikit-learn to train a model this way: from sklearn.ensemble import GradientBoostingClassifier as gbc clf = gbc() clf.fit(X_train, y_train) predicted = clf.predict(X_test) It works fine as long as users' memory is large enough to accommodate the entire dataset. The dilemma for me is exactly this--t... | After reading the section 6. Strategies to scale computationally: bigger data of the official manual mentioned by @StupidWolf in this post, I am aware that this question is more to this than meets the eye. The real difficulty is about the design of a lot of models. Take Random Forest as an example, one of the most impo... | 5 | 2 |
70,249,059 | 2021-12-6 | https://stackoverflow.com/questions/70249059/sort-a-subset-of-columns-of-a-pandas-dataframe-alphabetically-by-column-name | I'm having trouble finding the solution to a fairly simple problem. I would like to alphabetically arrange certain columns of a pandas dataframe that has over 100 columns (i.e. so many that I don't want to list them manually). Example df: import pandas as pd subject = [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,4,4,4,4,4,4] timepoi... | You can split your your dataframe based on column names, using normal indexing operator [], sort alphabetically the other columns using sort_index(axis=1), and concat back together: >>> pd.concat([df[['subject','timepoint']], df[df.columns.difference(['subject', 'timepoint'])]\ .sort_index(axis=1)],ignore_index=False,a... | 4 | 6 |
70,228,997 | 2021-12-4 | https://stackoverflow.com/questions/70228997/how-to-connect-sqlalchemy-to-snowflake-database-using-oauth2 | I need to connect to Snowflake using SQLAlchemy but the trick is, I need to authenticate using OAuth2. Snowflake documentation only describes connecting using username and password and this cannot be used in the solution I'm building. I can authenticate using Snowflake's python connector but I see no simple path how to... | Use snowflake.connector.connect to create a PEP-249 Connection to the database - see documentation. Then use param creator of create_engine (docs) - it takes a callable that returns PEP-249 Connection. If you use it then URL param is ignored. Example code: def get_connection(): return snowflake.connector.connect( user=... | 5 | 5 |
70,242,667 | 2021-12-6 | https://stackoverflow.com/questions/70242667/how-to-create-venv | I have been using my python v3.9 in my virtual environment, it contains all the packages and scripts i have been using for so long. But, now with the release of python v 3.10 it installed itself globally though I wanted it to be installed in same venv I was using for python v3.9 So, if anyone could help me with how can... | Simply put all the dependencies of your python 3.9 (venv) in requirements.txt file pip freeze > requirements.txt Create a new folder then move that file inside the newly created folder then execute the following code, it will create a new virtual environment with python 3.10 python -m venv newenv activate the newly c... | 7 | 14 |
70,235,264 | 2021-12-5 | https://stackoverflow.com/questions/70235264/beautiful-soup-select-google-image-returns-empty-list | I would like to retrieve information from Google Arts & Culture using BeautifulSoup. I have checked many of the stackoverflow posts ([1], [2], [3], [4], [5]), and still couldn't retrieve the information. I would like each tile (picture)'s (li) information such as href, however, find_all and select one return empty list... | Unfortunately, the problem is not that you're using BeautifulSoup wrong. The webpage that you're requesting appears to be missing its content! I saved html.text to a file for inspection: Why does this happen? Because the webpage actually loads its content using JavaScript. When you open the site in your browser, the b... | 5 | 2 |
70,235,696 | 2021-12-5 | https://stackoverflow.com/questions/70235696/checking-folder-and-if-it-doesnt-exist-create-it | I am quite new to python so I need some help. I would like to create a code that checks if a folder with a given name is created, if not, it creates it, if it exists, goes to it and in it checks if there is another folder with a given name, if not, it creates it. In my code I don't know how to go to folder that already... | If you want to create a folder inside a second folder or check the existence of them you can use builtin os library: import os PATH = 'folder_1/folder_2' if not os.path.exists(PATH): os.makedirs(PATH) os.makedirs() create all folders in the PATH if they does not exist. | 11 | 28 |
70,232,617 | 2021-12-5 | https://stackoverflow.com/questions/70232617/heatmap-error-nonetype-object-is-not-callable-when-using-with-dataframe | I have this issue with heatmap from seaborn. I don't know how, but seaborn.heatmap() refuses to take in dataframe, it instead show the mentioned error. Seaborn, matplotlib and pandas is up-to-date and I'm using python 3.10 on Visual Studio. The code is just a sample code from seaborn.heatmap itself: import pandas as pd... | Use Python 3.9 (or 3.8, 3.7, 3.6) as it seems like both pandas and plt are not quite ready to be used with Python 3.10: | 6 | 8 |
70,229,777 | 2021-12-4 | https://stackoverflow.com/questions/70229777/can-you-pre-install-libraries-on-databricks-pool-nodes | We have a number of Python Databricks jobs that all use the same underlying Wheel package to install their dependencies. Installing this Wheel package even with a node that has been idling in a Pool still takes 90 seconds. Some of these jobs are very long-running so we would like to use Jobs computer clusters for the l... | You can't install libraries directly into nodes from pool, because the actual code is executed in the Docker container corresponding to Databricks Runtime. There are several ways to speedup installation of the libraries: Create your own Docker image with all necessary libraries pre-installed, and pre-load Databricks R... | 6 | 3 |
70,231,487 | 2021-12-5 | https://stackoverflow.com/questions/70231487/output-dimensions-of-convolution-in-pytorch | The size of my input images are 68 x 224 x 3 (HxWxC), and the first Conv2d layer is defined as conv1 = torch.nn.Conv2d(3, 16, stride=4, kernel_size=(9,9)). Why is the size of the output feature volume 16 x 15 x 54? I get that there are 16 filters, so there is a 16 in the front, but if I use [(W−K+2P)/S]+1 to calculate ... | The calculation of feature maps is [(W−K+2P)/S]+1 and here [] brackets means floor division. In your example padding is zero, so the calculation is [(68-9+2*0)/4]+1 ->[14.75]=14 -> [14.75]+1 = 15 and [(224-9+2*0)/4]+1 -> [53.75]=53 -> [53.75]+1 = 54. import torch conv1 = torch.nn.Conv2d(3, 16, stride=4, kernel_size=(9,... | 8 | 11 |
70,227,330 | 2021-12-4 | https://stackoverflow.com/questions/70227330/maximum-path-sum-of-2-lists | My question is about this kata on Codewars. The function takes two sorted lists with distinct elements as arguments. These lists might or might not have common items. The task is find the maximum path sum. While finding the sum, if there any common items you can choose to change your path to the other list. The given e... | Your algorithm is actually fast, just your implementation is slow. The two things that make it take overall O(n²) time: l1.index(item) always searches from the start of the list. Should be l1.index(item, new_start1). itertools.islice(l1, new_start1, ...) creates an iterator for l1 and iterates over the first new_start... | 8 | 5 |
70,202,457 | 2021-12-2 | https://stackoverflow.com/questions/70202457/sorting-multiple-lists-together-in-place | I have lists a,b,c,... of equal length. I'd like to sort all of them the order obtained by sorting a, i.e., I could do the decorate-sort-undecorate pattern a, b, c = map(list, zip(*sorted(zip(a, b, c)))) or something like that. However, I'd like that the lists are sorted in place (I assume that sorted pulls everything... | I think "without creating temporary objects" is impossible, especially since "everything is an object" in Python. You could get O(1) space / number of objects if you implement some sorting algorithm yourself, though if you want O(n log n) time and stability, it's difficult. If you don't care about stability (seems like... | 11 | 11 |
70,227,908 | 2021-12-4 | https://stackoverflow.com/questions/70227908/iterating-over-rows-in-a-dataframe-in-pandas-is-there-a-difference-between-usin | When iterating through rows in a dataframe in Pandas, is there a difference in performance between using: for index in df.index: .... And: for index, row in df.iterrows(): .... ? Which one should be preferred? | When we doing for loop , look up index get the data require additional loc for index in df.index: value = df.loc['index','col'] When we do df.iterrows for index, row in df.iterrows(): value = row['col'] Since you already with pandas , both of them are not recommended. Unless you need certain function and cannot be ve... | 5 | 5 |
70,207,122 | 2021-12-2 | https://stackoverflow.com/questions/70207122/fastapi-some-requests-are-failing-due-to-10s-timeout | We have deployed a model prediction service in production that is using FastAPI and unfortunately, some of the requests are failing due to a 10s timeout. In terms of concurrent requests, we typically only load about 2/3 requests per second, so I wouldn't think that would be too much strain on FastAPI. The first thing w... | guidance on what the above segment implies here you have the official gunicorn config file with lot of explainations included. since you use gunicorn to manager uvicorn workers, forcing your timeout to 60 sec should work just fine for lnog running tasks (you should think about using a asynchronous task queue or job q... | 7 | 2 |
70,215,049 | 2021-12-3 | https://stackoverflow.com/questions/70215049/attributeerror-tfidfvectorizer-object-has-no-attribute-get-feature-names-out | Why do I keep on getting this error? I try other codes too, but once it uses the get_feature_names_out function it will pop out this error. Below is my code: from sklearn.datasets._twenty_newsgroups import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import Mul... | This is probably because you are using an older scikit-learn version than the one this code was written for. get_feature_names_out is a method of the class sklearn.feature_extraction.text.TfidfVectorizer since scikit-learn 1.0. Previously, there was a similar method called get_feature_names. So you should update your s... | 15 | 14 |
70,211,643 | 2021-12-3 | https://stackoverflow.com/questions/70211643/understanding-sklearn-calibratedclassifiercv | Hi all I am having trouble understanding how to use the output of sklearn.calibration.CalibratedClassifierCV. I have calibrated my binary classifier using this method, and results are greatly improved. However I am not sure how to interpret the results. sklearn guide states that, after calibration, the output of predi... | For me, you can actually use predict_proba() after calibration to apply a different cutoff. What happens within class CalibratedClassifierCV (as you noticed) is effectively that the output of predict() is based on the output of predict_proba() (see here for reference), i.e. np.argmax(self.predict_proba(X), axis=1) == s... | 7 | 2 |
70,213,579 | 2021-12-3 | https://stackoverflow.com/questions/70213579/how-to-install-libappindicator1-on-python-of-docker-image | I'd like to install goole chrome on Python of Docker image. So, I need install libappindicator1. However when I build this Dockerfile, I got error on libappindicator1 Dockerfile FROM python:3.9 # Install manually all the missing libraries RUN apt-get update RUN apt-get install -y gconf-service libasound2 libatk1.0-0 li... | I solved this problem by modifying the python image tag. python: 3.8 -> python: 3.8-buster When I use python: 3.8-bullseye I got the same error. So this error seems to be related with Debian 10 (bullseye). Note: buster is Debian 9 This is the reason, why Debian 10 (bullseye) can not install libappindicator1 5.3.1. No... | 6 | 12 |
70,209,111 | 2021-12-3 | https://stackoverflow.com/questions/70209111/how-to-swap-words-multiple-characters-in-a-string | Consider the following examples: string_now = 'apple and avocado' stringthen = string_now.swap('apple', 'avocado') # stringthen = 'avocado and apple' and: string_now = 'fffffeeeeeddffee' stringthen = string_now.swap('fffff', 'eeeee') # stringthen = 'eeeeefffffddffee' Approaches discussed in Swap character of string i... | Given that we want to swap words x and y, and that we don't care about the situation where they overlap, we can: split the string on occurrences of x within each piece, replace y with x join the pieces with y Essentially, we use split points within the string as a temporary marker to avoid the problem with sequential... | 10 | 17 |
70,205,486 | 2021-12-2 | https://stackoverflow.com/questions/70205486/clickable-hyperlinks-in-plotly-dash-datatable | There are several similar questions out there that I will reference in this, but I have a Dash DataTable with a column that I would like to make a clickable hyperlink. The table essentially looks like so: Date Ticket ID Work Order Link (s) 2018-08-30 22:52:25 1444008 119846184 google.com/woNum=119846184 2021-09-29 13:3... | If you make sure that the links are in Markdown format the solution suggested in the Plotly Dash community forum should work: import dash import dash_html_components as html import dash_table import pandas as pd df = pd.DataFrame({ 'Date': ['2018-08-30 22:52:25', '2021-09-29 13:33:49'], 'Ticket ID': [1444008, 1724734],... | 6 | 5 |
70,196,164 | 2021-12-2 | https://stackoverflow.com/questions/70196164/how-to-draw-oriented-edges-on-pyvis | I'm trying to plot an oriented graph with pyvis. In the documentation they suggest using the following command for creating an oriented edge: net.add_edge(4,1,from=1,to=4) The problems are two: I'm getting this error TypeError: add_edge() got multiple values for argument 'to' from is a python keyword so it can't ... | You don't need to directly specify to and from in your add_edge function if you had specified directed=True when you created your network. The order of the nodes in the add_edge function is enough to describe the direction. Below is an example: from pyvis.network import Network net = Network(directed =True) net.add_nod... | 6 | 11 |
70,197,646 | 2021-12-2 | https://stackoverflow.com/questions/70197646/python-add-weeks-to-date-from-df | How would I add two df columns together (date + weeks): This works for me: df['Date'] = pd.to_datetime(startDate, format='%Y-%m-%d') + datetime.timedelta(weeks = 3) But when I try to add weeks from a column, I get a type error: unsupported type for timedelta weeks component: Series df['Date'] = pd.to_datetime(startDate... | You can use the pandas to_timelta function to transform the number of weeks column to a timedelta, like this: import pandas as pd import numpy as np # create a DataFrame with a `date` column df = pd.DataFrame( pd.date_range(start='1/1/2018', end='1/08/2018'), columns=["date"] ) # add a column `weeks` with a random numb... | 5 | 4 |
70,197,944 | 2021-12-2 | https://stackoverflow.com/questions/70197944/webdriver-object-has-no-attribute-switch-to-frame | I cannot switch to the sucessfully identified iFrame(s). The script identifies the iFrame (checked in debugger), but the switch to the iFrame fails and runs into the exception trap. Few times ago it worked perfectly. Message='WebDriver' object has no attribute 'switch_to_frame' What happened in the meantime? Chromedri... | While switching to frame, the supported notations are: Switch to a frame using frame name: driver.switch_to.frame('frame_name') Switch to a frame using frame index: driver.switch_to.frame(1) Switch to a frame using frame element: driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0]) Switch to p... | 6 | 5 |
70,185,150 | 2021-12-1 | https://stackoverflow.com/questions/70185150/return-all-possible-entity-types-from-spacy-model | Is there a method to extract all possible named entity types from a model in spaCy? You can manually figure it out by running on sample text, but I imagine there is a more programmatic way to do this? For example: import spacy model=spacy.load("en_core_web_sm") model.*returns_entity_types* | The statistical pipeline components like ner provide their labels under .labels: import spacy nlp = spacy.load("en_core_web_sm") nlp.get_pipe("ner").labels | 12 | 23 |
70,187,208 | 2021-12-1 | https://stackoverflow.com/questions/70187208/in-pandas-how-to-pivot-a-dataframe-on-a-categorical-series-with-missing-categor | I have a pandas dataframe with a categorical series that has missing categories. In the example shown below, group has the categories "a", "b", and "c", but there are no cases of "c" in the dataframe. import pandas as pd dfr = pd.DataFrame({ "id": ["111", "222", "111", "333"], "group": ["a", "a", "b", "b"], "value": [1... | pd.pivot_table has a dropna argument which dictates dropping or not value columns full of NaNs. Try setting it to False: import pandas as pd dfr = pd.DataFrame({ "id": ["111", "222", "111", "333"], "group": ["a", "a", "b", "b"], "value": [1, 4, 9, 16]}) dfr["group"] = pd.Categorical(dfr["group"], categories=["a", "b", ... | 6 | 5 |
70,184,440 | 2021-12-1 | https://stackoverflow.com/questions/70184440/how-can-i-unpack-a-pydantic-basemodel-into-kwargs | I am trying to make a function that takes a pydantic BaseModel as an input to run another function. I need to unpack the BaseModel into kwargs. I tried doing this: def run_routing_from_job(job): return run_routing( job.inputs.input_file, **job.inputs.config.dict() ) where job is of the format class Job(BaseModel): cli... | I worked it out, just replace .dict() with __dict__ def run_routing_from_job(job): return run_routing( job.inputs.input_file, **job.inputs.config.__dict__ ) | 7 | 3 |
70,184,091 | 2021-12-1 | https://stackoverflow.com/questions/70184091/matplotlib-axes-axes-set-xticks-throws-set-ticks-takes-2-positional-arguments | this easy example from matplotlib throws the mentioned error: https://matplotlib.org/stable/gallery/lines_bars_and_markers/barchart.html I also cannot find any typo according to the documentation of set_xticks(): https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xticks.html Can anyone provide clearific... | This is error is based on the matplotlib version you use. The set_axis command was changed from matplotlib version 3.4.x to 3.5.x. Try using the newer version. You can install it via $ pip install matplotlib==3.5.0 | 11 | 12 |
70,111,401 | 2021-11-25 | https://stackoverflow.com/questions/70111401/python-3-10-pattern-matching-pep-634-wildcard-in-string | I got a large list of JSON objects that I want to parse depending on the start of one of the keys, and just wildcard the rest. A lot of the keys are similar, like "matchme-foo" and "matchme-bar". There is a builtin wildcard, but it is only used for whole values, kinda like an else. I might be overlooking something but ... | You can use a guard. for event in data: match event: case {'id': x} if x.startswith("matchme"): # guard print(event["message"]) case {'id':'anotherid'}: print(event["message"]) Quoting from the official documentation: Guard We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes o... | 29 | 38 |
70,177,062 | 2021-11-30 | https://stackoverflow.com/questions/70177062/cartopy-not-able-to-identify-geos-for-proj-install-on-windows | I am trying to install Cartopy on Windows. I have installed all the dependencies from their website, however when I go to run pip install Cartopy I get: Complete output (5 lines): setup.py:117: UserWarning: Unable to determine GEOS version. Ensure you have 3.7.2 or later installed, or installation may fail. warnings.... | Installing Cartopy on Windows using pip is not trivial. Nevertheless, here is a cartopy installation overview using the method that worked for me, specifically for Windows and without using conda. Start by uninstalling proj, geos, and shapely if they are already installed, otherwise skip to step 2. This will facilitat... | 8 | 20 |
70,118,412 | 2021-11-26 | https://stackoverflow.com/questions/70118412/keeping-endpoint-function-declarations-in-separate-modules-with-fastapi | I have an API that uses FastAPI. In a single file (main.py), I have the call to the function that creates the API from fastapi import FastAPI # ... app = FastAPI() As well as all the endpoints: @app.post("/sum") async def sum_two_numbers(number1: int, number2: int): return {'result': number1 + number2} But as the app... | So is this impossible to do and I have to stick to the one-file API, or it is possible to do, but I'm doing it wrong? One file api is just for demo/test purposes, in the real world you always do multi-file api especialy with framework like fastapi where you use different type of file like pydantic models, db models, ... | 7 | 6 |
70,098,351 | 2021-11-24 | https://stackoverflow.com/questions/70098351/how-to-mock-a-http-request-post-in-python-unittest | First time write unittest. Production code: def get_session_token(organization_id): endpoint = get_endpoint(organization_id) response = requests.post( endpoint + "/some/url/part", data=json.dumps({ "Login": CONFIG[organization_id]["username"], "Password": CONFIG[organization_id]["password"], }), headers={"Accept": "app... | See Where to patch. And, you should provide a mock return value for the mock_post using return_value - The value returned when the mock is called. E.g. member.py: import requests import json def get_session_token(organization_id): endpoint = 'http://localhost:3000/api' response = requests.post( endpoint + "/some/url/pa... | 6 | 14 |
70,175,977 | 2021-11-30 | https://stackoverflow.com/questions/70175977/multiprocessing-no-space-left-on-device | When i run the multiprocessing example on a OSX. I get the Error OSError: [Errno 28] No space left on device. The ENOSPC ("No space left on device") error will be triggered in any situation in which the data or the metadata associated with an I/O operation can't be written down anywhere because of lack of space. This ... | One possible reason to run into this error (as in my case), is that the system reaches a limit of allowed POSIX semaphores. This limit can be inspected by the sysctl kern.posix.sem.max command and is 10000 on my macOS 13.0.1. To set it, for example to 15000 until next reboot, you can use: sudo sysctl -w kern.posix.sem.... | 5 | 8 |
70,141,277 | 2021-11-28 | https://stackoverflow.com/questions/70141277/is-it-possible-to-use-python-3-10-in-google-colab | I would like to use the Structural Pattern Matching feature from Python 3.10 in Google Colab so using the commands !sudo apt-get install python3.10 !sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1 !sudo update-alternatives --set python3 /usr/bin/python3.10 I was able to make !python -... | You can use this notebook. make a copy of it run the first cell reload (Ctrl + R, or Cmd + R) run the second cell See this video demo by 1littlecoder. | 16 | 6 |
70,136,985 | 2021-11-27 | https://stackoverflow.com/questions/70136985/linting-error-on-bitbucket-typeerror-linterstats-object-is-not-subscriptable | I am using BitBucket pipelines to perform linting checks with pylint. It was working fine a few hours ago. I have been facing the following error even though the final score is well past the minimum criteria (8.0): Your code has been rated at 9.43/10 Traceback (most recent call last): File "/usr/local/bin/pylint-fail-u... | Do not use pylint-fail-under, pylint has a fail-under option since pylint 2.5.0, and pylint-fail-under's maintener will not update their package for newer pylint. Change pylint-fail-under --fail_under 8.0 to pylint --fail-under=8.0 and remove the dependency to pylint-fail-under. See also https://github.com/PyCQA/pylint... | 6 | 9 |
70,127,649 | 2021-11-26 | https://stackoverflow.com/questions/70127649/how-to-have-a-single-source-of-truth-for-poetry-and-pre-commit-package-version | I'm looking into this Python project template. They use poetry to define dev dependencies [tool.poetry.dev-dependencies] black = {version = "*", allow-prereleases = true} flake8 = "*" isort = "^5.6" mypy = ">0.900,<1" ... They use also pre-commit to check housekeeping things (e.g., formatting, linting, issorting, ...)... | Finally, I created a pre-commit hook to do the job: https://github.com/floatingpurr/sync_with_poetry Edit: If you use PDM, you can refer to this one: https://github.com/floatingpurr/sync_with_pdm This hook just keeps in sync the repos rev in .pre-commit-config.yaml with the packages version locked into poetry.lock. I... | 27 | 20 |
70,128,335 | 2021-11-26 | https://stackoverflow.com/questions/70128335/what-is-the-proper-way-to-make-an-object-with-unpickable-fields-pickable | For me what I do is detect what is unpickable and make it into a string (I guess I could have deleted it too but then it will falsely tell me that field didn't exist but I'd rather have it exist but be a string). But I wanted to know if there was a less hacky more official way to do this. Current code I use: def make_a... | What is the proper way to make an object with unpickable fields pickable? I believe the answer to this belongs in the question you linked -- Python - How can I make this un-pickleable object pickleable?. I've added a new answer to that question explaining how you can make an unpicklable object picklable the proper wa... | 6 | 2 |
70,104,873 | 2021-11-25 | https://stackoverflow.com/questions/70104873/how-to-access-relationships-with-async-sqlalchemy | import asyncio from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.f... | This is how: from sqlalchemy.orm import selectinload async with async_session() as session: result = await session.execute(select(A).order_by(A.id) .options(selectinload(A.bs))) a = result.scalars().first() print(a.bs) key is using the selectinload method to prevent implicit IO UPDATE There are a few alternatives to s... | 26 | 23 |
70,105,907 | 2021-11-25 | https://stackoverflow.com/questions/70105907/django-full-test-suite-failing-when-adding-a-testcase-but-full-test-suite-pas | So this seems to be an issue talked about here and there on StackOverflow with no real solution. So I have a bunch of tests that all pass when run individual. They even pass when run as a full test suite, EXCEPT when I add in my TestCase ExploreFeedTest. Now ExploreFeedTest passes when run by itself and it actually doe... | I posted the answer on the stack overflow question Django - Serializer throwing "Invalid pk - object does not exist" when setting ManyToMany attribute where foreign keyed object does exist I was also using factory boy, which doesn't seem to play nice with test suite. Test suite doesn't seem to know how to rollback the ... | 5 | 0 |
70,118,990 | 2021-11-26 | https://stackoverflow.com/questions/70118990/flask-fails-with-error-while-importing-x-an-importerror-was-raised-but-do | When starting a Flask app with: $ flask run I received the error: Error: While importing 'wsgi', an ImportError was raised. Usage: flask [OPTIONS] COMMAND [ARGS]...` ... However, there is no stack trace or other information provided. What is the best way to get the ImportError stack trace? | Import the Flask app at the Python interpreter prompt To see the ImportError stack trace, open a Python interpreter prompt and import the module that loads the Flask app (usually app.py or wsgi.py). If applicable, be sure that your virtual environment is activated. $ python >>> from my_app_folder import app Set the FL... | 4 | 7 |
70,110,392 | 2021-11-25 | https://stackoverflow.com/questions/70110392/mqtt-tls-certificate-verify-failed-self-signed-certificate | Am trying to implement TLS for mqtt and has followed the tutorials from the link below http://www.steves-internet-guide.com/mosquitto-tls/ I followed exactly how it has been instructed to generate certificates using openssl and pasted in the location of mqtt and changed the conf of mqtt and restarted the service. But w... | The message you are receiving indicates that the broker's server certificate is not trusted (because it is self-signed), therefore paho is not being correctly told it is trustworthy. It is possible your fake certificate authority's root certificate (the ca.crt file you feed to paho) is not properly signed or generated,... | 7 | 13 |
70,118,623 | 2021-11-26 | https://stackoverflow.com/questions/70118623/valueerror-after-attempting-to-use-onehotencoder-and-then-normalize-values-with | So I was trying to convert my data's timestamps from Unix timestamps to a more readable date format. I created a simple Java program to do so and write to a .csv file, and that went smoothly. I tried using it for my model by one-hot encoding it into numbers and then turning everything into normalized data. However, aft... | using OneHotEncoder is not the way to go here, it's better to extract the features from the column time as separate features like year, month, day, hour, minutes etc... and give these columns as input to your model. btc_data['Year'] = btc_data['Date'].astype('datetime64[ns]').dt.year btc_data['Month'] = btc_data['Date'... | 5 | 4 |
70,118,083 | 2021-11-25 | https://stackoverflow.com/questions/70118083/how-to-write-an-array-tag-in-a-variant-structure-on-an-openopc-server | I'm trying to communicate with an OPC DA server and need to write in a tag which is in an array format. We can connect with a simulation server, read tags (int, real, array) and write tags (int, real, str). The problem comes when we need to write in an array tag. The developper of the OpenOPC library (Barry Barnreiter)... | You have to change your line opc_local = OpenOPC.open_client() for opc_local = OpenOPC.client(). This will make you connect directly to the OPC server, as opposed to using the OpenOPC Gateway Service. The VARIANT structure is not included inside the Gateway Service exe. Note that the Gateway Service exe is it's own fro... | 8 | 3 |
70,098,133 | 2021-11-24 | https://stackoverflow.com/questions/70098133/npm-error-cant-find-python-executable-in-macos-big-sur | I've been looking for the answer to this for a good solid week now, with no success. I've looked at every StackOverflow post, every article from Google and every related Github issue I could find. Most related errors seem to be older, so I'm wondering if my issue is slightly different due to me being on macOS Big Sur. ... | Reading the gyp-node source might helps. Here are some steps you can try. Install python2. You should make sure that in the terminal, which -a python2 only returns one python2 and python2 -V returns the correct 2.x version. override PYTHON env. export PYTHON=python2. Rerun the install. If there's still an error, p... | 75 | 34 |
70,107,143 | 2021-11-25 | https://stackoverflow.com/questions/70107143/rename-and-refactor-a-python-file-in-vs-code | On PyCharm you can right-click a file -> Refactor -> Rename. And it would rename that file and update all import statements in all files in the project. In VS Code, while I can rename and refactor symbols by highlighting them -> F2, this only works for modules, classes, their members, and variables. E.g. I have an util... | Check out the enhanced module re-naming coming to vscode v1.63 (see release notes: python module rename refactoring. Module rename refactoring You can now more easily rename modules with the Python and Pylance extensions. Once you rename a Python module, you’ll be prompted to choose whether you’d like to change all im... | 7 | 4 |
70,170,480 | 2021-11-30 | https://stackoverflow.com/questions/70170480/how-to-scrape-product-data-from-website-pages-that-uses-graphql | I previously used the code below to scrape the search result for a word search, for example book, on https://www.walmart.com/. They have currently changed their request and response parameters and this code does not get any response again. params = { 'query': 'book', 'cat_id': 0, 'ps': 24, 'offset': 0, 'prg': 'desktop... | According to your question, to get the json response, You can follow my working solution as an example. Actually, the hidden api calls json response is here. The interesing matter is that the request method is post but it sends query string parameters & request payload/formdata and the next pages at the same time which... | 6 | 7 |
70,172,127 | 2021-11-30 | https://stackoverflow.com/questions/70172127/how-to-generate-a-uuid-field-with-fastapi-sqlalchemy-and-sqlmodel | I'm struggling to get the syntax to create a UUID field when creating a model in my FastAPI application. I'm using SQLModel. So basically, my models.py file looks like this: from datetime import datetime from typing import Optional import uuid from sqlalchemy import Column, DateTime from sqlalchemy.dialects import post... | The interpreter might be using UUID of your actual field uuid instead of the imported package. So, you can change the code as follows. import uuid as uuid_pkg from sqlalchemy import Field from sqlmodel import Field class UUIDModelBase(ModelBase): """ Base class for UUID-based models. """ uuid: uuid_pkg.UUID = Field( de... | 10 | 18 |
70,169,219 | 2021-11-30 | https://stackoverflow.com/questions/70169219/what-is-total-loss-loss-cls-etc | I want to train a custom dataset on using faster_rcnn or mask_rcnn with the Pytorch and Detectron2 .Everything works well but I wanted to know I want to know what are the results I have. [11/29 20:16:31 d2.utils.events]: eta: 0:24:04 iter: 19 total_loss: 9.6 loss_cls: 1.5 loss_box_reg: 0.001034 loss_mask: 0.6936 loss_r... | Those are metrics printed out at every iteration of the training loop. The most important ones are the loss values, but below are basic descriptions of them all (eta and iter are self-explanatory I think). total_loss: This is a weighted sum of the following individual losses calculated during the iteration. By default,... | 9 | 12 |
70,091,290 | 2021-11-24 | https://stackoverflow.com/questions/70091290/tensorflow-datasets-crop-resize-images-per-batch-after-dataset-batch | Is it possible to Crop/Resize images per batch ? I'm using Tensorflow dataset API as below: dataset = dataset.shuffle().repeat().batch(batch_size, drop_remainder=True) I want, within the batch all the images should have the same size. However across the batches it can have different sizes. For example, 1st batch has a... | Generally, you can try something like this: import tensorflow as tf import numpy as np dataset1 = tf.data.Dataset.from_tensor_slices(np.random.random((32, 300, 300, 3))) dataset2 = tf.data.Dataset.from_tensor_slices(np.random.random((32, 224, 224, 3))) dataset3 = tf.data.Dataset.from_tensor_slices(np.random.random((32,... | 5 | 2 |
70,168,829 | 2021-11-30 | https://stackoverflow.com/questions/70168829/use-ffmpeg-command-to-push-rtsp-stream-it-doesnt-contain-sps-and-pps-frame | I use python and opencv-python to capture frames from video, then use ffmpeg command to push rtsp stream with pipe. I can play the rtsp stream via gstreamer and vlc. However, a display device cannot decode and play the rtsp-stream because it cannot receive SPS and PPS frames. Use wireshark to capture stream, found that... | Try adding the arguments '-bsf:v', 'dump_extra'. According to FFmpeg Bitstream Filters Documentation: dump_extra Add extradata to the beginning of the filtered packets except when said packets already exactly begin with the extradata that is intended to be added. The filter supposed to add SPS and PPS NAL units with ... | 5 | 5 |
70,169,519 | 2021-11-30 | https://stackoverflow.com/questions/70169519/how-can-i-save-more-metadata-on-an-mlflow-model | I am trying to save a model to MLFlow, but as I have a custom prediction pipeline to retrieve data, I need to save extra metadata into the model. I tried using my custom signature class, which It does the job correctly and saves the model with the extra metadata in the MLModel file (YAML format). But when want to load ... | Finally, I made a class that contains every metadata and saved it as an model argument: model = LogisticRegression() model.fit(X, y) model.metadata = ModelMetadata(**metadata_dic) mlflow.sklearn.log_model(model, "model") Here I lost the customizable predict process, but after reading the MLFlow documentation is not ve... | 5 | 1 |
70,167,811 | 2021-11-30 | https://stackoverflow.com/questions/70167811/how-to-load-custom-model-in-pytorch | I'm trying to load my pretrained model (yolov5n) and test it with the following code in PyTorch: import os import torch model = torch.load(os.getcwd()+'/weights/last.pt') # Images imgs = ['https://example.com/img.jpg'] # Inference results = model(imgs) # Results results.print() results.save() # or .show() results.xyxy[... | You should be able to find the weights in this directory: yolov5/runs/train/exp/weights/last.pt Then you load the weights with a line like this: model = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5/runs/train/exp/weights/last.pt', force_reload=True) I have an example of a notebook that loads custom mode... | 4 | 10 |
70,177,467 | 2021-11-30 | https://stackoverflow.com/questions/70177467/databricks-pyspark-vs-pandas | I have a python script where I'm using pandas for transformations/manipulation of my data. I know I have some "inefficient" blocks of code. My question is, if pyspark is supposed to be much faster, can I just replace these blocks using pyspark instead of pandas or do I need everything to be in pyspark? If I'm in Databr... | If the data is small enough that you can use pandas to process it, then you likely don't need pyspark. Spark is useful when you have such large data sizes that it doesn't fit into memory in one machine since it can perform distributed computation. That being said, if the computation is complex enough that it could bene... | 11 | 20 |
70,174,054 | 2021-11-30 | https://stackoverflow.com/questions/70174054/how-to-reorder-rows-in-pandas-dataframe-by-factor-level-in-python | I've created a small dataset comparing coffee drink prices per cup size. When I pivot my dataset the output automatically reorders the index (the 'Size' column) alphabetically. Is there a way to assign the different sizes a numerical level (e.g. small = 0, medium = 1, large = 2) and reorder the rows this way instead? I... | You can use a Categorical type with ordered=True: df.index = pd.Categorical(df.index, categories=['Small', 'Medium', 'Large'], ordered=True) df = df.sort_index() output: Price Item Americano Cappuccino Latte Small 1.95 2.65 2.25 Medium 2.25 2.95 2.60 Large 2.45 3.25 2.85 You can access the codes with: >>> df.index.c... | 4 | 4 |
70,173,576 | 2021-11-30 | https://stackoverflow.com/questions/70173576/how-to-add-a-line-to-a-plotly-express-bar-chart | I am trying to add a very simple line across a bar chart in plotly and am struggling to to this. My dataframe contains one column with bins and the other with returnsdata and can be copied here: {'bins': {0: '(-23.077, 25.877]', 1: '(25.877, 34.666]', 2: '(34.666, 42.552]', 3: '(42.552, 46.044]', 4: '(46.044, 49.302]',... | You can use the Plotly's horizontal and vertical shapes to add a horizontal line: fig.add_hline(y=0.14080542857142858) | 5 | 5 |
70,163,883 | 2021-11-30 | https://stackoverflow.com/questions/70163883/google-colab-modulenotfounderror-no-module-named-sklearn-externals-joblib | My Initial import looks like this and this code block runs fine. # Libraries to help with reading and manipulating data import numpy as np import pandas as pd # Libraries to help with data visualization import matplotlib.pyplot as plt import seaborn as sns sns.set() # Removes the limit for the number of displayed colum... | For the second part you can do this to fix it, I copied the rest of your code as well, and added the bottom part. # Libraries to help with reading and manipulating data import numpy as np import pandas as pd # Libraries to help with data visualization import matplotlib.pyplot as plt import seaborn as sns sns.set() # Re... | 4 | 6 |
70,160,450 | 2021-11-29 | https://stackoverflow.com/questions/70160450/subprocess-command-shows-filenotfounderror-errno-2-no-such-file-or-directory | I'm trying to run shell commands using python by using subprocess module in the below code, but I don't why my script is throwing an error like below. Can someone help me what I'm missing? Traceback (most recent call last): File "/Scripts/test_file.py", line 6, in <module> p2 = subprocess.Popen('sed s\'/"/ /g\'', ... | Your commands are still wrong. If you just want to run these commands like the shell does, the absolutely easiest way to do that is to ... use the shell. result = subprocess.run(''' # useless cat, but bear with cat output3.txt | sed 's/"/ /g' | grep "shipOption" | grep -v "getShipMethod" | cut -d ',' -f2 | sed 's/... | 8 | 4 |
70,142,953 | 2021-11-28 | https://stackoverflow.com/questions/70142953/matplotlib-colormaps-choosing-a-different-color-for-each-graph-line-subject | I created a script that reads and plots .txt files and their content (numbers/values). Each .txt file is located in a different folder. Each folder, in turn, represents one subject from which the data stems. This code works fine. Python reads each single .txt. file and plots 23 individual graphs/lines into one single p... | One way to achieve your goal is to slice-up a colormap and then plot each line with one of the resulting colors. See the lines below that can be integrated in your code in appropriate places. import numpy as np import matplotlib.pyplot as plt # 1. Choose your desired colormap cmap = plt.get_cmap('plasma') # 2. Segmenti... | 5 | 4 |
70,127,049 | 2021-11-26 | https://stackoverflow.com/questions/70127049/what-is-the-use-of-dmatrix | The docs say: Data Matrix used in XGBoost. DMatrix is an internal data structure that is used by XGBoost, which is optimized for both memory efficiency and training speed. You can construct DMatrix from multiple different sources of data. I get this bit but what's the difference/use of DMatrix instead of a Pandas Dat... | When using the XGBoost Python package you can choose between two different APIs to train your model. XGB's own Learning API and the Scikit-Learn API. When using the Scikit-Learn API data is passed to the model as numpy array or pandas dataframes. When using the Learning API data is passed using the DMatrix. Have a look... | 21 | 25 |
70,159,221 | 2021-11-29 | https://stackoverflow.com/questions/70159221/runtimeerror-mean-input-dtype-should-be-either-floating-point-or-complex-dty | I wrote below code using PyTorch and ran into the runtime error: tns = torch.tensor([1,0,1]) tns.mean() --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-666-194e5ab56931> in <module> ----> 1 tns.mean() RuntimeError: mean(): input d... | This is because torch.int64 and torch.long both refer to the same data type, of 64-bit signed integers. See here for an overview of all data types. | 8 | 6 |
70,158,335 | 2021-11-29 | https://stackoverflow.com/questions/70158335/how-to-download-files-in-customized-location-using-selenium-chromedriver-and-chr | I want to download a txt and pdf files to a specific folder. But it just downloads them on another folder. The website http://demo.automationtesting.in/FileDownload.html. Is there something wrong with the code or I didn't put the correct location of the folder? import time from selenium import webdriver from selenium.w... | To download the required file within Automation Demo Site to a specific folder using Selenium, ChromeDriver and google-chrome you need to pass the preference "download.default_directory" along with the value (location of the directory) through add_experimental_option() and you can use the following solution: Code Block... | 5 | 5 |
70,145,904 | 2021-11-28 | https://stackoverflow.com/questions/70145904/transposition-tables-for-python-chess-engine | This is a follow-up to my last post. The code works without any errors and can calculate the next best move. I've been looking into how to incorporate transposition tables and move ordering into my negamax function to make it run faster and more accurately, but it seems somewhat difficult and advanced for a beginner li... | To use transposition tables you "need" to use Zorbrist hashing. The hashing gives each position an (almost) unique code that you store in the transposition table along with its evaluation. Then, to explain it easily, if the current position you are searching is found in your transposition table you won't have to evalua... | 6 | 4 |
70,147,659 | 2021-11-28 | https://stackoverflow.com/questions/70147659/importing-only-a-specific-class-from-a-python-module-with-importlib | How would one go about importing only a specific class from a Python module using its path? I need to import a specific class from a Python file using the file path. I have no control over the file and its completely outside of my package. file.py: class Wanted(metaclass=MyMeta): ... class Unwanted(metaclass=MyMeta): .... | If I am not mistaken, the name parameter is just used to name the module you are importing. But, more importantly, when you are importing any module, you are executing the whole file, which means that in your case both of these classes will be created. It would not matter whether you wrote from file import Wanted, impo... | 5 | 2 |
70,138,641 | 2021-11-27 | https://stackoverflow.com/questions/70138641/using-sqlalchemy-declarative-base-with-sql-model | In one of our project, we used SQL Alchemy declarative Base for all of our models for years (and there is many). We want to try the new SQLModel library for our latest model declaration. For that, we tried to declare it separately from the Base object, and call the create_all methods for both. i.e : Base.metadata.creat... | I've finally found a simple way to do that, according to this thread. Since SQLModel inherits the Metadata object from SQLAlchemy, We can simply bind the metadata object of SQLModel to the metadata object from SQLAlchemy : # Declarative base object Base = declarative_base() SQLModel.metadata = Base.metadata # Table dec... | 5 | 7 |
70,134,026 | 2021-11-27 | https://stackoverflow.com/questions/70134026/no-speedup-when-summing-uint16-vs-uint64-arrays-with-numpy | I have to do a large number of operations (additions) on relatively small integers, and I started considering which datatype would give the best performance on a 64 bit machine. I was convinced that adding together 4 uint16 would take the same time as one uint64, since the ALU could make 4 uint16 additions using only 1... | TL;DR: I made an experimental analysis on Numpy 1.21.1. Experimental results show that np.sum does NOT (really) make use of SIMD instructions: no SIMD instruction are used for integers, and scalar SIMD instructions are used for floating-point numbers! Moreover, Numpy converts the integers to 64-bits values for smaller ... | 7 | 12 |
70,147,889 | 2021-11-28 | https://stackoverflow.com/questions/70147889/how-to-reduce-a-string-by-another-string-in-python | I would like to remove all characters from a first string s1 exactly the number of times they appear in another string s2, i.e. if s1 = "AAABBBCCCCCCD" and s2 = "ABBCCC" then the result should be s = "AABCCCD". (The order of the characters in the resulting string is actually irrelevant but it's a plus if it can be pres... | You can use counter objects. Subtract one against the other and join the remaining elements together. from collections import Counter s1 = "AAABBBCCCCCCD" s2 = "ABBCCC" counter = Counter(s1) counter.subtract(Counter(s2)) result = ''.join(counter.elements()) print(result) AABCCCD As a one-liner: print(''.join((Counter... | 4 | 6 |
70,146,417 | 2021-11-28 | https://stackoverflow.com/questions/70146417/python-dictionary-with-enum-as-key | Let's say I have an enum class Color(Enum): RED = "RED" GREEN = "GREEN" BLUE = "BLUE" I wanted to create a ColorDict class that works as a native python dictionary but only takes the Color enum or its corresponding string value as key. d = ColorDict() # I want to implement a ColorDict class such that ... d[Color.RED] ... | A simple solution would be to slightly modify your Color object and then subclass dict to add a test for the key. I would do something like this: class Color(Enum): RED = "RED" GREEN = "GREEN" BLUE = "BLUE" @classmethod def is_color(cls, color): if isinstance(color, cls): color=color.value if not color in cls.__members... | 9 | 7 |
70,143,131 | 2021-11-28 | https://stackoverflow.com/questions/70143131/application-default-credentials-in-google-cloud-build | Within my code, I am attempting to gather the Application Default Credentials from the associated service account in Cloud Build: from google.auth import default credentials, project_id = default() This works fine in my local space because I have set the environment variable GOOGLE_APPLICATION_CREDENTIALS appropriatel... | There is a trick: you have to define the network to use in your Docker build. Use the parameter --network=cloudbuild, like that steps: - name: gcr.io/cloud-builders/docker entrypoint: 'docker' args: - build - '--no-cache' - '--network=cloudbuild' - '-t' - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SH... | 10 | 23 |
70,145,289 | 2021-11-28 | https://stackoverflow.com/questions/70145289/fastest-way-to-find-all-pairs-of-close-numbers-in-a-numpy-array | Say I have a Numpy array of N = 10 random float numbers: import numpy as np np.random.seed(99) N = 10 arr = np.random.uniform(0., 10., size=(N,)) print(arr) out[1]: [6.72278559 4.88078399 8.25495174 0.31446388 8.08049963 5.6561742 2.97622499 0.46695721 9.90627399 0.06825733] I want to find all unique pairs of numbers ... | This is a solution with pure numpy operations. It seems pretty fast on my machine, but I don't know what kind of speed we're looking for. def all_close_pairs(arr, tol=1.): N = arr.shape[0] # get indices in the array to consider using meshgrid pair_coords = np.array(np.meshgrid(np.arange(N), np.arange(N))).T # filter ou... | 4 | 3 |
70,143,797 | 2021-11-28 | https://stackoverflow.com/questions/70143797/pycharm-type-warnings-iterable-vs-valuesview-keysview-itemsview | Lately in PyCharm (I don't know which version started it, I'm currently running 2021.2.3 Pro), I'm getting warnings that don't make sense. For example, this snippet: d = {1: 2, 3: 4, 5: 6} for v in d.values(): print(v) Triggers the following warning: Expected type 'collections.Iterable', got 'ValuesView' instead In ... | This is a regression of a known bug in the PyCharm 2021.2.3 linter, see PY-41457 on the JetBrains bug tracker. It doesn't happen for me using the immediately previous PyCharm 2021.2.2 Pro version. The solution, for now, is to report the regression on the JetBrains bug tracker and wait for a fix. There's nothing wrong w... | 5 | 3 |
70,143,961 | 2021-11-28 | https://stackoverflow.com/questions/70143961/what-is-a-pythonic-way-to-conditionally-compose-a-sequence | In Perl I can do something like this to dynamically create an array based on some conditions: my @arr = ( $foo_defined ? 'foo' : (), $bar_defined ? 'bar' : (), $baz_defined ? 'baz' : (), ); This creates an array of up to 3 elements based on the values of the variables. What would be the closest alternative to this in ... | A close literal translation might be arr = list(chain( ['foo'] if foo_defined else [], ['bar'] if bar_defined else [], ['baz'] if baz_defined else [], )) a if b else c is the Python equivalent of b ? a : c. chain concatenates multiple iterable values into a single sequence, similar to how ( (), (), () ) builds an arra... | 4 | 4 |
70,135,719 | 2021-11-27 | https://stackoverflow.com/questions/70135719/creating-a-nested-recursive-list-without-slicing | I need to write a function that receives an non-negative integer and returns: [] for n=0 [[]] for n=1 [[],[[]]] for n=2 [[],[[]],[[],[[]]]] for n=3 And so on. For n, we will receive an n sized list, so that in index i there will be all the i-1 elements from the list. I don't know how to explain that better, English is... | If you can't use loops, you can use the following: def recursive_list(n): if n == 0: return [] else: return recursive_list(n-1) + [recursive_list(n-1)] EDIT You can do the following if you want to use append: def recursive_list(n: int) -> list: if n: result = recursive_list(n-1) result.append(recursive_list(n-1)) retu... | 6 | 4 |
70,138,815 | 2021-11-27 | https://stackoverflow.com/questions/70138815/fastapi-responding-slowly-when-calling-through-other-python-app-but-fast-in-cur | I have an issue that I can't wrap my head around. I have an API service built using FastAPI, and when I try to call any endpoint from another Python script on my local machine, the response takes 2+ seconds. When I send the same request through cURL or the built-in Swagger docs, the response is nearly instant. The enti... | Try using „127.0.0.1“ instead of „localhost“ to refer to your machine. I once had a similar issue, where the DNS lookup for localhost on windows was taking half a second or longer. I don‘t have an explanation for that behaviour, but at least one other person on SO seems to have struggled with it as well… | 7 | 19 |
70,138,169 | 2021-11-27 | https://stackoverflow.com/questions/70138169/what-is-the-point-of-an-abstractmethod-with-default-implementation | I’ve seen code that declares abstract methods that actually have a non-trivial body. What is the point of this since you have to implement in any concrete class anyway? Is it just to allow you to do something like this? def method_a(self): super(self).method_a() | I've used this before in cases where it was possible to have the concrete implementation, but I wanted to force subclass implementers to consider if that implementation is appropriate for them. One specific example: I was implementing an abstract base class with an abstract factory method so subclasses can define their... | 10 | 7 |
70,131,817 | 2021-11-27 | https://stackoverflow.com/questions/70131817/fourier-transform-time-series-in-python | I've got a time series of sunspot numbers, where the mean number of sunspots is counted per month, and I'm trying to use a Fourier Transform to convert from the time domain to the frequency domain. The data used is from https://wwwbis.sidc.be/silso/infosnmtot. The first thing I'm confused about is how to express the sa... | You can use any units you want. Feel free to express your sampling frequency as fs=12 (samples/year), the x-axis will then be 1/year units. Or use fs=1 (sample/month), the units will then be 1/month. The extra line you spotted comes from the way you plot your data. Look at the output of the np.fft.fftfreq call. The fir... | 7 | 4 |
70,132,993 | 2021-11-27 | https://stackoverflow.com/questions/70132993/does-numpy-array-really-take-less-memory-than-python-list | Please refer to below execution - import sys _list = [2,55,87] print(f'1 - Memory used by Python List - {sys.getsizeof(_list)}') narray = np.array([2,55,87]) size = narray.size * narray.itemsize print(f'2 - Memory usage of np array using itemsize - {size}') print(f'3 - Memory usage of np array using getsizeof - {sys.ge... | The calculation using: size = narray.size * narray.itemsize does not include the memory consumed by non-element attributes of the array object. This can be verified by the documentation of ndarray.nbytes: >>> x = np.zeros((3,5,2), dtype=np.complex128) >>> x.nbytes 480 >>> np.prod(x.shape) * x.itemsize 480 In the abov... | 8 | 7 |
70,121,429 | 2021-11-26 | https://stackoverflow.com/questions/70121429/how-to-plot-scatter-graph-with-markers-based-on-column-value | I am trying to plot a scatter graph on some data with grouping. They are grouped by the column group and I want them to have different marker styles based on the group. Minimal working code import matplotlib.pyplot as plt import pandas as pd import numpy as np colors = ['r','g','b','y'] markers = ['o', '^', 's', 'P'] d... | matplotlib that is ugly IMO to loop through a DataFrame row by row and I strongly believe there is a better way With matplotlib, I don't think there is a better way than to loop. Note that if you groupby the markers, it does not loop row by row, just group by group (so 4 times in this case). This will call plt.scatte... | 4 | 8 |
70,123,328 | 2021-11-26 | https://stackoverflow.com/questions/70123328/how-to-set-environment-variables-in-github-actions-using-python | I want to execute a python script to set some environment variables in GitHub actions. I want to use those environment variables later in my GitHub actions steps. My python script looks like: new_ver = get_version_from_commit(commit_msg) if new_ver: if new_ver == "false": os.environ["SHOULD_PUSH"] = "0" print("Not push... | You cannot set environment variables directly. Instead, you need to write your environment variables into a file, whose name you can get via $GITHUB_ENV. In a simple workflow step, you can append it to the file like so (from the docs): echo "{name}={value}" >> $GITHUB_ENV In python, you can do it like so: import os en... | 18 | 30 |
70,110,429 | 2021-11-25 | https://stackoverflow.com/questions/70110429/pytorch-runtimeerror-result-type-float-cant-be-cast-to-the-desired-output-typ | I have a model which looks as follows: IMG_WIDTH = IMG_HEIGHT = 224 class AlexNet(nn.Module): def __init__(self, output_dim): super(AlexNet, self).__init__() self._to_linear = None self.x = torch.randn(3, IMG_WIDTH, IMG_HEIGHT).view(-1, 3, IMG_WIDTH, IMG_HEIGHT) self.features = nn.Sequential( nn.Conv2d(3, 64, 3, 2, 1),... | I was getting the same error doing this: loss_fn(output, target) where the output was Tensor torch.float32 and target was Tensor torch.int64. What solved this problem was calling the loss function like this: loss_fn(output, target.float()) | 25 | 45 |
70,122,203 | 2021-11-26 | https://stackoverflow.com/questions/70122203/pandas-multiindex-intersection-on-partial-levels | say I have two dataframes with multiindices, where one of the indices is deeper than the other. Now I want to select only those rows from the one (deeper) dataframe where their partial index is included in the other dataframe. Example input: df = pandas.DataFrame( { "A": ["a1", "a1", "a1", "a2", "a2", "a2"], "B": ["b1"... | One option is to use isin on the specific labels common to both, and use the resulting boolean to filter df: df.loc[df.index.droplevel('C').isin(df2.index)] V A B C a1 b1 c1 1 c2 2 a2 b1 c1 4 | 4 | 8 |
70,119,576 | 2021-11-26 | https://stackoverflow.com/questions/70119576/exception-value-failed-loading-libasound-so-2-libasound-so-2-cannot-open-shar | I made a drowsiness detector for driving using django. I tried deploying it on heroku and everything seems to be working fine except as soon as I try to open the camera, I get the error: Exception Value: Failed loading libasound.so.2: libasound.so.2: cannot open shared object file: No such file or directory All the ot... | Your machine is missing libasound, install it with: sudo apt-get install libasound2 | 4 | 10 |
70,119,439 | 2021-11-26 | https://stackoverflow.com/questions/70119439/return-the-index-of-the-first-element-in-the-list-from-where-incremental-increas | Suppose I have a list like this, where numbers increase in different steps: [ 0, 4, 6, 8, 12, 15, 19, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32] I want to return the index for the first element in the list where the increase is incremental (+1 step only). In this case, 23 is the first location from which point the in... | Solution 1: operator from operator import sub, indexOf L = [ 0, 4, 6, 8, 12, 15, 19, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32] print(indexOf(map(sub, L[1:], L), 1)) # prints 8 Raises ValueError: sequence.index(x): x not in sequence if difference 1 never occurs, so might want to use try/except for that. Solution 2: b... | 4 | 6 |
70,115,749 | 2021-11-25 | https://stackoverflow.com/questions/70115749/is-there-any-reason-for-changing-the-channels-order-of-an-image-from-rgb-to-bgr | I've been following this keras video classification tutorial where in the data preparation section, they load the frames of a video in the load_video function pretty generically, but what caught my eye was this line: frame = frame[:, :, [2, 1, 0]] This is the first time I encounter this, most of the times you will jus... | From experience, the reason why the order can change is dependent on the framework you are using to load in images. OpenCV in particular orders the channels in BGR format because of mostly historical reasons that are now outdated. Because of this, we are unfortunately stuck with this design choice. Images in the regula... | 4 | 8 |
70,110,804 | 2021-11-25 | https://stackoverflow.com/questions/70110804/fast-removal-of-only-zero-columns-in-pandas-dataframe | Using: import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,3,(100000,5000))) df = df.loc[:, (df != 0).any(axis=0)] to get rid of columns containing only zeros is way too slow for a very large (1000000x2000) dataframe. Any suggestions how to speed this up? Thanks | There is a much faster way to implement that using Numba. Indeed, most of the Numpy implementation will create huge temporary arrays that are slow to fill and read. Moreover, Numpy will iterate over the full dataframe while this is often not needed (at least in your example). The point is that you can very quickly know... | 4 | 4 |
70,110,613 | 2021-11-25 | https://stackoverflow.com/questions/70110613/str-wrapper-in-custom-exception | Why does the below code print error msg instead of ABC\nerror msg? class CustomException(Exception): """ABC""" def __init__(self, *args): super().__init__(*args) self.__str__ = self._wrapper(self.__str__) def _wrapper(self, f): def _inner(*args, **kwargs): return self.__doc__ + '\n' + f(*args, **kwargs) return _inner p... | Operations backed by special methods usually explicitly look up the special method as a proper method not just as a callable attribute. Concretely, instead of self.__str__ the interpreter roughly looks at type(self).__str__.__get__(self, type(self)) – i.e. a descriptor __str__ on the class to be bound with the instanc... | 5 | 1 |
70,102,323 | 2021-11-24 | https://stackoverflow.com/questions/70102323/runtimeerror-expected-all-tensors-to-be-on-the-same-device-but-found-at-least | I trained a model for sequence classification using transformers (BertForSequenceClassification) and I get the error: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper__index_select) I don't really get where is the... | You did not move your model to device, only the data. You need to call model.to(device) before using it with data located on device. | 11 | 18 |
70,099,593 | 2021-11-24 | https://stackoverflow.com/questions/70099593/pandas-find-start-and-stop-point-of-non-null-values | I'd like to find the start and stop points of a column and flag them as shown below: value flag NaN NaN NaN NaN 1 start 2 NaN 1 NaN 3 NaN 2 stop NaN NaN 1 start 2 stop | start occurs when the current value is notnull and the previous value isnull stop occurs when the current value is notnull and the next value isnull Generate these conditions using shift and assign using loc: start = df.value.notnull() & df.value.shift().isnull() stop = df.value.notnull() & df.value.shift(-1).isnull(... | 5 | 5 |
70,104,101 | 2021-11-24 | https://stackoverflow.com/questions/70104101/valueerror-method-eth-maxpriorityfeepergas-not-supported-web3-py-with-ganache | I'm running the following code with web3.py: transaction = SimpleStorage.constructor().buildTransaction( {"chainId": chain_id, "from": my_address, "nonce": nonce} ) And I am running into the following error: Traceback (most recent call last): File "/Users/patrick/code/web3_py_simple_storage/deploy.py", line 64, in <mo... | This is an issue from a new edition of web3.py. You need to add gasPrice to your transaction, like so: transaction = SimpleStorage.constructor().buildTransaction( {"chainId": chain_id, "gasPrice": w3.eth.gas_price, "from": my_address, "nonce": nonce} ) This is due to EIP1559 changing, and web3.py updating for the chan... | 13 | 38 |
70,091,826 | 2021-11-24 | https://stackoverflow.com/questions/70091826/sum-dataframe-values-in-for-loop-inside-a-for-loop | I have a large polygon file, small polygon file and points file. What I do here is loop through large polygons to find which small polygons intersect. Then calculate the area of each small polygon within the large one. And then I loop through the small polygons to find points statistics in each of them. I have found nu... | you describe three GeoDataFrame large - have used country boundaries for this small - have used UTM zone boundaries for this point - have used randomly generated points that mostly overlap 2 you define that you want two outputs for each large geometry (country here) area - sum of intersection area of each small ge... | 5 | 2 |
70,100,524 | 2021-11-24 | https://stackoverflow.com/questions/70100524/iterate-dict-in-python-using-next | Is it possible to iterate dictionary in python using next(). (I need to access keys and values). Also would it work for extendable dictionaries with non-fixed length? | Use items to get the pairs key/value and iter() to be able to call next content = dict(zip(range(10), range(10, 20))) print(content) # {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19} iterable = iter(content.items()) print(next(iterable)) # (0, 10) print(next(iterable)) # (1, 11) print(next(iterab... | 4 | 8 |
70,096,110 | 2021-11-24 | https://stackoverflow.com/questions/70096110/valueerror-on-inverse-transform-using-ordinalencoder-with-dictionary | I can transform the target column to desired ordered numerical value using categorical encoding and ordinal encoding. But I am unable to perform inverse_transform as an error is showing which is written below. import pandas as pd import category_encoders as ce from sklearn.preprocessing import OrdinalEncoder lst = [ 'B... | The error comes from this line in the inverse_transform source code: inverse = pd.Series(data=column_mapping.index, index=column_mapping.values) It seems that even though the category_encoders documentation says that the mapping should be provided as a dictionary, their inverse_transform code is actually looking for a... | 5 | 3 |
70,051,619 | 2021-11-21 | https://stackoverflow.com/questions/70051619/pass-on-value-from-dependencies-in-include-router-to-routes-fastapi | I was wondering if it was possible to pass the results from the dependencies kwarg in include_router to the router that is passed to it. What I want to do is decode a JWT from the x-token header of a request and pass the decoded payload to the books routes. I know that I could just write authenticate_and_decode_JWT as ... | While the answer above about writing a middleware does work, if you don't want a middleware, you just want to use the include_router, then you can take the authenticate_and_decode_JWT method and extend it to write the JWT payload into the request object and then later have your routes read from that out from the reques... | 7 | 5 |
70,077,422 | 2021-11-23 | https://stackoverflow.com/questions/70077422/why-python-matches-a-list-as-a-tuple | With Python 3.11.0a2+, and the following code: def my_fun(e): match e: case (1,): print("tuple (1,)") case [1]: print("list [1]") case _: print("I don't understand") Calling the function with my_fun([1]) prints "tuple (1,)". Is this behavior correct? If I explicitly match against tuple((1, )) instead of (1,), it works... | This is documented under Structural Pattern Matching Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. Technically, the subject must be a sequence. Therefore, an important exception is that patterns don’t match iterators. Also, to prevent a common... | 4 | 6 |
70,060,847 | 2021-11-22 | https://stackoverflow.com/questions/70060847/how-to-work-with-openai-maximum-context-length-is-2049-tokens | I'd like to send the text from various PDF's to OpenAI's API. Specifically the Summarize for a 2nd grader or the TL;DR summarization API's. I can extract the text from PDF's using PyMuPDF and prepare the OpenAI prompt. Question: How best to prepare the prompt when the token count is longer than the allowed 2049? Do I ... | I faced the same problem. Here is the strategy I used to send text that is much, much longer than OpenAIs GPT3 token limit. Depending on the model (Davinci, Curie, etc.) used, requests can use up to 4097 tokens shared between prompt and completion. Prompt being the input you send to OpenAI, i.e. your "command", e.g. "... | 25 | 31 |
70,035,997 | 2021-11-19 | https://stackoverflow.com/questions/70035997/i-cant-read-excel-file-using-dt-fread-from-datatable-attributeerror | Hello I'm trying to read an excel file 'myFile.xlsx' using datatable.fread (version 1.0.0) function to speedup data manipulation. The problem is I had an AttributeError: module 'xlrd' has no attribute 'xlsx'. The command I used is: import datatable as dt DT = dt.fread("myFile.xlsx") I checked the module where the erro... | The issue is that datatable package is not updated yet to make use of xlrd>1.2.0, so in order to make it work you have to install xlrd = 1.2.0 pip install xlrd==1.2.0 I hope it helped. | 5 | 6 |
70,051,750 | 2021-11-21 | https://stackoverflow.com/questions/70051750/pytorch-runtimeerror-requires-grad-is-not-supported-on-scriptmodules | I'm running Python code from an old repo that seems to no longer work but I can't figure out why or how to fix it. SETUP CODE (Google Colab Notebook) #@title Setup import pkg_resources print(pkg_resources.get_distribution("torch").version) from IPython.utils import io with io.capture_output() as captured: !git clone ht... | For any unlucky soul that comes accross this issue this URL saved my soul https://github.com/mfrashad/text2art/issues/5 | 5 | 1 |
70,065,235 | 2021-11-22 | https://stackoverflow.com/questions/70065235/understanding-torch-nn-layernorm-in-nlp | I'm trying to understanding how torch.nn.LayerNorm works in a nlp model. Asuming the input data is a batch of sequence of word embeddings: batch_size, seq_size, dim = 2, 3, 4 embedding = torch.randn(batch_size, seq_size, dim) print("x: ", embedding) layer_norm = torch.nn.LayerNorm(dim) print("y: ", layer_norm(embedding... | Pytorch layer norm states mean and std calculated over last D dimensions. Based on this as I expect for (batch_size, seq_size, embedding_dim) here calculation should be over (seq_size, embedding_dim) for layer norm as last 2 dimensions excluding batch dim. A similar question and answer with layer norm implementation ca... | 10 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.