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 |
|---|---|---|---|---|---|---|
68,454,202 | 2021-7-20 | https://stackoverflow.com/questions/68454202/how-to-use-maxlen-of-typing-annotation-of-python-3-9 | I'm aware there's this new typing format Annotated where you can specify some metadata to the entry variables of a function. From the docs, you could specify the maximum length of a incoming list such as: Annotated can be used with nested and generic aliases: T = TypeVar('T') Vec = Annotated[list[tuple[T, T]], MaxL... | As stated by AntiNeutronicPlasma, Maxlen is just an example so you'll need to create it yourself. Here's an example for how to create and parse a custom annotation such as MaxLen to get you started. First, we define the annotation class itself. It's a very simple class, we only need to store the relevant metadata, in t... | 10 | 12 |
68,409,249 | 2021-7-16 | https://stackoverflow.com/questions/68409249/how-to-download-pdf-files-with-playwright-python | I'm trying to automate the download of a PDF file using Playwright, I've the code working with Selenium, but some features in Playwright got my attention. The real problem the documentation isn't helpful. When I click on download I get this: And I cant change the directory of the download, it also delete the "file" wh... | The download.path() in playwright is just a random GUID (globally unique identifier). It's designed to validate the download works - not to keep the file. Playwright is a testing tool and imagine running tests across every major browser on every code change - any downloads would quickly take up a lot of space and it wo... | 12 | 10 |
68,461,155 | 2021-7-20 | https://stackoverflow.com/questions/68461155/different-results-on-anomaly-detection-bettween-pycaret-and-h2o | I'm working on detect anomalies from the following data: It comes from a processed signal of and hydraulic system, from there I know that the dots in the red boxes are anomalies happen when the system fails. I'm using the first 3k records to train a model, both in pycaret and H20. These 3k records covers 5 cycles of d... | TLDR: your problem would be massively simplified by changing the instances to detect anomalies to be cycles, not individual data samples from sensor. The differences between existing applied methods are probably due to differences in hyper-parameters, and the sensitivity to hyperparameters due to the less-than-ideal pr... | 4 | 3 |
68,414,632 | 2021-7-16 | https://stackoverflow.com/questions/68414632/pickle-load-fails-on-protocol-4-objects-from-python-3-7-when-using-python-3-8 | Python changed its pickle protocol to 4 in python 3.4 to 3.7 and again changed it to protocol=5 in python 3.8. How do I open older pickled files in python 3.8? I tried: >>> with open('data_frame_111.pkl','rb') as pfile: ... x1 = pickle.load(pfile) ... Traceback (most recent call last): File "<stdin>", line 2, in <modul... | You need to upgrade to the latest version (1.3.1 worked for me) of pandas. Or, to be more precise, the pandas version when you did pickle.dump(some_path) should be the same pandas version as when you will do pickle.load(some_path). | 13 | 9 |
68,394,091 | 2021-7-15 | https://stackoverflow.com/questions/68394091/fastapi-sqlalchemy-pydantic-%e2%86%92-how-to-process-many-to-many-relations | I have editors and articles. Many editors may be related to many articles and many articles may have many editors at same time. My DB tables are Article id subject text 1 New Year Holidays In this year... etc etc etc Editor id name email 1 John Smith some@email EditorArticleRelation ed... | Not sure if my solution is most effective, but I did it by this way: route (same as in question): ... @app.post("/articles/", response_model=schema.Article) def create_article(article_data: schema.ArticleCreate, db: Session = Depends(get_db)): db_article = crud.get_article_by_name(db, name=article_data.name) if db_ar... | 10 | 6 |
68,446,601 | 2021-7-19 | https://stackoverflow.com/questions/68446601/pandas-class-with-pandas-pipe | @pd.api.extensions.register_dataframe_accessor("data_cleaner") class DataCleaner: def __init__(self, pandas_obj): self._obj = pandas_obj def multiply(self, col): self._obj[col] = self._obj[col] * self._obj[col] return self._obj def square(self, col): self._obj[col] = self._obj[col]**2 return self._obj def add_strings(s... | The question here is that .pipe expects a function that takes a DataFrame, a Series, or a GroupBy object. The documentation is quite clear with regards to that: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pipe.html. On top of that, the DataCleaner.process_all function is not implementing .pipe correct... | 5 | 2 |
68,419,632 | 2021-7-17 | https://stackoverflow.com/questions/68419632/apply-function-only-on-slice-of-array-under-jit | I am using JAX, and I want to perform an operation like @jax.jit def fun(x, index): x[:index] = other_fun(x[:index]) return x This cannot be performed under jit. Is there a way of doing this with jax.ops or jax.lax? I thought of using jax.ops.index_update(x, idx, y) but I cannot find a way of computing y without incur... | The previous answer by @rvinas using dynamic_slice works well if your index is static, but you can also accomplish this with a dynamic index using jnp.where. For example: import jax import jax.numpy as jnp def other_fun(x): return x + 1 @jax.jit def fun(x, index): mask = jnp.arange(x.shape[0]) < index return jnp.where(... | 7 | 7 |
68,460,396 | 2021-7-20 | https://stackoverflow.com/questions/68460396/contractnotfound-no-contract-deployed-at | I have been involved in the chainlink bootcamp and trying to finishing the final 'Exercise 3: Putting it all together'. However, I am stuck running: brownie run scripts/price_exercise_scripts/01_deploy_price_exercise.py --network kovan ContractNotFound: No contract deployed at 0xF4030086511a5bEEa4966F8cA5B36dbC97BeE88... | Problem - I was using the ethereum mainnet address instead of the correct kovan network address for btc / usd price. Changing the btc_usd_price_feed value to 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e in the config.yml fixed this issue for me. price feed addresses | 4 | 3 |
68,460,544 | 2021-7-20 | https://stackoverflow.com/questions/68460544/how-to-add-uirevision-directly-to-figure-in-plotly-dash-for-automatic-updates | I have a Plotly figure built in Python that updates automatically. I want to preserve dashboard zooms even with automatic updates. The documentation in Plotly says this can be done using the layout uirevision field, per the this community writeup. The docs give this as an example of the return dictionary: return { 'da... | Use the figure dictionary, which can be accessed like so: my_figure['layout']['uirevision'] = 'some_value' This can also be used to access other useful aspects of the figure, such as changing the line color of a specific line entry: my_figure['data'][2]['line']['color'] = '#FFFF00' To see the other entry options, pri... | 6 | 2 |
68,453,051 | 2021-7-20 | https://stackoverflow.com/questions/68453051/decode-a-uint8array-into-a-json | I am fetching data from an API in order to show sales and finance reports, but I receive a type gzip file which I managed to convert into a Uint8Array. I'd like to somehow parse-decode this into a JSON file that I can use to access data and create charts in my frontend with. I was trying with different libraries (pako ... | Please visit this answer https://stackoverflow.com/a/12776856/16315663 to retrieve GZIP data from the response. Assuming, You have already retrieved full data as UInt8Array. You just need the UInt8Array as String const jsonString = Buffer.from(dataAsU8Array).toString('utf8') const parsedData = JSON.parse(jsonString) co... | 7 | 14 |
68,455,515 | 2021-7-20 | https://stackoverflow.com/questions/68455515/different-results-in-idle-and-python-shell-using-is | I am exploring python is vs ==, when I was exploring it, I find out if I write following; >>> a = 10.24 >>> b = 10.24 in a python shell and on typing >> a is b, it gives me output as false. But when I write the following code in a python editor and run it I get true. a = 10.24 b = 10.24 print(a is b) Can anyone expla... | You should not rely on is for comparison of values when you want to test equality. The is keyword compares id's of the variables, and checks if they are the same object. This will only work for the range of integers [-5,256] in Python, as these are singletons (these values are cached and referred to, instead of having ... | 5 | 5 |
68,444,252 | 2021-7-19 | https://stackoverflow.com/questions/68444252/multiple-training-with-huggingface-transformers-will-give-exactly-the-same-resul | I have a function that will load a pre-trained model from huggingface and fine-tune it for sentiment analysis then calculates the F1 score and returns the result. The problem is when I call this function multiple times with the exact same arguments, it will give the exact same metric score which is expected, except for... | Sylvain Gugger answered this question here: https://discuss.huggingface.co/t/multiple-training-will-give-exactly-the-same-result-except-for-the-first-time/8493 You need to set the seed before instantiating your model, otherwise the random head is not initialized the same way, that’s why the first run will always be di... | 8 | 16 |
68,436,511 | 2021-7-19 | https://stackoverflow.com/questions/68436511/tabula-py-read-pdf-with-template-method | I am trying to read a particular portion of a document as a table. It is structured as a table but there are no dividing lines between, cells, rows or columns. I had success with using the read_pdf() method with the area and column arguments. I could specify exactly where the table starts and ends and where the columns... | I was just being a dum-dum. Templates are not something that you generate manually. They are supposed to be generated by the tabula app as mentioned here. Just download tabula from the official website. Once you launch the app, it's fairly simple. Manually click and drag on each table on each page and click on the down... | 6 | 10 |
68,449,103 | 2021-7-20 | https://stackoverflow.com/questions/68449103/tf-keras-preprocessing-image-dataset-from-directory-value-error-no-images-found | belos is my code to ensure that the folder has images, but tf.keras.preprocessing.image_dataset_from_directory returns no images found. What did I do wrong? Thanks. DATASET_PATH = pathlib.Path('C:\\Users\\xxx\\Documents\\images') image_count = len(list(DATASET_PATH.glob('.\\*.jpg'))) print(image_count) output = 2715 b... | There are two issues here, firstly image_dataset_from_directory requires subfolders for each of the classes within the directory. This way it can automatically identify and assign class labels to images. So the standard folder structure for TF is: data | |___train | |___class_1 | |___class_2 | |___validation | |___clas... | 6 | 12 |
68,418,727 | 2021-7-17 | https://stackoverflow.com/questions/68418727/pip-install-py-find-1st-fails-on-ubuntu20-centos-with-python3-9 | This is my process. I start a new aws t2.micro ec2 on ubuntu20 and run this script sudo apt-get update sudo apt-get install gcc sudo apt-get install python3.9 sudo apt-get install python3.9-venv curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py > get-pip.py python3.9 get-pip.py sudo apt-get inst... | This seems to be an issue with the module you are trying to install and not the header itself. The py-find-1st is a rather exotic module (9 stars on GitHub at the time of writing) and the build problem of this sort has been already reported. Solutions: Install libpython3.9 sudo apt install libpython3.9-dev Edit: this ... | 5 | 4 |
68,444,765 | 2021-7-19 | https://stackoverflow.com/questions/68444765/why-is-it-not-possible-to-unpack-lists-inside-a-list-comprehension | Starred expressions raise SyntaxError when used in list or generator comprehension. I'm curious about the reason behind this; is it an implementation choice or there are technical constraints that would prevent this operation? I've found a lot about the contexts that don't allow for unpacking iterables but nothing abou... | This was proposed in PEP 448 -- Additional Unpacking Generalizations but ultimately not accepted due to concerns about readability: Earlier iterations of this PEP allowed unpacking operators inside list, set, and dictionary comprehensions as a flattening operator over iterables of containers: [...] This was met with a... | 4 | 7 |
68,444,335 | 2021-7-19 | https://stackoverflow.com/questions/68444335/why-does-print-with-end-doesnt-appear-until-new-line | I have been making a program in python 3.9 and after having this code: #Print 3 dots at the interval shown def dots(t): t *= 3 sleep(t) print('.', end='') sleep(t) print('.', end='') sleep(t) print('.') And this calling it: # These are completely aesthetic sleep(0.25) print("Defining Functions", end='') dots(0.4) I e... | Python buffers output to stdout. This is because writing larger pieces of text at a time is more efficient (less syscalls). By default, if stdout is connected to a terminal, the output will be line-buffered. Thus printing a newline flushes the buffer and you see the output immediately. If stdout is redirected into a pi... | 6 | 13 |
68,439,799 | 2021-7-19 | https://stackoverflow.com/questions/68439799/typeerror-missing-1-required-positional-argument-while-using-pytest-fixture | I have written my test classes in a file and I am trying to use pytest fixtures so that I don't have to create the same input data in each test functions. Below is the minimal working example. import unittest import pytest @pytest.fixture def base_value(): return 5 class Test(unittest.TestCase): def test_add_two(self, ... | This is because you are mixing pytest and unittest. Try @pytest.fixture def base_value(): return 5 class Test: def test_add_two(self, base_value): result = base_value + 2 assert result == 7, "Result doesn't match" And in case of failure the error will be def test_add_two(self, base_value): result = base_value + 2 > as... | 27 | 37 |
68,398,033 | 2021-7-15 | https://stackoverflow.com/questions/68398033/svg-figures-hidden-in-jupyterlab-after-some-time | I recently found I could make all my matplotlib figures with SVG by default in my jupyterlab notebooks with import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_formats = ['svg'] However, if I refresh the page, the figures disappear, leaving behind <Figure size 864x576 with 1 Axes> This eff... | The behaviour looks in line with the security model of Jupyter. Untrusted HTML is always sanitized Untrusted Javascript is never executed HTML and Javascript in Markdown cells are never trusted Outputs generated by the user are trusted Any other HTML or Javascript (in Markdown cells, output generated by others) is ne... | 4 | 7 |
68,432,070 | 2021-7-18 | https://stackoverflow.com/questions/68432070/can-i-distinguish-positional-and-keyword-arguments-from-inside-the-called-functi | I would like to deprecate an old syntax for a function in a Python library. In order to effectively detect whether someone is using the old syntax, I need to know whether an argument is called positionally or through a keyword. Is there a way to detect this? As an example, consider this function: def store(name='', val... | You could add *args to your function's arguments and check if that contains any arguments - if yes, the user passed positional arguments to your function that should have been passed as keyword arguments: def store(*args, name='', value=0): if args: # args is not empty - user passed deprecated positional arguments prin... | 4 | 3 |
68,396,513 | 2021-7-15 | https://stackoverflow.com/questions/68396513/problem-in-lr-find-in-pytorch-fastai-course | While following the Jupyter notebooks for the course I hit upon an error when these lines are run. I know that the cnn_learner line has got no errors whatsoever, The problem lies in the lr_find() part It seems that learn.lr_find() does not want to return two values! Although its documentation says that it returns a tup... | I was having the same problem and I found that the lr_find() output's has updated. You can substitute the second line to lrs = learn.lr_find(suggest_funcs=(minimum, steep, valley, slide)), and then you just substitute where you using lr_min and lr_steep to lrs.minimum and lrs.steep respectively, this should work fine a... | 5 | 12 |
68,427,977 | 2021-7-18 | https://stackoverflow.com/questions/68427977/how-does-the-magic-store-commands-for-dataframe-work | I created two dataframes (df1 and df2) in two jupyter notebooks (N1 and N2) respectively. On day 1, I used the below store command to use the df1 and its variables in N2 jupyter notebook %store -r df1 But on day 25, I created a new jupyter notebook N3 and used the below store command again %store -r df1 And it seemed... | Storemagic is an IPython feature that "Stores variables, aliases and macros in IPython’s database". Because it is an IPython feature rather than exclusive to Jupyter you can store and restore variables across many IPython and Jupyter sessions. In my environment (IPython 7.19.0) the variables get stored in the directory... | 4 | 7 |
68,429,055 | 2021-7-18 | https://stackoverflow.com/questions/68429055/checking-if-a-list-contains-any-one-of-multiple-characters | I'm new to Python. I want to check if the given list A contains any character among ('0', '2', '4', '6', '8') or not, where '0' <= A[i] <= '9'. I can do this as: if not ('0' in A or '2' in A or '4' in A or '6' in A or '8' in A): return False but, is there any shorter way to do this? Thanks. | You can use any with generator expression A = [...] chars = ('0', '2', '4', '6', '8') return any(c in A for c in chars) | 5 | 5 |
68,428,331 | 2021-7-18 | https://stackoverflow.com/questions/68428331/is-validation-split-0-2-in-keras-a-cross-validation | I'm a self-taught Python user. In Python codes, model.fit(x_train, y_train, verbose=1, validation_split=0.2, shuffle=True, epochs=20000) Then, 80% of the data is used for training and 20% is used for validation, and the epoch is repeated 20,000 times for training. And, shuffle=True So, I think this code is a cross-va... | The model first shuffles the data and then splits it to train and validation For the next epoch, the train & validation have already been defined in the first epoch, so it does not shuffle & split again, but uses the previously defined datasets. Therefore, it is a cross-validation. | 7 | 8 |
68,426,892 | 2021-7-18 | https://stackoverflow.com/questions/68426892/why-i-get-this-error-on-python-firebase-admin-initialize-app | when I was trying to connect google firebase real time database, I got this error: ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do wan... | You only need to initialize (create) the app once. When you have created the app, use get_app instead: # The default app's name is "[DEFAULT]" firebase_admin.get_app(name='[DEFAULT]') | 5 | 4 |
68,422,297 | 2021-7-17 | https://stackoverflow.com/questions/68422297/batch-matrix-multiplication-in-numpy | I have two numpy arrays a and b of shape [5, 5, 5] and [5, 5], respectively. For both a and b the first entry in the shape is the batch size. When I perform matrix multiplication option, I get an array of shape [5, 5, 5]. An MWE is as follows. import numpy as np a = np.ones((5, 5, 5)) b = np.random.randint(0, 10, (5, 5... | You can work this out using numpy einsum. c = np.einsum('BNi,Bi ->BN', a, b) Pytorch also provides this einsum function with slight change in syntax. So you can easily work it out. It easily handles other shapes as well. Then you don't have to worry about transpose or squeeze operations. It also saves memory because n... | 5 | 5 |
68,424,586 | 2021-7-17 | https://stackoverflow.com/questions/68424586/set-of-sets-and-in-operator | I was doing some coding exercises and I ended up using a set of frozensets. Here is the code: cities = 4 roads = [[0, 1], [1, 2], [2, 0]] roads = set([frozenset(road) for road in roads]) output = [] for i in range(cities-1): for j in range(i+1, cities): if set([i,j]) not in roads: output.append([i,j]) As you can see, ... | From my reading of the CPython source it appears that the test for contains checks if the key is found in the set; if not, and if the key is a set object, an attempt is made to convert the key to a frozenset, and then that key is tested. The same behavior exists for operations like remove, as seen here: >>> s = set([fr... | 7 | 5 |
68,422,739 | 2021-7-17 | https://stackoverflow.com/questions/68422739/how-to-write-type-hints-for-a-function-returning-itself | from typing import Callable def f() -> Callable: return f How to explicitly define f's type? like Callable[[], Callable] I think it is slightly like a linked list, but I can't implement it. from typing import Union class Node: def __init__(self, val): self.val = val self.next: Union[Node, None] = None | I think @chepner's answer is great. If you really do want to express this as a recursive Callable type, then you could restructure the function as a callable class and do something like this: from __future__ import annotations class F: def __call__(self) -> F: return self f = F() You can test this with mypy to see tha... | 4 | 5 |
68,422,590 | 2021-7-17 | https://stackoverflow.com/questions/68422590/python-get-the-last-element-from-generator-items | I'm super amazed using the generator instead of list. But I can't find any solution for this question. What is the efficient way to get the first and last element from generator items? Because with list we can just do lst[0] and lst[-1] Thanks for the help. I can't provide any codes since it's clearly that's just what ... | You have to iterate through the whole thing. Say you have this generator: def foo(): yield 0 yield 1 yield 2 yield 3 The easiest way to get the first and last value would be to convert the generator into a list. Then access the values using list lookups. data = list(foo()) print(data[0], data[-1]) If you want to avoi... | 5 | 8 |
68,400,851 | 2021-7-15 | https://stackoverflow.com/questions/68400851/how-to-rotate-xtick-label-bar-chart-plotly-express | How can I rotate to 90° the team names (x-axis) on Plotly express? They are not turned in the right way. Here is my code. fig = px.bar(stacked_ratio, y="percent", x="team", color="outcome", color_discrete_map=colors, title="Long-Form Input") fig.show() Here how it looks: | You should be able to update your x-axis from a figure object with the update_xaxes method: fig = px.bar(stacked_ratio, y="percent", x="team", color="outcome", color_discrete_map=colors, title="Long-Form Input") fig.update_xaxes(tickangle=90) fig.show() You can see all options for fig.update_xaxes on the plotly websit... | 19 | 38 |
68,408,552 | 2021-7-16 | https://stackoverflow.com/questions/68408552/how-to-overwrite-a-file-using-google-drive-api-with-python | I want to create a simple script which will upload a file to my Drive every 5 minutes using cronjob. This is the code I have so far using the boilerplate code I extracted from different locations (mainly 2: getting started page & create page): from __future__ import print_function from apiclient import errors import pi... | Your code uses which will create a new file every time. myservice.files().create You need to use File update The only diffrence is you need to pass the file id. file = service.files().update(fileId=file_id, media_body=media_body).execute() | 5 | 8 |
68,402,691 | 2021-7-16 | https://stackoverflow.com/questions/68402691/adding-dropping-column-instance-into-a-pipeline | In general, we will df.drop('column_name', axis=1) to remove a column in a DataFrame. I want to add this transformer into a Pipeline Example: numerical_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='mean')), ('scaler', StandardScaler(with_mean=False)) ]) How can I do it? | You can encapsulate your Pipeline into a ColumnTransformer which allows you to select the data that is processed through the pipeline as follows: import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.impute import SimpleImputer from sklearn.compose import make_column_selector, make_column_tr... | 12 | 4 |
68,396,403 | 2021-7-15 | https://stackoverflow.com/questions/68396403/kernel-density-estimation-using-scipys-gaussian-kde-and-sklearns-kerneldensity | I created some data from two superposed normal distributions and then applied sklearn.neighbors.KernelDensity and scipy.stats.gaussian_kde to estimate the density function. However, using the same bandwith (1.0) and the same kernel, both methods produce a different outcome. Can someone explain me the reason for this? T... | What is meant by bandwidth in scipy.stats.gaussian_kde and sklearn.neighbors.KernelDensity is not the same. Scipy.stats.gaussian_kde uses a bandwidth factor https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html. For a 1-D kernel density estimation the following formula is applied: the bandw... | 6 | 6 |
68,407,112 | 2021-7-16 | https://stackoverflow.com/questions/68407112/merging-dataframes-with-multi-indexes-and-column-value | I have two dataframes with multi indexes and dates as a columns: df1 df1 = pd.DataFrame.from_dict({('group', ''): {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A', 6: 'A', 7: 'A', 8: 'B', 9: 'B', 10: 'B', 11: 'B', 12: 'B', 13: 'B', 14: 'B', 15: 'B', 16: 'C', 17: 'C', 18: 'C', 19: 'C', 20: 'C', 21: 'C', 22: 'C', 23: 'C',... | Create DatetimeIndex in column in df2 first, then unstack and merge by MultiIndexes: f = lambda x: pd.to_datetime(x) df = (df1.merge(df2.rename(columns=f).unstack(), left_index=True, right_index=True) .sort_index(axis=1)) print (df.head()) 2021-06-28 2021-07-05 \ Sales_1 Sales_2 total_orders total_sales Sales_1 group c... | 5 | 4 |
68,407,031 | 2021-7-16 | https://stackoverflow.com/questions/68407031/telethon-cannot-sign-into-accounts-with-two-step-verfication | I'm trying to log into telegram using telethon with a number with two-step verification. I use this code, client = TelegramClient(f'sessions/1', API_ID, API_HASH) client.connect() phone = input('phone ; ') y = client.send_code_request(phone) x = client.sign_in(phone=phone, password=input('password : '), code=input('cod... | You also need to pass the phone_code_hash returned from client.send_code_request(phone). You could try (see the function call of sign_in with phone_code_hash and send_code_request): y = client.send_code_request(phone) client.sign_in(phone=phone, password=input('password : '), code=input('code :'), phone_code_hash=y.pho... | 4 | 4 |
68,381,733 | 2021-7-14 | https://stackoverflow.com/questions/68381733/error-module-keras-optimizers-has-no-attribute-rmsprop | I am running this code below and it returned an error AttributeError: module 'keras.optimizers' has no attribute 'RMSprop'. I download tensorflow using pip install tensorflow. from keras import layers from keras import models model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape... | As you said, you installed tensorflow (which includes keras) via pip install tensorflow, and not keras directly. Installing keras via pip install keras is not recommended anymore (see also the instructions here). This means that keras is available through tensorflow.keras. Instead of importing via from keras import opt... | 11 | 17 |
68,399,161 | 2021-7-15 | https://stackoverflow.com/questions/68399161/why-not-use-runserver-for-production-at-django | Everywhere i see that uWSGI and Gunicorn are recommended for production mode from everyone. However, there is a lot more suffering to operate with it, the python manage.py runserver is more faster, simpler, and the logging is also more visible if something goes wrong. Still, why not recommend the "python manage.py runs... | The runserver management command is optimized for different things from a web-server. Here are some things it does that are great for local development but would add unnecessary overhead in a production environment (source): The development server automatically reloads Python code for each request, as needed When you ... | 8 | 3 |
68,399,376 | 2021-7-15 | https://stackoverflow.com/questions/68399376/add-a-column-in-a-dataframe-with-the-date-of-today-like-the-today-function-in-ex | I have a dataframe df wit lots of coumnns and I would love to add another column with the name date that contains the date of today like in Excel the TODAY function. How can I do this? | Assuming your dataframe is named df, you can use the datetime library: from datetime import datetime df['new_column']= datetime.today().strftime('%Y-%m-%d') @Henry Ecker raised the point that the same is possible in native pandas using pandas.Timestamp.today df['new_column'] = pd.Timestamp.today().strftime('%Y-%m-%d')... | 6 | 10 |
68,385,648 | 2021-7-14 | https://stackoverflow.com/questions/68385648/does-pyspark-support-the-short-circuit-evaluation-of-conditional-statements | I want to create a new boolean column in my dataframe that derives its value from the evaluation of two conditional statements on other columns in the same dataframe: columns = ["id", "color_one", "color_two"] data = spark.createDataFrame([(1, "blue", "red"), (2, "red", None)]).toDF(*columns) data = data.withColumn('is... | I don't think Spark support short-circuit evaluation on conditionals as stated here https://docs.databricks.com/spark/latest/spark-sql/udf-python.html#:~:text=Spark%20SQL%20(including,short-circuiting%E2%80%9D%20semantics.: Spark SQL (including SQL and the DataFrame and Dataset API) does not guarantee the order of eva... | 4 | 9 |
68,386,130 | 2021-7-14 | https://stackoverflow.com/questions/68386130/how-to-type-hint-a-callable-of-a-function-with-default-arguments | I'm trying to Type Hint the function bar, but I got the Too few arguments error when I run mypy. from typing import Callable, Optional def foo(arg: int = 123) -> float: return arg+0.1 def bar(foo: Callable[[int], float], arg: Optional[int] = None) -> float: if arg: return foo(arg) return foo() print(bar(foo)) print(bar... | Define this: class Foo(Protocol): def __call__(self, x: int = ..., /) -> float: ... then type hint foo as Foo instead of Callable[[int], float]. Callback protocols allow you to: define flexible callback types that are hard (or even impossible) to express using the Callable[...] syntax and optional arguments are one ... | 46 | 57 |
68,391,621 | 2021-7-15 | https://stackoverflow.com/questions/68391621/zappa-deploy-fails-with-attributeerror-template-object-has-no-attribute-add | Since a few days ago, zappa deploy fails with the following error (zappa version 0.50.0): Traceback (most recent call last): File "/root/repo/venv/lib/python3.6/site-packages/zappa/cli.py", line 2785, in handle sys.exit(cli.handle()) File "/root/repo/venv/lib/python3.6/site-packages/zappa/cli.py", line 510, in handle s... | Since version 3.0.0, the package troposphere removed the deprecated Template methods (see the changelog). Breaking changes: * Python 3.6+ (Python 2.x and earlier Python 3.x support is now deprecated due to Python EOL) * Remove previously deprecated Template methods. The above issue can be fixed by adding troposphere<... | 12 | 18 |
68,389,791 | 2021-7-15 | https://stackoverflow.com/questions/68389791/how-to-fix-attributeerror-wherenode-object-has-no-attribute-select-format | There are many similar questions on SO, but this specific error message did not turn up in any of my searches: AttributeError: 'WhereNode' object has no attribute 'select_format' This was raised when trying to annotate() a Django queryset with the (boolean) result of a comparison, such as the gt lookup in the followin... | This case can be fixed using the ExpressionWrapper() Score.objects.annotate( positive=ExpressionWrapper(Q(value__gt=0), output_field=BooleanField())) From the docs: ExpressionWrapper is necessary when using arithmetic on F() expressions with different types ... The same apparently holds for Q objects, although I cou... | 7 | 15 |
68,380,572 | 2021-7-14 | https://stackoverflow.com/questions/68380572/displayed-video-in-jupyter-notebook-is-unplayable | I'm trying to embed a video on my local drive in Jupyter Notebook. The file name is "openaigym.video.6.7524.video000000.mp4" and it is in a folder "gym-results". Using the following code produces nothing whatsoever: from IPython.display import Video Video("./gym-results/openaigym.video.4.7524.video000000.mp4",embed =Tr... | First method: it worked with me! Second method: You could try this as well: from ipywidgets import Video Video.from_file("./play_video_test.mp4", width=320, height=320) Third method: you should change the type of the cell from code to Markdown <video controls src="./play_video_test.mp4">animation</video> If all sol... | 8 | 3 |
68,387,192 | 2021-7-15 | https://stackoverflow.com/questions/68387192/what-is-np-uint8 | Is np.uint9 possible? Why use it? red_lower = np.array([136, 87, 111], np.uint9) | https://numpy.org/doc/stable/reference/arrays.scalars.html#unsigned-integer-types class numpy.ubyte[source] Unsigned integer type, compatible with C unsigned char. Character code 'B' Alias on this platform (Linux x86_64) numpy.uint8: 8-bit unsigned integer (0 to 255). Most often this is used for arrays representing im... | 5 | 6 |
68,381,803 | 2021-7-14 | https://stackoverflow.com/questions/68381803/cumulative-sum-but-conditionally-excluding-earlier-rows | I have a DataFrame like this: df = pd.DataFrame({ 'val_a': [3, 3, 3, 2, 2, 2, 1, 1, 1], 'val_b': [3, np.nan, 2, 2, 2, 0, 1, np.nan, 0], 'quantity': [1, 4, 2, 8, 5, 7, 1, 4, 2] }) It looks like this: | | val_a | val_b | quantity | |---:|--------:|--------:|-----------:| | 0 | 3 | 3 | 1 | | 1 | 3 | nan | 4 | | 2 | 3 | 2... | With the help of NumPy: # sum without conditions raw_sum = df.groupby("val_a", sort=False).quantity.sum().cumsum() # comparing each `val_b` against each unique `val_a` via `gt.outer` sub_mask = np.greater.outer(df.val_b.to_numpy(), df.val_a.unique()) # selecting values to subtract from `quantity` and summing per `val_a... | 5 | 2 |
68,380,123 | 2021-7-14 | https://stackoverflow.com/questions/68380123/cythonized-function-with-a-single-positional-argument-is-not-possible-to-call-us | Long story short, I want to cythonize my python code and build .so files to hide it from the customer. Take this simple function: def one_positional_argument(a): print(a) and my setup.py which builds the .so file from setuptools import setup, find_packages from Cython.Build import cythonize setup( name='tmp', version=... | You need the always_allow_keywords compiler directive (https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html#compiler-directives). Not allowing them by default is a deliberate compatibility/speed trade-off. However, in the forthcoming Cython v3 (the alpha version is usable now...) that... | 4 | 8 |
68,379,495 | 2021-7-14 | https://stackoverflow.com/questions/68379495/is-there-a-pyqt5-method-to-convert-a-python-string-to-a-qbytearray | this is probably a very simple question but I haven't been able to find a good answer to it yet. I've found answers for converting QByteArrays into python strings, but not vice versa. Is there a pyqt5 method that allows me to simply convert a python string into a QByteArray (so that it can be sent over a serial connect... | You have to convert the string to bytes: >>> from PyQt5.QtCore import QByteArray >>> s = "hello world" >>> ba = QByteArray(s.encode()) >>> print(ba) b'hello world' | 4 | 8 |
68,375,133 | 2021-7-14 | https://stackoverflow.com/questions/68375133/as-a-pip-install-user-am-i-supposed-to-have-wheel-installed | Consider the usual scenario - I want to create a virtual environment and install some packages. Say python3 -m venv venv source venv/bin/activate pip install databricks-cli During the installation, I get an error Building wheels for collected packages: databricks-cli Building wheel for databricks-cli (setup.py) ... er... | This was a pip bug, and the solution is to upgrade the pip. With the newest version things look fine: (venv) paulius@xps:~/Documents/wheeltest$ pip install databricks-cli Collecting databricks-cli Using cached databricks-cli-0.14.3.tar.gz (54 kB) Collecting click>=6.7 Using cached click-8.0.1-py3-none-any.whl (97 kB) C... | 14 | 4 |
65,550,168 | 2021-1-3 | https://stackoverflow.com/questions/65550168/get-number-of-documents-in-collection-firestore | Is it possible to count how many documents a collection in Firestore has, using python? I just found this code functions.firestore.document('collection/{documentUid}') .onWrite((change, context) => { if (!change.before.exists) { // New document Created : add one to count db.doc(docRef).update({numberOfDocs: FieldValue... | Firestore now has no limited support for aggregation queries. Previous answer below, as this still applies for cases that are not supported. Outside of the built-in count operation, if you want to determine the number of documents, you have two main options: Read all documents, and then count them in the client. Keep... | 8 | 2 |
65,549,855 | 2021-1-3 | https://stackoverflow.com/questions/65549855/openapi-specification-yml-yaml-all-refs-replace-or-expand-to-its-definition | I am looking for some solution or maybe some script that can help me to replace($ref) or expand its definitions within the YML file with schema validation. (For detail please find below example) **Example: Input with $ref ** /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById tags: - pets par... | Here are some tools that can claim to be able dereference internal $refs in addition to external ones. Be aware of potential issues with circular $refs. CLI: https://github.com/APIDevTools/swagger-cli swagger-cli bundle --dereference <file> Redocly OpenAPI CLI redocly bundle --dereferenced --output <outputName> --ex... | 8 | 6 |
65,509,313 | 2020-12-30 | https://stackoverflow.com/questions/65509313/tortoise-orm-filter-with-logical-operators | I have two tables class User(models.Model): id = fields.BigIntField(pk=True) name = CharField(max_length=100) tags: fields.ManyToManyRelation["Tag"] = fields.ManyToManyField( "models.Tag", related_name="users", through="user_tags" ) class Tag(models.Model): id = fields.BigIntField(pk=True) name = fields.CharField(max_l... | Tortoise-ORM provides Q objects for complicated queries with logical operators like |(or) and &(and). Your query could be made like this: u = await User.filter(Q(tags__name="t1") & (Q(tags__value="foo") | Q(tags__value="bar"))).count() | 5 | 9 |
65,515,182 | 2020-12-31 | https://stackoverflow.com/questions/65515182/are-multiple-objectives-possible-or-tools-constraint-programming | I have a problem where I have a set of warehouses with a given production capacity that send some product to a list of customers at a given cost. I'm trying to minimize the total cost of sending the products so that each customer's demand is satisfied. That part is sorted. Now I need to add a new objective (or constrai... | Solve with the first objective, constraint the objective with the solution, hint and solve with the new objective. from ortools.sat.python import cp_model model = cp_model.CpModel() solver = cp_model.CpSolver() x = model.NewIntVar(0, 10, "x") y = model.NewIntVar(0, 10, "y") # Maximize x model.Maximize(x) solver.Solve(m... | 5 | 13 |
65,575,796 | 2021-1-5 | https://stackoverflow.com/questions/65575796/why-does-the-flask-bool-query-parameter-always-evaluate-to-true | I have an odd behavior for one of my endpoints in my Flask application which accepts boolean query parameters. No matter what I pass to it, such as asfsdfd or true or false, it is considered true. Only by leaving it empty does it become false. full_info = request.args.get("fullInfo", default=False, type=bool) if full_i... | The type parameter of request.args.get is not for specifying the value's type, but for specifying a callable: type – A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the default value is returned. It accepts a callable (ex. a function), applies that callable to ... | 24 | 51 |
65,523,844 | 2020-12-31 | https://stackoverflow.com/questions/65523844/colormap-diverging-from-black-instead-of-white | I would like a diverging colormap that has another colour than white (preferably black) as it center color. Neither matplotlib or cmocean seems to have such a colormap. Is my best option to create an own colormap, or are there existing ones? | @JohanC put an obvious answer in their comment and I didn't see it because of the accepted answer which requires a less-known package: Seaborn supports arbitrary diverging palettes with black center hue_neg, hue_pos = 250, 15 cmap = sns.diverging_palette(hue_neg, hue_pos, center="dark", as_cmap=True) | 10 | 1 |
65,549,588 | 2021-1-3 | https://stackoverflow.com/questions/65549588/shap-treeexplainer-for-randomforest-multiclass-what-is-shap-valuesi | I am trying to plot SHAP This is my code rnd_clf is a RandomForestClassifier: import shap explainer = shap.TreeExplainer(rnd_clf) shap_values = explainer.shap_values(X) shap.summary_plot(shap_values[1], X) I understand that shap_values[0] is negative and shap_values[1] is positive. But what about for multiple class Ra... | How do I determine which index of shap_values[i] corresponds to which class of my output? shap_values[i] are SHAP values for i'th class. What is an i'th class is more a question of an encoding schema you use: LabelEncoder, pd.factorize, etc. You may try the following as a clue: from sklearn.preprocessing import Label... | 6 | 11 |
65,512,844 | 2020-12-30 | https://stackoverflow.com/questions/65512844/how-to-generate-apple-authorization-token-client-secret | How can I generate an authorization code/client secret in python for apple sign in and device check? | First of all we need to generate a app specific p8 file (pem formatted private key) do the following for this: go to your apple developer portal, under certificates identifiers & profiles apple => keys click the + sign and create a key with the services you want to use it for then download the p8 file (be cautious n... | 6 | 15 |
65,562,875 | 2021-1-4 | https://stackoverflow.com/questions/65562875/migration-admin-0001-initial-is-applied-before-its-dependency-app-0001-initial-o | I am trying to make custom made user model for my project in Django. My models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(d... | This error will usually happen if you've done your first initial migration without including your custom user model migration file. Exactly as the message says: "admin.0001_initial is applied before its dependency custom_user_app_label.0001_initial on database 'default'" Since beginners will always do their initial m... | 17 | 17 |
65,514,544 | 2020-12-30 | https://stackoverflow.com/questions/65514544/why-do-i-get-an-infinite-while-loop-when-changing-initial-constant-assignment-to | I'm trying to understand the walrus assignment operator. Classic while loop breaks when condition is reassigned to False within the loop. x = True while x: print('hello') x = False Why doesn't this work using the walrus operator? It ignores the reassignment of x producing an infinite loop. while x := True: print('hell... | You seem to be under the impression that that assignment happens once before the loop is entered, but that isn't the case. The reassignment happens before the condition is checked, and that happens on every iteration. x := True will always be true, regardless of any other code, which means the condition will always eva... | 23 | 35 |
65,577,396 | 2021-1-5 | https://stackoverflow.com/questions/65577396/create-random-list-of-given-length-from-a-list-of-strings-in-python | I have a list of strings: lst = ["orange", "yellow", "green"] and I want to randomly repeat the values of strings for a given length. This is my code: import itertools lst = ["orange", "yellow", "green"] list(itertools.chain.from_iterable(itertools.repeat(x, 2) for x in lst)) This implementation repeats but not rando... | You can use a list comprehension: import random lst = ["orange", "yellow", "green"] [lst[random.randrange(len(lst))] for i in range(100)] Explanation: random.randrange(n) returns an integer in the range 0 to n-1 included. the list comprehension repeatedly adds a random element from lst 100 times. change 100 to whatev... | 7 | 5 |
65,568,841 | 2021-1-4 | https://stackoverflow.com/questions/65568841/how-to-make-a-typeddict-with-integer-keys | Is it possible to use an integer key with TypedDict (similar to dict?). Trying a simple example: from typing import TypedDict class Moves(TypedDict): 0: int=1 1: int=2 Throws: SyntaxError: illegal target for annotation It seems as though only Mapping[str, int] is supported but I wanted to confirm. It wasn't specifica... | The intent of TypedDict is explicit in the PEP's abstract (emphasis added): This PEP proposes a type constructor typing.TypedDict to support the use case where a dictionary object has a specific set of string keys, each with a value of a specific type. and given the intended use cases are all annotatable in class syn... | 5 | 5 |
65,528,568 | 2021-1-1 | https://stackoverflow.com/questions/65528568/how-do-i-load-the-celeba-dataset-on-google-colab-using-torch-vision-without-ru | I am following a tutorial on DCGAN. Whenever I try to load the CelebA dataset, torchvision uses up all my run-time's memory(12GB) and the runtime crashes. Am looking for ways on how I can load and apply transformations to the dataset without hogging my run-time's resources. To Reproduce Here is the part of the code tha... | I did not manage to find a solution to the memory problem. However, I came up with a workaround, custom dataset. Here is my implementation: import os import zipfile import gdown import torch from natsort import natsorted from PIL import Image from torch.utils.data import Dataset from torchvision import transforms ## Se... | 7 | 9 |
65,571,729 | 2021-1-5 | https://stackoverflow.com/questions/65571729/hung-cells-running-multiple-jupyter-notebooks-in-parallel-with-papermill | I am trying to run jupyter notebooks in parallel by starting them from another notebook. I'm using papermill to save the output from the notebooks. In my scheduler.ipynb I’m using multiprocessing which is what some people have had success with. I create processes from a base notebook and this seems to always work the 1... | Have you tried using the subprocess module? It seems like a better option for you instead of multiprocessing. It allows you to asynchronously spawn sub-processes that will run in parallel, this can be used to invoke commands and programs as if you were using the shell. I find it really useful to write python scripts in... | 8 | 4 |
65,517,931 | 2020-12-31 | https://stackoverflow.com/questions/65517931/xgboost-not-running-with-callibrated-classifier | I am trying to run XGboost with with calibrated classifier, below is the snippet of code where I am facing the error: from sklearn.calibration import CalibratedClassifierCV from xgboost import XGBClassifier import numpy as np x_train =np.array([1,2,2,3,4,5,6,3,4,10,]).reshape(-1,1) y_train = np.array([1,1,1,1,1,3,3,3,3... | I believe that the problem comes from XGBoost. It's explained here: https://github.com/dmlc/xgboost/pull/6555 XGBoost defined: predict_proba(self, data, ... instead of: predict_proba(self, X, ... And since sklearn 0.24 calls clf.predict_proba(X=X), an exception is thrown. Here is an idea to fix the problem without chan... | 5 | 5 |
65,516,325 | 2020-12-31 | https://stackoverflow.com/questions/65516325/ssl-wrong-version-number-on-python-request | Python version: 3.9.1 I trying to write bot that send requests and it work perfectly fine, the only issue that i have is when i trying to use web debugging programs such as Charles 4.6.1 or Fiddler Everywhere. When I open it to see bot traffic and response form server it crash showing me this error: (Caused by SSLError... | I had the same problem. It's a bug in urllib3. You have to specify your proxy in the request, and change the 'https' value to 'http'. My example: proxies = {'https': 'http://127.0.0.1:8888'} request = r.get('https://www.example.net', verify=False, proxies=proxies) | 32 | 42 |
65,549,053 | 2021-1-3 | https://stackoverflow.com/questions/65549053/typeerror-not-supported-between-instances-of-function-and-str | I have built a sequential model with a customized f1 score metric. I pass this during the compilation of my model and then save it in *.hdf5 format. Whenever I load the model for testing purposes using the custom_objects attribute model = load_model('app/model/test_model.hdf5', custom_objects={'f1':f1}) Keras throws th... | After model.load() if you compile your model again with the custom metric then it should work. Therefore, after loading your model from disk using model = load_model('app/model/test_model.hdf5', custom_objects={'f1':f1}) Make sure to compile it with the metrics of interest model.compile(loss='categorical_crossentropy'... | 12 | 13 |
65,580,466 | 2021-1-5 | https://stackoverflow.com/questions/65580466/merging-multiple-videos-in-a-template-layout-with-python-ffmpeg | I'm currently trying to edit videos with the Python library of FFMPEG. I'm working with multiple file formats, precisely .mp4, .png and text inputs (.txt). The goal is to embed the different video files within a "layout" - for demonstration purposes I tried to design an example picture: The output is supposed to be a ... | I've done it. The code can be used as a command line program or as a module. To find out more about the command line usage, call it with the --help option. For module usage, import the make_video fucntion in your code (or copy-paste it), and pass the appropriate arguments to it. I have included a screenshot of what my ... | 7 | 3 |
65,505,710 | 2020-12-30 | https://stackoverflow.com/questions/65505710/why-is-my-fastapi-or-uvicorn-getting-shutdown | I am trying to run a service that uses simple transformers Roberta model to do classification. the inferencing script/function itself is working as expected when tested. when i include that with fast api its shutting down the server. uvicorn==0.11.8 fastapi==0.61.1 simpletransformers==0.51.6 cmd : uvicorn --host 0.0.0.... | I have solved this issue by starting a process pool using multiprocessing explicitly. from multiprocessing import set_start_method from multiprocessing import Process, Manager try: set_start_method('spawn') except RuntimeError: pass @app.get("/article_classify") def classification(text:str): """function to classify art... | 16 | 4 |
65,557,740 | 2021-1-4 | https://stackoverflow.com/questions/65557740/automatically-wrap-decorate-all-pytest-unit-tests | Let's say I have a very simple logging decorator: from functools import wraps def my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): print(f"{func.__name__} ran with args: {args}, and kwargs: {kwargs}") result = func(*args, **kwargs) return result return wrapper I can add this decorator to every pytest uni... | Provided you can move the logic into a fixture, as stated in the question, you can just use an auto-use fixture defined in the top-level conftest.py. To add the possibility to opt out for some tests, you can define a marker that will be added to the tests that should not use the fixture, and check that marker in the fi... | 8 | 8 |
65,527,354 | 2021-1-1 | https://stackoverflow.com/questions/65527354/cant-scrape-all-the-company-names-from-a-webpage | I'm trying to parse all the company names from this webpage. There are around 2431 companies in there. However, the way I've tried below can fetches me 1000 results. This is what I can see about the number of results in response while going through dev tools: hitsPerPage: 1000 index: "YCCompany_production" nbHits: 2431... | As a workaround you can simulate search using alphabet as a search pattern. Using code below you will get all 2431 companies as dictionary with ID as a key and full company data dictionary as a value. import requests import string params = { 'x-algolia-agent': 'Algolia for JavaScript (3.35.1); Browser; JS Helper (3.1.0... | 10 | 14 |
65,553,722 | 2021-1-3 | https://stackoverflow.com/questions/65553722/no-module-named-delta-tables | I am getting the following error for the code below, please help: from delta.tables import * ModuleNotFoundError: No module named 'delta.tables' INFO SparkContext: Invoking stop() from shutdown hook Here is the code: ''' from pyspark.sql import * if __name__ == "__main__": spark = SparkSession \ .builder \ .appName(... | According to delta package documentation, there is a python file named tables. You should clone the repository and copy the delta folder under python/delta to your site packages path (i.e. ..\python37\Lib\site-packages). then restart python and your code runs without the error. I am using Python3.5.3, pyspark==3.0.1, | 11 | 5 |
65,526,500 | 2021-1-1 | https://stackoverflow.com/questions/65526500/intellisense-vscode-not-showing-parameters-nor-documentation-when-hovering-above | I'm trying to migrate my entire workflow from eclipse and jupyter notebook all over to VS Code. I installed the python extension, which should come with Intellisense, but it only works partly. I get suggestions after typing a period (.), but don't get any information on parameters nor documentation when hovering over w... | You could use the shortcut key "Ctrl+Space" to open the suggested options: In addition, it is recommended that you use the extension "Pylance", which works better with the extension "Python". Update: Currently in VSCode, the "IntelliSense" document content is provided by the Python language service, which is mainly f... | 6 | 5 |
65,507,374 | 2020-12-30 | https://stackoverflow.com/questions/65507374/plotting-a-geopandas-dataframe-using-plotly | I have a geopandas dataframe, which consists of the region name(District), the geometry column, and the amount column. My goal is to plot a choropleth map using the method mentioned below https://plotly.com/python/choropleth-maps/#using-geopandas-data-frames Here’s a snippet of my dataframe I also checked that my colu... | I'll give you the answer to @tgrandje's comment that solved the problem. Thanks to @Poopah and @tgrandje for the opportunity to raise the answer. import pandas as pd import plotly.express as px import geopandas as gpd import pyproj # reading in the shapefile fp = "./data/" map_df = gpd.read_file(fp) map_df.to_crs(pypro... | 20 | 38 |
65,563,332 | 2021-1-4 | https://stackoverflow.com/questions/65563332/vscode-doesnt-see-pyenv-python-interpreters | I installed pyenv-win on my windows machine. It works fine in the command line. I can install python versions, set them as global etc. But My VS Code doesn't see them. It only sees one python interpreter I installed a long time ago when I wasn't using pyenv yet. VScode: pyenv: C:\Users\jbron\cmder λ pyenv versions 3.7... | It is recommended that you try the following: Please check whether the Python environment variable contains your installed Python path: Please reopen VSCode after installation: Update: The environment variable path of "pyenv" I use is: (Under this path, we can find Python 3.6.7 downloaded by pyenv) We can see t... | 6 | 2 |
65,551,736 | 2021-1-3 | https://stackoverflow.com/questions/65551736/python-3-9-scheduling-periodic-calls-of-async-function-with-different-paramete | How to in python 3.9 implement the functionality of calling the async functions with different parameters, by scheduled periods? The functionality should be working on any OS (Linux, Windows, Mac) I have a function fetchOHLCV which downloads market data from exchanges. The function has two input parameters - pair, time... | As a ready-to-use solution, you could use aiocron library. If you are not familiar with cron expression syntax, you can use this online editor to check. Example (this will work on any OS): import asyncio from datetime import datetime import aiocron async def foo(param): print(datetime.now().time(), param) async def mai... | 6 | 4 |
65,579,240 | 2021-1-5 | https://stackoverflow.com/questions/65579240/unittest-mock-pandas-to-csv | mymodule.py def write_df_to_csv(self, df, modified_fn): new_csv = self.path + "/" + modified_fn df.to_csv(new_csv, sep=";", encoding='utf-8', index=False) test_mymodule.py class TestMyModule(unittest.TestCase): def setUp(self): args = parse_args(["-f", "test1"]) self.mm = MyModule(args) self.mm.path = "Random/path" se... | You didn't provide a minimal, reproducible example, so I had to strip some things out to make this work. I suppose you can fill in the missing bits on your own. One problem was with mock.patch("project.mymodule.to_csv", ...) which tries to mock a class named to_csv in the module at the import path project.mymodule. Thi... | 8 | 3 |
65,588,130 | 2021-1-5 | https://stackoverflow.com/questions/65588130/running-a-loop-multiple-lines-in-vs-code-python-debug-console | How do I run a simple loop in VS Code's python debug console? When I try to enter the following: for el in dataset: It gives me the error below. I seem to be able to enter variable names, but not multi-line commands like I can in the normal python REPL. Traceback (most recent call last): File "/home/tensorflow/.local/... | You have 2 options: Write the command in a new editor window, then simply copy and paste the code in the debug console and press Enter Write the command directly in the debug console. When you want to enter a new line, press Shift+Enter. When the command is complete, execute with Enter | 7 | 15 |
65,561,794 | 2021-1-4 | https://stackoverflow.com/questions/65561794/fastai-tabular-model-how-to-get-predictions-for-new-data | I am using kaggle house prices dataset, it is divided into: train and test I built a model with fastai tabular using train set How can I predict values for test data set? I know it sounds easy and most other libs would do it like model.predict(test), but it is not the case here. I have searched fastai forums and SO a... | I found a problem. For future readers - why can't you get get_preds work for new df? (tested on kaggle's house prices advanced) The root of the problem was in categorical nans. If you train your model with one set of cat features, say color = red, green, blue; and your new df has colors: red, green, blue, black - it wi... | 6 | 3 |
65,548,452 | 2021-1-3 | https://stackoverflow.com/questions/65548452/how-to-find-the-common-eigenvectors-of-two-matrices-with-distincts-eigenvalues | I am looking for finding or rather building common eigenvectors matrix X between 2 matrices A and B such as : AX=aX with "a" the diagonal matrix corresponding to the eigenvalues BX=bX with "b" the diagonal matrix corresponding to the eigenvalues where A and B are square and diagonalizable matrices. I took a look in a ... | I don't think there is a built-in facility in Matlab for computing common eigenvalues of two matrices. I'll just outline brute force way and do it in Matlab in order to highlight some of its eigenvector related methods. We will assume the matrices A and B are square and diagonalizable. Outline of steps: Get eigenvecto... | 11 | 5 |
65,582,001 | 2021-1-5 | https://stackoverflow.com/questions/65582001/latin-1-codec-cant-encode-characters | My code works fine for English text, but doesn't work for for Russian search_text. How can I fix it? Error text UnicodeEncodeError: 'latin-1' codec can't encode characters in position 41-46: Body ('Москва') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8. My code import requests... | Try adding this after the line where you create the data variable before you post the request data=data.encode() #will produce bytes object encoded with utf-8 | 17 | 10 |
65,579,151 | 2021-1-5 | https://stackoverflow.com/questions/65579151/how-to-check-if-mypy-type-ignore-comments-are-still-valid-and-required | Imagine we have some giant legacy code base with a lot of files with ignored Mypy warnings: def foobar(): x = some_external_class.some_method()[0] # type: ignore[ignore-some-mypy-warning] Time to go... Some parts of code were changed. Some parts of code is still the same. How to check every "ignore" comment to know: w... | From mypy documentation: --warn-unused-ignores This flag will make mypy report an error whenever your code uses a # type: ignore comment on a line that is not actually generating an error message. | 9 | 17 |
65,580,052 | 2021-1-5 | https://stackoverflow.com/questions/65580052/pandas-does-uppercase-lowercase-mean-anything-in-dtypes | Float32 vs float32? What is the purpose of uppercase vs lowercase dtypes in Pandas? Uppercase seems more error prone: TypeError: object cannot be converted to a FloatingDtype. dtype = { 'doom_float64': 'Float64' , 'radiance_float32': 'Float32' , 'temperature_float': 'float' , 'moonday_int64': 'Int64' , 'month_int32': '... | Yes, see here for example. pandas can represent integer data with possibly missing values using arrays.IntegerArray. This is an extension types implemented within pandas. Or the string alias "Int64" (note the capital "I", to differentiate from NumPy’s 'int64' dtype: Capitalized types are pandas types, while uncapital... | 5 | 8 |
65,531,387 | 2021-1-1 | https://stackoverflow.com/questions/65531387/tortoise-orm-for-python-no-returns-relations-of-entities-pyndantic-fastapi | I was making a sample Fast Api server with Tortoise ORM as an asynchronous orm library, but I just cannot seem to return the relations I have defined. These are my relations: # Category from tortoise.fields.data import DatetimeField from tortoise.models import Model from tortoise.fields import UUIDField, CharField from... | The issue occurs when one try to generate pydantic models before Tortoise ORM is initialised. If you look at basic pydantic example you will see that all pydantic_model_creator are called after Tortoise.init. The obvious solution is to create pydantic models after Tortoise initialisation, like so: await Tortoise.init(... | 9 | 8 |
65,568,789 | 2021-1-4 | https://stackoverflow.com/questions/65568789/pycharm-deletes-quotation-marks-in-paramenter-field | I want to set a parameter for a python script by using the parameter field in PyCharm. My config: But the command in the Run console is: python3 path_to_script.py '{app_id: picoballoon_network, dev_id: ferdinand_8c ... and so on and not: python3 path_to_script.py '{"app_id": "picoballoon_network", "dev_id": "ferdinand... | To avoid the quotation marks being deleted notice the rules to writing parameters that contain quotation marks. Run/Debug Configuration: Python Configuration tab When specifying the script parameters, follow these rules: Use spaces to separate individual script parameters. Script parameters containing spaces should ... | 7 | 5 |
65,571,890 | 2021-1-5 | https://stackoverflow.com/questions/65571890/unzip-to-temp-in-memory-directory-using-python-mkdtemp | I've looked through the examples out there and don't seem to find one that fits. Looking to unzip a file in-memory to a temporary directory using Python mkdtemp(). Something like this feels intuitive, but I can't find the correct syntax: import zipfile import tempfile zf = zipfile.Zipfile('incoming.zip') with tempfile.... | I already mentioned in my comment why the code that you wrote doesn't work. .mkdtemp() returns just a path as a string, but what you really want to have is a context manager. You can easily fix that by using the the correct function .TemporaryDirectory() This function securely creates a temporary directory using the s... | 6 | 12 |
65,571,812 | 2021-1-5 | https://stackoverflow.com/questions/65571812/keep-indices-in-pandas-dataframe-with-a-certain-number-of-non-nan-entires | Lets say I have the following dataframe: df1 = pd.DataFrame(data = [1,np.nan,np.nan,1,1,np.nan,1,1,1], columns = ['X'], index = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']) print(df1) X a 1.0 a NaN a NaN b 1.0 b 1.0 b NaN c 1.0 c 1.0 c 1.0 I want to keep only the indices which have 2 or more non-NaN entries. In this... | Let us try filter out = df.groupby(level=0).filter(lambda x : x.isna().sum()<=1) X b 1.0 b 1.0 b NaN c 1.0 c 1.0 c 1.0 Or we do isin df[df.index.isin(df.isna().sum(level=0).loc[lambda x : x['X']<=1].index)] X b 1.0 b 1.0 b NaN c 1.0 c 1.0 c 1.0 | 7 | 10 |
65,563,922 | 2021-1-4 | https://stackoverflow.com/questions/65563922/how-to-change-subplot-title-after-creation-in-plotly | With matplotlib I could do this: import numpy as np import matplotlib.pyplot as plt fig, axs = plt.subplots(1, 2, figsize=(10, 5)) fig.patch.set_facecolor('white') axs[0].bar(x=[0,1,2], height=[1,2,3]) axs[1].plot(np.random.randint(1, 10, 50)) axs[0].set_title('BARPLOT') axs[1].set_title('WOLOLO') With plotly I know ... | The following code does the trick you want. import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots fig = make_subplots(rows=1, cols=2, subplot_titles=("Plot 1", "Plot 2")) fig.add_trace(go.Bar(y=[1, 2, 3]), row=1, col=1) fig.add_trace(go.Scatter(y=np.random.randint(1, 10, 50)), r... | 12 | 16 |
65,561,498 | 2021-1-4 | https://stackoverflow.com/questions/65561498/docker-sdk-for-python-how-to-build-an-image-with-custom-dockerfile-and-custom-c | I'm trying to replicate this command with the Docker SDK for Python: docker build -f path/to/dockerfile/Dockerfile.name -t image:version path/to/context/. path/to/dockerfile and path/to/context are different paths, ie: /opt/project/dockerfile and /opt/project/src/app/. The directory structure is the following: opt ├──... | I removed custom_context=True, and the problem went away. EDIT: Using your project tree: import docker client = docker.from_env() client.images.build( path = './project/src/app/target/', dockerfile = '../../../Dockerfile/Dockerfile.name', tag='image:version', ) | 6 | 2 |
65,557,258 | 2021-1-4 | https://stackoverflow.com/questions/65557258/typeerror-cant-pickle-coroutine-objects-when-i-am-using-asyncio-loop-run-in-ex | I am referring to this repo to adapt mmaction2 grad-cam demo from short video offline inference to long video online inference. The script is shown below: Note: to make this script can be easily reproduce, i comment out some codes that needs many dependencies. import cv2 import numpy as np import torchvision.transforms... | If you use run_in_executor, target function should not be async. You need to remove async keyword before def inference(). | 7 | 10 |
65,559,556 | 2021-1-4 | https://stackoverflow.com/questions/65559556/sum-negative-row-values-with-previous-rows-pandas | I'm having trouble finding a good way to find all negative entries in a column and move them up the column, summing them up with the existing entry (i.e. subtracting the negative entry from the present entry) until all values are positive. It is important that there are no negative values for the final dataframe & that... | You can try reverse cumsum after creating a group, then mask: s = df['Entries'].gt(0).cumsum() u= df['Entries'][::-1].groupby(s).cumsum().mask(df['Entries'].le(0),0) out = df.assign(New_Entries=u) # you can assign to the original column too. print(out) ID Date Entries New_Entries 0 1 2013 100 100 1 1 2014 0 0 2 1 201... | 5 | 8 |
65,557,061 | 2021-1-4 | https://stackoverflow.com/questions/65557061/why-does-popping-from-the-original-list-make-reversedoriginal-list-empty | I have the following code: s = [1,2,3] t = reversed(s) for i in t: print(i) # output: 3,2,1 If I pop one element from s (original), then the t (reversed) is emptied: s = [1,2,3] t = reversed(s) s.pop() for i in t: print(i) # expected output: 2, 1 # actual output (nothing): Why does this happen? | Taking a look at the cpython code on GitHub, we can get some intuition as to why it no longer works. The iterator that is returned essentially requires knowing the position of the last index and the length of the array. If the size of the array is changed, the iterator will no longer work. Test 1: Increasing the array ... | 32 | 30 |
65,525,189 | 2020-12-31 | https://stackoverflow.com/questions/65525189/python-google-cloud-function-missing-log-entries | I'm experimenting with GCP's cloud functions and python for the first time and wanted to get python's logging integrated sufficiently so that they fit well with GCP's logging infrastructure (specifically so that severity levels are recognized, and ideally execution_ids and trace ids also are included. I've been followi... | Looks like it's a known issue with Cloud Functions running Python 3.8. Here's a similar case currently open on issue tracker. I've now attached this thread to the issue tracker but feel free to comment in there as well. As a current workaround, I suggest that you use Python 3.7 until the issue is resolved. | 6 | 4 |
65,551,469 | 2021-1-3 | https://stackoverflow.com/questions/65551469/operator-index-with-custom-class-instance | I have a simple class below: class MyClass(int): def __index__(self): return 1 According to operator.index documentation: operator.index(a) Return a converted to an integer. Equivalent to a.__index__() But when I use operator.index with MyClass instance, I got 100 instead of 1 (I am getting 1 if I use a.__index__())... | This is because your type is an int subclass. __index__ will not be used because the instance is already an integer. That much is by design, and unlikely to be considered a bug in CPython. PyPy behaves the same. In _operator.c: static PyObject * _operator_index(PyObject *module, PyObject *a) /*[clinic end generated cod... | 7 | 5 |
65,526,149 | 2020-12-31 | https://stackoverflow.com/questions/65526149/pytest-customize-short-test-summary-info-remove-filepath | I'm trying to get more useful output from pytest -tb=no short output. I have integration tests stored in JSON files, so the output all looks extremely similar. tests/test_dit_cli.py .......F............................. [ 29%] ...F...F.FF........F............................F...FFFFFFF [ 75%] FFF.F..................F..... | If you just want to shorten the nodeids in the short summary info, you can overwrite the nodeid attribute of the report object. A simple example: def pytest_runtest_logreport(report): report.nodeid = "..." + report.nodeid[-10:] placed in your conftest.py, will truncate each nodeid to its last ten chars: ==============... | 6 | 8 |
65,548,855 | 2021-1-3 | https://stackoverflow.com/questions/65548855/when-using-f-read-the-iteration-loops-per-letter | I am iterating through my text file, but when I use the read() function, the loop iterates through the letters instead of the sentences. with the following code: for question in questions: # voor elke question moet er door alle lines geiterate worden print(f"Question: {question}") f = open("glad.txt", "r") text = f.rea... | Using text = f.read(), you are getting the whole text file into text. When you iterate over a string in Python, it gives you one character per iteration. Since you want to continue using .read(), use splitlines(): text = f.read().splitlines() Now, text is a list which you can freely iterate the same way you are alread... | 5 | 3 |
65,548,460 | 2021-1-3 | https://stackoverflow.com/questions/65548460/python-how-to-create-an-abc-that-inherits-from-others-abc | I am trying to create a simple abstract base class Abstract that along with its own methods provides the methods of two others abstract base classes: Publisher and Subscriber. When I try to initialize the concrete class Concrete, built on Abstract I get this error: Cannot create a consistent method resolution order (MR... | Abstract classes don't have to have abc.ABC in their list of bases. They have to have abc.ABCMeta (or a descendant) as their metaclass, and they have to have at least one abstract method (or something else that counts, like an abstract property), or they'll be considered concrete. (Publisher has no abstract methods, so... | 7 | 7 |
65,548,403 | 2021-1-3 | https://stackoverflow.com/questions/65548403/filter-elements-from-list-based-on-true-false-from-another-list | Is there an idiomatic way to mask elements of an array in vanilla Python 3? For example: a = [True, False, True, False] b = [2, 3, 5, 7] b[a] I was hoping b[a] would return [2, 5], but I get an error: TypeError: list indices must be integers or slices, not list In R, this works as I expected (using c() instead of []... | You can use itertools.compress: >>> from itertools import compress >>> a = [True, False, True, False] >>> b = [2, 3, 5, 7] >>> list(compress(b, a)) [2, 5] Refer "itertools.compress()" document for more details | 5 | 6 |
65,547,980 | 2021-1-3 | https://stackoverflow.com/questions/65547980/pandas-how-to-set-hour-of-a-datetime-from-another-column | I have a dataframe including a datetime column for date and a column for hour. like this: min hour date 0 0 2020-12-01 1 5 2020-12-02 2 6 2020-12-01 I need a datetime column including both date and hour. like this : min hour date datetime 0 0 2020-12-01 2020-12-01 00:00:00 0 5 2020-12-02 2020-12-02 05:00:00 0 6 2020-1... | You could also try using apply and np.timedelta64: df['datetime'] = df['date'] + df['hour'].apply(lambda x: np.timedelta64(x, 'h')) print(df) Output: min hour date datetime 0 0 0 2020-12-01 2020-12-01 00:00:00 1 1 5 2020-12-02 2020-12-02 05:00:00 2 2 6 2020-12-01 2020-12-01 06:00:00 | 6 | 5 |
65,547,821 | 2021-1-3 | https://stackoverflow.com/questions/65547821/how-to-add-attribute-to-class-in-python | I have: class A: a=1 b=2 I want to make as setattr(A,'c') then all objects that I create it from class A has c attribute. i did not want to use inheritance | There're two ways of setting an attribute to your class; First, by using setattr(class, variable, value) Code Syntax setattr(A,'c', 'c') print(dir(A)) OUTPUT You can see the structure of the class A within attributes ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__ge... | 8 | 8 |
65,523,909 | 2020-12-31 | https://stackoverflow.com/questions/65523909/what-features-of-xgboost-are-affected-by-seed-random-state | The Python API doesn't give much more information other than that the seed= parameter is passed to numpy.random.seed: seed (int) – Seed used to generate the folds (passed to numpy.random.seed). But what features of xgboost use numpy.random.seed? Running xgboost with all default settings still produces the same perfo... | Boosted trees are grown sequentially, with tree growth within one iteration being distributed among threads. To avoid overfitting, randomness is induced through the following params: colsample_bytree colsample_bylevel colsample_bynode subsample (note the *sample* pattern) shuffle in CV folder creation for cross valida... | 11 | 7 |
65,544,645 | 2021-1-2 | https://stackoverflow.com/questions/65544645/print-out-n-elements-of-a-list-each-time-a-function-is-run | I have a list of strings and I need to create a function that prints out n elements of the list each time it is run. For instance: book1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o'] Expected output first time I run the function if n = 5: a b c d e second time: f g h i j I tried this: def print_boo... | I guess you can try the following user function which applied to iterator book def print_book(book): cnt = 0 while cnt < 5: try: print(next(book)) except StopIteration: print("You have reached the end!") break cnt += 1 such that >>> bk1 = iter(book1) >>> print_book(bk1) a b c d e >>> print_book(bk1) f g h i j >>> prin... | 6 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.