QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
76,122,448
489,088
How to use numpy lexsort on a 3d array without changing the shape on the resulting array?
<p>I have a 3d array like so:</p> <pre><code>arr = [ [[1, 2, 0], [1, 0, 1], [1, 0, 0]], [[1, 2, 1], [1, 0, 2], [1, 2, 0]], [[1, 2, 2], [2, 0, 0], [1, 0, 3]] ] </code></pre> <p>I'd like to sort the inner arrays inside the second dimension array using the last item in that length 3 array as the first sorting column, then...
<python><arrays><numpy><numpy-ndarray>
2023-04-27 15:59:47
2
6,306
Edy Bourne
76,122,423
575,596
Python metaclass base class params not initialising
<p>I'm trying to create a metaclass that can extend the mandatory params from its base class.</p> <p>I have the following base class:</p> <pre><code>class BaseClass(JSONEncoder): def __init__(self, field1, field2, ...): self.field1 = field1 self.field2 = field2 ... </code></pre> <p>There are...
<python><python-3.x><typeerror><metaclass>
2023-04-27 15:56:50
1
7,113
MeanwhileInHell
76,122,411
8,964,393
Fill missing values with either previous or subsequent values by key
<p>I have this pandas dataframe: import pandas as pd import numpy as np</p> <pre><code>ds1 = {'col1':[1,1,1,1,1,1,1, 2,2,2,2,2,2,2], &quot;col2&quot; : [1,np.NaN,np.NaN,np.NaN,np.NaN,np.NaN,np.NaN, np.NaN,np.NaN,np.NaN,np.NaN,np.NaN,np.NaN,3]} df1 = pd.DataFrame(data=ds1) print(df1) col1 col2 0 1 1.0 1 ...
<python><pandas><replace><missing-data>
2023-04-27 15:55:29
2
1,762
Giampaolo Levorato
76,122,380
3,642,360
How to web scrape thomasnet website to get suppliers information in python
<p>I want to extract supplier information like supplier name, location, annual revenue, year founded, number of employees, product description etc from <a href="https://www.thomasnet.com/" rel="nofollow noreferrer">https://www.thomasnet.com/</a> for a particular location and category. For example, I want to extract all...
<python><html><web-scraping><beautifulsoup><python-requests>
2023-04-27 15:52:02
1
792
user3642360
76,122,360
2,915,302
Syntax error near ARRAY when I try to execute a multiple update in python with psycopg2
<p>I have a problem when I try to perform a multiple update of my table using psycopg2. When I run this query</p> <pre><code>query ='UPDATE table SET isValid = false where id = %s and customerid = %s and filed in %s' data = (id,customerid, fieldlist) cursor.execute(query, data) </code></pre> <p>where id and customer id...
<python><postgresql><psycopg2>
2023-04-27 15:49:48
1
488
P_R
76,122,317
4,139,024
How to type annotate List parameter with specific values in python
<p>I have a parameter that is a list of strings. However, I want to only allow certain strings, let's say &quot;hello&quot; and &quot;world&quot;. How can I correctly annotate the variable?</p> <p>Here is an example:</p> <pre class="lang-py prettyprint-override"><code>def foo(bar: List[str]): assert all(b in [&quot...
<python><python-3.x><types>
2023-04-27 15:44:56
1
3,338
timbmg
76,122,294
14,457,833
Pyinstaller adding directory inside dist as data
<p>I'm facing this issue while building a executable of my <a href="/questions/tagged/pyqt5" class="post-tag" title="show questions tagged &#39;pyqt5&#39;" aria-label="show questions tagged &#39;pyqt5&#39;" rel="tag" aria-labelledby="tag-pyqt5-tooltip-container">pyqt5</a> application. I've images folder which contain 6...
<python><pyqt5><pyinstaller>
2023-04-27 15:41:57
1
4,765
Ankit Tiwari
76,122,226
6,087,667
Plotting constant surface plot with `create_trisurf` of Plotly
<p>Plotly seems to having no problem plotting non-constant surfaces but throws an error when one has a constant surface (uncomment <code>c.z=1</code>). How can this be fixed? I necessarily need to start with pandas dataframe with 3 columns. I don't know what the Delaunay part means really either.</p> <pre><code>import ...
<python><pandas><plotly>
2023-04-27 15:34:22
0
571
guyguyguy12345
76,122,174
6,228,034
How to fix VSCode terminal to recognize commands 'python' and 'pip'
<p>I'm working with fresh installations of VSCode and Python 3.11. the commands <code>python</code> and <code>pip</code> are both recognized in the Window's powershell and command prompts. However, when I swap to VSCode, neither command is recognized in either terminal.</p> <p>VScode is obviously finding my python inst...
<python><powershell><visual-studio-code>
2023-04-27 15:29:19
1
477
W. Kessler
76,121,894
1,026,057
'datetime.datetime' object has no attribute '__module__' when returning results from Postgres hook in Airflow
<p>Given the following DAG definition:</p> <pre><code>from airflow.hooks.postgres_hook import PostgresHook from airflow.decorators import dag, task from airflow.utils.dates import days_ago default_args = { 'owner': 'airflow', } def get_data(): sql_stmt = &quot;SELECT * FROM table&quot; pg_hook = Postgres...
<python><postgresql><airflow>
2023-04-27 14:59:33
2
597
SelketDaly
76,121,882
4,487,457
Mocking a fake configuration during a unit test
<p>I have code that does something like this</p> <pre><code>from custom_paths import CONFIG_PATH class SomethingCool: def __init__(self, filepath: str) -&gt; None: with open(os.path.join(CONFIG_PATH, filepath)) as fd: self.config = yaml.safe_load(fd) blah blah do something </code></pre...
<python><unit-testing><pytest>
2023-04-27 14:58:30
1
2,360
Minh
76,121,781
775,821
capture network traffic and send to a remote machine
<p>I am trying to capture network traffic with tcpdump from a machine in the network and send each packet over the network to another device. I cannot save the packets captured by tcpdump in a file, because I need to process the packets as a stream (one by one) in real-time.</p> <p>I am using the following Python scrip...
<python><sockets><network-programming><tcpdump><packet-capture>
2023-04-27 14:49:28
2
805
Firouziam
76,121,714
5,852,692
Converting numpy array (or python list) to integer
<p><strong>I THINK BELOW QUESTION IS NOT POSSIBLE TO CALCULATE, SIMPLY BECAUSE 2^250 to BIG TO CALCULATE.</strong></p> <hr /> <p>I have a numpy array, which has a shape of <code>(1000,250)</code> with binary values and I want to convert the whole array to integer values;</p> <pre><code>&gt;&gt;&gt;in_[0] array([1, 0, 1...
<python><numpy><binary><integer>
2023-04-27 14:44:03
3
1,588
oakca
76,121,686
5,558,497
scan string until element in another list is not found, then split
<p>Say I have the following string</p> <pre><code>s = &quot;DH3580-Fr1-TRG-TRB-DH1234-Fr3&quot; </code></pre> <p>and I have a list of characters</p> <pre><code>l = ['Fr1', 'TRG', 'TRB', 'SOUL'] </code></pre> <p>Excluding the string upstream of the first <code>-</code> (<code>DH3580</code>), I want to scan <code>s</code...
<python><python-3.x><split>
2023-04-27 14:41:06
2
2,249
BCArg
76,121,624
1,422,096
Infix search in MySQL (search with pattern in the middle) with an index
<p>I have a MySQL 8 InnoDB compressed table, with an index:</p> <pre><code>set global innodb_file_per_table=1; create table t (id int primary key auto_increment, key varchar(200), value varchar(200)) row_format=compressed engine=innoDB; create index key_index on t(key) using BTREE; cr...
<python><mysql><search><full-text-search><innodb>
2023-04-27 14:34:35
1
47,388
Basj
76,121,448
575,596
Can metaclasses be made iterable?
<p>Trying to create a metaclass that inherits from a parent class, that inherits from JSONEncoder. However, I am getting the following error:</p> <p><code>TypeError: 'type' object is not iterable</code></p> <p>Code looks like:</p> <pre><code>class ParentClass(JSONEncoder): def __init__(self, ...): ... ...
<python><python-3.x><inheritance><metaclass>
2023-04-27 14:17:31
1
7,113
MeanwhileInHell
76,121,390
9,072,753
Unpack a tar archive generated by a shell command with Python tarfile
<p>I have a <code>nomad alloc exec</code> command kind-of like ssh that I am able to run tar on the other side and get stdout.</p> <p>I want to copy multiple files from a process that outputs a tar archive to stdout. In shell this is called a tar pipe, typically <code>ssh server tar cf - file1 file2 | tar xf - -C desti...
<python><python-3.x><linux>
2023-04-27 14:11:41
1
145,478
KamilCuk
76,121,334
12,636,391
Python: Check list of dictionaries with unknown size for certain conditions
<p>I'm pretty sure it's a beginners question, but I just can't find the solution for my problem. So I am thankful for every sort of help.</p> <p>My list of dictionaries with an unknown amount of entries and order looks something like this:</p> <pre><code>list_of_dict = [ {'value_a': '100', 'value_b': '25'}, {'v...
<python><list><dictionary>
2023-04-27 14:05:40
1
473
finethen
76,121,140
21,787,377
How can we use machine learning to detect nude content in user-uploaded videos
<p>How can I use <code>machine learning</code> to detect nude content in user-uploaded videos on my educational website forum?</p> <p>I'm building an educational website forum where users can upload videos, but some users may upload nude content which is against our terms of use. We have created a report feature, but r...
<python><machine-learning><computer-vision>
2023-04-27 13:45:17
1
305
Adamu Abdulkarim Dee
76,120,987
20,122,390
How can I change the headers of an uploaded CSV file?
<p>I have an application with Python and FastAPI which has an endpoint that receives a CSV file from the client to later save its content in a non-relational database (so I convert the CSV to dictionary). However I want to edit the CSV header to save it with a different one in the database. I tried the following:</p> <...
<python><csv><dictionary><backend><fastapi>
2023-04-27 13:28:26
0
988
Diego L
76,120,890
5,433,628
How to find all the possible exceptions raised by float()
<p>I know that <code>float(&quot;foo&quot;)</code> could raise a <code>ValueError</code>, so I wrote my method as follows:</p> <pre class="lang-py prettyprint-override"><code>def cast_to_float(value: str) -&gt; float: try: return float(value) except ValueError as e: # deal with it </code></pre> ...
<python>
2023-04-27 13:17:54
1
1,487
ebosi
76,120,706
6,195,489
Merge two dataframes, with multiple entries put into a list in a cell
<p>I have two dataframes:</p> <p>df_A</p> <pre><code>id status duration 1 C 1:00 2 F 3:00 3 D 2:50 4 Y 1:00 </code></pre> <p>df_B</p> <pre><code>id loaded 1 grand 1 vice 1 cont 2 grand 2 bliss 3 test </code></pre> <p>I would like to merge these such that the result looks lik...
<python><pandas><dataframe>
2023-04-27 12:56:46
3
849
abinitio
76,120,102
5,852,692
Keras predicting scalar value from a vector via NN
<p>I want to predict the scalar value (between 0 and 100) from the given vector (size=250, binary elements). I have a dataset, which contains 1000 x values and 1000 y values:</p> <pre><code>&gt;&gt;&gt;in_.shape (1000, 250) &gt;&gt;&gt;in_[0] array([1, 0, 1, 1, 1, 1, 1, 1, ...]) &gt;&gt;&gt;out.shape (1000,) &gt;&gt...
<python><tensorflow><keras><vector><binary>
2023-04-27 11:55:22
1
1,588
oakca
76,120,075
11,898,085
Xsens Device API function 'startRecording' fails
<p>I'm trying to write Xsens Device API Python code for reading live data from three MTw sensors connected to a Awinda2 USB Dongle. However, the library function <code>startRecording</code> fails every time. I've tried numerous rearrangements without success. My OS is Linux. The question is, how to make the function wo...
<python><sensors><wireless>
2023-04-27 11:52:20
1
936
jvkloc
76,120,029
7,895,542
How to type hint function that accepts Union of TypedDicts and Union of Literals?
<p>So i have a situation like this example:</p> <pre><code>from typing import Literal, overload, TypedDict, LiteralString class Test1(TypedDict) test1: str class Test2(TypedDict): test2: str @overload def _get_actor_key( actor: Literal[&quot;test1&quot;], game_action: Test1, ) -&gt; str: ... @ov...
<python><python-typing><pyright>
2023-04-27 11:47:50
2
360
J.N.
76,119,902
6,198,942
How to create a custom JSON mapping for nested (data)classes with SQLAlchemy (2)
<p>I want to persist a python (data)class (i.e. <code>Person</code>) using imperative mapping in SQLAlchemy. One field of this class refers to another class (<code>City</code>). The second class is only a wrapper around two dicts and I want to store it in a denormalized way as a JSON column.</p> <p>My example classes l...
<python><json><sqlalchemy>
2023-04-27 11:34:24
2
1,806
moe
76,119,703
9,974,205
looking for a random matrix of zeros and ones in python with a limited amount of ones
<p>I am generating a matrix of zeros and ones in python as</p> <pre><code>poblacionCandidata = np.random.randint(0, 2, size=(4, 2)) </code></pre> <p>However, I need for it to be only two ones at most in each row.</p> <p>I have checked <a href="https://stackoverflow.com/questions/61218595/generate-binary-random-matrix-w...
<python><matrix><random><max>
2023-04-27 11:11:47
2
503
slow_learner
76,119,596
3,653,343
numpy assert_equals for nested floating point
<p>I got a strange behaviour regarding an equal check for the weights for the vgg16 machine learning model</p> <p>loading two times the model</p> <pre><code>import torch from torch import nn from torchvision.models import vgg16 import numpy as np import torchvision.models as models model = models.vgg16(weights='IMAGEN...
<python><numpy><machine-learning><pytorch><equality>
2023-04-27 10:59:31
2
4,667
Nikaido
76,119,489
3,360,241
Reloading workers state from disk in FastAPI
<p>Reading through existing questions, I am still not sure if it is feasible to reload state of <strong>all</strong> Worker processes in FastAPI.</p> <p>Bellow is a simplified app sketch:</p> <pre><code>some_dict = load_data(path) server = Server(some_dict) app = FastAPI() app.include_router(server.router) uvicorn.ru...
<python><multithreading><multiprocessing><fastapi>
2023-04-27 10:45:16
1
5,317
John
76,119,462
8,965,861
Type comment list of values
<p>I'm using Jython 2.1, so I cannot use type annotations (<code>{var}: {type}</code>) but I use type comments (<code># type: {type}</code> for variables and <code># type: ({param_type}) -&gt; {ret_type}</code> for functions).</p> <p>I would like to specify that a variable/parameter can only contain specific values, bu...
<python><python-2.x><jython><python-typing><pylance>
2023-04-27 10:39:15
0
619
LukeSavefrogs
76,119,400
3,909,896
PySpark remove duplicated messages within a 24h window after an initial new value
<p>I have a dataframe with a status (integer) and a timestamp. Since I get a lot of &quot;duplicated&quot; status messages, I want to reduce the dataframe by removing any row which repeats a previous status within a 24h window after a &quot;new&quot; status, meaning:</p> <ul> <li>The first 24h window starts with the fi...
<python><apache-spark><pyspark><apache-spark-sql>
2023-04-27 10:32:35
3
3,013
Cribber
76,119,384
10,003,981
How to test a function which has a call to get connection to db within it using pytest?
<p>I have to test a function which has a call within it to get the snowflake connection object. I have created a fixture with dummy data for the main Class itself which has the function to test as well as the function to get connection which is used within the &quot;to be tested&quot; function.</p> <p>This is the sampl...
<python><pytest>
2023-04-27 10:30:51
0
822
ASHISH M.G
76,119,381
12,965,658
Map columns in dataframe from list
<p>I have a pandas dataframe.</p> <pre><code>is_active Device True 1 False 2 </code></pre> <p>I have a file called mapping.json</p> <pre><code>[ { &quot;description&quot;: &quot;Desktop&quot;, &quot;deviceId&quot;: &quot;1&quot; }, { &quot;description&quot;: &quot;Smartphone&quot;, &quo...
<python><python-3.x><pandas><dataframe>
2023-04-27 10:30:22
1
909
Avenger
76,119,231
575,596
String annotations of Python fields
<p>Does Python support any type of string annotation for class fields? For example, in Golang, I can define a structure like this, with an optional string tag:</p> <pre><code>type User struct { Name string `example:&quot;name&quot;` } </code></pre> <p>I need to define a new class in Python, which contains fields n...
<python>
2023-04-27 10:13:36
2
7,113
MeanwhileInHell
76,119,007
5,919,010
Efficient way to handle group of ids in pandas
<pre><code>df = pd.DataFrame({ 'caseid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'timestamp': [10, 20, 30, 10, 20, 30, 10, 20, 30] 'var1': [np.nan, np.nan, np.nan, 10, np.nan, 11, 12, 13, 14], 'var2': [2., 3., 4., np.nan, 5., 6., np.nan, np.nan, np.nan] }) </code></pre> <p>I need to find the first (and last) ...
<python><pandas>
2023-04-27 09:47:35
1
1,264
sandboxj
76,118,669
2,089,929
pymongo.errors.ConfigurationError: The DNS operation timed
<p>I am trying to connect the Mongo database with fast API, some i am able to make successful connection, on any code change happen, and restart the server i am getting below error</p> <pre><code>pymongo.errors.ConfigurationError: The DNS operation timed out after 21.168028831481934 seconds </code></pre> <p>I am using ...
<python><mongodb><fastapi>
2023-04-27 09:11:37
0
3,166
aman kumar
76,118,530
1,291,302
Is letting mypy handle typechecking a good practice in python?
<p>Say I have a function:</p> <pre><code>from typing import Union def foo(bar: Union[float, list]): if type(bar) == float: bar = [bar] return [baz(i) for i in bar] </code></pre> <p>The question is that technically, I left part of typechecking for the typehints, which are not evaluated by python, but b...
<python><mypy><typing>
2023-04-27 08:54:49
1
624
JonnyRobbie
76,118,444
3,875,610
Perform t-test per sub-group in pandas
<p>I have a dataframe (df) where I want to perform t-test on observation for consequent groups. The number of groups is not constant.</p> <p><strong>Dataframe:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>key</th> <th>group</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>A1<...
<python><pandas>
2023-04-27 08:43:35
1
1,829
Anubhav Dikshit
76,118,361
11,426,624
stack a pandas dataFrame
<p>I have a pandas dataframe</p> <pre><code>df = pd.DataFrame({'user':[1,2,2,3], 'date':['2023-04-12', '2023-04-13', '2023-04-15','2023-04-18'], 'variable':['x1','x1','x2','x1'], 'sth':['xx','yy','yy','zz']}) </code></pre> <pre><code>user date variable sth 0 1 2023-04-12 x1 xx 1 2 ...
<python><pandas><dataframe>
2023-04-27 08:33:34
0
734
corianne1234
76,118,329
19,041,437
How to match a column based on another one to fill a third column
<p>Let's say I have a dataframe:</p> <pre><code>data = {'col1': ['a1','c3','b1','a2','','','',''], 'col2': ['','', '','','','','',''], 'col3': ['b1\\whatever', 'c1\\etc', 'a1\\something', 'a2\\random', 'a3\\somethingrandom', 'a4\\something','b2', 'b3']} df = pd.DataFrame(data) col1 col2 ...
<python><pandas><dataframe>
2023-04-27 08:29:08
1
502
grymlin
76,118,325
12,173,376
How can I provide Python bindings for variadic template callables with pybind11?
<p>I am trying to create Python bindings using pybind11 for a C++17 library that has a lot of variadic (member) functions or constructors.</p> <pre class="lang-cpp prettyprint-override"><code>// variadic member function struct Bar { template &lt;typename... Args&gt; void baz(Args&amp;&amp;...){ /*...*/ } }; //...
<python><c++><c++17><variadic-templates><pybind11>
2023-04-27 08:28:55
1
2,802
joergbrech
76,118,201
1,788,656
Subtracting unaligned xarrays
<p>All, Subtracting two unaligned xarrays yield a new array with a different shape as below. The shape of the subtracted arrays is (2918,25,53) and the shape of the difference is (2916,25,53)</p> <pre><code>ds = xr.tutorial.load_dataset(&quot;air_temperature&quot;) # subtracting un-aligned dimensions! tem_data=ds.air...
<python><python-3.x><numpy><python-xarray>
2023-04-27 08:14:54
1
725
Kernel
76,118,198
8,461,786
Make sure module is ran even though it is not imported anywhere
<p>In my Flask app, I have a file <code>controllers.py</code> with <code>some_process</code> in it:</p> <pre><code>class SomeProcess: def __init__(self): self.subscribers = [] def subscribe(self, subscriber): self.subscribers.append(subscriber) return subscriber def notify(self, da...
<python>
2023-04-27 08:14:25
1
3,843
barciewicz
76,118,124
19,325,656
How to parse and save large pydantic model to sqlalchemy
<p>I'm writing my first app in <code>FastAPI</code> that saves output dictionary output from another program. This output looks something like this. In the header key there is way more data in the tuple <code>irl</code> I've just shortened it for question purposes</p> <pre><code>{'worksheet': 'TASKS', 'row_index': 2, '...
<python><sqlalchemy><fastapi><pydantic>
2023-04-27 08:04:59
1
471
rafaelHTML
76,118,029
2,110,805
Get features names with tensorflow-datasets (tfds)
<p>I just started using <code>tensorflow-datasets</code> and I'm a bit puzzled. I spent almost an hour googling it and I still cannot find a way to get feature names in a dataframe. I guess I'm missing something obvious.</p> <pre><code>import tensorflow_datasets as tfds ds, ds_info = tfds.load('iris', split='train', ...
<python><tensorflow><machine-learning><tensorflow-datasets>
2023-04-27 07:55:13
1
14,653
Cyrille
76,117,907
9,042,093
How to import modules in subprocess.popen
<p>I have a template directory where my <strong>test.py</strong> file is present.</p> <p>Path to test.py dir is - <strong>/user/document/test1/template/test.py</strong></p> <p>(I have <code>__init__.py</code> as well)</p> <p>contest of <strong>test.py</strong> is</p> <pre><code>import os test_dict = { 'number' : ['...
<python><subprocess>
2023-04-27 07:42:13
0
349
bad_coder9042093
76,117,743
235,671
Extract Excel file from a multipart/signed email attachment
<p>I need to extract an Excel email attachment from a signed email that I fetch via Microsoft Graph.</p> <p>Postman shows the <code>contentType</code> as <code>multipart/signed</code> and the <code>name</code> as <code>smime.p7m</code> so I guess I somehow need to unpack this attachment first.</p> <p>Can you help me fi...
<python><python-3.x><encryption><smime>
2023-04-27 07:20:19
1
19,283
t3chb0t
76,117,727
7,659,682
What are the rules for the result dtype in arithmetic operations of np.arrays with different dtypes?
<p>Using NumPy I do this operation:</p> <pre><code>x = np.array([1, 2], dtype=np.float16) y = np.array(1, dtype=np.float32) z = x * y print(z.dtype) </code></pre> <p>and the result is</p> <blockquote> <p>float16</p> </blockquote> <p>But, when I switch the data types as below:</p> <pre><code>x = np.array([1, 2], dtype=n...
<python><numpy>
2023-04-27 07:18:13
0
726
Ozcan
76,117,377
11,267,783
PyQt communication between different class
<p>I wanted to share data between two layouts (two classes in my case) in PyQt5.</p> <p>How can I connect one layout action to the layout of another class properly? For example every time I click on the button on class Left, the spinbox, on class Right, increases.</p> <pre class="lang-py prettyprint-override"><code> cl...
<python><pyqt5>
2023-04-27 06:30:45
2
322
Mo0nKizz
76,117,172
5,942,100
Tricky populate fields of excel sheet based on mapping using Pandas
<p>I have a df, df1, that, based on the bound, year, and state, I would like to populate another df, df3, with values from df2 if the year, qtr, state bound, and type match. I am thinking of using a combination of Pandas and OpenPyXL, but still researching this.</p> <p><strong>Data</strong></p> <p>df1</p> <pre><code>ye...
<python><pandas><numpy>
2023-04-27 05:59:24
1
4,428
Lynn
76,116,800
16,527,596
How to call the functions of 2 other classes into another class
<p>Im new to Python OOP and i was hoping you could help me with my problem</p> <p>Im asked to use the results of a function in 2 other classes in 3rd class to find a result but im unsure on how to do that</p> <pre><code>class ADC(): n_bit = np.array([2, 3, 4, 6, 8, 10, 12, 14, 16], dtype=np.int64); def __init__...
<python><oop>
2023-04-27 04:38:11
1
385
Severjan Lici
76,116,642
7,133,942
How to create a complex mulit partition array with numpy
<p>I have an array with 96 price values called <code>price_array</code> and would like to have a 4 dimensional array with the following characteristics for each dimesions:</p> <ol> <li>The first dimension quantifies the number of partitions <code>price_array</code> should have. The first entry just means, the whole arr...
<python><arrays><numpy>
2023-04-27 04:01:58
1
902
PeterBe
76,116,626
12,715,723
Error "'jupyter' is not recognized as an internal or external command, operable program or batch file" when installing Jupyter Notebook
<p>I am trying to install Jupyter Notebook without installing Anaconda on my Windows. I have followed the steps in <a href="https://jupyter.org/install" rel="nofollow noreferrer">https://jupyter.org/install</a> but seems not to work. I have tried to close &amp; reopen the command prompt and restart the Windows but didn...
<python><python-3.x><jupyter-notebook><jupyter>
2023-04-27 03:57:05
4
2,037
Jordy
76,116,445
2,604,247
Python Library to Substitute Some Texts in a Big Text File
<p>Using Python 3.10 on Ubuntu 22.04.</p> <p>Here is the scenario. There is a large text file called <code>raw.txt</code> stored locally with some parameterised text. A small example would be like</p> <pre><code>This letter serves to confirm the employment of {full_name} at {company_name}, at {city_name} with a compens...
<python><text>
2023-04-27 03:08:02
1
1,720
Della
76,116,200
489,088
How to sort 2d numpy array by items in the inner array?
<p>I have an array of arrays, and would like to sort these inner arrays based off the value of the first element in them, then the third element, and finally the second element.</p> <p>I tried specifying the order parameter in np.sort, but it gives me an error given this array is not an structured array:</p> <pre><code...
<python><arrays><numpy><sorting><numpy-ndarray>
2023-04-27 01:48:52
1
6,306
Edy Bourne
76,116,141
2,735,009
Mapreduce not running on 8 CPUs but works on 2 CPUs (Amazon Sagemaker)
<p>I have the following piece of code that I'm trying to run on multiple machines using <code>Amazon Sagemaker</code>. I am printing a few things for debugging in this code. When I run this code on an instance with 2 CPUs, it runs just fine. But when I try to run it on an instance with 8 CPUs, it doesn't print anything...
<python><machine-learning><parallel-processing><nlp><mapreduce>
2023-04-27 01:30:34
1
4,797
Patthebug
76,116,135
2,954,547
Pytest: print something in conftest.py without requiring "-s"
<p>I am using environment variables to control some Hypothesis settings in <code>conftest.py</code>:</p> <pre class="lang-py prettyprint-override"><code>test_max_examples = int(os.environ.get(&quot;TEST_MAX_EXAMPLES&quot;, &quot;100&quot;).strip()) hypothesis.settings.register_profile( &quot;dev&quot;, print_bl...
<python><pytest><python-hypothesis>
2023-04-27 01:29:31
1
14,083
shadowtalker
76,116,121
1,265,955
Slicing twice in Python
<p>Often times I have an offset and length of data I want to extract from a str or bytes.</p> <p>The way I most often see it done is:</p> <pre><code>mystr[ offset: offset+length ] </code></pre> <p>How much less efficient is it to do the following instead (which seems clearer to understand)?</p> <pre><code>mystr[ offset...
<python><performance><slice>
2023-04-27 01:26:00
1
515
Victoria
76,115,668
5,672,613
Poor rouge metric on CNN DailyMail dataset for pretrained T5 model
<p>I am trying to fine-tune a pre-trained T5 model on CNN/DailyMail dataset with the following code:</p> <pre class="lang-py prettyprint-override"><code>import torch import torch.nn as nn import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from datasets import load_dataset fro...
<python><deep-learning><pytorch><huggingface-transformers>
2023-04-26 23:06:29
0
694
Robur_131
76,115,465
19,576,113
tqdm not refreshing postfix after last iteration
<p>I have the following code:</p> <pre><code>for epoch in range(start_epoch, end_epoch): train_loss = 0.0 # Define training progress bar train_pbar = tqdm(train_dataloader, desc=f&quot;Epoch {epoch}/{end_epoch}&quot;) for inputs, targets in train_pbar: # Do something ... train_pbar.se...
<python><machine-learning><deep-learning><progress-bar><tqdm>
2023-04-26 22:13:51
0
487
Janikas
76,115,311
869,809
using session within template in flask jinja2 application?
<p>I made a small test project. See <a href="https://github.com/rkiddy/flask_template" rel="nofollow noreferrer">https://github.com/rkiddy/flask_template</a> for setup. I expect to see &quot;maybe&quot; on the page upon first access. Then I expect to be able to save to the session and use the value as shown. I think th...
<python><flask><jinja2>
2023-04-26 21:40:27
1
3,616
Ray Kiddy
76,115,277
14,715,170
How to use oauth2client.tools.run_flow with exceptions in python?
<p>When I try to run the below code,</p> <pre><code>from oauth2client import tools creds = tools.run_flow(flow, store, flags) </code></pre> <p>When I close the web browser without logging into it, Following is the screen that appears and freeze like this way on terminal and the page keeps loading and show nothing in my...
<python><python-3.x><django><google-drive-api><oauth2client>
2023-04-26 21:35:52
0
334
sodmzs1
76,115,261
11,761,166
How can I set protection on all excel files in a directory with openpyxl?
<p>I thought I would be able to set protection on the first sheet of all excel files in a directory using the method below, but for some reason I keep getting a <code>FileNotFoundError: [Errno 2] No such file or directory:</code> error even though the file exists and is found.</p> <p>The reason I believe that it should...
<python><excel><openpyxl>
2023-04-26 21:33:16
1
694
Rory
76,115,225
7,447,976
How to create a Boolean array with the same shape of a list containing multiple arrays
<p>I have a list that contains multiple same size arrays. I would like to create a 0-1 array with the same shape where every element in the list that is equal to a user-define value should be set as 0 in the 0-1 array.</p> <pre><code>import numpy as np y = ([np.array([[1., 0., 0.], [0., 0., 1.], [0., 0...
<python><list><numpy><boolean>
2023-04-26 21:28:12
1
662
sergey_208
76,115,009
6,824,949
Unable to install python3.8-venv on Ubuntu 22.04
<p>My objective is to create a Python <code>virtualenv</code> that uses Python <code>3.8</code> on Ubuntu 22.04. To do that I need <code>python3.8-venv</code>. After installing Python <code>3.8</code>, here are the steps I followed to install <code>python3.8-venv</code>:</p> <ol> <li>Attempt to install <code>python3.8-...
<python><ubuntu><ubuntu-22.04>
2023-04-26 20:54:59
0
348
aaron02
76,114,815
10,198,988
Crop array of images more efficiently python cv2
<p>I have some code that crops an ROI on a 3D array of images (so an array of image arrays) in python. I have code running now using a while loop, but it seems to be really slow. I was wondering if there was a more efficient way of doing this process as this seems to be taking quite some time for my large amount of ima...
<python><arrays><numpy><opencv><crop>
2023-04-26 20:23:49
1
468
obewanjacobi
76,114,767
9,415,280
tensorflow EarlyStopping check point to save best model on many trainning itteration
<p>I train a model on a huge set of data, too big for my memory. So I load chunk of my data set, and loop on this chunks on the trainning operation one at time.</p> <p>for exemple:</p> <pre><code> checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath='blabla.h5', moni...
<python><tensorflow><callback>
2023-04-26 20:16:39
1
451
Jonathan Roy
76,114,674
6,734,243
how to install a python package from a wheel that I don't exactly know the name?
<p>In a CI I create the Wheel of my package automatically and use it to run some test.</p> <p>running:</p> <pre><code>python -m build </code></pre> <p>Create a dist directory with a <code>.whl</code> file.</p> <p>now I would like to run the installation with test extras:</p> <pre><code>python -m pip install '*.whl[test...
<python><command-line>
2023-04-26 20:05:30
1
2,670
Pierrick Rambaud
76,114,591
2,791,067
Error on django-bootstrap-icons for cusom_icon in django project
<p>Normal bootstrap icon is working fine. like <em>{% bs_icon 'slack' size='2em' %}</em>.</p> <p>But when I am going to use <strong>custom_icon</strong> using <strong>django_bootstrap_icons</strong> module by using <em>{% custom_icon 'c-program' %}</em>. Its producing error:</p> <pre><code>KeyError at / 'fill-rule' Re...
<python><django>
2023-04-26 19:53:40
0
2,783
Roman
76,114,560
10,266,106
Decreasing Runtime of Scipy Statistical Computations
<p>I have a 2-D Numpy array with a shape 2500, 200, where Scipy is to compute statistics (gamma CDF specifically) at each entry in the array. I've provided a random generation of floating point numbers for those aiming to run the code locally, note that the data in this array must be expressed as decimals. The code is ...
<python><numpy><scipy><numpy-ndarray><scipy.stats>
2023-04-26 19:50:15
1
431
TornadoEric
76,114,381
11,779,941
BigQuery - How to configure write disposition for a insert_rows job?
<p>I'm creating a flow to insert rows in a BigQuery table from a list of dictionaries with the following format:</p> <pre><code>[ {'column1': 'value11', 'column2': 'value21', 'column3': [{'subfield1':'value131'}]}, {'column1': 'value12', 'column2': 'value22', 'column3': [{'subfield1':'value231'}]}, {'column1': 'value12...
<python><google-bigquery><jupyter><google-client>
2023-04-26 19:25:10
2
445
tcrepalde
76,114,292
1,515,117
Hyperlinks in Cells using Python Tabulator
<p>I am using Tabulator in Python to generate dynamic Quarto reports. I would like to embed a hyperlink in each cell to navigate to another page when clicked. I wasn't able to find how to do this from the documentation here: <a href="https://panel.holoviz.org/reference/widgets/Tabulator.html" rel="nofollow noreferrer">...
<python><tabulator><quarto><tabulator-py>
2023-04-26 19:12:27
1
3,405
Vince
76,114,022
15,803,668
Inaccurate Y Values When Extracting Text Coordinates
<p>I'm using <code>PyQt5.QWebEngineView</code> to display a pdf. Currently I'm working with <code>PDF.js</code> to extract text coordinates (based on this <a href="https://stackoverflow.com/questions/48950038/how-do-i-retrieve-text-from-user-selection-in-pdf-js">question</a>) from a selected region in a PDF document us...
<javascript><python><pdf.js><qwebengineview>
2023-04-26 18:34:52
1
453
Mazze
76,113,858
5,921,602
Google Search Console API error "Request had insufficient authentication scopes."
<p>I want to get result from search analytics query of Google Search Console API (<a href="https://developers.google.com/webmaster-tools/v1/searchanalytics/query" rel="nofollow noreferrer">ref</a>). Using API Explorer method on the right of the page, I get return 200 as a response, following with the json result. See t...
<python><google-search-console>
2023-04-26 18:12:25
0
863
khusnanadia
76,113,705
4,348,400
How to check for `list(np.ndarray)` in Python code?
<p>Looking at this <a href="https://stackoverflow.com/questions/27890735/difference-between-listnumpy-array-and-numpy-array-tolist">Difference between list(numpy_array) and numpy_array.tolist()</a> got me interested in this question. While I don't think that calling <code>list</code> on a numpy array is necessarily a p...
<python><numpy><abstract-syntax-tree>
2023-04-26 17:52:55
0
1,394
Galen
76,113,628
4,309,647
Plotly 3D Surface Cutting Out Data
<p>I tried this code with Plotly 5.10.0:</p> <pre><code>import plotly.graph_objects as go import numpy as np x = np.arange(0, 10) y = np.arange(0.5, 1.525, 0.025) np.random.seed(56) z = np.random.uniform(0.1, 0.5, size=(len(x), len(y))) fig = go.Figure(go.Surface( x=x, y=y, z=z) ) fig.show() </code></pr...
<python><plotly>
2023-04-26 17:41:34
1
315
fmc100
76,113,589
5,987
What does Python's open do when errors=None?
<p>The documentation for the <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow noreferrer"><code>open</code> function</a> states that the default for the <code>errors</code> argument is <code>None</code>. However it doesn't say anywhere what action that will result in; it only lists the var...
<python><file>
2023-04-26 17:35:36
1
309,773
Mark Ransom
76,113,571
2,326,788
Higher dimension matrix multiplication
<p>Suppose I have:</p> <ol> <li><p><strong>A</strong>, a matrix of shape (m, 3). <strong>A<sub>i</sub></strong> is the i<sup>th</sup> row of this matrix.</p> </li> <li><p>n matrices <strong>S<sub>1</sub></strong>, ..., <strong>S<sub>n</sub></strong>, each one of shape (3, 3)</p> </li> <li><p>n vectors <strong>v<sub>1</...
<python><numpy><tensor>
2023-04-26 17:33:44
2
325
Cider
76,113,561
4,502,950
How to delete nan in a column if conditions satisfies in another column
<p>I have a data frame with many columns I want to delete rows with null values in column 'Course' if another column 'Sheet' value is Gdg</p> <pre><code>Course Sheet_Name Nan Gdg course 1 Gdg course 2 ret nan ret </code></pre> <p>resulting column should be</p> <pre><code>Course Sheet_Name course ...
<python><pandas>
2023-04-26 17:32:43
2
693
hyeri
76,113,307
20,122,390
How can I scrape an interactive map with python?
<p>I have a page like this: <a href="https://www.enel.com.co/es/personas/mantenimientos-programados.html" rel="nofollow noreferrer">https://www.enel.com.co/es/personas/mantenimientos-programados.html</a></p> <p><a href="https://i.sstatic.net/i1Zpw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/i1Zpw.png...
<python><selenium-webdriver><web-scraping><python-requests><request>
2023-04-26 16:57:24
1
988
Diego L
76,113,110
4,534,466
Streamlit - Code block not showing copy to clipboard icon
<p>I am building a dashboard using Streamlit. I want to create a text box with a copy to clipboard button similar to the image:</p> <p><a href="https://i.sstatic.net/HNPRC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HNPRC.png" alt="enter image description here" /></a></p> <p>I've added the following ...
<python><python-3.x><streamlit>
2023-04-26 16:32:28
1
1,530
João Areias
76,113,096
20,646,254
Parallel automation of web scraping with Kubernetes
<p>I have a database, which collects requests from users. Each request consists of two main info: timestamp (date and time field) and task the system needs to do in backend (logged) page. On defined time in request the Python script opens certain webpage, log in with provided user's login data, and do the task defined ...
<python><kubernetes><digital-ocean>
2023-04-26 16:30:43
0
447
TaKo
76,113,094
21,420,742
Getting first row by ID in Python
<p>I have a piece of code that should be getting the <code>first_team</code> (first value) of a column grouped by ID and setting it to a dictionary, but what I am seeing is it is only getting the first value with value. Excluding those that are NaN.</p> <p>Here is a sample dataset</p> <pre><code> ID date ...
<python><python-3.x><pandas><dataframe><group-by>
2023-04-26 16:30:38
1
473
Coding_Nubie
76,112,858
1,843,329
How to replace pip install's removed install-option with its config-settings equivalent?
<p>I was previously installing a custom Python package with a C++ extension successfully on Windows by using this:</p> <pre><code> pip install --install-option=build_ext --install-option=&quot;--library-dirs=/path/to/lib&quot; *.zip </code></pre> <p>But then pip upgraded to 23.1 and its <code>--install-option</code>...
<python><pip><setuptools><python-packaging>
2023-04-26 16:04:15
3
2,937
snark
76,112,754
274,460
How can I use `select.select()` with `readline()`?
<p>Sample code:</p> <pre><code>import os import select r, w = os.pipe() rf = open(r, &quot;rb&quot;) wf = open(w, &quot;wb&quot;) wf.write(b&quot;abc\n&quot;) wf.write(b&quot;def\n&quot;) wf.flush() for ii in range(2): select.select([rf], [], []) print(rf.readline()) </code></pre> <p>This only prints out the f...
<python><python-3.x><select>
2023-04-26 15:52:00
0
8,161
Tom
76,112,733
7,477,996
I want to add diagonal text in a transparent image as a watermark. But that text should be dynamic
<p>I want to add diagonal text in a transparent image as a watermark. But that text should be dynamic. I have attached the image. I want to do something like that.</p> <p>I used the code but its noting showing in the text.</p> <pre><code>from PIL import Image, ImageDraw, ImageFont img = Image.new(&quot;RGB&quot;, (50...
<python><automation>
2023-04-26 15:49:20
1
1,037
Md Jewele Islam
76,112,722
10,620,003
Normalize an array based on another array
<p>I have an array with size A = (n, L*w) and I have a maximum array with size MAX =(n, w). I want to normalize the</p> <p>A based on the MAX array. I want to divide the value of array A to MAX by the window size of w. Here is a simple example:</p> <pre><code>import numpy as np A= np.random.randint(10, size = (2, 6)) M...
<python><python-3.x>
2023-04-26 15:47:38
1
730
Sadcow
76,112,690
21,404,794
Weighting sample values in scoring methods in scikit-learn
<p>I'm training a Gaussian Process regressor in a mix of categorical and numerical features, and for most categorical features, the amount of data I have is ok, but some categorical features are really sparse, and I think that makes the model mess up when it's tested against those features.</p> <p>Is there a way to wei...
<python><scikit-learn><gaussian-process>
2023-04-26 15:42:00
0
530
David Siret Marqués
76,112,687
7,454,177
How to test a patch request in Django Rest Framework?
<p>I have two test cases in Django Rest Framework: One is a post and one is a patch testcase. The post works without a problem, but the patch trows a problem. In reality they both work.</p> <pre><code>with open(os.path.join(self.path, &quot;..&quot;, &quot;..&quot;, &quot;plugin/test_files/icons.png&quot;), 'rb') as fi...
<python><django><unit-testing><django-rest-framework>
2023-04-26 15:41:55
2
2,126
creyD
76,112,675
1,765,302
numpy - casting uint32 to uint8
<p>I have the following code in python using numpy:</p> <pre><code>import numpy a = 423 b = numpy.uint8(a) print(b) </code></pre> <p>It gives me the result:</p> <p>b = 167</p> <p>I understand that uint8 (unsigned 8-bit integer) can represent values from 0 to 255. What I don't understand is how numpy does the cut-off or...
<python><numpy><casting><byte><unsigned-integer>
2023-04-26 15:40:40
1
1,276
jirikadlec2
76,112,581
1,997,735
PyCharm says package isn't included in project requirements but it is
<p>What is PyCharm not seeing that it wants to be seeing? In my Python file, PyCharm is indicating its annoyance and when I hover it tells me this:</p> <p><a href="https://i.sstatic.net/2efkz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2efkz.png" alt="enter image description here" /></a></p> <p>but ...
<python><pycharm>
2023-04-26 15:30:02
1
3,473
Betty Crokker
76,112,540
14,775,478
How to get dict key for matching value in unique values?
<p>A pretty basic question, but was really unable to find it on the Internet... What's the most pythonic way to get the key that belongs to a list of values of which the input arg is an element?</p> <p>I am under the impression that <code>dict</code> might not be the right type. Reason why I would chose it is that both...
<python><dictionary>
2023-04-26 15:24:54
3
1,690
KingOtto
76,112,483
6,611,672
Generate list of evenly distributed numbers from zero to limit with specific sum and count
<p>I want to write a Python function to generate a list of positive numbers that are evenly distributed from zero to a max called <code>limit</code>. The sum of the list should equal a value <code>total_sum</code> and the list should consist of <code>count</code> number of items.</p> <p>For example:</p> <pre><code>func...
<python>
2023-04-26 15:19:00
1
5,847
Johnny Metz
76,112,470
13,488,334
Creating multiple log files from child processes in multiprocessing.Pool
<p>I am in a situation where my Python application can process up to 500k jobs at a time. To accomplish this we use a <code>multiprocessing.Pool</code> in the following manner:</p> <pre class="lang-py prettyprint-override"><code># make the Pool of workers pool = multiprocessing.get_context('spawn').Pool(num_processors)...
<python><logging><multiprocessing><python-multiprocessing><python-logging>
2023-04-26 15:17:50
2
394
wisenickel
76,112,409
1,190,200
How to use reference to python int from rust method with pyo3?
<p>How does one unpack a python integer as a reference from a <code>rust</code> class method?</p> <p>I'm trying to expose a rust struct to python but the interpreter complains about the reference to the <code>i32</code>.</p> <p>This is the code:</p> <pre class="lang-rust prettyprint-override"><code>#[pyclass] pub struc...
<python><rust><pyo3>
2023-04-26 15:13:22
1
4,994
songololo
76,112,329
5,032,387
Understanding and diagnosing prediction of auto_arima model
<p>I have a very small array representing annual values. I'm trying to train a model using auto_arima and then get predictions.</p> <p>The predictions start off fine, decreasing as we would expect as per the trend in the training data. However, the last 3 values in the prediction actually start to increase. What par...
<python><arima>
2023-04-26 15:06:22
1
3,080
matsuo_basho
76,111,902
9,161,607
Using Smartsheet API, how do I fetch the metadata such as _OUTLINELEVEL_ or _ROWNUM_?
<p>I am able to get the Row and Column data from the Smartsheet API JSON response but in it there are no metadata such as <code>_OUTLINELEVEL_</code> or <code>_ROWNUM_</code>.</p> <p>When requesting the data from Smartsheet API, I also sent additional params such as:</p> <pre><code>params = {'include': 'objectValue,obj...
<python><smartsheet-api><smartsheet-api-2.0>
2023-04-26 14:22:53
1
2,793
floss
76,111,798
9,063,088
response.history not capturing redirects
<p>I have a simple call to hit an amazon product page:</p> <pre><code>response = requests.get('https://www.amazon.com/dp/...') print(response.url) print(response.history </code></pre> <p>When I physically navigate to the page in my browser (chrome), I get redirected to a new product page that's not the one I searched.<...
<python><url><python-requests><request>
2023-04-26 14:11:26
0
750
Jet.B.Pope
76,111,613
4,405,794
Why is the sunrise and sunset time returned by pyephem incorrect for a given location?
<p>I am using the ephem module in Python to calculate the next sunrise and sunset time for a given location (Boston). However, the results returned by the next_rising and next_setting methods are incorrect.</p> <p>Here is the code I am using:</p> <pre><code>import ephem import datetime Boston=ephem.Observer() Boston.l...
<python><pyephem>
2023-04-26 13:53:26
2
659
Ali Hassaine
76,111,503
7,599,062
Efficiently searching for custom objects in large Python lists
<p>I have a list of custom Python objects and need to search for the existence of specific objects within that list. My concern is the performance implications of searching large lists, especially frequently.</p> <p>Here's a simplified example using a custom Person class with attributes name and age:</p> <pre><code>cla...
<python><string><algorithm><dynamic-programming><lcs>
2023-04-26 13:43:08
4
543
SyntaxNavigator