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
75,185,375
5,684,405
How to prepare PIL Image.Image for tf.image.decode_image
<p>For a file read with:</p> <pre><code>import PIL import tensorflow as tf from keras_preprocessing.image import array_to_img path_image = &quot;path/cat_960_720.jpg&quot; read_image = PIL.Image.open(path_image) # read_image.show() image_decode = tf.image.decode_image(read_image) print(&quot;This is the size of the ...
<python><tensorflow><python-imaging-library>
2023-01-20 14:29:03
1
2,969
mCs
75,185,306
9,759,263
python3 finds some programs in a folder, but not others
<p>I have the following directory:</p> <pre><code>~/Library/Python/3.9/bin </code></pre> <p>Inside that folder, for example, appear these two programs:</p> <p><a href="https://i.sstatic.net/z9GW0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/z9GW0.png" alt="enter image description here" /></a></p> <p>E...
<python><shell>
2023-01-20 14:22:43
0
1,311
F. Zer
75,185,226
15,233,108
How to copy file from directory A to directory B using a list
<p>I'm trying to copy files from directory A, to directory B, based on a txt file containing the list of files to be extracted - located in directory B. I referred to this code: <a href="https://stackoverflow.com/questions/66408075/how-to-extract-files-from-a-particular-folder-with-filename-stored-in-a-python-l">How to...
<python>
2023-01-20 14:16:09
1
582
Megan Darcy
75,185,209
5,868,293
Generating new data using VAE in keras
<p>I have built the following function which takes as input some data and runs a VAE on them:</p> <pre><code>def VAE(data, original_dim, latent_dim, test_size, epochs): x_train, x_test = train_test_split(data, test_size=test_size, random_state=42) # Define the VAE architecture #Encoder encoder...
<python><machine-learning><keras><deep-learning><autoencoder>
2023-01-20 14:15:11
1
4,512
quant
75,185,014
9,367,543
Groupby dataframe to count values
<p>I have a dataframe that I want to groupby and get the count per value.</p> <pre><code>date Severity 01-12-22 Sev1 05-12-22 Sev5 22-12-22 Sev1 01-01-23 Sev4 21-01-23 sev4 30-01-23 sev3 </code></pre> <p...
<python><pandas>
2023-01-20 13:59:29
1
338
welu
75,184,989
7,211,014
python argparse default with nargs wont work
<p>Here is my code:</p> <pre><code>from argparse import ArgumentParser, RawTextHelpFormatter example_text = &quot;test&quot; parser = ArgumentParser(description='my script.', epilog=example_text, formatter_class=RawTextHelpFormatter) parser.add_argument('host', type=st...
<python><argparse><default>
2023-01-20 13:58:01
1
1,338
Dave
75,184,846
781,938
How do I change the default figure config in the python plotly library?
<p>Plotly (python) supports specifying a <code>config</code> like this:</p> <pre class="lang-py prettyprint-override"><code>import plotly.express as px config = { 'toImageButtonOptions': { 'format': 'svg', # one of png, svg, jpeg, webp } } fig = px.bar(x=[1, 2, 3], y=[1, 3, 1]) fig.show(config=config) </code...
<python><plotly>
2023-01-20 13:46:56
0
6,130
william_grisaitis
75,184,817
2,196,409
Create a list of dictionary keys whose string values are empty, using comprehension
<p>How would the following be achieved using comprehension so that <code>bad_keys</code> only contains the keys where the length of the associated <code>value</code> is 0?</p> <pre><code>def _check_data_for_length(self) -&gt; []: &quot;&quot;&quot; checks the lengths of the values contained within the dicti...
<python><list-comprehension><dictionary-comprehension>
2023-01-20 13:44:31
1
1,173
eklektek
75,184,736
7,697,375
add a column to numpy array for groupby rolling count
<p>I have a dataframe with 4 columns. I want to add a column that will give running total by a group. I know how to do that in pandas( i.e cumcount +1 with groupby) but I want to move the data into numpy array and vectorize the operation. Example input data</p> <p><a href="https://i.sstatic.net/Xr9pV.png" rel="nofollow...
<python><numpy>
2023-01-20 13:38:01
0
305
Pawan Tolani
75,184,683
11,254,837
How to export dictionary as a .property file in python
<p>How can a dictionary in python be exported to .properties file type in python?</p> <p>What I have:</p> <p><code>dict = {&quot;key1&quot;:&quot;sentence1&quot;, &quot;key2&quot;:&quot;sentence2&quot;}</code></p> <p>The object <code>dict</code> should be saved as <code>.properties</code> file in python, the output sh...
<python><dictionary><properties-file>
2023-01-20 13:33:16
2
800
pikachu
75,184,649
1,169,091
Why is cross_val_score not producing consistent results?
<p>When this code executes the results are not consistent. Where is the randomness coming from?</p> <pre><code>from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.tree import DecisionTreeCla...
<python><scikit-learn><cross-validation>
2023-01-20 13:29:47
1
4,741
nicomp
75,184,615
774,575
How to create a 2D array of scaled+shifted unit impulses?
<p>I'm looking for an efficient way to get a 2D array like this:</p> <pre><code>array([[ 2., -0., -0., 0., -0., -0., 0., 0., -0., 0.], [ 0., -1., -0., 0., -0., -0., 0., 0., -0., 0.], [ 0., -0., -5., 0., -0., -0., 0., 0., -0., 0.], [ 0., -0., -0., 2., -0., -0., 0., 0., -0., 0.], ...
<python><arrays><scipy><signal-processing>
2023-01-20 13:27:12
1
7,768
mins
75,184,572
1,512,250
IndexError: Index contains null values when adding dataframe to featuretools EntitySet
<p>I have my dataframe which I want to add to EntitySet:</p> <pre><code> Unnamed: 0 Year name Pos Age Tm G GS \ 24672 24672 2017.0 Troy Williams SF 22.0 TOT 30.0 16.0 24675 24675 2017.0 Kyle Wiltjer PF 24.0 HOU 14.0 0.0 24688 24688 2017...
<python><pandas><featuretools>
2023-01-20 13:23:00
1
3,149
Rikki Tikki Tavi
75,184,483
5,368,122
Connect to azure sql with managed identity python
<p>I have a compute in azure ML that I am using for development. I am trying to connect to an azure sql database with managed identity but unable to do so as it returns the error:</p> <pre><code>Traceback (most recent call last): File &quot;active_monitoring/dbtester.py&quot;, line 8, in &lt;module&gt; err_mart_c...
<python><azure><odbc><azure-sql-database>
2023-01-20 13:12:47
1
844
Obiii
75,184,391
16,622,985
Windowing Strategy for Unbounded Side Input
<p>I have a pipeline which streams IoT log data. In addition, it has a bounded side input, containing the initial configurations of the devices. This configuration changes over time and has to be updated by specific logs (ConfigLogs) coming from the main PubSub source. All remaining logs (PayloadLogs) need to consume a...
<python><google-cloud-dataflow><apache-beam>
2023-01-20 13:03:20
0
1,176
CaptainNabla
75,184,383
2,715,216
dbx execute install from azure artifacts / private pypi
<p>I would like to use dbx execute to run a task/job on an azure databricks cluster. However, i cannot make it install my code.</p> <p>More Details on the situation:</p> <ul> <li>Project A with a setup.py is dependent on Project B</li> <li>Project B is also python based and is realeased as a azure devops artifact</li> ...
<python><azure><databricks><azure-databricks><dbx>
2023-01-20 13:02:29
1
371
thompson
75,184,357
16,829,292
What is the best experinces to structure a Django project for scale?
<p>Django is great. But as we add new features, as our dev team grows, the software needs to be stable on production, things can get quite messy.</p> <p>We are going to want some common patterns, derived from experience, on how to structure your Django project for scale and longevity.</p> <p>What is your suggestion?</p...
<python><django><django-rest-framework>
2023-01-20 13:00:16
1
323
Amin Zayeromali
75,184,221
12,403,550
Convert nested dict to dataframe, syntax error?
<h4>Problem</h4> <p>I am converting multiple nested dicts to dataframes. I have a slightly different dict that I haven't been able to convert to a dataframe using my attempted solution. I am providing a shortened copy of my dict with dummy values as the reprex.</p> <h4>Reprex dict:</h4> <pre><code>{'metrics': [{'metric...
<python><dataframe><dictionary>
2023-01-20 12:45:51
1
433
prayner
75,184,131
12,078,893
Why does loc[[]] not work for a single column?
<p>In the official documentation for the loc function in pandas, it is written that using double brackets, loc[[]], returns a dataframe.</p> <blockquote> <p>Single tuple. Note using [[]] returns a DataFrame. <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html#" rel="nofollow noreferrer">http...
<python><pandas><syntax-error>
2023-01-20 12:37:31
2
349
김예군
75,184,039
16,607,067
Overriding django admin get_queryset()
<p>I have two models which is one of them proxy model. In admin I registered both and overrided <code>get_queryset()</code> method but it is not working as expected.<br /> <strong>admin.py</strong></p> <pre class="lang-py prettyprint-override"><code>@admin.register(Category) class CategoryAdmin(admin.ModelAdmin): ...
<python><django><django-models><inheritance><django-admin>
2023-01-20 12:28:53
2
439
mirodil
75,183,965
3,968,048
Is it possible to manually correct a POS tag in Spacy, and also refetch the lemma after updating the POS?
<p>Let's say I have two sentences. In english <code>I took a fall last month.</code>, and in spanish <code>Tomé una caída el mes pasado.</code></p> <p>Spacy gives me the following:</p> <pre><code>I took a fall last month . &quot;PRON&quot;, &quot;VERB&quot;, &quot;DET&quot;, &quot;NOUN&quot;, &quot...
<python><spacy>
2023-01-20 12:20:48
1
3,536
Peter R
75,183,958
4,620,679
Why pandas DataFrame allows to set column using too large Series?
<p>Is there a reason why pandas raises ValueError exception when setting DataFrame column using a list and doesn't do the same when using Series? Resulting in superfluous Series values being ignored (e.g. 7 in example below).</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&...
<python><pandas><dataframe><series>
2023-01-20 12:20:10
1
501
michalmonday
75,183,956
3,251,645
Import file from subdirectory into file in another subdirectory
<p>I have a python project a folder structure like this:</p> <pre><code>main_directory main.py drivers __init__.py xyz.py utils __init__.py connect.py </code></pre> <p>I want to import <code>connect.py</code> into <code>xyz.py</code> and here's my code:</p> <pre><code>from utils import connect as ...
<python><python-import><python-packaging>
2023-01-20 12:20:01
4
2,649
Amol Borkar
75,183,616
12,936,009
neovim: pwntools process automatically stops when trying to invoke interactive shell
<p>I'm using python pwntools. I'm using <em><strong>python 3.10.x</strong></em></p> <p>This line of code should open a shell for me: <code>io.interactive()</code></p> <p>But while running this file from vim using <code>!./%</code> it doesn't open the shell doesn't invoke as it was supposed to be. The process stops cont...
<python><python-interactive><interactive-shell><pwntools>
2023-01-20 11:48:03
0
847
NobinPegasus
75,183,571
4,332,480
DRF: Which if better to create custom structure of response in Serializer/ModelSerializer?
<p>I am currently making a simple <code>CRUD</code> application on <code>Django Rest Framework</code>.</p> <p>I need to return a response to the client for any request in a specific structure.</p> <p>For example, if a client makes a <code>POST</code> request to create a new record and it was executed successfully, then...
<python><django><django-rest-framework><django-views><django-serializer>
2023-01-20 11:43:47
2
5,276
Nurzhan Nogerbek
75,183,494
2,635,863
scale within groups with scikit-learn
<pre><code>from sklearn.preprocessing import scale df = pd.DataFrame({'x':['a','a','a','a','b','b','b','b'], 'y':[1,1,2,2,1,1,2,2], 'z':[12,32,14,64,24,67,44,33]}) </code></pre> <p>I'm trying to scale column <code>z</code> for each combination of <code>x</code> and <code>y</code>:</p> <pre><code> x y z z2 0 a...
<python><pandas><scikit-learn>
2023-01-20 11:36:28
1
10,765
HappyPy
75,183,426
649,920
Rolling median of deviation from the current value
<p>Let's say I have a dataframe in pandas indexed by timestamps. For each point I need to compute median of absolute differences between the future values in the next 5 seconds and the current one. For example,</p> <pre><code>df = pd.DataFrame({'A': [2, 1, 3, 4, -1, 2, -3, 5, 4, -10]}, index=pd.date_range('2022-01-...
<python><pandas>
2023-01-20 11:29:30
1
357
SBF
75,183,361
1,259,374
Python: initiated Logger with dataclass field param
<p>This is my <code>Logger</code> class:</p> <pre><code>import logging import os import datetime class Logger: _logger = None def __new__(cls, user: str, *args, **kwargs): if cls._logger is None: cls._logger = super().__new__(cls, *args, **kwargs) cls._logger = logging.getLogg...
<python><logging><field><python-dataclasses>
2023-01-20 11:22:04
2
1,139
falukky
75,183,258
9,182,743
Add second y-axis with percentage in bar chart plotly
<p>Given df:</p> <pre><code> names values pct 0 a 10 0.1 1 b 20 0.2 2 c 70 0.7 </code></pre> <p>Return a bar chart with secondary y-axis as a percentage (col pct)</p> <p>Current code:</p> <pre class="lang-py prettyprint-override"><code> import pandas as pd import numpy as np import plot...
<python><pandas><plotly>
2023-01-20 11:13:52
1
1,168
Leo
75,183,093
15,476,955
python: clean dynamoDB AWS item?
<p>With AWS DynamoDB calls, we sometime get complex of item which precise the type of every element in the item. It can be useful but it's a mess to extract the data.</p> <pre><code>{ &quot;a&quot;: { &quot;S&quot;: &quot;AAAA&quot; }, &quot;myList&quot;: { &quot;L&quot;: [ { &quot;S&quot;: &quot;T1&quot;...
<python><amazon-web-services><dictionary><amazon-dynamodb>
2023-01-20 10:57:41
2
1,168
Utopion
75,183,054
2,783,767
Is there a way to get title of a google drive file in python using its google drive file id?
<p>I have google drive IDs of many files which I want to download. However the apis to download google drive files want the filename as well to save the file with that name.</p> <p>Is there a way in python to get the title/name of the file from the google drive file ID in python?</p> <p>If so please help to share a sam...
<python><google-drive-api>
2023-01-20 10:53:37
1
394
Granth
75,182,976
7,714,681
Store a dictionary variable from Google Colab locally
<p>In Google Colab, I have created a <code>dict</code> file names <code>list_dict</code>. How can pickle this and store it locally?</p> <pre><code>PATH = &lt;LOCAL_PATH&gt; pickle_out = open(PATH +'&lt;FILE_NAME&gt;.pickle', 'wb') pickle.dump(list_dict, pickle_out) pickle_out.close() </code></pre> <p>However, this retu...
<python><dictionary><local-storage><google-colaboratory><pickle>
2023-01-20 10:46:39
2
1,752
Emil
75,182,825
386,861
How to plot multiple times series using pandas and seaborn
<p>I've got a dataframe of data that people have helpfully collate.</p> <p>It looks like this (ignore the index, I'm just sampling):</p> <pre><code> uni score year 18 Arden University Limited 78.95 2020 245 The University of Manchester 71.35 2022 113 Darlington College ...
<python><pandas><matplotlib><seaborn>
2023-01-20 10:34:15
2
7,882
elksie5000
75,182,812
8,916,474
How in tox run bash script and reuse returned value?
<p>When I create a tox environment, some libraries are installed under different paths depending on the environment that I use to trigger tox:</p> <pre><code># Tox triggered inside virtual env .tox/lib/site-packages </code></pre> <p>Sometimes</p> <pre><code># Tox triggered inside docker .tox/lib/python3.8/site-packages...
<python><bash><tox>
2023-01-20 10:32:58
1
504
QbS
75,182,688
8,601,920
Get values from current till last column values in pandas groupby
<p>Image following pandas dataframe:</p> <pre><code>+----+------+-------+ | ID | Name | Value | +----+------+-------+ | 1 | John | 1 | +----+------+-------+ | 1 | John | 4 | +----+------+-------+ | 1 | John | 10 | +----+------+-------+ | 1 | John | 50 | +----+------+-------+ | 1 | Adam | 6 | +---...
<python><pandas><group-by>
2023-01-20 10:23:06
1
557
adama
75,182,628
9,794,068
Optimal ways to search for elements in sorted list
<p>Whenever I needed to check whether an item belongs to a given group I used to store the elements in a list and use <code>in</code> to make the check:</p> <pre><code>def is_in_list(element, l): if element in l: print('yes') else: print('no') is_in_list(2, [1,2,3]) </code></pre> <p>This soluti...
<python>
2023-01-20 10:17:58
0
530
3sm1r
75,182,398
4,451,521
import __main__ with pickles
<p>Can someone explain me what is the role of <code>import __main__</code> in python? I read a similar question but could not understand it. (this in general first)</p> <p>Then in particular, when a pickle of an object is made in a script from within a <code>if __name__ == &quot;__main__&quot;:</code> , and I try to r...
<python><pickle>
2023-01-20 09:57:12
0
10,576
KansaiRobot
75,182,377
304,215
Electron forge distributable showing "error spawn python ENOENT" when starting the app
<p>I've one Electron app in which I've used python flask a server with Angular JS for all HTML front end thing. In dev environment it's working fine as I expect. But, after creating a distributable by electron forge when I'm trying to open the <code>.exe</code> file it showing this <code>Error spawn python ENOENT</cod...
<python><node.js><electron><electron-builder><electron-forge>
2023-01-20 09:55:32
0
5,999
Suresh
75,182,338
5,684,405
The all method not see the instance field values for subclassing keras.Model
<p>For subclassing to create a Tensorflow model with the following code:</p> <pre><code>class MyClass(keras.Model): def __int__( self, input_shape: tuple, classes_count: int = 10, model_name: str = 'model_name', **kwargs, ): super(MyClass, self).__init__(name=self...
<python><tensorflow><subclassing>
2023-01-20 09:51:45
1
2,969
mCs
75,182,302
9,528,575
Doing group calculations with two separate dataframes in python
<p>I have two pandas dataframes like this:</p> <pre><code>df1= pd.DataFrame({'sub-group':['2020','2030','2040','2030','2040','2030','2040'], 'group':['a', 'a', 'a', 'b', 'b', 'c', 'c'], 'value1':[12,11,41,33,66,22,20]}) sub-group group value1 2020 a ...
<python><pandas><dataframe><group-by>
2023-01-20 09:48:51
3
361
Novic
75,182,268
1,512,250
Create integer unique keys in 3 dataframes for rows with same names to generate automatic features using featuretools
<p>I have three different data frames with basketball players' data.</p> <p>In all three dataframes there are basketball players' names. I want to join all three dataframes into one EntitySet to use automatic feature generation using featuretools.</p> <p>As I understand, I need to create an integer key in 3 dataframes,...
<python><pandas><featuretools>
2023-01-20 09:46:32
1
3,149
Rikki Tikki Tavi
75,182,208
9,234,100
Connect to cloudSQL db using service account with pymysql or mysql.connector
<p>I have a running CloudSQL instance running in another VPC and a nginx proxy to allow cross-vpc access. I can access the db using a built-in user. But how can I access the DB using a Google Service Account?</p> <pre><code>import google.auth import google.auth.transport.requests import mysql.connector from mysql.conne...
<python><google-cloud-platform><google-cloud-sql><mysql-connector><pymysql>
2023-01-20 09:40:40
3
365
Max
75,182,045
17,884,397
Access the `b` parametr in the SVC object of scikit learn
<p>According to <a href="https://scikit-learn.org/stable/modules/svm.html#mathematical-formulation" rel="nofollow noreferrer">scikit learn's mathematical model of the SVC</a> there is a parameter <code>b</code> (constant value of the model):</p> <p><a href="https://i.sstatic.net/IvLx0.png" rel="nofollow noreferrer"><im...
<python><scikit-learn><data-science><documentation>
2023-01-20 09:25:27
1
736
Eric Johnson
75,181,924
12,129,443
How to interpret torch.where() output when x , y are not given?
<p>I understand the output of torch.where() as per the content mentioned in the <a href="https://pytorch.org/docs/stable/generated/torch.where.html" rel="nofollow noreferrer">documentation</a>. However, I do not understand the output it produces when x and y are not given as show below (the dimensionality of this outpu...
<python><pytorch>
2023-01-20 09:15:55
2
668
Srinivas
75,181,880
14,073,111
How to pass a parameter to a class scope fixture
<p>Lets say I have a fixture like this:</p> <pre><code>@pytest.fixture(scope=&quot;class&quot;) def some_fixture(some_paramaters): do_something yield do_something </code></pre> <p>And i want to use it in this way:</p> <pre><code>@pytest.mark.usefixtures('some_fixtures') class TestSomething: code.... </c...
<python><python-3.x><pytest><fixtures>
2023-01-20 09:11:47
1
631
user14073111
75,181,821
8,771,201
Python mysql insert when record does not exist
<p>I have a table with articles like this:</p> <p>Table: artPerBrand</p> <p>Colums: ID (auto increment), BrandID, ArtCat, ArtNrShort, ArtNrLong, Active</p> <p>I want to insert new articles (using a python script) but only if the same ArtNrLong does not already exist.</p> <p>I cannot do this by making the ArtNrLong uniq...
<python><mysql>
2023-01-20 09:06:44
2
1,191
hacking_mike
75,181,796
4,125,774
Poetry package modulenotfound when installing a local package
<p>I am new to this packaging, and facing now a problem. The problem is as follows. I have created a poetry project from the CLI:</p> <pre><code> poetry new mypackage_test </code></pre> <p>and have a file structure as follows:</p> <p><a href="https://i.sstatic.net/Dj9Dg.png" rel="nofollow noreferrer"><img src="https://...
<python><python-import><python-packaging><python-poetry>
2023-01-20 09:04:39
1
307
KapaA
75,181,692
17,561,414
change a struct type to map type pyspark
<p>Im trying to change the <code>Struct</code> type to <code>Map</code> type. I found this this solution --&gt;</p> <pre><code>from pyspark.sql.functions import col,lit,create_map df = df.withColumn(&quot;propertiesMap&quot;,create_map( lit(&quot;salary&quot;),col(&quot;properties.salary&quot;), lit(&qu...
<python><pyspark><dtype>
2023-01-20 08:53:50
0
735
Greencolor
75,181,599
11,159,734
Airflow how to catch errors from an Operator outside of the operator
<p>Maybe the question isn't phrased in the best way. Basically what I want to do is: Building a DAG that iterates over a list of sql files and using the BigQueryOperator() to execute these sql files.</p> <p>However there will be sql files in the list where the corresponding <strong>tables do not exist in BQ</strong>. A...
<python><google-cloud-platform><airflow>
2023-01-20 08:45:07
1
1,025
Daniel
75,181,393
3,352,254
Unable to fit custom model with lmfit - ValueError: The model function generated NaN values and the fit aborted
<p>I have this data:</p> <pre><code>y=[2.103402,2.426855,1.011672,1.595371,1.861879,2.492542,2.567561,4.685010,4.452643,5.321630,6.637233, 6.109260,6.220958,5.928408,5.654726,5.498096,5.468448,6.128418,6.071376,6.487270,6.609533,6.907320, 7.626838,8.432065,9.749410,8.976752,8.742036,8.779956,8.212357,8.578200,9.170012,...
<python><lmfit>
2023-01-20 08:21:53
1
825
smaica
75,181,179
10,722,752
Azure ML pipeline fails with ImportError: cannot import name 'time_ns' error
<p>I am trying to run a ML pipeline in Azure, I use <code>pandarallel</code> module but the pipeline fails with below error.</p> <pre><code> from pandarallel import pandarallel File &quot;/azureml-envs/azureml_76aa2eb12d27af119fdfef634eaaf565/lib/python3.6/site-packages/pandarallel/__init__.py&quot;, line 1, in &l...
<python><pandas><azure>
2023-01-20 07:55:53
1
11,560
Karthik S
75,181,173
4,806,787
Non-monotonic evolution of runtime with increasing parallelization
<p>I'm running some runtime tests to understand what I can gain from parallelization and how it affects runtime (linearly?). For a given integer <code>n</code> I successively compute the <code>n</code>-th Fibonacci number and vary the degree of parallelization by allowing to compute each Fibonacci number <code>i</code>...
<python><parallel-processing><multiprocessing>
2023-01-20 07:54:46
1
313
clueless
75,181,125
16,626,322
How can I get current text from TextArea in Gradio
<pre><code>import gradio as gr input1 = gr.TextArea(label=&quot;Text (100 words max)&quot;, value=example, elem_id=f&quot;input{i}&quot;) </code></pre> <p>I made a Text Area, and wanna get current text value from TextArea.</p> <p><code>input1.value</code> jus...
<python><gradio>
2023-01-20 07:49:01
1
539
sooyeon
75,181,057
3,164,492
Remove If block with FunctionDef keeping the untouched code as it is
<p>I need to replace the if-else section with a function enclosing the same if-else. For ex:</p> <p>Following is the code with if-else condition</p> <pre><code>x = 5 # comments to be retained # above new line as well if foo() == 'bar': y = 10 print('foo is bar') else: print('foo is not bar') z =100 </code></p...
<python><tokenize><abstract-syntax-tree>
2023-01-20 07:40:40
1
1,805
Devavrata
75,180,971
10,924,836
Columns selection on specific text
<p>I want to extract specific columns that contain specific names. Below you can see my data</p> <pre><code>import numpy as np import pandas as pd data = { 'Names': ['Store (007) Total amount of Sales ', 'Store perc (65) Total amount of sales ', 'Mall store, aid (005) To...
<python><pandas>
2023-01-20 07:32:04
1
2,538
silent_hunter
75,180,805
1,146,785
do asyncio tasks have to be async all the way down?
<p>I'm having problems wrapping an external task to parallelize it. I'm a newbie with asyncio so maybe I'm doing something wrong:</p> <p>I have an <code>animate</code> method that I have also declared as async. But that calls an external library that uses various iterators etc. I'm wondering if something in a library i...
<python><asynchronous><python-asyncio>
2023-01-20 07:13:22
1
12,455
dcsan
75,180,687
12,242,085
How to create new columns with name of columns in list with the highest value per ID, metioned after coma if need in Python Pandas?
<p>I have Pandas DataFrame like below (I can add that my DataFrame is definitely bigger, so I need to do below aggregation only for selected columns):</p> <pre><code>ID | COUNT_COL_A | COUNT_COL_B | SUM_COL_A | SUM_COL_B -----|-------------|-------------|-----------|------------ 111 | 10 | 10 | 320...
<python><pandas><dataframe><numpy>
2023-01-20 06:56:22
1
2,350
dingaro
75,180,598
11,402,025
TypeError: Object of type 'type' is not JSON serializable
<p>The code works fine in Postman and provides a valid response but fails to generate the OpenAPI/Swagger UI automatic docs.</p> <pre class="lang-py prettyprint-override"><code>class Role(str, Enum): Internal = &quot;internal&quot; External = &quot;external&quot; class Info(BaseModel): id: int role:...
<python><swagger><fastapi><swagger-ui><openapi>
2023-01-20 06:43:30
2
1,712
Tanu
75,180,457
12,242,085
How to create 2 new column in DataFrame based on the highest values in rest of column with appropriate prefix in Python Pandas?
<p>I have Pandas DataFrame like below (I can add that my DataFrame is definitely bigger, so I need to do below aggregation only for selected columns):</p> <pre><code>ID | COUNT_COL_A | COUNT_COL_B | SUM_COL_A | SUM_COL_B -----|-------------|-------------|-----------|------------ 111 | 10 | 10 | 320...
<python><pandas><dataframe><numpy><aggregate>
2023-01-20 06:26:05
1
2,350
dingaro
75,180,456
8,040,369
openpyxl(): Reading the cell value not the cell formula
<p>I am using openpyxl() to copy the contents of an excel to another excel.</p> <p>My original excel has an empty column in it, so i am not inserting the first column value and removing the empty column to the new file.</p> <p>Because of this the formulas that was being used gets messed up. Ex: Original File:</p> <pre>...
<python><python-3.x><openpyxl>
2023-01-20 06:25:57
1
787
SM079
75,180,344
8,002,010
localstack s3 can't be accessed via boto3
<p>I am able to run localstack via docker and my docker-compose file looks like:</p> <pre><code> services: localstack: image: localstack/localstack:latest network_mode: host environment: - SERVICES=s3 - AWS_DEFAULT_REGION=eu-west-1 - HOSTNAME_EXTERNAL=localhost - DEBUG=1 ports:...
<python><amazon-s3><boto3><localstack>
2023-01-20 06:11:01
2
664
talkdatatome
75,180,332
10,020,470
How to sum second list from list of list in Python
<p>I would like to sum from list of list as below</p> <pre><code>array([[[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]], [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]], [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]...
<python><arrays><python-3.x><numpy>
2023-01-20 06:09:22
4
437
foy
75,180,152
2,339,664
How can I create a Python class with a member named 'class'
<p>I want to create a Python class that represents a dictionary <strong>my_dict</strong> that I want to convert as follows</p> <pre><code>my_class = MyClass(**my_dict) </code></pre> <p>The issues is that one of the dicts keys is called 'class'</p> <p>So when I do as follows Python complains:</p> <pre><code>class MyCla...
<python><python-3.x>
2023-01-20 05:39:39
1
4,917
Harry Boy
75,179,944
10,308,255
How to use `groupby` to aggregate columns into dictionary so that new column contains that dictionary?
<p>I have a dataframe that contains a <code>person</code>, <code>year</code>, and a bunch of <code>flag</code> containing columns, like below:</p> <pre><code># sample dataframe data = [[&quot;John Doe&quot;, 2018, True, False, True], [&quot;Jane Doe&quot;, 2019, True, False, False]] df = pd.DataFrame(data, columns=[&q...
<python><pandas><dataframe><dictionary>
2023-01-20 01:59:41
1
781
user
75,179,880
19,950,360
plotly dash chained callback
<p>This is my code</p> <pre><code>app = Dash(__name__) app.layout = html.Div([ dcc.Location(id='url', refresh=False), dcc.Dropdown(options=['bar', 'pie'], id='dropdown', multi=False, value='bar', placeholder='Select graph type'), html.Div(id='page-content'), ]) @app.callback( Output('see1', 'options'...
<python><plotly><plotly-dash>
2023-01-20 01:42:53
1
315
lima
75,179,732
3,169,603
Pythonic method for stacking np.array's of different row length
<p>Assume I have following multiple numpy <code>np.array</code> with different number of rows but same number of columns:</p> <pre><code>a=np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) b=np.array([[1, 2, 3], [4, 5, 6]]) </code></pre> <p>I want to combine them to have followin...
<python><numpy>
2023-01-20 01:08:12
1
1,093
doubleE
75,179,517
327,026
A build-system independent way to get the version from a package source directory
<p>There are many different ways that Python packages manage their version data. Is there a build-system independent way to extract the version from a package source directory?</p> <p>I'm aware of the <a href="https://peps.python.org/pep-0517/" rel="nofollow noreferrer">PEP 517</a> compatible Python package builder <a ...
<python><versioning><python-packaging><pep517>
2023-01-20 00:11:52
1
44,290
Mike T
75,179,258
11,999,684
Python Exception Message Escaping <=> character
<p>My colleagues and I are working on some code to produce SQL merge strings for users of a library we're building in Python to be run in the Azure Databricks environment. These functions provide the SQL string through a custom exception that we've written called DebugMode. The issue that we've encountered and I can't ...
<python><databricks>
2023-01-19 23:21:12
1
323
FoxHound
75,179,210
214,526
Reading key/value pair text file efficiently with correct by construction
<p>I have few thousands of text files where each file is of following form:</p> <pre><code>Some Key: value1 Some Other Key: value2 Another Key: value3 ... &lt; 300+ such entries &gt; ... </code></pre> <p>I want to read each of these files as dictionary and populate as a row in pandas dataframe. Though at this moment I ...
<python><python-3.x>
2023-01-19 23:14:32
1
911
soumeng78
75,179,038
9,428,990
PyJWT validate custom claims
<p>Been using authlib for a while and it has been real easy to validate both the existence of a claim but also its value. According to the example:</p> <pre><code>claims_options = { &quot;iss&quot;: { &quot;essential&quot;: True, &quot;value&quot;: &quot;https://idp.example.com&quot; }, &quot;aud&quot;: { &quot...
<python><python-3.x><jwt><pyjwt>
2023-01-19 22:42:37
1
719
Frankster
75,179,010
388,951
How can I disable pylint's missing-module-docstring for unit tests?
<p>I'm a big fan of pylint's built-in docstring checker. I'm very happy to require docstrings on all my classes, all my functions, and all my modules.</p> <p>What I don't like, however, is that pylint also wants docstrings on all my test modules and all my <code>pytest</code> test functions. This leads to low-value doc...
<python><pytest><pylint><pylintrc>
2023-01-19 22:38:18
1
17,142
danvk
75,178,894
5,032,387
Specifying complex truncated beta distribution
<p>I'd like to specify a truncated beta distribution such that the support is [0.1, 0.4], and allow for the probability density at the lower bound to be higher than very near 0.</p> <p>Here's what I have so far. I realize that the parameters I specify here may not give me the distribution exactly like I described, but...
<python><scipy><beta-distribution>
2023-01-19 22:21:53
1
3,080
matsuo_basho
75,178,854
496,289
How do I exclude multiple folders and/or file-patterns from pre-commit analysis?
<p>I have my python project. I'm trying to setup pre-commit checks using <a href="https://pre-commit.com/" rel="nofollow noreferrer">pre-commit</a>. I want to exclude some folders and some files (by pattern) from the analysis. The `exclude tag in config file only supports string not an array.</p> <p>E.g. in following p...
<python><git><continuous-integration><pre-commit-hook><pre-commit.com>
2023-01-19 22:16:53
1
17,945
Kashyap
75,178,705
3,853,537
How to Get Path Similarity of Stopwords like "and"
<p>I'm trying to get the synsets of words to get their similarity matrix. However, one of the words is &quot;and.&quot; I realized that it is a stopword in nltk and thus may not have a synset. For example,</p> <pre class="lang-py prettyprint-override"><code>wn.synsets('and') </code></pre> <p>simply returns <code>[]</co...
<python><nltk><wordnet>
2023-01-19 21:55:58
1
1,484
Zhanwen Chen
75,178,696
8,696,281
Why can Pyarrow read additional index column while Pandas dataframe cannot?
<p>I have the following code:</p> <pre><code>import pandas as pd import dask.dataframe as da from pyarrow.parquet import ParquetFile df = pd.DataFrame([1, 2, 3], columns=[&quot;value&quot;]) my_dataset = da.from_pandas(df, chunksize=3) save_dir = './local/' my_dataset.to_parquet(save_dir) pa = ParquetFile(&quot;./...
<python><pandas><dask><parquet><pyarrow>
2023-01-19 21:55:06
1
783
noobie2023
75,178,632
4,114,325
scikit-learn RandomForestClassifier list all variables of an estimator tree?
<p>I train a <code>RandomForestClassifier</code> as</p> <pre><code>from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification X, y = make_classification() clf = RandomForestClassifier() clf.fit(X,y) </code></pre> <p>where <code>X</code> and <code>y</code> are some feature vecto...
<python><scikit-learn><random-forest><class-variables>
2023-01-19 21:47:58
1
1,023
Kagaratsch
75,178,621
10,963,057
how to get the x-axis in german letter format in plotly
<p>i try to get instead of the american letters german letters. As example: May = Mrz; Oct = Okt; Dec = Dez</p> <pre><code>import plotly.express as px df = px.data.stocks() fig = px.line(df, x=&quot;date&quot;, y=df.columns, title='custom tick labels') fig.update_xaxes(dtick=&quot;M1&quot;, tickformat=&q...
<python><plotly><date-formatting>
2023-01-19 21:46:49
1
1,151
Alex
75,178,603
14,676,485
How to loop over all columns and check data distribution using Fitter library?
<p>I need to check data distributions of all my numeric columns in a dataset. I chose <code>Fitter</code> library to do so. I loop over all columns but have only one plot+summary table as an outcome instead. What is wrong with my code?</p> <pre><code>from fitter import Fitter import numpy as np df_numeric = df.select_...
<python><statistics><data-science>
2023-01-19 21:45:08
1
911
mustafa00
75,178,550
392,086
Multiple gunicorn workers prevents flask app from making https calls
<p>A simple flask app accepts requests and then makes calls to https endpoints. Using gunicorn with multiple worker processes leads to ssl failures.</p> <p>Using <code>flask run</code> works perfectly, albeit slowly.</p> <p>Using <code>gunicorn --preload --workers 1</code> also works perfectly, albeit slowly.</p> <p>Ch...
<python><flask><openssl><gunicorn>
2023-01-19 21:38:27
1
1,092
MJZ
75,178,538
19,369,393
Why -1//2 = -1 but int(-1/2) = 0?
<p>I found that <code>-1 // 2</code> is equal to -1 (Why not 0?), but <code>int(-1 / 2)</code> is equal to 0 (as I expected). It's not the case with 1 instead of -1, so both <code>1 // 2</code> and <code>int(1 / 2)</code> is equal to 0.</p> <p>Why the results are different for -1?</p>
<python>
2023-01-19 21:37:03
1
365
g00dds
75,178,436
12,417,488
How to correct MLFlow UI FileNotFoundError: [WinError 2]?
<p>I created an MLFlow tracking folder and logged metrics/parameters in the following way:</p> <pre><code>dir_parent = os.getcwd() dir_mlflow = 'file:' + os.sep + os.path.join(dir_parent, 'mlflow_test') mlflow.set_tracking_uri(dir_mlflow) # log parameters in mlflow mlflow.log_param('batch_size',args.batch_size) mlflow...
<python><machine-learning><command-line><mlflow>
2023-01-19 21:25:39
0
663
PJ_
75,178,435
558,619
Python: Event-Handler for background task complete
<p>I have a <code>_global_variable = Big_Giant_Class()</code>. <code>Big_Giant_Class</code> takes a long time to run, but it also has constantly refreshing 'live-data' behind it, so I always want as new a instance of it as possible. Its not <code>IO-bound</code>, just a load of CPU computations.</p> <p>Further, my prog...
<python><async-await><python-asyncio>
2023-01-19 21:25:38
1
3,541
keynesiancross
75,178,182
1,578,210
Python NAND function
<p>How can I do a logical NAND on two numbers in python? Simple example. Let's say I have a number (0xFF) and I want a logical NAND with a mask value of 0x5.</p> <pre><code>number = 0xFF = 0b1111 1111 mask = 0x05 = 0b0000 0101 --------------------------- desired= 0xFA = 0b1111 1010 </code></pre> <p>I'm not reinvent...
<python><bit-manipulation>
2023-01-19 20:54:06
1
437
milnuts
75,178,105
2,662,901
Why is DataFrame int column value sometimes returned as float?
<p>I add a calculated column <code>c</code> to a DataFrame that only contains integers.</p> <pre><code>df = pd.DataFrame(data=list(zip(*[np.random.randint(1,3,5), np.random.random(5)])), columns=['a', 'b']) df['c'] = np.ceil(df.a/df.b).astype(int) df.dtypes </code></pre> <p>The DataFrame reports that the column type of...
<python><pandas><dataframe>
2023-01-19 20:46:27
2
3,497
feetwet
75,178,102
3,785,426
Python & Selenium: WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 1 in google colab
<p>I use Selenium in Python(Google Colab) for scraping.</p> <p>Error occurred even though nothing was changed.</p> <p>It worked fine yesterday.</p> <p>Sometimes it works, sometimes it doesn't.</p> <p>Why does this happen?</p> <p><strong>ERROR</strong></p> <pre><code>-----------------------------------------------------...
<python><selenium><selenium-webdriver><selenium-chromedriver><google-colaboratory>
2023-01-19 20:46:25
3
861
SamuraiBlue
75,177,922
692,658
Passing variables to a script over ssh using gcloud command -- all variables treated as a single string?
<p>I'm trying to setup a system to run some commands on VM's in google cloud, in my case we want to run a tcpdump at a certain time using the 'at' command. Right now I'm just trying to execute any commands successfully, when I have to pass arguments along with the command and getting confusing behaviour, which appears ...
<python><bash><gcloud>
2023-01-19 20:28:06
1
316
djsmiley2kStaysInside
75,177,824
8,372,455
how to reshape array to predict with LSTM
<p>I made an LSTM model based on <a href="https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/" rel="nofollow noreferrer">this tutorial</a> where the model input batch shape is:</p> <pre><code>print(config[&quot;layers&quot;][0][&quot;config&quot;][&quot;batch_input_sha...
<python><tensorflow><keras><lstm>
2023-01-19 20:18:15
1
3,564
bbartling
75,177,795
7,796,833
Conda install script installs wrong version and then doesnt update
<p>Conda tells me that there is an update available, but when I try to update, it doesnt work. I run <code>conda update -n base -c defaults conda</code> and get the following notification:</p> <pre><code>Collecting package metadata (current_repodata.json): done Solving environment: done ==&gt; WARNING: A newer versio...
<python><anaconda><conda><anaconda3>
2023-01-19 20:14:43
1
618
Carol Eisen
75,177,744
557,406
Unicode not consistently working with Alembic
<p>I have a migration that is running some custom code that depends on unicode characters. I am currently using SQLAlchemy 1.1.9 and Alembic 1.0.2.</p> <p>I can see my database and table have all the right settings:</p> <pre><code>mysql&gt; SELECT @@character_set_database, @@collation_database; +-----------------------...
<python><unicode><sqlalchemy><alembic>
2023-01-19 20:09:53
1
6,395
Charles L.
75,177,719
304,215
Python Flask server not running inside electron app
<p>I'm working on an Electron app where I'm running a Python Flask server inside the Electron app. Code has shared below. When I'm trying to run the Electron app by <code>npm run start</code> command my electron app is working. But, when ever I'm trying to access my Flask route it's showing error like - &quot;(failed) ...
<python><node.js><flask><electron>
2023-01-19 20:06:41
1
5,999
Suresh
75,177,494
2,878,298
parse xlsx file having merged cells using python or pyspark
<p>I want to parse an xlsx file. Some of the cells in the file are merged and working as a header for the underneath values.<br /> But do not know what approach I should select to parse the file.</p> <ol> <li>Shall I parse the file from xlsx to json format and then I should perform the pivoting or transformation of dat...
<python><pandas><openpyxl><azure-databricks><xlrd>
2023-01-19 19:43:33
1
1,268
venus
75,177,101
4,133,188
Getting pixel coordinates and pixel values in image region bounded by an ellipse using opencv python
<p>I would like to draw an arbitrary ellipse on an opencv image in python and then return two arrays: (1) The pixel coordinates of all pixels bounded by the ellipse, both on the ellipse line and inside the ellipse, (2) the pixel values of each of the pixels from array (1).</p> <p>I looked at this <a href="https://stack...
<python><opencv>
2023-01-19 19:00:32
1
771
BeginnersMindTruly
75,177,041
11,666,502
How to find the longest continuous stretch of matching elements in 2 lists
<p>I have 2 lists:</p> <pre><code>a = [ 'Okay. ', 'Yeah. ', 'So ', 'my ', 'thinking ', 'is, ', 'so ', 'when ', &quot;it's &quot;, 'set ', 'up ', 'just ', 'one ', 'and ', &quot;we're &qu...
<python><list>
2023-01-19 18:54:24
2
1,689
connor449
75,176,951
15,171,387
Python add weights associated with values of a column
<p>I am working with an ex termly large datfarem. Here is a sample:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'ID': ['A', 'A', 'A', 'X', 'X', 'Y'], }) ID 0 A 1 A 2 A 3 X 4 X 5 Y </code></pre> <p>Now, given the frequency of each value in column '''ID''', I want to calculate a wei...
<python><pandas><dataframe>
2023-01-19 18:45:17
2
651
armin
75,176,912
20,589,275
How to split a number into three sets
<p>I have got an a number: like 5 i need to split it into 3 sets like</p> <pre><code>2 1 4 2 2 3 1 5 </code></pre> <p>Or the number 8:</p> <pre><code>2 8 4 2 7 5 4 1 2 3 6 </code></pre> <p>I try to</p> <pre><code>def partition(n): if n &lt; 5: return s = n * (n + 1) // 2 if s % 3 != 0: ...
<python>
2023-01-19 18:42:56
0
650
Proger228
75,176,822
11,616,106
Write changing text to new pdf
<p>I'm trying to open abc.pdf and find google.com and replace with input words. text changing but, I can write the new text to output.pdf it stay same with abc.pdf how can i solve this ?</p> <pre><code>import PyPDF2 import fitz from PyPDF2 import PdfReader, PdfWriter import requests # # Replace with the URL of the PDF...
<python>
2023-01-19 18:33:44
0
521
hobik
75,176,798
107,832
Is there a good way to use C# (.NET Framework) and Python code together?
<p>We have a solution written in C#/.NET Framework 4.7. It has a lot of infrastructure code related to environment configurations, database access, logging, exception handling etc. Our co-workers are eager to contribute to the project with Python code that makes a lot of special calculations. Ideally we want to pass co...
<python><c#><.net><integration>
2023-01-19 18:31:01
2
547
Dmitry Duginov
75,176,745
3,352,254
Pandas assign series to another Series based on index
<p>I have three Pandas Dataframes:</p> <p><code>df1</code>:</p> <pre><code>0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 NaN </code></pre> <p><code>df2</code>:</p> <pre><code>0 1 3 7 6 5 9 2 </code></pre> <p><cod...
<python><pandas><indexing><assign>
2023-01-19 18:26:20
1
825
smaica
75,176,489
12,224,591
Converting Python List to .NET IEnumerable?
<p>I'm attempting to call a C# function from a Python script, via the <code>clr</code> module from the <code>PythonNet</code> library.</p> <p>One of the arguments that this C# function takes is of the type <code>System.Collections.Generic.IEnumerable</code>. Simply supplying a list of the required data types to the fir...
<python><ienumerable><python.net>
2023-01-19 18:02:52
2
705
Runsva
75,176,315
18,183,907
how to skip backslash followed by integer?
<p>i have regex <a href="https://regex101.com/r/2H5ew6/1" rel="nofollow noreferrer">https://regex101.com/r/2H5ew6/1</a></p> <pre><code>(\!|\@)(1) Hello!1 World </code></pre> <p>and i wanna get first mark (!|@) and change the number <code>1</code> to another number <code>2</code> I did</p> <pre><code>{\1}2_ \1\\2_ </c...
<python><regex>
2023-01-19 17:47:17
4
487
yvgwxgtyowvaiqndwo