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
63,430,672
2020-8-15
https://stackoverflow.com/questions/63430672/how-to-make-pytest-ignore-a-class-named-testsomething
I am working on a kind of test framework that happens to have classes named TestSomething of course. And I realized my tests are failing because pytest sees these classes as "something I need to instantiate and run!", as soon as imported. And this absolutely won't work. import pytest from package import TestSomethingCl...
Explicitly Disable You're able to allow pytest to ignore this specific class by virtue of it starting with the word Test, by setting the __test__ flag to False within your conflicting class class TestSomethingClass(object): __test__ = False def test_class_something(self, object): pass feature: https://github.com/pytes...
9
12
63,427,771
2020-8-15
https://stackoverflow.com/questions/63427771/extracting-intermediate-layer-outputs-of-a-cnn-in-pytorch
I am using a Resnet18 model. ResNet( (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace=True) (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=Fals...
If you know how the forward method is implemented, then you can subclass the model, and override the forward method only. If you are using the pre-trained weights of a model in PyTorch, then you already have access to the code of the model. So, find where the code of the model is, import it, subclass the model, and ove...
8
13
63,426,545
2020-8-15
https://stackoverflow.com/questions/63426545/best-way-of-tqdm-for-data-loader
How to use tqdm for data_loader ? is this the correct way? for i,j in enumerate(data_loader,total = 100): pass
You need to wrap the iterable with tqdm, as their documentation clearly says: Instantly make your loops show a smart progress meter - just wrap any iterable with tqdm(iterable), and you’re done! If you're enumerating over an iterable, you can do something like the following. Sleep is only for visualizing it. from tqd...
27
34
63,420,889
2020-8-14
https://stackoverflow.com/questions/63420889/fastapi-pydantic-circular-references-in-separate-files
I would love to use a schema that looks something like the following in FastAPI: from __future__ import annotations from typing import List from pydantic import BaseModel class Project(BaseModel): members: List[User] class User(BaseModel): projects: List[Project] Project.update_forward_refs() but in order to keep my p...
There are three cases when circular dependency may work in Python: Top of module: import package.module Bottom of module: from package.module import attribute Top of function: works both In your situation, the second case "bottom of module" will help. Because you need to use update_forward_refs function to resolve py...
28
25
63,424,180
2020-8-15
https://stackoverflow.com/questions/63424180/bs4-replace-with-result-is-no-longer-in-tree
I need to replace multiple words in a html document. Atm I am doing this by calling replace_with once for each replacement. Calling replace_with twice on a NavigableString leads to a ValueError (see example below) cause the replaced element is no longer in the tree. Minimal example #!/usr/bin/env python3 from bs4 impor...
The first txt.replace_with(...) removes NavigableString (here stored in variable txt) from the document tree (doc). This effectively sets txt.parent to None The second txt.replace_with(...) looks at parent property, finds None (because txt is already removed from tree) and throws an ValueError. As you said at the end o...
7
5
63,422,389
2020-8-15
https://stackoverflow.com/questions/63422389/is-there-a-way-to-download-video-while-keeping-their-chapters-metadata
I've used many video downloaders before: atube catcher, 4k downloader, jDownloader, and currently using youtube-dl. I can't download videos, this for example, while still keeping their online chapters intact, like part1 is "intro" lasting from 00:00 to 00:45 and so on. So far I tried these parameters with youtube-dl Fi...
The information you want is called chapters in the youtube-dl info JSON. There is a recent open pull request for youtube-dl that fixes a problem with this information. In the current release of youtube-dl, if you use the ---write-info-json or --dump-json you will see that the chapters information is null ("chapters": n...
7
8
63,370,701
2020-8-12
https://stackoverflow.com/questions/63370701/snowflake-pandas-pd-writer-writes-out-tables-with-nulls
I have a Pandas dataframe that I'm writing out to Snowflake using SQLAlchemy engine and the to_sql function. It works fine, but I have to use the chunksize option because of some Snowflake limit. This is also fine for smaller dataframes. However, some dataframes are 500k+ rows, and at a 15k records per chunk, it takes ...
Turns out, the documentation (arguably, Snowflake's weakest point) is out of sync with reality. This is the real issue: https://github.com/snowflakedb/snowflake-connector-python/issues/329. All it needs is a single character in the column name to be upper case and it works perfectly. My workaround is to simply do: df.c...
9
21
63,412,583
2020-8-14
https://stackoverflow.com/questions/63412583/nswindow-drag-regions-should-only-be-invalidated-on-the-main-thread-this-will-t
I am writing a Python program with two threads. One displays a GUI and the other gets input from a scanner and saves data in an online database. The code works fine on my raspberry pi but if I try it on my MacBook Pro (Catalina 10.15.2), I get the above mentioned warning followed by my code crashing. Does anyone have a...
You likely use different Python versions. Your Python on your Raspberry PI still allows invalidating NSWindow drag regions outside the Main thread, while your Python in your MacBook Pro already stopped supporting this. You will likely need to refactor your code so that NSWindow drag regions will only be invalidated on ...
13
5
63,412,782
2020-8-14
https://stackoverflow.com/questions/63412782/pandas-dataframe-filling-missing-values-in-a-column
I have a large DataFrame with the following columns: import pandas as pd x = pd.read_csv('age_year.csv') x.head() ID Year age 22445 1991 29925 1991 76165 1991 223725 1991 16.0 280165 1991 The Year column has values ranging from 1991 to 2017. Most ID have an age value in each Year, for example: x.loc[x['ID'] == 280165]...
I think instead of trying to fill the values, find the year of birth instead. df["age"] = df["Year"] - (df["Year"]-df["age"]).mean() Or general solution with more than 1 id: s = df.loc[df["age"].notnull()].groupby("ID").first() df["age"] = df["Year"]-df["ID"].map(s["Year"]-s["age"]) print (df) ID Year age 0 280165 199...
7
3
63,413,928
2020-8-14
https://stackoverflow.com/questions/63413928/how-to-manually-set-the-color-of-points-in-plotly-express-scatter-plots
https://plotly.com/python/line-and-scatter/ has many scatter plot examples, but not a single one showing you how to set all the points' colours within px.scatter: # x and y given as DataFrame columns import plotly.express as px df = px.data.iris() # iris is a pandas DataFrame fig = px.scatter(df, x="sepal_width", y="se...
For that you may use the color_discrete_sequence argument. fig = px.scatter(df, x="sepal_width", y="sepal_length", color_discrete_sequence=['red']) This argument is to use a custom color paletter for discrete color factors, but if you are not using any factor for color it will use the first element for all the points ...
37
27
63,410,588
2020-8-14
https://stackoverflow.com/questions/63410588/cant-install-opencv-python3-8
When I execute this command: pip3 install opencv-python I get the following error: Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 /usr/lib/python3/dist-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-z4c_sn6u/overlay --no-w...
Try to upgrade your pip with pip install --upgrade pip and then run the pip install opencv-python
9
9
63,396,950
2020-8-13
https://stackoverflow.com/questions/63396950/will-conda-clean-erase-my-favorite-packages
I have to do some cleanup with my (Mini)conda python packages to free some disk space, and I see people usually resort to the conda clean command to get this job done. Conda documentation says that it it's safe to do that, as it will only erase packages that "have never been used in any environment". I've never used co...
At the very least, tarballs can be removed with no risk. Cleaning packages is done based on counting the number of hardlinks for the package. If there is only one hardlink, this implies the package is not referenced by any environment, and therefore can be removed. This will be the case for all packages that were previ...
8
10
63,400,417
2020-8-13
https://stackoverflow.com/questions/63400417/groupby-names-replace-values-with-there-max-value-in-all-columns-pandas
I have this DataFrame lst = [['AAA',15,'BBB',20],['BBB',16,'AAA',12],['BBB',22,'CCC',15],['CCC',11,'AAA',31],['DDD',25,'EEE',35]] df = pd.DataFrame(lst,columns = ['name1','val1','name2','val2']) which looks like this name1 val1 name2 val2 0 AAA 15 BBB 20 1 BBB 16 AAA 12 2 BBB 22 CCC 15 3 CCC 11 AAA 31 4 DDD 25 EEE 35...
Try using pd.wide_to_long to melt that dataframe into a long form, then use groupby with transform to find the max value. Map that max value to 'name' and reshape back to four column (wide) dataframe: df_long = pd.wide_to_long(df.reset_index(), ['name','val'], 'index', j='num',sep='',suffix='\d+') mapper= df_long.group...
7
8
63,396,570
2020-8-13
https://stackoverflow.com/questions/63396570/pip-is-selecting-wrong-path
I'm using windows 10 and I got rid of python 3.8 and installed 3.7 as the only python version on my system. When trying to install libraries using pip I now get the error: Fatal error in launcher: Unable to create process using '"c:\users\user\appdata\local\programs\python\python38-32\python.exe" "C:\Users\User\AppData...
to fix do this : check if you still have the python38-32 folder in your local variable list Delete the "%userprofile%\AppData\Local\Programs\Python\Python38" folder run pip from command line if the problem still persists then type "environment variables" in the windows search box and add "%userprofile%\AppData\Loc...
7
2
63,386,812
2020-8-13
https://stackoverflow.com/questions/63386812/plotly-how-to-hide-axis-titles-in-a-plotly-express-figure-with-facets
Is there a simple way to hide the repeated axis titles in a faceted chart using plotly express? I tried setting visible=True In the code below, but that also hid the y axis tick labels (the values). Ideally, I would like to set hiding the repeated axes titles a default for faceted plots in general (or even better, jus...
This answer has five parts: Hide subplot titles (not 100% sure you wanted to do that though...) Hide y-axis tick values using fig.layout[axis].tickfont = dict(color = 'rgba(0,0,0,0)') Set single axis labels using go.layout.Annotation(xref="paper", yref="paper") the plotly figure Complete code snippet at the end One v...
15
10
63,373,911
2020-8-12
https://stackoverflow.com/questions/63373911/how-do-you-make-pylint-in-vscode-know-that-its-in-a-package-so-that-relative-i
Layout: workspace/ .vscode/launch.json main.py foo.py: def harr(): pass launch.json: { "version": "0.2.0", "configurations": [ { "name": "Python: Module", "type": "python", "request": "launch", "cwd": "${workspaceFolder}/..", "module": "${workspaceFolderBasename}" } ] } main.py and pylint error: from .foo import harr...
Currently pylint cannot find modules accurately through relative imports, it will mess up the path, although the code can run. You could try the following two ways to solve it: 1.Add the following settings in the setting.json file. "python.linting.pylintArgs": ["--disable=all", "--enable=F,E,unreachable,duplicate-key,...
7
3
63,388,135
2020-8-13
https://stackoverflow.com/questions/63388135/vs-code-modulenotfounderror-no-module-named-pandas
Tried to import pandas in VS Code with import pandas and got Traceback (most recent call last): File "c:\Users\xxxx\hello\sqltest.py", line 2, in <module> import pandas ModuleNotFoundError: No module named 'pandas' Tried to install pandas with pip install pandas pip3 install pandas python -m pip install pandas separ...
The solution seems fairly simple! First things first though! From looking at your post, you seem to have followed a guide into installing Pandas. Nothing is wrong about that but I must point out first based on your information that you provided to us, you seem to run Windows Powershell PS C:\Users\xxxx\hello> and the e...
24
1
63,388,372
2020-8-13
https://stackoverflow.com/questions/63388372/why-there-is-an-unbound-variable-error-warning-by-ide-in-this-simple-python-func
Very simple question, but I can't find the answer to it. My IDE vs code (pylance) give me the warning/hint for a being possibly unbound. Why is this? How do I fix it? def f(): for i in range(4): a = 1 print(a) return a
Because range(4) might be something empty (if you overwrite the built-in range), in which case the loop body will never run and a will not get assigned. Which is a problem when it's supposed to get returned. Maybe you can tell your IDE to ignore this and not show the warning. Or assign some meaningful default to a befo...
15
26
63,387,031
2020-8-13
https://stackoverflow.com/questions/63387031/how-to-clear-existing-flash-messages-in-flask
I have a warning flash message in Flask that that appears before the user tries to submit a form based on background information about the user. If the user goes ahead and submits the form the way they were warned not to, they are prevented and see a second flash message. I'd like to clear the first flash message befor...
This way you can clear the flash message as there is no predefined method to clear the flash message in Flask flash helpers. You can try the below code. It works for me and maybe useful to you. session.pop('_flashes', None)
10
12
63,383,594
2020-8-12
https://stackoverflow.com/questions/63383594/how-does-tensorflow-build-work-from-tf-keras-layers-layer
I was wondering if anyone knew how the build() function works from the tf.keras.layers.Layer class under the hood. According to the documentation: build is called when you know the shapes of the input tensors and can do the rest of the initialization so to me it seems like the class is behaving similar to this: class...
The Layer.build() method is typically used to instantiate the weights of the layer. See the source code for tf.keras.layers.Dense for an example, and note that the weight and bias tensors are created in that function. The Layer.build() method takes an input_shape argument, and the shape of the weights and biases often ...
14
15
63,383,347
2020-8-12
https://stackoverflow.com/questions/63383347/runtimeerror-expected-object-of-scalar-type-long-but-got-scalar-type-float-for
I'm running into an issue while calculating the loss for my Neural Net. I'm not sure why the program expects a long object because all my Tensors are in float form. I looked at threads with similar errors and the solution was to cast Tensors as floats instead of longs, but that wouldn't work in my case because all my d...
As per the documentation and official example at pytorch webpage, The targets passed to nn.CrossEntropyLoss() should be in torch.long format # official example import torch import torch.nn as nn loss = nn.CrossEntropyLoss() input = torch.randn(3, 5, requires_grad=True) target = torch.empty(3, dtype=torch.long).random_(...
13
20
63,377,150
2020-8-12
https://stackoverflow.com/questions/63377150/what-became-available-attrs-on-django-3
First of all, I'm new to Django, so please be nice with me :D I'm currently adapting .py files for Django 3 because the files I have are compatible for Django 2. So, some changes have been made for the new version and in a file, it's written : @wraps(view_func, assigned=available_attrs(view_func)) With the import : fr...
available_attrs() only ever existed to help bridge between Python 2 and Python 3. This is documented in the Django 3.0 release notes: Removed private Python 2 compatibility APIs While Python 2 support was removed in Django 2.0, some private APIs weren’t removed from Django so that third party apps could continue using...
14
21
63,372,039
2020-8-12
https://stackoverflow.com/questions/63372039/how-can-you-read-a-gzipped-parquet-file-in-python
I need to open a gzipped file, that has a parquet file inside with some data. I am having so much trouble trying to print/read what is inside the file. I tried the following: with gzip.open("myFile.parquet.gzip", "rb") as f: data = f.read() This does not seem to work, as I get an error that my file id not a gz file. T...
You can use read_parquet function from pandas module: Install pandas and pyarrow: pip install pandas pyarrow use read_parquet which returns DataFrame: data = read_parquet("myFile.parquet.gzip") print(data.count()) # example of operation on the returned DataFrame
10
15
63,307,440
2020-8-7
https://stackoverflow.com/questions/63307440/how-to-plot-a-mean-line-on-a-kdeplot-between-0-and-the-y-value-of-the-mean
I have a distplot and I would like to plot a mean line that goes from 0 to the y value of the mean frequency. I want to do this, but have the line stop at when the distplot does. Why isn't there a simple parameter that does this? It would be very useful. I have some code that gets me almost there: plt.plot([x.mean(),x....
Update for the latest versions of matplotlib (3.3.4) and seaborn (0.13.3): the kdeplot with shade=True now doesn't create a line object anymore. To get the same outcome as before, setting fill=False will still create the line object. The curve can then be filled with ax.fill_between(). The code below is changed accordi...
7
25
63,367,594
2020-8-11
https://stackoverflow.com/questions/63367594/the-url-function-in-django-has-been-deprecated-do-i-have-to-change-my-source
The url() function in django has been deprecated since version 3.1. Here's how backwards compatibility is being handled; def url(regex, view, kwargs=None, name=None): warnings.warn( 'django.conf.urls.url() is deprecated in favor of ' 'django.urls.re_path().', RemovedInDjango40Warning, stacklevel=2, ) return re_path(reg...
will the projects that use it have to change their source code? Yes, if they upgrade to django-4.0, url will no longer be available. Typically if something is marked deprecated, it is removed two versions later, so in django-4.0, since after django-3.2, django-4.0 will be released. If you thus have an active project,...
6
9
63,264,888
2020-8-5
https://stackoverflow.com/questions/63264888/pydantic-using-property-getter-decorator-for-a-field-with-an-alias
scroll all the way down for a tl;dr, I provide context which I think is important but is not directly relevant to the question asked A bit of context I'm in the making of an API for a webapp and some values are computed based on the values of others in a pydantic BaseModel. These are used for user validation, data seri...
If you can update to the newest version of Pydantic 2, which may be a bit of an ordeal honestly, there are some really nice new feature including support for properties like you are referring to. I recently updated and after some refactoring I have been happy with the newer version. from pydantic import BaseModel, comp...
17
10
63,351,189
2020-8-11
https://stackoverflow.com/questions/63351189/pyarrow-add-column-to-pyarrow-table
I have a pyarrow table name final_table of shape 6132,7 I want to add column to this table list_ = ['IT'] * 6132 final_table.append_column('COUNTRY_ID', list_) but I am getting following error ArrowInvalid: Added column's length must match table's length. Expected length 6132 but got length 12264
According to the documentation: Append column at end of columns. Parameters field (str or Field) – If a string is passed then the type is deduced from the column data. column (Array, list of Array, or values coercible to arrays) – Column data. Returns pyarrow.Table – New table with the passed column added. I think pya...
7
12
63,363,044
2020-8-11
https://stackoverflow.com/questions/63363044/why-does-np-inf-2-result-in-nan-and-not-infinity
I’m slightly disappointed that np.inf // 2 evaluates to np.nan and not to np.inf, as is the case for normal division. Is there a reason I’m missing why nan is a better choice than inf?
I'm going to be the person who just points at the C level implementation without any attempt to explain intent or justification: *mod = fmod(vx, wx); div = (vx - *mod) / wx; It looks like in order to calculate divmod for floats (which is called when you just do floor division) it first calculates the modulus and float...
41
33
63,316,840
2020-8-8
https://stackoverflow.com/questions/63316840/django-3-1-streaminghttpresponse-with-an-async-generator
Documentation for Django 3.1 says this about async views: The main benefits are the ability to service hundreds of connections without using Python threads. This allows you to use slow streaming, long-polling, and other exciting response types. I believe that "slow streaming" means we could implement an SSE view with...
This is an old question but it came up on a Google result since I was looking for a solution to the same issue. In the end I found this repo https://github.com/valberg/django-sse - which uses async views in Django 4.2 to stream via SSE (specifically see here). I understand this is a recent addition to Django so I hope ...
21
4
63,304,163
2020-8-7
https://stackoverflow.com/questions/63304163/how-to-create-a-deb-package-for-a-python-project-without-setup-py
Any documentation I've found about this topic mentions that the "only" requirement to build a deb package is to have a correct setup.py (and requirements.txt). For instance in dh-virtualenv tutorial, stdeb documentation and the Debian's library style guide for python. But nowadays new (amazing) tools like poetry allow ...
setuptools, and the setup.py file that it requires, has been the de-facto packaging standard in python for the longest time. The new package managers you mention were enabled by the introduction of PEP 517 and PEP 518 (or read this for a high-level description on the topic), which provide a standardized way of specifyi...
17
12
63,312,692
2020-8-8
https://stackoverflow.com/questions/63312692/importerror-attempted-relative-import-with-no-known-parent-package
I'm attempting to import a script from my Items file but I keeps on getting an error from .Items.Quest1_items import * gives from .Items.Quest1_items import * # ImportError: attempted relative import with no known parent package # Process finished with exit code 1 Here my project tree, I'm running the script from the...
Remove the dot from the beginning. Relative paths with respect to main.py are found automatically. from Items.Quest1_items import *
25
28
63,335,753
2020-8-10
https://stackoverflow.com/questions/63335753/how-to-check-if-string-exists-in-enum-of-strings
I have created the following Enum: from enum import Enum class Action(str, Enum): NEW_CUSTOMER = "new_customer" LOGIN = "login" BLOCK = "block" I have inherited from str, too, so that I can do things such as: action = "new_customer" ... if action == Action.NEW_CUSTOMER: ... I would now like to be able to check if a s...
I just bumped into this problem today (2020-12-09); I had to change a number of subpackages for Python 3.8. Perhaps an alternative to the other solutions here is the following, inspired by the excellent answer here to a similar question, as well as @MadPhysicist's answer on this page: from enum import Enum, EnumMeta cl...
39
52
63,257,839
2020-8-5
https://stackoverflow.com/questions/63257839/best-way-to-specify-nested-dict-with-pydantic
Context I'm trying to validate/parse some data with pydantic. I want to specify that the dict can have a key daytime, or not. If it does, I want the value of daytime to include both sunrise and sunset. e.g. These should be allowed: { 'type': 'solar', 'daytime': { 'sunrise': 4, # 4am 'sunset': 18 # 6pm } } And { 'type'...
Pydantic create_model function is what you need: from pydantic import BaseModel, create_model class Plant(BaseModel): daytime: Optional[create_model('DayTime', sunrise=(int, ...), sunset=(int, ...))] = None type: str
20
23
63,266,504
2020-8-5
https://stackoverflow.com/questions/63266504/python-pytest-mock-fails-with-assert-none-for-function-call-assertions
I am trying to mock some calls to boto3 and it looks like the mocked function is returning the correct value, and it look like if I change the assertion so it no longer matches what was passed in the assertion fails because the input parameters do not match, however if I make them match then the assertion fails with: E...
You have two assertions on this line: assert site_dao.ddb_client.get_item.assert_called_with(TableName=...) The first assertion is assert_called_with which sounds like it is what you want. Then you have another assertion at the beginning of the line: assert ... which asserts on the return value of the assert_called_wi...
21
86
63,280,876
2020-8-6
https://stackoverflow.com/questions/63280876/what-is-the-difference-between-config-and-configure-in-tkinter
I'm a beginner in Python. Recently, I finished the basics, and now I'm trying to make some GUI applications. I have found many cases where we use config() and configure(). But what is the difference between config() and configure()? I mean, in what cases should config() be used, and in what cases should configure() be ...
Both are exactly the same, the only difference is, the difference in the name, I would just reccomend using .config() just to save a few typing characters ;-)
7
7
63,318,719
2020-8-8
https://stackoverflow.com/questions/63318719/difference-between-type-alias-and-newtype
What is the difference between this: INPUT_FORMAT_TYPE = NewType('INPUT_FORMAT_TYPE', Tuple[str, str, str]) and this INPUT_FORMAT_TYPE = Tuple[str, str, str] Functionally, both work but IDEs like PyCharm flag code like this: return cast(INPUT_FORMAT_TYPE, ("*", "*", "All"))
InputFormat (renamed it to keep type notation consistent) can be a subtype or alias of Tuple[str, str, str]. Having it be a subtype (your first example) instead of an alias (your second example) is useful for a situation where you want to statically verify (through something like mypy) that all InputFormats were made i...
15
21
63,290,336
2020-8-6
https://stackoverflow.com/questions/63290336/python-mock-check-if-methods-are-called-in-mocked-object
I have a certain piece of code that looks like this: # file1.py from module import Object def method(): o = Object("param1") o.do_something("param2") I have unittests that look like this: @patch("file1.Object") class TestFile(unittest.TestCase): def test_call(self, obj): ... I can do obj.assert_called_with() in the u...
You can do this, because the arguments are passed to the mock object. This should work: @patch("file1.Object") class TestFile: def test_call(self, obj): method() obj.assert_called_once_with("param1") obj.return_value.do_something.assert_called_once_with("param2") obj.return_value is the Object instance (which is a Mag...
7
10
63,347,818
2020-8-10
https://stackoverflow.com/questions/63347818/aiohttp-client-exceptions-clientconnectorerror-cannot-connect-to-host-stackover
here is my code: import asyncio from aiohttp import ClientSession async def main(): url = "https://stackoverflow.com/" async with ClientSession() as session: async with session.get(url) as resp: print(resp.status) asyncio.run(main()) if I run it on my computer, everything works, but if I run it on pythonanywhere, I ge...
first solution Referring to the help from the forum, I added trust_env = True when creating the client and now everything works. Explanation: Free accounts on PythonAnywhere must use a proxy to connect to the public internet, but aiohttp, by default, does not connect to a proxy accessible from an environment variable. ...
29
32
63,308,383
2020-8-7
https://stackoverflow.com/questions/63308383/typeerrorkeyword-argument-not-understood-groups-in-keras-models-load-mod
After training a model using Google Colab, I downloaded it using the following command (inside Google Colab): model.save('model.h5') from google.colab import files files.download('model.h5') My problem is that when I try to load the downloaded model.h5 using my local machine (outside Google Colab), I get the following...
I commented earlier saying I had the same exact error from doing the same exact thing. I just solved it by upgrading both tensorflow and keras on my local machine pip install --upgrade tensorflow pip install --upgrade keras The error was probably due to differing versions of the packages between Colab and local machin...
11
14
63,272,417
2020-8-5
https://stackoverflow.com/questions/63272417/pandas-groupby-drops-group-columns-after-fillna-in-1-1-0
I have a piece of pandas code which used to work in version 1.0.5. Here's a simplified, self-contained example of my problem: import pandas as pd df = pd.DataFrame(data=[ ('bk1', 10), ('bk1', None), ('bk1', 13), ('bk1', None), ('bk2', None), ('bk2', 14), ('bk3', 12), ('bk3', None), ], columns=('book', 'price')) grouped...
You could take a different approach to get around this issue (different from the solution proposed by Nick ODell) by using the update function: df.update(df.groupby(['book']).ffill()) print(df) Out[1]: book price 0 bk1 10.0 1 bk1 10.0 2 bk1 13.0 3 bk1 13.0 4 bk2 NaN 5 bk2 14.0 6 bk3 12.0 7 bk3 12.0 This also works in ...
7
5
63,365,434
2020-8-11
https://stackoverflow.com/questions/63365434/how-to-create-any-aws-lambda-python-layer-usage-example-with-xgboost
I am having trouble creating a lambda layer for the xgboost library. Im running: Im grabbing a zip of xgboost and it's dependencies from here (https://github.com/alexeybutyrev/aws_lambda_xgboost) and loading it into a layer. When I try to test my lambda, I get this error: Unable to import module 'lambda_function': No m...
EDIT: As @Marcin has remark, the first answer provided works for packages under 262 MB large. A. Python Packages within Lambda Layer size limit You can also do it with AWS sam cli and Docker (see this link to install the SAM cli), to build the packages inside a container. Basically you initialize a default template wit...
8
8
63,342,767
2020-8-10
https://stackoverflow.com/questions/63342767/command-errored-out-with-exit-status-1-python-setup-py-egg-info-check-the-logs
I am trying to install mysqlclient for python, but I always get this error when I try: $ pip3 install mysqlclient How can I resolve this issue?
Looking at the error message, it seems that there is an OS Error, and judging by the terminal layout, you're using Linux. It seems that to install this package on Linux, there are extra instructions to follow, mentioned on the module's github page: You may need to install the Python 3 and MySQL development headers and...
6
24
63,279,168
2020-8-6
https://stackoverflow.com/questions/63279168/valueerror-input-0-of-layer-sequential-is-incompatible-with-the-layer-expect
I keep on getting this error related to input shape. Any help would be highly appreciated. Thanks! import tensorflow as tf (xtrain, ytrain), (xtest, ytest) = tf.keras.datasets.mnist.load_data() model = tf.keras.Sequential([ tf.keras.layers.Conv2D(16, kernel_size=3, activation='relu'), tf.keras.layers.MaxPooling2D(pool_...
The input layers of the model you created needs a 4 dimension tensor to work with but the x_train tensor you are passing to it has only 3 dimensions This means that you have to reshape your training set with .reshape(n_images, 286, 384, 1). Now you have added an extra dimension without changing the data and your model ...
23
20
63,277,123
2020-8-6
https://stackoverflow.com/questions/63277123/what-does-the-error-message-about-pip-use-feature-2020-resolver-mean
I'm trying to install jupyter on Ubuntu 16.04.6 x64 on DigitalOcean droplet. It is giving me the following error message, and I can't understand what this means. ERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency...
According to this announcement, pip will introduce a new dependency resolver in October 2020, which will be more robust but might break some existing setups. Therefore they are suggesting users to try running their pip install scripts at least once (in dev mode) with this option: --use-feature=2020-resolver to anticipa...
87
64
63,326,840
2020-8-9
https://stackoverflow.com/questions/63326840/specifying-command-line-scripts-in-pyproject-toml
I'm trying to add a pyproject.toml to a project that's been using setup.py in order to enable support by pipx. I'd like to specify the command line scripts the project includes in pyproject.toml, but all the guides I can find give instructions for use with poetry, which I am not using. I also don't want to specify entr...
Is there a proper place in pyproject.toml to specify command line scripts? PEP566 (Metadata 2.1) only defines Core metadata specifications. Thus, the answer depends on your build system (Note: PEP518 defines build system concept). If you use the existing build tools such as setuptools, poetry, and flit, you only can ...
61
14
63,272,437
2020-8-5
https://stackoverflow.com/questions/63272437/how-can-i-send-a-message-to-someone-with-telegram-api-using-my-own-account
It's awesome how google something can be annoying when you can't find the right words. I found a million answers on how about to create a Telegram Bot to send and receive messages, and it's easy as write maybe five code lines. But how about managing my own account? I want to know if it it's posible, using Python (telep...
Telegram has a thorough and documented public API. Following some links from there, here is the summary of the relevant parts: the API is not restricted to bots, they are just a (special) kind of users; the API has methods called getMessages and sendMessage, that should be what you need; to call the API, Telegram reco...
30
30
63,341,773
2020-8-10
https://stackoverflow.com/questions/63341773/pipenv-install-giving-failed-to-load-paths-errors
I am running pipenv install --dev which is giving me the following errors Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environm...
Remove your Pipfile.lock and try rerunning pipenv install to rebuild your dependencies from your Pipfile. It is looking for a virtual environment that does not exist. By removing your Pipfile.lock, you force pipenv to create a new environment.
10
7
63,361,579
2020-8-11
https://stackoverflow.com/questions/63361579/aot-compiler-for-python
I want to get my Python script working on a bare metal device like microcontroller WITHOUT the need for an interpreter. I know there are already JIT compilers for Python like PyPy, and interpreters like CPython. However, existing interpreters I've seen (such as CPython) take up large memory (in MB range). Is there an A...
As you already mentioned Cython is an option (However, it is true that the result is big due since the C runtime need to implement the Python functionality together with your program). With regards to LLVM there was a project by Google named unladen swallow. However, that project is mostly abandoned. You can find some ...
7
7
63,338,424
2020-8-10
https://stackoverflow.com/questions/63338424/how-to-append-new-argument-after-executing-parse-args-for-argparse-in-python
I want to use argeparse module in following way, from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-b', dest='binKey', type=str) args = parser.parse_args() # I will make use of args.binKey option in this space print args.binKey # After that I want to add -d option to the arguments parse...
With the help from @hpaulj's comment, here is the resolution: Turn off help option while creating ArgumentParser object. You can call parse_known_args multiple times in between. Add help option at the end. Below is a snippet of the code from argparse import ArgumentParser parser = ArgumentParser(add_help=False) parse...
7
6
63,261,658
2020-8-5
https://stackoverflow.com/questions/63261658/get-environment-variables-in-a-cloud-function
I have a Cloud Function in GCP that queries BigQuery in a specific project/environment. As I have multiple environments I would like to get the current project/environment of the cloud function. This is so that I can access BigQuery in the corresponding environment. Of course I could just hardcode the project_id, but I...
Those environment variables you are referring to only applies to python 3.7, the second section on that page (https://cloud.google.com/functions/docs/env-var#nodejs_10_and_subsequent_runtimes) states : All languages and runtimes other than those mentioned in the previous section will use this more limited set of prede...
11
6
63,300,859
2020-8-7
https://stackoverflow.com/questions/63300859/python-location-show-distance-from-closest-other-location
I am a location in a dataframe, underneath lat lon column names. I want to show how far that is from the lat lon of the nearest train station in a separate dataframe. So for example, I have a lat lon of (37.814563 144.970267), and i have a list as below of other geospatial points. I want to find the point that is close...
A few key concepts do a Cartesian product between two data frames to get all combinations (joining on identical value between two data frames is approach to this foo=1) once both sets of data is together, have both sets of lat/lon to calculate distance) geopy has been used for this cleanup the columns, use sort_values...
10
7
63,314,452
2020-8-8
https://stackoverflow.com/questions/63314452/python-autopep8-formatting-not-working-with-max-line-length-parameter
I noticed one strange thing that autopep8 autoformatting in VSCode doesn't work when we set "python.formatting.autopep8Args": [ "--line-length 119" ], But if this setting is in a default mode that is line length 79 then it works well. Is there some issue with autopep8 to work only with line length 79 not more than th...
experimental worked for me "python.formatting.autopep8Args": ["--max-line-length", "120", "--experimental"] check out this link for proper format specifier settings
29
66
63,320,653
2020-8-8
https://stackoverflow.com/questions/63320653/preventing-namespace-collisions-between-private-and-pypi-based-python-packages
We have 100+ private packages and so far we've been using s3pypi to set up a private pypi in an s3 bucket. Our private packages have dependencies on each other (and on public packages), and it is (of course) important that our GitLab pipelines find the latest functional version of packages it relies on. I.e. we're not ...
It might not be the solution for you, but I tell what we do. Prefix the package names, and using namespaces (eg. company.product.tool). When we install our packages (including their in-house dependencies), we use a requirements.txt file including our PyPI URL. We run everything in container(s) and we install all publi...
37
15
63,325,727
2020-8-9
https://stackoverflow.com/questions/63325727/pandas-resample-a-dataframe-to-match-a-datetimeindex-of-a-different-dataframe
I have a two time series in separate pandas.dataframe, the first one - series1 has less entries and different start datatime from the second - series2: index1 = pd.date_range(start='2020-06-16 23:16:00', end='2020-06-16 23:40:30', freq='1T') series1 = pd.Series(range(len(index1)), index=index1) index2 = pd.date_range('...
Use reindex: series2.reindex(series1.index) Output: 2020-06-16 23:16:00 2 2020-06-16 23:17:00 4 2020-06-16 23:18:00 6 2020-06-16 23:19:00 8 2020-06-16 23:20:00 10 2020-06-16 23:21:00 12 2020-06-16 23:22:00 14 2020-06-16 23:23:00 16 2020-06-16 23:24:00 18 2020-06-16 23:25:00 20 2020-06-16 23:26:00 22 2020-06-16 23:27:0...
9
8
63,367,559
2020-8-11
https://stackoverflow.com/questions/63367559/how-to-fix-usr-local-bin-virtualenv-usr-bin-python-bad-interpreter-no-such
When I tried to use virtualenv on Ubuntu 18.04, I got this error: bash: /usr/local/bin/virtualenv: /usr/bin/python: bad interpreter: No such file or directory Python 2 and 3 is working fine: josir@desenv16:~/bin$ which python3 /usr/bin/python3 josir@desenv16:~/bin$ python3 Python 3.6.9 (default, Apr 18 2020, 01:56:04...
bash: /usr/local/bin/virtualenv: /usr/bin/python: bad interpreter: No such file or directory The error is in '/usr/local/bin/virtualenv' — it's first line (shebang) is #!/usr/bin/python and there is no such file at your system. I believe the stream of events led to the situation is: you've installed virtualenv with p...
7
4
63,361,267
2020-8-11
https://stackoverflow.com/questions/63361267/plotly-how-to-update-plotly-data-using-dropdown-list-for-line-graph
I am trying to add a dropdown menu to a plotly line graph that updates the graph data source when selected. My data has 3 columns and looks as such: 1 Country Average House Price (£) Date 0 Northern Ireland 47101.0 1992-04-01 1 Northern Ireland 49911.0 1992-07-01 2 Northern Ireland 50174.0 1992-10-01 3 Northern Ireland...
I've made a preliminary setup using your full datasample, and I think I've got it figured out. The challenge here is that px.line will group your data by the color argument. And that makes it a bit harder to edit the data displayed using a dropdownmenu with a direct reference to the source of your px.line plot. But you...
9
5
63,366,843
2020-8-11
https://stackoverflow.com/questions/63366843/how-to-find-the-minimal-numpy-dtype-to-store-a-maximum-integer-value
I need to create a very large numpy array that will hold non-negative integer values. I know in advance what the largest integer will be, so I want to try to use the smallest datatype possible. So far I have the following: >>> import numpy as np >>> def minimal_type(max_val, types=[np.uint8,np.uint16,np.uint32,np.uint6...
It's numpy.min_scalar_type. Examples from the docs: >>> np.min_scalar_type(10) dtype('uint8') >>> np.min_scalar_type(-260) dtype('int16') >>> np.min_scalar_type(3.1) dtype('float16') >>> np.min_scalar_type(1e50) dtype('float64') >>> np.min_scalar_type(np.arange(4,dtype='f8')) dtype('float64') You might not be interest...
6
11
63,366,430
2020-8-11
https://stackoverflow.com/questions/63366430/pass-a-dictionary-in-try-except-clause
I have a use case that requires passing a dictionary in a try/exception clause in Python 3.x The error message can be accessed as a string using str() function, but I can't figure out who to get it as a dictionary. try: raise RuntimeError({'a':2}) except Exception as e: error = e print(error['a']) e is a RuntimeError ...
Exceptions store their init args in an "args" attribute: try: raise RuntimeError({'a':2}) except Exception as e: (the_dict,) = e.args print(the_dict["a"]) That being said, if you want an exception type which has a structured key/value context associated, it would be best to define your own custom exception subclass fo...
7
14
63,361,807
2020-8-11
https://stackoverflow.com/questions/63361807/how-can-i-get-the-arguments-i-sent-to-threadpoolexecutor-when-iterating-through
I use a ThreadPoolExecutor to quickly check a list of proxies to see which ones are dead or alive. with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: futures = [] for proxy in proxies: future = executor.submit(is_proxy_alive, proxy) futures.append(future) for future in futures: print(future.result()...
While submitting the task, you could create a mapping from future to its proxy. with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: future_proxy_mapping = {} futures = [] for proxy in proxies: future = executor.submit(is_proxy_alive, proxy) future_proxy_mapping[future] = proxy futures.append(future) ...
8
18
63,339,707
2020-8-10
https://stackoverflow.com/questions/63339707/is-it-possible-to-include-c-code-in-python-in-pycharm
I'm trying to speed up some code that I have written in Python and have thought about writing some code in C to do so. However, I am using PyCharm and its supported languages section, https://www.jetbrains.com/help/pycharm/supported-languages.html doesn't mention C, meaning no option to just create a C file and then im...
Unfortunately PyCharm does not support any C/C++ coding and there are no existing plugins for PyCharm that will support this. With that said, there is an IDE for C and C++ called CLion which is released by JetBrains just like PyCharm. CLion supports many features varying from Python debugger to Python Console for worki...
7
9
63,350,459
2020-8-11
https://stackoverflow.com/questions/63350459/getting-the-frequencies-associated-with-stft-in-librosa
When using librosa.stft() to calculate a spectrogram, how does one get back the associated frequency values? I am not interested in generating an image as in librosa.display.specshow, but rather I want to have those values in hand. y, sr = librosa.load('../recordings/high_pitch.m4a') stft = librosa.stft(y, n_fft=256, w...
I would like to point out this question and answer in particular: How do I obtain the frequencies of each value in an FFT?. In addition to consulting the documentation for the STFT from librosa, we know that the horizontal axis is the time axis while the vertical axis are the frequencies. Each column in the spectrogram...
9
10
63,353,438
2020-8-11
https://stackoverflow.com/questions/63353438/plotly-how-to-set-a-varying-marker-opacity-but-keep-the-same-outline-color-for
I'm trying to plat marker where maker opacity is changed by some vector. But marker edge color opacity is constant. fig.add_trace(go.Scatter(x=real.index, y=real['some_value'], mode='markers', marker={'opacity': real['another value'], 'color':'green', 'size':10, 'line':dict(width=1, color='rgba(165,42,42,1)')} )) It ...
You can easily rescale a pandas series between 0 and 1 and use that as an argument in rgba(red,green,blue,opacity) like color='rgba(100,0,255,'+opac+')' where opac is some opacity between 0 and 1 for a certain marker in your figure. The color property of the markers is unique for any go.Scatter(), so you'll have to add...
7
6
63,347,977
2020-8-10
https://stackoverflow.com/questions/63347977/what-is-the-conceptual-purpose-of-librosa-amplitude-to-db
I'm using the librosa library to get and filter spectrograms from audio data. I mostly understand the math behind generating a spectrogram: Get signal window signal for each window compute Fourier transform Create matrix whose columns are the transforms Plot heat map of this matrix So that's really easy with librosa:...
The range of perceivable sound pressure is very wide, from around 20 μPa (micro Pascal) to 20 Pa, a ratio of 1 million. Furthermore the human perception of sound levels is not linear, but better approximated by a logarithm. By converting to decibels (dB) the scale becomes logarithmic. This limits the numerical range, t...
7
14
63,341,547
2020-8-10
https://stackoverflow.com/questions/63341547/how-to-inject-pygame-events-from-pytest
How can one inject events into a running pygame from a pytest test module? The following is a minimal example of a pygame which draws a white rectangle when J is pressed and quits the game when Ctrl-Q is pressed. #!/usr/bin/env python """minimal_pygame.py""" import pygame def minimal_pygame(testing: bool=False): pygame...
Pygame can react to custom user events, not keypress or mouse events. Here is a working code where pytest sends a userevent to pygame, pygame reacts to it and sends a response back to pytest for evaluation: #!/usr/bin/env python """minimal_pygame.py""" import pygame TESTEVENT = pygame.event.custom_type() def minimal_py...
7
3
63,343,230
2020-8-10
https://stackoverflow.com/questions/63343230/get-rankings-of-column-names-in-pandas-dataframe
I have pivoted the Customer ID against their most frequently purchased genres of performances: Genre Jazz Dance Music Theatre Customer 100000000001 0 3 1 2 100000000002 0 1 6 2 100000000003 0 3 13 4 100000000004 0 5 4 1 100000000005 1 10 16 14 My desired result is to append the column names according to the rankings: ...
Use: i = np.argsort(df.to_numpy() * -1, axis=1) r = pd.DataFrame(df.columns[i], index=df.index, columns=range(1, i.shape[1] + 1)) df = df.join(r.add_prefix('Rank')) Details: Use np.argsort along axis=1 to get the indices i that would sort the genres in descending order. print(i) array([[1, 3, 2, 0], [2, 3, 1, 0], [2, ...
6
5
63,269,750
2020-8-5
https://stackoverflow.com/questions/63269750/can-i-store-a-parquet-file-with-a-dictionary-column-having-mixed-types-in-their
I am trying to store a Python Pandas DataFrame as a Parquet file, but I am experiencing some issues. One of the columns of my Pandas DF contains dictionaries as such: import pandas as pandas df = pd.DataFrame({ "ColA": [1, 2, 3], "ColB": ["X", "Y", "Z"], "ColC": [ { "Field": "Value" }, { "Field": "Value2" }, { "Field":...
ColC is a UDT (user defined type) with one field called Field of type Union of String, List of String. In theory arrow supports it, but in practice it has a hard time figuring out what the type of ColC is. Even if you were providing the schema of your data frame explicitly, it wouldn't work because this type of convers...
11
9
63,324,327
2020-8-9
https://stackoverflow.com/questions/63324327/write-a-csv-file-asynchronously-in-python
I am writing a CSV file with the following function: import csv import os import aiofiles async def write_extract_file(output_filename: str, csv_list: list): """ Write the extracted content into the file """ try: async with aiofiles.open(output_filename, "w+") as csv_file: writer = csv.DictWriter(csv_file, fieldnames=c...
In my opinion it’s better not to try to use the aiofiles with the csv module and run the synchronous code using loop.run_in_executor and wait it asynchronously like below: def write_extract_file(output_filename: str, csv_list: list): """ Write the extracted content into the file """ try: with open(output_filename, "w+"...
11
8
63,294,040
2020-8-7
https://stackoverflow.com/questions/63294040/pandas-check-if-dataframe-has-negative-value-in-any-column
I wonder how to check if a pandas dataframe has negative value in 1 or more columns and return only boolean value (True or False). Can you please help? In[1]: df = pd.DataFrame(np.random.randn(10, 3)) In[2]: df Out[2]: 0 1 2 0 -1.783811 0.736010 0.865427 1 -1.243160 0.255592 1.670268 2 0.820835 0.246249 0.288464 3 -0.9...
Actually, if speed is important, I did a few tests: df = pd.DataFrame(np.random.randn(10000, 30000)) Test 1, slowest: pure pandas (df < 0).any().any() # 303 ms ± 1.28 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Test 2, faster: switching over to numpy with .values for testing the presence of a True entry (df...
12
18
63,329,657
2020-8-9
https://stackoverflow.com/questions/63329657/python-3-7-error-unsupported-pickle-protocol-5
I'm trying to restore a pickled config file from RLLib (json didn't work as shown in this post), and getting the following error: config = pickle.load(open(f"{path}/params.pkl", "rb")) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input...
Use pickle5 or load it into python 3.8+ and then serialize it to a lower version of it using the protocol parameter.
95
69
63,297,763
2020-8-7
https://stackoverflow.com/questions/63297763/why-is-this-regular-expression-so-slow-in-java
I recently had a SonarQube rule (https://rules.sonarsource.com/java/RSPEC-4784) bring to my attention some performance issues which could be used as a denial of service against a Java regular expression implementation. Indeed, the following Java test shows how slow the wrong regular expression can be: import org.junit...
Caveat: I don't really know much about regex internals, and this is really conjecture. And I can't answer why Java suffers from this, but not the others (also, it is substantially faster than your 12 seconds in jshell 11 when I run it, so it perhaps only affects certain versions). "aaaaaaaaaaaaaaaaaaaaaaaaaaaabs".match...
51
54
63,318,567
2020-8-8
https://stackoverflow.com/questions/63318567/azure-function-exception-oserror-errno-30-read-only-file-system
I'm trying to copy the value from the Excel file but it returns this error message: Exception while executing function: Functions.extract Result: Failure Exception: OSError: [Errno 30] Read-only file system: './data_download/xxxxx.xlsx' Stack: File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_wor...
This is not related to Azure function, in general Only /tmp seems to be writable Try adding tmp to the file path filepath = '/tmp/' + key
9
13
63,265,707
2020-8-5
https://stackoverflow.com/questions/63265707/plotly-how-to-plot-multiple-lines-with-shared-x-axis
I would like to have a multiple line plot within same canvas tied with the same x-axis as shown something in the figure: Using subplots does not achieve the intended desire. import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots(rows=2, shared_xaxes=...
With a dataset such as this you can select any number of columns, set up a figure using fig = make_subplots() with shared_xaxes set to True and then add your series with a shared x-axis using fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1) in a loop to get this: Let me know if this is a setu...
10
15
63,310,735
2020-8-8
https://stackoverflow.com/questions/63310735/do-pyspark-dataframes-have-a-pipe-function-like-in-pandas
For example in Pandas I would do data_df = ( pd.DataFrame(dict(col1=['a', 'b', 'c'], col2=['1', '2', '3'])) .pipe(lambda df: df[df.col1 != 'a']) ) This is similar to R's pipe %>% Is there something similar in PySpark?
I think, in pyspark, you can easily achieve this pipe functionality with help of pipeline. convert each of the pipe function into the transformer. There are some predefined transformers that spark provides, we can make use of that also Create pipeline using the transformers Run the pipeline to transform provided dataf...
7
2
63,302,027
2020-8-7
https://stackoverflow.com/questions/63302027/how-to-avoid-double-extracting-of-overlapping-patterns-in-spacy-with-matcher
I need to extract item combination from 2 lists by means of python Spacy Matcher. The problem is following: Let us have 2 lists: colors=['red','bright red','black','brown','dark brown'] animals=['fox','bear','hare','squirrel','wolf'] I match the sequences by the following code: first_color=[] last_color=[] only_first_...
You may use spacy.util.filter_spans: Filter a sequence of Span objects and remove duplicates or overlaps. Useful for creating named entities (where one token can only be part of one entity) or when merging spans with Retokenizer.merge. When spans overlap, the (first) longest span is preferred over shorter spans. Pyth...
15
20
63,302,534
2020-8-7
https://stackoverflow.com/questions/63302534/how-to-write-torch-devicecuda-if-torch-cuda-is-available-else-cpu-as-a-f
I'm a beginner to Pytorch and wanted to type this statement as a whole if else statement:- torch.device('cuda' if torch.cuda.is_available() else 'cpu') Can somebody help me?
Here is the code as a whole if-else statement: torch.device('cuda' if torch.cuda.is_available() else 'cpu') if torch.cuda.is_available(): torch.device('cuda') else: torch.device('cpu') Since you probably want to store the device for later, you might want something like this instead: device = torch.device('cuda' if to...
11
30
63,302,082
2020-8-7
https://stackoverflow.com/questions/63302082/syntaxerror-f-string-expecting
I have a problem here. I don't know why this code does not work. newline = '\n' tasks_choosen = ['markup', 'media', 'python_api', 'script', 'style', 'vue'] print(f'{ newline }### Initializing project with the following tasks: { ' '.join(tasks_choosen) }.{ newline }') Error: File "new-gulp-project.py", line 85 print(f...
Because you use single quotes twice you get: print(f'{ newline }### Initializing project with the following tasks: { ' instead of print(f'{ newline }### Initializing project with the following tasks: { ' '.join(tasks_choosen) }.{ newline }') Use double quotes inside: print(f'{ newline }### Initializing project with th...
10
24
63,286,757
2020-8-6
https://stackoverflow.com/questions/63286757/sqlalchemy-mysql-pass-table-name-as-a-parameter-in-a-raw-query
In my app I use SQLAlchemy and mysql-connector-python. I would like to perform such query SELECT * FROM :table LIMIT 10 on my mysql database. However my code doesn't work table_name = "tmp1" QUERY = "SELECT * FROM :table LIMIT 10" conn = create_sql_connection() res = conn.execute( QUERY, {'table': table_name} ).fetchal...
you can pass the user provided string to a Table statement and build queries from this: (here I assume you get the user data from a post request json) table_name_string = request.get_json().get('table') selected_table = db.Table(table_name_string, metadata, autoload=True) query = selected_table.select() you can also g...
7
6
63,298,721
2020-8-7
https://stackoverflow.com/questions/63298721/how-to-update-imagefield-in-django
i am new in Django. i am having issue in updating ImageField.i have following code in models.py class ImageModel(models.Model): image_name = models.CharField(max_length=50) image_color = models.CharField(max_length=50) image_document = models.ImageField(upload_to='product/') -This is My forms.py class ImageForm(fo...
I think you missed the enctype="multipart/form-data", try to change: <form method="POST" action="/myapp/updateimage/{{ singleimagedata.id }}"> into; <form method="POST" enctype="multipart/form-data" action="{% url 'updateimage' id=singleimagedata.id %}"> Don't miss also to add the image_color field to your html inpu...
8
8
63,276,033
2020-8-6
https://stackoverflow.com/questions/63276033/what-is-the-difference-between-using-mock-mock-vs-mock-patch-and-when-to-us
What is the difference between using mock.Mock() vs mock.patch()? When to use mock.Mock() and when to use mock.patch() I've read that Mock is used to replace something that is used in the current scope, vs, patch is used to replace something that is imported and/or created in another scope. Can someone explain what ...
I'm not completely sure if I understood your question, but I'll give it a try. As described in the documentation, Mock objects (actually MagickMock instances) are created by using the patch decorator: from unittest.mock import patch @patch('some_module.some_object') def test_something(mocked_object): print(mocked_objec...
15
22
63,289,981
2020-8-6
https://stackoverflow.com/questions/63289981/pyspark-insertinto-overwrite
I am trying to insert data from a data frame into a Hive table. I have been able to do so successfully using df.write.insertInto("db1.table1", overwrite = True). I am just a little confused about the overwrite = True part -- I tried running it multiple times and it seemed to append, not overwrite. There wasn't too much...
df.insertInto works only if table already exists in hive. df.write.insertInto("db.table1",overwrite=False) will append the data to the existing hive table. df.write.insertInto("db.table1",overwrite=True) will overwrite the data in hive table. Example: df.show() #+----+---+ #|name| id| #+----+---+ #| a| 1| #| b| 2| #+--...
6
13
63,289,494
2020-8-6
https://stackoverflow.com/questions/63289494/what-is-the-correct-syntax-for-walrus-operator-with-ternary-operator
Looking at Python-Dev and StackOverflow, Python's ternary operator equivalent is: a if condition else b Looking at PEP-572 and StackOverflow, I understand what Walrus operator is: := Now I'm trying to to combine the "walrus operator's assignment" and "ternary operator's conditional check" into a single statement, som...
Syntactically, you are just missing a pair of parenthesis. do_something(list_of_roles) if (list_of_roles := get_role_list(username)) else "Role list is [] empty" If you look at the grammar, := is defined as part of a high-level namedexpr_test construct: namedexpr_test: test [':=' test] while a conditional expression...
18
27
63,278,444
2020-8-6
https://stackoverflow.com/questions/63278444/google-cloud-storage-python-client-attributeerror-clientoptions-object-has-no
I am using cloud storage with App Engine Flex. Out of the blue i start getting this error message after deploy succeeds The error is happening from these lines in my flask app. from google.cloud import storage, datastore client = storage.Client() File "/home/vmagent/app/main.py", line 104, in _load_db client = storage...
This is due to https://github.com/googleapis/google-cloud-python/issues/10471. I'd recommend upgrading google-cloud-core and google-api-core to the latest versions with the bugfix.
12
9
63,286,750
2020-8-6
https://stackoverflow.com/questions/63286750/how-to-apply-kernel-regularization-in-a-custom-layer-in-keras-tensorflow
Consider the following custom layer code from a TensorFlow tutorial: class MyDenseLayer(tf.keras.layers.Layer): def __init__(self, num_outputs): super(MyDenseLayer, self).__init__() self.num_outputs = num_outputs def build(self, input_shape): self.kernel = self.add_weight("kernel", shape=[int(input_shape[-1]), self.num...
The add_weight method takes a regularizer argument which you can use to apply regularization on the weight. For example: self.kernel = self.add_weight("kernel", shape=[int(input_shape[-1]), self.num_outputs], regularizer=tf.keras.regularizers.l1_l2()) Alternatively, to have more control like other built-in layers, you...
6
13
63,278,737
2020-8-6
https://stackoverflow.com/questions/63278737/object-of-type-decimal-is-not-json-serializable-aws-lambda-dynamodb
Lambda execution failed with status 200 due to customer function error: Object of type 'Decimal' is not JSON serializable I went through all the existing solutions in the following link but nothing worked for me. What am I doing wrong?: Python JSON serialize a Decimal object import json import boto3 import decimal cl...
It seems you have two options: Probably easiest, you can serialize the int/float value of a Decimal object: """ assume d is your decimal object """ serializable_d = int(d) # or float(d) d_json = json.dumps(d) You can add simplejson to your requirements.txt, which now has support for serializing Decimals. It's a dro...
15
18
63,265,669
2020-8-5
https://stackoverflow.com/questions/63265669/is-possible-to-save-a-temporaly-file-in-a-azure-function-linux-consuption-plan-i
first of all sorry for my English. I have an Azure Function Linux Consuption Plan using Python and I need to generate an html, transform to pdf using wkhtmltopdf and send it by email. #generate temporally pdf config = pdfkit.configuration(wkhtmltopdf="binary/wkhtmltopdf") pdfkit.from_string(pdf_content, 'report.pdf',c...
The tempfile.gettempdir() method returns a temporary folder, which on Linux is /tmp. Your application can use this directory to store temporary files generated and used by your functions during execution. So use /tmp/report.pdf as the file directory to save temporary file. with open('/tmp/report.pdf', 'rb') as f: data ...
8
10
63,273,028
2020-8-5
https://stackoverflow.com/questions/63273028/fastapi-get-user-id-from-api-key
In fastAPI one can simply write a security dependency at the router level and secure an entire part of the URLs. router.include_router( my_router, prefix="/mypath", dependencies=[Depends(auth.oauth2_scheme)] ) This avoids repeating a lot of code. The only problem is that I would like to protect a part of URLs with a r...
Once the user is authenticated in the dependency function add the user_id to request.state, then on your route you can access it from the request object. async def oauth2_scheme(request: Request): request.state.user_id = "foo" my_router = APIRouter() @my_router .get("/") async def hello(request: Request): print(request...
7
4
63,259,362
2020-8-5
https://stackoverflow.com/questions/63259362/type-hints-for-lxml
New to Python and come from a statically typed language background. I want type hints for https://lxml.de just for ease of development (mypy flagging issues and suggesting methods would be nice!) To my knowledge, this is a python 2.0 module and doesn’t have types. Currently I’ve used https://mypy.readthedocs.io/en/stab...
There is an official stubs package for lxml now called lxml-stubs: $ pip install lxml-stubs Note, however, that the stubs are still in development and are not 100% complete yet (although very much usable from my experience). These stubs were once part of typeshed, then curated by Jelle Zijlstra after removal and now a...
17
16
63,258,749
2020-8-5
https://stackoverflow.com/questions/63258749/how-to-extract-density-function-probabilities-in-python-pandas-kde
The pandas.plot.kde() function is handy for plotting the estimated density function of a continuous random variable. It will take data x as input, and display the probabilities p(x) of the binned input as its output. How can I extract the values of probabilities it computes? Instead of just plotting the probabilities o...
there are several ways to do that. You can either compute it yourself or get it from the plot. As pointed out in the comment by @RichieV following this post, you can extract the data from the plot using data.plot.kde().get_lines()[0].get_xydata() Use seaborn and then the same as in 1): You can use seaborn to estim...
14
19
63,168,043
2020-7-30
https://stackoverflow.com/questions/63168043/python-matplotlib-3d-plot-with-two-axes
I am trying to create a plot similar to the one below taken from this paper, essentially a 3d plot with two distinct y-axes. Following guidance in this blog, I created a minimal example. Modules from mpl_toolkits import mplot3d import numpy as np %matplotlib inline import numpy as np import matplotlib.pyplot as plt Cr...
This isn't easy. One possible workaround approach is as follows: Based on your shared reference figure, I think you mean actually that you are looking to implement a second z-axis, not y-axis. The axes object for the 3d plot remains singular and shared (out of necessity / apparent matplotlib 3d plot limitations), but ...
7
3
63,199,763
2020-7-31
https://stackoverflow.com/questions/63199763/maintained-alternatives-to-pypdf2
I'm using the PyPDF2 library for extracting text, images, page width and heights, annotations, and other attributes from pdf documents. However, the library has many bugs and issues and seems not to be maintained for a long time already. (edit: PyPDF2 is maintained again) Is there a more vivid fork that is being maint...
Update: pypdf (pypi) is maintained again - and I am the maintainer (of pypdf and PyPDF2) :-) I've just released a new version with several bugfixes. Looking at the top PyPI packages, PyPDF2 is also the most used one (and pypdf==3.1.0 is almost the same as PyPDF2==3.0.0, the community just needs a bit of time to switch ...
24
48
63,178,721
2020-7-30
https://stackoverflow.com/questions/63178721/how-do-decode-b-x95-xc3-x8a-xb0-x8ds-x86-x89-x94-x82-x8a-xba
[Summary]: The data grabbed from the file is b"\x95\xc3\x8a\xb0\x8ds\x86\x89\x94\x82\x8a\xba" How to decode these bytes into readable Chinese characters please? ====== I extracted some game scripts from an exe file. The file is packed with Enigma Virtual Box and I unpacked it. Then I'm able to see the scripts' names j...
In order to reliably decode bytes, you must know how the bytes were encoded. I will borrow the quote from the python codecs docs: Without external information it’s impossible to reliably determine which encoding was used for encoding a string. Without this information, there are ways to try and detect the encoding (c...
7
7
63,221,321
2020-8-2
https://stackoverflow.com/questions/63221321/discord-py-how-to-get-the-user-who-invited-added-the-bot-to-his-server-soluti
I want to send a DM to the user, who invited/added the bot to his server. I noticed that it's displayed in the audit log. Can I fetch that and get the user or is there a easier way to achieve that? Example: bot = commands.Bot() @bot.event async def on_guild(guild, inviter): await inviter.send("Thanks for adding the bo...
With discord.py 2.0 you can get the BotIntegration of a server and with that the user who invited the bot. Example from discord.ext import commands bot = commands.Bot() @bot.event async def on_guild_join(guild): # get all server integrations integrations = await guild.integrations() for integration in integrations: if ...
7
4
63,169,865
2020-7-30
https://stackoverflow.com/questions/63169865/how-to-do-multiprocessing-in-fastapi
While serving a FastAPI request, I have a CPU-bound task to do on every element of a list. I'd like to do this processing on multiple CPU cores. What's the proper way to do this within FastAPI? Can I use the standard multiprocessing module? All the tutorials/questions I found so far only cover I/O-bound tasks like web ...
async def endpoint You could use loop.run_in_executor with ProcessPoolExecutor to start function at a separate process. @app.post("/async-endpoint") async def test_endpoint(): loop = asyncio.get_event_loop() with concurrent.futures.ProcessPoolExecutor() as pool: result = await loop.run_in_executor(pool, cpu_bound_func)...
58
123
63,216,201
2020-8-2
https://stackoverflow.com/questions/63216201/how-to-install-python-with-conda
I'm trying to install python 3.9 in a conda enviroment. I tried creating a new conda env using the following command, conda create --name myenv python=3.9 But I got an error saying package not found because python 3.9 is not yet released So, I manually created a folder in envs folder and tried to list all envs. But I ...
To create python 3.11 conda environment use the following command conda create -n py311 python=3.11 py311 - environment name Update 3 To create python 3.10 conda environment use the following command conda create -n py310 python=3.10 py310 - environment name Update 2 You can now directly create python 3.9 environme...
106
122
63,177,681
2020-7-30
https://stackoverflow.com/questions/63177681/is-there-a-difference-between-running-fastapi-from-uvicorn-command-in-dockerfile
I am running a fast api and when i was developing i had the following piece of code in my app.py file code in app.py: import uvicorn if __name__=="__main__": uvicorn.run("app.app:app",host='0.0.0.0', port=4557, reload=True, debug=True, workers=3) so i was about to run CMD ["python3","app.py"] in my Dockerfile. on the ...
Update (on 2022-12-31) As an update from @Marcelo Trylesinski, from uvicorn v 0.19.0, the --debug flag was removed (Ref #1640). No, there is no difference. The commadline run method (uvicorn app.main:app) and executing the app.py using python command (python app.py) are the same. Both methods are calling the uvicorn.m...
42
39
63,174,561
2020-7-30
https://stackoverflow.com/questions/63174561/pip-install-package-from-private-github-repo-with-deploy-key-in-docker
I'm trying to build a Docker container that should install a series of python packages from a requirements.txt file. One of the entries is a python package hosted on a private GitHub repository. To install it, I've created a pair of SSH keys and added the public one as a Deploy Key to the GitHub repository. However, wh...
git@github.com:organization/my-package.git is a valid SSH URL. ssh://git@github.com:organization/my-package.git is not. ssh://git@github.com/organization/my-package.git would be. As in here, you can add GIT_SSH_COMMAND='ssh -v' pip install ... to see exactly what is going on. You might need: git config --global url."ss...
7
6
63,187,644
2020-7-31
https://stackoverflow.com/questions/63187644/import-error-cannot-import-name-ft2font-from-partially-initialized-module-ma
import matplotlib.pyplot as plt output ImportError Traceback (most recent call last) <ipython-input-7-a0d2faabd9e9> in <module> ----> 1 import matplotlib.pyplot as plt ~\AppData\Roaming\Python\Python38\site-packages\matplotlib\__init__.py in <module> 172 173 --> 174 _check_versions() 175 176 ~\AppData\Roaming\Python\P...
As you are on a windows machine, there is a possible duplicate. Navigate by clicking here. This could be an issue regarding matplotlib. A force reinstall over pip would solve the issue. pip install matplotlib --force-reinstall If you are working on Anaconda, launch Anaconda as Administrator, conda install freetype --f...
16
19
63,220,597
2020-8-2
https://stackoverflow.com/questions/63220597/python-in-r-error-could-not-find-a-python-environment-for-usr-bin-python
I don't understand how R handles the Python environment and Python version and keep getting the error Error: could not find a Python environment for /usr/bin/python. I installed Miniconda and created a conda environment in the shell: conda activate r-reticulate Then, in R, I try to install keras (same problem with pac...
Try to follow the guide at https://tensorflow.rstudio.com/installation/: In your R-studio console : install.packages("tensorflow") library(tensorflow) install_tensorflow() If you have not installed Anaconda / Miniconda manually, then at step no. 3, a prompt will ask your permission to install Miniconda. If you alr...
14
26
63,158,424
2020-7-29
https://stackoverflow.com/questions/63158424/why-does-keras-model-fit-with-sample-weight-have-long-initialization-time
I am using keras with a tensorflow (version 2.2.0) backend to train a classifier to distinguish between two datasets, A and B, which I have mixed into a pandas DataFrame object x_train (with two columns), and with labels in a numpy array y_train. I would like to perform sample weighting in order to account for the fact...
The issue is caused by how TensorFlow validates some type of input objects. Such validations, when the data are surely correct, are exclusively a wasted time expenditure (I hope in the future it will be handled better). In order to force TensorFlow to skip such validation procedures, you can trivially wrap the weights ...
7
9
63,218,645
2020-8-2
https://stackoverflow.com/questions/63218645/lowering-the-xtick-label-density-for-a-datetime-axis
Pretty new to python and programming in general so bear with me please. I have a data set imported from a .csv file and I'm trying to plot a column of values (y axis) by date (x axis) over a 1 year period but the problem is that the dates are way too dense and I can't for the life of me figure out how to space them out...
Assumption I suppose you start from a dataframe similar to this one saved in a Vanuatu Earthquakes 2018-2019.csv file : import pandas as pd import numpy as np time = pd.date_range(start = '01-01-2020', end = '31-03-2020', freq = 'D') df = pd.DataFrame({'date': list(map(lambda x: str(x), time)), 'mag': np.random.random(...
7
12