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,941,725
10,176,057
How to find transparent background location in image?
<p>I have a HTML code where I will place text in the transparent background area of an image. Since I don't know how to get the exact coordinate on the fly using JS or HTML, the only solution I was able to start was using the <code>pyautogui</code> Python library. But I was also not being able to find the correct trans...
<javascript><python><html><image><pyautogui>
2023-04-05 16:07:09
1
649
Guilherme Matheus
75,941,716
10,957,844
Selenium Proxy Error when intializing webdriver
<p>When using selenium for work behind enterprise firewall, it's necessary to connect to proxy to access internet. However, selenium is returning proxy error even when initializing the webdriver.</p> <pre><code>from selenium import webdriver proxy='x.x.x.x:xxx' chrome_options = webdriver.ChromeOptions() chrome_options...
<python><selenium-webdriver>
2023-04-05 16:06:16
1
3,457
Tim
75,941,644
7,626,198
How to read QVector with QDataStream using PyQt5
<p>I have a QtDataStream:</p> <pre><code>from PyQt5 import QtCore infile = QtCore.QFile(path) if not infile.open(QtCore.QIODevice.ReadOnly): raise IOError(infile.errorString() stream = QtCore.QDataStream(infile) </code></pre> <p>And I need to read a QVector. I need something like this:</p> <pre><code>var = QtCore.Q...
<python><pyqt><pyqt5><qvector><qdatastream>
2023-04-05 15:59:47
1
442
Juan
75,941,480
2,607,331
Writing large objects in MongoDB's GridFS & extracting it in Python
<p>Context - On daily basis application log files are generated for external REST calls. I am trying to parse the log files and extract information related to external REST call. The information extracted are StartTime of Rest Call, EndTime when response was received, payloads etc. This information is collected and col...
<python><java><json><mongodb><gridfs>
2023-04-05 15:43:44
0
687
Tushar Saurabh
75,941,470
17,902,018
Count overlapping filaments in image
<p>I am trying to count filaments in binary images. They are segmentation masks for cell <a href="https://en.wikipedia.org/wiki/Filopodia" rel="nofollow noreferrer">filopodia</a>, and they are often overlapping. This overlapping makes it difficult to accurately count them.</p> <p>I am trying with this code that works w...
<python><numpy><image-processing><computer-vision><scikit-image>
2023-04-05 15:42:16
1
2,128
rikyeah
75,941,464
21,420,742
How to locate and add text to rows that don't fit the conditions. In python
<p>I have a dataset that uses numpy and pandas with employment history and in my code I look for those employees that report to a vacant manager spot being held by another manager in the mean time. Right now it kind of works but needs to be refined. Here is the current data and code that I have.</p> <p>Code:</p> <pre>...
<python><python-3.x><pandas><dataframe><numpy>
2023-04-05 15:41:38
1
473
Coding_Nubie
75,941,259
1,682,525
Append all logs to text file and send it to slack via AWS lambda python script
<p>I have a python script that collect the data from aws cloudwatch and send it to slack. Its working completely fine. Its sending logs to slack in the form of text in slack channel.</p> <p>I would want the same logs data to be stored in a text file and send it to slack. I am not into python so, please excuse my code.<...
<python><amazon-web-services><aws-lambda><amazon-cloudwatch>
2023-04-05 15:23:14
1
3,887
Santosh
75,941,255
6,706,419
Selenium - Get Text Attribute of Element
<p>I am trying to scrape a table and store in list/dict with intent to add this data to a Pandas Dataframe. I am having issues getting the desired output in my dictionary though.</p> <pre><code># import currencies from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support...
<python><html><selenium-webdriver>
2023-04-05 15:23:06
1
14,588
urdearboy
75,941,202
4,865,723
RegEx: Disallow strings in a sub catchgroup
<p>I still have a working regex pattern. Now I found a new case that isn't catched My first solution does interfere with the previous cases.</p> <p>I want to extract three parts of a string. I'm using Python3 for this and also tested arround on regex101.com.</p> <p>Here is an example input string:</p> <pre><code>foo:ba...
<python><regex>
2023-04-05 15:16:41
3
12,450
buhtz
75,941,135
5,212,614
Trying to Minimize Wages/Workers Problem Using SciPy Optimize
<p>I just recently learned about PuLP and now I am trying to learn about SciPy Optimize. If I have a simple dataframe, like the one below, how can I optimize/minimize wages, workers, or both?</p> <pre><code>import pandas as pd import numpy as np import scipy.optimize as sco from io import StringIO with StringIO( '''...
<python><python-3.x><optimization><scipy-optimize><scipy-optimize-minimize>
2023-04-05 15:11:29
0
20,492
ASH
75,941,121
848,277
Replicating pandas to_dict in polars
<p>In pandas I can do the following to get a key/value dictionary from <code>to_dict</code></p> <pre><code>d = [{'key':'a', 'value':1}, {'key':'b', 'value':2}, {'key':'b', 'value':1}] df = pd.DataFrame(d) df.groupby('key')['value'].sum().to_dict() Out[13]: {'a': 1, 'b': 3} </code></pre> <p>When I attempt to replicate t...
<python><pandas><dataframe><python-polars>
2023-04-05 15:10:08
1
12,450
pyCthon
75,940,723
1,631,306
create masking using image boundaries
<p>I have a image where I have defined some boundaries. I am trying to mask these different boundaries.</p> <p><a href="https://i.sstatic.net/EGc7B.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EGc7B.png" alt="enter image description here" /></a></p> <p>So, I want to create mask for green circle (eye) ...
<python><opencv>
2023-04-05 14:32:09
2
4,501
user1631306
75,940,698
4,877,683
Unable to change default download directory for google chrome while downloading using Selenium - python
<p>I'm trying to download a file from a URL using Selenium in Python. I'm trying to change the default download directory using <em>Options</em></p> <p>The script runs without any error message, but the download directory doesn't get updated. I'm using a jupyter notebook on Windows. This is what my code looks like:</p>...
<python><css><selenium-webdriver><web-scraping>
2023-04-05 14:30:18
2
703
Danish Zahid Malik
75,940,697
2,893,053
Importing uninstalled Python package inside bash script doesn't fail but its __file__ is None
<p>I am facing a weird situation I've never encountered before.</p> <p>I have a bash script that contains the following line:</p> <pre><code>python -c &quot;import foo; print(foo.__file__); import pdb; pdb.set_trace() </code></pre> <p>When I directly run this bash script, I am getting None for <code>foo.__file__</code>...
<python><bash>
2023-04-05 14:30:01
0
1,528
zkytony
75,940,559
6,357,916
Logging everything to file and only DEBUG messages to console in python
<p>I want logger to log everything to file but only debug messages to console. <a href="https://stackoverflow.com/a/17109663/6357916">This answer</a> suggests creating custom handler. I tried following:</p> <pre><code>import logging import sys class DebugConsoleHandler(logging.StreamHandler): def __init__(self): ...
<python><python-logging>
2023-04-05 14:17:19
1
3,029
MsA
75,940,472
353,337
Preserve custom dtype when creating NumPy array
<p>For compatibility with legacy software, I need to create a NumPy array with dtype</p> <pre class="lang-py prettyprint-override"><code>np.dtype(&quot;(2,)u8&quot;) </code></pre> <p>(i.e., an array of tuples of two <code>u8</code> integers each). When creating such an array, NumPy automatically converts the array to ...
<python><numpy><dtype>
2023-04-05 14:10:11
0
59,565
Nico Schlömer
75,940,278
13,300,255
How to access various Plotter methods outside my class?
<p>I'm plotting a mesh with PyVista using <a href="https://docs.pyvista.org/api/core/_autosummary/pyvista.UnstructuredGrid.html#pyvista-unstructuredgrid" rel="nofollow noreferrer"><code>UnstructuredGrid</code></a>. It's going pretty well and I managed to plot the geometry I want using <code>grid.plot()</code>.</p> <p>I...
<python><pyvista>
2023-04-05 13:50:24
1
439
man-teiv
75,940,265
21,351,146
How do I create a multithreaded async server application with Python
<p>for clarity i am using python3.10.9</p> <p>The program i am trying to make consists of a ThreadPool and some type of async runtime environment. If a connection comes in on a listening socket, the async environment should be able to handle multiple connections concurrently. Database writing and other proccessing work...
<python><python-3.x><multithreading><asynchronous><python-asyncio>
2023-04-05 13:49:29
1
301
userh897
75,940,177
5,574,107
Merge dataframes where df1['row']<=df2['row']
<p>I have two tables:</p> <pre><code>d = {'ID': ['A', 'B', 'C'], 'Month': [1,3,5],'group':['x','x','x'} df1 = pd.DataFrame(data=d) d2 = {'Month': [1, 2,3,4,5], 'value': [0.8, 0.2,0.5,0.3,0.7],'group':['x','x','x']} df2 = pd.DataFrame(data=d2) </code></pre> <p>I would like to join on group, which in my real table is no...
<python><pandas><dataframe>
2023-04-05 13:41:34
1
453
user13948
75,940,073
19,980,284
Calculate the percent occurrence of values from summed rows and plot as bars
<p>I have survey data based on 6 questions, where each column corresponds to one question (case), and each row corresponds to one survey respondent who answered all 6 questions. <code>1.0</code> means the respondent would give fluid, and <code>0.0</code> means they would not give fluid:</p> <pre><code> case_1 case_...
<python><pandas><matplotlib><bar-chart>
2023-04-05 13:31:53
1
671
hulio_entredas
75,940,020
8,573,615
What is best practice for sharing config files across multiple functions in an AWS API Gateway?
<p>I am deploying an API Gateway to AWS that has multiple endpoints, grouped into multiple groups. In the interests of speed, readability and reusability, I've deployed this as a set of different lambda functions, one per group. In the interests of portability I've defined it all in one cloudformation template.</p> <...
<python><aws-lambda><aws-api-gateway>
2023-04-05 13:27:35
0
396
weegolo
75,939,929
17,267,064
Unable to transfer ownership of a google sheet owned by my service account to my personal account
<p>I want to transfer ownership of a google sheet that I created using my service account to my personal account using Python.</p> <pre><code>from google.oauth2 import service_account from googleapiclient.discovery import build creds = service_account.Credentials.from_service_account_file('credentials.json') service ...
<python><google-sheets><gspread>
2023-04-05 13:18:08
0
346
Mohit Aswani
75,939,770
10,499,953
How can I construct a DataFrame that uses the PyArrow backend directly (i.e., without a pd.read_xx() method)?
<p>Pandas 2.0 introduces the option to use PyArrow as the backend rather than NumPy. As of version 2.0, using it seems to require either calling one of the <code>pd.read_xxx()</code> methods with <code>type_backend='pyarrow'</code>, or else constructing a <code>DataFrame</code> that's NumPy-backed and then calling <cod...
<python><pandas><pyarrow>
2023-04-05 13:01:31
1
417
Attila the Fun
75,939,717
3,214,872
How to generate dummy op for torch-to-ONNX export?
<p>I'm trying to export a torch model to ONNX and, due to some custom operations in the model, I need to generate custom ONNX nodes hwile exporting. I would like to be able to define a &quot;dummy&quot; operation that I can then use to register a symbolic function handling the ONNX node generation, however I don't know...
<python><pytorch><torchscript>
2023-04-05 12:57:48
0
19,263
GPhilo
75,939,550
1,000,343
globals() Doesn't Work Inside of a Package
<p>It is sometimes convenient to source part of a .py file into the global workspace when you're doing interactive tasks (I am aware that <code>exec</code> has code smell&quot;). I have a function that takes a file and regex markers of what start and end points to source lines from and assigns the contents of the file...
<python><python-3.x>
2023-04-05 12:41:30
1
110,512
Tyler Rinker
75,939,403
9,577,700
How to print only specific text to multiline window in pysimplegui
<p>I have a situation where I am creating application which is storing log information. I have added UI using pysimplegui package. what I want to achieve is</p> <ol> <li>Print some information into text file</li> <li>Print few information line to UI multiline box.</li> </ol> <p>Currently whatever I have printed is goin...
<python><pysimplegui>
2023-04-05 12:24:56
0
481
dnyanesh ambhore
75,939,141
1,446,710
Create task from within another running task
<p>In Python I create two async tasks:</p> <pre><code>tasks = [ asyncio.create_task(task1(queue)), asyncio.create_task(task2(queue)), ] await asyncio.gather(*tasks) </code></pre> <p>Now, I have a need to create a third task &quot;task3&quot; <strong>within</strong> task1.</p> <p>So I have:</p> <pre><code>async ...
<python><python-asyncio>
2023-04-05 11:56:31
1
2,725
Daniel
75,939,055
3,630,230
Determine the current binlog file with python-mysql-replication
<p>I'm using the <a href="https://github.com/julien-duponchelle/python-mysql-replication" rel="nofollow noreferrer">python-mysql-replication</a> package to consume the MySQL binlog. The current binlog position is accessible as shown below, but I'm unable to access the current binlog file, which I'd need if I want to re...
<python><mysql>
2023-04-05 11:49:06
1
343
Weston Sankey
75,938,908
19,580,067
Find the index of the word in sentence even if it matches partially (fuzzy)
<p>I need to find the start index of a word in a sentence even if it matches partially.</p> <p>I tried find() method. But it matches only if the word is exact match.</p> <p>code:</p> <pre><code>import re body = 'Charles D�Silva | Technical Officer Anglo (UK) Limited' word = 'ANGLO (UK) LTD' start_idx = body.lower()...
<python><regex><string><fuzzy-search>
2023-04-05 11:34:35
2
359
Pravin
75,938,884
9,544,904
OSMNX find nearest nodes within 1km euclidean distance of a co-ordinate point
<p>I have an osmnx graph <code>G</code> and some co-ordinate points <code>P</code>. Now I want to find all the nodes which are within 1km Euclidean distance of at least one co-ordinate point of <code>P</code>. My code is as follows:</p> <pre class="lang-py prettyprint-override"><code> import osmnx as ox G = ox.g...
<python><osmnx>
2023-04-05 11:32:09
1
443
Sihan Tawsik
75,938,882
1,498,199
Slice and assign in a pd.DataFrame
<p>At first we create a small <code>pd.DataFrame</code> with MultiIndex on both axis:</p> <pre><code>columns = pd.MultiIndex.from_tuples([('a', 2), ('a', 3), ('b', 1), ('b', 3)], names=['col_1', 'col_2']) index = pd.MultiIndex.from_tuples([(pd.Timestamp('2023-03-01'), 'A'), (pd.Timestamp('2023-03-01'), 'B'), (pd.Timest...
<python><pandas><dataframe><multi-index>
2023-04-05 11:32:04
3
1,296
JoergVanAken
75,938,581
5,016,028
How can I use sympy sum over elements of a list in python?
<p>I am just trying to use a sympy sum over a list of elements, for example:</p> <pre><code>x = [1,2,3,4,5] expression = sympy.sum(x[i], (i,0,2)) * sympy.sum(x[j], (j,1,3)) </code></pre> <p>and I just want it to numerically evaluate this. I always get index out of range, although it's clearly not out of range. Any ide...
<python><python-3.x><list><sympy>
2023-04-05 10:57:16
1
4,373
Qubix
75,938,574
13,839,945
Matplotlib animation.artistanimation showing all plots at once for inital figure
<p>I want to create live plots of my results and found this SO question which did most of the job: <a href="https://stackoverflow.com/questions/49158604/matplotlib-animation-update-title-using-artistanimation">Matplotlib animation update title using ArtistAnimation</a></p> <p>BUT, when I start the script, the first fig...
<python><matplotlib><plot><matplotlib-animation>
2023-04-05 10:56:31
1
341
JD.
75,938,471
17,973,259
Compare two image variables in pygame
<p>I have this method that when called it changes the weapon for the player, I want to somehow be able to determine if the current weapon is already the new weapon. I tried with <code>is</code> and <code>pygame.surface.get_at()</code> but it didn't work. Eventually I will do another action when the weapon is the same, ...
<python>
2023-04-05 10:44:30
1
878
Alex
75,938,329
938,021
Paramiko SFTPClient class throws "Authentication failed", but Transport class and WinSCP work
<p>I have an issue using Paramiko and connecting to an SFTP server.</p> <p>The connecting work fine using same credentials in WinSCP.<br /> I am also able to use pysftp.<br /> But I would prefer to be able to use Paramiko, which gives access to better control of timeouts (removed in the example below).</p> <p>I get the...
<python><sftp><paramiko><pysftp>
2023-04-05 10:29:13
2
1,302
jakobdo
75,938,285
857,741
Get values of range object without using 'for' loop
<p>It seems <code>range()</code> doesn't have a method of getting values (something like <code>dict().values()</code>).</p> <p>Is there a way of getting the values without doing &quot;manual&quot; iteration (like <code>[x for x in range(10)]</code>)?</p>
<python>
2023-04-05 10:23:57
3
6,914
LetMeSOThat4U
75,938,229
5,868,293
Create indicator column threshold of values of another column for different rows with groupby in pandas
<p>I have the following dataframe</p> <pre><code>import pandas as pd pd.DataFrame({'id':[1,1,2,2,3,3], 'phase': ['pre', 'post','pre', 'post','pre', 'post'], 'n': [5,6,7,3,10,10]}) </code></pre> <p>I want to create a new column (<code>new_col</code>) which indicates if <code>n&gt;=5</code> for ...
<python><pandas>
2023-04-05 10:17:48
2
4,512
quant
75,938,214
9,861,647
Duplicate rows in pandas on condition
<p>I have this pandas dataframe:</p> <pre><code> Column1 Column2 Column3 1 A C 2 A D 3 B </code></pre> <p>If the is a &quot;D&quot; in my column2 i want to duplicate the row with is values and reset the index like this :</p> <pre><code> Column1 Column2 Column3 1...
<python><pandas>
2023-04-05 10:15:55
1
1,065
Simon GIS
75,938,122
14,997,346
Flask MJPEG stream has long loading time
<p>I wrote a class to display images on a small webpage (mainly images captured by a camera, some image processing in between). I worked after <a href="https://blog.miguelgrinberg.com/post/video-streaming-with-flask" rel="nofollow noreferrer">Miguel's blog post</a>.<br /> Since few weeks I have an issue that the websit...
<python><flask><mjpeg>
2023-04-05 10:04:50
0
331
chillking
75,937,978
10,938,315
structlog: display log level in Cloudwatch
<p>I have set up my logger like this:</p> <pre><code>import logging import structlog class Logging: @staticmethod def my_logger() -&gt; logging.Logger: structlog.configure( processors=[ structlog.processors.add_log_level, structlog.processors.TimeStamper(fmt...
<python><amazon-web-services><structlog>
2023-04-05 09:49:18
1
881
Omega
75,937,954
5,674,660
How to filter convert a date field into a date to extract the current month in SQLite db using func.strftime() in sqlalchemy
<p>I want to know the subscribed events (events that I am following) that took place in current month. This is irrespective of whether they took place 5 years ago, or a year ago, so long as they took place in the current month. I am convinced by problem emanates from <code>Event.event_date</code>. How do I convert this...
<python><datetime><flask><sqlalchemy><func>
2023-04-05 09:46:54
1
1,012
chibole
75,937,941
12,667,081
concurrent futures threadpoolexecutor repeating list items
<p>I'm new to multi-threading in Python, and trying to manage a script that calls thousands of APIs. I've read a number of answers and articles and got to this:</p> <pre><code>import requests import json import time import sys import concurrent.futures import threading thread_local = threading.local() pet_data = [] ...
<python><python-3.x><list><multithreading>
2023-04-05 09:45:33
1
545
Brian - RGY Studio
75,937,892
14,649,310
Can an SQLAlchemy ARRAY column be mapped to a python tuple?
<p>I have seen the SQLAlchemy ARRAY columns be mapped to lists with a default empty list value like this:</p> <pre><code>tags = Column(ARRAY(Text, dimensions=1), default=[]) </code></pre> <p>Can this mapped to a non-mutable python object like a tuple?</p>
<python><sqlalchemy><flask-sqlalchemy>
2023-04-05 09:38:56
1
4,999
KZiovas
75,937,792
7,295,936
Group a list of strings by similar values
<p>I want to group a list of strings by similarity.</p> <p>In my case (here simplified cause this list can be huge) it's a list of path to zip files like this:</p> <pre><code>[&quot;path/002_AC_HELICOPTEROS-MARINOS_20230329_210358_145T3_21049_00748_DMAU.zip&quot;, &quot;path/002_AC_NOLAS_20230326_234440_145T2_20160_06...
<python><python-3.x><string><list><grouping>
2023-04-05 09:27:42
2
1,560
FrozzenFinger
75,937,745
2,885,763
get reference from parent object
<p>is there a more efficient/pythonic way to catch a composition object upper reference. Not an heritage in terms of class but from an object that is an attribut of a parent one (array or direct). Something like <code>PythonicRef(self)</code> in this concept sample</p> <pre><code>class TheChild : def GetParentColor(...
<python><python-3.x>
2023-04-05 09:23:12
1
10,057
NeronLeVelu
75,937,636
6,375,025
Optimizing Complex Data Processing: Advanced Techniques for Efficiently Handling Massive CSV Files in Python
<p>I'm working on a project where I need to process massive CSV files that contain hundreds of millions of rows and dozens of columns. I've tried using various Python libraries such as pandas, Dask, and PySpark, but I'm still encountering serious performance issues, and my code keeps crashing due to memory errors.</p> ...
<python><pandas><performance><csv><memory-management>
2023-04-05 09:10:14
0
435
Millet Antoine
75,937,624
1,240,108
Python 3.8 and pickle load()
<p>I am struggling reading a pickle file. I keep having the <code>EOFError: Ran out of input</code> My file is definitely not empty and I am using python3.8 with pandas 1.4.4</p> <p><a href="https://i.sstatic.net/Br1na.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Br1na.png" alt="enter image descriptio...
<python><pandas><pickle><python-3.8>
2023-04-05 09:08:53
0
1,079
JPV
75,937,608
275,224
How to make VSCode continue search for modules to import under debugging when having several packages under same namespace
<p>I have a Python project where I depend on another Python package I develop.</p> <p>Call them 'moduleA' and 'moduleB'. Both are distributed as Python packages.</p> <p>I have given the packages a namespace where the company name is the top level. i.e. 'companyA.moduleA' and 'companyA.moduleB'.</p> <p>In my repo (for m...
<python><python-3.x><visual-studio-code>
2023-04-05 09:08:00
2
576
pablaasmo
75,937,446
7,330,316
pandas - How to show whole numbers along with floats?
<p>Imagine I have this list:</p> <pre class="lang-py prettyprint-override"><code>df = pandas.DataFrame([1, 2.321, 13.3444, 7.5, 5]) </code></pre> <p>How can I make the output table show whole numbers without decimal places and others with, say 2, decimal places? Something like this:</p> <pre><code>1 2.30 13.34 7.50 5 <...
<python><pandas>
2023-04-05 08:52:33
1
2,462
Shahriar
75,937,434
13,793,478
How to perform 2 operations in MathFilters ( Django )
<p>I wanted to perform 2 operations 1: subtract entry_price from Exit_price then multiply the outcome by size. I am getting the error:</p> <pre><code>Could not parse some characters: |(journals.exit_price||sub:journals.entry_price)|mul:journals.size </code></pre> <pre><code>&lt;p class=&quot;pnl&quot;&gt; {% if jou...
<python><django>
2023-04-05 08:50:59
1
514
Mt Khalifa
75,937,355
18,091,040
Fill pandas dataframe missing data based on correlation with other columns
<p>I have a pandas DataFrame with many rows and a column of strings named <code>error_text</code> that contains several empty values. I wanted to fill these missing data based on the correlation of this column with another one.</p> <pre><code>mydf_example = pd.DataFrame({'a':[1,2,3,4,5,6,3],'b':[10,20,30,40,50,60,30],'...
<python><pandas><dataframe><missing-data>
2023-04-05 08:41:11
1
640
brenodacosta
75,937,200
6,871,867
How to select option from a combobox in python selenium?
<p>I am trying to put value in a combo-box using python selenium. As we enter text it gives different possible values in dropdown. How to select the first value on the drop down? As soon as I try to click on it, it removes the text and makes it blank.</p> <p><a href="https://i.sstatic.net/8iOxE.jpg" rel="nofollow noref...
<python><selenium-webdriver>
2023-04-05 08:22:31
1
462
Gopal Chitalia
75,937,184
10,735,143
How to remove all ampersands in a string except for specific tokens
<p>I need to remove every ampersand in a string except tokens like 'd&amp;g' or 'black&amp;jones'. For this purpose it must be done using regex. I used this pattern <code>r'[a-zA-Z]&amp;[a-zA-Z]'</code> but not working. Any help or guidance would be greatly appreciated.</p>
<python><regex><string>
2023-04-05 08:20:14
2
634
Mostafa Najmi
75,937,154
13,647,125
Dash title while updating
<p>I would like to change app title <a href="https://i.sstatic.net/tIczX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tIczX.png" alt="enter image description here" /></a></p> <p>this is how my app.callback looks like</p> <pre><code>@app.callback( Output('table', 'data'), [Input('interval-compo...
<python><plotly-dash><title>
2023-04-05 08:17:34
1
755
onhalu
75,936,946
15,877,202
How can I add and drop columns and rows in a pandas dataframe followed by saving it down into a csv (adding and dropping works but doesn't save)?
<p>So I have some code that drops a few columns in a pandas dataframe and add one column to the pandas dataframe:</p> <pre><code>import pandas as pd df = pd.read_csv('TradedInstrument_20230331_real.txt', sep='\t', encoding='unicode_escape') cols = ['stopTrdgAllag', 'stopTrdgsAllowTrdg', 'stopTrdleInTrdg', 'presholdCh...
<python><dataframe>
2023-04-05 07:56:47
1
566
Patrick_Chong
75,936,937
7,132,482
Python3: Update date format
<p>I have a tricky with date format with time series data. In my dataframe of over one hundred thousand rows I have a column datetime with date value but the format is %M:%S.%f.</p> <p>Example:</p> <pre><code>datetime 0 59:57.7 1 00:09.7 2 00:21.8 </code></pre> <p>What I want in output is to convert this form...
<python><pandas><dataframe><datetime><timedelta>
2023-04-05 07:55:34
1
335
Laurent Cesaro
75,936,847
11,333,604
cannot import name 'function' from 'file' on collab
<p>I have a helper_functions.py file that I want to use some functions from, but nothing seems to work.</p> <p><code>from helper_functions import plot_decision_boundary</code></p> <p><em>ImportError: cannot import name 'plot_decision_boundary' from 'helper_functions' (/content/helper_functions.py)</em></p> <p><code>fro...
<python><import><google-colaboratory>
2023-04-05 07:46:16
3
303
Iliasp
75,936,744
9,270,562
Errors when trying to install psycopg2 using pip
<p>I was trying to install psycopg2 using pip when I got the errors:</p> <pre><code>subprocess-exited-with-error and legacy-install-failure </code></pre> <p>The following is the error description:</p> <pre><code>Collecting psycopg2 Using cached psycopg2-2.9.6.tar.gz (383 kB) Preparing metadata (setup.py) ... done B...
<python><python-3.x><pip>
2023-04-05 07:32:40
0
362
Suneha K S
75,936,663
15,010,256
If condition is met, skip from 2nd iteration onwards
<pre><code>#Can be more than two items also. item_list = [&quot;rpm&quot;, &quot;exe&quot;] extraction_status = True while extraction_status: file_status_flag = True file_status = some_other_function(arg1, arg2) # returns a nested dictionary of lists. for item in file_status['BU']: # file_status[...
<python><python-3.x>
2023-04-05 07:20:37
2
466
Chel MS
75,936,529
1,478,875
Verifying Crowdstrike Webhooks
<p>I am attempting to verify webhooks that are sent from CrowdStrike to my python application.</p> <p>I know the signature is generated using HmacSHA256, and I have the shared secret.</p> <p>However, I'm not sure what they're hashing to get the signature. I have tried hashing the body of the webhook with the secret, an...
<python><webhooks>
2023-04-05 07:03:45
1
659
mark_3094
75,936,515
14,269,252
Adjust the height of y axes in scatter plot in Plotly instead of having it fixed
<p>I wrote the code as follows using Plotly. This is connected to some filter. The problem is I can have varies number of category (code) on my Y axes.</p> <p>How can I adjust the height and space between two code which is shown in the attached picture if I choose 2 code it should be small, when I choose 50, it must be...
<python><plotly>
2023-04-05 07:01:04
0
450
user14269252
75,936,392
1,446,710
Asyncio: task got bad yield?
<p>My code here always drops an error message which neither google, neither chatgpt are unable to explain:</p> <pre><code>import asyncio import udiskie import udiskie.config import udiskie.udisks2 async def main(): device = '/dev/mmcblk0p1' config = udiskie.config.Config.from_file() udisks = await udiskie....
<python><python-3.x><python-asyncio>
2023-04-05 06:43:47
1
2,725
Daniel
75,936,278
8,820,616
Python in time or Datetime, List all time zones available
<p>Is the a way to list All timezones for Time and Datetime library in Python</p> <p>so it can be used as options to get time in respective timezone</p> <p>like in the example</p> <pre><code>from datetime import datetime from pytz import timezone south_africa = timezone('Africa/Johannesburg') sa_time = datetime.no...
<python><datetime><time><timezone>
2023-04-05 06:30:00
1
694
Pradeep Padmanaban C
75,936,149
4,412,885
Convert TensorFlow to ONNX: Current implementation of RFFT or FFT only allows ComplexAbs as consumer not {'Imag', 'Real'}
<p>I am trying to convert this <a href="https://tfhub.dev/google/lite-model/spice/1" rel="nofollow noreferrer">TensorFlow model</a> to <a href="https://github.com/onnx/tensorflow-onnx" rel="nofollow noreferrer">onnx</a>. But I get an error message:</p> <pre><code>&gt; python -m tf2onnx.convert --saved-model .\spice --o...
<python><tensorflow><tensorflow-lite><onnx><tf2onnx>
2023-04-05 06:10:40
1
1,277
mihca
75,935,842
11,630,148
Pytest and pytest-django ends up with assert error
<p>I've been dealing with this for the last 30 mins and I just want to move on from it. Basically, the test returns Assertion Error:</p> <pre class="lang-py prettyprint-override"><code>E AssertionError: assert {} == {'rant': 'Kulugo', 'slug': 'apostrophe'} E Right contains 2 more items: E {'rant':...
<python><django><pytest><pytest-django>
2023-04-05 05:11:19
1
664
Vicente Antonio G. Reyes
75,935,575
2,246,380
Identify missing data in python dataframe
<p>I have a dataframe that looks like this</p> <pre><code>location_id device_id phase timestamp date day_no hour quarter_hour data_received data_sent 10001 1001 Phase 1 2023-01-30 00:00:00 2023-01-30 1 0 00:00:00 150 98 10001 1001 Pha...
<python><pandas><dataframe><missing-data>
2023-04-05 04:08:25
1
3,091
Ram
75,935,536
1,768,029
How to dynamically access string value?
<p>If I define 2 strings as:</p> <pre><code>Str1 = &quot;select * from tableA&quot; Str2 = &quot;select * from tableB&quot; </code></pre> <p>Now when i = 1, Str1 value should be retrieved and when i = 2 , str2 value should be retrieved. How to dynamically access string value?</p> <pre><code>Src=“Str” for i in range(1,...
<python>
2023-04-05 04:01:20
3
425
user1768029
75,935,511
6,534,818
Pandas: How can I use str.extractall with another column as the pattern input?
<p>How can I use another column as my pattern for str.extract/all? The below example uses a hardcoded pattern, but I want Pandas to look at every row in the <code>Pattern</code> column and use that pattern for its extraction search.</p> <pre><code>df = pd.DataFrame({&quot;Pattern&quot;: ['a|c'], &quo...
<python><pandas>
2023-04-05 03:51:45
1
1,859
John Stud
75,935,442
9,644,490
Calling child method from parent method not working
<p>I have a Parent and Child class as follows:</p> <pre><code>class Parent: def __init__(self): self.__set_config(): def __set_config(self): raise NotImplementedError def run(self): # do something class Child: def __set_config(self): self.config = {&quot;foo&quot;: &quot;bar&quot;} </code></p...
<python>
2023-04-05 03:33:53
0
409
kyuden
75,935,433
424,957
how to calculate time between two datetime in python?
<p>I have two datetime as below</p> <pre><code>start=2023/04/05 08:00:00, end=2023/04/05 16:00:00 </code></pre> <p>I want to get time by</p> <pre><code>lTime = start + (end - start) /3 or lTime = (start * 2 + end) /3 </code></pre> <p>I used code as below</p> <pre><code>lTime = start + timedelta(end - start) / 3 </cod...
<python><datetime><timedelta>
2023-04-05 03:30:56
1
2,509
mikezang
75,935,429
5,212,614
How to normalize or explode a field from a JSON file?
<p>I'm reading a JSON file; it looks like this.</p> <pre><code> type features 0 FeatureCollection {'type': 'Feature', 'properties': {'GEO_ID': '... 1 FeatureCollection {'type': 'Feature', 'properties': {'GEO_ID': '... 2 FeatureCollection {'type'...
<python><json><python-3.x>
2023-04-05 03:30:19
1
20,492
ASH
75,935,363
2,825,403
Adding a column based on condition in Polars
<p>Let's say I have a Polars dataframe like so:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({ 'a': [0.3, 0.7, 0.5, 0.1, 0.9] }) </code></pre> <p>And now I need to add a new column where 1 or 0 is assigned depending on whether a value in column <code>'a'</code> is greater or less than some ...
<python><dataframe><python-polars>
2023-04-05 03:11:16
1
4,474
NotAName
75,935,347
10,051,099
Can I set command output to basepython in tox.ini?
<p>Can I set command output to basepython in tox.ini? I want to do something like this:</p> <pre><code>[tox] envlist = pymain pynext [testenv:pymain] basepython=$(get_python_main_path) [testenv:pynext] basepython=$(get_python_next_path) </code></pre> <p>get_python_main_path and get_python_next_path are shell ...
<python><tox>
2023-04-05 03:07:23
0
3,695
tamuhey
75,935,293
10,756,025
pynecone cannot get detail information from item in the cards example (grid + foreach)
<p>This is our expected output.<br /> <a href="https://i.sstatic.net/t6Wnl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/t6Wnl.png" alt="enter image description here" /></a></p> <p>And this is the current output.<br /> <a href="https://i.sstatic.net/2QPfz.png" rel="nofollow noreferrer"><img src="https:...
<python><foreach><grid><python-reflex>
2023-04-05 02:54:13
1
4,045
Milo Chen
75,935,256
16,922,748
How to efficiently apply a function to every row in a dataframe
<p>Given the following table:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'code':['100M','60M10N40M','5S99M','1S25I100M','1D1S1I200M']}) </code></pre> <p>that looks like this:</p> <pre class="lang-none prettyprint-override"><code> code 0 100M 1 60M10N40M 2 5S99M 3 1S25I100M 4 1D1...
<python><pandas><string><performance>
2023-04-05 02:43:10
5
315
newbzzs
75,935,251
262,875
Discord.py: How to get access to self in a check's predicate function?
<p>I've spent at least a day trying to find an answer to the question, including messing around with nested decorators for at least a couple hours but I don't seem to be able to figure it out.</p> <p>I am using Discord.py and it's <code>commands.check</code> &quot;decorator generator&quot;, but I think the problem (and...
<python><discord.py><python-decorators>
2023-04-05 02:42:09
1
11,089
Daniel Baulig
75,935,049
6,676,101
When does a regex interpret something as a string of many characters and when does a regex use a single letter or other character?
<p>When I look at the regular expression <code>(foo|bar|baz)</code> I get confused.</p> <p>Does the regex say:</p> <ul> <li><code>fo</code>, followed by <code>o</code> or <code>b</code>, followed by exactly one letter <code>a</code>, followed by <code>r</code> or <code>b</code>, followed by the string <code>az</code>?...
<python><regex>
2023-04-05 01:41:30
2
4,700
Toothpick Anemone
75,934,965
14,892,434
Celery task stays running forever, but completes successfully
<p>My Task:</p> <pre class="lang-py prettyprint-override"><code>@app.task(ignore_result=True) def leaks_scan(target: str, remove_type: str = &quot;old&quot;, **kwargs): url = settings.API_URL + &quot;leaks&quot; skip = 0 limit = 1000 max_limit = 5000 if remove_type == &quot;all&quot;: remove...
<python><django><celery>
2023-04-05 01:15:32
1
305
OmerFI
75,934,860
19,157,137
View all of the built in functions that take in a particular data type in Python
<p>How would I be able to view all of built in functions take in a particular object(<code>list, str, int, float</code> ....) as its parameter for example some functions that pass <code>list</code> are <code>max(), min(), len() ....</code>. I can view all of the methods by simply <code>dir(object)</code> like <code>dir...
<python><function><object>
2023-04-05 00:42:20
0
363
Bosser445
75,934,857
18,551,983
generate a new dictionary based on list of values
<p>I have an input dictionary d1 and list l1 and want to generate output dictionary d2.</p> <pre><code>d1 = {'A1':['b1','b2','b3'], 'A2':['b2', 'b3'], 'A3':['b1', 'b5']} l1 = ['b2', 'b5', 'b1', 'b3'] </code></pre> <p>Output dictionary</p> <pre><code>d2 = {'b2':['A1','A2'], 'b5':['A3'], 'b1':['A1','A3'], 'b3':['A1','A2'...
<python><python-3.x><list><dictionary>
2023-04-05 00:41:24
1
343
Noorulain Islam
75,934,851
10,941,410
How to make sure list defined in class variable objects are not shared across different instances?
<p>I have the following:</p> <pre class="lang-py prettyprint-override"><code>class Loop: def __init__(self, group_class: Type[SegmentGroup], start: str, end: str): self.group_class = group_class self.start = start self.end = end self._groups: List[SegmentGroup] = [] def from_...
<python><metaclass>
2023-04-05 00:39:54
3
305
Murilo Sitonio
75,934,631
3,380,902
Error connecting to aws redshift using dask
<p>I am using <code>dask</code> to connect to AWS Redshift and query the db. I run into an error when attempting to pass a connection string to <code>read_sql_query</code> method.</p> <p><code>config.py</code></p> <pre><code>import os # Create dictionary of environment variables env_var_dict = { # ...
<python><sqlalchemy><amazon-redshift><dask>
2023-04-04 23:38:13
1
2,022
kms
75,934,545
15,178,267
Django: How to loop through query set and change the boolean field to True in django?
<p>I am trying to loop through a queryset in django and turn all the boolean fields in the queryset to true.</p> <p>I want to turn this booleans to True on the success_page, so i tried doing it like this</p> <pre><code>@login_required def PaymentSuccessView(request): ... order = get_object_or_404(CartOrder, str...
<python><django><django-rest-framework><django-views>
2023-04-04 23:19:05
1
851
Destiny Franks
75,934,493
13,916,049
Snakemake workflow error: tuple index out of range
<p>I want to create a reproducible workflow using <a href="https://snakemake.readthedocs.io/en/stable/tutorial/basics.html" rel="nofollow noreferrer">Snakemake</a>, which is built on top of Python.</p> <p>The <code>SAMPLES</code> is a list of strings in the <code>&quot;./input/SRR_Acc_List.txt&quot;</code> file and it ...
<python><snakemake>
2023-04-04 23:08:26
1
1,545
Anon
75,934,421
4,560,996
What is Most Efficient Way to Split Python List
<p>I have a vector that is always a multiple of the objects <code>M</code> and <code>K</code>. In the example below, <code>M=2</code> and <code>K=3</code> the vector is of length 6. What I want to find is the best way to use use the values of <code>M</code> and <code>K</code> to split my list so it results in a pandas ...
<python><pandas><numpy>
2023-04-04 22:51:24
2
827
dhc
75,934,399
5,054,505
How can I efficiently read paths stored in a column of a pyspark dataframe?
<p>The input to my process is a structured dataset where one column is a GCS path to a blob, something like:</p> <pre class="lang-py prettyprint-override"><code>df = spark.createDataFrame( [(&quot;gs://my/bucket/image.jpg&quot;,), (&quot;gs://my/bucket/image2.jpg&quot;,)], [&quot;image_path&quot;] ) </code></p...
<python><image><apache-spark><pyspark>
2023-04-04 22:46:37
1
610
Patrick
75,934,397
9,927,519
Is it possible to create a TypedDict equivalent with its own methods and properties in Python?
<p>I like to work with <a href="https://docs.python.org/3/library/typing.html#typing.TypedDict" rel="nofollow noreferrer"><code>TypedDict</code></a>s to convey the batch and item information in PyTorch. It works well with the default collate function and adds the possibility to add types.</p> <p>What I don't like is th...
<python><dictionary><pytorch><python-typing><typeddict>
2023-04-04 22:46:14
0
3,287
Xiiryo
75,934,322
12,043,177
Neo4j python driver results don't contain edge data
<p>This is my Cypher query and its equivalent result in neo4j Browser</p> <blockquote> <p>MATCH (a)-[b:REFERENCE]-&gt;(c) RETURN a,b,c LIMIT 200</p> </blockquote> <p><a href="https://i.sstatic.net/B1OZP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/B1OZP.png" alt="enter image description here" /></a></...
<python><neo4j><neo4j-python-driver>
2023-04-04 22:29:18
2
974
kenneth-rebello
75,934,227
1,552,698
How to flatten list of dictionaries
<p>I am learning how to traverse lists and dictionaries in Python. I am a beginner.</p> <pre><code>process = [ { 'process1': [ {&quot;subprocess1&quot;:[&quot;subprocess1_1&quot;,&quot;subprocess1_2&quot;]}, ...
<python><list><dictionary>
2023-04-04 22:11:11
3
597
user1552698
75,934,176
5,692,012
Can't recover memory from deleted objects in Python
<p>I'm working on a project where I temporarily store objects in lists. But it seems that even when all references to these objects are deleted, the memory isn't freed, which leads to very high RAM usage in my process.</p> <p>I've tried to reproduce a simple example and the results are indeed very strange, I can't expl...
<python><memory><memory-leaks><garbage-collection><python-3.9>
2023-04-04 22:01:45
0
5,694
RobinFrcd
75,934,148
1,497,199
Django primary key field not showing up in postgres database
<p>I have a model class</p> <pre><code>import uuid import datetime, pytz from django.db import models from django.conf import settings class Topic(models.Model): key = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=168) owner = models.ForeignKey(s...
<python><django><postgresql>
2023-04-04 21:56:10
0
8,229
Dave
75,933,853
5,407,050
Why two datetime.time cannot be substracted?
<p>For satisfying my curiosity, is there any reason why two datetime.time values cannot be direclty subtracted?</p> <pre><code>seconds = (datetime.combine(date.today(), end_time) - datetime.combine(date.today(), start_time)).total_seconds() </code></pre> <p>works, but</p> <pre><code>seconds = (end_time - start_time).to...
<python>
2023-04-04 21:06:35
0
334
Daniel Lema
75,933,813
1,914,034
Numpy - calculate mean of groups
<p>I have a an array of shape (N, 3) like this one for instance:</p> <pre><code>arr = np.array( [ [0,1,1], [0,1,2], [2,2,2] ] ) </code></pre> <p>I want to group this array by the two first columns to obtain an array like this</p> <pre><code>grouped_arr = np.array([[[0,1,1], [0,1,2]], [[2,2,2]]]) </cod...
<python><numpy><average>
2023-04-04 21:00:33
1
7,655
Below the Radar
75,933,760
1,315,621
Python Boto3 check if file on s3 is equal to local file
<p>I have some files in a local folder. These files can be modified locally. I need to keep a copy of the updated files on S3. Is there a way I can check whether a local file is equal to a file on S3 (example: using checksum)? In this way I won't have to upload the files that have not been changed. I am using boto3 and...
<python><amazon-web-services><amazon-s3><upload><boto3>
2023-04-04 20:52:04
3
3,412
user1315621
75,933,676
1,446,710
Unmount a drive with python with udisks2 via dbus
<p>I'm trying to achieve the title.</p> <p>Here is my code:</p> <pre><code>from dbus_next.aio import MessageBus async def unmount_device(device_path): bus = await MessageBus().connect() udisk_obj = bus.get_proxy_object('org.freedesktop.UDisks2', device_path) udisk_interface = udisk_obj.get_interface('org.f...
<python><dbus><udisks>
2023-04-04 20:40:23
1
2,725
Daniel
75,933,400
8,382,452
how to prevent firefox from opening a downloaded file in selenium?
<p>I'm doing a selenium test to click on a button and download a file. It is downloading the file, but the browser always opens it in the middle of the execution, opening a new tab on firefox and breaking my test.</p> <p>I tried to set the preferences in code, but it's not working.</p> <pre><code>firefox_options = Opti...
<python><selenium-webdriver>
2023-04-04 20:03:05
0
345
Yuri Costa
75,933,341
4,579,256
Dash: callback after clicking anywhere on a Scattermapbox map
<p>I am looking for a Dash callback that would access via <code>go.Scattermapbox()</code> any coordinate (longitude and latitude) after clicking or just hovering over a Mapbox map.</p> <p>It is possible to access image coordinates in case of a <code>dcc.Graph</code> containing an image, as shown here: <a href="https://...
<python><mapbox><plotly-dash>
2023-04-04 19:56:06
1
350
petervanya
75,933,279
19,051,091
How to improve pytroch model?
<p>Good evening, I have 4 classes with black and white images each class has 3000 images with a test of 600 images so how to improve this model and that's my full code:</p> <pre><code>data_transform = transforms.Compose([ transforms.Grayscale(num_output_channels=1), transforms.Resize(size=(150, 150)), trans...
<python><pytorch>
2023-04-04 19:47:40
2
307
Emad Younan
75,933,263
13,742,058
how to set experimental options on undetected chromedriver in selenium python?
<p>whenever I run this code ..</p> <pre><code>import undetected_chromedriver as uc from selenium.webdriver.support.ui import Select from webdriver_manager.chrome import ChromeDriverManager from selenium import webdriver from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() options.a...
<python><selenium-webdriver><webdriver><undetected-chromedriver>
2023-04-04 19:45:11
0
308
fardV
75,933,081
12,016,688
Where is the giant cpython switch case statement moved?
<p>Not sure if it's off topic but don't know any better place to ask. In <code>cpython</code> there was a very giant <code>switch</code> <code>case</code> statement for executing each opcode. This switch case previously was placed in the <code>_PyEval_EvalFrameDefault</code> function. Here is the <a href="https://githu...
<python><cpython>
2023-04-04 19:20:02
1
2,470
Amir reza Riahi