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 |
|---|---|---|---|---|---|---|
71,803,409 | 2022-4-8 | https://stackoverflow.com/questions/71803409/vscode-how-to-interrupt-a-running-python-test | I'm using VSCode Test Explorer to run my Python unit tests. There was a bug in my code and my tested method never finishes. How do I interrupt my test? I can't find how to do it using the GUI. I had to close VSCode to interrupt it. I'm using pytest framework. | Silly me, here is the Stop button at the top right of the the Testing tab: | 33 | 78 |
71,786,694 | 2022-4-7 | https://stackoverflow.com/questions/71786694/building-a-random-forest-classifier-with-equal-output-probabilities-to-a-decisio | I have been trying to build a RandomForestClassifier() (RF) model and a DecisionTreeClassifier() (DT) model in order to get the same output (only for learning purposes). I have found some questions with answers where I used those answers to build this code, like the required parameters to make both models equal but I c... | It appears to be due to random states, despite your best efforts. For the random forest to be effective at its randomization, it needs to provide each component decision tree with a different random state (using sklearn.ensemble._base._set_random_states, source). You can check in your code that while RF.random_state an... | 5 | 3 |
71,846,838 | 2022-4-12 | https://stackoverflow.com/questions/71846838/gitlab-ci-cd-pipeline-runs-django-unit-tests-before-migrations | Problem I'm trying to set up a test stage in Gitlab's CI/CD. Locally, running the unit tests goes fine and as expected. In Gitlab's CI/CD, though, when running the script coverage run manage.py test -v 2 && coverage report the unit tests are executing before the migrations are completed in the test database, which is u... | Add a python manage.py migrate line before coverage run manage.py test ... in the scripts section of your gitlab-ci.yml. | 5 | 3 |
71,821,025 | 2022-4-10 | https://stackoverflow.com/questions/71821025/remove-the-unnecessary-padding-inside-the-html-table-cells-which-is-being-gener | I have a python script which dynamically generates a HTML Table according to some specifications provided to it. A sample generated output is given below, As you can see, it is possible that, It is possible for two consecutive cells to be merged (it is done from the Python Script, again. With the help of Jinja2) It i... | Assign the following CSS rulesets: Figure I Selector Property Value td position relative td padding 0 td div position relative td p position absolute td p margin 0 .course top 0.5rem .course left 0.5rem .room bottom 0.5rem .room right 0.5rem .teacher bottom 0.5rem .teacher left 0.5rem Ba... | 4 | 1 |
71,818,149 | 2022-4-10 | https://stackoverflow.com/questions/71818149/post-request-gets-blocked-on-python-backend-get-request-works-fine | I am building a web app where the front-end is done with Flutter while the back-end is with Python. GET requests work fine while POST requests get blocked because of CORS, I get this error message: Access to XMLHttpRequest at 'http://127.0.0.1:8080/signal' from origin 'http://localhost:57765' has been blocked by CORS p... | I finally figured out what was going on. First I disabled the same origin policy in chrome using this command: this is run clicking the start button in windows and typing this command directly.. chrome.exe --disable-site-isolation-trials --disable-web-security --user-data-dir="D:\anything" This fired a separate chrome... | 7 | 1 |
71,842,013 | 2022-4-12 | https://stackoverflow.com/questions/71842013/seaborn-pairplot-with-log-scale-only-for-specific-columns | I have a dataframe and I'm using seaborn pairplot to plot one target column vs the rest of the columns. Code is below, import seaborn as sns import matplotlib.pyplot as plt tgt_var = 'AB' var_lst = ['A','GH','DL','GT','MS'] pp = sns.pairplot(data=df, y_vars=[tgt_var], x_vars=var_lst) pp.fig.set_figheight(6) pp.fig.set_... | Iterate pp.axes.flat and set xscale="log" if the xlabel matches "GH" or "MS": log_columns = ["GH", "MS"] for ax in pp.axes.flat: if ax.get_xlabel() in log_columns: ax.set(xscale="log") Full example with the iris dataset where the petal columns are xscale="log": import seaborn as sns df = sns.load_dataset("iris") pp = ... | 4 | 9 |
71,838,934 | 2022-4-12 | https://stackoverflow.com/questions/71838934/arangodb-read-timed-out-read-timeout-60 | I have a problem. I am using ArangoDB enterprise:3.8.6 via Docker. But unfortunately my query takes longer than 30s. When it fails, the error is arangodb HTTPConnectionPool(host='127.0.0.1', port=8529): Read timed out. (read timeout=60). My collection is aroung 4GB huge and ~ 1.2 mio - 900k documents inside the collec... | You can increase the HTTP client's timeout by using a custom HTTP client for Arango. The default is set here to 60 seconds. from arango.http import HTTPClient class MyCustomHTTPClient(HTTPClient): REQUEST_TIMEOUT = 1000 # Set the timeout you want in seconds here # Pass an instance of your custom HTTP client to Arango: ... | 4 | 6 |
71,845,596 | 2022-4-12 | https://stackoverflow.com/questions/71845596/python-typing-narrowing-type-from-function-that-returns-a-union | I have difficulties finding return types that satisfy mypy. I have two functions. The first one returns a Union type, since the type depends on the parameter given to the function. The second function calls the first one with a default parameter. Thus, the type is not a Union type -- it can be narrowed down to one of t... | mypy can't infer the relationship between the types of the parameters and the types of the return values. You have two options: Use an assert to make sure that the type is correct: def second(as_string) -> str: ret = first(True) assert isinstance(ret, str) return ret You can use typing.cast to assert to the typechec... | 19 | 17 |
71,828,861 | 2022-4-11 | https://stackoverflow.com/questions/71828861/filtering-audio-signal-in-tensorflow | I am building an audio-based deep learning model. As part of the preporcessing I want to augment the audio in my datasets. One augmentation that I want to do is to apply RIR (room impulse response) function. I am working with Python 3.9.5 and TensorFlow 2.8. In Python the standard way to do it is, if the RIR is given a... | Here is one way you could do Notice that tensor flow function is designed to receive batches of inputs with multiple channels, and the filter can have multiple input channels and multiple output channels. Let N be the size of the batch I, the number of input channels, F the filter width, L the input width and O the nu... | 7 | 4 |
71,837,032 | 2022-4-12 | https://stackoverflow.com/questions/71837032/python3-file-open-write-exception-handling | Does the code below provide correct exception handling. My goal is, to not attempt the file.write() unless the file was successfully opened and ensure the file is closed. I am not concerned with the exact errors of why the file did not open or why the file did not write. Python version 3.6.9. OS Linux. data = "Some dat... | You should basically never use a blanket except; always spell out which exception(s) exactly you want to handle. Here is a refactoring using a context handler, so you can avoid the explicit finally: close data = "Some data" filename = "test.txt" try: with open(filename, 'w+') as file: try: file.write(data) except (IOEr... | 6 | 6 |
71,812,767 | 2022-4-9 | https://stackoverflow.com/questions/71812767/how-to-stop-python-from-truncating-print-statements | I have a print statement that prints a very long big Pandas DataFrame series out, but I need all the information. When printing, Python gives 0 [{This is a long stateme.....}] 1 [{This is a long stateme.....}] and terminates the print statement with dots. I want to see the entire print statement without Python termina... | Pandas allows options to see a set number of rows, as well as width pd.set_option("display.max_rows", n) pd.set_option("display.expand_frame_repr", True) pd.set_option('display.width', 1000) To increase the number of characters printed per column, use: pd.set_option("display.max_colwidth", max_characters) By default, ... | 7 | 1 |
71,828,733 | 2022-4-11 | https://stackoverflow.com/questions/71828733/flake8-on-all-files-under-specific-subdirectories | I'm trying to use flake8 only on 3 specific sub directories: features_v2, rules_v2 and indicators_v2. In order to test if my pattern is correct I tried applying it only to features_v2 at first. so I came up with this pattern: exclude = ^(?!.*features_v2).*$ but sadly it doesn't seems to work. Is flake8 does not support... | flake8's exclude is not a regex but a glob -- it cannot support what you're looking for may I suggest instead to run flake8 on the directories you want? flake8 features_v2 rules_v2 indicators_v2 disclaimer: I maintain flake8 | 8 | 13 |
71,820,357 | 2022-4-10 | https://stackoverflow.com/questions/71820357/obtaining-tweets-image-urls-with-tweepy-v2-on-twitter-api-v2 | what is an elegant way to access the urls of tweets pictures with tweepy v2? Twitter released a v2 of their API and tweepy adjusted their python module to it (tweepy v2). Lets say for example I have a dataframe of tweets created with tweepy, holding tweet id and so on. There is a row with this example tweet: https://tw... | The arguments of get_liked_tweets seem to be correct. Have you looked in the includes dict at the root of the response? The media fields are not in data, so you should have something like that: { "data": { "attachments": { "media_keys": [ "16_1211797899316740096" ] }, "author_id": "2244994945", "id": "12120926280296980... | 5 | 5 |
71,827,522 | 2022-4-11 | https://stackoverflow.com/questions/71827522/unable-to-install-pickle5 | PS C:\Users\Lenovo> pip install pickle5 Collecting pickle5 Using cached pickle5-0.0.11.tar.gz (132 kB) Preparing metadata (setup.py) ... done Using legacy 'setup.py install' for pickle5, since package 'wheel' is not installed. Installing collected packages: pickle5 Running setup.py install for pickle5 ... error error: ... | You only need pickle5, a module backporting Pickle protocol 5 features to older Pythons when running on Python versions older than 3.8. As evident from Python310 and -3.10 in the output, you're on Python 3.10. You don't need pickle5. Thus, the answer to "what should you do", without us not knowing more details about yo... | 7 | 6 |
71,823,279 | 2022-4-11 | https://stackoverflow.com/questions/71823279/python-read-huge-file-line-per-line-and-send-it-to-multiprocessing-or-thread | I have been trying to get my code to work for many days, I am desperate. I've scoured the internet, but I still can't find it. I have a text file encoded in "latin-1" of 9GB -> 737 022 387 lines, each line contains a string. I would like to read each line and send them in an http PUT request that waits for a response, ... | Although the problem seems unrealistic though. shooting 737,022,387 requests! calculate how many months it'll take from single computer!! Still, Better way to do this task is to read line by line from file in a separate thread and insert into a queue. And then multi-process the queue. Solution 1: from multiprocessing i... | 6 | 4 |
71,768,804 | 2022-4-6 | https://stackoverflow.com/questions/71768804/two-ways-to-create-timezone-aware-datetime-objects-django-seven-minutes-diffe | Up to now I thought both ways to create a timezone aware datetime are equal. But they are not: import datetime from django.utils.timezone import make_aware, get_current_timezone make_aware(datetime.datetime(1999, 1, 1, 0, 0, 0), get_current_timezone()) datetime.datetime(1999, 1, 1, 0, 0, 0, tzinfo=get_current_timezone(... | This happens on Django 3.2 and lower, which rely on the pytz library. In Django 4 (unless you enable to setting to use the deprecated library), the output of the two examples you give is identical. In Django 3.2 and below, the variance arises because the localised time is built in two different ways. When using make_aw... | 10 | 11 |
71,823,151 | 2022-4-11 | https://stackoverflow.com/questions/71823151/deploy-reacts-build-folder-via-fastapi | I want to serve my React frontend using FastAPI. The goal being 0 Javascript dependency for the user. The user can simply download the Python code, start server, and view the website on localhost. My folder structure is: - my-fullstack-app - frontend/ - build/ - public/ - ... - package.json - backend/ - main.py - stati... | The answer mentioned by @flakes is exactly what I was looking for. Check it out for more details. For completeness, Without html=True flag. app.mount("/", StaticFiles(directory="static/"), name="static") Navigate to http://127.0.0.1:8000/index.html to view the html file. With html=True flag. app.mount("/", StaticFile... | 7 | 10 |
71,773,998 | 2022-4-6 | https://stackoverflow.com/questions/71773998/how-to-draw-a-progress-bar-with-pillow | I am currently trying to draw a progress bar, based on a calculated percentage. However, I am not able to display it in the right format. I orientated myself on another answer from this site here (How do you make a progress bar and put it on an image? & Is it possible to add a blue bar using PIL or Pillow?) But either ... | The issue with your code was that the background and progress bar sections were of the same color, and as such, you couldn't see it. This can be fixed by coloring them differently. The line progress = ((already_earned / to_reach ) * 100) also sets progress to a percentage [0, 100]. You then multiply width by this. For ... | 7 | 4 |
71,812,508 | 2022-4-9 | https://stackoverflow.com/questions/71812508/sqlalchemy-select-from-join-of-two-subqueries | Need help translating this SQL query into SQLAlchemy: select COALESCE(DATE_1,DATE_2) as DATE_COMPLETE, QUESTIONS_CNT, ANSWERS_CNT from ( (select DATE as DATE_1, count(distinct QUESTIONS) as QUESTIONS_CNT from GUEST_USERS where LOCATION like '%TEXAS%' and DATE = '2021-08-08' group by DATE ) temp1 full join (select DATE ... | Not sure if this is the best solution but this is how I got it to work. Using 3 subqueries essentially. query1 = db.session.query( GUEST_USERS.DATE_WEEK_START.label("DATE_1"), func.count(GUEST_USERS.QUESTIONS).label("QUESTIONS_CNT") ).filter( GUEST_USERS.LOCATION.like("%TEXAS%"), GUEST_USERS.DATE == "2021-08-08" ).grou... | 4 | 5 |
71,798,863 | 2022-4-8 | https://stackoverflow.com/questions/71798863/how-to-change-the-default-backend-in-matplotlib-from-qtagg-to-qt5agg-in-pych | Qt5Agg is necessary to use the mayavi 3D visualization package. I have installed PyQt5 and mayavi using pip in a separate copied conda environment. The default backend then changes from TkAgg to QtAgg. This is a bit weird because in an earlier installation in a different PC the default changed directly to Qt5Agg. I alw... | Thanks to @PaulH's comment, I was able to solve the issue. Owing to @mx0's suggestion, I shall now explicitly mention the fix below so that others can also benefit from it. In a particular conda environment, if matplotlib package is installed, then there will be a 'matplotlibrc' file stored somewhere that defines what ... | 5 | 8 |
71,802,758 | 2022-4-8 | https://stackoverflow.com/questions/71802758/when-using-slots-why-does-dirtype-have-no-dict-attribute | I'm trying to understand slots. Therefore, I have written a little script with two classes, one using slots and one not. class A: def __init__(self, name): self.name = name def getName(self): return self.name class C: __slots__ = "name" def __init__(self, name): self.name = name def getName(self): return self.name Whe... | Since you don't override __dir__ here, in each case here it will resolve in the MRO to type.__dir__(A) or type.__dir__(C). So we look at the default implementation of __dir__ for types, here in Objects/typeobject.c /* __dir__ for type objects: returns __dict__ and __bases__. We deliberately don't suck up its __class__,... | 8 | 7 |
71,805,426 | 2022-4-9 | https://stackoverflow.com/questions/71805426/how-to-tell-a-python-type-checker-that-an-optional-definitely-exists | I'm used to typescript, in which one can use a ! to tell the type-checker to assume a value won't be null. Is there something analogous when using type annotations in python? A (contrived) example: When executing the expression m.maybe_num + 3 in the code below, the enclosing if guarantees that maybe_num won't be None.... | Sadly there's no clean way to infer the type of something from a function call like this, but you can work some magic with TypeGuard annotations for the has_a_num() method, although the benefit from those annotations won't really be felt unless the difference is significantly more major than the type of a single int. I... | 7 | 2 |
71,805,129 | 2022-4-9 | https://stackoverflow.com/questions/71805129/pandas-dataframe-concatenation-with-axis-1-lost-column-names | I'm trying to concatenate two dataframes with these conditions : for an existing header, append to the column ; otherwise add a new column. The code is working but the columns names are lost in case 2. Why? It doesn't seem to be mentioned in Pandas doc. Or I missed something? How to keep the column names? The code : ... | You requested to drop the index with ignore_index=True. As you are concatenating on axis=1 the index is the columns! frames = [result_1, df3] if "E" in df3.columns : result_2 = pd.concat(frames, axis=1) print(result_2) Output: A B C D E 0 A0 B0 C0 D0 E0 1 A1 B1 C1 D1 E1 2 A2 B2 C2 D2 E2 3 A3 B3 C3 D3 E3 4 A4 B4 C4 D4... | 7 | 10 |
71,802,492 | 2022-4-8 | https://stackoverflow.com/questions/71802492/how-to-pass-parameter-to-dictionary-input-for-agg-pyspark-function | From the pyspark docs, I Can do: gdf = df.groupBy(df.name) sorted(gdf.agg({"*": "first"}).collect()) In my actual use case I have maaaany variables, so I like that I can simply create a dictionary, which is why: gdf = df.groupBy(df.name) sorted(gdf.agg(F.first(col, ignorenulls=True)).collect()) @lemon's suggestion wo... | You can use list comprehension. gdf.agg(*[F.first(x, ignorenulls=True).alias(x) for x in df.columns]).collect() | 4 | 4 |
71,801,541 | 2022-4-8 | https://stackoverflow.com/questions/71801541/how-can-i-dynamically-pad-a-number-in-python-f-strings | I have an f-string like this: f"foo-{i:03d}" This is producing a filename for a file that I read in. The problem is sometimes there are hundreds of files, so the files are named like foo-001, foo-002, etc., but other times there are thousands, so the files are foo-0001 and 04d would be needed. Is there a way I can do ... | Nested f-string: >>> pad = 4 >>> i = 1 >>> f"foo-{i:>0{pad}}" 'foo-0001' | 7 | 11 |
71,798,874 | 2022-4-8 | https://stackoverflow.com/questions/71798874/django-how-to-add-or-condition-to-queryset-filter-in-custom-filter | I want to make a search filter which searches in multiple fields with multiple conditions, using only one search field. I have this filters.py file: import django_filters from .models import Product class ProductFilter(django_filters.FilterSet): q = django_filters.CharFilter(method='search_filter', label='Cerca') class... | You can filter with Q objects [Django-doc]: import django_filters from django.db.models import Q from .models import Product class ProductFilter(django_filters.FilterSet): q = django_filters.CharFilter(method='search_filter', label='Cerca') class Meta: model = Product fields = ['q'] def search_filter(self, queryset, na... | 4 | 6 |
71,787,974 | 2022-4-7 | https://stackoverflow.com/questions/71787974/why-does-x13-formatx-asd-cause-a-typeerror | Consider this: >>> '{x[1]}'.format(x="asd") 's' >>> '{x[1:3]}'.format(x="asd") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: string indices must be integers What could be the cause for this behavior? | An experiment based on your comment, checking what value the object's __getitem__ method actually receives: class C: def __getitem__(self, index): print(repr(index)) '{c[4]}'.format(c=C()) '{c[4:6]}'.format(c=C()) '{c[anything goes!@#$%^&]}'.format(c=C()) C()[4:6] Output (Try it online!): 4 '4:6' 'anything goes!@#$%^&... | 35 | 29 |
71,794,902 | 2022-4-8 | https://stackoverflow.com/questions/71794902/issue-with-bad-request-syntax-with-flask | I am testing/attempting to learn flask, and flast_restful. This issue I get is: code 400, message Bad request syntax ('name=testitem') main.py: from flask import Flask,request from flask_restful import Api, Resource, reqparse app = Flask(__name__) api = Api(app) product_put_args = reqparse.RequestParser() product_put_a... | You need to add the location information to the RequestParser by default it tries to parse values from flask.Request.values, and flask.Request.json, but in your case, the values need to be parsed from a flask.request.form. Below code fixes your error from flask import Flask,request from flask_restful import Api, Resour... | 4 | 12 |
71,765,091 | 2022-4-6 | https://stackoverflow.com/questions/71765091/unit-testing-by-mocking-s3-bucket | I am new to unit testing and I require to perform some simple unit tests for an object storage class. I have a class named OSBucket as follows: def __initBucket(self): ecs_session = boto3.Session( aws_access_key_id="OSKEY", aws_secret_access_key="SECRETKEY" ) OS_resource = ecs_session.resource('s3', verify=cert, endpoi... | First Approach: using python mocks You can mock the s3 bucket using standard python mocks and then check that you are calling the methods with the arguments you expect. However, this approach won't actually guarantee that your implementation is correct since you won't be connecting to s3. For example, you can call non-... | 5 | 11 |
71,791,008 | 2022-4-8 | https://stackoverflow.com/questions/71791008/np-cumsumdfcolumn-treatment-of-nans | np.cumsum([1, 2, 3, np.nan, 4, 5, 6]) will return nan for every value after the first np.nan. Moreover, it will do the same for any generator. However, np.cumsum(df['column']) will not. What does np.cumsum(...) do, such that dataframes are treated specially? In [2]: df = pd.DataFrame({'column': [1, 2, 3, np.nan, 4, 5, ... | When you call np.cumsum(object) with an object that is not a numpy array, it will try calling object.cumsum() See this thread for details . You can also see it in the Numpy source. The pandas method has a default of skipna=True. So np.cumsum(df) gets turned into the equivalent of df.cumsum(axis=None, skipna=True, *args... | 6 | 6 |
71,763,118 | 2022-4-6 | https://stackoverflow.com/questions/71763118/what-is-causing-my-random-joblib-externals-loky-process-executor-terminatedwor | I'm making GIS-based data-analysis, where I calculate wide area nation wide prediction maps (e.g. weather maps etc.). Because my target area is very big (whole country) I am using supercomputers (Slurm) and parallelization to calculate the prediction maps. That is, I split the prediction map into multiple pieces with e... | Q :" What causes this problem, any ideas? - I am using supercomputers " A :a) Python Interpreter process ( even if run on supercomputers ) is living in an actual localhost RAM-memory.b) given (a), the number of such localhost CPU-cores controls the joblib.Parallel() behaviour.c)given (b) and having set n_jobs = -1 an... | 7 | 7 |
71,769,975 | 2022-4-6 | https://stackoverflow.com/questions/71769975/in-the-python-requests-cache-package-how-do-i-detect-a-cache-hit-or-miss | The Python https://requests-cache.readthedocs.io/ library can be used to cache requests. If I'm using requests-cache, how do I detect whether a response came from the cache, or had to be re-fetched from the network? | Based on the docs The following attributes are available on responses: from_cache: indicates if the response came from the cache cache_key: The unique identifier used to match the request to the response (see Request Matching for details) created_at: datetime of when the cached response was created or last updated ex... | 7 | 10 |
71,767,715 | 2022-4-6 | https://stackoverflow.com/questions/71767715/importerror-cannot-import-name-container-from-collections | My code is running fine in local, but crashes on Heroku. What can I do to fix it? Traceback (most recent call last) File "/app/nao_entre_em_panico.py", line 2, in <module> from flask import Flask, jsonify, request File "/app/.heroku/python/lib/python3.10/site-packages/flask/__init__.py", line 17, in <module> from werk... | Container, Iterable, MutableSet, and other abstract base classes are in collections.abc since Python 3.3. | 4 | 5 |
71,766,568 | 2022-4-6 | https://stackoverflow.com/questions/71766568/convert-string-to-int-before-querying-django-orm | I have a model class Entry(models.Model): maca = models.CharField(max_length=100, blank=True, null=True) This field will accept only numbers (cannot set char field to integer field for business reasons) Now I have to get all entries that have maca greater than 90 What I'm trying to do is this: Entry.objects.filter(mac... | Try this: from django.db.models.functions import Cast from django.db.models import IntegerField Entry.objects.annotate(maca_integer=Cast('maca', output_field=IntegerField())).filter(maca_integer__gte=90) | 4 | 6 |
71,764,027 | 2022-4-6 | https://stackoverflow.com/questions/71764027/numpy-installation-fails-when-installing-with-poetry-on-m1-and-macos | I have a Numpy as a dependency in Poetry pyproject.toml file and it fails to install. error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly error: Command "clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wal... | Make sure you have OpenBLAS installed from Homebrew: brew install openblas Then before running any installation script, make sure you tell your shell environment to use Homebrew OpenBLAS installation export OPENBLAS="$(brew --prefix openblas)" poetry install If you get an error File "/private/var/folders/tx/50wn88yd... | 13 | 17 |
71,710,921 | 2022-4-1 | https://stackoverflow.com/questions/71710921/python-run-multiple-async-functions-simultaneously | I'm essentially making a pinger, that makes has a 2d list, of key / webhook pairs, and after pinging a key, send the response to a webhook the 2d list goes as follows: some_list = [["key1", "webhook1"], ["key2", "webhook2"]] My program is essentially a loop, and I'm not too sure how I can rotate the some_list data, in... | You made your method recursive await do_ping(some_pair), it never ends for the loop in main to continue. I would restructure the application like this: async def do_ping(some_pair): async with aiohttp.ClientSession() as s: while True: tasks = await gen_tasks(s, some_pair) results = await asyncio.gather(*tasks) await as... | 4 | 8 |
71,753,605 | 2022-4-5 | https://stackoverflow.com/questions/71753605/polars-read-csv-with-german-number-formatting | Is there a possibility in polars to read in csv with german number formatting like it is possible in pandas.read_csv() with the parameters "decimal" and "thousands" | Currently, the Polars read_csv method does not expose those parameters. However, there is an easy workaround to convert them. For example, with this csv, allow Polars to read the German-formatted numbers as utf8. import polars as pl my_csv = b"""col1\tcol2\tcol3 1.234,5\tabc\t1.234.567 9.876\tdef\t3,21 """ df = pl.read... | 4 | 5 |
71,759,316 | 2022-4-5 | https://stackoverflow.com/questions/71759316/easily-convert-string-column-to-pl-datetime-in-polars | Consider a Polars data frame with a column of str type that indicates the date in the format '27 July 2020'. I would like to convert this column to the polars.datetime type, which is distinct from the Python standard datetime. import polars as pl from datetime import datetime df = pl.DataFrame({ "id": [1, 2], "event_da... | The easiest way to convert strings to Date/Datetime is to use Polars' own functions: .str.to_date() .str.to_datetime() df.with_columns( pl.col("event_date").str.to_datetime("%d %B %Y") ) shape: (2, 2) ┌─────┬─────────────────────┐ │ id ┆ event_date │ │ --- ┆ --- │ │ i64 ┆ datetime[μs] │ ╞═════╪═════════════════════╡... | 25 | 45 |
71,758,283 | 2022-4-5 | https://stackoverflow.com/questions/71758283/how-is-python-polars-treating-the-index | I want to try out polars in Python so what I want to do is concatenate several dataframes that are read from jsons. When I change the index to date and have a look at lala1.head() I see that the column date is gone, so I basically lose the index. Is there a better solution or do I need to sort by date, which basically ... | Polars intentionally eliminates the concept of an index. From the "Coming from Pandas" section in the User Guide: Polars aims to have predictable results and readable queries, as such we think an index does not help us reach that objective. Indeed, the from_pandas method ignores any index. For example, if we start wi... | 7 | 12 |
71,737,836 | 2022-4-4 | https://stackoverflow.com/questions/71737836/how-to-use-polars-with-plotly-without-converting-to-pandas | I would like to replace Pandas with Polars but I was not able to find out how to use Polars with Plotly without converting to Pandas. I wonder if there is a way to completely cut Pandas out of the process. Consider the following test data: import polars as pl import numpy as np import plotly.express as px df = pl.DataF... | Yes, no need for converting to a Pandas dataframe. Someone (sa-) has requested supporting a better option here and included a workaround for it. "The workaround that I use right now is px.line(x=df["a"], y=df["b"]), but it gets unwieldy if the name of the data frame is too big" For the OP's code example, the approach... | 12 | 12 |
71,722,882 | 2022-4-3 | https://stackoverflow.com/questions/71722882/how-do-you-print-the-django-sql-query-for-an-aggregation | If I have a django queryset print(queryset.query) shows me the SQL statement so I can validate it. But with aggregations they never return a queryset. How do you print those queries out. I guess I can turn on debug logging for the ORM and find them that way but it seems like I should be able to get it right before the ... | You can use connection.queries after your aggregation query. Example: ... from django.db import connection def your_view(request): # Your view logic and aggregate queryset print(connection.queries) return render(request, 'index.html', {}) The output is a dictionary of SQL queries that you entered into the database. | 9 | 3 |
71,751,434 | 2022-4-5 | https://stackoverflow.com/questions/71751434/pylance-type-of-pandas-method-is-partially-unknown | If I try to validate code that uses pandas methodes with pylance in strict mode, I get a validation error. import pandas as pd ser: pd.Series[float] = pd.Series([.1, .2, .5, .3]) print(ser.max()) Pylance in strict mode returns the error: Type of "max" is partially unknown Am I doing something wrong? Can I avoid this... | According to pyright documentation, one can turn off this specific check by creating pyrightconfig.json file in the same project folder with the next content: { "reportUnknownMemberType":"none", } So you can be still in strict mode, but with one type of checks disabled. | 6 | 2 |
71,758,114 | 2022-4-5 | https://stackoverflow.com/questions/71758114/python-list-comprehension-with-complex-data-structures | I'm trying to flatten some mixed arrays in Python using LC. I'm having some trouble figuring out how to structure it. Here's the array's i'm trying to flatten arr_1 = [1, [2, 3], 4, 5] arr_2 = [1,[2,3],[[4,5]]] I tried this methods for arr_1 but get "TypeError: 'int' object is not iterable" print([item if type(items) ... | Using an internal stack and iter's second form to simulate a while loop: def flatten(obj): return [x for stack in [[obj]] for x, in iter(lambda: stack and [stack.pop()], []) if isinstance(x, int) or stack.extend(reversed(x))] print(flatten([1, [2, 3], 4, 5])) print(flatten([1, [2, 3], [[4, 5]]])) print(flatten([1, [2, ... | 6 | 19 |
71,718,167 | 2022-4-2 | https://stackoverflow.com/questions/71718167/importerror-cannot-import-name-escape-from-jinja2 | I am getting the error ImportError: cannot import name 'escape' from 'jinja2' When trying to run code using the following requirements.txt: chart_studio==1.1.0 dash==2.1.0 dash_bootstrap_components==1.0.3 dash_core_components==2.0.0 dash_html_components==2.0.0 dash_renderer==1.9.1 dash_table==5.0.0 Flask==1.1.2 matpl... | Jinja is a dependency of Flask and Flask V1.X.X uses the escape module from Jinja, however recently support for the escape module was dropped in newer versions of Jinja. To fix this issue, simply update to the newer version of Flask V2.X.X in your requirements.txt where Flask no longer uses the escape module from Jinja... | 136 | 189 |
71,703,734 | 2022-4-1 | https://stackoverflow.com/questions/71703734/how-to-upgrade-version-of-pyenv-on-ubuntu | I wanted to install python 3.10 but that version is not available on pyenv version list. checked by pyenv install --list. People suggested to upgrade pyenv that but I do not see help related to updating pyenv. | pyenv isn't really 'installed' in a traditional sense, it's just a git checkout. All you have to do to update is cd ~/.pyenv git pull That also updates the list of available python versions. | 22 | 40 |
71,674,202 | 2022-3-30 | https://stackoverflow.com/questions/71674202/how-do-i-make-mypy-recognize-non-nullable-orm-attributes | Mypy infers ORM non-nullable instance attributes as optionals. Filename: test.py from sqlalchemy.orm import decl_api, registry from sqlalchemy import BigInteger, Column, String mapper_registry = registry() class Base(metaclass=decl_api.DeclarativeMeta): __abstract__ = True registry = mapper_registry metadata = mapper_r... | I had the same question when evaluating a nullable=False column with mypy. One of my teammates found the answer in the SqlAlchemy docs: https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html#introspection-of-columns-based-on-typeengine The types are by default always considered to be Optional, even for the primary... | 6 | 1 |
71,679,094 | 2022-3-30 | https://stackoverflow.com/questions/71679094/python-vs-javascript-execution-time | I tried solving Maximum Subarray using both Javascript(Node.js) and Python, with brute force algorithm. Here's my code: Using python: from datetime import datetime from random import randint arr = [randint(-1000,1000) for i in range(1000)] def bruteForce(a): l = len(a) max = 0 for i in range(l): sum = 0 for j in range(... | Python is not per se slower than Javascript, it depends on the implementation. Here the results comparing node and PyPy which also uses JIT: > /pypy39/python brute.py 109.8594 ms N= 10000 result= 73682 > node brute.js 167.4442000091076 ms N= 10000 result= 67495 So we could even say "python is somewhat faster" ... And ... | 12 | 19 |
71,708,147 | 2022-4-1 | https://stackoverflow.com/questions/71708147/mlflow-tracking-ui-not-showing-experiments-on-local-machine-laptop | I am a beginner in mlflow and was trying to set it up locally using Anaconda 3. I have created a new environment in anaconda and install mlflow and sklearn in it. Now I am using jupyter notebook to run my sample code for mlflow. ''' import os import warnings import sys import pandas as pd import numpy as np from sklear... | Where do you run mlflow ui command? I think if you pass tracking ui path in the arguments, it would work: mlflow ui --backend-store-uri file:///Users/Swapnil/Documents/LocalPython/MLFLowDemo/mlrun | 9 | 5 |
71,716,936 | 2022-4-2 | https://stackoverflow.com/questions/71716936/how-to-log-stacktrace-in-json-format-python | Im using structlog for logging and want the exception/stacktrace to be printed in json format. Currently its not formatted and in string format which is not very readable { "message": "Error info with an exc", "timestamp": "2022-03-31T13:32:33.928188+00:00", "logger": "__main__", "level": "error", "exception": "Traceba... | Here is a snippet which does that: https://gitlab.com/-/snippets/2284049 It will eventually land directly in structlog. edit: https://github.com/hynek/structlog/pull/407 has been merged and will be part of v22.1. | 4 | 5 |
71,712,258 | 2022-4-1 | https://stackoverflow.com/questions/71712258/error-could-not-build-wheels-for-backports-zoneinfo-which-is-required-to-insta | The Heroku Build is returning this error when I'm trying to deploy a Django application for the past few days. The Django Code and File Structure are the same as Django's Official Documentation and Procfile is added in the root folder. Log - -----> Building on the Heroku-20 stack -----> Determining which buildpack to u... | Avoid installing backports.zoneinfo when using python >= 3.9 Edit your requirements.txt file FROM: backports.zoneinfo==0.2.1 TO: backports.zoneinfo;python_version<"3.9" OR: backports.zoneinfo==0.2.1;python_version<"3.9" You can read more about this here and here | 72 | 155 |
71,688,065 | 2022-3-31 | https://stackoverflow.com/questions/71688065/generic-requirements-txt-for-tensorflow-on-both-apple-m1-and-other-devices | I have a new MacBook with the Apple M1 chipset. To install tensorflow, I follow the instructions here, i.e., installing tensorflow-metal and tensorflow-macos instead of the normal tensorflow package. While this works fine, it means that I can't run the typical pip install -r requirements.txt as long as we have tensorfl... | According to this post Is there a way to have a conditional requirements.txt file for my Python application based on platform? You can use conditionals on your requirements.txt, thus tensorflow==2.8.0; sys_platform != 'darwin' or platform_machine != 'arm64' tensorflow-macos==2.8.0; sys_platform == 'darwin' and platform... | 6 | 8 |
71,673,404 | 2022-3-30 | https://stackoverflow.com/questions/71673404/importerror-cannot-import-name-unicodefun-from-click | When running our lint checks with the Python Black package, an error comes up: ImportError: cannot import name '_unicodefun' from 'click' (/Users/robot/.cache/pre-commit/repo3u71ccm2/py_env-python3.9/lib/python3.9/site-packages/click/init.py)` In researching this, I found the following related issues: ImportError: c... | This has been fixed by Black 22.3.0. Versions before that won't work with click 8.1.0. Incompatible with click 8.1.0 (ImportError: cannot import name '_unicodefun' from 'click') #2964 E.g.: black.yml python-version: 3.8 - name: install black run: | - pip install black==20.8b1 + pip install black==22.3.0 - name: run bl... | 184 | 240 |
71,695,387 | 2022-3-31 | https://stackoverflow.com/questions/71695387/connecting-to-a-different-google-drive-than-the-one-logged-into-google-colab | recently colab removed the ability to connect to google drive from different accounts other than the one you were logged into in google drive. There was a workaround someone posted with the following code which worked great, until now... !apt-get install -y -qq software-properties-common python-software-properties modu... | edit: do it all in one cell without printing unneeded information edit2 april 28th 2022: changed !sudo apt install google-drive-ocamlfuse >/dev/null 2>&1 to a new line because sudo apt update was failing on colab and preventing it from running the install line. !sudo echo -ne '\n' | sudo add-apt-repository ppa:alessand... | 4 | 11 |
71,745,931 | 2022-4-5 | https://stackoverflow.com/questions/71745931/restrictedpython-call-other-functions-within-user-specified-code | Using Yuri Nudelman's code with the custom _import definition to specify modules to restrict serves as a good base but when calling functions within said user_code naturally due to having to whitelist everything is there any way to permit other user defined functions to be called? Open to other sandboxing solutions alt... | First of all, the replacement for the __import__ built-in is implemented incorrectly. That built-in is supposed to return the imported module, not mutate the globals to include it: Python 3.9.12 (main, Mar 24 2022, 13:02:21) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>... | 6 | 7 |
71,737,316 | 2022-4-4 | https://stackoverflow.com/questions/71737316/problems-installing-lxml-on-m1-mac | So, I'm having the classic trouble install lxml. Initially I was just pip installing, but when I tried to free up memory using Element.clear() I was getting the following error: Python(58695,0x1001b4580) malloc: *** error for object 0x600000bc3f60: pointer being freed was not allocated I thought this must be because l... | It turned out that installing lxml with a simple pip install was working fine. The reason for my malloc error was the fact that I was trying to clear the element before the end tag had been seen. Turns out this isn't possible and you need to wait for the end tag even if you already know you aren't interested in the ele... | 8 | -1 |
71,758,620 | 2022-4-5 | https://stackoverflow.com/questions/71758620/error-installing-python-3-7-6-using-pyenv-on-new-macbook-pro-m1-in-os-12-3 | I am struggling to install python version 3.7.6 using pyenv on my new macbook pro M1 running on mac os 12.3.1. My configuration $ clang -v Apple clang version 13.1.6 (clang-1316.0.21.2) Target: arm64-apple-darwin21.4.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin $ pyenv install 3.7.6 ... | Finally this patch works in installing 3.7.6 on macbook m1 using pyenv. To install python 3.7.6 version in mac os 12+ , M1 chip, apple clang version 13+ using pyenv, create a file anywhere in your local and call it python-3.7.6-m1.patch and copy the contents(below) to that file and save it. diff --git a/configure b/c... | 5 | 3 |
71,691,598 | 2022-3-31 | https://stackoverflow.com/questions/71691598/how-to-run-python-as-x86-with-rosetta2-on-arm-macos-machine | I have a python app with downstream dependencies on dynamic libraries that are available as X86 only. The app runs on a X86 MacOS machine, but on a ARM MacOS machine it fails with an ImportError. I've run lipo -archs on the libraries and they are x86_64 only. I have Python running in a virtualenv and it is a universal ... | Looks like the only way to do this is to install a X86 version of python. I found a how to guide here - https://towardsdatascience.com/how-to-use-manage-multiple-python-versions-on-an-apple-silicon-m1-mac-d69ee6ed0250 but couldn't quite get the pyenv build part to work. So in the Rosetta i386 terminal I brew86 installe... | 11 | 5 |
71,709,229 | 2022-4-1 | https://stackoverflow.com/questions/71709229/vscode-debugger-can-not-import-queue-due-to-shadowing | When I try to run any python code in debug mode using VScode, I got an error message saying: 42737 -- /home/<username>/Desktop/development/bopi/experiment_handler.py .vscode-server/extensions/ms-python.python-2022.4.0/pythonFiles/lib/python/debugpy/launcher 4 Traceback (most recent call last): File "/usr/lib/python2.7/... | Downgrading my Python extension in Visual Studio Code to v2022.2.1924087327 worked for me. Elevating @Onur Berk's comment below as part of the answer: Its is very easy to downgrade the python extension, just click 'extensions' and find the Python extension and select it. Rather than clicking 'uninstall' click the arro... | 12 | 25 |
71,753,428 | 2022-4-5 | https://stackoverflow.com/questions/71753428/how-to-get-shap-values-for-each-class-on-a-multiclass-classification-problem-in | I have the following dataframe: import pandas as pd import random import xgboost import shap foo = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10], 'var1':random.sample(range(1, 100), 10), 'var2':random.sample(range(1, 100), 10), 'var3':random.sample(range(1, 100), 10), 'class': ['a','a','a','a','a','b','b','c','c','c']}) I... | By doing some research and with the help of this post and @Alessandro Nesti 's answer, here is my solution: foo = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10], 'var1':random.sample(range(1, 100), 10), 'var2':random.sample(range(1, 100), 10), 'var3':random.sample(range(1, 100), 10), 'class': ['a','a','a','a','a','b','b','c... | 5 | 2 |
71,746,654 | 2022-4-5 | https://stackoverflow.com/questions/71746654/how-do-i-add-selenium-chromedriver-to-an-aws-lambda-function | I am trying to host a webscraping function on aws lambda and am running into webdriver errors for selenium. Could someone show me how you go about adding the chromedriver.exe file and how do you get the pathing to work in AWS Lambda function. This is the portion of my function that has to do with selenium, from seleniu... | I've been struggling adding selenium to the aws lambda for last couple days. I have a web scraping function (uses selenium and google api) which extracts data from a website and writes the outputs to a google spreadsheet. Let me explain what i did step by step and how i finally succeeded so you don't have to deal with ... | 8 | 19 |
71,672,179 | 2022-3-30 | https://stackoverflow.com/questions/71672179/the-file-is-not-a-zip-file-error-for-the-output-of-git-show-by-gitpython | The script to reproduce the issue Save this code as a shell script and run it. The code should report the File is not a zip file error. #!/bin/bash set -eu mkdir foo cd foo pip install --user GitPython echo foo > a zip a.zip a # -t option validates the zip file. # See https://unix.stackexchange.com/questions/197127/tes... | Update GitPython version 3.1.28 (not yet released) should add the strip_newline_in_stdout option. If the option is set to False, the trailing \n of the stdout of any commands run by repo.git.foobar will be preserved. raw = repo.git.show("HEAD~:image.kra", strip_newline_in_stdout=False) Original answer It seems that th... | 4 | 5 |
71,731,988 | 2022-4-4 | https://stackoverflow.com/questions/71731988/sum-of-the-maximums-of-all-subarrays-multiplied-by-their-lengths-in-linear-ti | Given an array I should compute the following sum in linear time: My most naive implementation is O(n3): sum_ = 0 for i in range(n): for j in range(n, i, -1): sum_ += max(arr[i:j]) * (j-i) I have no idea what to do. I have tried many algorithms but they were at best O(n*log(n)), but I should solve it in linear time. ... | Keep a stack of (indices of) non-increasing values. So before appending the new value, pop smaller ones. Whenever you pop one, add its contribution to the total. def solution(arr): arr.append(float('inf')) I = [-1] total = 0 for i in range(len(arr)): while arr[i] > arr[I[-1]]: j = I.pop() a = j - I[-1] b = i - j total ... | 4 | 6 |
71,706,506 | 2022-4-1 | https://stackoverflow.com/questions/71706506/why-does-open3d-visualization-disappear-when-i-left-click-the-window | I try to write a simple application in python which views a 3d mesh on the right and have some user input on the left in a single window. I use a SceneWidget to visualize a mesh and add it to a horizontal gui element. I also add a filepicker to that gui element and then add the gui element to the window. So far so good... | Finally I found a solution: Adding a Scenewidget to a gui container doesn't seem to work. But encapsulating it inside a frame and move it to the right side and add it directly to the window works. _widget3d.frame = gui.Rect(500, w.content_rect.y, 900, w.content_rect.height) Creating a frame for the gui in a similar way... | 5 | 6 |
71,757,871 | 2022-4-5 | https://stackoverflow.com/questions/71757871/why-is-sys-getsizeof-reporting-bigger-values-for-smaller-lists | I don't understand how sizeof behaves differently when both the lists are created like literals. I expect the output of the second sizeof to be equal or less than that of the first sizeof, not greater! >>> sys.getsizeof([0,1,2,3,4,5,6]) 120 >>> sys.getsizeof([0,1,2,3,4,5]) 152 | Short story: It's about overallocation and avoiding useless overallocation. Your cases have 6 and 7 elements. In both cases, Python first calculates 12 as the number of spots to allocate. The purpose of overallocation is to allow fast future extensions with more elements, so Python tries to guess what will happen in th... | 8 | 11 |
71,699,098 | 2022-3-31 | https://stackoverflow.com/questions/71699098/optuna-lightgbm-lightgbmpruningcallback | I am getting an error on my modeling of lightgbm searching for optimal auc. Any help would be appreciated. import optuna from sklearn.model_selection import StratifiedKFold from optuna.integration import LightGBMPruningCallback def objective(trial, X, y): param = { "objective": "binary", "metric": "auc", "verbosity": -... | Your objective function returns two values but you specify only one direction when creating the study. Try this: study = optuna.create_study(directions=["minimize", "maximize"], study_name="LGBM Classifier") | 5 | 3 |
71,757,452 | 2022-4-5 | https://stackoverflow.com/questions/71757452/is-it-possible-to-properly-type-hint-the-filterm-function-in-python | I'm currently self-studying functional programming by writing a monad library in python. And I'm having trouble with type hinting. So for example, there is a function filterM in Haskell with signature filterM :: (a -> m Bool) -> [a] -> m [a] Ideally, if python can pattern match "subtypes" of a TypeVar by putting a bra... | Currently, what you want cannot be done. You'll have to make a plan that doesn't require it. | 5 | 4 |
71,756,172 | 2022-4-5 | https://stackoverflow.com/questions/71756172/how-to-unpin-pinned-package-in-conda-mamba | I have a conda environment that has a package pinned as follows: Pinned packages: - python 3.8.* - bcbio-gff 0.6.7.* - snakemake 6.7.0.* How do I remove the pin for one of the pinned packages, just using command line conda / mamba? I've tried conda update snakemake but that doesn't remove the pin. I can change the pin... | This is only a suboptimal answer, but it's the best I could find so far: You need to manually remove the pinned package from a config file called pinned which you can find in CONDA_PATH/base/envs/ENV_NAME/conda-meta/pinned In my case I had to do: vim /usr/local/Caskroom/mambaforge/base/envs/nextstrain/conda-meta/pinne... | 6 | 5 |
71,754,506 | 2022-4-5 | https://stackoverflow.com/questions/71754506/viewing-pytorch-weights-from-a-pth-file | I have a .pth file created with Pytorch with weights. How would I be able to view the weights from this file? I tried this code to load and view but it was not working (as a newbie, I might be entirely wrong)- import torch import torchvision.models as models torch.save('weights\kharif_crops_final.pth') models.load_stat... | import torch model = torch.load('path') print(model) (Verify and confirm) | 5 | 5 |
71,753,572 | 2022-4-5 | https://stackoverflow.com/questions/71753572/importerror-cannot-import-name-callable-from-traitlets | I can run jupyter notebook, but when I try to open a jupyter file I get the following error on my browser 500 : Internal Server Error in the console, I get this error message To access the notebook, open this file in a browser: file:///C:/Users/Bruno/AppData/Roaming/jupyter/runtime/nbserver-23164-open.html Or copy and... | The problem was solved by installing traitlets v5.1.1 and traitlets-widget v5.5.0 | 5 | 6 |
71,743,450 | 2022-4-4 | https://stackoverflow.com/questions/71743450/how-to-cache-python-dependecies-in-gitlab-ci-cd-without-using-venv | I am trying to use cache in my .gitlab-ci.yml file, but the time only increases (testing by adding blank lines). I want to cache python packages I install with pip. Here is the stage where I install and use these packages (other stages uses Docker): image: python:3.8-slim-buster variables: PIP_CACHE_DIR: "$CI_PROJECT_D... | PIP_CACHE_DIR is a pip feature that can be used to set the cache dir. The second answer to this question explains it. There may be some disagreement on this, but I think that for something like pip packages or node modules, it is quicker to download them fresh for each pipeline. When the packages are cached by Gitlab b... | 12 | 6 |
71,689,095 | 2022-3-31 | https://stackoverflow.com/questions/71689095/how-to-solve-the-pytorch-runtimeerror-numpy-is-not-available-without-upgrading | I am running a simple CNN using Pytorch for some audio classification on my Raspberry Pi 4 on Python 3.9.2 (64-bit). For the audio manipulation needed I am using librosa. librosa depends on the numba package which is only compatible with numpy version <= 1.20. When running my code, the line spect_tensor = torch.from_nu... | Just wanted to give an update on my situation. I downgraded torch to version 0.9.1 which solved the original issue. Now OpenBLAS is throwing a warning because of an open MPLoop. But for now my code is up and running. | 29 | 6 |
71,737,743 | 2022-4-4 | https://stackoverflow.com/questions/71737743/how-can-i-change-playback-speed-of-an-audio-file-in-python-whilst-it-is-playing | I've done alot of searching to try and find a way to achieve this but the solutions I've found either don't do what I need or I don't understand them. I'm looking for a way of playing a sound in python (non-blocking) that allows me to change the playback speed in real time, as it's playing, with no gaps or cutouts. Cha... | I've found a solution, using python-mpv, a wrapper for mpv.io from pynput.keyboard import Key, Listener import mpv speed=1 #quick function to change speed via keyboard. def on_press(key): global speed if key.char == 'f' : speed=speed-0.1 player.speed=speed if key.char == 'g' : speed=speed+0.1 player.speed=speed player ... | 6 | 0 |
71,747,998 | 2022-4-5 | https://stackoverflow.com/questions/71747998/pytorch-assign-values-from-one-mask-to-another-masked-by-itself | I have a mask active that tracks batches that still have not terminated in a recurrent process. It's dimension is [batch_full,], and it's true entries show which elements need to still be used in current step. The recurrent process generates another mask, terminated, which has as many elements as true values in active ... | There are a few solutions, I will also give their speed as measured by timeit, 10k repetitions, on 2021 macbook pro. The simplest solution, taking 0.260s: active[active.clone()] = ~terminated We can use masked_scatter_ inplace operation for abt. 2x speedup (0.136s): active.masked_scatter_( active, ~terminated, ) Out ... | 4 | 5 |
71,747,824 | 2022-4-5 | https://stackoverflow.com/questions/71747824/slicing-2d-python-list | Let's say I have a list: list = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [9, 8, 7, 6]] and I would like to get something like: newList = [[2, 3, 4], ['b', 'c', 'd'], [8, 7, 6]] hence I tried going with this solution print(list[0:][1:]) But I get this output [['a', 'b', 'c', 'd'], [9, 8, 7, 6]] Therefore I tried print(l... | You want the 1 to end element of every row in your matrix. mylist = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [9, 8, 7, 6]] new_list = [row[1:] for row in mylist] | 4 | 5 |
71,735,261 | 2022-4-4 | https://stackoverflow.com/questions/71735261/how-can-i-show-transformation-of-coordinate-grid-lines-in-python | Suppose I have the regular cartesian coordinate system $(x,y)$ and I consider a rectangular mesh region $D$ (split into little squares). I want to see how the domain D would be mapped under a coordinate transform T:(x,y) -> (u(x,y) ,v(x,y) ) in Python? I'm looking for something like this: See here. Could I be advised ... | If I understand you correctly, you want to be able to see a sort of a grid plot of a transformed cartesian space? In that case, maybe something like this, using Numpy and Matplotlib. (You could do the same with just Pillow to draw some lines, but this is more convenient...) EDIT: Following the discussion in the comment... | 4 | 7 |
71,744,729 | 2022-4-4 | https://stackoverflow.com/questions/71744729/how-to-grab-last-row-of-datetime-in-pandas-dataframe | II currently have a very large .csv with 2 million rows. I've read in the csv and only have 2 columns, number and timestamp (in unix). My goal is to grab the last and largest number for each day (eg. 1/1/2021, 1/2/2021, etc.) I have converted unix to datetime and used df.groupby('timestamp').tail(1) but am still not a... | The "problem" lies in the grouper, use .dt.date for correct grouping (assuming your data is already sorted): x = df.groupby(df['timestamp'].dt.date).tail(1) print(x) | 4 | 4 |
71,739,517 | 2022-4-4 | https://stackoverflow.com/questions/71739517/detect-squares-paintings-in-images-and-draw-contour-around-them-using-python | I'm trying to detect and draw a rectangular contour on every painting on for example this image: I followed some guides and did the following: Grayscale conversion Applied median blur Sharpen image Applied adaptive Threshold Applied Morphological Gradient Find contours Draw contours And got the following result: I ... | Here's a simple approach: Obtain binary image. We load the image, grayscale, Gaussian blur, then Otsu's threshold to obtain a binary image. Two pass dilation to merge contours. At this point, we have a binary image but individual separated contours. Since we can assume that a painting is a single large square contour... | 4 | 4 |
71,740,863 | 2022-4-4 | https://stackoverflow.com/questions/71740863/django-celery-error-unrecoverable-error-attributeerrorentrypoint-object-ha | I am perplexed,from a weird error which i have no idea as i am new to celery, this error occurs on just the setup phase, every thing is simply configured as written in the celery doc https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html the tracback is: (env) muhammad@huzaifa:~/Desktop/practice/app$ ce... | You are encountering a new bug with celery, reported here: https://github.com/celery/celery/issues/7409 The workaround you can try is to pin the versions of your dependency for celery to an older version (i.e. before release of the celery bug). For instance, my requirements.txt includes: celery==5.2.3 or on the comman... | 7 | 14 |
71,739,870 | 2022-4-4 | https://stackoverflow.com/questions/71739870/how-to-install-python-2-on-macos-12-3 | macOS 12.3 update drops Python 2 and replaces it with version 3: https://developer.apple.com/documentation/macos-release-notes/macos-12_3-release-notes Python Deprecations Python 2.7 was removed from macOS in this update. Developers should use Python 3 or an alternative language instead. (39795874) I understand we ne... | You can get any Python release, including the last Python 2, from the official download site: https://www.python.org/downloads/release/python-2718/ → macOS 64-bit installer | 48 | 101 |
71,736,573 | 2022-4-4 | https://stackoverflow.com/questions/71736573/how-to-get-the-deepest-list-in-list-with-abstract-element | Here I have some lists with any particular element (a, b, and c) a = [2, 4, [9, 10]] b = [1, 3, 5, 9, [11, 13, 14, 15, [16, 17, 19, 24]]] c = [2, 4, [5, 11, 13, [14, 17, 29, [31, 19]]]] npA = np.array(a, dtype = object) npB = np.array(b, dtype = object) npC = np.array(c, dtype = object) I am trying to get the deepest ... | You can solve this recursively, without numpy: from typing import List def deepest_list(l: List) -> List: last_item = l[-1] if isinstance(last_item, list): return deepest_list(last_item) return l output: deepest_list(c) [31, 19] | 4 | 5 |
71,735,869 | 2022-4-4 | https://stackoverflow.com/questions/71735869/how-to-reduce-number-if-statements-using-dict | I have the following code with multiple cases: def _extract_property_value(selector: Selector) -> str: raw_value = selector.xpath("span[2]") default_value = raw_value.xpath("./text()").get().strip() value_with_a = ', '.join([value.strip() for value in raw_value.xpath("./a /text()").getall()]) value_with_div_and_a = ', ... | We can reduce the number of if statements but without the aid of a dictionary. The code in question unconditionally assigns values to 3 variables. Having done so, those variables are examined to determine which, if any, is to be returned to the caller. However, there are no dependencies between those variables. Therefo... | 6 | 5 |
71,733,837 | 2022-4-4 | https://stackoverflow.com/questions/71733837/how-to-figure-out-correct-headers-of-an-excel-file-programmatically-while-readin | I have a list of excel files (.xlsx,.xls), I'm trying to get headers of each of these files after loaded. Here I have taken a one excel file and loaded into pandas as. pd.read_excel("sample.xlsx") output is: Here we would like to get an header information as per our requirement, here in the attached image the require... | Use: df = pd.read_excel('sample_file.xlsx') #test all rows if previous row is only NaNs m1 = df.shift(fill_value=0).isna().all(axis=1) #test all rows if no NaNs m2 = df.notna().all(axis=1) #chain together and filter all next rows after first match df = df[(m1 & m2).cummax()] #set first row to columns names df = df.set_... | 4 | 4 |
71,729,997 | 2022-4-3 | https://stackoverflow.com/questions/71729997/numpyic-way-to-take-the-first-n-rows-and-columns-out-of-every-m-rows-and-columns | I have a 20 x 20 square matrix. I want to take the first 2 rows and columns out of every 5 rows and columns, which means the output should be a 8 x 8 square matrix. This can be done in 2 consecutive steps as follows: import numpy as np m = 5 n = 2 A = np.arange(400).reshape(20,-1) B = np.asarray([row for i, row in enum... | You can use np.ix_ to retain the elements whose row / column indices are less than 2 modulo 5: import numpy as np m = 5 n = 2 A = np.arange(400).reshape(20,-1) mask = np.arange(20) % 5 < 2 result = A[np.ix_(mask, mask)] print(result) This outputs: [[ 0 1 5 6 10 11 15 16] [ 20 21 25 26 30 31 35 36] [100 101 105 106 110... | 4 | 3 |
71,722,066 | 2022-4-3 | https://stackoverflow.com/questions/71722066/ipykernel-launcher-processes-are-consuming-memory-not-able-to-kill | What are these zombie ipykernel_launcher process in my machine, which are hogging to much memory: This is output of htop command, but I ps for those processes,(to kill them) I do not see them as: ps -ef|grep ipykernel Not sure, how to get rid of these memory hogs! | The reason why you're seeing all these processes in htop and not with ps is that htop is showing threads (see https://serverfault.com/questions/24198/why-does-htop-show-lots-of-apache2-processes-by-ps-aux-doesnt). Type "-H" inside htop to toggle showing threads. Automatically stop idle kernels Concerning Jupyter notebo... | 4 | 5 |
71,724,842 | 2022-4-3 | https://stackoverflow.com/questions/71724842/gitlab-ci-python-black-formatter-says-would-reformat-whereas-running-black-doe | When I run GitLab CI on this commit with this gitlab-ci.yml: stages: - format - test black_formatting: image: python:3.6 stage: format before_script: # Perform an update to make sure the system is up to date. - sudo apt-get update --fix-missing # Download miniconda. - wget -q https://repo.continuum.io/miniconda/Minicon... | The miniconda environment in the GitLab CI used python black version: black, 22.3.0 (compiled: yes) Whereas the local environment used python black version: black, version 19.10b0 Updating the local black version, pushing the formatted code according to the latest python black version, and running the GitLab CI on th... | 12 | 12 |
71,724,403 | 2022-4-3 | https://stackoverflow.com/questions/71724403/crop-an-image-in-pil-using-the-4-points-of-a-rotated-rectangle | I have a list of four points of a rotated rectangle in the form of: points = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] I can crop in PIL using: img.crop((x1, y1, x2, y2)) But this doesn't work with a rotated rectangle. Just to clarify I want the resulting cropped image to be rotated so the cropped area becomes a non-r... | If you start with this image: You can do it like this using a QuadTransform: #!/usr/bin/env python3 from PIL import Image, ImageTransform # Open starting image and ensure RGB im = Image.open('a.png').convert('RGB') # Define 8-tuple with x,y coordinates of top-left, bottom-left, bottom-right and top-right corners and a... | 4 | 4 |
71,717,020 | 2022-4-2 | https://stackoverflow.com/questions/71717020/how-do-i-fill-nan-values-with-different-random-numbers-on-python | I want to replace the missing values from a column with people's ages (which also contains numerical values, not only NaN values) but everything I've tried so far either doesn't work how I want it to or it doesn't work at all. I wish to apply a random variable generator which follows a normal distribution using the mea... | Series.fillna can accept a Series, so generate a random array of size len(df_travel): rng = np.random.default_rng(0) mu = df_travel['Age'].mean() sd = df_travel['Age'].std() filler = pd.Series(rng.normal(loc=mu, scale=sd, size=len(df_travel))) df_travel['Age'] = df_travel['Age'].fillna(filler) | 4 | 5 |
71,713,961 | 2022-4-2 | https://stackoverflow.com/questions/71713961/how-to-deconstruct-a-python-like-function-call | Suppose I had a function call as a string, like "log(2, floor(9.4))". I want to deconstruct the call in a way that allows me to access the function name and arguments for the firstmost call and accurately deducts whether a function call as an argument is an argument or not. For example, the arguments when deconstructin... | You can use the ast module: import ast data = "log(2, floor(9.4))" parse_tree = ast.parse(data) # ast.unparse() is for 3.9+ only. # If using an earlier version, use the astunparse package instead. result = [ast.unparse(node) for node in parse_tree.body[0].value.args] print(result) This outputs: ['2', 'floor(9.4)'] I ... | 4 | 9 |
71,701,041 | 2022-4-1 | https://stackoverflow.com/questions/71701041/jaxxla-vs-numballvm-reduction | Is it possible to make CPU only reductions with JAX comparable to Numba in terms of computation time? The compilers come straight from conda: $ conda install -c conda-forge numba jax Here is a 1-d NumPy array example import numpy as np import numba as nb import jax as jx @nb.njit def reduce_1d_njit_serial(x): s = 0 fo... | When performing these kinds of microbenchmarks with JAX, you have to be careful to ensure you're measuring what you think you're measuring. There are some tips in the JAX Benchmarking FAQ. Implementing some of these best practices, I find the following for your benchmarks: import jax.numpy as jnp # Native jit-compiled ... | 4 | 7 |
71,686,960 | 2022-3-31 | https://stackoverflow.com/questions/71686960/typeerror-credentials-need-to-be-from-either-oauth2client-or-from-google-auth | I'm new to python and currently is working on a project that requires me to export pandas data frame from google collab to a google spreadsheet with multiple tabs. Previously when I run this specific code, there are no errors but then now it shows an error like this: TypeError Traceback (most recent call last) <ipytho... | I had the same problem today and found this answer: https://github.com/burnash/gspread/issues/1014#issuecomment-1082536016 I finally solved it by replacing the old code with this one: from google.colab import auth auth.authenticate_user() import gspread from google.auth import default creds, _ = default() gc = gspread.... | 17 | 47 |
71,707,006 | 2022-4-1 | https://stackoverflow.com/questions/71707006/how-to-use-pt-file | I'm trying to make a currency recognition model and I did so using a dataset on kaggle and colab using yolov5 and I exactly carried out the steps explained on yolov5 github. At the end, I downloaded a .pt file which has the weights of the model and now I want to use it in python file to detect and recognize currency . ... | If you want to read trained parameters from .pt file and load it into your model, you could do the following. file = "model.pt" model = your_model() model.load_state_dict(torch.load(file)) # this will automatically load the file and load the parameters into the model. before calling load_state_dict(), be sure that the... | 6 | 5 |
71,705,240 | 2022-4-1 | https://stackoverflow.com/questions/71705240/how-to-convert-boolean-column-to-0-and-1-by-using-pd-get-dummies | I want to convert all boolean columns in my pandas dataframe into 0 and 1 by using pd.get_dummies. However, the boolean values stay the same after the get_dummies function. For example: tmp = pd.DataFrame([ ['green' , True], ['red' , False], ['blue' , True]]) tmp.columns = ['color', 'class'] pd.get_dummies(tmp) # I hav... | For processing boolean columns convert them to strings (here are converted all columns): print (pd.get_dummies(tmp.astype(str))) color_blue color_green color_red class_False class_True 0 0 1 0 0 1 1 0 0 1 1 0 2 1 0 0 0 1 Of convert only boolean: print (pd.get_dummies(tmp.astype({'class':'str'}))) color_blue color_gree... | 8 | 1 |
71,690,620 | 2022-3-31 | https://stackoverflow.com/questions/71690620/debugging-python-program-doesnt-work-after-updating-to-vs-code-1-66-0 | Today (2022/3/31) I let the auto-update function update my VS Code to latest version 1.66.0 on Windows. After that, my normal debugging process doesn't work any more: when I press F5, the debugging control panel flashes and disappears immediately, nothing else happends. I couldn't find any useful error message on outpu... | You can try to reinstall the Python extension or install the older version of the Python extension. Delete the deprecated configuration of python.pythonPath in your settings.json. | 8 | 3 |
71,701,629 | 2022-4-1 | https://stackoverflow.com/questions/71701629/importerror-no-module-named-thread | Compiling python2 in vscode gives an error. But when I compile python3 it succeeds. print('test') returns: ImportError: No module named _thread PS C:\source> c:; cd 'c:\source'; & 'C:\Python27\python.exe' 'c:\Users\keinblue\.vscode\extensions\ms-python.python-2022.4.0\pythonFiles\lib\python\debugpy\launcher' '52037' '... | There is an issue with the vscode python extension version 2022.4.0 just downgrade to version 2022.2.1924087327 and it will work as it works for me now Just follow these steps: Go to extensions. Click on Gear Icon for the installed extension Click on Install Another Version select the version you wish to install | 14 | 36 |
71,697,019 | 2022-3-31 | https://stackoverflow.com/questions/71697019/generating-list-of-every-combination-without-duplicates | I would like to generate a list of combinations. I will try to simplify my problem to make it understandable. We have 3 variables : x : number of letters k : number of groups n : number of letters per group I would like to generate using python a list of every possible combinations, without any duplicate knowing that... | There will certainly be more sophisticated/efficient ways of doing this, but here's an approach that works in a reasonable amount of time for your example and should be easy enough to adapt for other cases. It generates unique teams and unique combinations thereof, as per your specifications. from itertools import comb... | 8 | 2 |
71,690,992 | 2022-3-31 | https://stackoverflow.com/questions/71690992/cannot-install-latest-version-of-numpy-1-22-3 | I am trying to install the latest version of numpy, the 1.22.3, but it looks like pip is not able to find this last release. I know I can install it locally from the source code, but I want to understand why I cannot install it using pip. PS: I have the latest version of pip, the 22.0.4 ERROR: Could not find a version ... | Please check your Python version. Support for Python 3.7 is dropped since Numpy 1.22.0 release. [source] | 8 | 14 |
71,683,346 | 2022-3-30 | https://stackoverflow.com/questions/71683346/find-element-by-the-value-attribute-using-selenium-python | I`m trying to find a specific element in the web page. It has to be by a specific number inside the text in value...In this case, I need to find the element by the number 565657 (see outer HTML below) I've tried via xpath: ("//*[contains(text(),'565657')]") and also ("//input[@value='565657']") but it did not work. Can... | To locate the element through the value attribute i.e. 565657 you can use either of the following Locator Strategies: Using css_selector: element = driver.find_element(By.CSS_SELECTOR, "input[value*='565657']") Using xpath: element = driver.find_element(By.XPATH, "//input[contains(@vlaue, '565657')]") To locate i... | 5 | 5 |
71,677,490 | 2022-3-30 | https://stackoverflow.com/questions/71677490/how-to-properly-include-data-folder-to-python-package | I'm building a small python package that I deploy to our internal pypi server to be easily installable with pip. I'm using setup.py to build the tar.gz archive to upload there. And I need to include some additional data - to be more specific, I use nltk in my project and I want to ship the package with specific nltk da... | You can simply specify the relative path to the data you want to include. You need to put an __init__.py-file in both subfolders though, but then it should work. package_data={'my_pkg' :['my_pkg/resources/nltk_data/*']} To use the data in your script, use importlib (for example importlib.read_text) to open your desire... | 5 | 6 |
71,671,866 | 2022-3-30 | https://stackoverflow.com/questions/71671866/python-what-is-the-difference-between-lambda-and-lambda | I know the function of lambda: and lambda var: , but what does lambda_: means acutally? | lambda_ is just a variable name, like any other. Like foo or x. If you saw: lambda_: Something Then that is actually a variable annotation, for type hints, so the same as: num: int num = 0 | 6 | 5 |
71,670,608 | 2022-3-30 | https://stackoverflow.com/questions/71670608/how-to-import-subrequest-pytest | In the following code, the request has the type of <class '_pytest.fixtures.SubRequest'>. I want to add type hint to the parameter request. @pytest.fixture def dlv_service(request: SubRequest): # How to import SubRequest? print(type(request), request) filepath = pathlib.Path(request.node.fspath.strpath) f = filepath.wi... | I've found one on the internet, hope this will help. from _pytest.fixtures import SubRequest I think it's worth trying, but not sure whether it could work, sorry. | 11 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.