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,424,946
10,474,998
Make subplots using plotly express with values coming from a dataframe
<p>Assuming I have a toy model <code>df</code> which lists the <code>model</code> of the car and <code>customer rating</code> of one car showroom.</p> <pre><code>CustomerID Model Cust_rating 1 Corolla A 2 Corolla B 3 Forester A 4 ...
<python><pandas><matplotlib><plotly>
2023-02-12 04:47:03
2
1,079
JodeCharger100
75,424,936
11,611,632
ModuleNotFoundError - from .local_settings import *; Django
<p>Rather than using environmental variables to hide sensitive information, such as, SECRET_KEY, I'm using a module called <code>local_settings.py</code> since the file is ignored by <code>gitignore</code>.</p> <ul> <li><a href="https://stackoverflow.com/questions/33179419/private-settings-in-django-and-deployment">Pri...
<python><django><git><pythonanywhere>
2023-02-12 04:44:45
1
739
binny
75,424,934
4,531,757
Pandas-Transpose multi column level
<p>I got stuck with my limited Pandas knowledge. I have 100s patients who have test results (Success or Fail) spread by date. My objective here is to group the test result by Patient, Brand, Status types ....and spread by Date.</p> <p>I am enclosing my sample data and giving my result as a screenshot. Please help.</p> ...
<python><pandas><numpy>
2023-02-12 04:43:11
1
601
Murali
75,424,785
1,128,412
Case insensitive Array any() filter in sqlalchemy
<p>I'm migrating some code from SqlAlchemy 1.3 to SqlAlchemy 1.4 with Postgres 12. I found a query that looks like this:</p> <pre><code>session.query(Horse) .filter(Horse.nicknames.any(&quot;charlie&quot;, operator=ColumnOperators.ilike)) </code></pre> <p>The type of the column <code>nicknames</code> is <code>Column(...
<python><postgresql><sqlalchemy>
2023-02-12 03:44:38
1
3,609
Juan Enrique Muñoz Zolotoochin
75,424,637
10,613,037
How to get inclusive difference between timestamps
<p>I'd like to get the difference between the end and start date columns, inclusive</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame() df['start'] = pd.to_datetime(['1/1/2020','1/2/2020']) df['end'] = pd.to_datetime(['1/31/2020', '1/25/2020']) df['diff'] = df['end'] - df['start'] </code></pre> <...
<python><pandas>
2023-02-12 02:52:10
1
320
meg hidey
75,424,585
343,215
How do I work with Pandas multi-level series?
<p>I'm using Pandas <code>filter()</code> and <code>groupby()</code> to arrive at a count of employee types on a given day. I need to analyze this data for outliers. In this toy example, the outlier is any shift &amp; day where there are not two (2) shifts.</p> <pre><code>shifts = [(&quot;Cashier&quot;, &quot;Thursday&...
<python><pandas>
2023-02-12 02:32:20
1
2,967
xtian
75,424,473
511,571
Python return type hint of literal string
<p>This code is from GitPython library, and in particular from the <a href="https://github.com/gitpython-developers/GitPython/blob/3.1.30/git/cmd.py#L1207" rel="nofollow noreferrer">cmd.py file</a> (removed comments, to make it more concise):</p> <pre><code>class Git(LazyMixin): # A lot of code, removed def __...
<python><python-3.x><type-hinting>
2023-02-12 01:57:11
0
1,685
Virtually Real
75,424,467
10,557,442
How to customize the superuser creation in Django when using a proper User model?
<p>I have the following models defined on my user's app:</p> <pre class="lang-py prettyprint-override"><code>class Address(models.Model): tower = models.SmallIntegerField() floor = models.SmallIntegerField() door = models.CharField(max_length=5) class User(AbstractUser): address = models.OneToOneField...
<python><django>
2023-02-12 01:54:57
2
544
Dani
75,424,412
5,500,634
No module named 'pm4py.objects.petri' in pm4py
<p>I am using thePython open source <a href="https://github.com/pm4py" rel="nofollow noreferrer">pm4py</a>, and following the blog: <a href="https://medium.com/@c3_62722/process-mining-with-python-tutorial-a-healthcare-application-part-2-4cf57053421f" rel="nofollow noreferrer">Process Mining with Python tutorial: A hea...
<python><machine-learning>
2023-02-12 01:36:31
1
489
TripleH
75,424,405
11,671,779
Python decorate `class.method` that modify on `class.self`
<p>How to access <code>self</code> of the decorated method?</p> <p>Based on <a href="https://stackoverflow.com/a/57807897/11671779">this answer</a>, the self refer to the decorator:</p> <pre class="lang-py prettyprint-override"><code>class Decorator: def __init__(self, func): self.func = func def __cal...
<python><python-3.x><python-decorators><python-class>
2023-02-12 01:35:01
1
2,276
Muhammad Yasirroni
75,424,382
6,024,751
Use different values of expandtabs() in the same string - Python
<p>How can we define several tab lengths in a python string? For example, we want to print the keys, value types and values of a dict nicely aligned (with varying sizes of keys and types):</p> <pre><code>my_dict = { &quot;short_key&quot;: 4, &quot;very_very_very_very_very_long_keys&quot;: 5.0 } formatted_strin...
<python><string><string-formatting><tabexpansion>
2023-02-12 01:27:10
2
790
Julep
75,424,342
3,788,614
Python: Extract text and element selectors from html elements
<p>Given something like the following html:</p> <pre><code>&lt;div&gt; &lt;div&gt; &lt;meta ... /&gt; &lt;img /&gt; &lt;/div&gt; &lt;div id=&quot;main&quot;&gt; &lt;p class=&quot;foo&quot;&gt;Hello, World&lt;/p&gt; &lt;div&gt; &lt;div class=&quot;bar&quot;&gt;...
<python><html><beautifulsoup><css-selectors>
2023-02-12 01:09:51
1
1,116
Jack
75,424,275
19,130,803
How to kill a thread in python
<p>I have a flask app, in that I have a button name start and a cancel button. I have a task to process. I am creating a new thread for it to run in background setting as daemon thread. since it is a long running task, I am trying to provide a cancel option for it.</p> <p>Methods used as below:</p> <ul> <li>I tried us...
<python><flask>
2023-02-12 00:48:00
0
962
winter
75,424,197
1,441,864
Python email module behaves unexpected when trying to parse "raw" subject lines
<p>I have trouble parsing an email which is encoded in win-1252 and contains the following header (literally like that in the file):</p> <pre><code>Subject: Счета на оплату по заказу . . </code></pre> <p>Here is a hexdump of that area:</p> <pre><code>000008a0 56 4e 4f 53 41 52 45 56 40 41 43 43 45 4e 54 2e |V...
<python><email><character-encoding><subject><eml>
2023-02-12 00:24:41
3
823
born
75,424,185
6,228,056
Pandas pull rows where any column contains certain strings
<p>I'm trying to return rows where any of my columns contain any of the words in a word list. Let's say <code>word_list = ['Synthetic', 'Advanced or Advantage/Excellence']</code>. I've tried the following code <code>df[df.apply(' '.join, 1).str.contains('|'.join(word_list))]</code>.</p> <p>The problem is some of my col...
<python><pandas><string><dataframe><null>
2023-02-12 00:22:35
1
865
Stanleyrr
75,424,006
5,157,280
Is @staticmethod thread blocking?
<p>I had this question while adding an explicit wait for selenium as below.</p> <pre class="lang-py prettyprint-override"><code>class Wait: @staticmethod def wait_until_element_present(driver: webdriver, timeout: int = 10) -&gt; None: WebDriverWait(driver, timeout).until( EC.presence_of_elem...
<python><python-3.x><multithreading><blocking>
2023-02-11 23:36:17
1
322
Rasika
75,423,878
14,566,295
How to apply pipe to dictionary in python
<p>I am wondering if there is any way to apply pipe operator to the dictionary object like pandas dataframe.</p> <p>With pandas dataframe we can do below steps:</p> <pre><code>import pandas as pd dat1 = pd.DataFrame({'A' : [0], 'B' : [1]}) dat2 = pd.DataFrame({'C' : [0], 'D' : [1]}) chose = 'something' ((dat1 if chose...
<python>
2023-02-11 23:08:00
2
1,679
Brian Smith
75,423,821
12,546,311
Find first row where value is less than threshold
<p>I have a pandas data frame where I try to find the first <code>ID</code> for when the <code>left</code> is less than the values of</p> <pre><code>list = [0,50,100,150,200,250,500,1000] </code></pre> <pre><code> ID ST ... csum left 0 0 AK ... 4.293174e+05 760964.996900...
<python><pandas><dataframe>
2023-02-11 22:51:02
2
501
Thomas
75,423,594
7,267,480
pyswarms optimization of function in python
<p>I am trying to implement the fitting routine for experimentally received data. But the function that I am trying to optimize is a black-box - I don't know anything about some specific moments right now - but I can call it with some parameters.</p> <p>I am trying to find optimal parameters for function f(x), where x...
<python><optimization><particle-swarm>
2023-02-11 22:04:37
1
496
twistfire
75,423,541
6,630,397
In Spyder, is it possible to avoid "SyntaxError: 'return' outside function" when running a cell with a return statement
<p>In the <a href="https://www.spyder-ide.org/" rel="nofollow noreferrer">Spyder</a> (v.5.4.2) IDE, let:</p> <pre class="lang-py prettyprint-override"><code>import modules # %% def func(**args): # %% Spyder cell N do stuff if not var: return # &lt;-- this line causes the error in Spyder when running the...
<python><spyder>
2023-02-11 21:54:07
0
8,371
swiss_knight
75,423,423
7,437,143
Adding a new attribute to super class of plotly Annotation object?
<h2>Error message</h2> <p>After creating a super class that contains 1 additional attribute than the original <code>Annotation</code> class from Plotly, I am receiving error:</p> <pre><code>File &quot;/home/name/git/snn/snncompare/src/snncompare/mwe0.py&quot;, line 8, in __init__ self.edge = edge File &quot;/home...
<python><properties><attributes><plotly-dash><super>
2023-02-11 21:31:18
0
2,887
a.t.
75,423,388
4,320,924
Python's orphaned parser commands expr, st2list, sequence2st, compilest: are there any replacements?
<p>I have (I might even say I inherited it) a superb curve fitting library entirely written in Python. It worked pretty well until 3.10 was released. Then the module <strong>parser</strong> was deprecated and, obviously, my much-loved library stopped working. It all boils down to four parser commands only: <strong>expr...
<python><python-3.x><parsing>
2023-02-11 21:23:48
1
408
Fausto Arinos Barbuto
75,423,382
14,509,475
How to remove carriage return characters from string as if it was printed?
<p>I would like to remove all occurrences of <code>\r</code> from a string as if it was printed via <code>print()</code> and store the result in another variable.</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; s = &quot;hello\rworld&quot; &gt;&gt;&gt; print(s) world </code></pre> <p>In...
<python><python-3.x><string><stdout><carriage-return>
2023-02-11 21:22:58
3
496
trivicious
75,423,304
2,755,116
Make python script executable via pip using pyproject.toml
<p>I do not find any way to make an executable script via <code>pyproject.toml</code>. All I found is to use old <code>setup.cfg</code> file. The <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/" rel="nofollow noreferrer">official documentation</a> says nothing about that.</p> <p>Suppose yo...
<python><pip><executable>
2023-02-11 21:09:08
0
1,607
somenxavier
75,423,280
3,132,935
Python is printing 0x90c2 instead of just 0x90 NOP
<p>The following command is outputting 200 bytes of 'A' followed by one byte of 0x0a:</p> <pre class="lang-python prettyprint-override"><code>python3 -c &quot;print('\x41'*200)&quot; &gt; out.txt </code></pre> <p><code>hexdump out.txt</code> confirms this:</p> <pre><code>0000000 4141 4141 4141 4141 4141 4141 4141 4141 ...
<python><python-3.x><no-op>
2023-02-11 21:03:02
3
900
ramon
75,423,278
12,013,353
How are arrays formed in particle swarm optimization with pyswarms?
<p>I'm very new to optimization algorithms. I'm trying to do a particle swarm optimization in python with <code>pyswarms</code>, but I'm obviously missing something as I'm constantly getting errors like:<br /> <code>ValueError: operands could not be broadcast together with shapes (1,40,10) (10,40) (10,40)</code><br /> ...
<python><optimization><particle-swarm>
2023-02-11 21:02:46
1
364
Sjotroll
75,423,163
14,722,297
Sorting by subsampling every nth element in numpy array?
<p>I am trying to sample every nth element to sort an array. My current solution works, but it feels like there should be a solution that does not involve concatenation.</p> <p>My current implementation is as follows.</p> <pre class="lang-py prettyprint-override"><code>arr = np.arange(10) print(arr) [0 1 2 3 4 5 6 7 8 ...
<python><numpy><sorting>
2023-02-11 20:41:39
1
1,895
BoomBoxBoy
75,423,123
14,715,170
how to iterate dictionary over list in python?
<p>I have a dictionary following,</p> <pre><code>a = [{&quot;x&quot;:&quot;--New Value&quot;,&quot;y&quot;:20},{&quot;x&quot;:&quot;--New Value&quot;,&quot;y&quot;:21},{&quot;x&quot;:&quot;--New Value&quot;,&quot;y&quot;:27}] </code></pre> <p>While iterating using the code,</p> <pre><code>for i in a: print(i[&quot;...
<python><python-3.x><list><dictionary><for-loop>
2023-02-11 20:32:23
2
334
sodmzs1
75,423,085
1,317,018
How do I make appending large vectors to list faster
<p>I am trying to implement skip gram algorithm in plain numpy (not pytorch) which requires doing calculation (possibly avoidable details at the end):</p> <pre><code>xy = [] for i in tqdm(range(100000)): for j in range(15): xy.append([np.zeros(50000), np.zeros(50000)]) </code></pre> <p>So, this is a huge a...
<python><numpy><machine-learning><numpy-ndarray>
2023-02-11 20:24:36
1
25,281
Mahesha999
75,423,020
8,372,455
pyTest verify files are created correctly
<p>I'm using the <a href="https://python-docx.readthedocs.io/en/latest/" rel="nofollow noreferrer">Python docx package</a> to generate Microsoft Word documents with a script that also incorporates some other calculations/math functions handled in Python/Pandas/Numpy, etc... that automatically get inputted into the Word...
<python><pytest>
2023-02-11 20:11:16
1
3,564
bbartling
75,422,970
12,945,785
Plotly backend with pandas
<p>Hi I would like to do multiple graph (2 indeed) with pandas / backend Plotly. I don't know how to proceed. and what are the main option to change the size of my graph (it seems that figsize does not work) ? the color ?</p> <p>I did something like that:</p> <pre><code>import pandas as pd import matplotlib.pyplot as p...
<python><pandas><plotly>
2023-02-11 20:01:03
3
315
Jacques Tebeka
75,422,565
10,796,158
Why use read_fwf in Pandas if I can just use read_csv with a custom separator?
<p>I don't see the point of using <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_fwf.html#pandas.read_fwf" rel="nofollow noreferrer"><code>read_fwf</code></a> in Pandas. Why would I ever use this instead of <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow nore...
<python><pandas><dataframe><csv>
2023-02-11 18:52:11
1
1,682
An Ignorant Wanderer
75,422,440
17,124,619
Threading decorator is not callable
<p>I am implementing a thread as a decorator to a class which should apply threads to the method, all concurrently. However, I get the following error:</p> <blockquote> <p>TypeError: 'TEST_THREAD' object is not callable</p> </blockquote> <p>The example below should print out each iteration over the maximum thread numbe...
<python><multithreading>
2023-02-11 18:34:13
1
309
Emil11
75,422,337
14,947,895
Dask LocalCluster Fails to compute random.random above 300Mio data points
<p>I wanted to create some random data for later benchmarking. The chunks need to be configured this way as I want to calculate the rfft later.</p> <p>However, the sampling of the random data fails as soon as I am around (and above) 300 million data points. The code works fine in local mode. The code works fine when I ...
<python><dask><dask-distributed>
2023-02-11 18:19:11
0
496
Helmut
75,422,292
7,744,106
Telethon: check if message has replies?
<p>Let's assume we have replies with this structure:</p> <p>1─┐        (How are you today?)<br />      2─┐   (I'm fine, thanks. And you?)<br />           3   (I'm all right.)</p> <p>And I somehow got second message. I know that I can <code>get_reply_message</code> - this way I will get message <code>1</code> (current m...
<python><telethon><telegram-api>
2023-02-11 18:13:43
1
2,043
egvo
75,422,260
3,620,725
Do any libraries other than pandas use a MultiIndex?
<p>Are there any libraries with data tables that allow you to define multiple levels of column names the way you can in pandas with <a href="https://pandas.pydata.org/docs/user_guide/advanced.html" rel="nofollow noreferrer">MultiIndex</a>?</p> <p>It seems like there is no equivalent in <a href="https://stackoverflow.co...
<python><pandas>
2023-02-11 18:09:50
0
5,507
pyjamas
75,422,158
998,070
Moving Points with 1D Noise
<p>I'd like to move points in X &amp; Y with 1D Noise. To further clarify, I don't want each point to move by a unique random number, but rather a larger noise over the whole line with gradients moving the points. The Noise would serve as a multiplier for a move amount and would be a value between -1 and 1. For exampl...
<python><numpy><scipy><noise><perlin-noise>
2023-02-11 17:54:00
0
424
Dr. Pontchartrain
75,422,072
3,376,169
Dataframe query to filter using dictionary results
<p>I want to filter dataframe rows using dictionary. I want all the rows where val1 &gt; min_val_dict[user_id] But when I run following I get error</p> <pre><code>TypeError: unhashable type: 'Series' </code></pre> <p>Here is code:</p> <pre><code>import pandas as pd d={'user_id':[1,1,2,2,2,3,3],'val1':[101,102,103,104,...
<python><python-3.x><pandas>
2023-02-11 17:40:30
1
439
user3376169
75,422,064
3,963,430
Validate X-Hub-Signature-256 meta / whatsapp webhook request
<p>I can't manage to validate the X-Hub-Signature-256 for my meta / whatsapp webhook in flask successfully.</p> <p>Can anyone tell me where the error is or provide me with a working example?</p> <pre class="lang-python prettyprint-override"><code>import base64 import hashlib import hmac import os from dotenv import lo...
<python><flask><whatsapi>
2023-02-11 17:39:42
3
838
Gurkenkönig
75,422,019
3,485,908
Running different celery tasks (@shared_tasks) on different databases in django multi tenant application
<p>The application I am working on is a multitenant application. I am using celery to run background tasks.</p> <p>The background tasks that get pushed to Queue (rabbitmq) are getting executed properly when run on the <code>default</code> db setting configured in the settings. But when I submit the background jobs from...
<python><python-3.x><django><celery>
2023-02-11 17:32:17
2
1,539
ankit
75,421,997
5,212,614
How can I make node_color and node_size from items in a column and plot in networkx?
<p>I am trying to understand networkx. I am testing the sample code below.</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import numpy as np import networkx as nx # Input data files check from subprocess import check_output import warnings warnings.filterwarnings('ignore') G = nx.Graph() #df_...
<python><python-3.x><pandas><networkx>
2023-02-11 17:28:21
1
20,492
ASH
75,421,959
14,720,975
Python Equivalent for Deno's ensureDir
<p>What's the Python equivalent to Deno's <a href="https://deno.land/std@0.144.0/fs/ensure_dir.ts?s=ensureDir" rel="nofollow noreferrer"><code>ensureDir</code></a>?</p> <p>Usage example:</p> <pre><code>import { ensureDir, ensureDirSync } from &quot;https://deno.land/std/fs/mod.ts&quot;; ensureDir(&quot;./logs&quot;).th...
<python><file-handling>
2023-02-11 17:20:57
1
720
Eliaz Bobadilla
75,421,849
4,837,637
Google Cloud Run Flask App error import module
<p>I have developed a flask rest API and I'm using flask_smorest. I'm developing into cloud shell editor into google cloud. When I run google cloud run emulator, I receive the error:</p> <pre><code>##########Linting Output - pylint########## ************* Module app 3,0,error,import-error:Unable to import 'flask_smores...
<python><docker><google-cloud-run>
2023-02-11 17:03:28
1
415
dev_
75,421,794
8,162,211
App created using Pyinstaller unable to run due to pyqtgraph colormap issue
<p>I have a simple script that uses pyqtgraph to create a heatplot animation. I receive no error messages when converting it to an .app using pyinstaller. However, when attempting to run the .app from the command line using</p> <pre><code>./dist/MyApplication.app/Contents/MacOS/MyApplication </code></pre> <p>I obtain t...
<python><pyqt><pyqtgraph>
2023-02-11 16:54:16
1
1,263
fishbacp
75,421,574
14,045,537
How to customize marker styles and add numbers inside Folium markers
<p>I saw an example to add numbers inside markers using <code>plugins.BeautifyIcon</code> here - <a href="https://stackoverflow.com/a/70896775/14045537">Folium markers with numbers inside</a>.</p> <p>But I need an alternate solution to add numbers without using <code>plugins.BeautifyIcon</code>.</p> <pre><code>import f...
<python><html><css><leaflet><folium>
2023-02-11 16:21:08
1
3,025
Ailurophile
75,421,404
14,045,537
How to add Search plugin in folium for multiple fields?
<p>I'm trying to add a search bar in <code>folium</code> map using <code>folium plugins</code>.</p> <p><strong>Data:</strong></p> <pre><code>import geopandas states = geopandas.read_file( &quot;https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json&quot;, driver=&quot;Geo...
<python><leaflet><full-text-search><folium><folium-plugins>
2023-02-11 15:56:50
1
3,025
Ailurophile
75,421,384
5,308,892
No intellisense for Tensorflow functions in VSCode
<p>I've been trying to setup Tensorflow for Python in VSCode for a while now and I am constantly running into issues for which I cannot find a solution on the web. I installed it via <code>pip install tensorflow</code> and imported it with <code>import tensorflow as tf</code>. However, I do not seem to be getting any i...
<python><tensorflow><intellisense>
2023-02-11 15:54:46
1
2,146
cabralpinto
75,421,383
18,758,062
Resume Optuna study from most recent checkpoints
<p>Is there a way to be able to pause/kill the optuna study, then resume it either by running the incomplete trials from the beginning, or resuming the incomplete trials from the latest checkpoint?</p> <pre><code>study = optuna.create_study() study.optimize(objective) </code></pre>
<python><pytorch><hyperparameters><optuna>
2023-02-11 15:54:38
3
1,623
gameveloster
75,421,382
7,090,501
Highlight a single point in a boxplot in Plotly
<p>I have a boxplot in Plotly. I would like to overlay a single point on some of the boxes. I thought I could do this by adding a scatter trace to the <code>fig</code>, but when I look into the data of the figure I can't see anything specifying the y coordinate of the boxes so I'm not sure how to overlay the point. How...
<python><plotly><scatter-plot><boxplot>
2023-02-11 15:54:26
1
333
Marshall K
75,421,365
4,451,315
Groupby sum string
<p>In pandas, I can do</p> <pre class="lang-py prettyprint-override"><code>In [33]: df = pd.DataFrame({'a': [1, 1, 2], 'b': ['foo', 'bar', 'foo']}) In [34]: df Out[34]: a b 0 1 foo 1 1 bar 2 2 foo In [35]: df.groupby('a')['b'].sum() Out[35]: a 1 foobar 2 foo Name: b, dtype: object </code></pre> <...
<python><group-by><python-polars>
2023-02-11 15:52:10
3
11,062
ignoring_gravity
75,421,335
13,629,335
tkinter - Infinite Canvas "world" / "view" - keeping track of items in view
<p>I feel like this is a little bit complicated or at least I'm confused on it, so I'll try to explain it by rendering the issue. Let me know if the issue isn't clear.</p> <hr /> <p>I get the output from my <code>viewing_box</code> through the <code>__init__</code> method and it shows:<br /> <code>(0, 0, 378, 265)</cod...
<python><tkinter><canvas><tk-toolkit>
2023-02-11 15:47:30
1
8,142
Thingamabobs
75,421,185
683,945
Extract element names and type from XSD schemas
<p>I've got several schema definitions that I need to reconcile with a data model. I'm trying to extract the entity names, types and attribute names and types from these schema definitions with the Python ElemTree library, but finding it difficult to get the exact information out.</p> <p>In my XSDs there are several of...
<python>
2023-02-11 15:22:36
1
1,097
L4zl0w
75,421,008
173,748
Passing a python class constant to a decorator without self
<p>I'm using the python ratelimit library and it uses a decorator to handle rate limiting of a function. I have a class constant I'd like to pass into the decorator but of course <code>self</code> wont work.</p> <p>Is there a way to reference the <code>UNIVERSALIS_MAX_CALLS_PER_SECOND</code> constant within the decorat...
<python><decorator><introspection>
2023-02-11 14:55:59
2
2,067
Chris Cummings
75,420,947
11,462,274
How to collect the updated expiry time of a service created using gspread?
<p>In order not to need to create a new service each time I need it (sometimes I use it 8 times per code loop), I create a global object:</p> <pre class="lang-python prettyprint-override"><code>import gspread client_gspread = None def send_sheet(id_sheet, page_sheet, sheet_data): global client_gspread if not c...
<python><google-oauth><gspread>
2023-02-11 14:46:02
1
2,222
Digital Farmer
75,420,922
19,369,393
How to transform every element of numpy array into an array of size N filled with the element?
<p>I have a numpy array <code>a</code> the shape of which is (m, n). I want to transform this array into an array <code>b</code> with shape (m, n, l), where:</p> <pre><code>b[i,j].length == l b[i,j,k] == a[i,j] 0 &lt;= i &lt; m 0 &lt;= j &lt; n 0 &lt;= k &lt; l </code></pre> <p>For example:</p> <pre><code>m = 2 n = 3 ...
<python><arrays><numpy>
2023-02-11 14:40:29
1
365
g00dds
75,420,760
13,885,312
Django ORM JOIN of models that are related through JSONField
<p>If I have 2 models related through ForeignKey I can easily get a queryset with both models joined using select_related</p> <pre><code>class Foo(Model): data = IntegerField() bar = ForeignKey('Bar', on_delete=CASCADE) class Bar(Model): data = IntegerField() foos_with_joined_bar = Foo.objects.select_rel...
<python><django><orm><django-orm>
2023-02-11 14:13:52
3
415
Anton M.
75,420,574
2,762,570
As of 2023, is there any way to line profile Cython at all?
<p>Something has substantially changed with the way that line profiling Cython works, such that previous answers no longer work. I am not sure if something subtle has changed, or if it is simply totally broken.</p> <p>For instance, <a href="https://stackoverflow.com/questions/28301931/how-to-profile-cython-functions-li...
<python><profiling><cython><profiler><cythonize>
2023-02-11 13:43:09
1
405
Mike Battaglia
75,420,397
6,357,916
nn.Linear gives `Only Tensors of floating point and complex dtype can require gradients`
<p>I am trying to understand hon <code>nn.Embedding</code> works as <code>nn.Linear</code> in case when input is one hot vector.</p> <p>Consider, input is <code>[0,0,0,1,0,0]</code> which is one hot vector corresponding to index 3. So, I first created both:</p> <pre><code>_in = torch.tensor([0,0,0,1,0,0]).long() # used...
<python><numpy><pytorch>
2023-02-11 13:04:36
1
3,029
MsA
75,420,317
15,363,250
How to remove nulls from a pyspark dataframe based on conditions?
<p>Let's say I have a table with the ids of my clients, which streaming platform they are subscribers to and how often they pay for their subscription:</p> <pre><code>user_info +------+------------------+---------------------+ | id | subscription_plan| payment_frequency | +------+------------------+----------------...
<python><dataframe><pyspark>
2023-02-11 12:47:15
2
450
Marcos Dias
75,420,105
1,484,601
python typing: callback protocol and keyword arguments
<p>For example, mypy accepts this:</p> <pre><code>class P(Protocol): def __call__(self, a: int)-&gt;int: ... def call(a: int, f: P)-&gt;int: return f(a) def add_one(a: int)-&gt;int: return a+1 call(1,add_one) </code></pre> <p>but not this:</p> <pre><code>class P(Protocol): def __call__(self, a: int, ...
<python><python-typing><callable>
2023-02-11 12:07:20
3
4,521
Vince
75,420,072
7,848,740
Django media file page not found
<p>So, I'm trying to follow <a href="https://docs.djangoproject.com/en/4.1/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow noreferrer">Django documentation</a> about the static files and media files</p> <p>I have a clean Django installation and I want to add the media folder. What...
<python><django><django-urls><django-staticfiles><django-media>
2023-02-11 12:01:49
2
1,679
NicoCaldo
75,420,026
18,749,472
Python - create wrapper function for SQL queries
<p>In my project I have lots of functions that carry out SQL queries. These queries include SELECT, UPDATE, INSERT etc... When writing functions for SELECT queries for example, I write the same structure of code in every single function. e.g.</p> <pre><code>def generic_select_function(self): result = self.cursor.ex...
<python><oop><decorator><wrapper><python-decorators>
2023-02-11 11:53:00
1
639
logan_9997
75,419,990
7,093,241
Capturing or printing variables in bashrc with shell=True in run command of subprocess module
<p>I am learning concurrency with <em>Python 3 Standard Library, 2nd Editio</em>n. Is there a way to get the <code>subprocess</code> module to use variables in my <code>.bashrc</code> when I set <code>shell=True</code>?</p> <p>I tried adding <code>echo &quot;something&quot;</code> in my <code>.bashrc</code> and ran the...
<python><bash><subprocess>
2023-02-11 11:48:33
1
1,794
heretoinfinity
75,419,794
720,877
How to specify setuptools entrypoints in a pyproject.toml
<p>I have a setup.py like this:</p> <pre><code>#!/usr/bin/env python from setuptools import setup, find_packages setup( name=&quot;myproject&quot;, package_dir={&quot;&quot;: &quot;src&quot;}, packages=find_packages(&quot;src&quot;), entry_points={ &quot;console_scripts&quot;: [ &q...
<python><setuptools><program-entry-point><python-packaging><pyproject.toml>
2023-02-11 11:17:53
1
2,820
Croad Langshan
75,419,592
12,263,543
AzureML SVD Model Deployment Fails for Managed Instance. Missing azureml.studio package
<p>I've built a SVD recommmendation model in AzureML Studio based on the <a href="https://learn.microsoft.com/en-us/azure/machine-learning/component-reference/train-svd-recommender" rel="nofollow noreferrer">example in the azure docs</a>. If I deploy the model to a real-time Container Instance endpoint directly from th...
<python><azure-machine-learning-service><azuremlsdk>
2023-02-11 10:39:24
0
1,655
picklepick
75,419,489
9,102,437
Jupyter lab doesn't open a notebook
<p>I am using jupyter lab on a server. I have recently reinstalled it using <code>pip-autoremove</code> and got a new issue: some <code>.ipynb</code> files which were created prior to the reinstall are not opening, they just display a blank page (as if there are no cells) and I am unable to run the code. At the same ti...
<python><linux><jupyter-notebook><jupyter><jupyter-lab>
2023-02-11 10:19:12
0
772
user9102437
75,419,222
17,696,880
Replace all occurrences of a word with another specific word that must appear somewhere in the sentence before that word
<pre class="lang-py prettyprint-override"><code>import re #example 1 input_text = &quot;((PERSON)María Rosa) ((VERB)pasará) unos dias aqui, hay que ((VERB)mover) sus cosas viejas de aqui, ya que sus cosméticos ((VERB)estorban) si ((VERB)estan) tirados por aquí. ((PERSON)Cyntia) es una buena modelo, su cabello es muy b...
<python><python-3.x><regex><string><regex-group>
2023-02-11 09:29:51
1
875
Matt095
75,419,141
1,999,585
How can I efficiently create a list with the figures of a number in Python?
<p>I have a number and I want to create a list, each element having the figures of the aforementioned number.</p> <p>As an example, I have <code>n=225</code> and I want to have the list <code>l=[2,2,5]</code>.</p> <p>I can convert the number into a string, then convert the string as a list, like this:</p> <pre><code>l=...
<python>
2023-02-11 09:11:44
0
2,424
Bogdan Doicin
75,419,046
19,429,024
Why can't I sort columns in my PyQt5 QTableWidget using UserRole data?
<p>I am trying to sort my QTableWidget columns by the values stored in the user role of each QTableWidgetItem, but I am unable to do so. I have enabled sorting with <code>self.setSortingEnabled(True)</code>, and I have set the data in each QTableWidgetItem with <code>item.setData(Qt.DisplayRole, f'M - {r}')</code> and ...
<python><qt><pyqt><pyqt5>
2023-02-11 08:51:01
2
587
Collaxd
75,418,911
9,363,441
How to set connection with database in the api Flask?
<p>I'm trying to create the api on my linux PC. At this moment I have support for some basic requests which were done just for testing. My api works in cooperation with <code>uswgi+nginx+flask</code>. And now I'm trying to add connection to the database. For this purpose I had installed <code>MySQL</code> and created d...
<python><mysql><flask>
2023-02-11 08:18:50
1
2,187
Andrew
75,418,680
9,757,174
firebase-admin adding a random alphanumeric key to the realtime database when using push()
<p>I am using the Python <code>firebase-admin</code> library to integrate Django rest framework and Firebase Realtime storage. I am using the <code>push()</code> function to create a new child node. However, the function adds an alphanumeric key to each child. Is there a way I can avoid that and add my own custom keys ...
<python><django><firebase><django-rest-framework><firebase-admin>
2023-02-11 07:19:26
1
1,086
Prakhar Rathi
75,418,655
6,778,118
How to load private python package when loading a MLFlow model?
<p>I am trying to use a private Python package as a model using the <code>mlflow.pyfunc.PythonModel</code>.</p> <p>My <code>conda.yaml</code> looks like</p> <pre><code>channels: - defaults dependencies: - python=3.10.4 - pip - pip: - mlflow==2.1.1 - pandas - --extra-index-url &lt;private-pypa-repo-link&gt; - &l...
<python><pandas><mlflow><mlops>
2023-02-11 07:13:57
1
383
Vikrant Yadav
75,418,351
14,436,930
np.pad significantly slower than concatenate or assignment
<p>Given a list of <code>n</code> integer arrays of variable lengths (length always less than 500), my goal is to form a single matrix of size <code>(n, 500)</code>, the arrays shorter than 500 will be padded with a given constant in the front. However, I noticed that np.pad, which is designed to pad values, is actuall...
<python><arrays><numpy><performance>
2023-02-11 05:50:52
2
671
seermer
75,418,252
19,238,204
How to Create 3D Torus from Circle Revolved about x=2r, r is the radius of circle (Python or JULIA)
<p>I need help to create a torus out of a circle by revolving it about x=2r, r is the radius of the circle.</p> <p>I am open to either JULIA code or Python code. Whichever that can solve my problem the most efficient.</p> <p>I have Julia code to plot circle and the x=2r as the axis of revolution.</p> <pre><code>using P...
<python><julia>
2023-02-11 05:23:33
3
435
Freya the Goddess
75,418,186
7,797,210
Linux NoHup fails for Streaming API IG Markets where file is python
<p>This is quite a specific question regarding nohup in linux, which runs a python file. Back-story, I am trying to save down streaming data (from IG markets broadcast signal). And, as I am trying to run it via a remote-server (so I don't have to keep my own local desktop up 24/7), somehow, the nohup will not engage wh...
<python><linux><algorithmic-trading><nohup>
2023-02-11 05:02:03
1
571
Kiann
75,418,176
2,324,298
BERT get top N words for each category
<p>I trained a BERT text classification model with 38 categories. Now, for each of these 38 categories I want to find out the top N words.</p> <p>To do that, I used sklearn's CountVectorizer to create a vocabulary from the training dataset.</p> <p>I passed that vocabulary to the tokenizer and used those tokens to pass ...
<python><pytorch><huggingface-transformers><bert-language-model>
2023-02-11 04:58:07
1
8,005
Clock Slave
75,418,150
1,354,930
Is there a way to access the "another exceptions" that happen in a python3 traceback?
<p>Let's assume you have some simple code that <em>you don't control</em> (eg: it's in a module you're using):</p> <pre class="lang-py prettyprint-override"><code>def example(): try: raise TypeError(&quot;type&quot;) except TypeError: raise Exception(&quot;device busy&quot;) </code></pre> <p>How...
<python><python-3.x><error-handling><try-except><traceback>
2023-02-11 04:49:10
1
1,917
dthor
75,418,148
9,596,111
Why is the "is" operator behaves differently for strings and lists in Python?
<p>From what I read in the documents,</p> <blockquote> <p><code>is</code> operator is used to check if two values are located on the same part of the memory</p> </blockquote> <p>So I compared two empty lists and as I expected I got <code>False</code> as a result.</p> <pre><code>print([] is []) # False </code></pre> <p>...
<python><arrays><string>
2023-02-11 04:48:56
0
878
Maran Sowthri
75,418,054
58,845
Where can I find information about model size or model-loading rate limits when using MLflow on Azure Databricks?
<p>How can I find out what the limits might be to the rate at which I can load MLflow models or the size of models I can register with MLflow? (I'm using MLflow as integrated with Azure Databricks.)</p> <p>I've been looking at these two posts from the Databricks blog:</p> <ul> <li><a href="https://www.databricks.com/bl...
<python><azure><databricks><azure-databricks><mlflow>
2023-02-11 04:12:17
0
7,164
jtolle
75,417,919
11,652,655
Computing similarities between pairs of words
<p>This the code I am using to compute similarities between pairs of words.</p> <pre><code>computed_similarities=[] for s in nlp.vocab.vectors: _:nlp.vocab[s] for word in nlp.vocab: if word.has_vector: if word.is_lower: if word.is_alpha: similarity=cosine_similarity(new_vec...
<python><scipy><spacy>
2023-02-11 03:25:34
1
1,285
Seydou GORO
75,417,698
16,124,033
What type of code should I use to insert some strings in a string?
<p>I want to insert some strings in a string.</p> <p>All I know is that there are four ways to do this, here are four examples:</p> <pre class="lang-py prettyprint-override"><code>query = &quot;What type of code should I use to insert some strings in a string?&quot; category = &quot;Python&quot; query_category = &quo...
<python>
2023-02-11 02:10:42
1
4,650
My Car
75,417,677
219,976
How to debug docker application running by gunicorn by PyCharm
<p>I have django rest framework application with socket.io which is run in docker using gunicorn as a WSGI-server. Here's how application is run in docker-compose:</p> <pre><code> web: build: context: . command: - gunicorn - my_app.wsgi:application ports: - &quot;8000:8000&quot; </co...
<python><docker><debugging><pycharm><gunicorn>
2023-02-11 02:05:38
0
6,657
StuffHappens
75,417,661
9,988,487
Make a Python memory leak on purpose
<p>I'm looking for an example that purposely makes a memory leak in Python.</p> <p>It should be as short and simple as possible and ideally not use non-standard dependencies (that could simply do the memory leak in C code) or multi-threading/processing.</p> <p>I've seen memory leaks achieved before but only when bad th...
<python><memory-leaks><cpython>
2023-02-11 02:01:01
1
1,640
Adomas Baliuka
75,417,626
219,976
How to I set logging for gunicorn GeventWebSocketWorker
<p>I have django rest framework application with socket.io. To run it in staging I use gunicorn as WSGI-server and GeventWebSocketWorker as a worker. The thing I want to fix is that there's no logs for web requests like this:</p> <pre><code>[2023-02-10 10:54:21 -0500] [35885] [DEBUG] GET /users </code></pre> <p>Here's ...
<python><logging><gunicorn>
2023-02-11 01:47:08
2
6,657
StuffHappens
75,417,581
10,568,883
How to properly connect QPushButton clicked signal to pyqtSlot
<p>I'm writing a tool with GUI, where I inevitably need to use <code>pyqtSlot</code>. I had errors in this tool, related to its usage and decided to try a minimal example. However, I still fail to figure out the problem.</p> <p>I've read instructions <a href="https://pythonspot.com/pyqt5-buttons/" rel="nofollow norefer...
<python><qt><pyqt5><qt5>
2023-02-11 01:34:00
0
499
Евгений Крамаров
75,417,579
4,212,158
How to manually log to Ray Train's internal Tensorboard logger?
<p>Ray Train automatically stores various things to Tensorboard. In addition, I want to log custom histograms, images, PR curves, scalars, etc. How do I access Ray Train's internal TBXLogger so that I can log additional things?</p>
<python><tensorboard><ray><ray-tune><tensorboardx>
2023-02-11 01:33:33
1
20,332
Ricardo Decal
75,417,499
1,410,769
Sum cells with duplicate column headers in pandas during import - python
<p>I am trying to do some basic dimensional reduction. I have a CSV file that looks something like this:</p> <pre><code>A B C A B B A C 1 1 2 2 1 3 1 1 1 2 3 0 0 1 1 2 0 2 1 3 0 1 2 2 </code></pre> <p>I want to import as a pandas DF but without renaming the headers to A.1 A.2 etc. Instead I want to sum the duplicates a...
<python><pandas><csv>
2023-02-11 01:12:56
2
455
Taurophylax
75,417,495
3,508,811
How to use Python's regex to match a GPG signature?
<p>I am trying to see if I can match the gpgsig using the regex below, but ran into an error also shown below.</p> <p>Is there any guidance on how to fix it?</p> <pre><code>import re if __name__ == '__main__': log = ''' tree e76fa5ccd76492d843b6a4a06038d1c3b5aef6f8 parent 0d533a3a5fd51fd8c2x932832ef9ea91d0756c18 a...
<python><python-3.x><python-re><gpg-signature>
2023-02-11 01:12:14
1
925
user3508811
75,417,406
13,460,543
Is there an error with pandas.Dataframe.ewm calculation or I am wrong?
<p>I choose the recursive option in order to calculate weighted moving average starting from the latest calculated value.</p> <p>According to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html" rel="nofollow noreferrer">Documentation</a> :</p> <blockquote> <p>When adjust=False, the exponent...
<python><pandas>
2023-02-11 00:48:49
1
2,303
Laurent B.
75,417,334
825,227
Use of parameters dictionary with Python requests GET method
<p>Trying to retrieve data via the EIA data API (v2): <a href="https://www.eia.gov/opendata/documentation.php" rel="nofollow noreferrer">https://www.eia.gov/opendata/documentation.php</a>.</p> <p>I'm able to use the API dashboard to return data:</p> <p><a href="https://www.eia.gov/opendata/browser/electricity/retail-s...
<python><python-requests>
2023-02-11 00:29:11
1
1,702
Chris
75,417,315
5,049,813
`isin` fails to detect a row that is in a dataframe
<p>I've been struggling with an error for days, and after many conversations with ChatGPT, finally got it boiled down to this one minimal example:</p> <pre><code>import pandas as pd # Create two data frames with duplicate values goal_df = pd.DataFrame({'user_id': [1], 'sentence_id': [2]}) source_df = pd.DataFrame({'us...
<python><pandas>
2023-02-11 00:26:35
3
5,220
Pro Q
75,417,265
3,769,076
Error uploading Spark parquet files from Snowflake-S3-Stage to a Snowflake Table
<p>EDIT: The error was from Spark's <code>_SUCCESS</code> file. Only include parquet files in the SQL query: <code>pattern = '.*parquet'</code></p> <p>Original:</p> <p>Can Snowflake load my multi-part parquet files? I have other inserts that work in the same tech-stack but they all use a single parquet file. I'm wonder...
<python><apache-spark><snowflake-cloud-data-platform><parquet>
2023-02-11 00:15:42
1
1,068
solbs
75,417,119
6,484,157
how to find what is the latest version of python that pytorch
<p>When I try <code>pip install torch</code>, I get</p> <p>ERROR: Could not find a version that satisfies the requirement torch (from versions: none)</p> <p>ERROR: No matching distribution found for torch</p> <p>Searching on here stackoverflow I find that the issue is I need an older verson of python, currently I'm usi...
<python><pytorch>
2023-02-10 23:42:00
2
501
usr0192
75,416,994
998,070
Maintaining Sharp Corners in a Numpy Interpolation
<p>I am interpolating a shape with numpy's <code>linspace</code> and <code>interp</code> using <a href="https://stackoverflow.com/users/2749397/gboffi">gboffi</a>'s magnificent code from <a href="https://stackoverflow.com/questions/75416188/get-evenly-spaced-points-from-a-curved-shape/">this post</a> (included, below)....
<python><numpy><matplotlib><scipy><interpolation>
2023-02-10 23:18:17
4
424
Dr. Pontchartrain
75,416,990
3,821,425
Pythonic: How much work is too much work to run at the time of file import
<p>Conceptually what I'm wanting to do is below. I have an enum for status, and I want to make a set which defines the statuses which are a 'completed' status (e.g. finished and failed)</p> <p>My internal gripe is that the variable 'completed_statuses' is being created at import time. I've been on teams where people w...
<python><enums>
2023-02-10 23:17:58
0
3,107
nanotek
75,416,925
702,846
group_by and add a counter column in polars dataframe
<p>I have a polars dataframe</p> <pre><code>import polars as pl df = pl.from_repr(&quot;&quot;&quot; ┌─────────┬─────────────────────────────┐ │ item_id ┆ num_days_after_first_review │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════════╪═════════════════════════════╡ │ 1 ...
<python><python-polars>
2023-02-10 23:08:18
1
6,172
Areza
75,416,834
1,451,579
How to apply a transformation matrix to the plane defined by the origin and normal
<p>I have a plane defined by the origin(point) and normal. I need to apply 4 by 4 transformation matrix to it. How to do this correctly?</p>
<python><numpy><geometry><rotation>
2023-02-10 22:51:15
1
659
Brans
75,416,760
8,548,583
Chrome does not use my download.default_directory settings, and always downloads to my Python execution folder
<p>This is Chrome 111 on Debian 11 - I am attempting to download a file to a folder. As of 3 AM last night, it was working - as of 6 AM this morning, with no server modifications or updates or resets, it was not - all files any Python script utilizing this code segment now download the files to their execution directo...
<python><linux><selenium-chromedriver><debian>
2023-02-10 22:37:46
3
458
Kwahn
75,416,656
6,357,649
403 Request Failure Despite working Service Account google.oauth2
<p>I am consistently running into problems querying in python using the following libraries. I am given a 403 error, that the &quot;user does not have 'bigquery.readsessions.create' permissions for the project I am accessing.</p> <pre><code>#BQ libs from google.cloud import bigquery from google.oauth2 import service_ac...
<python><pandas><google-bigquery>
2023-02-10 22:20:48
1
323
Devin
75,416,655
17,274,113
calling a function defined in different python script within working folder
<p>I am trying to call a function defined in file <code>lidar_source_code.py</code> from my main script <code>py_lidar_depressions.py</code>. There are numerous sources which explain how to do this such as <a href="https://www.geeksforgeeks.org/python-call-function-from-another-file/" rel="nofollow noreferrer">this one...
<python><function>
2023-02-10 22:20:42
0
429
Max Duso