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
72,621,273
2022-6-14
https://stackoverflow.com/questions/72621273/numba-parallelization-with-prange-is-slower-when-used-more-threads
I tried a simple code to parallelize a loop with numba and prange. But for some reason when I use more threads instead of going faster it gets slower. Why is this happening? (cpu ryzen 7 2700x 8 cores 16 threads 3.7GHz) from numba import njit, prange,set_num_threads,get_num_threads @njit(parallel=True,fastmath=True) de...
This is totally normal. Numba needs to create threads and distribute the work between them so they can execute the computation in parallel. Numba can use different threading backends. The default if generally OpenMP and the default OpenMP implementation should be IOMP (OpenMP runtime of ICC/Clang) which try to create t...
6
6
72,580,483
2022-6-10
https://stackoverflow.com/questions/72580483/aws-cdk-reference-existing-image-on-ecr
New to AWS CDK and I'm trying to create a load balanced fargate service with the construct ApplicationLoadBalancedFargateService. I have an existing image on ECR that I would like to reference and use. I've found the ecs.ContainerImage.from_ecr_repository function, which I believe is what I should use in this case. How...
You are looking for from_repository_attributes() to create an instance of IRepository from an existing ECR repository.
8
4
72,620,119
2022-6-14
https://stackoverflow.com/questions/72620119/turn-off-corner-rounding-in-matplotlib-plot-with-thicker-lines
Question: Is it possible to turn off "corner rounding" when using plot in matplotlib? Setup: I am trying to present a complicated nonsmooth function in a presentation. As a default (understandably) matplotlib rounds corners. (This is especially visible when the linewidth is increased.) I need more linewidth so the plo...
You can specify a JoinStyle: plt.plot(x, y, linewidth=10, solid_joinstyle='miter')
4
5
72,619,143
2022-6-14
https://stackoverflow.com/questions/72619143/unable-to-import-psutil-on-m1-mac-with-miniforge-mach-o-file-but-is-an-incomp
I'm using a miniforge environment on an M1 mac, and unable to import psutil: ImportError: dlopen(/Users/caspsea/miniforge3/lib/python3.9/site-packages/psutil/_psutil_osx.cpython-39-darwin.so, 0x0002): tried: '/Users/caspsea/miniforge3/lib/python3.9/site-packages/psutil/_psutil_osx.cpython-39-darwin.so' (mach-o file, bu...
Have you tried: pip uninstall psutil followed by: pip install --no-binary :all: psutil
6
18
72,609,159
2022-6-13
https://stackoverflow.com/questions/72609159/how-do-i-format-a-date-and-also-pad-it-with-spaces
Formatting appears to work differently if the object you're formatting is a date. today = "aaa" print(f'{today:>10}') returns aaa i.e. it has the padding. If I now do this: today = datetime.date.today() print(f'{today:>10}') then the response is >10 Which is obviously not what I want. I've tried various other comb...
Python's scheme for formatting via f-strings (and the .format method of strings) allows the inserted data to override how the format specification works, using the __format__ magic method: >>> class Example: ... def __format__(self, template): ... return f'{template} formatting of {self.__class__.__name__} instance' .....
4
5
72,592,670
2022-6-12
https://stackoverflow.com/questions/72592670/why-is-accessing-elements-using-tolist-faster-than-accessing-it-directly-throu
I have a dataframe and I wanted to apply a certain function on a set of columns. Something like: data[["A","B","C","D","E"]].apply(some_func, axis=1) In the some_func function, the first step is extracting out all the column values into separate variables. def some_func(x): a,b,c,d,e = x # or x.tolist() #Some more pro...
Let's define two functions and inspect them with dis: from dis import dis from pandas import Series x = Series([1,2,3,4,5], index=["A","B","C","D","E"]) def a(): a, b, c, d, e = x.tolist() def b(): a, b, c, d, e = x dis(a) dis(b) Executing the above will yield: # dis(a) 7 0 LOAD_GLOBAL 0 (x) 2 LOAD_METHOD 1 (tolist) 4...
4
3
72,586,296
2022-6-11
https://stackoverflow.com/questions/72586296/pytest-invoked-in-code-only-run-tests-in-current-file
I have a python file with some code and simple tests on that code. I would like to invoke pytest from that python file, have it collect only the tests in that file, and run them. For example, foo.py: # ... various code above... def test_foo(): foo = Foo() assert foo() def test_bar(): bar = Bar() assert bar.baz if __nam...
According to the pytest documentation, options and arguments can be passed to pytest.main. To run tests in foo.py, this would work: # ... various code above... def test_foo(): foo = Foo() assert foo() def test_bar(): bar = Bar() assert bar.baz if __name__ == '__main__': import pytest pytest.main(["foo.py"]) # consider ...
6
6
72,588,287
2022-6-11
https://stackoverflow.com/questions/72588287/django-how-to-set-foreignkey-related-name-in-abstract-model-class
I want to create on Abstract Model class for future inheriting like this: class AbstractModel(models.Model): created_at = models.DateTimeField( auto_now_add=True, blank=True, null=True, ) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='XXX_created_by', blank=True, null...
As the Be careful with related_name and related_query_name section of the documentation says, you can: To work around this problem, when you are using related_name or related_query_name in an abstract base class (only), part of the value should contain '%(app_label)s' and '%(class)s'. '%(class)s' is replaced by the l...
6
9
72,585,750
2022-6-11
https://stackoverflow.com/questions/72585750/django-subquery-sum-with-no-results-returns-none-instead-of-0
I have a Django Subquery which returns a Sum. If the subquery finds at least one result, it works fine. But, if the subquery finds no records, it returns None which then causes any other calculations using this result (I use it later in my query in an F expression) to also result in None. I am trying to Sum all non-nul...
You should not Coalesce the .annotate(…) in the Subquery, but the result of the Subquery, so: .annotate(tapx=Coalesce( Subquery(InvTrx.objects.filter( job=OuterRef('job'), consumed__isnull=False, inventory__inv_type='APX' ).values('job_id').annotate(tot_cons=Sum('consumed')).values('tot_cons')), Value(0)) )
5
8
72,586,906
2022-6-11
https://stackoverflow.com/questions/72586906/how-to-ensure-only-one-entry-is-true-in-a-django-model
I'm stuck on thinking about implementing a "only one entry might be True for one combination". A Project has n members (Guards) through an intermediate table. every Guard may be member of n Projects only one combination of Guard <-> Project is allowed (unique_together) a MemberShip might be the 'Main' one (is_main) BU...
You can work with a UniqueConstraint [Django-doc] that is filtered: from django.db.models import UniqueConstraint, Q class ProjectMembership(models.Model): guard = models.ForeignKey(Guard, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) is_main = models.BooleanField(_('is main p...
7
10
72,582,066
2022-6-11
https://stackoverflow.com/questions/72582066/will-fastapi-application-with-only-async-endpoints-encounter-the-gil-problem
If all the fastapi endpoints are defined as async def, then there will only be 1 thread that is running right? (assuming a single uvicorn worker). Just wanted to confirm in such a setup, we will never hit the python's Global Interpreter Lock. If the same was to be done in a flask framework with multiple threads for the...
Your understanding is correct. When using 1 worker with uvicorn, only one process is run. That means, there is only one thread that can take a lock on the interpreter that is running your application. Due to the asynchronous nature of your FastAPI app, it will be able to handle multiple simultaneous requests, but not i...
5
7
72,577,929
2022-6-10
https://stackoverflow.com/questions/72577929/dask-multi-stage-resource-setup-causes-failed-to-serialize-error
Using the exact code from Dask's documentation at https://jobqueue.dask.org/en/latest/examples.html In case the page changes, this is the code: from dask_jobqueue import SLURMCluster from distributed import Client from dask import delayed cluster = SLURMCluster(memory='8g', processes=1, cores=2, extra=['--resources ssd...
As noted by @Michael Delgado in the comments, this appears to be a problem with the documentation (raised here). Resources are a dictionary with each key being name of a resource and value representing the amount used by a task. In an answer to a related question, Matt Rocklin, the initial commit author, mentions that ...
4
5
72,580,747
2022-6-10
https://stackoverflow.com/questions/72580747/why-time-zone-is-0456
The following code print 2022-01-01 05:30:00-04:56. What's -04:56? import pytz, datetime tz = pytz.timezone("America/New_York") t = datetime.datetime(2022, 1,1, 5, 30) u = t.replace(tzinfo=tz) print(u) 2022-01-01 05:30:00-04:56 In jupyter, u has the value of datetime.datetime(2022, 1, 1, 5, 30, tzinfo=<DstTzInfo 'Amer...
(Delete previous answer) My bad: I parsed datetime.datetime(2022, 1,1, 5, 30) as 30 May (I'm answering this on 10 June.). We're not in daylight savings time in January. ^ For me, this whole question is yet another reminder that I don't * really * understand time. OP. will you please remove this as an accepted solution?...
5
2
72,576,024
2022-6-10
https://stackoverflow.com/questions/72576024/smtplib-smtpauthenticationerror-535-b5-7-8-username-and-password-not-accepte
I'm writing a site on Flask and I came across the problem that when sending emails to email users there is such an error. smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials i1-20020ac25221000000b00478f5d3de95sm4732790...
Since You can't use the less secure app now as the deadline was 30th May 2022. An alternative way to send Gmail via flask using an App password Before generating the APP password your google account must enable the 2FA. If the 2FA is enabled then you can hop on to the security section in the manage accounts and there y...
5
11
72,576,260
2022-6-10
https://stackoverflow.com/questions/72576260/whats-solution-for-sending-emails-from-python-while-gmail-the-less-secure-app
I recently was using smtp library for sending emails from gmail account but recently it stopped working after research I found out the google can not let you enable the less secure app anymore . So is there any workaround this ?
If you want to continue using Gmail SMTP, you can set it up by setting an app password. An app password works like an alternate password for your account. It can only be used by the applications you share it with, so it’s more secure than sharing your primary password. Here's how you can set it up: https://support.goog...
4
3
72,574,761
2022-6-10
https://stackoverflow.com/questions/72574761/what-is-the-correct-way-to-mock-psycopg2-with-pytest
I need to simulate DB connection without actual connection. All answers I found are trying to mock methods in different ways, connect to docker db, connect to actual PostgreSQL running locally. I believe I need mocking variant but I cannot formulate in my head how should I mock. Am I missing something? Am I moving into...
The solution I landed at is below. Created fake class that has exactly structure of PostgresqlApi. (see implementation below) Created fixture for db_connection method. (see implementation below) Fake class implementation class FakePostgresqlApi(PostgresqlApi): event_list = [] def __init__(self): pass def add_event(se...
5
3
72,574,603
2022-6-10
https://stackoverflow.com/questions/72574603/how-to-fix-integrityerror-psycopg2-errors-foreignkeyviolation-update-or-delet
I have two tables created with Flask-SQLAlchemy below - they have a one to one relationship. class Logo(db.Model): __tablename__ = "logo" id = db.Column(db.Integer, primary_key=True) filename = db.Column(db.String(100)) data = db.Column(db.LargeBinary) username = db.Column(db.String(100), db.ForeignKey("users.username"...
You could temporarily make the foreign key constraint deferrable and make the update in psql. Say we have these tables: test# \d parent Table "public.parent" Column │ Type │ Collation │ Nullable │ Default ════════╪═══════════════════╪═══════════╪══════════╪══════════════════════════════ id │ integer │ │ not null │ gene...
4
2
72,571,235
2022-6-10
https://stackoverflow.com/questions/72571235/can-i-install-node-js-18-on-centos-7-and-do-i-need-python-3-install-too
I'm not sure if node.js 18 supports centos 7 and is it a requirement to install python 3 for node.js 18?
Step 1 - curl --silent --location https://rpm.nodesource.com/setup_18.x | sudo bash - Step 2 - sudo yum -y install nodejs I don't think you need Python 3. Reference - https://computingforgeeks.com/install-node-js-on-centos-rhel-rocky-linux/
16
-6
72,558,809
2022-6-9
https://stackoverflow.com/questions/72558809/python-attributeerror-numpy-ndarray-object-has-no-attribute-to
I now have the updated code as follows: # Hyperparameters random_seed = 123 learning_rate = 0.01 num_epochs = 10 batch_size = 128 device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") for epoch in range(num_epochs): model = resnet34.train() for batch_idx, (features, targets) in enumerate(train_gener...
It would be nice to see your train_generator code for clarity, but it does not seem to be a torch DataLoader. In this case, you should probably convert your arrays to tensors manually. There are several ways to do so: torch.from_numpy(numpy_array) - for numpy arrays; torch.as_tensor(list) - for common lists and tuples...
6
7
72,554,445
2022-6-9
https://stackoverflow.com/questions/72554445/pandas-convert-a-series-which-contains-strings-like-10-and-0-10-into-numer
What is the best way to convert a Pandas series that contains strings of the type "10%" and "0.10" into numeric values? I know that if I have a series with just "0.10" type strings I can just do pd.to_numeric. I also know that if I have a series of "10%" type strings I can do str.replace("%","") and then do pd.to_numer...
The easiest solution is to select entries using a mask and handle them in bulk: from pandas import Series, to_numeric mixed = Series(["10%", "0.10", "5.5%", "0.02563"]) # make an empty series with similar shape and dtype float converted = Series(index=mixed.index, dtype='float') # use a mask to select specific entries ...
7
5
72,553,699
2022-6-9
https://stackoverflow.com/questions/72553699/what-is-the-kotlin-equivalent-of-python-generators
If I have a python generator function, let's say this one: def gen(): x = 0 while (true): yield x x += 1 This function remembers its current state, and every time you call gen(), yields a new value. Essentially, I would like a Kotlin sequence which can remember its state.
def gen(): x = 0 while (true): yield x x += 1 This function remembers its current state, and every time you call gen(), yields a new value. This is incorrect. Every time you call gen() you get a new "generator object" whose state is independent of any other generator object created by this function. You then query t...
5
7
72,555,346
2022-6-9
https://stackoverflow.com/questions/72555346/calculation-of-sales-with-a-dataframe-takes-too-long
I have a problem. I would like to calculate the turnover for a customer in the last 6 months. The methods work on my dummy record, unfortunately the whole thing does not work on my real record as it is too slow. How can I rewrite this so that it performs faster? Dataframe customerId fromDate sales 0 1 2022-06-01 100 1...
Using multiprocessing and consider 6 months as 180 days to reduce the memory size and the time computing. Copy the following code to a python file and run it from the console (not from a Jupyter Notebook) import pandas as pd import numpy as np import multiprocessing as mp import time def sum_sales(customer, df): # 1st ...
4
1
72,550,789
2022-6-8
https://stackoverflow.com/questions/72550789/generate-a-type-from-another-type-and-change-fields-to-optional
I have this type: class SomeResource: id: int name: str And I need this type: class SomeResourceQuery: id: Optional[int] name: Optional[str] But I'd like to avoid having to write it by hand. Is it possible to generate this SomeResourceQuery type from the SomeResource type? Just convert all the types of the fields to ...
You can use the type constructor to construct the new type with the appropriate annotations. def construct_query_class(cls: type) -> type: annotations = {key: typing.Optional[value] for key, value in cls.__annotations__.items()} return dataclasses.dataclass(type(cls.__name__ + 'Query', (), {'__annotations__': annotatio...
4
6
72,558,859
2022-6-9
https://stackoverflow.com/questions/72558859/transforming-in-pandas-groupby
Index E_Id P_Id Date 121 701 9002 2021 122 701 9001 2019 123 702 9002 2021 124 702 9002 2019 125 703 9001 2021 126 704 9002 2019 127 704 9003 2019 Now I want to Create another DataFrame groupedby E_Id But I want to Count the number of rows against each P_Id call it 'x', and then sum of 'x' for w...
Thank you for an interesting question. My approach is: You creates a df1 with unique combination of E_id and P_id Create df2 to count number of unique occur of P_id Merge df1 and df2, then use groupby with sum I modify your sample a bit # Dataframe: df = pd.DataFrame({'e':[701, 701,701,701, 701, 701,702,702,703,704, ...
4
2
72,552,217
2022-6-8
https://stackoverflow.com/questions/72552217/what-is-the-equivalent-of-connecting-to-google-cloud-storagegcs-like-in-aws-s3
I want to access google cloud storage as in the code below. # amazon s3 connection import s3fs as fs with fs.open("s3://mybucket/image1.jpg") as f: image = Image.open(f).convert("RGB") # Is there an equivalent code like this GCP side? with cloudstorage.open("gs://my_bucket/image1.jpg") as f: image = Image.open(f).conve...
You're looking for gcsfs. Both s3fs and gcsfs are part of the fsspec project and have very similar APIs. import gcsfs fs = gcsfs.GCSFileSystem() with fs.open("gs://my_bucket/image1.jpg") as f: image = Image.open(f).convert("RGB") Note that both of these can be accessed from the fsspec interface, as long as you have th...
5
8
72,551,878
2022-6-8
https://stackoverflow.com/questions/72551878/how-to-flatten-a-multi-column-dataframe-into-2-columns
Given the following table: group_a = {'ba':[2.0,9.4,10.8], 'bb':[4.2,7.1,3], 'bc':[8.1,9.5,6.1]} A = pd.DataFrame(group_a, index=['aa','ab','ac']) That looks like this: ba bb bc aa 2.0 4.2 8.1 ab 9.4 7.1 9.5 ac 10.8 3.0 6.1 How can I flatten this table so that it looks like this: Values aa_ba 2.0 aa_bb 4.2 aa_bc 8....
You can use stack and rework the index: B = A.stack() B.index = B.index.map('_'.join) out = B.to_frame('Values') output: Values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1
3
7
72,547,116
2022-6-8
https://stackoverflow.com/questions/72547116/modulenotfounderror-no-module-named-discord-slash
I'm trying to install a module called "discord_slash" and when I use it in a python file it displays the error "ModuleNotFoundError: No module named 'discord_slash'". I've tried uninstalling it and installing it again but it's not working.
You're attempting to use the legacy v3 version import of the library, available here. As of 4.0, you should be using import interactions. Based on a comment, I understand you're watching a video from 2021, if you'd like to use a similar version you can use discord-py-slash-command 3.0.3 which is the latest release of t...
4
7
72,545,775
2022-6-8
https://stackoverflow.com/questions/72545775/django-orm-postgresql-delete-query
I have 30 instances of the Room objects, i.e. 30 rows in the database table. In Python code I have Room.objects.all().delete(). I see that Django ORM translated it into the following PostgreSQL query: DELETE FROM "app_name_room" WHERE "app_name_room"."id" IN ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,...
Interesting question. It got me thinking so I went a little deeper. The main reason could be that using DELETE FROM app_name_room doesn't take care of CASCADE delete However, answering your question Is there any way to switch to it and avoid listing all IDs? You can do this using the private method _raw_delete. For i...
4
1
72,456,234
2022-6-1
https://stackoverflow.com/questions/72456234/why-does-print-i-e-three-dots-in-a-row-print-blank
I'd like to print three dots in a row (to form an ellipsis), but print() prints blank. print("one moment...") one moment... print("...") print("..") .. print("...abc...") abc... print("\u2026") … What's happening here? Why is "..." parsed in an exceptional way? I am using ipython in PyCharm.
Update 2024-07-31 According to the YouTrack issue (archive) this issue has been fixed and is available in builds: 242.6184, 241.16163, 241.17011.12, 242.10180.17. Original Post Looks like this is a known issue with Pycharm where its interactive console removes the leading three periods from a print statement. Here’s t...
63
69
72,474,673
2022-6-2
https://stackoverflow.com/questions/72474673/what-is-the-recommended-way-for-retrieving-row-numbers-index-for-polars
I know polars does not support index by design, so df.filter(expr).index isn't an option, another way I can think of is by adding a new column before applying any filters, not sure if this is an optimal way for doing so in polars df.with_columns(pl.Series('index', range(len(df))).filter(expr).index
Use with_row_index(): df = pl.DataFrame([pl.Series("a", [5, 9, 6]), pl.Series("b", [8, 3, 4])]) In [20]: df.with_row_index() Out[20]: shape: (3, 3) ┌────────┬─────┬─────┐ │ index ┆ a ┆ b │ │ --- ┆ --- ┆ --- │ │ u32 ┆ i64 ┆ i64 │ ╞════════╪═════╪═════╡ │ 0 ┆ 5 ┆ 8 │ │ 1 ┆ 9 ┆ 3 │ │ 2 ┆ 6 ┆ 4 │ └────────┴─────┴─────┘ #...
11
16
72,482,298
2022-6-2
https://stackoverflow.com/questions/72482298/why-isnt-my-class-initialized-by-def-int-or-def-init-why-do-i-get-a
If your question was closed as a duplicate of this, it is because you had a code sample including something along the lines of either: class Example: def __int__(self, parameter): self.attribute = parameter or: class Example: def _init_(self, parameter): self.attribute = parameter When you subsequently attempt to cre...
This is because the code has a simple typographical error: the method should instead be named __init__ - note the spelling, and note that there are two underscores on each side. What do the exception messages mean, and how do they relate to the problem? As one might guess, a TypeError is an error that has to do with th...
12
7
72,472,167
2022-6-2
https://stackoverflow.com/questions/72472167/deprecation-warning-the-system-version-of-tk-is-deprecated-m1-mac-in-vs-code
(M1 MBA 2020, MacOS 12.3.1) So inside of Vs Code, when I select my interpreter as Python 3.8.9 from my usr/local/bin Tkinter it runs as I want it to. Here is the running code for reference. The problem arises when I am trying to use the Global Python 3.8.9 interpreter (usr/bin/python3). When the code runs, the applic...
If you have Homebrew installed, you can update tk with: brew uninstall tcl-tk --devel brew install tcl-tk Which is the recommended option Then you may need to add export PATH="/usr/local/opt/tcl-tk/bin:$PATH" to your .zshrc file: If you are using a zsh terminal: Use: echo "# For tkinter export PATH=\"/usr/local/opt/t...
10
15
72,504,576
2022-6-5
https://stackoverflow.com/questions/72504576/why-use-from-module-import-a-as-a-instead-of-just-from-module-import-a
When reading source code of fastapi, this line make me fuzzy: from starlette.testclient import TestClient as TestClient Why not just: from starlette.testclient import TestClient?
From the point of view of executable code, there is absolutely no difference in terms of the Python bytecode being generated by the two different code examples (using Python 3.9): >>> dis.dis('from starlette.testclient import TestClient as TestClient') 1 0 LOAD_CONST 0 (0) 2 LOAD_CONST 1 (('TestClient',)) 4 IMPORT_NAME...
11
16
72,478,573
2022-6-2
https://stackoverflow.com/questions/72478573/how-to-send-an-email-using-python-after-googles-policy-update-on-not-allowing-j
I am trying to learn how to send an email using python. All the tutorials on the web that I have read explain how to do it using Gmail. But, from 30/05/2022 (despite the fact that everybody is free to do whatever he wants with his account) Google has a new policy that states: To help keep your account secure, starting...
Here is a more precise answer with all the main steps. I hope it will help other people. Log in into your email account: https://myaccount.google.com Then go to the security part Be sure that you have turn on two steps verification and click on "App password." As of 9th July 2023, this might not be visible, but is...
21
47
72,490,783
2022-6-3
https://stackoverflow.com/questions/72490783/how-do-you-use-patch-as-a-context-manager
I have a class that mocks database functionality which does not subclass Mock or MagicMock because it defines its own __init__() method: class DatabaseMock(): def __init__(self, host=None): self.host = host self.x = {} # other methods that mutate x There is a function I want to test that makes an API call to the real ...
I have figured out the issue. When patch is given a class, it will return a class, not an object instance of that class. So in my example, mock is not a DataBaseMock object instance, but a reference to the class. This is why class level variables are visible, but not object instance fields. In order to get my desired f...
4
2
72,461,176
2022-6-1
https://stackoverflow.com/questions/72461176/dictstr-unknown-is-incompatible-with-my-custom-typeddict
Given this custom TypedDict TMyDict: class TMyDict(TypedDict, total=False): prop_a: int prop_b: int This is ok: def get_my_dict_works() -> TMyDict: return { 'prop_a': 0, 'prop_b': 1 } But this don't: def get_my_dict_fail() -> TMyDict: d= { 'prop_a': 0, 'prop_b': 1 } return d Error message is: Expression of type "di...
Your type checker determined the type of d before you used it In order to be performant and to keep type inference simple, type checkers typically only scan the code once and try to determine the type of a variable the moment it is assigned. It saw the line d = { 'prop_a': 0, 'prop_b': 1 } and assumed that d: dict[str...
5
3
72,465,421
2022-6-1
https://stackoverflow.com/questions/72465421/how-to-use-poetry-with-docker
How do I install poetry in my image? (should I use pip?) Which version of poetry should I use? Do I need a virtual environment? There are many examples and opinions in the wild which offer different solutions.
TL;DR Install poetry with pip, configure virtualenv, install dependencies, run your app. FROM python:3.10 # Configure Poetry ENV POETRY_VERSION=1.2.0 ENV POETRY_HOME=/opt/poetry ENV POETRY_VENV=/opt/poetry-venv ENV POETRY_CACHE_DIR=/opt/.cache # Install poetry separated from system interpreter RUN python3 -m venv $POET...
31
59
72,466,218
2022-6-1
https://stackoverflow.com/questions/72466218/ufeff-is-appearing-while-reading-csv-using-unicodecsv-module
I have following code import unicodecsv CSV_PARAMS = dict(delimiter=",", quotechar='"', lineterminator='\n') unireader = unicodecsv.reader(open('sample.csv', 'rb'), **CSV_PARAMS) for line in unireader: print(line) and it prints ['\ufeff"003', 'word one"'] ['003,word two'] ['003,word three'] The CSV looks like this "0...
encoding='utf-8-sig' will remove the UTF-8-encoded BOM (byte order mark) used as a UTF-8 signature in some files: import unicodecsv with open('sample.csv','rb') as f: r = unicodecsv.reader(f, encoding='utf-8-sig') for line in r: print(line) Output: ['003,word one'] ['003,word two'] ['003,word three'] But why are you ...
4
14
72,468,241
2022-6-1
https://stackoverflow.com/questions/72468241/exception-closing-connection-using-sqlalchemy-with-asyncio-and-postgresql
I have an API server using Python 3.7.10. I am using the FastAPI framework with sqlalchemy, asyncio, psycopg2-binary, asyncpg along with postgresql. I am deploying this using aws elasticbeanstalk. The application seems to work fine but everytime my frontend calls an endpoint, it seems like the connection is not closing...
My problem was fixed by using NullPool class. from sqlalchemy.pool import NullPool from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from app.model.base import CustomBase from app.core.config import SQLALC...
5
1
72,523,108
2022-6-6
https://stackoverflow.com/questions/72523108/decompressing-gzip-chunks-of-response-from-http-client-call
I have the following code that I am using to try to chunk response from a http.client.HTTPSConnection get request to an API (please note that the response is gzip encoded: connection = http.client.HTTPSConnection(api, context = ssl._create_unverified_context()) connection.request('GET', api_url, headers = auth) respon...
The most probable reason for that is, the response your received is indeed not a gzipped file. I notice that in your code, you pass a variable called auth. Typically, a server won't send you a compressed response if you don't specify in the request headers that you can accept it. If there is only auth-related keys in y...
5
0
72,472,220
2022-6-2
https://stackoverflow.com/questions/72472220/dataclass-inheritance-fields-without-default-values-cannot-appear-after-fields
Context I created two data classes to handle table metadata. TableMetadata apply to any kind of tables, while RestTableMetadata contains information relevant for data extracted from REST apis @dataclass class TableMetadata: """ - entity: business entity represented by the table - origin: path / query / url from which d...
Here is a working solution for python > 3.10 @dataclass(kw_only=True) class TableMetadata: """ - entity: business entity represented by the table - origin: path / query / url from which data withdrawn - id: field to be used as ID (unique) - historicity: full, delta - upload: should the table be uploaded """ entity: str...
13
10
72,507,137
2022-6-5
https://stackoverflow.com/questions/72507137/get-data-of-a-document-in-firestore-by-giving-a-field-value-belonged-to-that-doc
I'm new to python. I'm using a firebase firestore database for this project. After entering the Admission_No, I want to retrieve all the data in the relevant document such as name, grade, phone. I tried to write a program for it. But I failed. Please help me to complete my project. Thank you all. The Code might be full...
In this case, I tried many ways. But finally, I realized we should provide the correct Document ID for retrieve all fields of data from firestore. Getting Data from Firestore - Method given in firestore documentation doc_ref = db.collection(u'cities').document(u'SF') doc = doc_ref.get() if doc.exists: print(f'Document ...
4
2
72,522,003
2022-6-6
https://stackoverflow.com/questions/72522003/xgbregressor-with-weights-and-base-margin-out-of-sample-validation-possible
I have an old linear model which I wish to improve using XGBoost. I have the predictions from the old model, which I wish to use as a base margin. Also, due to the nature of what I'm modeling, I need to use weights. My old glm is a poisson regression with formula number_of_defaults/exposure ~ param_1 + param_2 and weig...
You can use cross_val_predict with fit_params argument, or GridSearchCV.fit with **fit_params. Here is a working proof of concept import xgboost as xgb from sklearn import datasets from sklearn.model_selection import cross_val_predict, GridSearchCV import numpy as np # Sample dataset diabetes = datasets.load_diabetes()...
6
3
72,499,414
2022-6-4
https://stackoverflow.com/questions/72499414/i-got-an-error-about-error-cant-find-libdevice-directory-cuda-dir-nvvm-libd
Windows Version: Windows 10 Pro 21H2 19044.1706 GPU: rtx2070 import tensorflow as tf import torch print(torch.__version__) #1.10.1+cu113 print(torch.version.cuda) #11.3 print(tf.__version__) #2.9.1 and i run python .\object_detection\builders\model_builder_tf2_test.py i can get 'Ran 24 tests in 18.279s OK (skipped=1)...
I had the same problem and just fixed it. The library can't find the folder even if you set the "CUDA_DIR" because it's not using that variable or any other I tried. This post is helpful in understanding the issue. The only solution I was able to find is just copying the required files. Steps for a quick fix: Find whe...
6
12
72,476,094
2022-6-2
https://stackoverflow.com/questions/72476094/pydantic-error-wrappers-validationerror-11-validation-errors-for-for-trip-type
Im getting this error with my pydantic schema, but oddly it is generating the object correctly, and sending it to the SQLAlchemy models, then it suddenly throws error for all elements in the model. response -> id field required (type=value_error.missing) response -> date field required (type=value_error.missing) respon...
It seems like a bug on the pydantic model, it happened to me as well, and i was not able to fix it, but indeed if you just skip the type check in the route it works fine
7
3
72,503,309
2022-6-4
https://stackoverflow.com/questions/72503309/save-a-bert-model-with-custom-forward-function-and-heads-on-hugginface
I have created my own BertClassifier model, starting from a pretrained and then added my own classification heads composed by different layers. After the fine-tuning, I want to save the model using model.save_pretrained() but when I print it upload it from pretrained i don't see my classifier head. The code is the foll...
Maybe something is wrong with the config_class attribute inside your BertClassifier class. According to the documentation you need to create an additional config class which inherits form PretrainedConfig and initialises the model_type attribute with the name of your custom model. The BertClassifier's config_class has ...
5
3
72,535,079
2022-6-7
https://stackoverflow.com/questions/72535079/python-easiest-way-to-insert-a-dictionary-into-a-database-table
I have a dictionary with keys and values like: my_dict = {'a':33, 'b': 'something', 'c': GETDATE(), 'd': 55} Assume column names in the SQL table are also named like the keys of the dict, i.e. "a,b,c,d". The actual dictionary is 20+ key:value pairs. Code I have used pyodbc.connect to create a cursor which I could use ...
If you're using pyodbc then this might work: columns = {row.column_name for row in cursor.columns(table='TABLEabc')} safe_dict = {key: val for key, val in my_dict.items() if key in columns} # generate a parameterised query for the keys in our dict query = "INSERT INTO TABLEabc ({columns}) VALUES ({value_placeholders})"...
5
3
72,534,575
2022-6-7
https://stackoverflow.com/questions/72534575/fastapi-fileresponse-cannot-find-file-in-tempdirectory
I'm trying to write an endpoint that just accepts an image and attempts to convert it into another format, by running a command on the system. Then I return the converted file. It's slow and oh-so-simple, and I don't have to store files anywhere, except temporarily. I'd like all the file-writing to happen in a temporar...
According to the documentation of TemporaryDirectory() This class securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the temporary directory object, the newly created temporary di...
7
10
72,467,711
2022-6-1
https://stackoverflow.com/questions/72467711/is-memory-supposed-to-be-this-high-during-model-fit-using-a-generator
The tensorflow versions that I can still recreate this behavior are: 2.7.0, 2.7.3, 2.8.0, 2.9.0. Actually, these are all the versions I've tried; I wasn't able to resolve the issue in any version. OS: Ubuntu 20 GPU: RTX 2060 RAM: 16GB I am trying to feed my data to a model using a generator: class DataGen(tf.keras.ut...
How to minimize RAM usage From the very helpful comments and answers of our fellow friends, I came to this conclusion: First, we have to save the data to an HDF5 file, so we would not have to load the whole dataset in memory. import h5py as h5 import gc file = h5.File('data.h5', 'r') X = file['X'] y = file['y'] gc.co...
5
3
72,511,979
2022-6-6
https://stackoverflow.com/questions/72511979/valueerror-install-dbtypes-to-use-this-function
I'm using BigQuery for the first time. client.list_rows(table, max_results = 5).to_dataframe(); Whenever I use to_dataframe() it raises this error: ValueError: Please install the 'db-dtypes' package to use this function. I found this similar problem (almost exactly the same), but I can't understand how to implement ...
I was able to replicate your use case as shown below. Easiest solution is to pip install db-dtypes as mentioned by @MattDMo. Or you can specify previous version of google-cloud-bigquery by creating a requirements.txt with below contents: google-cloud-bigquery==2.34.3 And then pip install by using command as shown bel...
32
20
72,505,627
2022-6-5
https://stackoverflow.com/questions/72505627/mediapipe-not-running-even-after-installation-macbook-m1
I am trying to get MediaPipe Pose estimation running on VS code on my MacBook M1. I installed it using pip install mediapipe-silicon and it installed successfully. I am running the generic MediaPipe code without modifications: import cv2 import mediapipe as mp import numpy as np mp_drawing = mp.solutions.drawing_utils ...
I was facing this exact same issue today and installing mediapipe-silicon and opencv-python in a new 3.9.10 Python environment did the trick. I think it might have something to do with the under-the-hood operation of mediapipe and the compiled version "media pipe-silicon" that prevents it from playing nicely with other...
5
2
72,520,627
2022-6-6
https://stackoverflow.com/questions/72520627/python-big-o-seems-to-return-completely-incorrect-results-what-am-i-doing-wron
I am comparing runtimes of different ways of flattening a list of lists using the big_o module, and for following methods my function does not return the expected results, namely: This one: def itertools_chain_from_iterable(arr): return list(chain.from_iterable(arr)) returns "constant", which can't possibly be true...
Your lambda ignores its argument n and instead always produce the same constant-size input. Produce input of size n instead. (A note: originally the question had 8 functions and 7 of them were judged "constant time". It was edited to a larger constant and then got other judgements. I guess your computer's speed is some...
4
4
72,522,021
2022-6-6
https://stackoverflow.com/questions/72522021/is-there-a-way-for-snakemake-to-evaluate-dynamic-snakefile-constructs-like-eval
I would like to have various dynamic "shortcuts" (rule names) in my Snakemake workflow without needing marker files. The method I have in mind is similar to eval in GNU Make, but it doesn't seem like Snakemake can evaluate variable-expanded code in the Snakefile syntax. Is there a way to accomplish this? Here's a simpl...
Since Snakefile is a Python file, the following might help to achieve what you are after: for stage in stages: rule: name: f'{stage}' input: expand(f'{stage}{{step}}_file', step=steps)
7
8
72,524,450
2022-6-6
https://stackoverflow.com/questions/72524450/replace-none-with-incremental-value-excluding-values-from-skip-list
I am trying to replace all None values in all sublists within a list to incremental numbers starting from 0 but excluding the numbers from the skip list. And there is one more requirement. If first element of a sublist matches to any other sublists' first element, then they all need to have the same value that replaces...
You're looking up the wrong element in the cache in a couple places, and not skipping properly when the skip list contains consecutive elements. Here's the minimal fix with inline comments indicating changed lines: skip = [1,2] a = [[1, None, 2], [3, 4, 5], [1, None, 7], [8, 9, 10],[11, None, 12]] b = 0 d = {} for i in...
4
2
72,521,182
2022-6-6
https://stackoverflow.com/questions/72521182/how-to-reduce-space-between-columns-in-a-horizontal-legend-python
I would like to reduce space between legend columns (An example is shown in the attached image). So, what I want to do is, [before] (Sym.)A ------ (Sym.)B ------ (Sym.)C ------ (Sym.)D [after] (Sym.)A -- (Sym.)B -- (Sym.)C -- (Sym.)D Is there a way to do it? (e.g., plt.legend(ncol=4, [a hidden parameter??])) Thanks! I...
Take a look at the description of columnspacing from documentation. You can try: plt.legend(ncol=4, columnspacing=0.8)
7
13
72,520,366
2022-6-6
https://stackoverflow.com/questions/72520366/why-does-functools-partial-not-inherit-name-and-other-meta-data-by-defau
I am wondering why meta data (e.g. __name__, __doc__) for the wrapped method/function by partial is not inherited by default. Instead, functools provides the update_wrapper function. Why it is not done by default is not mentioned anywhere (as far as I could see) e.g. here and many tutorials on functools.partial talk ab...
Think about what that would actually look like: def add(x, y): "Adds two numbers" return x + y add_5 = partial(add, 5) Would it actually make sense for add_5 to have __name__ set to "add" and __doc__ set to "Adds two numbers"? The callable created by partial behaves completely differently from the original function. I...
8
16
72,496,224
2022-6-4
https://stackoverflow.com/questions/72496224/is-sgd-optimizer-in-pytorch-actually-does-gradient-descent-algorithm
I'm working on trying to compare the converge rate of SGD and GD algorithms for the neural networks. In PyTorch, we often use SGD optimizer as follows. train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True) optimizer = torch.optim.SGD(model.parameters(), lr=0.001) for epoch in range...
Your understanding is correct. SGD is just updating weights based on the gradient computed by backpropagation. The flavor of gradient descent that it performs is therefore determined by the data loader. Gradient descent (aka batch gradient descent): Batch size equal to the size of the entire training dataset. Stochast...
8
6
72,518,160
2022-6-6
https://stackoverflow.com/questions/72518160/detect-strings-containing-only-digits-letters-and-one-or-more-question-marks
I am writing a python regex that matches only string that consists of letters, digits and one or more question marks. For example, regex1: ^[A-Za-z0-9?]+$ returns strings with or without ? I want a regex2 that matches expressions such as ABC123?A, 1AB?CA?, ?2ABCD, ???, 123? but not ABC123, ABC.?1D1, ABC(a)?1d on mysql,...
How about something like this: ^(?=.*\?)[a-zA-Z0-9\?]+$ As you can see here at regex101.com Explanation The (?=.*\?) is a positive lookahead that tells the regex that the start of the match should be followed by 0 or more characters and then a ? - i.e., there should be a ? somewhere in the match. The [a-zA-Z0-9\?]+ ma...
4
6
72,512,921
2022-6-6
https://stackoverflow.com/questions/72512921/python-tqdm-package-miniters-not-working-occasionally
Since I'm looping over permutations I don't want too frequent updates of the progress bar, so I set miniters to be one-tenth of the total length: total_len = len(list(itertools.permutations(range(N), 2))) for row_a, row_b in tqdm(itertools.permutations(range(N), 2), total=total_len , miniters=int(total_len/10), disable...
I think I found the reason, another argument maxinterval controls the maximum update interval which is set to 10 (seconds) by default, so when the progress bar updates too slowly it'll automatically modify the miniters parameter. Therefore I'll need to specify a larger maxinterval as well. So the code should be total_l...
4
6
72,509,839
2022-6-5
https://stackoverflow.com/questions/72509839/how-to-use-jax-vmap-over-zipped-arguments
I have the following example code that works with a regular map def f(x_y): x, y = x_y return x.sum() + y.sum() xs = [jnp.zeros(3) for i in range(4)] ys = [jnp.zeros(2) for i in range(4)] list(map(f, zip(xs, ys))) # returns: [DeviceArray(0., dtype=float32), DeviceArray(0., dtype=float32), DeviceArray(0., dtype=float32)...
For using jax.vmap, you do not need to zip your variables. You can write what you want like below: import jax.numpy as jnp from jax import vmap def f(x_y): x, y = x_y return x.sum() + y.sum() xs = jnp.zeros((4,3)) ys = jnp.zeros((4,2)) vmap(f)((xs, ys)) Output: DeviceArray([0., 0., 0., 0.], dtype=float32)
4
3
72,504,678
2022-6-5
https://stackoverflow.com/questions/72504678/can-a-dataclass-field-format-its-value-for-the-repr
I have a Node class holding RGB data in both hex and HSV form. I'll be using this to sort colors in various ways and would prefer the HSV tuple to remain in float form for comparisons instead of converting from a string for every use. Is there a way to specify to the dataclass field that it should format the value in a...
The dataclasses library currently does not support formatting fields like that. The code generated in the default __repr__ for each included field is always in the formf'field={self.field!r}'. You will have to write your own __repr__.
7
6
72,502,292
2022-6-4
https://stackoverflow.com/questions/72502292/fatal-error-python-h-no-such-file-or-directory-when-compiling-pybind11-example
I am starting out with pybind11, trying to compile the first example. I am using Xubuntu 20.04. My system python is 3.8, but I have install pybind11 only for python 3.10, which is the version that executes when I type python at the command prompt. When I run the compilation command given in the pybind11 docs: c++ -O3 -...
The problem is that the OS installs the header files for Python 3.10 in /usr/include/python3.10/include. This keeps them separate from the default sytem Python (3.8), in case that development package is also installed (otherwise, one set of files would overwrite the other set of files). But /usr/include/python3.10/incl...
6
5
72,463,669
2022-6-1
https://stackoverflow.com/questions/72463669/how-to-set-xaxis-ticks-in-plotly
This is my data: z=[[2.021127032949411, 2.405934869144868, 6.005238252515181, 0.43308358365566557, 6.80624302463342, 1.4243920241458794], [6.754588097147502, 17.66441844606136, 17.66863225189955, 4.796490376261003, 4.100119672126023, 2.6461740133188454], [30.522227304933793, 25.244026806049867, 44.77345477001106, 24.58...
Well, hello o/ Follow the code below and adapt/update it how you want ;) import plotly.graph_objects as go fig = go.Figure(data=go.Heatmap( z=z, x=x, y=y, colorscale='Viridis')) fig.update_layout( xaxis = dict( tickmode='array', #change 1 tickvals = x, #change 2 ticktext = [0,5,10,15,20,25], #change 3 ), font=dict(size...
4
5
72,500,067
2022-6-4
https://stackoverflow.com/questions/72500067/how-to-use-python-variable-in-sql-query-in-databricks
I am trying to convert a SQL stored procedure to databricks notebook. In the stored procedure below 2 statements are to be implemented. Here the tables 1 and 2 are delta lake tables in databricks cluster. I want to use a python variable in place of max_date in SQL query. How to do it? %sql DELETE FROM table1 WHERE Date...
If you are going to run it cell by cell then you can use databricks widgets like First cell x=str(datetime.date.today()) dbutils.widgets.text("max_date",x) Second cell %sql select getArgument("max_date") AS max_date will give you max_date 2022-06-04 but as mentioned here it does not work when run all is used and ide...
5
11
72,497,046
2022-6-4
https://stackoverflow.com/questions/72497046/skipping-a-certain-range-of-a-list-at-time-in-python
I have a array, I want to pick first 2 or range, skip the next 2, pick the next 2 and continue this until the end of the list list = [2, 4, 6, 7, 9,10, 13, 11, 12,2] results_wanted = [2,4,9,10,12,2] # note how it skipping 2. 2 is used here as and example Is there way to achieve this in python?
Taking n number of elements and skipping the next n. l = [2, 4, 6, 7, 9, 10, 13, 11, 12, 2] n = 2 wanted = [x for i in range(0, len(l), n + n) for x in l[i: i + n]] ### Output : [2, 4, 9, 10, 12, 2]
5
4
72,491,761
2022-6-3
https://stackoverflow.com/questions/72491761/difference-of-gaussian-variable-results
I am trying to get my head around this one. I am quite new to python and even more to image filters and manipulation. I'd like tu use OpenCV to apply this function : def gaussianFilter(img, kernel_size=(3,3), standard_dev=1): return cv2.GaussianBlur(img, ksize=kernel_size, sigmaX=standard_dev, sigmaY=standard_dev) La...
Kernel size should be proportional to sigma. You didn't adjust that kernel size in these calls, so your sigma=10 lowpass amounts to a 3x3 box blur... which has a sigma of around 1-2, but isn't a gaussian anymore. Rule of thumb: kernel radius ~= 3*sigma. Then you get +- three sigmas of gaussian distribution, which is 99...
4
4
72,489,775
2022-6-3
https://stackoverflow.com/questions/72489775/python-dict-comprehension-convert-list-of-tuples-of-dictionaries-and-integers-in
I have list of dictionaries and list of integers x = [ { "name": "tom", "job": "judge" }, { "name":"bob", "job": "policeman" } ] y = [1000, 2200] I want to zip them and add y elements to dictionaries as "payroll": y_element The desired output would be: [ { "name": "tom", "job": "judge", "payroll": 1000 }, { "name":"bo...
You can merge the dict with the required data using ** here. [{**d, 'payroll':i} for d, i in zip(x, y)] # [{'name': 'tom', 'job': 'judge', 'payroll': 1000}, # {'name': 'bob', 'job': 'policeman', 'payroll': 2200}]
4
9
72,487,738
2022-6-3
https://stackoverflow.com/questions/72487738/insert-array-into-all-places-in-another-array
For two arrays, say, a = np.array([1,2,3,4]) and b = np.array([5,6]), is there a way, if any, to obtain a 2d array of the following form without looping: [[5 6 1 2 3 4] [1 5 6 2 3 4] [1 2 5 6 3 4] [1 2 3 5 6 4] [1 2 3 4 5 6]] i.e. to insert b in all possible places of a. And if loops are unavoidable, how to do it the ...
Consider using numba acceleration. This happens to be what numba is best at. For your example, it can speed up nearly 6 times: from timeit import timeit import numpy as np from numba import njit a = np.arange(1, 5) b = np.array([5, 6]) def fill(a, b): rows = a.size + 1 cols = a.size + b.size res = np.empty((rows, cols)...
4
1
72,474,765
2022-6-2
https://stackoverflow.com/questions/72474765/make-reusable-iterable-out-of-generator
I want to convert generators to reusable iterables. For example, consider generator: def myrange(n): for i in range(n): yield i It generates one-use iterator: x = myrange(3) print(list(x)) # [0, 1, 2] print(list(x)) # [] I want to add a decorator to the definition of myrange such that it produces reusable iterable (l...
This should work: def mk_reusable(f): """ Makes a reusable iterable out of generator by remembering its arguments """ class MyIterable: def __init__(self, *args, **kwargs): self._args = args self._kwargs = kwargs def __iter__(self): yield from f(*self._args, **self._kwargs) return MyIterable # TEST @mk_reusable def myr...
5
1
72,485,331
2022-6-3
https://stackoverflow.com/questions/72485331/python-get-child-class-inside-parent-class-static-class-method
The output of: class Dog(): def get_class(): return __class__ class Cat(): def get_class(): return __class__ print(Dog.get_class()) print(Cat.get_class()) is: <class '__main__.Dog'> <class '__main__.Cat'> I want to DRY up my code with a subclass. But the output of: class BaseClass(): def get_class(): return __class__...
you are almost there : class BaseClass: @classmethod def get_class(cls): return cls class Dog(BaseClass): pass class Cat(BaseClass): pass print(Dog.get_class()) print(Cat.get_class()) <class '__main__.Dog'> <class '__main__.Cat'>
6
3
72,484,789
2022-6-3
https://stackoverflow.com/questions/72484789/numpy-array-tolist-converts-numpy-datetime64-to-int
I have an array of datetimes that I need to convert to a list of datetimes. My array looks like this: import numpy as np my_array = np.array(['2017-06-28T22:47:51.213500000', '2017-06-28T22:48:37.570900000', '2017-06-28T22:49:46.736800000', '2017-06-28T22:50:41.866800000', '2017-06-28T22:51:17.024100000', '2017-06-28T2...
Explicitly casting the numpy.ndarray as a native Python list will preserve the contents as numpy.datetime64 objects: >>> list(my_array) [numpy.datetime64('2017-06-28T22:47:51.213500000'), numpy.datetime64('2017-06-28T22:48:37.570900000'), numpy.datetime64('2017-06-28T22:49:46.736800000'), numpy.datetime64('2017-06-28T2...
6
4
72,483,752
2022-6-3
https://stackoverflow.com/questions/72483752/how-to-limit-a-python-module-to-expose-specific-parts
I just made a module in python but I don't want people to do this: import mymodule mymodule. and this then shows all methods and variables I added to the module. I just want them to see specified ones because I have many additional ones that are only for internal use.
If this is your module mymodule.py: def expose_this(): print('yes please') def but_not_this(): print('definitely not') Importing it directly like this: import mymodule Gives a user access to mymodule.expose_this() and mymodule.but_not_this(), there's no way to change that, although you could call but_not_this somethi...
4
5
72,482,384
2022-6-2
https://stackoverflow.com/questions/72482384/how-to-read-emails-from-gmail
I am trying to connect my gmail to python, but show me this error: I already checked my password, any idea what can be? b'[AUTHENTICATIONFAILED] Invalid credentials (Failure)' Traceback (most recent call last): File "/Users/myuser/Documents/migrations/untitled3.py", line 29, in read_email_from_gmail mail.login(FROM_EMA...
You need to enable 'Less secure apps' in your Gmail account if you're going to check it this way. For that reason, it would be better to use the Gmail API. SMTP port is not set - ensure you are using the correct port (993)
15
2
72,480,454
2022-6-2
https://stackoverflow.com/questions/72480454/sending-email-with-python-google-disables-less-secure-apps
I am trying to send email using python. My code was working fine before Google disabled 'less secure apps'. My email address and password are both correct. server = smtplib.SMTP_SSL("smtp.gmail.com", 465) serverEmail = "EMAILADDRESS" serverPw = "QWERTY" server.login(serverEmail, serverPw) subject = "Rejection" body = "...
This is working for me. You need to generate an app password for this. See https://support.google.com/accounts/answer/185833?hl=en import smtplib as smtp connection = smtp.SMTP_SSL('smtp.gmail.com', 465) email_addr = 'my_email@gmail.com' email_passwd = 'app_password_generated_in_Google_Account_Settings' connection.logi...
8
6
72,479,262
2022-6-2
https://stackoverflow.com/questions/72479262/shap-python-model-type-not-yet-supported-by-treeexplainer-class-sklearn-ensemb
I tried to use Shap (Tree Explainer) for sklearn.ensemble._stacking.StackingClassifier explainer = shap.TreeExplainer(clf) shap_values = explainer.shap_values(x) shap.initjs() return shap.force_plot(explainer.expected_value[1], shap_values[1], x) But I got an error: Model type not yet supported by TreeExplainer: <clas...
TreeExplainer only works on tree-based models themselves, not on pipelines or metamodels that end with a tree-based model. If you want interpretability in terms of your original features, you will need to use the base Explainer class (or equivalently, the KernelExplainer class). Unfortunately, this will be approximate ...
4
5
72,476,514
2022-6-2
https://stackoverflow.com/questions/72476514/python-aiohttp-returns-a-different-reponse-than-python-requests-i-need-help-und
after the whole evening yesterday and morning today i really an help for understanding why, aiohttp request returns differently than requests request. import requests reqUrl = "https://api-mainnet.magiceden.io/all_collections_with_escrow_data" headersList = { "Accept": "*/*", " User-Agent" : " Mozilla/5.0 (Windows NT 1...
The text is actually in a StreamReader object in the content attribute get_image_data = await session.get('https://api-mainnet.magiceden.io/all_collections_with_escrow_data', headers=headersList) stream = get_image_data.content data = await stream.read() print(data)
4
2
72,472,526
2022-6-2
https://stackoverflow.com/questions/72472526/how-to-filter-out-nan-by-pydantic
How to filter out NaN in pytdantic float validation? from pydantic import BaseModel class MySchema(BaseModel): float_value: float
You can use confloat and set either the higher limit to infinity or the lower limit to minus infinity. As all numeric comparisons with NaN return False, that will make pydantic reject NaN, while leaving all other behaviour identical (including parsing, conversion from int to float, ...). from pydantic import BaseModel,...
6
4
72,473,515
2022-6-2
https://stackoverflow.com/questions/72473515/why-python-code-generation-from-proto-is-not-generating-classes
I'm currently trying to generate python code from a proto file. My proto file looks like this: syntax = "proto3"; package display; message Hello { uint32 version = 1; uint32 value = 2; int32 id = 3; } I used this protoc command to generate the python code: protoc -I="." --python_out="." test.proto And here is the res...
add --grpc_python_out="." to the protoc command. this will generate an additional script with the required classes
6
5
72,457,638
2022-6-1
https://stackoverflow.com/questions/72457638/why-isnt-mypy-seeing-types-from-typeshed
I'm trying to add more mypy type annotations to my existing codebase. I have a file that uses a lot of bs4. When I run the mypy checker on this file I get the error: error: Skipping analyzing "bs4": module is installed, but missing library stubs or py.typed marker In the mypy docs on "Missing library stubs" it says: ...
Here is the content of mypy typeshed. It doesn't include third-party libraries, limited only to standard library. So types for beautifulsoup are not shipped with mypy (and it would be really odd to do so, because these stubs are updated sometimes more often than mypy itself, plus other typecheckers rely on this typeshe...
5
1
72,455,487
2022-6-1
https://stackoverflow.com/questions/72455487/activating-venv-and-conda-environment-at-the-same-time
I am a beginner and was "playing around" with environments a bit. I came across a situation where it seemed that I had two environments activated: I create a directory, create an environment with venv, activate it and then also conda activate a conda environment which I created before. These are the commands: mkdir dum...
No, it does not mean they are both activated. Only one can have priority in the PATH, which is what I’d consider the simplest definition of what “activated” means, functionally. The indicators in the PS1 string (i.e., the shell’s prompt string) are not robustly managed. The two environment managers are simply unaware o...
10
9
72,460,444
2022-6-1
https://stackoverflow.com/questions/72460444/fastest-way-to-iterate-through-multiple-2d-numpy-arrays-with-numba
When using numba and accessing elements in multiple 2d numpy arrays, is it better to use the index or to iterate the arrays directly, because I'm finding that a combination of the two is the fastest which seems counterintuitive to me? Or is there another better way to do it? For context, I am trying to speed up the imp...
In general, the fastest way to iterate over an array is a basic low-level integer iterator. Such a pattern cause the minimum number of transformation in Numba so the compiler should be able to optimize the code pretty well. Functions likes zip and enumerate often add an additional overhead due to indirect code transfor...
7
2
72,461,109
2022-6-1
https://stackoverflow.com/questions/72461109/sqlalchemy-does-not-insert-default-values
I have workspacestable workspaces_table = Table( "workspaces", metadata_obj, Column("id", UUID(as_uuid=False), primary_key=True, default=uuid.uuid4), Column("name", JSONB(), nullable=False), Column("created_at", TIMESTAMP(timezone=False), default=datetime.datetime.now(), nullable=False), Column("updated_at", TIMESTAMP(...
Column(…, default=…) is a client-side default value that is used by SQLAlchemy Core (and SQLAlchemy ORM) when you do something like workspaces_table.insert(). Note that if SQLAlchemy creates the table then that column does not have a server-side DEFAULT: workspaces_table = Table( "workspaces", MetaData(), Column("id", ...
5
3
72,461,032
2022-6-1
https://stackoverflow.com/questions/72461032/plot-a-route-in-a-map
I'm using python and I need to plot a route in a map. I have a dataframe that looks like this: latitude longitude 41.393095 -8.703483 41.393095 -8.703483 41.393095 -8.703483 41.392483 -8.703088 40.942170 -8.540572 40.942188 -8.540567 41.187624 -8.568143 41.321009 -8.711874 41.345618 -8.547567 The order of the datafra...
Using This tutorial, I managed to plot the points on a map: # Create a bounding box to determine the size of the required map BBox = (df.longitude.min()-0.1, df.longitude.max()+0.1, df.latitude.min()-0.1, df.latitude.max()+0.1) # Downloaded using this tutorial: https://medium.com/@abuqassim115/thanks-for-your-response...
4
7
72,400,478
2022-5-27
https://stackoverflow.com/questions/72400478/with-python-oracledb-what-does-dpy-4027-no-configuration-directory-to-search-f
With the python-oracledb driver the code: import oracledb cs = "MYDB" c = oracledb.connect(user='cj', password=mypw, dsn=cs) gives the error: oracledb.exceptions.DatabaseError: DPY-4027: no configuration directory to search for tnsnames.ora The same error also occurs in a second case: import oracledb cs = "MYDB = (...
This error means you used a connection string that python-oracledb took to be some kind of alias it needed to look up in a tnsnames.ora file, but it didn't know where to find that file. Database connection strings in python-oracledb can be one of: An Oracle Easy Connect string like myhost:1521/orclpdb1 An Oracle Net C...
4
7
72,373,545
2022-5-25
https://stackoverflow.com/questions/72373545/what-is-the-difference-between-torch-nn-functional-grid-sample-and-torch-nn-func
Let's say I have an image I want to downsample to half its resolution via either grid_sample or interpolate from the torch.nn.functional library. I select mode ='bilinear' for both cases. For grid_sample, I'd do the following: dh = torch.linspace(-1,1, h/2) dw = torch.linspace(-1,1, w/2) mesh, meshy = torch.meshgrid((d...
Interploate is limited to scaling or resizing the input. Grid_sample is more flexible and can perform any form of warping of the input grid. The warping grid can specify the position where each element in the input will end up in the output. In simple terms, interpolate does not provide the ability to change the orderi...
4
1
72,434,896
2022-5-30
https://stackoverflow.com/questions/72434896/jupyter-kernel-doesnt-use-poetry-environment
I'm trying to install a Jupyter kernel for my poetry environment, but it seems like the kernel gets my base conda environment. Here's what I'm trying: poetry env list >ENV_NAME-HASH-py3.9 (Activated) poetry run which python >/Users/myusername/Library/Caches/pypoetry/virtualenvs/ENV_NAME-HASH-py3.9/bin/python poetry run...
Bonjour, I come tardily but I think I have your solution. If you just want to use your currently configured Poetry environment in VSCode with your .ipynb notebooks, you can do this for example: Create a new project with Poetry: poetry new test_ipynb cd test_ipynb Use a specific Python version with your environment: ...
11
6
72,439,540
2022-5-30
https://stackoverflow.com/questions/72439540/change-the-number-of-resources-during-simulation-in-simpy
I am currently working on a model which simulates a delivery process throughout an operating day in simpy. The deliveries are conducted by riders which are delivering one package at a time. The packages need to be delivered within a certain time window. In addition, the system deals with fluctuating demand throughout t...
Use a store instead of a resource. Resources has a fix number of resources. Stores works a bit like a bit more like a queue backed with a list with a optional max capacity. To reduce then number in the store, just stop putting the object back into the store. So is a example I wrapped a store with a class to manage the ...
4
5
72,436,467
2022-5-30
https://stackoverflow.com/questions/72436467/how-to-provide-type-hinting-to-userdict
I want to define a UserDict that reads values from JSON and stores a position for a given key. The JSON file looks like this: { "pages": [ { "areas": [ { "name": "My_Name", "x": 179.95495495495493, "y": 117.92792792792793, "height": 15.315315315315303, "width": 125.58558558558553 }, ... ] } ] } I would like to indicat...
Actually, you can directly provide the type to UserDict with square brackets ([...]) like you would with a Dict: class Page(UserDict[str, Position]): ... For Python 3.6 or earlier, this will not work. For Python >=3.7 and <3.9, you need the following to subscript collections.UserDict and put it in a separate block spe...
3
8
72,449,482
2022-5-31
https://stackoverflow.com/questions/72449482/f-string-representation-different-than-str
I had always thought that f-strings invoked the __str__ method. That is, f'{x}' was always the same as str(x). However, with this class class Thing(enum.IntEnum): A = 0 f'{Thing.A}' is '0' while str(Thing.A) is 'Thing.A'. This example doesn't work if I use enum.Enum as the base class. What functionality do f-strings i...
From "Formatted string literals" in the Python reference: f-strings invoke the "format() protocol", meaning that the __format__ magic method is called instead of __str__. class Foo: def __repr__(self): return "Foo()" def __str__(self): return "A wild Foo" def __format__(self, format_spec): if not format_spec: return "A...
74
105
72,454,359
2022-5-31
https://stackoverflow.com/questions/72454359/python-uniswap-subgraph-constant-product-formula
I'm trying to calculate the price impact on trades and am getting strange results. I am using uniswap v2 subgraph to get current data for WETH/USDC. def loadUni2(): query = """ { pairs ( first: 10 orderBy: volumeUSD orderDirection:desc ){ id reserve0 token0Price token0 { id symbol decimals } token1Price reserve1 token1...
you are not including the 0.3% percent fee which affects the amount of return value. initially we have "x" and "y" amount so constant product is k = x * y There is an inverse relationship between x and y because increase in one will lead to decrease on other this is our graph for this equation If you add some "x" to...
4
2
72,394,322
2022-5-26
https://stackoverflow.com/questions/72394322/how-to-use-sync-to-async-in-django-template
I am trying to make the Django tutorial codes polls into async with uvicorn async view. ORM query works with async view by wrapping in sync_to_async() as such. question = await sync_to_async(Question.objects.get, thread_sensitive=True)(pk=question_id) But I have no idea how to apply sync_to_async or thread inside Djan...
I have found several solutions for that: It's not safe. In your settings.py add: import os os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" Or get your Question object in separate function: @sync_to_async def get_question(question_id): return get_object_or_404(Question, pk=question_id) question = await get_question(pk...
5
1
72,401,377
2022-5-27
https://stackoverflow.com/questions/72401377/error-could-not-build-wheels-for-pandas-which-is-required-to-install-pyproject
I'm trying to install pandas via pip install pandas on my laptop. Environment: Window 11 Pro Python 3.10.4 Pip version 22.0.4 Compatibility: Officially Python 3.8, 3.9 and 3.10. You must have pip>=19.3 to install from PyPI. C:\Users\PC>pip install pandas WARNING: Ignoring invalid distribution -ywin32 (c:\users\pc\...
Pandas doesn't require Anaconda to work, but based on python310-32 in your output, you're using a 32-bit build of Python. Pandas evidently does not ship 32-bit wheels for Python 3.10 (they do have win32 wheels for Python 3.8 and Python 3.9 though). (There could be alternate sources for pre-built 32-bit wheels, such as ...
20
10
72,381,940
2022-5-25
https://stackoverflow.com/questions/72381940/permanently-change-the-default-python3-version-in-linux-ubuntu-on-windows
I'm using WSL2 with Ubuntu on Windows 11 v2004.2022.10 and I have both Python 3.8 and 3.9 installed. I want to make the 3.9 version the default, and I'm happy to remove Python 3.8 altogether if necessary. If I type python --version in Ubuntu, I get Python 3.8.10. I tried the following: sudo update-alternatives --instal...
You can always use sudo update-alternatives --config python3 and then select your python3 version. That should solve your issue without needing to do weird configs.
4
2
72,442,087
2022-5-31
https://stackoverflow.com/questions/72442087/cant-install-proj-8-0-0-for-cartopy-linux
I am trying to install Cartopy on Ubuntu and need to install proj v8.0.0 binaries for Cartopy. However when I try to apt-get install proj-bin I can only get proj v6.3.1. How do I install the latest (or at least v8.0.0) proj for cartopy?
I'm answering my own question here partly to help others with this problem, and partly as an archive for myself so I know how to fix this issue if I come across it again. I spent quite a while trying to figure it out, and wrote detailed instructions, so see below: Installing cartopy is a huge pain, and I've found using...
5
7
72,407,887
2022-5-27
https://stackoverflow.com/questions/72407887/python-opencv-error-unsupported-combination-of-source-format
I am trying to run this code: import cv2 import numpy as np src = np.array([[10, 20, 40, 50], [50, 20, 50, 20], [10, 10, 30, 60], [20, 40, 60, 70]]) dst1 = cv2.blur(src, ksize=(3, 3), borderType = cv2.BORDER_CONSTANT) print(dst1) dst2 = cv2.GaussianBlur(src, ksize=(3, 3), sigmaX=0, borderType = cv2.BORDER_CONSTANT) An...
if you construct an np.array like that, it's (default) format is np.int32, which is not supported. rather make it: src = np.array([[10, 20, 40, 50], [50, 20, 50, 20], [10, 10, 30, 60], [20, 40, 60, 70]], np.uint8) # <-- correct type !!!
5
3
72,450,281
2022-5-31
https://stackoverflow.com/questions/72450281/python-3-10-deprecation-warning-for-distutils
DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives from distutils.dir_util import copy_tree Is it something that I should worry about? Which import should I use to replace the from distutils.dir_util import copy_tree...
Change from: from distutils.dir_util import copy_tree copy_tree(loc_source, loc_destination) To: import shutil shutil.copytree(loc_source, loc_destination) Or, to replace existing files and folders: import shutil shutil.copytree(loc_source, loc_destination, dirs_exist_ok=True) Documentation: https://docs.python.org/...
4
9
72,374,296
2022-5-25
https://stackoverflow.com/questions/72374296/how-do-i-properly-change-package-name-built-with-poetry
I built a package using poetry package manager but I regret naming it because it sounds a bit childish. Besides, because poetry's default behavior is to force change the project's name to lower case (SuperPackage --> superpackage), it is difficult to import the package inside/outside the package's main directory. Here'...
Change the name field in pyproject.toml, run poetry update (not sure that's needed but do it just in case?) and change the directories names. Note that the name of the virtual environment on your computer will stay the same, but that probably isn't a problem as it only is a local ting.
11
12
72,437,583
2022-5-30
https://stackoverflow.com/questions/72437583/difference-between-forward-and-train-step-in-pytorch-lightning
I have a transfer learning Resnet set up in Pytorch Lightning. the structure is borrowed from this wandb tutorial https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY and from looking at the documentation https://pytorch-lightning.readthedocs.io/en/latest/common/l...
I am confused about the difference between the def forward () and the def training_step() methods. Quoting from the docs: "In Lightning we suggest separating training from inference. The training_step defines the full training loop. We encourage users to use the forward to define inference actions." So forward() defi...
4
9
72,425,408
2022-5-29
https://stackoverflow.com/questions/72425408/interrupt-not-prevent-from-starting-screensaver
I am trying to programmatically interrupt the screensaver by moving the cursor like this: win32api.SetCursorPos((random.choice(range(100)),random.choice(range(100)))) And it fails with the message: pywintypes.error: (0, 'SetCursorPos', 'No error message is available') This error only occurs if the screensaver is acti...
The Windows operating system has a hierarchy of objects. At the top of the hierarchy is the "Window Station". Just below that is the "Desktop" (not to be confused with the desktop folder, or even the desktop window showing the icons of that folder). You can read more about this concept in the documentation. I mention t...
43
52
72,427,869
2022-5-29
https://stackoverflow.com/questions/72427869/pytorch-cuda-version-is-always-10-2
I've installed a handful of PyTorch versions (CUDA 11.7 nightly, CUDA 11.6 nightly, 11.3), but every time, torch.version.cuda returns 10.2. I'd like to run PyTorch on CUDA 11.7. My graphics card has CUDA capability sm_86. [me@legion imagen-test]$ sudo pip3 install torch torchvision torchaudio --extra-index-url https://...
You've probably installed PyTorch with CUDA 10.2 among your different installed versions. This may be taking priority over the versions of PyTorch. To fix this, simply uninstall all versions of PyTorch with pip uninstall torch -y and reinstall PyTorch with CUDA 11.7. Source: https://discuss.pytorch.org/t/cuda-version-i...
4
2