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,443,742
10,844,937
How to inspect total amount of celery worker?
<p>I start 10 <code>celery</code> workers by the following.</p> <pre><code>celery -A worker.celery worker -l info -c 10 </code></pre> <p>I need to know the total amount of active <code>celery</code> workers. If the total amout of active workers are not bigger than 10, we can handle the new task. If not, the new task h...
<python><subprocess><celery>
2023-02-14 05:15:29
2
783
haojie
75,443,581
18,758,062
stable_baselines3 callback on each step
<p>I am training a <code>stable_baselines3</code> <code>PPO</code> agent and want to perform some task on every step. To do this, I'm using a callback <code>CustomCallback</code> with <code>_on_step</code> method defined.</p> <p>But it appears that <code>_on_step</code> is called only on every <code>PPO.n_steps</code>,...
<python><machine-learning><pytorch><reinforcement-learning><stable-baselines>
2023-02-14 04:50:50
0
1,623
gameveloster
75,443,467
102,401
How do you parse sections of text with Lark in Python
<p>I'm trying to figure out how to use the <a href="https://lark-parser.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">Lark Python Module</a> to parse a document that looks like this:</p> <pre><code>---&gt; TITLE Introduction ---&gt; CONTENT The quick Brown fox ---&gt; TEST Jumps over ---&gt; CON...
<python><lark-parser>
2023-02-14 04:30:03
1
25,593
Alan W. Smith
75,443,406
7,766,024
How do I "push down" the current columns to form the first row, and create new columns to replace that one?
<p>I have a DataFrame that essentially has the first row that I want as the column row and I'd like to know how to set new columns and set that row as the first row.</p> <p>For example:</p> <pre><code>| 4 | 3 | dog | | --- | --- | --- | | 1 | 2 | cat | </code></pre> <p>I want to change that DataFrame to be:</p>...
<python><pandas><dataframe>
2023-02-14 04:17:31
1
3,460
Sean
75,443,405
14,661,648
Python psycopg2 Caching?
<p>Is it possible to store the executed <code>fetchall()</code> query from psycopg2 into memory, so that I don't have to run that again on my database with a million entries?</p> <p>What's the best way to store them locally on a machine so that Python can any time dissect the <code>list</code>?</p>
<python><postgresql><psycopg2>
2023-02-14 04:17:29
1
1,067
Jiehfeng
75,443,369
1,056,563
"RuntimeWarning: divide by zero encountered in log" in numpy.log even though small values were filtered out
<p>Given <code>samplex</code>:</p> <pre><code>In [22]: samplex Out[22]: array([0. , 0.00204082, 0.00408163, 0.00612245, 0.00816327, 0.01020408, 0.0122449 , 0.01428571, 0.01632653, 0.01836735, 0.02040816, 0.02244898, 0.0244898 , 0.02653061, 0.02857143, 0.03061224, 0.03265306, 0.03469388, 0.03...
<python><numpy>
2023-02-14 04:07:49
3
63,891
WestCoastProjects
75,443,351
5,182,223
Python asyncio unable to run multiple tasks properly
<p>I have the following code snippet that I am expecting it to run two async functions (<code>func1</code> and <code>func2</code>) concurrently, and:</p> <ul> <li><code>Worker</code> is an infinite loop that keeps fetching items from a global <code>asyncio.Queue</code> instance no matter if the queue is empty or not an...
<python><python-asyncio>
2023-02-14 04:04:26
1
677
nonemaw
75,443,262
11,462,274
The zone attribute is specific to pytz's interface; please migrate to a new time zone provider
<p>I need to filter the lines where the date is today and not more than 2 hours ago according to local time (the code needs to be malleable as I travel to different timezones):</p> <pre class="lang-python prettyprint-override"><code> from tzlocal import get_localzone import pandas as pd import pytz df['DATA_HORA'] = d...
<python><pandas><datetime><timezone><pytz>
2023-02-14 03:47:06
1
2,222
Digital Farmer
75,443,109
9,331,134
pandas join on columns which contains a list - match any
<p>I have two dataframes <br> I want to join on a column where one of the column is a list, <br> need to join if any value in list matches</p> <pre><code>df1 = | index | col_1 | | ----- | ----- | | 1 | 'a' | | 2 | 'b' | df2 = | index_2 | col_1 | | ------- | ----- | | A | ['a...
<python><pandas><dataframe><join>
2023-02-14 03:08:12
2
1,082
Kaushik J
75,443,080
13,730,432
How can I fix this error while uploading csv to bigquery?
<p>I am getting the below error while uploading a CSV to bigquery using Python:</p> <p>google.api_core.exceptions.BadRequest: 400 Error while reading data, error message: Could not parse '80:00:00' as TIME for field global_time_for_first_response_goal (position 36) starting at location 11602908 with message 'Invalid t...
<python><csv><google-bigquery>
2023-02-14 03:02:09
1
701
xis10z
75,443,038
5,666,087
How do I modify TIFF physical resolution metadata
<p>I have several pyramidal, tiled TIFF images that were converted from a different format. The converter program wrote incorrect data to the XResolution and YResolution TIFF metadata. How can I modify these fields?</p> <pre><code>tiff.ResolutionUnit: 'centimeter' tiff.XResolution: '0.34703996762331574' tiff.YResolutio...
<python><tiff>
2023-02-14 02:52:47
1
19,599
jkr
75,442,872
4,780,574
Postgres/psycopg2 "executue_values": Which argument was not converted during string formatting?
<p>I am using <code>execute_values</code> to insert a list of lists of values into a postgres database using psycopg2. Sometimes I get &quot;not all arguments converted during string formatting&quot;, indicating that one of the values in one of the lists is not the expected data type (and also not NoneType). When it is...
<python><postgresql><debugging><psycopg2><sqldatatypes>
2023-02-14 02:14:48
0
814
Stonecraft
75,442,675
564,872
lxml fails to import, with error `symbol not found in flat namespace '_xsltDocDefaultLoader'`
<p>With the code:</p> <pre><code>from lxml.etree import HTML, XML </code></pre> <p>I get the traceback:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/username/code/project/lxml-test.py&quot;, line 3, in &lt;module&gt; from lxml.etree import HTML, XML ImportError: dlopen(/Users/username/.virt...
<python><python-3.x><lxml><apple-m1>
2023-02-14 01:26:17
3
655
Civilian
75,442,651
3,225,420
Miniconda Not Using Environment Python
<p>I've searched for hours - if this is a duplicate question please be kind :)</p> <p>PC had Anaconda 4.x.x. Resolver took hours and I was stuck, could not upgrade Anaconda. Therefore I:</p> <ul> <li>Uninstalled Anaconda</li> <li>Downloaded Miniconda for Windows 10</li> <li>Created a new environment, installed pandas...
<python><anaconda><miniconda><anaconda3>
2023-02-14 01:21:18
0
1,689
Python_Learner
75,442,308
3,763,616
How to calculate the month begin and end month date from date in polars?
<p>Is there an efficient way to get the month end date on a date column. Like if date =β€˜2023-02-13” to return β€œ2023-02-28”, also beginning of the month would be great as well. Thanks!</p> <pre><code>df = pl.DataFrame({'DateColumn': ['2022-02-13']}) test_df = df.with_columns([ pl.col('DateColumn').str.strptime(pl....
<python><date><python-polars>
2023-02-14 00:05:27
2
489
Drthm1456
75,442,268
70,157
Specify install directories, with PEP 517 installer
<p>How can I specify, to a PEP 517 conformant installer, the directories where libraries and scripts should be installed?</p> <h2>Deprecated Setuptools installer does it right</h2> <p>Using <code>python3 -m setup install --install-lib=/usr/share/foo/ --install-scripts=/usr/share/bar/</code>, I can specify the installat...
<python><software-packaging>
2023-02-13 23:58:40
0
32,600
bignose
75,442,206
8,321,207
Finding mean/SD of a group of population and mean/SD of remaining population within a data frame
<p>I have a pandas data frame that looks like this:</p> <pre><code>id age weight group 1 12 45 [10-20] 1 18 110 [10-20] 1 25 25 [20-30] 1 29 85 [20-30] 1 32 49 [30-40] 1 31 70 [30-40] 1 37 39 [30-40] </code></pre> <p>I am looking for a data frame that wo...
<python><pandas><dataframe><mean><standard-deviation>
2023-02-13 23:44:48
1
375
Kathan Vyas
75,442,186
505,188
Pandas Mean and Merge Two DataFrames
<p>I have two dataframes that I need to get the means for plus merge based on their original column names. An example is this:</p> <pre><code> df = pd.DataFrame({ 'sepal_length': [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0], 'sepal_width': [3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4], 'petal_length': [1.4, 1.4, 1.3, 1.5, 1.4,...
<python><pandas><dataframe>
2023-02-13 23:41:13
1
712
Allen
75,442,020
10,659,353
Python list.index function with random probability on collision
<p>Let's say I have a list: <code>a = [1,1]</code>.</p> <p>If I call <code>a.index(1)</code> it will always return <code>0</code>.</p> <p>Is there any pythonic way to return <code>0</code> or <code>1</code> in equal probabilities?</p>
<python><arrays><random>
2023-02-13 23:09:12
1
381
Enzo Dtz
75,441,985
18,476,381
Python convert datetime in jinja template to update SQL table
<p>I have a jinja template below in which some of the values are of datetime. I initially ran my template but the SQL query generated would convert datetime values to the following:</p> <blockquote> <p>2023-02-13 20:56:13.112000+00:00</p> </blockquote> <p>. The datetime should instead be strings without the extra +00:0...
<python><sql><datetime><jinja2>
2023-02-13 23:01:57
1
609
Masterstack8080
75,441,980
2,487,835
How to install imagemagick on android?
<p>I am writing python code on android using Pydroid app. Able to install pip packages, but imagemagick, which is requirement for image generation, as I understand, is a binary. I have access to terminal emulator, but don't know command that would work on android. Please suggest what to do.</p>
<python><android><imagemagick><pydroid>
2023-02-13 23:00:51
0
3,020
Lex Podgorny
75,441,918
214,526
DataFrame from list of dicts with relative order of keys maintained in columns
<p>I have a list of dictionaries (row data) like below:</p> <pre class="lang-py prettyprint-override"><code>from typing import List, Dict, Any testDict: List[Dict[str, Any]] = list( ( {&quot;A&quot;: 0.1, &quot;B&quot;: 1, &quot;E&quot;: &quot;ABE&quot;}, {&quot;A&quot;: 0.11, &quot;B&quot;: 20, &q...
<python><pandas><dataframe>
2023-02-13 22:51:41
2
911
soumeng78
75,441,827
188,547
vectorized addition in numpy array
<p>How do I vectorize addition between columns in a numpy array? For example, what is the fastest way to implement something like:</p> <pre><code>import numpy ary = numpy.array([[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,11]]) for i in range(ary.shape[0]): ary[i,0] += ary[i,1] </code></pre>
<python><numpy>
2023-02-13 22:34:52
1
1,423
Brad
75,441,786
4,688,190
Selenium Python Chrome: Extremely slow. Are cookies the problem?
<p>I read that Selenium Chrome can run faster if you use implicit waits, headless, ID and CSS selectors etc. Before implementing those changes, I want to know whether cookies or caching could be slowing me down.</p> <p>Does Selenium store cookies and cache like a normal browser or does it reload all assets everytime it...
<python><selenium-webdriver><selenium-chromedriver>
2023-02-13 22:27:50
2
678
Ned Hulton
75,441,774
18,505,884
How to customise distance between tickers on the 2nd y-axis in BokehJS
<p>So I'm trying to create a plot with BokehJS. This plot needs 3 axes (left, right, bottom): The plot looks like this</p> <p><a href="https://i.sstatic.net/qGHzS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qGHzS.png" alt="Graph output" /></a></p> <p>As you can see, the right y-axis is pretty ugly, y...
<javascript><python><plot><bokeh><bokehjs>
2023-02-13 22:25:44
1
614
mrblue6
75,441,747
5,302,069
Function imported from file can't find a module - what's going on? (python)
<p>As the title says, I'm encountering an issue where a function imported from a file (<code>myfun_fromfile</code>) doesn't seem to have access to other imported modules, e.g. <code>cv2</code>.</p> <p>Solutions that work are 1) defining the function in the same script it's called in (<code>myfun_inline</code>) and 2) i...
<python><opencv><import>
2023-02-13 22:21:29
1
499
R Greg Stacey
75,441,624
3,803,152
Can I get both an enum value and enum class name from a string in Python?
<p>Let's say I have the following Python enum class:</p> <pre class="lang-py prettyprint-override"><code>class FooEnum(IntEnum): foo = auto() bar = auto() baz = auto() </code></pre> <p>And I also have the strings <code>&quot;FooEnum&quot;</code> and <code>&quot;bar&quot;</code>. Both of the strings come fro...
<python>
2023-02-13 22:01:16
1
6,985
TheSoundDefense
75,441,557
11,397,243
Regex with m flag in Perl vs. Python
<p>I'm trying to automatically translate some simple Perl code with a regex to Python, and I'm having an issue. Here is the Perl code:</p> <pre class="lang-perl prettyprint-override"><code>$stamp='[stamp]'; $message = &quot;message\n&quot;; $message =~ s/^/$stamp/gm; print &quot;$message&quot;; [stamp]message </code></...
<python><regex><multiline>
2023-02-13 21:52:53
3
633
snoopyjc
75,441,438
3,383,640
Detect Fluid Pathlines in Images
<p>I have several thousand images of fluid pathlines -- below is a simple example --</p> <p><a href="https://i.sstatic.net/vZe68.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vZe68.jpg" alt="image" /></a></p> <p>and I would like to automatically detect them: Length and position. For the position a defi...
<python><fluid-dynamics>
2023-02-13 21:39:43
1
5,078
Suuuehgi
75,441,386
1,260,682
generating AST from existing python function
<p>I'm trying to use python's <code>ast.parse</code> to generate the AST of a function I defined, but the <code>parse</code> function takes in strings as parameter. How can I use it on a function / code object that is defined in the same file? For instance:</p> <pre><code>def foo(bar): print(bar) import ast ast.pars...
<python>
2023-02-13 21:33:04
0
6,230
JRR
75,441,359
6,211,470
create Self Referencing Table using peewee
<p>I am failing to find a way I can create a self-referencing table using peewee. I am trying to create an entity similar to one on <a href="https://www.codeproject.com/Tips/5255964/How-to-Create-and-Use-a-Self-referencing-Hierarchi" rel="nofollow noreferrer">this article</a>.</p> <p><a href="https://i.sstatic.net/u542...
<python><postgresql><orm><peewee>
2023-02-13 21:29:34
1
358
tendaitakas
75,441,343
6,100,445
Python and Starlette: running a long async task
<p>I have a simple experiment in the code snippet shown below. My goal is to have the browser client (via a WebSocket) kick off a long-running task on the server, but the server should service WebSocket messages from the client while the long-running task is running. Here's the workflow (&quot;OK&quot; means this ste...
<python><python-3.x><python-asyncio><starlette>
2023-02-13 21:27:42
1
927
rob_7cc
75,441,334
14,790,056
How to addline to link stacked bar plot categories
<p>I have a stacked bar chart for two variables.</p> <pre><code>ax = count[['new_category', &quot;Count %&quot;, &quot;Volume%&quot;]].set_index('new_category').T.plot.bar(stacked=True) plt.xticks(rotation = 360) plt.show() </code></pre> <p>I want to connect the categories with lines, so my categories are connected wi...
<python><matplotlib>
2023-02-13 21:25:52
1
654
Olive
75,441,263
5,759,359
redis.exceptions.ConnectionError: Error UNKNOWN while writing to socket. Connection lost
<p>For my python <code>(python 3.10)</code> based project, we were using aioredis <code>(aioredis 2.0.1)</code> to connect to redis cache and all of a sudden all the requests accessing redis cache started failing. After analysis, we found that <a href="https://github.com/aio-libs/aioredis-py" rel="nofollow noreferrer">...
<python><redis><redis-py><aioredis>
2023-02-13 21:16:27
0
477
Kashyap
75,441,242
17,696,880
How to perform string separations using regex as a reference and that a part of the used separator pattern is not removed from the following string?
<pre class="lang-py prettyprint-override"><code>import re sentences_list = [&quot;El coche ((VERB) es) rojo, la bicicleta ((VERB)estΓ‘) allΓ­; el monopatΓ­n ((VERB)ha sido pintado) de color rojo, y el camiΓ³n tambiΓ©n ((VERB)funciona) con cargas pesadas&quot;, &quot;El Γ‘rbol ((VERB es)) grande, las hojas ((VERB)son) dorada...
<python><python-3.x><regex><list><regex-group>
2023-02-13 21:13:36
1
875
Matt095
75,441,104
7,331,538
Why is RSI calculation with python ta library changes depending on starting position?
<p>I have a <code>DataFrame</code> and I want to calculate the RSI on the <code>Close</code> column with a window of <code>14</code> like so:</p> <pre><code>from ta.momentum import RSIIndicator import pandas as pd data = pd.read_csv() output = RSIIndicator(data.Close, 14).rsi() print(output.head(20)) </code></pre> <p>...
<python><technical-indicator>
2023-02-13 20:56:21
1
2,377
bcsta
75,441,003
4,045,121
How to correctly pivot a dataframe so the values of the first column are my new columns?
<p>I have a file with some random census data, in essence multiple lines of the following:</p> <pre><code>age=senior workclass=Self-emp-not-inc education=Bachelors edu_num=13 marital=Divorced occupation=Craft-repair relationship=Not-in-family race=White sex=Male gain=high loss=none hours=half-time country=United-States...
<python><python-3.x><pandas>
2023-02-13 20:45:12
3
3,452
dearn44
75,440,987
7,762,646
How to increase Google Colab cell output width?
<p>I found a very similar <a href="https://stackoverflow.com/questions/21971449/how-do-i-increase-the-cell-width-of-the-jupyter-ipython-notebook-in-my-browser">question</a> but the solution did not work on Google colab. I would like to see better the text in my pandas dataframes columns. Right now the default width see...
<python><html><css><pandas><google-colaboratory>
2023-02-13 20:44:02
1
1,541
G. Macia
75,440,942
15,515,166
Convert ByteString into numpy array of 1s and 0s
<p>I am wanting to turn a bytestring, for example <code>b'\xed\x07b\x87S.\x866^\x84\x1e\x92\xbf\xc5\r\x8c'</code> into a numpy array of 1s and 0s (i.e. the binary value of this bytestring as an array of binary values).</p> <p>How would I go about doing this?</p> <p>I tried using <code>np.fromstring</code> and <code>np....
<python><numpy>
2023-02-13 20:39:12
2
1,153
Sam
75,440,935
4,688,190
Python Requests POST / Upload Image File
<p>How can I os.remove() this image after it has been uploaded? I believe that I need to close it somehow.</p> <pre><code>import requests, os imageFile = &quot;test.jpg&quot; myobj = {'key': 'key', 'submit':'yes'} up = {'fileToUpload':(imageFile, open(imageFile, 'rb'), 'multipart/form-data')} r = requests.post('https...
<python><post><python-requests>
2023-02-13 20:37:58
2
678
Ned Hulton
75,440,932
12,297,666
Convert a digit code into datetime format in a Pandas Dataframe
<p>I have a pandas dataframe that has a column with a 5 digit code that represent a day and time, and it works like following:</p> <p><strong>1</strong> - The first three digits represent the day;</p> <p><strong>2</strong> - The last two digits represent the hour:minute:second.</p> <p><strong>Example1:</strong> The fir...
<python><pandas><datetime>
2023-02-13 20:37:55
2
679
Murilo
75,440,925
13,571,357
Python multiprocessing: sharing global real-only large data without reloading from disk for child processes
<p>Say I need to read from disk a large data and do some <strong>read-only</strong> work on it.</p> <p>I need to use multiprocessing, but to share it across processes using <code>multiprocessing.Manager()</code> or <code>Array()</code> is way too slow. Since my operation on this large data is read-only, according to <a...
<python><memory><parallel-processing><multiprocessing><python-multiprocessing>
2023-02-13 20:36:42
1
731
graphitump
75,440,860
6,099,211
Compare result of "in statement" with bool in Python, why 1 in [1] == True results with False?
<pre class="lang-py prettyprint-override"><code>print(1 in [1] == True) # False Why?????????????????? print((1 in [1]) == True) # True OK print(1 in ([1] == True)) # TypeError: argument of type 'bool' is not iterable OK </code></pre> <p>So just what is happening here? How Python interprets this statement?</p>
<python>
2023-02-13 20:28:07
0
1,200
Anton Ovsyannikov
75,440,753
4,856,302
Popular Python type checkers give a false negative with Any annotation
<p>I tested the following snippet with 4 common type checkers for Python and, to my surprise, none of them complained:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any def length(s: str) -&gt; int: return len(s) def any_length(o: Any) -&gt; int: return length(o) if __name__ == &quot...
<python><types><static-analysis>
2023-02-13 20:14:14
1
1,020
shooqie
75,440,456
2,088,886
Flask IIS Webapp Attempting to Get User IP Address
<p>I am attempting to deploy a Flask webapp onto IIS. First, I used standard suggestions (Flask, IIS, wfastcgi). This method allowed me to correctly see the IPs of users using <code>ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)</code></p> <p>For various reasons detailed here: <a href="https://stackove...
<python><request><waitress><httpplatformhandler>
2023-02-13 19:35:12
1
2,161
David Yang
75,440,379
9,795,817
Unable to pip install old version of scikit-learn
<p>I need to use <code>scikit-learn==0.23.1</code> (or older) to make my project compatible with an AWS Lambda layer.</p> <p>As suggested by <a href="https://stackoverflow.com/questions/62248752/how-do-i-install-previous-version-of-scikit">this post</a>, I tried <code>pip3 install scikit-learn==0.23.1</code>, but it di...
<python><scikit-learn><pip>
2023-02-13 19:22:48
1
6,421
Arturo Sbr
75,440,354
54,873
Why does pandas read_excel fail on an openpyxl error saying 'ReadOnlyWorksheet' object has no attribute 'defined_names'?
<p>This bug suddenly came up literally today after read_excel previously was working fine. Fails no matter which version of python3 I use - either 10 or 11.</p> <p>Do folks know the fix?</p> <pre><code> File &quot;/Users/aizenman/My Drive/code/daily_new_clients/code/run_daily_housekeeping.py&quot;, line 38, in &lt;mo...
<python><pandas><openpyxl>
2023-02-13 19:20:26
4
10,076
YGA
75,440,187
19,369,310
Create a new column in Pandas based on count of other columns and a fixed specific value
<p>This is a continuation of my another related question: <a href="https://stackoverflow.com/questions/75439107/create-a-new-column-based-on-count-of-other-columns">Create a new column based on count of other columns</a></p> <p>I have a dataframe that looks like</p> <pre><code>col_1 col_2 col_3 6 A 1 2 ...
<python><python-3.x><pandas><dataframe>
2023-02-13 19:02:55
1
449
Apook
75,440,166
11,922,765
Raspberry Pi No module named Plotly
<p>I have installed <code>plotly</code> on the <code>Raspberry Pi</code>. The objective is connecting to a remote MySql database and plot interactive time-series plots (that would update as the new data arrives into the MySql database). But I am running into <code>no module found</code> even after installing it. Looks ...
<python><raspberry-pi><plotly><raspberry-pi4>
2023-02-13 18:59:33
2
4,702
Mainland
75,439,970
5,212,614
In Jupyter Notebook -- No module named 'pandas'
<p>I'm working in a Windows 10 Enterprise environment. I have been using Jupiter Notebooks successfully for several months, and all of a sudden this morning I'm getting the following error message:</p> <pre><code>ModuleNotFoundError: No module named 'pandas' </code></pre> <p>So, I go to my Anaconda cmd prompt and type:...
<python><python-3.x><jupyter>
2023-02-13 18:37:19
0
20,492
ASH
75,439,401
21,192,065
Child Class from MagicMock object has weird spec='str' and can't use or mock methods of the class
<p>When a class is created deriving from a MagicMock() object it has an unwanted spec='str'. Does anyone know why this happens? Does anyone know any operations that could be done to the MagicMock() object in this case such that it doesn't have the spec='str' or can use methods of the class?</p> <pre><code>from unittest...
<python><python-3.x><python-unittest><python-unittest.mock><magicmock>
2023-02-13 17:39:28
1
978
arrmansa
75,439,361
10,620,003
Move the ytick vertically in plot python
<p>I have a histogram plot and I want to move the yticks vertically (0.2 cm lower than their positions of the existing yticks). I searched a lot and I could not find anything which exactly did this. Could you please help me with that? I attached an image here that shows the new location of the y ticks. <a href="https:/...
<python><matplotlib><seaborn>
2023-02-13 17:36:25
2
730
Sadcow
75,439,221
4,157,512
DjangoRestFramwork how to override ModelViewSet get method
<p>I have a model like this :</p> <pre class="lang-py prettyprint-override"><code>class AccountViewSet(viewsets.ModelViewSet): &quot;&quot;&quot; A simple ViewSet for viewing and editing accounts. &quot;&quot;&quot; queryset = Account.objects.all() serializer_class = AccountSerializer permission...
<python><django><django-rest-framework><get>
2023-02-13 17:22:52
3
3,835
BoumTAC
75,439,152
18,020,941
Django Admin select_related issue
<p>I'm trying to <code>select_related</code> for a bunch of assets in the Django admin. These assets are tied to a product, which in turn has a separate Company and Category model. These are both a foreign key from product, to the respective model. I defined the string method like so in the Product class:</p> <pre><cod...
<python><django><django-models><django-views><django-queryset>
2023-02-13 17:16:47
1
1,925
nigel239
75,439,107
19,369,310
Create a new column based on count of other columns
<p>I have a dataframe in pandas that looks like</p> <pre><code>col_1 col_2 6 A 2 A 5 B 3 C 5 C 3 B 6 A 6 A 2 B 2 C 5 A 5 B </code></pre> <p>and i want to add a new colum...
<python><python-3.x><pandas><dataframe>
2023-02-13 17:13:33
2
449
Apook
75,439,020
1,483,263
pip install --pre without installing pre-releases for dependencies
<p>Say I have a package <code>A</code> on pypi with a pre-release version <code>1.0.0rc1</code>.</p> <p>Package <code>A</code> has package <code>B</code> as a dependency with version <code>B &gt;= 1.0.0</code>, but <code>B</code> also has a pre-release version <code>1.0.0rc1</code> that is incompatible with <code>A</co...
<python><pip><release>
2023-02-13 17:03:29
1
534
twhughes
75,438,927
1,945,875
Tensorflow GO - how to port python querie
<p>pretty new to the whole world of tf and co.</p> <p>managed to create/train/predict a model - in jupyter-playbook using python.</p> <p>for production, i'd like to use golang. but i am unable to find a &quot;simple&quot; sample on how to do the prediction inside go.</p> <p>i'd like to have this piece of python, for go...
<python><tensorflow><go>
2023-02-13 16:54:06
1
1,634
Helmut Januschka
75,438,855
6,930,340
How to tell mypy that I am explicitly testing for an incorrect type?
<p>Consider the following toy example:</p> <pre><code>import pytest def add(a: float) -&gt; float: if not isinstance(a, float): raise ValueError(&quot;a must be of type float&quot;) return 10 + a def test_add_wrong_type() -&gt; None: with pytest.raises(ValueError) as err: add(&quot;foo&q...
<python><pytest><mypy>
2023-02-13 16:47:57
2
5,167
Andi
75,438,839
11,501,370
Combine rows in pyspark dataframe to fill in empty columns
<p>I have the following pyspark dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Car</th> <th>Time</th> <th>Val1</th> <th>Val2</th> <th>Val 3</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>None</td> <td>1.5</td> <td>None</td> </tr> <tr> <td>1</td> <td>1</td> <td>3.5</td...
<python><pyspark>
2023-02-13 16:46:45
1
369
DataScience99
75,438,549
5,896,319
How to merge multiple csv files?
<p>I have several csv files that has same first row element in it. For example:</p> <pre><code>csv-1.csv: Value,0 Currency,0 datetime,0 Receiver,0 Beneficiary,0 Flag,0 idx,0 csv-2.csv: Value,0 Currency,1 datetime,0 Receiver,0 Beneficiary,0 Flag,0 idx,0 </code></pre> <p>And with these files (more than 2 files by the wa...
<python><pandas><csv>
2023-02-13 16:20:20
3
680
edche
75,438,527
3,116,231
Webhook verification fails with Shopify triggering an Azure function
<p>I'm trying to create a webhook consumer:</p> <ul> <li>Shopify is posting the data</li> <li>an Azure function written in Python is triggered by HTTP</li> <li>the sample code below just logged the result of the webhook verificationthe result of the verification is being logged</li> </ul> <p>There's an <a href="https:/...
<python><azure-functions><webhooks><hmac><shopify-api>
2023-02-13 16:18:35
1
1,704
Zin Yosrim
75,438,514
978,511
Split number into chunks according to rank
<p>This is a very practical task. I have a number of items that need to be distributed into several stores, according to store rank. So the higher the rank, the more items store will get, so store with rank 1 will get most items and store with rank 100 least.</p> <p>So the inputs are:</p> <ul> <li>number of items to di...
<python><math>
2023-02-13 16:17:47
1
13,523
Andrey Marchuk
75,438,456
15,481,917
Keras: color_mode = 'grayscale' does not convert to grayscale
<p>I am trying to read a dataset from directory <code>data</code> and I want the photos to be grayscaled.</p> <pre><code>data = tf.keras.utils.image_dataset_from_directory('data', shuffle=True, color_mode='grayscale') </code></pre> <p>When I print the results, the images are not grayscaled: <a href="https://i.sstatic....
<python><tensorflow><keras>
2023-02-13 16:12:45
1
584
Orl13
75,438,450
12,968,928
Skip to the next iteration if a warning is raised
<p>How can I skip the iteration if warning is raised</p> <p>Suppose I have the code below</p> <pre><code>import warnings # The function that might raise a warning def my_func(x): if x % 2 != 0: warnings.warn(&quot;This is a warning&quot;) return &quot;Problem&quot; else: return &qu...
<python>
2023-02-13 16:12:16
2
1,511
Macosso
75,438,358
8,553,795
Which metrics are printed (train or validation) when validation_split and validation_data is not specified in the keras model.fit function?
<p>I have a TF neural network and I am using the <code>tf.data</code> API to create the dataset using a generator. I am not passing <code>validation_split</code> and <code>validation_data</code> into the <code>model.fit()</code> function of keras.</p> <p>The default values for the above parameter are <code>0.0</code> a...
<python><tensorflow><keras><tensorflow2.0><tensorflow-datasets>
2023-02-13 16:03:55
1
393
learnToCode
75,438,284
11,002,498
Why is the parallel version of my code slower than the serial one?
<p>I am trying to run a model multiple times. As a result it is time consuming. As a solution I try to make it parallel. However, it ends up to be slower. <strong>Parallel is 40 seconds</strong> while <strong>serial is 34 seconds</strong>.</p> <pre><code># !pip install --target=$nb_path transformers oracle = pipeline(m...
<python><multiprocessing><google-colaboratory><python-multiprocessing><huggingface-transformers>
2023-02-13 15:57:00
1
464
Skapis9999
75,438,217
10,266,106
NumPy Nearest Neighbor Line Fitting Across Moving Window
<p>I have two two-dimensional arrays loaded into NumPy, both of which are 80i x 80j in size. I'm looking to do a moving window polyfit calculation across these arrays, I've nailed down how to conduct the polyfit but am stuck on the specific moving window approach I'm looking to accomplish. I'm aiming for:</p> <p><stron...
<python><arrays><numpy><slice><numpy-ndarray>
2023-02-13 15:51:44
1
431
TornadoEric
75,438,152
2,623,317
How to convert time durations to numeric in polars?
<p>Is there any built-in function in <code>polars</code> or a better way to convert time durations to numeric by defining the time resolution (e.g.: days, hours, minutes)?</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;from&quot;: [&quot;2023-01-01&quot;, &quot;20...
<python><dataframe><datetime><python-polars><duration>
2023-02-13 15:46:43
2
477
Guz
75,438,149
3,922,727
Azure http trigger functions throwing an error over imported modules from other folder
<p>We are building an http trigger using Azure functions.</p> <pre><code>import logging import azure.functions as func def main(req: func.HttpRequest) -&gt; func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: ...
<python><azure><azure-functions><azure-web-app-service><azure-http-trigger>
2023-02-13 15:46:33
1
5,012
alim1990
75,438,124
203,175
How to print several strings side-by-side and span multiple lines at a fixed output width
<p>I am trying to print out three long strings (same-length), character-by-character, and with a fixed output width at 60, which may be rendered like:</p> <pre><code>aaaaaaaaaaaaa bbbbbbbbbbbbb ccccccccccccc ---blank line--- aaaaaaaaaaaaa bbbbbbbbbbbbb ccccccccccccc ..... </code></pre> <p>I simplify the strings so tha...
<python><python-3.x>
2023-02-13 15:43:33
2
6,851
Kevin
75,438,026
802,589
How to show play button in every code cell for jupyter lab
<p>In vscode and colab, there's a play button in every code cell in the notebook. <a href="https://stackoverflow.com/questions/54607200/remove-play-button-display-at-every-cell-line-of-jupyter-notebook">This issue</a> seems to suggest there should be the play button in <code>notebook</code> 5.6.0, but I'm on 5.6.1 (and...
<python><jupyter-notebook><jupyter-lab>
2023-02-13 15:35:24
1
1,629
liang
75,437,933
10,613,037
When writing to excel, add padding on the top of dataframe with meta info
<p>I've got a dataframe e.g <code>df = pd.DataFrame({'col1': [1,2]})</code></p> <pre><code> col1 0 1 1 2 </code></pre> <p>I want it when I do <code>df.to_excel('abc.xlsx')</code>, I get an output with a bit of padding on top of the entire dataframe, where I write some meta information in that space, i.e</p> <p><...
<python><excel><pandas><dataframe>
2023-02-13 15:28:26
0
320
meg hidey
75,437,921
11,391,711
Computing statistical results for the test dataset in PyTorch - Python
<p>I'm creating a vanilla neural network with artificial datasets to learn <code>pytorch</code>. I'm currently looking how I can get the predictions for the test data set and obtain the statistical metrics including <code>mse</code>, <code>mae</code>, and <code>r2</code>. I was wondering if my calculations are correct....
<python><machine-learning><pytorch><static-analysis>
2023-02-13 15:27:43
0
488
whitepanda
75,437,910
2,487,835
Pydroid PIL does not display image on android
<p>I am writing code on my Android. I know, it's weird. But my notebook is being repaired :)</p> <p>I am trying to display an image generated by pillow library. I'm doing this within Pydroid app.</p> <p>Matplotlib charts are displaying okay. But not the image of pillow.</p> <p>There is a question similar to mine, that ...
<python><android><python-imaging-library><pydroid>
2023-02-13 15:26:35
1
3,020
Lex Podgorny
75,437,890
19,580,067
Send a email in Outlook for automation
<p>Tried to send an outlook email as a part of automation. But the usual code seems not working. Not sure what I'm missing here.</p> <p>The code I tried is here</p> <pre><code>import win32com.client ol=win32com.client.Dispatch(&quot;outlook.application&quot;) olmailitem=0x0 #size of the new email newmail=ol.CreateItem(...
<python><outlook><pywin32><win32com><office-automation>
2023-02-13 15:25:19
2
359
Pravin
75,437,773
1,876,739
Pandas MultiIndex Lookup By Equality and Set Membership
<p>Given a pandas <code>Series</code>, or <code>Dataframe</code>, with a multiindex:</p> <pre><code>first_key = ['a', 'b', 'c'] second_key = [1, 2, 3] m_index = pd.MultiIndex.from_product([first_key, second_key], names=['first_key', 'second_key']) series_with_index = pd.Series(0.0...
<python><pandas>
2023-02-13 15:16:07
4
17,975
RamΓ³n J Romero y Vigil
75,437,730
3,507,584
Python - Categorise a single value yields error "Input array must be 1 dimensional"
<p>I am trying to categorise single float numbers avoiding a list of <code>if</code> and <code>elif</code> statements using <code>pd.cut</code>.</p> <p>Why the 2 codes below yield error <code>Input array must be 1 dimensional</code>?</p> <pre><code>import pandas as pd import numpy as np pd.cut(0.96,bins=[0,0.5,1,10],la...
<python><arrays><pandas>
2023-02-13 15:12:09
1
3,689
User981636
75,437,697
10,613,037
When writing to excel, make columns not at top level
<p>I've got a dataframe e.g <code>df = pd.DataFrame({'col1': [1,2]})</code></p> <pre><code> col1 0 1 1 2 </code></pre> <p>I want it when I do <code>df.to_excel('abc.xlsx')</code>, I get an output with a bit of padding on top e.g.</p> <p><a href="https://i.sstatic.net/3AIvw.png" rel="nofollow noreferrer"><img src...
<python><excel><pandas><dataframe>
2023-02-13 15:08:46
0
320
meg hidey
75,437,666
9,758,017
Remove duplicate of a list via list matching in Python
<p>I have chosen a slightly different procedure to remove duplicates of a list. I want to keep a new list in parallel, in which each duplicate is added. Afterwards I check if the element is present in the &quot;newly created list&quot; in order to delete it.</p> <p>The code looks like this:</p> <pre><code># nums = [1,1...
<python>
2023-02-13 15:06:20
1
1,778
41 72 6c
75,437,636
13,382,780
Filter for specific tags on Zendesk API using Zenpy on python
<p>Need some help, while trying to retrieve some tickets with Zenpy, I encounter that when I search for more than one tag, they fetch all the data related to both tags, is there a way to filter only for the tickets who have both tags?</p> <p>An example of my script is:</p> <p><code>zenpy_client.search(tags = [&quot;tag...
<python><python-3.x><zendesk><zendesk-api>
2023-02-13 15:04:26
1
312
Tayzer Damasceno
75,437,326
3,719,167
python fnmatch exclude path with string
<p>I want to perform check and allow access to only specific pattern URLs and exclude few.</p> <p>Using the following check to match for the allowed URLs</p> <pre class="lang-py prettyprint-override"><code>ALLOWED_URL = [ '/auth/*' ] </code></pre> <p>and using <code>fnmatch</code> to match the pattern</p> <pre><code>...
<python><fnmatch>
2023-02-13 14:39:32
1
9,922
Anuj TBE
75,437,202
9,401,029
Python path remains unchanged even after config update and restart
<p>I am using a <code>mac</code> and my end goal is for <code>which python</code> to return</p> <pre><code>/usr/bin/python2.7 </code></pre> <p>The above path exists and it is an executable that works fine.</p> <p>At present <code>which python</code> incorrectly returns</p> <pre><code>/Library/Frameworks/Python.framewor...
<python><zsh>
2023-02-13 14:29:39
1
1,836
karvai
75,437,159
6,372,859
Reshape pandas columns into numpy arrays
<p>I have a very long dataframe with many columns of the form <code>k1, p1, k2, p2,...,kn, pn</code> such as</p> <pre><code> k1 p1 k2 p2 k3 p3 ... -0.001870 0.000659 -0.005000 0.000795 -0.003889 0.000795 ... -0.002778 0.000556 0.000795 ...
<python><arrays><pandas><numpy><reshape>
2023-02-13 14:26:11
2
583
Ernesto Lopez Fune
75,437,105
19,238,204
How to Convert Automatically Currency to USD and Label the Legend with the Index Name with Python, pandas, yfinance
<p>I want to label the legend of the index stocks with its name like &quot;Euronext 100 Index&quot; instead of &quot;^N100&quot; because it is easier to be read that way for me. How to modify the label on the legend for each chart?</p> <p>Second, I want to convert the price if it is in GBP it will be converted to USD, ...
<python><pandas><yfinance>
2023-02-13 14:21:21
1
435
Freya the Goddess
75,437,030
14,125,436
How to implement self daptive weight in neural network in Pytorch
<p>I want to develop a Physics Informed Neural Network model in Pytorch. My network should be trained based on two losses: boundary condition (BC) and partial derivative equation (PDE). I am adding these two losses but the problem is that the BC is controlling the main loss, like the following figure:</p> <p><a href="h...
<python><machine-learning><deep-learning><pytorch><neural-network>
2023-02-13 14:14:52
1
1,081
Link_tester
75,436,689
7,882,899
How to make python multiple conditions into a single statement
<p>How to make the method below be returned in a single line?</p> <p>Prefer to the #Note ## remarks below.</p> <pre><code>def falsify(leftover): #Note ## Your code here (replace with a single line) ### def falsify(leftover): false = [] for num in leftover: if 30 &gt; num &gt; 20: ...
<python><python-3.x><list><conditional-statements>
2023-02-13 13:44:11
2
337
Banana Tech
75,436,462
19,238,204
How to Add Legend for Specific Stock Chart using matplotlib?
<p>I have this code to plot 3 game corporation stocks. But I want to give legend thus I can know which chart is for EA or for Take Two or for Activision.</p> <pre><code>from pandas_datareader import data as pdr import yfinance as yf import matplotlib.pyplot as plt yf.pdr_override() y_symbols = ['EA', 'TTWO', 'ATVI'] ...
<python><matplotlib>
2023-02-13 13:24:16
1
435
Freya the Goddess
75,436,252
5,641,924
Fast solution to get NaN and ignore None in numpy array
<p>I have an array like this:</p> <pre><code>array = np.random.randint(1, 100, 10000).astype(object) array[[1, 2, 6, 83, 102, 545]] = np.nan array[[3, 8, 70]] = None </code></pre> <p>Now, I want to find the indices of the <code>NaN</code> items and ignore the <code>None</code> ones. In this example, I want to get the <...
<python><numpy>
2023-02-13 13:03:58
1
642
Mohammadreza Riahi
75,436,228
10,049,514
Efficiently setting and deleting array items with Redis JSON
<p>I'm using Redis OM for Python and my models look like below:</p> <pre class="lang-py prettyprint-override"><code>from typing import List from pydantic import BaseModel from redis_om import EmbeddedJsonModel, Field, JsonModel, Migrator class FeedItem(EmbeddedJsonModel): id: str = Field(index=True) s_score:...
<python><redis><py-redis>
2023-02-13 13:01:29
0
1,071
knl
75,436,220
14,403,266
Sum the rows of a pandas dataframe grouping by the last n dates
<p>I have a pandas dataframe looking like this:</p> <pre><code>Ac |Type |Id |Date |Value |Pe | --------------------------------------------------- Debt |Other |DE |2017-12-31 |5 |12M | Debt |Other |DE |2018-03-31 |4 |12M | Debt |Other |DE |2018-06-30 |3 |12M...
<python><pandas><datetime>
2023-02-13 13:00:34
1
337
Valeria Arango
75,436,154
10,437,727
VSCode Python debugger throwing ImportError ModuleNotFound
<p>I'm running tests for my project which contains several modules:</p> <pre><code>β”œβ”€β”€ compute_metrics_service β”‚ β”œβ”€β”€ tests β”‚ β”‚ β”œβ”€β”€ integration β”‚ β”œβ”€β”€ test_app.py β”‚ └── __init__.py β”‚ β”‚ └── unit β”‚ └── utils β”œβ”€β”€ data_quality β”‚ β”œβ”€β”€ helpers β”‚ └── tests β”‚ β”œβ”€β”€ integration β”‚ └── u...
<python><visual-studio-code><vscode-debugger>
2023-02-13 12:53:34
0
1,760
Fares
75,436,081
5,257,286
Strings searches in a list, if the list contains a string with a space
<p>I'd like to identify a word in a list, however one of the strings has a space in-between and is not recognized. My code:</p> <pre><code>res = [word for word in somestring if word not in myList] myList = [&quot;first&quot;, &quot;second&quot;, &quot;the third&quot;] </code></pre> <p>So when</p> <pre><code>somestring...
<python><python-3.x><string><list>
2023-02-13 12:46:56
2
1,192
pymat
75,435,961
15,485
Matplotlib imshow and secondary x and y axis
<p>Let's say I have a picture taken with a sensor where the pixel size is 1mm. I would like to show the image with <code>imshow</code>: the main axes should show the pixel while the secondary axes should show the mm.</p> <p><code>frassino.png</code> is the following picture</p> <p><a href="https://i.sstatic.net/eURq0.p...
<python><matplotlib><imshow>
2023-02-13 12:36:29
1
18,835
Alessandro Jacopson
75,435,956
1,436,800
An exception is being raised when testing websocket with POSTMAN
<p>I am implementing web sockets in my Django Project with channels library. When an object is created, name of that object should be sent to a consumer with group name test_consumer_group_1.</p> <pre><code>class MyClass(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyTo...
<python><django><django-rest-framework><websocket><django-channels>
2023-02-13 12:35:45
1
315
Waleed Farrukh
75,435,780
478,213
Dynamic number of lamda and apply statements in Pandas
<p>I am trying to create a nested JSON block and came accross this awesome solution <a href="https://stackoverflow.com/questions/61781186/pandas-grouping-by-multiple-columns-to-get-a-multi-nested-json">Pandas grouping by multiple columns to get a multi nested Json</a>:</p> <pre><code>test = [df.groupby('cat_a')\ ...
<python><pandas>
2023-02-13 12:18:39
2
1,424
NickP
75,435,594
11,167,163
tag_configure does not apply background as excepted to tagged row
<p>It seems that I have an issue with <code>tag_configure</code> : nor size &amp; color are taken into account :</p> <pre><code>import tkinter as tk from tkinter import ttk import pandas as pd class ScrollTree(ttk.Treeview): def __init__(self, master,ROW, *args, **kwargs): ttk.Treeview.__init__(self, maste...
<python><tkinter>
2023-02-13 11:59:10
0
4,464
TourEiffel
75,435,585
756,233
Using Python 3.9.1 and requests 2.25.1 a local connection to a Mongoose HTTP server takes 2 seconds
<p>I am writing a little REST API client using Python, Java and NodeJS. The server is written using the Mongoose HTTP server.</p> <p>With Java and NodeJS every request takes only milliseconds but with Python every request takes 2 seonds.</p> <p>I confirmed that this is not a requests problem by using urllib directly. T...
<python><python-requests><mongoose-web-server>
2023-02-13 11:58:24
1
11,321
Ray Hulha
75,435,484
248,959
Trying to install GDAL on Ubuntu 20: error in GDAL setup command: use_2to3 is invalid
<p>I'm trying to install GDAL using this command:</p> <p><code>pip install GDAL==3.0.4</code></p> <p>but I'm getting this below:</p> <p><a href="https://i.sstatic.net/NcJG0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NcJG0.png" alt="enter image description here" /></a></p> <p>I'm using <code>pip inst...
<python><pip><gdal>
2023-02-13 11:49:11
1
31,891
tirenweb
75,435,464
18,215,498
How to POST image using Python requests to FastAPI backend?
<p>I have my own simple API build with FastAPI. It's very simple -&gt; <code>/predict</code> endpoint expects image, and it returns some predictions from neural network. I connected it with JS front and it works very well.</p> <p>Backend snippet:</p> <pre class="lang-py prettyprint-override"><code>@app.post(&quot;/pred...
<python><http><python-requests><fastapi>
2023-02-13 11:47:29
0
533
mcdominik
75,435,423
6,930,340
Create a pd.DataFrame with a minimum number of rows using hypothesis
<p>I'm using the <code>hypothesis</code> library and I would like to create a <code>pd.DataFrame</code> with three columns. Each column may contain integer values, either +1, 0, or -1. The values doesn't need to be unique. Also, I would like to get at least ten rows.</p> <p>With the following code, <code>hypothesis</co...
<python><python-hypothesis>
2023-02-13 11:43:17
1
5,167
Andi