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
⌀
77,026,689
22,070,773
What is the nanobind equivalent of the Boost.Python function manage_new_object?
<p>I'm trying to wrap a function that exposes a raw, heap-allocated pointer, and I want Python to be responsible for its lifetime. This is usually achieved in Boost.Python with using the <code>return_value_policy</code> of <code>manage_new_object</code> when wrapping it, is there a similar way to achieve this in nanobi...
<python><c++><nanobind>
2023-09-02 01:54:51
1
451
got here
77,026,565
5,287,011
Count certain occurrences with multiple conditions: groupby(), count or len
<p>I have the following dataframe tran:</p> <pre><code>SourceLoc DestLoc SourceEq DestEq TypeT Loc1 Loc1 Eq1 Eq2 Make Loc1 Loc2 Eq1 Eq1 Transfer Loc1 Loc3 Eq2 Eq2 Transfer Vend Loc2 Eq1 Eq1 Buy Loc2...
<python><pandas><dataframe><group-by><count>
2023-09-02 00:52:06
2
3,209
Toly
77,026,453
13,250,589
Python's collection.Counter equivalent in C# or .NET
<p>While solving problems in Python I often had to use Python's <code>collections.Counter</code> object.</p> <p>When I started solving the same problems in C# I couldn't find an equivalent method or class for it.</p> <p>I was just wondering if there is any?</p> <h3>Explanation of <code>collections.Counter</code></h3> <...
<python><c#><dictionary><hashmap><counter>
2023-09-01 23:56:54
3
885
Hammad Ahmed
77,026,441
14,509,604
How do filter/slicing in pandas work? Why always it occupies ram?
<p>I've been doing data science for few years, but just right now I've realized that when I filter columns with any <strong>any</strong> method, it occupies RAM.</p> <pre><code>import pandas as pd import numpy as np import datetime df = pd.DataFrame({'A' : ['spam', 'eggs', 'spam', 'eggs'] * 175000, ...
<python><pandas>
2023-09-01 23:50:55
1
329
juanmac
77,026,403
2,905,762
AES CTR encrypt on Flutter and failed to decrypt on python
<p>I have a project that needs to encrypt text on the front end using Flutter and decrypt it on Python.</p> <p>After I searched, I found the way to use AES CTR in this link <a href="https://stackoverflow.com/questions/62580708/same-encryption-between-flutter-and-python-aes">same encryption between flutter and python [ ...
<python><flutter><encryption><aes><ctr>
2023-09-01 23:33:26
0
694
Hansen
77,026,147
3,821,009
Jpype java to python type conversions
<p>Say I create a simple java type with jpype:</p> <pre><code>jt = jpype.java.lang.System.currentTimeMillis() print(jt) print(type(jt)) pt = int(jt) print(pt) print(type(pt)) </code></pre> <p>This produces:</p> <pre><code>1693604984710 &lt;java class 'JLong'&gt; 1693604984710 &lt;class 'int'&gt; </code></pre> <p>as ex...
<python><jpype>
2023-09-01 21:53:00
0
4,641
levant pied
77,025,944
4,224,575
Temporal topological sort of NetworkX graph
<p>I have a <a href="https://networkx.org/documentation/stable/index.html" rel="nofollow noreferrer">NetworkX graph</a> which was constructed using simple node and edge types, with the addition of a timestamp field on nodes:</p> <pre class="lang-py prettyprint-override"><code>class Node: key: str timestamp: int cl...
<python><networkx>
2023-09-01 20:54:57
1
5,968
Lorah Attkins
77,025,869
18,150,609
Can't Connect Python Service to Mongo Server in Docker
<p>I have a docker file with two services running on the same network. The purpose is to scrape data and store it in a database.</p> <p>When I attempt to run the program <code>db_connector.py</code> inside service <code>block_scraper</code> I get an error (Timeout):</p> <pre><code>pymongo.errors.ServerSelectionTimeoutE...
<python><mongodb><docker><docker-compose>
2023-09-01 20:34:25
1
364
MrChadMWood
77,025,860
2,673,149
Setuptools -- Replacing Manifest.in with pyproject.toml
<p>Does setuptools support replacing the Manifest.in file, which specifies files that should only be included in the sdist distribution with a declaration in pyproject.toml?</p>
<python><setuptools><pep517><sdist>
2023-09-01 20:29:31
1
400
Spitfire19
77,025,859
9,947,159
How to parallelize a for loop that takes a dataframe as input
<p>I have a function that takes a dataframe as an input and loops through each row to perform a bunch of operations and writes the final output to a file in append mode. I want to parallelize the execution of this function such that instead of iterating through all the rows of the dataframe one by one, it will loop ove...
<python><parallel-processing>
2023-09-01 20:29:17
1
5,863
Rajat
77,025,766
6,843,153
Post hyperlink to slack using slack sdk for python
<p>I want to post to slack a string that includes a hyperlink, and I'm using slack SDK for python. The string is made up this way:</p> <pre><code>f&quot;:notepadicon: *{doc_to_report['desc']}*: {doc_to_report['file_name']} [link]({doc_to_report['url']})\n&quot; </code></pre> <p>I know the markdown code for hyperlink is...
<python><hyperlink><markdown><slack-api>
2023-09-01 20:08:28
1
5,505
HuLu ViCa
77,025,762
1,397,061
Idiomatic way to check if any elements in a polars DataFrame are null
<p>Is there a more idiomatic way than:</p> <p><code>df.select(pl.any_horizontal(pl.all().null_count()))[0, 0]</code></p> <p>to check if any elements in a polars DataFrame <code>df</code> are null?</p>
<python><dataframe><python-polars>
2023-09-01 20:06:44
2
27,225
1''
77,025,537
11,332,999
I can use random to get a random value from a range. How do I make math evaluator that does opposite and also has access to math modules?
<p>I want to build a math evaluator for a private use (no security limitations when doing eval operations) that can give me possible outcomes of mathematical statements. Assume random() here refers to range() and also built-in Python range doesn't work with float values. So while it should do normal evals as default, r...
<python><math><range><expression><eval>
2023-09-01 19:15:36
2
629
Machinexa
77,025,425
10,859,585
Squeeze x-axis dates on altair line chart
<p>I have a burndown graph that shows dates on the x-axis and remaining objects on the y-axis. Sometimes I have a large amount of &quot;stagnant&quot; data (no objects completed for X-amount of time). The stagnant data is overpowering the line chart and viewers are more interested in the end part of the line chart. Giv...
<python><datetime><streamlit><altair>
2023-09-01 18:49:08
1
414
Binx
77,025,354
8,139,261
With Pydantic V2 and model_validate, how can I create a "computed field" from an attribute of an ORM model that IS NOT part of the Pydantic model
<p>This context here is that I am using FastAPI and have a <code>response_model</code> defined for each of the paths. The endpoint code returns a SQLAlchemy ORM instance which is then passed, I believe, to <code>model_validate</code>. The <code>response_model</code> is a Pydantic model that filters out many of the ORM ...
<python><fastapi><pydantic>
2023-09-01 18:32:31
1
1,908
jsnow
77,025,330
378,622
Rewriting complex exponential as trig functions
<p>I want to rewrite complex exponentials as trig functions like you see in this picture: <a href="https://i.sstatic.net/PDuPc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PDuPc.png" alt="enter image description here" /></a></p> <p>My attempt with e^(2 pi I / 8) is not working, because it instantly co...
<python><sympy><trigonometry><complex-numbers>
2023-09-01 18:25:57
1
26,851
Ben G
77,025,285
823,633
Python expressions in f-strings do not return same result as str() conversion for subclasses?
<p>For example, we override the <code>__str__</code> method in <code>Decimal</code> then call it two different ways</p> <pre><code>from decimal import Decimal class D(Decimal): def __str__(self): return super().normalize().__str__() num = D('1.0') print(f&quot;{num}&quot;) print(f&quot;{str(num)}&quot;) </c...
<python><string><overriding><f-string>
2023-09-01 18:17:38
1
1,410
goweon
77,025,228
1,466,897
How do you collect performance metrics from Chrome DevTools Protocol (cdp) with the python selenium RemoteWebDriver?
<p>I have an existing set of frontend automated tests that run in python and use pytest. I would like to add an automated test that, when run against a chromium based browser, collect performance metrics.</p> <p>Assume that <code>browser</code> is a custom wrapper around <code>RemoteWebdriver</code> and that I am not a...
<python><selenium-webdriver><selenium-chromedriver><ui-automation>
2023-09-01 18:07:25
1
392
Muttonchop
77,025,034
11,001,493
How to horizontally stretch a signal
<p>I have a dataframe with two columns. This is an example of signal that varies along depth:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({&quot;DEPTH&quot;:[5, 10, 15, 20, 25, 30, 35, 40, 45, 50], &quot;PROPERTY&quot;:[23, 29, 26, 17, 15, 20, 28, 25, 20, 17...
<python><matplotlib><signal-processing><scaling>
2023-09-01 17:28:38
1
702
user026
77,024,952
10,574,250
Sending email with python 3.10 not working with error EOF occurred in violation of protocol (_ssl.c:1007)
<p>I am trying to send an email using python 310 but am getting an error that I can't find a solution to. I should mention I am using a company proxy but this seems to work with python 3.8 so I'm not sure why it doesn't now. The code looks as such:</p> <pre><code>def send_email(): text = self.message.as_string() ...
<python><email><ssl><openssl><starttls>
2023-09-01 17:14:35
2
1,555
geds133
77,024,850
11,922,765
Download all xlsx files and metainformation from a website
<p>I am using kaggle browser. Looking to see if all the below can be done on this kaggle notebook.</p> <p>Website url: <a href="https://www.eia.gov/electricity/gridmonitor/dashboard/electric_overview/US48/US48" rel="nofollow noreferrer">click here</a></p> <p>Website screenshot:</p> <p><a href="https://i.sstatic.net/v0h...
<python><python-3.x><web-scraping><beautifulsoup>
2023-09-01 16:55:40
2
4,702
Mainland
77,024,812
2,441,441
Avoiding Spark withColumn when using complex column derivation logic
<p>I went through the link here <a href="https://stackoverflow.com/questions/70381876/why-is-my-code-repo-warning-me-about-using-withcolumn-in-a-for-while-loop">Why is my Code Repo warning me about using withColumn in a for/while loop?</a></p> <p>which says that we need to avoid withColumn, and use this instead:</p> <p...
<python><python-2.7><apache-spark><pyspark><apache-spark-sql>
2023-09-01 16:47:55
1
1,397
user2441441
77,024,785
22,434,294
How to clone lines with a specific condition?
<p>I have some hyperlinks in a text file. I want to compare the link on first line to next adjacent line and create links as per number?. For example,</p> <p>Consider below adjacent links</p> <pre><code>https://gp.to/ab/394/las69-02-09-2020/ https://gp.to/ab/394/las69-02-09-2020/4/ </code></pre> <p>Here the output file...
<python><r>
2023-09-01 16:43:03
2
577
nicholaspooran
77,024,725
7,086,220
Convert the path string from VSCode python into windows style
<p>The standard windows path string use backslash '\' to divide folders. In python, it is either converted to forward slash '/' or escaped to double backslash '\\'. Is there VSCode built-in trick or extension to covert between them? For now I have to copy it, and then paste it into a temporary new file, and then search...
<python><visual-studio-code><path><copy-paste>
2023-09-01 16:33:29
1
343
jerron
77,024,638
13,086,128
Logarithm to base 3 in python
<p>I am trying to find the logarithm of a number to base 3 using python.</p> <p>Here is the problem :</p> <p><a href="https://leetcode.com/problems/power-of-three/description/" rel="nofollow noreferrer">https://leetcode.com/problems/power-of-three/description/</a></p> <p>I am using this code:</p> <pre><code>import math...
<python><python-3.x><math><logarithm>
2023-09-01 16:17:20
2
30,560
Talha Tayyab
77,024,623
16,383,578
How to find extrema per cell in 3 dimensional array with Numba?
<p>I have recently written a script to convert BGR arrays of [0, 1] floats to HSL and back. I posted it on <a href="https://codereview.stackexchange.com/questions/286798/numpy-script-to-convert-bgr-to-hsl-and-back">Code Review</a>. There is currently one answer but it doesn't improve performance.</p> <p>I have benchmar...
<python><numpy><numba><jit>
2023-09-01 16:14:07
2
3,930
Ξένη Γήινος
77,024,602
13,129,731
How to execute two different functions concurrently in Python?
<p>I have two different functions (<code>funcA</code> and <code>funcB</code>) that I want to be executed concurrently to cut down on overall execution time.</p> <p><code>funcA</code> is an API call that takes somewhere between 5 to 7 seconds.</p> <p><code>funcB</code> is a CPU intensive operation that uses ML algorithm...
<python><python-asyncio><python-multiprocessing><python-multithreading>
2023-09-01 16:10:54
2
640
eNeM
77,024,542
12,334,809
Linking span to parent span using trace_id and span_id
<p>I have a go process which starts a parent span up. I then call an export function to save the span_id and trace_id in a json file.</p> <pre><code>tracer := otel.GetTracerProvider().Tracer(&quot;&quot;) _, span := tracer.Start(ctx, &quot;parent span name&quot;) exportSpanContextToJSON(span) ... defer span.End() </cod...
<python><go><open-telemetry>
2023-09-01 15:59:32
1
372
Randy Maldonado
77,024,475
6,655,075
Pandas dataframe update column for lowest x values in group?
<p>I have some race data in a csv file that looks like this:</p> <p><a href="https://i.sstatic.net/iCajh.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iCajh.png" alt="" /></a></p> <p>My aim is to update the 'FAV' for each race in the table relative to the 'BSP' value - lowest BSP = 1, 2nd lowest = 2. (...
<python><pandas><dataframe>
2023-09-01 15:47:27
1
474
Jeremy
77,024,117
11,136,668
My Firestore query always takes just over 20 seconds. Is there a hidden timeout or similar?
<p>I am having an issue with a Firestore query taking a long time to run.</p> <p>There are currently 2 records in the Firestore collection, but this query is always taking 20-21 seconds.</p> <p>This suggests to me that there is a sleep or a timeout that lasts 20 seconds somewhere.</p> <pre class="lang-py prettyprint-ov...
<python><database><firebase><google-cloud-firestore>
2023-09-01 14:51:32
1
904
Jeremy Savage
77,024,110
14,508,690
pynput: getting different outputs with pynput.keyboard.Listener.running (in "non-blocking fashion")
<p>In the &quot;non-blocking fashion&quot; of starting a <code>pynput</code> <code>Listener</code>, I'm getting different behaviors with the code below:</p> <pre><code>from time import sleep import pynput def stop(k): if k: print(&quot;end&quot;) l.stop() l = pynput.keyboard.Listener(on_press=sto...
<python><debugging><listener><pynput>
2023-09-01 14:50:20
1
399
101is5
77,024,058
11,197,301
find the time difference between adjacent value in padas
<p>I have this dataframe</p> <pre><code>date qq q_t l_t 1956-01-01 1 4 True 1956-01-02 2 5 True 1956-01-03 3 1 False 1956-01-04 4 1 False 1956-01-05 5 1 False 1956-01-06 6 10 True 1956-01-07 7 11 True 1956-01-08 8 12 True 1956-01-09 9 5 False 1956-01-10 10 3 False 1956-...
<python><pandas><date><operation>
2023-09-01 14:43:10
1
623
diedro
77,023,991
1,020,139
AWS Lambda Python 3.11: Cannot import lxml: libxslt.so.1: cannot open shared object file: No such file or directory
<p>I have a Python function on AWS Lambda that depends on <code>lxml</code>. The dependent layer includes the result of <code>poetry install lxml</code>, yet I receive the following error at runtime:</p> <pre><code> &quot;errorMessage&quot;: &quot;Unable to import module 'app.dim.application.watchdog': libxslt.so.1: c...
<python><amazon-web-services><aws-lambda><arm><lxml>
2023-09-01 14:34:02
3
14,560
Shuzheng
77,023,539
2,725,810
Transaction affects time of computation?
<p>Consider:</p> <pre class="lang-py prettyprint-override"><code>with transaction.atomic(): job = Job.objects.select_for_update().get(id=job_id) texts = pickle.loads(job.job_body) timer = Timer() print(&quot;Computing embedding for:&quot;, texts, flush=True) job.started = ms_now() result = get_e...
<python><django><performance><concurrency><transactions>
2023-09-01 13:32:41
0
8,211
AlwaysLearning
77,023,312
1,552,080
Python multithreading blocks unexpectedly
<p>I am developing a Python particle swarm optimizer application which exchanges messages with a Kafka broker. I want to send a message to the broker, where another application (will be JAVA) pick up the message, processes it and returns a result. The python applications needs to wait until the result is available. Cur...
<python><multithreading><events>
2023-09-01 12:58:25
0
1,193
WolfiG
77,023,270
15,923,186
Mask RGBA image with another one
<p>Consider there are two opencv images / numpy arrays of different shapes. Smaller one is called <code>small</code> and is <code>(150,150,4)</code>, bigger one is called <code>big</code> and is <code>(300,300,4)</code>, both are RGBA images. I'm trying to get the smaller one to be &quot;on top&quot; of the bigger one,...
<python><numpy><opencv>
2023-09-01 12:51:01
1
1,245
Gameplay
77,023,212
4,844,184
Dynamically decorating method of instance in Python
<p>I have recently come across <code>MethodType</code> which allows to do arguably hacky but fun stuff like:</p> <pre><code>from types import MethodType class MyClass(): def __init__(self, n : int): self.list_of_items = list(range(n)) def __getitem__(self, idx): return self.list_of_items[idx] ...
<python><methods><dynamic><instance>
2023-09-01 12:42:14
0
2,566
jeandut
77,023,101
13,219,123
'__init__.py' file in tests folder
<p>I am having problems with pytest my directory looks like below:</p> <pre><code>├── modules | ├── __init__.py │ ├── data | | ├── __init__.py │ | └── tables.py ├── tests │ └── test_tabels.py └── main.py </code></pre> <p>My problem was that I was getting a <code>Pytest Discovery Error</code>. When readin...
<python><pytest>
2023-09-01 12:25:22
0
353
andKaae
77,023,072
1,329,744
How to run a fully container-based Python dev environment in VSCode
<p>TL;DR: Why does this need to be started twice before it works?</p> <p>I am trying to set up a Python development environment in my VSCode. The app will run in a container in production, so why hassle with Python versions, virtualenvs and so on on my dev machine, when my editor is able to also use that very same cont...
<python><docker><remote-debugging><vscode-debugger><vscode-remote>
2023-09-01 12:21:48
1
1,553
mcnesium
77,022,836
13,100,938
Apache Beam: Wait N seconds after window closes to execute DoFn
<p>I have real time data being published and read into a Dataflow pipeline in a synchronous manner.</p> <p>I collect the data, window it (1 second fixed) with accumulation then write it to a Firestore DB. This DB is being watched by a front end and when new data arrives the front end automatically pulls in the snapshot...
<python><google-cloud-platform><google-cloud-firestore><google-cloud-dataflow><apache-beam>
2023-09-01 11:46:38
0
2,023
Joe Moore
77,022,582
12,040,751
Type hint for a special argument
<p>Consider the following function:</p> <pre><code>from datetime import date def days_between(start_date: date, end_date: date) -&gt; int: if start_date == &quot;initial&quot;: start_date = date(2023, 9, 1) delta = end_date - start_date return delta.days </code></pre> <p>The type hint of start dat...
<python><python-typing>
2023-09-01 11:05:29
1
1,569
edd313
77,022,574
3,312,274
Flask is not reacting to the FLASK_ENV variable setting
<p>I am trying to activate debug mode in Flask.</p> <p>What I have tried so far:</p> <ul> <li>set FLASK_ENV=development directly in Windows cmd</li> <li>pip installed python-dotenv successfully and set FLASKENV=development in .env file</li> <li>ensured that there is no dotenv package globally and within virtual env</li...
<python><flask><python-dotenv>
2023-09-01 11:04:42
1
565
JeffP
77,022,479
11,197,301
compare two dataframe according to the year and month
<p>I have two dataframe:</p> <p>dfr1</p> <pre><code> qq date 1956-01-01 685.519348 1956-01-02 731.868500 1956-01-03 510.579375 1956-01-04 412.347250 1956-01-05 358.297625 2010-12-27 3.992000 2010-12-28 1.099583 2010-12-29 104.428958 2010-12-30 4.932750 2010-12-31 101.73729...
<python><pandas><dataframe><datetime><operation>
2023-09-01 10:48:19
1
623
diedro
77,021,891
1,455,474
Parallel workers initialized with individual objects in Python
<p>I need a number of workers in Python that is initialized with an object. The main process will send commands+arguments to the workers that should then execute methods in their object and return the result in parallel.</p> <p>I have tried with multiprocessing.pool, but when calling pool.map, it seems random which pro...
<python><parallel-processing><multiprocessing>
2023-09-01 09:13:54
2
623
Mads M Pedersen
77,021,872
4,193,573
How do I find lines containing a specific string when it is not prefixed by another string with regex
<p>I am parsing some html files using a python script.</p> <p>As part of this parsing, I need to detect text which contains &quot;&lt;...#id=xxx&gt;&quot; or &quot;&lt;a id=xxx&gt;&quot;, but do not want to find text which contains &quot;&lt;....#bshid=xxx&gt;&quot; or &quot;&lt;a bshid=xxx&gt;&quot;</p> <p>In other wo...
<python><regex>
2023-09-01 09:10:59
1
461
didjek
77,021,797
9,751,398
How to bundle an FMU with a png-file that illustrates the system?
<p>I use FMU a lot for simulation of Modelica models in a Python environment. It would be nice to bundle the obtained FMU from compilation with a png-file that shows the system. Is that possible?</p> <p>And how to access that png-file and show it in a Jupyter notebook?</p>
<python><jupyter-notebook><fmi>
2023-09-01 09:00:15
3
1,156
janpeter
77,021,769
13,911,870
Pytest fixtures skipping test
<p>I have this factory as ficture:</p> <pre><code> @pytest.fixture def user_factory(db): def create_app_user( username: str, password: str = None, first_name: str = &quot;firstname&quot;, last_name: str = &quot;lastname&quot;, email: str = &quot;user@g.com...
<python><pytest><pytest-django><pytest-fixtures>
2023-09-01 08:54:17
1
360
DevolamiTech
77,021,739
5,300,978
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 147: invalid continuation byte
<p>I am trying to send a file and params to an endpoint of FastAPI, but i am getting the following error (on the title).</p> <p>My code</p> <pre><code>response = requests.post(url=f'{os.environ[&quot;URL&quot;]}/summarize', files=[('files', open(file[0].name, 'rb'))], p...
<python><fastapi>
2023-09-01 08:49:19
1
1,324
M. Mariscal
77,021,698
10,194,070
python + run sed command in python
<p>I created python3 module file ( <code>sed_util_conf.py</code> ) that include <code>sed</code> Linux command that replaced <strong>old</strong> string with <strong>new</strong> for example - key - <code>http-server.https.port</code> and value )</p> <pre><code>def run_cli(action_details, command_to_run): print(act...
<python><python-3.x><linux><sed>
2023-09-01 08:45:29
1
1,927
Judy
77,021,670
3,678,257
Storing a list of floats or integers in Redis Search
<p>I'm testing Redis vector search solution. I have install the Redis server and have been following these tutorials and documentation:</p> <ol> <li><a href="https://github.com/openai/openai-cookbook/blob/main/examples/vector_databases/redis/getting-started-with-redis-and-openai.ipynb" rel="nofollow noreferrer">https:/...
<python><search><redis>
2023-09-01 08:41:06
1
664
ruslaniv
77,021,604
2,876,079
How to switch between local and installed version of python package, including IDE support (PyCharm)?
<p>I develop a package fhg_isi and currently have installed version 0.0.1.</p> <p>What is the recommended way to switch between the local version 0.0.2 (being in development) and the installed version?</p> <p>I am already able to load the local version by modifying the system path (and If I want to use the installed ve...
<python><import><pycharm><package-management>
2023-09-01 08:30:25
1
12,756
Stefan
77,021,415
7,973,386
ModuleNotFoundError: No module named 'pytorch3d.io' in colab
<p>I was running this Google Colab today everything was working fine but eventually I starting getting these errors in the Set Up Environment. I can't find a fix. Any help would be appreciated let me know if I need to provide more info.</p> <p>Here is the link for the colab <a href="https://colab.research.google.com/dr...
<python><google-colaboratory>
2023-09-01 07:59:07
1
1,370
Balaji Venkatraman
77,021,379
5,821
How to validate deeply nested data structures using Pydantic?
<p>Suppose I have the following data structure:</p> <pre class="lang-py prettyprint-override"><code>{ &quot;code&quot;: 123, &quot;a&quot;: { &quot;b&quot;: { &quot;c&quot;: { &quot;d&quot;: { &quot;value&quot;: &quot;hello world&quot; } } } } } </code></pre> <p>And I...
<python><pydantic>
2023-09-01 07:53:08
2
45,522
Pēteris Caune
77,021,203
2,678,074
My hex values are converted to int while passing as args
<p>I am creating an usb connection, and this works.</p> <pre><code>device = usb.core.find(idVendor=0x47f, idProduct=0x2e6) </code></pre> <p>According to signature of the method, those arguments are passed to method as <em>args</em></p> <pre><code>def find(find_all=False, backend = None, custom_match = None, **args): </...
<python><integer><hex>
2023-09-01 07:17:37
1
845
user2678074
77,021,145
17,896,651
Migrate a django project to new server with already exists postgresql database of anotehr django project
<p>I have 2 django apps on separate servers.</p> <p>Both have completely different models</p> <p>The database name of app1 is xxxx1</p> <p>The database name of app2 is xxxx2</p> <p>how to migrate xxxx2 to server1 without damage anything ?</p>
<python><django><database><postgresql>
2023-09-01 07:06:42
1
356
Si si
77,021,140
1,852,526
pygithub search and read specific files
<p>I am using pyGithub to go through the files in the Github repository. The problem is, with this code <code>my_code.get_contents(&quot;&quot;)</code>, it goes through each and every file in all the folders and subfolders in the repo. Is there a way to make this code efficient. I am only interested in parsing the .csp...
<python><pygithub>
2023-09-01 07:05:23
1
1,774
nikhil
77,021,106
10,669,819
Is there anyway to generate doc strings for Python code using Github Copilot (VS Code)
<p>Is there anyway to generate doc string using Github Copilot</p> <p>I have code and I want to generate doc string for it.</p> <pre><code>def make_chat_content(self,chat_uuid,text,db_session): import uuid all_content = ChatContent.query.filter_by(chat_uuid=chat_uuid).all() chat_json = dump(all_content) ...
<python><visual-studio-code><github-copilot>
2023-09-01 06:56:20
2
580
Usman Rafiq
77,021,026
12,466,687
How to expand list columns into rows in polars?
<p>I am trying to <strong>expand the list column data</strong> into non list format in <code>Polars</code> but not able to do it.</p> <p><strong>dataframe</strong></p> <pre><code>import polars as pl pl_mtcars = pl.DataFrame({'model': ['Mazda RX4','Mazda RX4 Wag','Datsun 710','Hornet 4 Drive', 'Hornet Sportabout','Va...
<python><dataframe><python-polars>
2023-09-01 06:44:10
1
2,357
ViSa
77,020,991
10,170,808
Why the path is different between Python terminal in code editor vs after compiled into exe
<p>So I have this simple code in <code>C:\Work\Python Scripts\dfr_monthly\myfile.py</code></p> <pre><code>print(os.getcwd()) print(os.path.dirname(__file__)) </code></pre> <p>When I run this file from code editor (VSCode), the output in the python terminal is</p> <pre><code>(base) C:\Work&gt;C:/Users/coco/Anaconda3/pyt...
<python>
2023-09-01 06:37:21
1
791
random student
77,020,971
1,503,984
How to properly terminate or close a background task in aiohttp application?
<p>I'm writing an app using aiohttp and asyncio. One of the parts of the app is supposed to continuously monitor a specific device for incoming data. It works as expected except that I cannot close the app if no data comes from the device. Here's a stipped version of the code:</p> <pre class="lang-py prettyprint-overri...
<python><python-3.x><python-asyncio><aiohttp>
2023-09-01 06:34:26
0
446
miwa
77,020,925
10,232,932
Running a for-loop for the same function several times for a filtered dataframe, pythonic way to do that
<p>I am having an example pandas dataframe df:</p> <pre><code>TypeA TypeB timepoint value A AB 1 10 A AB 2 10 A AC 1 5 A AC 2 15 A AC 3 10 ... D DB 1 1 D DB 2 1 </code></pre> <p>How can I run a function sever...
<python><pandas><dataframe>
2023-09-01 06:25:23
1
6,338
PV8
77,020,917
22,070,773
How to add a submodule to an extension with nanobind?
<p>I want to be able to add a extension to my extension, so that I can do:</p> <p><code>import my_ext.sub_ext</code></p> <p>In order to split up the extension so that different sub components of the extension can be imported seperately.</p> <p>This is done in <code>Boost::python</code> like this:</p> <pre><code>bp::obj...
<python><c++><nanobind>
2023-09-01 06:23:53
1
451
got here
77,020,794
2,556,795
How to get last date along with its multiple rows
<p>I have a dataframe as below</p> <pre><code>import pandas as pd from io import StringIO df = pd.read_csv(StringIO(&quot;&quot;&quot; id date1 date2 101 2021-10-01 2021-09-01 101 2021-11-01 2021-10-01 101 2021-11-01 2021-12-01 102 2022-09-01 2022-09-01 102 2022-11-01 2023-01-01 103 202...
<python><python-3.x><pandas>
2023-09-01 05:59:45
3
1,370
mockash
77,020,618
882,512
Xampp on windows server trying php run a python script
<p>I am trying to execute a python script from php on windows server. I have read tutorials and answers here in SO but I can not make it work.</p> <p>My Script is:</p> <pre><code>$cmd = escapeshellcmd('c:/Windows/py.exe c:/xampp/htdocs/python.py'); echo shell_exec($cmd); </code></pre> <p>But it does not work.</p> <p>I ...
<python><php>
2023-09-01 05:02:33
1
753
Christoforos
77,020,444
22,070,773
How to manually build a nanobind extension?
<p>I am trying to manually build the example extension for nanobind:</p> <pre><code>// main.cpp #include &lt;nanobind/nanobind.h&gt; int add(int a, int b) { return a + b; } NB_MODULE(my_ext, m) { m.def(&quot;add&quot;, &amp;add); } </code></pre> <blockquote> <p>g++ -I/usr/include/python3.8 -I./nanobind/include ma...
<python><c++><nanobind>
2023-09-01 04:05:18
0
451
got here
77,020,430
8,075,540
Logging from QueueHandler not appearing until future.result() is called
<p>I'm playing around with <code>logging.handlers.QueueHandler</code> (I'm trying to integrate it into my pytest suite). Here's my MRE:</p> <pre class="lang-py prettyprint-override"><code>import concurrent.futures import logging import logging.handlers import multiprocessing import threading logging.basicConfig(level...
<python><logging><multiprocessing>
2023-09-01 04:00:58
1
6,906
Daniel Walker
77,020,338
9,300,659
Robot framework keywords are showing "No keyword with name xyz"
<p>I am new to robot framework and python, I am facing problem with the keywords, which shows me the error <code>No keyword with name xyz</code>. For an example in file <code>csv_handler.py</code></p> <pre><code>import all library and key words class csv_handler: @keyword(&quot;Extract text from CSV file&quot;) ...
<python><python-3.x><selenium-webdriver><robotframework><selenium-server>
2023-09-01 03:23:51
0
558
Satyajit Behera
77,020,319
7,058,869
Having Python Files in an R package- Where do I put it?
<p>I am working on a R package and for various reasons I need to write some code in Python.</p> <p>For my current workflow I have the various scripts sitting in the root directory which I run in my various R codes with <code>reticulate::py_run_file()</code> followed by <code>reticulate::py$my_function()</code> (not ide...
<python><r><r-package><reticulate><file-structure>
2023-09-01 03:17:47
1
1,076
Bensstats
77,020,278
12,931,358
How to load a huggingface dataset from local path?
<p>Take a simple example on Hugging Face: <a href="https://huggingface.co/datasets/Dahoas/rm-static" rel="nofollow noreferrer">Dahoas/rm-static</a></p> <p>If I want to load this dataset online, I just directly use:</p> <pre class="lang-py prettyprint-override"><code>from datasets import load_dataset dataset = load_data...
<python><huggingface><huggingface-datasets><huggingface-hub>
2023-09-01 03:03:06
4
2,077
4daJKong
77,020,135
955,091
How to create and compare syrupy snapshots in hypothesis's stateful testing?
<p>I want to create a <code>hypothesis.stateful.RuleBasedStateMachine</code> to run <a href="https://hypothesis.readthedocs.io/en/latest/stateful.html" rel="nofollow noreferrer">stateful testing</a> in Python. When the test is running, I want it to be deterministic and either update some snapshots or compare with exist...
<python><testing><python-hypothesis><property-based-testing><snapshot-testing>
2023-09-01 02:10:40
1
3,773
Yang Bo
77,020,014
17,197,068
How to select an option from fiba page using playwright
<p>I am trying to get the fiba world cup 2023 team stats where my country (Philippines) is one of the host nations.</p> <p>The url of the page is: <a href="https://www.fiba.basketball/basketballworldcup/2023/teamstats" rel="nofollow noreferrer">https://www.fiba.basketball/basketballworldcup/2023/teamstats</a></p> <p>Th...
<python><web-crawler><playwright-python>
2023-09-01 01:16:48
1
5,094
ferdy
77,019,852
433,202
Numpy `.astype` rounding up
<p>Similar to <a href="https://stackoverflow.com/questions/43910477/numpy-astype-rounding-to-wrong-value">Numpy astype rounding to wrong value</a> but that seemed like the opposite issue and is actually what I want (truncating). In my real world case I'm doing various calculations where some values could get very very ...
<python><numpy><floating-point>
2023-08-31 23:56:42
1
3,695
djhoese
77,019,827
2,153,235
PYTHONPATH not propagating from CMD to Spyder
<p>I installed PySpark under Anaconda by issuing the following commands at a Conda prompt:</p> <pre><code>conda create -n py39 python=3.9 anaconda conda activate py39 conda install openjdk conda install pyspark conda install -c conda-forge findspark </code></pre> <p>As can be seen, this is all within the <code>py39</co...
<python><pyspark><cmd><anaconda><spyder>
2023-08-31 23:46:36
1
1,265
user2153235
77,019,642
1,620,040
Converting custom string to dictionary python
<p>I have an example string from</p> <pre><code> kubectl get nodes -o wide </code></pre> <p>command output, which looks like</p> <pre><code> NAME STATUS ROLES AGE VERSION INTERNAL-IP cp-node-1 Ready control-plane xxx ...
<python><string>
2023-08-31 22:45:14
2
5,362
Lakshmi Narayanan
77,019,628
21,891,079
How to order facets when using the Seaborn objects interface
<p>I am trying to order facets in a plot produced by the <a href="https://seaborn.pydata.org/tutorial/objects_interface.html" rel="nofollow noreferrer"><code>seaborn</code> objects interface</a>.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import seaborn as sns import seaborn.objects as so im...
<python><seaborn><seaborn-objects>
2023-08-31 22:41:41
1
1,051
Joshua Shew
77,019,475
6,928,914
How to clear memory from a qlikview document programmatically?
<p>I have lots of Qlikview documents in various folders. I would like to delete all the memory from all these documents programmatically , say for example using FOR LOOP in a python program. How can I do that? Are there other ways to do that?</p>
<python><qlikview>
2023-08-31 21:56:03
2
719
Kay
77,019,330
22,407,544
Why is my Docx converter returning 'None'
<p>I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the translated document it cannot be opened.</p> <ol> <li><p>When I inspect the file type I saw it identified a...
<python><django><pdf><ms-word><pywin32>
2023-08-31 21:18:21
1
359
tthheemmaannii
77,019,152
17,653,423
How to flat a Series list of dictionaries in Dataframe?
<p>How can I convert a Series list of dictionaries into a DataFrame? Given:</p> <pre><code>import pandas as pd data = [ { &quot;id&quot;: 1, &quot;detail&quot;: [ { &quot;name&quot; : &quot;name1&quot;, &quot;type&quot; : &quot;type1&quot;, }, ...
<python><pandas><dataframe>
2023-08-31 20:39:58
3
391
Luiz
77,019,129
7,347,925
How to pcolormesh RGB array with cartopy?
<p>I have asked <a href="https://stackoverflow.com/q/70541279/7347925">similar question</a> about plotting RGB array on normal axis. The idea is plotting one channel of RGB array and set the facecolor by the combination of RGB.</p> <p>I wanna apply this method to axis with projection.</p> <pre><code>import numpy as np ...
<python><matplotlib><cartopy>
2023-08-31 20:34:58
0
1,039
zxdawn
77,018,924
259,538
Log Viewer wth Error Highlighting in Scrollbar
<p>I am working on a custom notepad style log viewer in Python 3.11 using PySide6.</p> <p>The ui is created with QtDesigner and must be compiled into python with pyuic command and is imported into the following code with import &quot;main_ui&quot;.</p> <p>The application loads a file called sample.log into a QPlainText...
<python><pyside6><pyqt6>
2023-08-31 19:58:47
1
7,959
panofish
77,018,917
12,466,687
How to convert column to list over groups in expressions in Polars?
<p>I am not able to create a <code>list</code> of values for each group from another column.</p> <p><strong>Data</strong></p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;A&quot;: [1,4,4,7,7,10,10,13,16], &quot;B&quot;: [2,5,5,8,18,11,11,14,17], &quot;C&quot;: [3,6,6,9,9,12,12,...
<python><dataframe><python-polars>
2023-08-31 19:57:53
2
2,357
ViSa
77,018,742
12,708,740
Use column names of one df to map values into rows of another df
<p>I am trying to map the values of one df (based on its column names) into the values of another df. Code below – however, here is also a screenshot to illustrate my question:</p> <p><a href="https://i.sstatic.net/aynaQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aynaQ.png" alt="enter image descript...
<python><pandas><dataframe><dictionary>
2023-08-31 19:27:31
3
675
psychcoder
77,018,692
12,611,330
Solving environment: failed when install RAPIDS using conda
<p>In order to install <code>RAPIDS</code>, I get the command from the site below and run it, but the following error occurs.</p> <p><a href="https://docs.rapids.ai/install" rel="nofollow noreferrer">https://docs.rapids.ai/install</a></p> <pre><code>conda create --solver=libmamba -n rapids-23.08 -c rapidsai -c conda-fo...
<python><conda><rapids>
2023-08-31 19:17:51
1
1,012
Tio
77,018,639
4,470,365
ModuleNotFoundError: No module named pyjanitor despite pyjanitor being installed
<p>I've confirmed the pyjanitor package is installed - it shows up in <code>pip list</code> and I get a confirmation if I try to reinstall with <code>pip install pyjanitor</code>. But then when I run <code>import pyjanitor</code> I get the error:</p> <blockquote> <p>No module named 'pyjanitor'</p> </blockquote> <p>Wha...
<python><pyjanitor>
2023-08-31 19:10:25
1
23,346
Sam Firke
77,018,585
181,238
Checking if "protected" links resolve
<p>I wrote a simple python script that goes over local HTML documents and text files and tries to check if all the links in them resolve.</p> <p>Basically, something similar to this (very simplified):</p> <pre><code>import re, requests with open(filename, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file: for line i...
<javascript><python><html><python-requests>
2023-08-31 18:57:58
1
1,976
Alex O
77,018,538
12,466,687
How to convert column to list in expressions in Polars?
<p>I was earlier able to convert column to <code>list</code> but it is not working now after the <code>latest version update</code>.</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;A&quot;: [1,4,4,7,7,10,10,13,16], &quot;B&quot;: [2,5,5,8,18,11,11,14,17], &quot;C&quot;: [3,6,...
<python><python-polars>
2023-08-31 18:50:25
1
2,357
ViSa
77,018,508
5,858,752
Iterating over dict of dicts vs (some other data structure) of dicts
<p>I'm looking at a codebase, and I see them iterating over only the values of a dict of dicts <code>d</code>. The only places where <code>d</code> is used, it's used with <code>itervalues()</code> (the code iterates over only the values of the dict), so the keys of <code>d</code> is never used, so I think they're just...
<python><arrays><list><dictionary>
2023-08-31 18:42:52
1
699
h8n2
77,018,494
4,443,378
How to normalize nested fields with json_normalizer()?
<p>I have a json with nested objects (nested list of objects): json:</p> <pre><code>{ &quot;uniqueIdentifier&quot;: { &quot;identity&quot;: { &quot;textIdentifier&quot;: &quot;MysticFoliage&quot;, &quot;encodedIdentifier&quot;: &quot;&lt;p&gt;MysticFoliage&lt;/p&gt;&quot; } ...
<python><json><pandas><json-normalize>
2023-08-31 18:40:55
1
596
Mitch
77,018,449
1,852,526
ET.fromstring gives ParseError
<p>I am trying to parse an XML string and I want just the PackageReference Include attribute details and the Version of it. When I say ET.fromstring(xml) it gives error like <code>xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 284, column 84</code>. I verified if the xml is valid on multiple we...
<python><xml><elementtree>
2023-08-31 18:32:59
2
1,774
nikhil
77,018,367
3,412,607
XSLT Pandas - How to Pull the Grandchild value to a Dataframe
<p>I'm trying to flatten an XML structure into a Pandas (Python) Dataframe using a custom XSLT with the read_xml function.</p> <p>Given the following XML Structure:</p> <pre><code>&lt;ml:Meals xmlns:ml=&quot;http://www.food.com&quot;&gt; &lt;ml:Meal&gt; &lt;ml:type&gt;lunch&lt;/ml:type&gt; &lt;ml:main_course&...
<python><pandas><xml><xslt><parent-child>
2023-08-31 18:20:14
2
815
daniel9x
77,018,312
8,844,970
Pytest: Specify different environments for different tests
<p>I am writing a long workflow for scientific data processing that uses Snakemake. Along the workflow, there are multiple scripts that use different environments. The folder looks something like this:</p> <pre><code>package |-- scripts | | | -- script1.py | -- script2.py |-- tests | | | -- test1.py | -- te...
<python><pytest>
2023-08-31 18:08:10
0
369
spo
77,018,288
6,099,211
sqlalchemy: how to customize standard type like DateTime() param binding processing for dialect?
<p>Given the following snippet</p> <pre><code>t = Table( &quot;foo&quot;, MetaData(), Column(&quot;bar&quot;, DateTime()), ) engine.execute(t.insert((datetime(1900, 1, 1),))) engine.execute(t.insert((&quot;1900-01-01&quot;,))) </code></pre> <p>the last statement works well for postgresql, while failing for...
<python><apache-spark-sql><sqlalchemy>
2023-08-31 18:03:18
2
1,200
Anton Ovsyannikov
77,018,174
9,318,372
Is it OK to have a mutable default argument if it's annotated as immutable?
<p>It is generally, for good reason, considered unsafe to use mutable default arguments in python. On the other hand, it is quite annoying to always have to wrap everything in <code>Optional</code> and do the little unpacking dance at the start of the function.</p> <p>In the situation when one want to allow passing <co...
<python><default-parameters>
2023-08-31 17:42:00
2
1,721
Hyperplane
77,018,149
38,975
How to read and store vector (List[float]) in Dask DataFrame?
<p>I am trying to have &quot;vector&quot; column in Dask DataFrame, from a large np.array of vectors (at this point it is 500k * 1536 vector).</p> <p>With Pandas DataFrame code would look something like this:</p> <pre><code>import pandas as pd import numpy as np vectors = np.array([ np.array([1, 2, 3]), np.ar...
<python><pandas><dataframe><dask>
2023-08-31 17:37:42
3
26,818
Mike Chaliy
77,018,145
1,708,550
python3 -m pip: Unverified HTTPS request is being made to host 'pypi.org'
<p>I am running <code>python3</code>:</p> <pre><code>python3 --version Python 3.9.2 </code></pre> <p>I was going to update local <code>pip</code> packages and for that I first checked which were outdated:</p> <pre><code>python3 -m pip list --outdated </code></pre> <p>This produced a warning message for each specific pa...
<python><pip><urllib3>
2023-08-31 17:37:22
1
1,848
Blitzkoder
77,018,079
9,942,944
Query parent objects and filter child lists without excluding parents
<p>I managed to query a list of <code>Parent</code> objects while at the same time filter each parent's list of children using <code>contains_eager()</code></p> <pre><code>stmt = select(Parent) stmt = stmt.outerjoin(Parent.child) stmt = stmt.filter(Child.a == None) stmt = stmt.options(contains_eager(DbStudy.milestones)...
<python><join><select><sqlalchemy><orm>
2023-08-31 17:25:42
0
919
Peter Petrus
77,018,045
8,378,817
How to load pdf files from Azure Blob Storage with LangChain PyPDFLoader
<p>I currently trying to implement langchain functionality to talk with pdf documents. I have a bunch of pdf files stored in Azure Blob Storage. I am trying to use langchain PyPDFLoader to load the pdf files to the Azure ML notebook. However, I am not being able to get it done. If I have the pdf stored locally, it is n...
<python><azure><azure-machine-learning-service><langchain><azureml-python-sdk>
2023-08-31 17:19:50
1
365
stackword_0
77,017,948
12,466,687
How to filter duplicates based on multiple columns in Polars?
<p>I was earlier able to <strong>filter duplicates</strong> based on <strong>multiple columns</strong> using <code>df.filter(pl.col(['A','C']).is_duplicated())</code> but after the latest version update this is not working.</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;A&quot;: [1,4,4,7,7...
<python><python-polars>
2023-08-31 17:05:48
2
2,357
ViSa
77,017,910
10,909,217
Why does the sum function not work with pyarrow fields?
<p>Consider the following list of fields.</p> <pre><code>import pyarrow.dataset as ds fields = [ds.field('a'), ds.field('b'), ds.field('c')] </code></pre> <p><code>sum(fields)</code> produces the following error:</p> <pre><code>TypeError: Argument 'self' has incorrect type (expected pyarrow._compute.Expression, got int...
<python><pyarrow>
2023-08-31 16:59:09
1
1,290
actual_panda
77,017,856
5,561,472
How to run transaction on every document in collection in Firestore
<p>I need to update the documents in collection. But I would like to run transaction for every document:</p> <pre class="lang-py prettyprint-override"><code>async def example(): @google.cloud.firestore.async_transactional async def update_in_transaction(transaction: AsyncTransaction, city_ref, data): tr...
<python><google-cloud-firestore>
2023-08-31 16:52:23
0
6,639
Andrey