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 |
|---|---|---|---|---|---|---|
69,571,919 | 2021-10-14 | https://stackoverflow.com/questions/69571919/heroku-error-while-deploying-error-rpc-failed-http-504-curl-22-the-requested | I had no problems in the past with the deployment to Heroku via HTTP transport, but recently I am unable to deploy. This is the error I am getting: Enumerating objects: 58668, done. Counting objects: 100% (57434/57434), done. Delta compression using up to 16 threads Compressing objects: 100% (16705/16705), done. Writin... | I raised a support ticket to Heroku and the answer was to reset the Git repo heroku plugins:install heroku-repo heroku repo:reset -a <app-name> After I did this, I had no problems with the deployment | 8 | 13 |
69,570,682 | 2021-10-14 | https://stackoverflow.com/questions/69570682/how-to-setup-django-permissions-to-be-specific-to-a-certain-models-instances | Please consider a simple Django app containing a central model called Project. Other resources of this app are always tied to a specific Project. Exemplary code: class Project(models.Model): pass class Page(models.Model): project = models.ForeignKey(Project) I'd like to leverage Django's permission system to set granu... | I wasn't quite happy with the answers that were (thankfully!) proposed because they seemed to introduce overhead, either in complexity or maintenance. For django-guardian in particular I would have needed a way to keep those object-level permissions up-to-date while potentially suffering from (slight) performance loss.... | 9 | 4 |
69,561,572 | 2021-10-13 | https://stackoverflow.com/questions/69561572/sqlalchemy-with-multiple-binds-dynamically-choose-bind-to-query | I have 4 different databases, one for each one of my customers (medical clinics), which all of them have the exact same structure. In my application, I have models such as Patient, Doctor, Appointment, etc. Let's take one of them as an example: class Patient(db.Model): __tablename__ = "patients" id = Column(Integer, pr... | 1. Create tables in all binds Observation: db.create_all() calls self.get_tables_for_bind(). Solution: Override SQLAlchemy get_tables_for_bind() to support '__all__'. class MySQLAlchemy(SQLAlchemy): def get_tables_for_bind(self, bind=None): result = [] for table in self.Model.metadata.tables.values(): # if table.info.g... | 6 | 15 |
69,611,485 | 2021-10-18 | https://stackoverflow.com/questions/69611485/react-to-django-cors-issue | Error Details Two requests have been generating on button click. What did I search so far? Axios blocked by CORS policy with Django REST Framework CORS issue with react and django-rest-framework but to no avail What am I doing? Submitting POST request from react to DJango API Django side settings file CORS_ORIGIN_ALLO... | Below settings work for me CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = [ "127.0.0.1", ] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1", ] CORS_ALLOW_CREDENTIALS = False INSTALLED_APPS = [ ..... "corsheaders" ] MIDDLEWARE = [ ...... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] | 6 | 4 |
69,615,605 | 2021-10-18 | https://stackoverflow.com/questions/69615605/importing-custom-plugins-in-airflow-2-cloud-composer | I have a directory structure as such: airflow_dags ├── dags │ └── hk │ └── hk_dag.py ├── plugins │ └── cse │ └── operators.py │ └── cse_to_bq.py └── test └── dags └── dag_test.py In the GCS bucket created by Cloud Composer, there's a plugin folder where I upload the cse folder. Now in my hk_dag.py file if I import the... | In Airflow 2.0 to import your plugin you just need to do it directly from the operators module. In your case, has to be something like: from operators.cse_to_bq import CSEToBQOperator But before that you have to change your folder structure to: airflow_dags ├── dags │ └── hk │ └── hk_dag.py ├── plugins │ └── operators... | 5 | 6 |
69,636,389 | 2021-10-19 | https://stackoverflow.com/questions/69636389/deduplication-merging-of-mutable-data-in-python | High-level view of the problem I have X sources that contain info about assets (hostname, IPs, MACs, os, etc.) in our environment. The sources contain anywhere from 1500 to 150k entries (at least the ones I use now). My script is supposed to query each of them, gather that data, deduplicate it by merging info about the... | Summary: we define two sketch functions f and g from entries to sets of “sketches” such that two entries e and e′ are similar if and only if f(e) ∩ g(e′) ≠ ∅. Then we can identify merges efficiently (see the algorithm at the end). I’m actually going to define four sketch functions, fos, faddr, gos, and gaddr, from whic... | 5 | 3 |
69,625,550 | 2021-10-19 | https://stackoverflow.com/questions/69625550/skip-the-default-on-onupdate-defined-for-specific-update-queries-in-sqlalchemy | If I have a list of posts, which have created and updated dates with a default attached onupdate callback. Sometimes I need to flag the post, for inappropriate reports or similar actions. I do not want the created and updated dates to be modified. How can I skip the defined onupdate, while making an update action? | SQLAlchemy will apply a default when no value was provided to the INSERT or UPDATE statement for that column however the obvious workaround - explicitly setting the column to its current value - won't work because the session checks whether the value has actually changed, and does not pass a value if it hasn't. Here ... | 6 | 6 |
69,610,572 | 2021-10-18 | https://stackoverflow.com/questions/69610572/how-can-i-solve-the-below-error-while-importing-nltk-package | Screenshot of the error After installing nltk using pip3 install nltk I am unable to import nltk in python shell in macOS File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/__init__.py", line 137, in <module> from nltk.text import * File "/Libra... | Just ran into this, I found that the following fixes it: xcrun codesign --sign - "[YOUR_PATH_TO_DYLIB_HERE]" In my case the error was like so: ImportError: dlopen(/Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so, 2): no suitable image found. Did find: /Users/USER/dev/cr-likes... | 5 | 4 |
69,637,772 | 2021-10-19 | https://stackoverflow.com/questions/69637772/iterate-over-pairs-in-order-of-sum-of-absolute-values | I want to iterate over pairs of integers in order of the sum of their absolute values. The list should look like: (0,0) (-1,0) (0,1) (0,-1) (1,0) (-2,0) (-1,1) (-1,-1) (0,2) (0,-2) (1,1) (1,-1) (2,0) [...] For pairs with the same sum of absolute values I don't mind which order they come in. Ideally I would like to be ... | This seems to do the trick: from itertools import count # Creates infinite iterator def abs_value_pairs(): for absval in count(): # Generate all possible sums of absolute values for a in range(-absval, absval + 1): # Generate all possible first values b = abs(a) - absval # Compute matching second value (arbitrarily do ... | 7 | 9 |
69,626,949 | 2021-10-19 | https://stackoverflow.com/questions/69626949/is-there-a-way-to-improve-the-performance-of-this-fractal-calculation-algorithm | Yesterday I came across the new 3Blue1Brown video about Newton's fractal and I was really mesmerized by his live representation of the fractal. (Here's the video link for anybody interested, it's at 13:40: https://www.youtube.com/watch?v=-RdOwhmqP5s) I wanted to have a go at it myself and tried to code it in python (I ... | I got an improvement (~40% faster) by using single complex (np.complex64) precision. (...) state = np.transpose((np.linspace(c[0] - s/2, c[0] + s/2, n)[:, None] + 1j*np.linspace(c[1] - s/2, c[1] + s/2, n))) state = state.astype(np.complex64) (...) 3Blue1Brown added this link in the description: https://codepen.io/m... | 5 | 2 |
69,625,661 | 2021-10-19 | https://stackoverflow.com/questions/69625661/create-a-3d-surface-plot-in-plotly | I want to create a 3D surface plot in Plotly by reading the data from an external file. Following is the code I am using: import numpy as np import plotly.graph_objects as go import plotly.express as px data = np.genfromtxt('values.dat', dtype=float) # The shape of X, Y and Z is (10,1) X = data[:,0:1] Y = data[:,1:2] ... | From plotly figure reference: The data the describes the coordinates of the surface is set in z. Data in z should be a 2D list. Coordinates in x and y can either be 1D lists or {2D arrays} I have an example data set. It contains three columns (x,y,z). import plotly.graph_objects as go import pandas as pd import numpy a... | 5 | 8 |
69,606,986 | 2021-10-17 | https://stackoverflow.com/questions/69606986/regex-matching-separated-values-for-union-types | I'm trying to match type annotations like int | str, and use regex substitution to replace them with a string Union[int, str]. Desired substitutions (before and after): str|int|bool -> Union[str,int,bool] Optional[int|tuple[str|int]] -> Optional[Union[int,tuple[Union[str,int]]]] dict[str | int, list[B | C | Optional[D... | You can install the PyPi regex module (as re does not support recursion) and use import regex text = "str|int|bool\nOptional[int|tuple[str|int]]\ndict[str | int, list[B | C | Optional[D]]]" rx = r"(\w+\[)(\w+(\[(?:[^][|]++|(?3))*])?(?:\s*\|\s*\w+(\[(?:[^][|]++|(?4))*])?)+)]" n = 1 res = text while n != 0: res, n = rege... | 5 | 1 |
69,623,784 | 2021-10-19 | https://stackoverflow.com/questions/69623784/how-to-set-environment-variable-in-pytest | I have a lamba handler that uses an environment variable. How can I set that value using pytest. I'm getting the error tests/test_kinesis.py:3: in <module> from runner import kinesis runner/kinesis.py:6: in <module> DATA_ENGINEERING_BUCKET = os.environ["BUCKET"] ../../../../../.pyenv/versions/3.8.8/lib/python3.8/os.py:... | You're getting the failure before your monkeypatch is able to run. The loading of the environment variable will happen when the runner module is first imported. If this is a module you own, I'd recommend modifying the code to use a default value if DATA_ENGINEERING_BUCKET isn't set. Then you can modify it's value to wh... | 11 | 11 |
69,618,070 | 2021-10-18 | https://stackoverflow.com/questions/69618070/redefine-method-of-an-object | I've got a class, where a method should only run once. Of course, it could easily be done with artificial has_executed = True/False flag, but why use it, if you can just delete the method itself? python's a duck-typed language, everything is a reference, bla-bla-bla, what can go wrong? At least it was the thought. I co... | It doesn't work because b isn't an attribute belonging to the instance, it belongs to the class. So you can't delete it on the instance because it isn't there to be deleted. >>> a = A() >>> list(a.__dict__) [] >>> list(A.__dict__) ['__module__', 'b', '__dict__', '__weakref__', '__doc__'] When a.b is evaluated, Python ... | 5 | 6 |
69,552,230 | 2021-10-13 | https://stackoverflow.com/questions/69552230/no-logging-on-azure-devops-pipeline | Update: Is it possible to add or change a command that executes a pipeline on Azure DevOps? Running my program locally on Visual Studio Code, I do get outputs. However, running my GitHub origin branch on Azure DevOps does not yield any output. I followed a Stack Overflow answer, which references this solution to a Git... | I think you have fundamentally mixed up some things here: the links you have provided and are following provide guidance on setting up logging in Azure Functions. However, you appear to be talking about logging in Azure Pipelines, which is an entirely different thing. So just to be clear: Azure Pipelines run the build ... | 7 | 2 |
69,615,293 | 2021-10-18 | https://stackoverflow.com/questions/69615293/number-of-digits-after-decimal-point-in-pandas | I have CSV file with data: Number 1.1 2.2 4.1 5.4 9.176 14.54345774 16.25664 If I print to display with pandas I get: df = pd.read_csv('data.csv') print(df) Number 0 1.100000 1 2.200000 2 4.100000 3 5.400000 4 9.176000 5 14.543458 6 16.256640 But if I cut 14.54345774 to 14.543 output is changed: Number 0 1.10000 1 2... | You can use pd.set_option to set the decimal number display precision to e.g. 5 in this case: pd.set_option("display.precision", 5) or use: pd.options.display.float_format = '{:.5f}'.format Result: print(df) # with original value of 14.54345774 Number 0 1.10000 1 2.20000 2 4.10000 3 5.40000 4 9.17600 5 14.54346 6 16.... | 5 | 9 |
69,605,603 | 2021-10-17 | https://stackoverflow.com/questions/69605603/what-should-go-in-my-procfile-for-a-django-application | What should go in my Procfile for a Django application on Heroku? I tried: web: python appname.py because I found an example like that for python apps. Further searching didn't make things any clearer except for that I might need to use gunicorn instead of python. I found various posts suggesting various formats such ... | Heroku's Procfile format is quite simple. As described in the documentation: A Procfile declares its process types on individual lines, each with the following format: <process type>: <command> You can see that there should be a colon after the process type, so the web gunicorn example in your question is not going... | 6 | 1 |
69,605,313 | 2021-10-17 | https://stackoverflow.com/questions/69605313/vs-code-terminal-activate-ps1-cannot-be-loaded-because-running-scripts-is-disa | I created a virtual environment in python, now while activating the same from my command line in vscode I am getting the error PS C:\Users\hpoddar\Desktop\WebDev\ReactComplete\DjangoReact\ArticlesApp\APIProject> ..\venv\scripts\activate ..\venv\scripts\activate : File C:\Users\hpoddar\Desktop\WebDev\ReactComplete\Djang... | A way is changing the terminal in VSCode to Command Prompt instead of PowerShell. Open the drop-down on the right of the terminal and choose Select Default Profile Select Command Prompt from the options. Or, you can also set the execution policy to RemoteSigned or Unrestricted in PowerShell Note: This only affect... | 24 | 70 |
69,583,134 | 2021-10-15 | https://stackoverflow.com/questions/69583134/why-is-there-a-difference-between-0-3-2-and-3-2 | I was figuring out how to do floor/ceiling operations without the math module. I solved this by using floor division //, and found out that the negative "gives the ceiling". So this works: >>> 3//2 1 >>> -3//2 -2 I would like the answer to be positive, so first I tried --3//2, but this gives 1. I inferred this is beca... | Python uses the symbol - as both a unary (-x) and a binary (x-y) operator. These have different operator precedence. In specific, the ordering wrt // is: unary - binary // binary - By introducing a 0 as 0--3//2, the first - is a binary - and is applied last. Without a leading 0 as --3//2, both - are unary and applied... | 63 | 85 |
69,579,950 | 2021-10-15 | https://stackoverflow.com/questions/69579950/vs-code-python-doesnt-recognize-match-statement | When I use a match-case statement in Python in VS Code, it gives red squiggly lines and errors in the "problems" tab: | I got a response from one of the vscode-python devs on GitHub: Unfortunately Jedi (and it's underlying parser, parso) has not added support for the match statement yet. Please consider switching your language server to "Default"/"Pylance" as our Pylance language server already has support. As soon as Jedi makes a ne... | 20 | 22 |
69,596,494 | 2021-10-16 | https://stackoverflow.com/questions/69596494/unable-to-import-freegames-python-package-attributeerror-module-collections | Python version : 3.10 I was trying to install the freegames python package using the following pip command C:\Users\praty>pip install freegames Defaulting to user installation because normal site-packages is not writeable Collecting freegames Downloading freegames-2.3.2-py2.py3-none-any.whl (108 kB) |██████████████████... | For quite some time Sequence was importable from collections: $ python2.7 -c "from collections import Sequence" $ python3.4 -c "from collections import Sequence" $ python3.5 -c "from collections import Sequence" $ python3.6 -c "from collections import Sequence" Starting from Python 3.7 there was a warning the class ha... | 12 | 18 |
69,553,159 | 2021-10-13 | https://stackoverflow.com/questions/69553159/how-to-provide-type-hints-for-argparse-arguments | I would like to get proper linting and type hints by [PyFlakes, Pylint] and mypy. For example, in the following code, we cannot get type error for the last line. We cannot even know if float_input exists. import argparse parser = argparse.ArgumentParser() parser.add_argument('--float_input', type=float) args = parser.p... | You can use typed-argument-parser to provide type hints for your arguments. You can define your arguments in a typesafe manner. from typing import Optional from tap import Tap class FooArgumentParser(Tap): float_input: Optional[float] = None args = FooArgumentParser().parse_args() def int_sum(a: int, b: int): return a ... | 7 | 3 |
69,591,717 | 2021-10-16 | https://stackoverflow.com/questions/69591717/how-is-the-keras-conv1d-input-specified-i-seem-to-be-lacking-a-dimension | My input is a array of 64 integers. model = Sequential() model.add( Input(shape=(68,), name="input")) model.add(Conv1D(64, 2, activation="relu", padding="same", name="convLayer")) I have 10,000 of these arrays in my training set. And I supposed to be specifying this in order for conv1D to work? I am getting the dreade... | Don't let the name confuse you. The layer tf.keras.layers.Conv1D needs the following shape: (time_steps, features). If your dataset is made of 10,000 samples with each sample having 64 values, then your data has the shape (10000, 64), which is not directly applicable to the tf.keras.layers.Conv1D layer. You are missing... | 7 | 13 |
69,564,830 | 2021-10-14 | https://stackoverflow.com/questions/69564830/python-dataclass-setting-default-list-with-values | Can anyone help me fix this error. I just started using dataclass I wanted to put a default value so I can easily call from other function I have this class @dataclass(frozen=True) class MyClass: my_list: list = ["list1", "list2", "list3"] my_list2: list = ["list1", "list2", "list3"] But when i print print(MyClass.my_... | What it means by mutable default is that the lists provided as defaults will be the same individual objects in each instance of the dataclass. This would be confusing because mutating the list in an instance by e.g. appending to it would also append to the list in every other instance. Instead, it wants you to provide ... | 11 | 25 |
69,584,171 | 2021-10-15 | https://stackoverflow.com/questions/69584171/is-there-a-way-to-dynamically-change-a-plotly-animation-axis-scale-per-frame | I have an animated plotly scatter graph which plots x,y coordinates normally within the 0-0.5 range with date/time being the frame key. Sometime however I will have to handle anomalous data points which will be well out with this range. I would like the graph to be able to dynamically scale so that the points are not l... | As pointed out in the comments, there is a way to change a plotly animation axis scale per frame. The question remains how dynamic it's possible to make it. But if we can say that you've made a few calculations that will let you know which frames you'd like to adjust the ranges for, then a combination of a dict like yr... | 5 | 3 |
69,590,754 | 2021-10-15 | https://stackoverflow.com/questions/69590754/nattype-object-has-no-attribute-isna | I am trying to create a new column 'Var' in the following Pandas DataFrame based on values from the other columns. I am encountering issues when dealing with the NaN, NaT. Data: ( Used apply(pd.to_datetime) on the Date columns at a previous step) Date C A Age 2017-12-13 1233.0 N 9 NaT NaN N 5 2007-09-24 49.... | "NaT" (for date/time types) and "NaN" are not the same. However, you can use the "isnull" function for both types: elif pd.isnull(Flat['Data']): | 7 | 8 |
69,564,817 | 2021-10-14 | https://stackoverflow.com/questions/69564817/typeerror-load-missing-1-required-positional-argument-loader-in-google-col | I am trying to do a regular import in Google Colab. This import worked up until now. If I try: import plotly.express as px or import pingouin as pg I get an error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-19-86e89bd44552> in... | Found the problem. I was installing pandas_profiling, and this package updated pyyaml to version 6.0 which is not compatible with the current way Google Colab imports packages. So just reverting back to pyyaml version 5.4.1 solved the problem. For more information check versions of pyyaml here. See this issue and forma... | 73 | 57 |
69,584,027 | 2021-10-15 | https://stackoverflow.com/questions/69584027/why-is-np-sumrangen-very-slow | I saw a video about speed of loops in python, where it was explained that doing sum(range(N)) is much faster than manually looping through range and adding the variables together, since the former runs in C due to built-in functions being used, while in the latter the summation is done in (slow) python. I was curious w... | np.sum(range(N)) is slow mostly because the current Numpy implementation do not use enough informations about the exact type/content of the values provided by the generator range(N). The heart of the general problem is inherently due to dynamic typing of Python and big integers although Numpy could optimize this specif... | 30 | 18 |
69,585,800 | 2021-10-15 | https://stackoverflow.com/questions/69585800/what-is-the-fundamental-difference-between-tar-unix-and-tarfile-python | What is the fundamental difference between tarring a folder using tar on Unix and tarfile in Python that results in a different file size? In the example below, there is an 8.2 MB difference. I'm currently using a Mac. The folder in this example contains a bunch of random text files for testing purposes. tar -cvf archi... | Interesting question. The documentation of tarfile (https://docs.python.org/3/library/tarfile.html) mentions that the default format for tar archive created by tarfile is, since python 3.8, PAX_FORMAT whereas archives created by the tar command have the GNU format which I believe explains the difference. Now to produce... | 6 | 7 |
69,580,833 | 2021-10-15 | https://stackoverflow.com/questions/69580833/fastest-way-to-move-objects-within-an-s3-bucket-using-boto3 | I need to copy all files from one prefix in S3 to another prefix within the same bucket. My solution is something like: file_list = [List of files in first prefix] for file in file_list: copy_source = {'Bucket': my_bucket, 'Key': file} s3_client.copy(copy_source, my_bucket, new_prefix) However I am only moving 200 tin... | I would do it in parallel. For example: from multiprocessing import Pool file_list = [List of files in first prefix] print(objects_to_download) def s3_coppier(s3_file): copy_source = {'Bucket': my_bucket, 'Key': s3_file} s3_client.copy(copy_source, my_bucket, new_prefix) # copy 5 objects at the same time with Pool(5) a... | 6 | 6 |
69,577,782 | 2021-10-14 | https://stackoverflow.com/questions/69577782/how-does-python-3-10-match-compares-1-and-true | PEP 622, Literal Patterns says the following: Note that because equality (__eq__) is used, and the equivalency between Booleans and the integers 0 and 1, there is no practical difference between the following two: case True: ... case 1: ... and True.__eq__(1) and (1).__eq__(True) both returns True, but when I run th... | Looking at the pattern matching specification, this falls under a "literal pattern": A literal pattern succeeds if the subject value compares equal to the value expressed by the literal, using the following comparisons rules: Numbers and strings are compared using the == operator. The singleton literals None, True an... | 7 | 10 |
69,575,019 | 2021-10-14 | https://stackoverflow.com/questions/69575019/overloading-operators-using-getattr-in-python | I am trying to overload several operators at once using the __getattr__ function. In my code, if I call foo.__add__(other) it works as expected, but when I try foo + bar, it does not. Here is a minimal example: class Foo(): def add(self, other): return 1 + other def sub(self, other): return 1 - other def __getattr__(se... | This is happening because python operators use an optimization to look up the function implementing the operator. The following lines are roughly equivalent: foo + 1 type(foo).__add__(foo, 1) Operators are found specifically on the class object only, never on the instance. bar.__add__(1) calls __getattr__ to find the ... | 6 | 7 |
69,551,066 | 2021-10-13 | https://stackoverflow.com/questions/69551066/add-xll-as-addin-to-excel | I got a .xll file that I can easily add to excel by doing this: Options > Addins > Browse > double click .xll file It gets imported + activated (and it remains in my excel addins every time I close and open Excel). This is the manual way I try to replace with a script. PowerShell $excel=New-Object -ComObject excel.appl... | Thanks to the link Charles Williams gave me, I was able to do it a little bit different. You can easily create a registry key to let excel know that it should run the .xll-file. # initializing new variables $req_path = Get-Item -Path Registry::HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Options | Select-Obje... | 5 | 1 |
69,561,458 | 2021-10-13 | https://stackoverflow.com/questions/69561458/how-to-check-type-of-files-using-the-header-file-signature-magic-numbers | By entering the file with its extension, my code succeeds to detect the type of the file from the "magic number". magic_numbers = {'png': bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]), 'jpg': bytes([0xFF, 0xD8, 0xFF, 0xE0]), #*********************# 'doc': bytes([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]... | You most like just want to iterate over the loop and test them all. You may be able to optimize or provide some error checking by using the extension as well. If you strip off the extension and check that first, you'll be successful most of the time, and if not you may not want to accept "baby.png" as an xlsx file. Tha... | 6 | 4 |
69,555,581 | 2021-10-13 | https://stackoverflow.com/questions/69555581/python-string-split-by-separator-all-possible-permutations | This might be heavily related to similar questions as Python 3.3: Split string and create all combinations , but I can't infer a pythonic solution out of this. Question is: Let there be a str such as 'hi|guys|whats|app', and I need all permutations of splitting that str by a separator. Example: #splitting only once ['h... | An approach, once you have split the string is to use itertools.combinations to define the split points in the list, the other positions should be fused again. def lst_merge(lst, positions, sep='|'): '''merges a list on points other than positions''' '''A, B, C, D and 0, 1 -> A, B, C|D''' a = -1 out = [] for b in list(... | 5 | 1 |
69,551,065 | 2021-10-13 | https://stackoverflow.com/questions/69551065/setup-with-submodules-dependencies | We have a python package which is also a git repo. It depends on other python packages, themselves git repos. We made the latter git submodules of the former. None of these are public, so no PyPI. None of the other questions related to installing with submodule dependencies match our pattern. My question is not about f... | You will need to specify where to install the submodule from. install_requires=[ 'SQLAlchemy', 'pandas', # Your private repository module '<dependency_name> @ git+ssh://git@github.com/<user_name>/<repo_name>@<branch>' ] | 5 | 2 |
69,541,613 | 2021-10-12 | https://stackoverflow.com/questions/69541613/how-to-json-serialize-enum-classes-in-pydantic-basemodel | I have the following code that uses Pydantic BaseModel data class from enum import Enum import requests from pydantic import BaseModel from requests import Response class PetType(Enum): DOG: str = 'dog' CAT: str = 'cat' class Pet(BaseModel): name: str type: PetType my_dog: Pet = Pet(name='Lucky', type=PetType.DOG) # Th... | **<---- Addition 2 ----> ** Check types like https://docs.python.org/3/library/enum.html#enum.StrEnum and https://docs.python.org/3.12/library/enum.html#enum.IntEnum Instead of MyEnum(str, Enum) use MyEnum(StrENum) **<---- Addition ----> ** Look for Pydantic's parameter "use_enum_values" in Pydantic Model Config use_en... | 9 | 18 |
69,506,719 | 2021-10-9 | https://stackoverflow.com/questions/69506719/dealing-with-0000-in-datetime-format | How do you convert a column of dates of the form "2020-06-30 15:20:13.078196+00:00" to datetime in pandas? This is what I have done: pd.concat([df, df.date_string.apply(lambda s: pd.Series({'date':datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')}))], axis=1) pd.concat([df, df.file_created.apply(lambda s: pd.Series({'dat... | +00:00 is a UTC offset of zero hours, thus can be interpreted as UTC. The easiest thing to do is let pd.to_datetime auto-infer the format. That works very well for standard formats like this (ISO 8601): import pandas as pd dti = pd.to_datetime(["2020-06-30 15:20:13.078196+00:00"]) print(dti) # DatetimeIndex(['2020-06-3... | 6 | 8 |
69,475,317 | 2021-10-7 | https://stackoverflow.com/questions/69475317/how-to-setup-netbeans-ide-for-python-development | I was using PyDev plugin in eclipse for developing python. But now I switched to NetBeans IDE 12.6 and I searched google for finding python plugins for NetBeans. I found a plugin called nbpython. But it is for NetBeans 8.1 and I am using NetBeans 12.6. So is there any plugin for NetBeans IDE 12.6 for developing Python ... | The new plugin for python is netbeansPython: https://plugins.netbeans.apache.org/catalogue/?id=89 https://github.com/albilu/netbeansPython | 6 | 4 |
69,504,352 | 2021-10-9 | https://stackoverflow.com/questions/69504352/fastapi-get-request-results-in-typeerror-value-is-not-a-valid-dict | this is my database schema. I defined my Schema like this: from pydantic import BaseModel class Userattribute(BaseModel): name: str value: str user_id: str id: str This is my model: class Userattribute(Base): __tablename__ = "user_attribute" name = Column(String) value = Column(String) user_id = Column(String) id = C... | Pydantic 2 changed how models gets configured, so if you're using the most recent version of Pydantic, see the section named Pydantic 2 below. SQLAlchemy does not return a dictionary, which is what pydantic expects by default. You can configure your model to also support loading from standard orm parameters (i.e. attri... | 34 | 81 |
69,546,459 | 2021-10-12 | https://stackoverflow.com/questions/69546459/convert-hydra-omegaconf-config-to-python-nested-dict-list | I'd like to convert a OmegaConf/Hydra config to a nested dictionary/list. How can I do this? | See OmegaConf.to_container(). Usage snippet: >>> conf = OmegaConf.create({"foo": "bar", "foo2": "${foo}"}) >>> assert type(conf) == DictConfig >>> primitive = OmegaConf.to_container(conf) >>> show(primitive) type: dict, value: {'foo': 'bar', 'foo2': '${foo}'} >>> resolved = OmegaConf.to_container(conf, resolve=True) >>... | 21 | 35 |
69,490,450 | 2021-10-8 | https://stackoverflow.com/questions/69490450/objectnotexecutableerror-when-executing-any-sql-query-using-asyncengine | I'm using async_engine. When I try to execute anything: async with self.async_engine.connect() as con: query = "SELECT id, name FROM item LIMIT 50;" result = await con.execute(f"{query}") I'm getting: Exception has occurred: ObjectNotExecutableError Not an executable object: 'SELECT id, name FROM item LIMIT 50;' Thi... | As the exception message suggests, the str 'SELECT id, name FROM item LIMIT 50;' is not an executable object. To make it executable, wrap it with sqlalchemy.text. from sqlalchemy import text async with self.async_engine.connect() as con: query = "SELECT id, name FROM item LIMIT 50;" result = await con.execute(text(quer... | 61 | 148 |
69,544,658 | 2021-10-12 | https://stackoverflow.com/questions/69544658/how-to-build-a-self-referencing-model-in-pydantic-with-dataclasses | I am building an API using FastAPI and pydantic. As I follow DDD / clean architecture, which separates the definition of the model from the definition of the persistence layer, I use standard lib dataclasses in my model and then map them to SQLAlchemy tables using imperative mapping (ie. classical mapping). This works ... | It seems there are no easy solution to build a REST API with FastAPI, self-referencing objects and SQLAlchemy imperative mapping. I have decided to switch to the FastAPI / GraphQL stack, with the Strawberry library which is explicitly recommended in the FastAPI documentation. No problem so far, Strawberry makes it easy... | 12 | 4 |
69,542,217 | 2021-10-12 | https://stackoverflow.com/questions/69542217/how-to-disable-server-exceptions-on-fast-api-when-testing-with-httpx-asyncclient | We have a FastApi app and using httpx AsyncClient for testing purposes. We are experiencing a problem where the unit tests run locally fine but fail on the CI server (Github Actions). After further research we have come across this proposed solution by setting raise_server_exceptions=False to False. client = TestClient... | The problem is caused by FastApi version. You can use fastapi==0.65.0 and even without the ASGITransport object and the raise_app_exceptions=False flag you will be able to run the tests which are checking for custom exception raising. Also the fastapi version should be frozen in the requirements file. You can read more... | 9 | 2 |
69,513,799 | 2021-10-10 | https://stackoverflow.com/questions/69513799/pandas-read-csv-the-error-bad-lines-argument-has-been-deprecated-and-will-be-re | I am trying to read some data which may sometimes have erroneous and bad rows, so as always I passed error_bad_lines=False but the console keeps throwing the deprecation warning on every run. Why is this feature deprecated and is there any other alternative for skipping bad lines? | Read the documentation: Deprecated since version 1.3.0: The on_bad_lines parameter should be used instead to specify behavior upon encountering a bad line instead. So, replace: df = pd.read_csv(..., error_bad_lines=False) with: df = pd.read_csv(..., on_bad_lines='skip') | 26 | 52 |
69,464,512 | 2021-10-6 | https://stackoverflow.com/questions/69464512/django-rest-error-attributeerror-module-collections-has-no-attribute-mutab | I'm build Django app, and it's work fine on my machine, but when I run inside docker container it's rest framework keep crashing, but when I comment any connection with rest framework it's work fine. My machine: Kali Linux 2021.3 docker machine: Raspberry Pi 4 4gb docker container image: python:rc-alpine3.14 python ve... | You can downgrade your Python version. That should solve your problem; if not, use collections.abc.Mapping instead of the deprecated collections.Mapping. Refer here: Link | 9 | 8 |
69,482,678 | 2021-10-7 | https://stackoverflow.com/questions/69482678/specnotfound-invalid-name-try-the-format-user-package-in-creating-new-conda | I'm trying to Create New conda environment by 'Anaconda Prompt' usnig yml File in Windows 10. So here is the steps i made through: 1. using cd command i changed the directory to dir which my yml file located. (suppose my yml file is in c:/Users/<USER NAME>/.jupyter ) 2. Then i used conda env create -f Python 310.yml co... | issue solved by changing contents of Python 310.yml and renaming yml file to Python310.yml. Here is the final .yml file content: name: Python3.9 channels: - defaults dependencies: - numpy - pandas - matplotlib - pip - python=3.9.* - python-dateutil - pytz - scikit-learn - scipy - statsmodels - xlrd - openpyxl - lxml - ... | 27 | 4 |
69,534,651 | 2021-10-12 | https://stackoverflow.com/questions/69534651/disable-python-auto-concatenate-strings-across-lines | I was creating a long list of strings like this: tlds = [ 'com', 'net', 'org' 'edu', 'gov', ... ] I missed a comma after 'org'. Python automatically concatenated it with the string in the next line, into 'orgedu'. This became a bug very hard to identify. There are already many ways to define multi-line strings, some v... | The right Platonic thing to do is to modify the linter. But I think life is too short to do so, in addition to the fact that if the next coder does not know about your modified linter, his/her life would be a living hell. There should not be shame in ensuring that the input, even if hardcoded, is valid. If it was for m... | 13 | 1 |
69,485,319 | 2021-10-7 | https://stackoverflow.com/questions/69485319/starting-django-with-docker-unexpected-character | I'm trying to start up this Project on my Mac https://github.com/realsuayip/django-sozluk It works on my Windows machine, but I got this Error on my Mac: unexpected character "." in variable name near "127.0.0.1 192.168.2.253\nDJANGO_SETTINGS_MODULE=djdict.settings_prod\n\n\nSQL_ENGINE=django.db.backends.postgresql\nS... | (Sorry about the answer - I don't yet have the rep to comment) Just want to add a note on to the answer by D.Mo - I had the same error this morning, and adding quotes around the values in my .env file did seem to resolve the issue. Though I then noticed that in the documentation for these env files, Docker mentions Th... | 11 | 2 |
69,477,169 | 2021-10-7 | https://stackoverflow.com/questions/69477169/how-to-randomly-set-inputs-to-zero-in-keras-during-training-autoencoder-callbac | I am training 2 autoencoders with 2 separate input paths jointly and I would like to randomly set one of the input paths to zero. I use tensorflow with keras backend (functional API). I am computing a joint loss (sum of two losses) for backpropagation. A -> A' & B ->B' loss => l2(A,A')+l2(B,B') networks taking A and B ... | Maybe try the following: import random def decision(probability): return random.random() < probability Define a method that makes a random decision based on a certain probability x and make your loss calculation depend on this decision. if current_epoch == random.choice(epochs): keep_mask = tf.ones_like(A.input, dtype... | 5 | 5 |
69,476,935 | 2021-10-7 | https://stackoverflow.com/questions/69476935/how-to-remove-parent-json-element-in-python3-if-child-is-object-is-empty | I'm trying to move data from SQL to Mongo. Here is a challenge I'm facing, if any child object is empty I want to remove parent element. I want till insurance field to be removed. Here is what I tried: def remove_empty_elements(jsonData): if(isinstance(jsonData, list) or isinstance(jsonData,dict)): for elem in list(jso... | Your if statements are kind of confusing. I think you are looking for a recursion: import json # define which elements you want to remove: to_be_deleted = [[], {}, "", None] def remove_empty_elements(jsonData): if isinstance(jsonData, list): jsonData = [new_elem for elem in jsonData if (new_elem := remove_empty_element... | 5 | 2 |
69,482,632 | 2021-10-7 | https://stackoverflow.com/questions/69482632/recover-from-pendingrollbackerror-and-allow-subsequent-queries | We have a pyramid web application. We use SQLAlchemy@1.4 with Zope transactions. In our application, it is possible for an error to occur during flush as described here which causes any subsequent usage of the SQLAlchemy session to throw a PendingRollbackError. The error which occurs during a flush is unintentional (... | Instead of trying to execute your query, just try to get the connection: def exception_handling_view(): try: _ = session.connection() except PendingRollbackError: session.rollback() session.query(...) session.rollback() only rolls back the innermost transaction, as is usually expected — assuming nested transactions ar... | 5 | 8 |
69,507,269 | 2021-10-9 | https://stackoverflow.com/questions/69507269/why-cant-add-file-handler-with-the-form-of-self-fh-in-the-init-method | os and python info: uname -a Linux debian 5.10.0-8-amd64 #1 SMP Debian 5.10.46-4 (2021-08-03) x86_64 GNU/Linux python3 --version Python 3.9.2 Here is a simple class which can start multiprocessing. from multiprocessing.pool import Pool class my_mp(object): def __init__(self): self.process_num = 3 fh = open('test.txt',... | The problem: Stdlib multiprocessing uses pickle to serialize objects. Anything which needs to be sent across the process boundary needs to be picklable. Custom class instances are generally picklable, as long as all their attributes are picklable - it works by importing the type within the subprocess and unpickling the... | 6 | 3 |
69,517,460 | 2021-10-10 | https://stackoverflow.com/questions/69517460/bert-get-sentence-embedding | I am replicating code from this page. I have downloaded the BERT model to my local system and getting sentence embedding. I have around 500,000 sentences for which I need sentence embedding and it is taking a lot of time. Is there a way to expedite the process? Would sending batches of sentences rather than one senten... | About your original question: there is not much you can do. BERT is pretty computationally demanding algorithm. Your best shot is to use BertTokenizerFast instead of the regular BertTokenizer. The "fast" version is much more efficient and you will see the difference for large amounts of text. Saying that, I have to war... | 6 | 2 |
69,468,552 | 2021-10-6 | https://stackoverflow.com/questions/69468552/efficiency-of-sorting-by-multiple-keys-in-python | I have a list of strings that I want to sort by two custom key functions in Python 3.6. Comparing the multi-sort approach (sorting by the lesser key then by the major key) to the multi-key approach (taking the key as the tuple (major_key, lesser_key)), I could see the latter being more than 2x slower than the former, w... | Here's a third way to time: start = time() l3 = sorted(lst, key=lambda x: (''.join(sorted(x)) + "/" + x[::2])) t3 = time() - start and expanding the last line to assert l1 == l2 == l3 This uses a single string as the key, but combining the two string keys you view as as being the "primary" and "secondary" keys. Note ... | 8 | 5 |
69,518,429 | 2021-10-10 | https://stackoverflow.com/questions/69518429/opencv-videocapture-returns-strange-frame-offset-for-different-versions | I'm using opencv-python and when I execute the following code: index = 0 cap = cv2.VideoCapture(video_path) while True: offset = cap.get(cv2.CAP_PROP_POS_MSEC) print(cv2.__version__, index, offset) ok, frame = cap.read() if not ok: break index += 1 I get the following output: 3.4.7 0 0.0 3.4.7 1 33.36666666666667 3.4.... | I read the OpenCV docs and they said: "Reading / writing properties involves many layers. Some unexpected result might happens along this chain. Effective behaviour depends from device hardware, driver and API Backend." (source: https://docs.opencv.org/3.4.15/d4/d15/group__videoio__flags__base.html#gaeb8dd9c89c10a5c63c... | 9 | 5 |
69,525,290 | 2021-10-11 | https://stackoverflow.com/questions/69525290/python-function-to-find-the-numeric-volume-integral | Goal I would like to compute the 3D volume integral of a numeric scalar field. Code For this post, I will use an example of which the integral can be exactly computed. I have therefore chosen the following function: In Python, I define the function, and a set of points in 3D, and then generate the discrete values at t... | A nice way to go about this would be using scipy's tplquad integration. However, to use that, we need a function and not a cloud point. An easy way around that is to use an interpolator, to get a function approximating our cloud point - we can for example use scipy's RegularGridInterpolator if the data is on a regular ... | 15 | 9 |
69,514,660 | 2021-10-10 | https://stackoverflow.com/questions/69514660/using-assignment-as-operator | Consider: course_db = Course(title='Databases') course_db.save() Coming from a C++ background, I would expect (course_db = Course(title='Databases')) to behave like it would in C++, that is, assign Course(title='Databases') to course_db and return the assigned object so that I can use it as part of a larger expression... | You should do some more research about the differences between statements and expressions in Python. If you are using Python 3.8+, you can use the := operator: In [1]: class A: ...: def save(self): ...: return 1 ...: In [2]: (a := A()).save() Out[2]: 1 In [3]: a Out[3]: <__main__.A at 0x7f074e2ddaf0> | 6 | 6 |
69,546,268 | 2021-10-12 | https://stackoverflow.com/questions/69546268/pandas-group-cumsum-with-condition | I have the following df: df = pd.DataFrame({"values":[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],"signal":['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]}) df values signal 0 1 L_exit 1 5 None 2 7 None 3 3 R_entry 4 0 R_exit... | You can first create a mask to get the contiguous R_entries up to reaching to L_exit. Then get the first R_entry per group (by comparing to the next value) and apply a cumsum. # keep only 'R_entry'/'L_exit' and get groups mask = df['signal'].where(df['signal'].isin(['R_entry', 'L_exit'])).ffill().eq('R_entry') # get gr... | 5 | 2 |
69,541,296 | 2021-10-12 | https://stackoverflow.com/questions/69541296/pd-read-csv-ignore-comma-if-it-is-inside-parenthesis | I have a very simple file: [Name] Streamline 1 [Data] X [ m ], Y [ m ], Z [ m ], Velocity [ m s^-1 ] 2.66747564e-01, 0.00000000e+00, 2.03140453e-01, (0.00000000e+00, 8.17744827e+00, 0.00000000e+00) 2.66958952e-01, 0.00000000e+00, 2.07407191e-01, (0.00000000e+00, 6.77392197e+00, 0.00000000e+00) 2.63460875e-01, 0.0000000... | After numerous attempts, I have found an answer how to create a very simple one-liner on this. Here it is if anyone is interested: df = pd.read_csv("C:/Users/Marek/Downloads/0deg-5ms.csv", skiprows=5, delimiter=',(?![^\(]*[\)])', engine="python") Delimiter checks for the comma in everything outside the brackets. Simpl... | 8 | 2 |
69,540,474 | 2021-10-12 | https://stackoverflow.com/questions/69540474/is-it-possible-to-make-the-imports-within-init-py-visible-for-python-help | Suppose I have a module: mymodule/example.py: def add_one(number): return number + 1 And mymodule/__init__.py: from .example import * foo = "FOO" def bar(): return 1 Now I see the function at the root of mymodule: >>> import mymodule >>> mymodule.add_one(3) 4 >>> mymodule.foo 'FOO' Also, I see imported add_one throu... | From the source code of help() (docmodule under pydoc.py) for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all, object): funcs.append... | 6 | 3 |
69,536,863 | 2021-10-12 | https://stackoverflow.com/questions/69536863/how-to-make-pydantic-raise-an-exception-right-away | I wrote a Pydantic model to validate API payload. The payload has 2 attributes emailId as list and role as str { "emailId": [], "role":"Administrator" } I need to perform two validation on attribute email - emailId must not be empty. emailId must not contain emails from x, y, z domains. Hence to accomplish this I wr... | If you have checks, the failure of which should interrupt the further validation, then put them in the pre=True root validator. Because field validation will not occur if pre=True root validators raise an error. For example: class PayloadValidator(BaseModel): emailId: List[str] role: str @root_validator(pre=True) def r... | 5 | 5 |
69,535,331 | 2021-10-12 | https://stackoverflow.com/questions/69535331/how-to-compare-2-dataframes-in-python-unittest-using-assert-methods | I'm writing unittest for a method that returns a dataframe, but, while testing the output using: self.asserEquals(mock_df, result) I'm getting ValueError: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Right now I'm comparing properties that serves the purp... | import unittest import pandas as pd class TestDataFrame(unittest.TestCase): def test_dataframe(self): df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]}) self.assertEqual(True, df1.equals(df2)) if __name__ == '__main__': unittest.main() | 5 | 6 |
69,520,829 | 2021-10-11 | https://stackoverflow.com/questions/69520829/openai-gym-attributeerror-module-contextlib-has-no-attribute-nullcontext | I'm running into this error when trying to run a command from docker a docker container on google compute engine. Here's the stacktrace: Traceback (most recent call last): File "train.py", line 16, in <module> from stable_baselines.ppo1 import PPO1 File "/home/selfplay/.local/lib/python3.6/site-packages/stable_baseline... | It seems like this is an issue with python 3.6 and gym. Upgrading my container to python 3.7 fixed the issue. | 9 | 9 |
69,531,196 | 2021-10-11 | https://stackoverflow.com/questions/69531196/how-to-add-a-newline-between-sequences-with-pyyaml | I've searched and I haven't found very much information on this. I'm writing a Python script to take a list of dictionaries and dump it to a yaml file. For example, I have code like the following: import yaml dict_1 = {'name' : 'name1', 'value' : 12, 'list' : [1, 2, 3], 'type' : 'doc' } dict_2 = {'name' : 'name2', 'val... | You can dump each object one at a time following each with a new line. with open('test_file.yaml', 'w+') as f: for yaml_obj in file_info: f.write(yaml.dump([yaml_obj])) f.write("\n") | 5 | 10 |
69,526,398 | 2021-10-11 | https://stackoverflow.com/questions/69526398/capture-pycharm-stop-signal-in-python | I want to try capturing PyCharm's stop signal (when stop is pressed) in a try block, but I cannot figure out what this signal is or how to capture it in code. JetBrains doesn't provide insight into this in their documentation. I've tried catching it as BaseException but it does not seem to be an exception at all. Is th... | I wasn't able to replicate the other answers as the stop button being sent as a keyboard interrupt. I do believe it's possible for the stop button to be implemented differently on different versions of PyCharm and OS (I'm on Linux where a different answer seems to be Windows, but I'm not positive on many aspects here) ... | 5 | 4 |
69,525,753 | 2021-10-11 | https://stackoverflow.com/questions/69525753/add-comma-sepated-values-inside-a-column | Hi I have a file format (TSV) as like this Name type Age Weight Height Xxx M 12,34,23 50,30,60,70 4,5,6,5.5 Yxx F 21,14,32 40,50,20,40 3,4,5,5.5 I would like to add all the values in Age, Weight and Height and add a column after this, then so some percentage also, like Total_Height/Total_Weight (awk '$0=$0"\t"(NR==1?"... | With your shown samples please try following code. awk ' FNR==1{ print $0,"Total_Age Total_Weight Total_Height Percentage" next } FNR>1{ totAge=totWeight=totHeight=0 split($3,tmp,",") for(i in tmp){ totAge+=tmp[i] } split($4,tmp,",") for(i in tmp){ totWeight+=tmp[i] } split($5,tmp,",") for(i in tmp){ totHeight+=tmp[i] ... | 8 | 7 |
69,527,239 | 2021-10-11 | https://stackoverflow.com/questions/69527239/what-is-context-variable-in-airflow-operators | I'm trying to understand what is this variable called context in Airflow operators. as example: def execute(self, **context**). Where it comes from? where can I set it? when and how can I use it inside my function? Another question is What is *context and **context? I saw few examples that uses this variable like this... | When Airflow runs a task, it collects several variables and passes these to the context argument on the execute() method. These variables hold information about the current task, you can find the list here: https://airflow.apache.org/docs/apache-airflow/stable/macros-ref.html#default-variables. Information from the con... | 17 | 16 |
69,480,199 | 2021-10-7 | https://stackoverflow.com/questions/69480199/pad-token-id-not-working-in-hugging-face-transformers | I want to download the GPT-2 model and tokeniser. For open-end generation, HuggingFace sets the padding token ID to be equal to the end-of-sentence token ID, so I configured it manually using : import tensorflow as tf from transformers import TFGPT2LMHeadModel, GPT2Tokenizer tokenizer = GPT2Tokenizer.from_pretrained("... | Your code does not throw any error for me - I would try re-installing the most recent version of transformers - if that is a viable solution for you. | 5 | 2 |
69,524,514 | 2021-10-11 | https://stackoverflow.com/questions/69524514/how-to-modify-the-kernel-density-estimate-line-in-a-sns-histplot | I am creating a histrogram (frecuency vs. count) and I want to add kernel density estimate line in a different colour. How can I do this? I want to change the colour for example sns.histplot(data=penguins, x="flipper_length_mm", kde=True) Example taken from https://seaborn.pydata.org/generated/seaborn.histplot.html | histplot's line_kws={...} is meant to change the appearance of the kde line. However, the current seaborn version doesn't allow changing the color that way, probably because the color goes together with the hue parameter (although hue isn't used in this case). import seaborn as sns penguins = sns.load_dataset('penguins... | 7 | 24 |
69,519,755 | 2021-10-10 | https://stackoverflow.com/questions/69519755/what-is-the-difference-between-rounding-decimals-with-quantize-vs-the-built-in-r | When working with the built in decimal module in python I can round decimals as follows. Decimal(50.212345).quantize(Decimal('0.01')) > Decimal('50.21') But I can also round the same number with the built in round function round(Decimal(50.212345), 2) > Decimal('50.21') Why would I use one instead of the other when r... | The return types aren't always the same. round() used with a single argument actually returns an int: >>> round(5.3) 5 >>> round(decimal.Decimal("5.3")) 5 Other than that, suit yourself. quantize() is especially handy if you want a deoimal rounded to "the same" precision as another decimal you already have. >>> x = de... | 9 | 13 |
69,515,321 | 2021-10-10 | https://stackoverflow.com/questions/69515321/an-attempt-has-been-made-to-start-a-new-process-before-the-current-process-has-f | I try to run this code on python import multiprocessing manager = multiprocessing.Manager() final_list = manager.list() input_list_one = ['one', 'two', 'three', 'four', 'five'] input_list_two = ['six', 'seven', 'eight', 'nine', 'ten'] def worker(data): for item in data: final_list.append(item) if __name__ == '__main__'... | The problems is with the statement: manager = multiprocessing.Manager() which does its "magic" by starting a server process. Therefore, this statement needs to be moved to within the if __name__ = '__main__': block along with the creation of the managed list, which now needs to be passed as an additional argument to y... | 7 | 12 |
69,502,756 | 2021-10-9 | https://stackoverflow.com/questions/69502756/add-task-to-running-loop-and-run-until-complete | I have a function called from an async function without await, and my function needs to call async functions. I can do this with asyncio.get_running_loop().create_task(sleep()) but the run_until_complete at the top level doesn't run until the new task is complete. How do I get the event loop to run until the new task i... | It appears that the package nest_asyncio will help you out here. I've also included in the example fetching the return value of the task. import asyncio import nest_asyncio def in_control(sleep): print("In control") nest_asyncio.apply() loop = asyncio.get_running_loop() task = loop.create_task(sleep()) loop.run_until_c... | 5 | 3 |
69,495,398 | 2021-10-8 | https://stackoverflow.com/questions/69495398/how-to-fillna-in-pandas-dataframe-based-on-pattern-like-in-excel-dragging | I have dataframe which should be filled by understanding rows understanding like we do in excel. If its continious integer it fill by next number itself. Is there any function in python like this? import pandas as pd d = { 'year': [2019,2020,2019,2020,np.nan,np.nan], 'cat1': [1,2,3,4,np.nan,np.nan], 'cat2': ['c1','c1',... | Here is my solution for the specific use case you mention - The code for these helper functions for categorical_repeat, continous_interpolate and other is provided below in EXPLANATION > Approach section. config = {'year':categorical_repeat, #shortest repeating sequence 'cat1':continous_interpolate, #curve fitting (l... | 9 | 5 |
69,516,166 | 2021-10-10 | https://stackoverflow.com/questions/69516166/how-to-shuffle-the-order-of-if-statements-in-a-function-in-python | I have a functions in Python which has a series of if statements. def some_func(): if condition_1: return result_1 if condition_2: return result_2 ... #other if statements But I want that the order of these if statements is changed every time I call the function. Like if I call the function there can be a case when co... | You can create list of condition and result then shuffle them like below: import random def some_func(x): lst_condition_result = [((x>1), True), ((x>2), False)] random.shuffle(lst_condition_result) for condition, result in lst_condition_result: if condition: return result Output: >>> some_func(20) True >>> some_func(2... | 6 | 5 |
69,503,347 | 2021-10-9 | https://stackoverflow.com/questions/69503347/how-can-i-solve-this-arithmetic-puzzle-my-solution-is-too-slow-after-n-14 | Given numbers 1 to 3n, construct n equations of the form a + b = c or a x b = c such that each number is used exactly once. For example: n=1 => 1+2=3 n=2 => 1+4=5, 2x3=6 n=3 => 4+5=9, 1+7=8, 2x3=6 The question is, does a solution exist for every n? I tried writing a basic program and it becomes too slow after n = 14. ... | This looks like a combinatorial problem where its "messiness" suggests no mathematical answer can be formulated. The cheer number of allowed combinations makes it ever more likely that each n has a valid solution, especially given that for small n you already found solutions. Finding solutions for larger n can be trick... | 7 | 2 |
69,507,122 | 2021-10-9 | https://stackoverflow.com/questions/69507122/fastapi-custom-response-model | I have a router that fetches all data from the database. Here is my code: @router.get('/articles/', response_model=List[articles_schema.Articles]) async def main_endpoint(): query = articles_model.articles.select().where(articles_model.articles.c.status == 2) return await db.database.fetch_all(query) The response is a... | You could simply define another model containing the items list as a field: from pydantic import BaseModel from typing import List class ResponseModel(BaseModel): items: List[articles_schema.Articles] and use it in the response: @router.get('/articles/', response_model=ResponseModel) async def main_endpoint(): query =... | 5 | 7 |
69,507,208 | 2021-10-9 | https://stackoverflow.com/questions/69507208/find-out-how-similar-a-set-is-compared-to-all-other-sets-in-a-collection-of-sets | I'm trying to calculate how similar a set is compared to all other sets in a collection by counting the number of elements that match. Once I have the counts, I want to perform further operations against each set with the top X (currently 100) similar sets (ones with the highest count). I have provided an example input... | Use an inverted index to avoid computing intersection with those sets that the cardinality of the intersection is 0: from collections import defaultdict, Counter from itertools import chain from pprint import pprint data = { "list1": ["label1", "label2", "label3"], "list2": ["label2", "label3", "label4"], "list3": ["la... | 5 | 5 |
69,505,726 | 2021-10-9 | https://stackoverflow.com/questions/69505726/pandas-typeerror-cannot-perform-rand-with-a-dtyped-bool-array-and-scalar | I wanted to change a value of a cell with the conditions of another cell value and used this code dfT.loc[dfT.state == "CANCELLED" & (dfT.Activity != "created"), "Activity"] = "cancelled" This is an Example Table: ID Activity state 1 created CANCELLED 1 completed CANCELLED 2 created FINNISHED 2 completed ... | You need to wrap your conditions inside () Use: dfT.loc[(dfT.state == "CANCELLED") & (dfT.Activity != "created"), "Activity"] = "cancelled" | 6 | 15 |
69,505,262 | 2021-10-9 | https://stackoverflow.com/questions/69505262/how-to-compare-dataclasses | I would like to compare two global dataclasses in terms of equality. I changed the field in one of the dataclasses and python still insists on telling me, that those objects are equal. I don't know how internally dataclasses work, but when I print asdict I get an empty dictionary... What am I doing wrong and how can I ... | For Python to recognize fields of a dataclass, those fields should have PEP 526 type annotations. For example: from typing import Optional @dataclass class TestClass: field1: Optional[str] = None field2: bool = False With that definition comparisons and asdict work as expected: In [2]: TestClass(field2=True) == TestCl... | 7 | 10 |
69,483,214 | 2021-10-7 | https://stackoverflow.com/questions/69483214/issues-setting-up-python-testing-in-vscode-using-pytest | I am trying to use the testing extension in VSCode with the Python extension. I am using pytest as my testing library. My folder structure looks like this: PACKAGENAME/ ├─ PACKAGENAME/ │ ├─ __init__.py │ ├─ main.py ├─ tests/ │ ├─ test_main.py ├─ requirements.txt In the test_main.py file I am trying to import the packa... | I suggest that you try like this: make sure that your VS Code workspace is set to the parent directory of (the root directory) PACKAGENAME add an empty __init__.py file in testsdirectory in test_main.py, replace from PACKAGENAME import * with from PACKAGENAME.main import * | 9 | 10 |
69,503,887 | 2021-10-9 | https://stackoverflow.com/questions/69503887/pip-cannot-install-anything-after-upgrading-to-python-3-10-0-on-windows | I recently upgraded to the latest version of python version 3.10.0 and upgraded pip also to the latest version 21.2.4. Now I cannot use pip to install anything. This is the error it gives for anything I try to install. C:\Users\AMAL>pip install numpy Collecting numpy Using cached numpy-1.21.2.zip (10.3 MB) Installing ... | Try to upgrade your pip pip install --upgrade pip | 5 | 2 |
69,491,795 | 2021-10-8 | https://stackoverflow.com/questions/69491795/how-to-force-keras-to-use-tensorflow-gpu-backend | I know this is one of the popular questions, but none of the solutions worked for me, so far. I'm running a legacy code that is written in tensorflow v1.13.1 and keras v2.2.4. I cannot modify the code to run latest tensorflow version. Since keras has now been merged into tensorflow, I'm facing problems installing the s... | Installing tensorflow first and then keras worked! conda install tensorflow-gpu=1.13.1 conda install keras-gpu=2.2.4 | 5 | 0 |
69,493,263 | 2021-10-8 | https://stackoverflow.com/questions/69493263/why-do-keyword-arguments-to-a-class-definition-reappear-after-they-were-removed | I created a metaclass that defines the __prepare__ method, which is supposed to consume a specific keyword in the class definition, like this: class M(type): @classmethod def __prepare__(metaclass, name, bases, **kwds): print('in M.__prepare__:') print(f' {metaclass=}\n {name=}\n' f' {bases=}\n {kwds=}\n {id(kwds)=}') ... | and the dict that is passed to new is the same object that was passed to prepare Unfortunately, this is where you are wrong. Python only recycles the same object id. If you create a new dict inside __prepare__ you will notice the id of kwds changes in __new__. class M(type): @classmethod def __prepare__(metaclass, na... | 6 | 6 |
69,492,265 | 2021-10-8 | https://stackoverflow.com/questions/69492265/fastapi-sqlalchemy-pytest-unable-to-get-100-coverage-it-doesnt-properly-co | I'm trying to build FastAPI application fully covered with test using python 3.9 For this purpose I've chosen stack: FastAPI, uvicorn, SQLAlchemy, asyncpg, pytest (+ async, cov plugins), coverage and httpx AsyncClient Here is my minimal requirements.txt All tests run smoothly and I get the expected results. But I've fa... | it's an issue with SQLAlchemy 1.4 in coveragepy: https://github.com/nedbat/coveragepy/issues/1082, https://github.com/nedbat/coveragepy/issues/1012 you can try with --concurrency==greenlet option | 13 | 13 |
69,492,406 | 2021-10-8 | https://stackoverflow.com/questions/69492406/streamlit-how-to-display-buttons-in-a-single-line | Hi all I am building a simple web app with streamlit in python. I need to add 3 buttons but they must be on the same line. Obviously the following code puts them on three different lines st.button('Button 1') st.button('Button 2') st.button('Button 3') Do you have any tips? | Apparently this should do it col1, col2, col3 = st.columns([1,1,1]) with col1: st.button('1') with col2: st.button('2') with col3: st.button('3') | 20 | 33 |
69,486,648 | 2021-10-7 | https://stackoverflow.com/questions/69486648/python-regex-where-a-set-of-options-can-occur-at-most-once-in-a-list-in-any-ord | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of foo(?: [abc])*, where a, b, c could only appear once. So: foo a b c foo b c a foo a b foo b would all be valid, but foo b b would ... | You may use this regex with a capture group and a negative lookahead: For Perl, you can use this variant with forward referencing: ^foo((?!.*\1) [abc])+$ RegEx Demo RegEx Details: ^: Start foo: Match foo (: Start a capture group #1 (?!.*\1): Negative lookahead to assert that we don't match what we have in capture gr... | 22 | 13 |
69,487,794 | 2021-10-7 | https://stackoverflow.com/questions/69487794/pandas-how-to-filter-dataframe-with-certain-range-of-numbers-in-a-column-of-data | I am trying to come up with a way to filter dataframe so that it contains only certain range of numbers that is needed for further processing. Below is an example dataframe data_sample = [['part1', 234], ['part2', 224], ['part3', 214],['part4', 114],['part5', 1111], ['part6',1067],['part7',1034],['part8',1457],['part9'... | New version Use np.logical_and and any to select values in ranges and invert the mask to keep other ones. intervals = [(100, 130), (200, 230), (350, 370), (1000, 1150)] m = np.any([np.logical_and(data_df['sbin'] >= l, data_df['sbin'] <= u) for l, u in intervals], axis=0) out = data_df.loc[~m] Note any can be replaced ... | 5 | 4 |
69,477,337 | 2021-10-7 | https://stackoverflow.com/questions/69477337/function-for-restricting-the-type-of-attributes-in-an-object-python-mypy | Example setup: from typing import Optional class A(object): def __init__(self): self.a: Optional[int] = None def check_a(self) -> bool: return self.a is not None a = A() if a.check_a(): print(a.a + 1) # error: Unsupported operand types for + ("None" and "int") The check_a method checks what type of variable a is, but ... | There are two ways in which this can be done with the new TypeGuard feature, which can be imported from typing in Python 3.10, and is available from the PyPI typing_extensions package in earlier Python versions. Note that typing_extensions is already a dependency of Mypy, so if you're using Mypy, you likely already hav... | 5 | 5 |
69,483,237 | 2021-10-7 | https://stackoverflow.com/questions/69483237/how-to-create-base64-encode-sha256-string-in-javascript | I want to log script hashes to implement content security policy. I have been able to generate the hash in python with the following code: import hashlib import base64 string=''' //<![CDATA[ var theForm = document.forms['ctl00']; if (!theForm) { theForm = document.ctl00; } function __doPostBack(eventTarget, eventArgume... | const string = ` //<![CDATA[ var theForm = document.forms['ctl00']; if (!theForm) { theForm = document.ctl00; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theFor... | 5 | 8 |
69,483,502 | 2021-10-7 | https://stackoverflow.com/questions/69483502/is-there-a-way-to-infer-in-python-if-a-date-is-the-actual-day-in-which-the-dst | I would like to infer in Python if a date is the actual day of the year in which the hour is changed due to DST (Daylight Saving Time). With the library pytz you can localize a datetime and the actual DST change is correctly done. Furthermore, there is the method dst() of the library datetime that allows you to infer i... | You can make use of datetime.dst() (a change in UTC offset is not necessarily a DST transition): from datetime import datetime, time, timedelta from zoneinfo import ZoneInfo # Python 3.9+ def is_date_of_DSTtransition(dt: datetime, zone: str) -> bool: """ check if the date part of a datetime object falls on the date of ... | 5 | 4 |
69,479,559 | 2021-10-7 | https://stackoverflow.com/questions/69479559/why-does-mypy-not-accept-a-liststr-as-a-listoptionalstr | Example 1: from typing import List, Optional def myfunc() -> List[Optional[str]]: some_list = [x for x in "abc"] return some_list Mypy complains on example 1: Incompatible return value type (got "List[str]", expected "List[Optional[str]]") However, this example gets no complaint: Example 2: def myfunc() -> List[Opti... | Since in Python lists are invariant (see the examples here and here). If we pass List[str] to someone that expects List[Optional[str]], that someone may add a None to our list and break our assumptions. The second example is valid however as the output of list() in the return statement is not saved anywhere and no one ... | 7 | 6 |
69,479,669 | 2021-10-7 | https://stackoverflow.com/questions/69479669/kneighborsclassifier-with-cross-validation-returns-perfect-accuracy-when-k-1 | I'm training a KNN classifier using scikit-learn's KNeighborsClassifier with cross validation: k=1 param_space = {'n_neighbors': [k]} model = KNeighborsClassifier(n_neighbors=k, metric='euclidean') search = GridSearchCV(model, param_space, cv=cv, verbose=10, n_jobs=8) search.fit(X_df, y_df) preds = search.best_estimato... | Your predictions are from the best_estimator_, which is a copy of the estimator with the optimal hyperparameters (according to the cross-validation scores) refitted to the entire training set. So the confusion matrix you generate is really a training score, and for 1-neighbors that's trivially perfect (the nearest neig... | 5 | 2 |
69,459,268 | 2021-10-6 | https://stackoverflow.com/questions/69459268/cant-install-python-3-10-0-with-pyenv-on-macos | Trying to install Python 3.10.0 on MacOS 11.6 (Intel) with pyenv 2.1.0 (from homebrew) fails with: python-build: use openssl@1.1 from homebrew python-build: use readline from homebrew Downloading Python-3.10.0.tar.xz... -> https://www.python.org/ftp/python/3.10.0/Python-3.10.0.tar.xz Installing Python-3.10.0... python-... | The problem was that I had a second version of clang installed (via homebrew), which interfered with the build. After running brew uninstall llvm pyenv/python-build picked the clang from xcode and now pyenv works again. | 11 | 2 |
69,473,782 | 2021-10-6 | https://stackoverflow.com/questions/69473782/how-to-use-one-else-statement-with-multiple-if-statements | So I'm trying to make a login prompt and I want it to print 'Success' only if there are no errors. This is the code I'm using: if not is_email(email) or not is_name(name) or password != confirmPassword or not is_secure(password): if not is_email(email): print('Not a valid email') if not is_name(name): print('Not a vali... | How about this? flags = [is_email(email), is_name(name), password != confirmPassword, is_secure(password)] prints = ['Not a valid email', 'Not a valid name', 'Passwords don\'t match', 'Password is not secure'] for index in range(len(flags)): if flags[index] == False: print(prints[index]) | 6 | 3 |
69,472,351 | 2021-10-6 | https://stackoverflow.com/questions/69472351/python-pydantic-how-to-mark-field-as-secret | How to mark pydantic model filed as secret so it will not shown in the repr str and will be excluded from dict and etc... from pydantic import BaseModel class User(BaseModel): name: str password_hash: str # I do not want this field to leak out. I write my code with security in mind and I afraid that in the future some... | Pydantic provides convenience Secret* classes for this exact purpose: from pydantic import BaseModel, SecretStr class User(BaseModel): name: str password_hash: SecretStr | 6 | 8 |
69,471,749 | 2021-10-6 | https://stackoverflow.com/questions/69471749/importerror-cannot-import-name-batchnormalization-from-keras-layers-normaliz | i have an import problem when executing my code: from keras.models import Sequential from keras.layers.normalization import BatchNormalization 2021-10-06 22:27:14.064885: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not fou... | You're using outdated imports for tf.keras. Layers can now be imported directly from tensorflow.keras.layers: from tensorflow.keras.models import Sequential from tensorflow.keras.layers import ( BatchNormalization, SeparableConv2D, MaxPooling2D, Activation, Flatten, Dropout, Dense ) from tensorflow.keras import backend... | 31 | 16 |
69,469,980 | 2021-10-6 | https://stackoverflow.com/questions/69469980/what-is-an-opaque-object-in-the-context-of-the-copy-module | Reading the documentation of the python standard library copy module I stumbled across the following sentence: The memo dictionary should be treated as an opaque object. I understand that an opaque object usually is an object whose internals are unknown and which is only accessed via member functions. What does being... | Read the sentence that precedes your quoted sentence. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument. The idea is that your __deepcopy__ method should do nothing with ... | 6 | 6 |
69,465,156 | 2021-10-6 | https://stackoverflow.com/questions/69465156/unable-to-build-a-docker-image-following-docker-tutorial | I was following this tutorial on a Macbook to build a sample Docker image but when I tried to run the following command: docker build -t getting-started . I got the following error: [+] Building 3.2s (15/24) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 1.05kB 0.0s => [interna... | See its Dockerfile, it uses FROM python:alpine AS base, which means it used a shared tag. Another word, at the time the document wrote, python:alpine means maybe python:3.9-alpine or others. But now, it means python:3.10-alpine, see this. The problems happens at mkdocs itself, it uses next code: from collections import... | 8 | 6 |
69,462,277 | 2021-10-6 | https://stackoverflow.com/questions/69462277/use-pre-commit-hook-for-black-with-multiple-language-versions-for-python | We are using pre-commit to format our Python code using black with the following configuration in .pre-commit-config.yaml: repos: - repo: https://github.com/ambv/black rev: 20.8b1 hooks: - id: black language_version: python3.7 As our packages are tested against and used in different Python versions (e.g. 3.7, 3.8, 3.9... | one way would be to set language_version: python3 (this used to be the default for black) -- the actual language_version you use there doesn't matter all that much as black doesn't use it to pick the formatted language target (that's a separate option) generally though, you shouldn't need to set language_version as eit... | 8 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.