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 ⌀ |
|---|---|---|---|---|---|---|---|---|
76,031,827 | 5,387,770 | Flattening of Nested dataframe | <p>I have a multi level nested dataframe something like the below:</p>
<pre><code>DataFrame[date_time: timestamp, filename: string, label: string, description: string,
feature_set: array<struct<direction:string,tStart:double,tEnd:double,
features:array<struct<field1:string,field2:string,field3:string,fiel... | <python><apache-spark><pyspark> | 2023-04-17 04:57:26 | 1 | 625 | Arun |
76,031,802 | 13,557,241 | Python Kubernetes Client: equivalent of kubectl api-resources --namespaced=false | <p>Via the CLI, I can use <code>kubectl api-resources --namespaced=false</code> to list all available cluster-scoped resources in a cluster.</p>
<p>I am writing a custom operator with the <a href="https://github.com/kubernetes-client/python" rel="nofollow noreferrer">Python Kubernetes Client API</a>, however I can't se... | <python><kubernetes> | 2023-04-17 04:51:31 | 3 | 323 | 0xREDACTED |
76,031,736 | 14,358,886 | Pandas - Table Pivot | <p>I currently have this table</p>
<p><a href="https://i.sstatic.net/1fduw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1fduw.png" alt="enter image description here" /></a></p>
<p>and want to get this output:
<a href="https://i.sstatic.net/lqTZl.png" rel="nofollow noreferrer"><img src="https://i.sstat... | <python><pandas><dataframe> | 2023-04-17 04:33:46 | 2 | 802 | Void S |
76,031,591 | 1,290,147 | Custom metric for a CatBoost classifier using GPU & optuna | <p>I have the following objective function to run in an Optuna hyper parameter optimization:</p>
<pre><code>def objective(trial, data=data):
num_train_pool = data["num_train_pool"]
num_test_pool = data["num_test_pool"]
true_labels_test = data["true_labels_test"]
param... | <python><machine-learning><classification><catboost><optuna> | 2023-04-17 03:47:09 | 1 | 5,137 | Luis Miguel |
76,031,569 | 3,398,324 | Merge PyTorch predictions to original dataframe | <p>I have obtained predictions from my PyTorch model as a tensor with the following shape (torch.Size([2958, 96])). My original dataset has 2958 qids and some of them have a max number of documents of 96 (min is 47). The predictions have padded the missing one with -1s. The shape of my original dataframe is (221567, 7)... | <python><pytorch><prediction> | 2023-04-17 03:39:59 | 2 | 1,051 | Tartaglia |
76,031,485 | 2,955,827 | Inherit function arguments definition in python | <p>If I have these two functions:</p>
<pre class="lang-py prettyprint-override"><code>def foo(code:int, *args, **kwargs):
if code == 1:
bar(*args, **kwargs)
else:
return None
def bar(a:str, b:int, c:int=1, d:int=2):
pass
</code></pre>
<p>I want users can see what argument can be passed to <... | <python><type-hinting> | 2023-04-17 03:13:42 | 0 | 3,295 | PaleNeutron |
76,031,409 | 3,713,336 | Fastest way to loop through GCP project | <p>I am trying to loop through GCP projects, where I have more than 50,000 projects and close to 20,000 buckets. However, what is the best way to make the loop faster? Here is my code below:</p>
<pre class="lang-py prettyprint-override"><code>for project in projects:
#print(project)
project = project['projectId... | <python><performance><google-cloud-platform><devops> | 2023-04-17 02:47:16 | 0 | 357 | lisa_rao007 |
76,031,309 | 12,311,071 | Is it possible to hint that a function parameter should not be modified? | <p>For example, I might have an abstract base class with some abstract method that takes some mutable type as a parameter:</p>
<pre class="lang-py prettyprint-override"><code>from abc import *
class AbstractClass(metaclass=ABCMeta):
@abstractmethod
def abstract_method(self, mutable_parameter: list | set):
... | <python><python-typing> | 2023-04-17 02:13:23 | 2 | 314 | Harry |
76,031,275 | 12,300,981 | How is the error of the solutions in your residuals incorporated in the error of minimized variables | <p>I have a pretty straight forward question. Given a system of equations</p>
<pre><code>x+y=1
x-y=2
x+2y=3
</code></pre>
<p>Find the values of x and y. A simple minimization problem.</p>
<pre><code>from scipy.optimize import minimize
import numpy as np
sol1=1
sol2=2
sol3=3
fun(k):
a=k[0]+k[1]
b=k[0]-k[1]
c... | <python><scipy><scipy-optimize> | 2023-04-17 02:02:42 | 0 | 623 | samman |
76,031,100 | 6,087,667 | pandas' `merge` drops levels on multiindex joins | <p>I don't understand why <code>merge</code> call below dropped the zero level <code>l0</code> while <code>join</code> didn't? I don't see that behavior described in the docs. Any explanation?</p>
<pre><code>import string
import pandas as pd
alph = string.ascii_lowercase
n=5
inds = pd.MultiIndex.from_tuples([(i,j) for... | <python><pandas><join><merge> | 2023-04-17 01:07:37 | 1 | 571 | guyguyguy12345 |
76,031,012 | 15,178,267 | Django: how to create a signal using django? | <p>I have a bidding system and there is an ending date for the bidding, i want users to bid against themselves till the ending of the bidding date.</p>
<p>The product creators are the ones to add the ending date which would be some date in the future, how can i write a django signal to check if the date that was added ... | <python><django><django-models><django-views> | 2023-04-17 00:41:52 | 1 | 851 | Destiny Franks |
76,030,877 | 1,884,367 | Problem with migrating Metropolis-Hastings algorithm from R to Python | <p>New to Python. I am trying to port the R code for the Metropolis Hastings Algorithm found <a href="https://stephens999.github.io/fiveMinuteStats/MH_intro.html" rel="nofollow noreferrer">here</a> over to Python. I have successfully duplicated the results in R, but am struggling with the Python version. I just can't... | <python><r><montecarlo><markov> | 2023-04-16 23:46:30 | 1 | 425 | user1884367 |
76,030,844 | 1,798,351 | how to get a human readable call stack from an ipynb error traceback['stack']? | <p>I'm hitting an error in a notebook and instead of showing a full call stack, it's a truncated stack with only the last few calls and the following message printed on top:</p>
<pre><code>Output exceeds the size limit. Open the full output data *in a text editor*
</code></pre>
<p>Which links to a text file like:</p>
<... | <python><exception><jupyter><stack-trace> | 2023-04-16 23:38:34 | 1 | 1,073 | mkk |
76,030,776 | 10,363,163 | How to get partial subtree depending on dependency relations with SpaCy? | <p>I have parsed the dependency relations of some text with SpaCy. How can I impose a condition relating to those dependency relations when extracting the subtree of a given token/span?</p>
<p>For example, I would like to get the subtree of a given token but exclude all portions of the subtree where the immediate child... | <python><graph-theory><spacy> | 2023-04-16 23:20:18 | 0 | 3,489 | dufei |
76,030,663 | 1,330,719 | Excluding fields on a pydantic model when it is the nested child of another model | <p>I have a pydantic model that I want to dynamically exclude fields on.</p>
<p>I can do this by overriding the <code>dict</code> function on the model so it can take my custom flag, e.g.:</p>
<pre class="lang-py prettyprint-override"><code>class MyModel(BaseModel):
field: str
def dict(self, **kwargs):
if ('ex... | <python><pydantic> | 2023-04-16 22:37:11 | 2 | 1,269 | rbhalla |
76,030,612 | 9,668,218 | How to compare two python files with the same name in different branches in GitHub? | <p>I have 2 versions of a Python code (python files with the same name) in 2 different branches in GitHub.</p>
<p>How can I compare these files in GitHub?</p>
<p>I am aware of <code>git diff</code> command but I am looking for a way to compare files in the repository user interface (instead of using git commands in the... | <python><github><compare><branch> | 2023-04-16 22:21:01 | 1 | 1,033 | Mohammad |
76,030,280 | 635,799 | How to import a module in Python unit test? | <pre><code>.
├── mymodule
│ ├── __init__.py
│ └── foo.py
├── tests
├── __init__.py
├── utils.py
└── test_module.py
</code></pre>
<p>I have the above directory structure for my Python package.</p>
<p>Within the <code>test_module.py</code> file, I need to import <code>tests/utils.py</code>. How should I ... | <python><import><pytest> | 2023-04-16 20:52:48 | 1 | 898 | Chang |
76,030,225 | 19,854,658 | How to select separate lines in a json file for json.loads()? | <p>Anyone know an effective way to select just one line at a time of this json file in Python?</p>
<p>I want to be able to write each line into a relational database but json.loads() throws an 'Extra Data' error if I don't select each line separately.</p>
<p>Thanks</p>
<pre><code>{"flight_date":"2023-04-... | <python><json> | 2023-04-16 20:40:05 | 1 | 379 | Jean-Paul Azzopardi |
76,030,177 | 11,388,321 | Wordpress REST API how to assign different categories to a post using Python requests library | <p>I've created a python script to create & post articles to WordPress site but it seems that the category in post data isn't getting assigned to the posts and it always gets assigned to <code>uncategorized</code> category, I am looking to only assign 1 category to the posts.</p>
<p>Am I doing something wrong here?... | <python><wordpress><python-requests><wordpress-rest-api> | 2023-04-16 20:31:03 | 3 | 810 | overdeveloping |
76,030,107 | 1,330,719 | Excluding pydantic model fields only when returned as part of a FastAPI call | <h2>Context</h2>
<p>I have a very complex pydantic model with a lot of nested pydantic models. I would like to ensure certain fields are never returned as part of API calls, but I would like those fields present for internal logic.</p>
<h2>What I tried</h2>
<p>I first tried using pydantic's <code>Field</code> function ... | <python><fastapi><pydantic><starlette> | 2023-04-16 20:15:06 | 2 | 1,269 | rbhalla |
76,029,974 | 3,323,394 | How to run blocking operations loops concurrently using python async? | <p>I have two unrelated blocking operations that listen to different events. When any of them return, I need to do an appropriate handling of the underlying event they raised.</p>
<p>For some reason, no matter how I schedule them using AsyncIO, I never get to run them concurrently. Apparently, <code>receive_json()</cod... | <python><websocket><redis><fastapi><starlette> | 2023-04-16 19:40:43 | 1 | 1,512 | Diane M |
76,029,891 | 16,067,738 | Python-Sql connection. Entries made in python terminal are not committing to the MySql server. Producing null table despite showing no error | <p>I am working on a small project which pertains the connectivity of python with MySql. What I have envisioned is that I will use Python to store the credentials like username and password to the database named <code>PENGUINX</code> I connected with MySql server. So far , my code looks clean and shows no error upon ex... | <python><mysql> | 2023-04-16 19:20:32 | 1 | 417 | LunaticXXD10 |
76,029,548 | 906,551 | Connecting to Bluetooth devices from Python for Windows? | <p>I've spent a good time searching, but cannot find a solution that does not require installing C++ compilers. Surely in 2023 there is a way to use Bluetooth from Python with pure Python or at least a pre-built module?</p>
| <python><windows><bluetooth> | 2023-04-16 18:15:09 | 1 | 349 | Scott Thibault |
76,029,219 | 629,283 | setting up docker with python 3.9 + poetry getting 'does not contain any element' | <p>I am trying to setup docker for local dev and i keep getting "does not contain any element" when i try to use poetry with docker. Originally I used the requirement.txt, however i would prefer it to have poetry because where i work we have a pyserver which we need to pull some of the .wh from.</p>
<p>So i a... | <python><docker><python-poetry> | 2023-04-16 17:08:49 | 1 | 349 | user629283 |
76,029,048 | 4,835,204 | Code crashes when put into separate functions within a class | <p>I've ran into an odd situation in Python where code works if I put everything in the <code>__init__</code> function of a class, but if I break it up into functions within the class, the otherwise identical code crashes. Here is my current example:</p>
<p>This works:</p>
<pre><code># SimpleDisplay5.py
import faulth... | <python><pangolin> | 2023-04-16 16:35:47 | 1 | 3,840 | cdahms |
76,029,005 | 4,458,718 | Docker wont install numpy on ubunty 18.04 but same docker ile runs just fine on sagemaker notebook instance | <p>I am trying to build an image using the docker file below (using this <a href="https://github.com/aws/amazon-sagemaker-examples/tree/main/advanced_functionality/scikit_bring_your_own" rel="nofollow noreferrer">example</a>). It works just fine on my notebook instance, but when I try to run it locally I get numpy erro... | <python><amazon-web-services><docker><numpy><amazon-sagemaker> | 2023-04-16 16:29:03 | 1 | 1,931 | L Xandor |
76,028,969 | 238,898 | PyPDF extract text from highlight annonations coordinates | <p>I want to extract the Text from Highlight Annotations.</p>
<p>PyPDF should be able to do this.<br />
They provide an example on how to get the coordinates for the Highlights:
<a href="https://pypdf.readthedocs.io/en/latest/user/reading-pdf-annotations.html#highlights" rel="nofollow noreferrer">https://pypdf.readthed... | <python><pypdf> | 2023-04-16 16:22:15 | 0 | 11,338 | TunaFFish |
76,028,844 | 10,313,194 | How to get post data from facebook page using python? | <p>I try to get post data from facebook page using Facebook Graph API like this.</p>
<p><a href="https://i.sstatic.net/5QuUB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5QuUB.png" alt="enter image description here" /></a></p>
<p>The output not show anything. So I try to use facebook-scraper like <a h... | <python><facebook> | 2023-04-16 16:03:37 | 1 | 639 | user58519 |
76,028,664 | 1,916,588 | asyncio to download data in batches and return a list of lists | <p>I want to download data in batches asynchronously.</p>
<p>The data for each <code>name</code> is downloaded in batches, and I'd like <code>asyncio.gather(*coroutines)</code> to return a list of lists (a list of batches for each name). So far I have this code, but it raises an exception:</p>
<pre class="lang-py prett... | <python><python-asyncio> | 2023-04-16 15:31:15 | 1 | 12,676 | Kurt Bourbaki |
76,028,639 | 1,609,066 | VSCode Python Testing `Test result not found for...` bug | <p>While working in a multi-project (VSCode would call it multi-root) python repository the VSCode python plugin for testing fails to run all the test when choosing to run all the tests, however running individual folders or tests passes. This is obviously a strange issue so I investigated this further.</p>
<p>The outp... | <python><pytest><vscode-extensions><vscode-python> | 2023-04-16 15:26:52 | 1 | 1,171 | Rijul Gupta |
76,028,597 | 13,723,501 | How can I send data from thread to Gtk app? | <p>I have the following code:</p>
<pre class="lang-py prettyprint-override"><code>import socket
from queue import Queue
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
import threading
HOST = '' # Listen on all available network interfaces
PORT = 5000 # Arbitrary port number
def sock... | <python><multithreading><sockets><gtk3> | 2023-04-16 15:18:10 | 1 | 343 | Parker |
76,028,510 | 12,832,931 | Convert Regularly Geographic Points into a matrix (keeping the correct order) | <p>Considering the following dataset:</p>
<pre><code>freguesia Datetime C1 latitude longitude geometry
0 Parque das Nações 2022-09-07 09:30:00+00:00 72.37 38.753769 -9.095670 POINT (-9.09567 38.75377)
1 Parque das Nações 2022-09-07 09:30:00+00:00 4.65 38.7... | <python><pandas><numpy><gis><geopandas> | 2023-04-16 14:59:52 | 1 | 542 | William |
76,028,482 | 359,178 | Python module defining constants for month numbers? | <p>The <code>calendar</code> module defines constants e.g. <code>MONDAY</code> (0), <code>TUESDAY</code> (1), etc. for the <a href="https://docs.python.org/3/library/calendar.html#calendar.MONDAY" rel="nofollow noreferrer">days of the week</a>.</p>
<p>And the source code even <a href="https://github.com/python/cpython/... | <python><datetime><calendar> | 2023-04-16 14:53:56 | 0 | 11,105 | Juan A. Navarro |
76,028,292 | 15,326,565 | POST a file and json object to FastAPI route | <p>I want to post a file and a json object to a route in my FastAPI in only one request, but doing so results in errors like:</p>
<pre><code>422
{"detail":[{"loc":["body"],"msg":"value is not a valid list","type":"type_error.list"},{"loc":[... | <python><json><http><file-upload><fastapi> | 2023-04-16 14:18:55 | 0 | 857 | Anm |
76,028,237 | 15,763,991 | Setting a timeout for Calculator code: How to handle high number calculations and prevent freezing | <p>I'm making a Calculator and the Code freezes when you try to calculate a high number (like 9⁹⁹⁹⁹⁹⁹) To counter this, I want to set a Timeout and if the calculation takes longer than 3 seconds, the result is just "NAN".
the Code snipped where the results are calculated looks like this, but it doesn't work. ... | <python><python-asyncio> | 2023-04-16 14:06:22 | 1 | 418 | EntchenEric |
76,028,127 | 595,305 | Suppress/redirect stack trace print out with logger.exception? | <p>A great way to process exceptions is to use <code>Logger.exception</code>:</p>
<pre><code>try:
do_something()
except BaseException:
logger.exception('some message')
</code></pre>
<p>... this not only prints out the user message, but also the exception message and exception type, and also a full stacktrace.</... | <python><exception><logging><stack-trace><stderr> | 2023-04-16 13:45:47 | 1 | 16,076 | mike rodent |
76,028,082 | 4,913,254 | Find duplicates in three columns and add plus 1 to results in another column | <p>I want to identify duplicate values in three columns and sum +1 in the results of another column.</p>
<pre><code># This is my data frame,
# I want to identify duplication in column1, column2 and column3
d = {
'Column1': ['1', '1', '2','3'],
'column2': [101, 101, 234, 203],
'column3': ['c', 'c', 'd','c'],
'columnx': ... | <python><pandas> | 2023-04-16 13:36:38 | 3 | 1,393 | Manolo Dominguez Becerra |
76,028,053 | 713,200 | How to remove preceding zeros in version numbers with alphabets using python? | <p>I have to read version numbers from a couple of servers and remove preceding 0s from it to match with expected version number.
My version number from server looks like these</p>
<pre><code>15.04.03a
4.05.03.034I
12.09.02a
4.09.1.028I
</code></pre>
<p>so I'm expecting output to be like <code>15.4.3a</code> and so on... | <python> | 2023-04-16 13:29:47 | 4 | 950 | mac |
76,028,018 | 12,828,984 | numpy roll produce a unnecessary horizontal line | <p>I have the following python code where I read from a CSV file a produce a plot. My goal is to shift the data in X-axis by some extend however the x axis is phase (between 0 - 1) and shifting in this context means rolling the elements (thats why I use numpy roll). My problem is that when I use numpy roll, It produces... | <python><numpy> | 2023-04-16 13:23:05 | 1 | 398 | Sara Krauss |
76,027,886 | 11,092,636 | Suffix Array, n^2*log(n) faster than n*log^2(n) even for large inputs? | <p>I learned this theory in class and decided to implement everything to make sure I understood it all; but the theoretical results don't align with the memory and time usages I obtain. I'm pretty sure this is not a shortcoming of theoretical algorithms but rather a mistake on my end and would like to investigate it.</... | <python><algorithm><suffix-array> | 2023-04-16 12:54:40 | 1 | 720 | FluidMechanics Potential Flows |
76,027,854 | 4,913,660 | Pandas Dataframe - compute mean on column k based on value on column j being the same, then remove duplicates | <p>Say I have a dataframe like this</p>
<pre><code>
columns = ["Col1", "Col2", "Col3"]
values = np.array([[1, 1, 7], [1,1, 8], [1, 2, 5],
[1, 2, 5.5]])
index = ["foo", "foo", "baz","baz"]
df = pd.DataFrame(values, index=index, col... | <python><pandas> | 2023-04-16 12:48:39 | 1 | 414 | user37292 |
76,027,790 | 3,103,957 | type object in Python | <p>In Python, I reckon object(s) are available for the type class and the object name is same as class name which is type.
I have a question regarding this... When we create classes using type(classname,base_class,att_dict), actually the <strong>call</strong>() method in type is getting invoked.
This will eventually pr... | <python><call><metaclass> | 2023-04-16 12:35:29 | 1 | 878 | user3103957 |
76,027,718 | 10,535,123 | Create new column when using Pandas groupby with two columns and aggregate by multiple metrices? | <p>The data itself is not realy matter.</p>
<p>I have the following code -</p>
<pre><code># convert timestamp to millisecond
relevant_data_pdf['milli'] = pd.to_datetime(relevant_data_pdf['timestamp']).astype(np.int64) / int(1e6)
# sort (day are values between 1 to 7)
relevant_data_pdf = relevant_data_pdf.sort_values([... | <python><pandas><dataframe> | 2023-04-16 12:21:01 | 1 | 829 | nirkov |
76,027,495 | 10,200,497 | creating a column based on values of two other columns | <p>This is my dataframe:</p>
<pre><code>df = pd.DataFrame({'a': [10, 20, 50], 'b': [5, 2, 20]})
</code></pre>
<p>And this is the output that I need:</p>
<pre><code> a b c
0 10 5 1005
1 20 2 1009.02
2 50 20 1109.922
</code></pre>
<p>I want to create column <code>c</code>. I have an initial value... | <python><pandas> | 2023-04-16 11:32:48 | 2 | 2,679 | AmirX |
76,026,821 | 8,586,803 | Cannot print numpy arrays with logging module | <p>This snippet doesn't print anything:</p>
<pre class="lang-py prettyprint-override"><code>import logging
import numpy as np
logging.info(np.eye(4))
# this doesn't work either
logging.info('matrix', np.eye(4))
</code></pre>
<p>But it works fine with native <code>print</code>:</p>
<pre class="lang-py prettyprint-over... | <python><numpy><logging><stdout> | 2023-04-16 09:05:50 | 1 | 6,178 | Florian Ludewig |
76,026,805 | 9,940,188 | Logging: How to use different formatters for different handlers? | <p>I'm trying to set up two logging handlers, one of which has a custom Formatter for exceptions. Here's what I've tried:</p>
<pre><code>import logging
def log_something():
log.error("Normal error")
try:
raise RuntimeError("Exception!")
except Exception as e:
log.excepti... | <python> | 2023-04-16 09:02:39 | 1 | 679 | musbur |
76,026,778 | 5,029,589 | Read only column names using python | <p>I have a excel file (Can be any type from csv,xsls,xslb) which can be very large (may be 500 mb) . I only want to get the column names from the file . Now I tried using pandas and get only column names ,but internally it seems to read or load the entire file which takes approx 1 minute . I don't want to load the ent... | <python><pandas> | 2023-04-16 08:54:36 | 1 | 2,174 | arpit joshi |
76,026,500 | 713,200 | How to extract data from html response using python? | <p>I'm trying to extract some of the data from an HTML response I'm getting after executing an API in Python. Here is the HTML response I get:</p>
<pre><code><?xml version="1.0" ?>
<mgmtResponse responseType="operation" requestUrl="https://6.7.7.7/motion/api/v1/op/enablement/ethernet/... | <python><html><json><python-3.x> | 2023-04-16 07:45:25 | 2 | 950 | mac |
76,026,337 | 2,051,572 | Pandas - merging rows under certain conditions | <p>I have a table in this form:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Cat A</th>
<th>Cat B</th>
<th>Year</th>
<th>Area</th>
<th>Names</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>C</td>
<td>2012</td>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>A</td>
<td>D</td>
<td>2012</td>
<td>2</td... | <python><pandas><group-by> | 2023-04-16 07:08:29 | 1 | 2,512 | Ohm |
76,026,333 | 11,210,476 | dataclass __annotation__ not working with inheritance | <p>I tried this code:</p>
<pre><code>from dataclasses import dataclass
@dataclass
class Data1:
d11: str
d12: float
@dataclass
class Data2:
d21: str
d22: float
@dataclass
class D3(Data1, Data2): pass
print(D3.__annotations__)
</code></pre>
<p>But the annotations for <code>D3</code> are only <code>{'d... | <python><dictionary><object><inheritance><python-dataclasses> | 2023-04-16 07:06:56 | 1 | 636 | Alex |
76,026,327 | 1,581,090 | How to use the same logger in different python modules? | <p>Here is what I have in the main code:</p>
<pre><code>from mf import gameplay
....
if __name__ == "__main__":
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create a file handler
handler = logging.FileHandler('example.log')
handler.setLevel(log... | <python><logging> | 2023-04-16 07:04:25 | 2 | 45,023 | Alex |
76,026,274 | 1,581,090 | How to fix "logging.ini" for python? | <p>I am following the tutorial on logging <a href="https://betterprogramming.pub/how-to-implement-logging-in-your-python-application-1730315003c4" rel="nofollow noreferrer">HERE</a> and also had a look at the documentation <a href="https://docs.python.org/3/library/logging.config.html#configuration-file-format" rel="no... | <python><logging> | 2023-04-16 06:46:56 | 1 | 45,023 | Alex |
76,026,112 | 610,569 | Is there a vectorize way to iterate through a fixed n of an input x dict instead the full range of n? | <p>Given a fixed size <code>n</code> and a <code>x</code> dict of input key-value pairs, the goal is iterate through 1...n (1st index), then fetch the values from x if the index exists as x's key, otherwise insert the value -1.</p>
<p>I've tried the following and it kind of work as expected:</p>
<pre><code>n = 10
# V... | <python><pandas><dictionary><vectorization> | 2023-04-16 05:56:27 | 2 | 123,325 | alvas |
76,025,977 | 15,320,579 | Perform some operation if 2 pandas dataframe have same entries in python | <p>I have 2 dataframes (<strong>purchase</strong> and <strong>sales</strong>) as follows:</p>
<p><strong>PURCHASE:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>item</th>
<th>voucher</th>
<th>Amt</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>Item1</td... | <python><pandas><dataframe><data-munging> | 2023-04-16 04:59:52 | 3 | 787 | spectre |
76,025,854 | 17,491,224 | Pandas fillna not successfully replacing nan values | <p>Attempting to fill na values in the following manner:</p>
<pre><code>df['column'].fillna(value='value',inplace=True)
</code></pre>
<p>I print the values before and after and get the following results:</p>
<pre><code>['11', '12', '81', '21', '22', nan, '41', '71', '10', '23', '02', '20', '19', '72', '24', '53', '60',... | <python><python-3.x><pandas> | 2023-04-16 04:09:14 | 1 | 518 | Christina Stebbins |
76,025,807 | 4,107,349 | Setting similarity threshold for trigram_similar Django PostgreSQL lookups? | <p>We're using <a href="https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/lookups/#trigram-similarity" rel="nofollow noreferrer">Django's trigram similarity</a> <code>__trigram_similar</code> lookup and it works nicely, except we want to adjust the similarity threshold and don't know how. Queries are currently... | <python><django><postgresql><django-views><django-queryset> | 2023-04-16 03:46:18 | 1 | 1,148 | Chris Dixon |
76,025,419 | 2,661,251 | Python string check against a particular pattern | <p>My requirement is that I want to print true if the string matches with the word "develop" or "develop[0-9]" . This is the python code I wrote</p>
<pre class="lang-py prettyprint-override"><code>import re
# Target String one
str = ["develop","develop1","develop123&qu... | <python><regex> | 2023-04-16 00:47:37 | 2 | 516 | gcpdev-guy |
76,025,370 | 5,394,072 | optimization - scipy minimize with contraints on returned values | <p>I have a function for weekly revenue, which is function of few variables (say variables are spend on different days of week, sunday through saturday). Now, I need to find the values of the variables that maximizes the weekly revenue.</p>
<p>In addition to above, I also need to have a constraint on the <code>total re... | <python><optimization><mathematical-optimization><scipy-optimize><scipy-optimize-minimize> | 2023-04-16 00:26:34 | 0 | 738 | tjt |
76,025,305 | 18,533,248 | dynamically calling an ffi function in python? | <p>I'm writing a simple program that needs to reach out to libc for some functions. My problem is that I don't know what these functions are when writing the program ie. the functions that will be called are imported dynamically, based on some user input.</p>
<p>How can I do this? Ideally I'd like to have a python dict... | <python><shared-libraries><dllimport> | 2023-04-16 00:02:43 | 1 | 501 | kamkow1 |
76,025,304 | 12,035,739 | Why is my PNG being read as black and white? | <p>I am reading this picture,</p>
<p><a href="https://i.sstatic.net/PcjMu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PcjMu.png" alt="enter image description here" /></a></p>
<p>Using the following Python,</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from PIL import Image as... | <python><numpy><matplotlib><python-imaging-library> | 2023-04-16 00:01:14 | 3 | 886 | scribe |
76,025,232 | 2,266,881 | Click event function not working in PyQT6 when added dynamically | <p>I'm creating a bunch of QPushButton's in PyQt6 dynamically in a loop. They all use the same target function and the only difference between them is one argument they are receiving, but for some reason, when i assign them dynamically, the all get the arg of the last one assigned.</p>
<p>Doing this:</p>
<pre><code>for... | <python><pyqt6> | 2023-04-15 23:36:40 | 0 | 1,594 | Ghost |
76,025,196 | 480,118 | how to gracefully kill all processes created by a python subprocess call to script which creates child processes (script, java, tee) | <p>This gets a bit complicated. But in short i have a python script that calls a bash script which launches a long running java process via yet another bash script. i've written another python process that will allow me to kill the process if need be. The problem im having is that i see the processes for the two shel... | <python><linux><bash><shell><sh> | 2023-04-15 23:23:59 | 0 | 6,184 | mike01010 |
76,025,129 | 6,063,706 | Custom Pytorch function with hard clamp forwards and softclamp backwards | <p>I want to implement a custom differentiable function in PyTorch that acts like torch.clamp in the forward pass but in the backward pass outputs the gradients as if it where a tanh.</p>
<p>I tried the following code:</p>
<pre><code>import torch
class ClampWithGrad (torch.autograd.Function):
@staticmethod
... | <python><pytorch> | 2023-04-15 22:59:02 | 1 | 1,035 | Tob |
76,025,095 | 165,659 | Can't correctly decode an image frame using PyAV | <p>I'm trying to simply encode and decode a capture frame from the web-cam. I want to be able to send this over TCP but at the moment I'm having trouble performing this just locally.</p>
<p>Here's my code that simply takes the frame from the web-cam, encodes, then decodes, and displays the two images in a new window. T... | <python><ffmpeg><pyav> | 2023-04-15 22:47:51 | 2 | 2,205 | Martin Blore |
76,025,067 | 19,003,861 | How to call variable processed in forloop function (views) in django template? | <p>I am trying to refer a variable <code>modela_completed</code> in my django template after some logic was applied to it.</p>
<p>Since it seems templates are only a place for making a page look nice, there must be a way to assign a value to a variable in a forloop and refer it into the template.</p>
<p><strong>models<... | <python><django><django-views><django-templates> | 2023-04-15 22:39:23 | 2 | 415 | PhilM |
76,025,059 | 124,367 | Python - Cannot upgrade pip or install any packages due to SSL Certificate errors | <p>I have a company-owned Windows machine with Python 3.11.2. Pip is version 22.3.1 (as I write this, the current version is 23.1). The local Python folder is <code>C:\Users\{User}\AppData\Local\Programs\Python\Python311</code></p>
<p>If I try to upgrade pip or install any packages, I get an SSL Error. For example, run... | <python><python-3.x><pandas><ssl><pip> | 2023-04-15 22:36:05 | 1 | 11,801 | PowerUser |
76,024,738 | 10,327,984 | RuntimeError: running_mean should contain 1 elements not 200 | <p>I am implementing a conditional gan for image generation with text embedding from scratch and I am getting the above error exactly in the BatchNorm1d layer from the embedding_layers in the generator <br>
generator class :</p>
<pre><code>import torch.nn as nn
class Generator(nn.Module):
def __init__(self, embedd... | <python><pytorch><generative-adversarial-network> | 2023-04-15 20:59:58 | 2 | 622 | Mohamed Amine |
76,024,686 | 12,603,110 | Pytorch Lambda Transforms and pickling? | <p>I am beginning to read and experiment with Pytorch recently and I saw that the transform module has a <code>Lambda</code> class. currently as far as I am aware composing transforms requires just a callable and a plain lambda can suffice.</p>
<p>What's the purpose of the <code>Lambda</code> class if python lambdas wo... | <python><pytorch><pickle> | 2023-04-15 20:47:19 | 0 | 812 | Yorai Levi |
76,024,680 | 1,028,162 | Problems with immidiate concistency in terraform AWS lambda layer | <p><br />
I'm having trouble configuring my tf insrastructure of AWS Lambda + Lambda Layer. I'll start with what I want to achieve: I want to implement a Lambda that uses a Layer for dependencies (in my case - using python - installed from <code>requirements.txt</code>), and I want the layer to be built and uploaded <s... | <python><aws-lambda><terraform><terraform-provider-aws> | 2023-04-15 20:46:34 | 1 | 839 | A. Kali |
76,024,643 | 817,659 | Pass MySQLDB connection to SQLAlchemy | <p>If I create a connection that works to <code>MySQL</code> using MySQLdb like this:</p>
<pre><code>connection = MySQLdb.connect(
host= os.getenv("HOST"),
user=os.getenv("USERNAME"),
passwd= os.getenv("PASSWORD"),
db= os.getenv("DATABASE"),
... | <python><sqlalchemy><mysql-python> | 2023-04-15 20:40:31 | 0 | 7,836 | Ivan |
76,024,591 | 11,388,321 | How can I post response to WordPress via REST API? | <p>I'm trying to post OpenAI's response (content message) as the content for my WordPress post, however, the WordPress part of my code doesn't seem to work, I've played around with doing it different ways but no post is created as a draft, how can I get OpenAI's response as the content of my drafted WordPress post?</p>... | <python><wordpress> | 2023-04-15 20:25:53 | 0 | 810 | overdeveloping |
76,024,288 | 12,724,372 | Problems installing quantlib in python | <p>I'm trying to install <code>quantlib</code> in python, using <code>pycharm</code>. But I'm receiving this error:</p>
<pre><code>ERROR: Could not find a version that satisfies the requirement QuantLib (from versions: none)
ERROR: No matching distribution found for QuantLib
[notice] A new release of pip available: 22... | <python><quantlib> | 2023-04-15 19:15:29 | 2 | 1,275 | Devarshi Goswami |
76,024,251 | 3,475,434 | hatch and scripts entry point in Python | <p>I need a script to be produced by installing the package and to be put in user <code>PATH</code>. I've followed the <a href="https://hatch.pypa.io/latest/config/metadata/#entry-points" rel="nofollow noreferrer">Hatch guide on entry points</a> and my directory looks like this:</p>
<pre><code>.
├── docs
│ ├── conf.p... | <python><program-entry-point><hatch> | 2023-04-15 19:07:39 | 0 | 3,253 | Luca Braglia |
76,024,248 | 13,903,942 | Java | Safest way to close resources | <h2>Question</h2>
<p>What's the best way / safest way to close a 'i/O resource' in Java?</p>
<h3>Context</h3>
<p>Coming from python background, which uses the <code>with</code> which creates a <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" rel="nofollow noreferrer">Context Manager</a> st... | <python><java><memory-leaks><io><resources> | 2023-04-15 19:06:34 | 2 | 7,945 | Federico Baù |
76,024,167 | 10,200,497 | Creating a new column based on values of two other columns | <p>This is my dataframe:</p>
<pre><code>df = pd.DataFrame({'a': [10, 20, 50], 'b': [5, -2, 20]})
</code></pre>
<p>And this is the output that I want:</p>
<pre><code> a b c
0 10 5 105
1 20 -2 20.58
2 50 20 12.348
</code></pre>
<p>I have an initial value which is 1000. The first row of <code>... | <python><pandas> | 2023-04-15 18:51:56 | 2 | 2,679 | AmirX |
76,024,153 | 5,636,889 | Retrieve large objects with multiprocessing.Pipe | <p>I'm current working in a RAM monitoring decorator:</p>
<pre><code>import time
import asyncio
import multiprocessing as mp
import psutil
import numpy as np
class MemoryMonitor:
def __init__(
self,
threshold=115343360, # Bytes
delay=1 # Seconds
):
self.threshold... | <python><asynchronous><multiprocessing><out-of-memory><psutil> | 2023-04-15 18:50:35 | 0 | 525 | Jose |
76,024,129 | 2,946,746 | ERROR in using beautiful Soup to extract SEC filling header information with returning NONE | <p>When I'm trying to use beautiful soup to get the header information from the SEC I'm getting a a return value of none. The tag I'm using is <code>"<SEC-HEADER>"</code>.</p>
<p>Any idea on how to get this code work correctly?</p>
<p>My code is:</p>
<pre><code>
import requests
from bs4 import Beautiful... | <python><beautifulsoup> | 2023-04-15 18:46:01 | 1 | 1,810 | user2946746 |
76,024,124 | 11,397,243 | Python "import as" changing global namespace | <p>I'm automatically translating some perl code to python with my <a href="https://github.com/snoopyjc/pythonizer" rel="nofollow noreferrer">pythonizer</a> tool. The perl code uses the Date::Manip package, which has a submodule Date::Manip::Date. I use a <code>Date</code> variable (which I defined in <code>builtins</... | <python><import><global><python-module> | 2023-04-15 18:45:13 | 1 | 633 | snoopyjc |
76,023,998 | 3,116,231 | Create an Azure Keyvault with Python | <p>I'm trying to create a keyvault with Python by running the code from <a href="https://github.com/Azure-Samples/key-vault-python-manage" rel="nofollow noreferrer">here</a>:</p>
<pre><code>import os
import json
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.keyvault import KeyVaultMan... | <python><azure-active-directory><azure-keyvault> | 2023-04-15 18:19:15 | 1 | 1,704 | Zin Yosrim |
76,023,938 | 10,200,497 | Creating a new column that shows percent change based on values of another column | <p>This is my dataframe:</p>
<pre><code>df = pd.DataFrame({'a': [10, 20, 50]})
</code></pre>
<p>And this is the output that I want:</p>
<pre><code> a b
0 10 100
1 20 20
2 50 10
</code></pre>
<p>I have an initial value which is 1000. Then I want to create column <code>b</code>. The first row ... | <python><pandas> | 2023-04-15 18:07:42 | 1 | 2,679 | AmirX |
76,023,916 | 13,955,154 | Layer "decoder" expects 1 input(s), but it received 3 input tensors | <p>I'm trying to train an autoencoder (and actually the fit seems to go correctly). Then I want to test my models:</p>
<pre><code>encoded_imgs = encoder.predict(images[:10])
decoded_imgs = decoder.predict(encoded_imgs)
</code></pre>
<p>where images is an array of images (224,224) and the latent vector is equal to 1024.... | <python><tensorflow><keras><autoencoder> | 2023-04-15 18:03:32 | 1 | 720 | Lorenzo Cutrupi |
76,023,766 | 20,266,647 | MLRunPreconditionFailedError: 412 Client Error, "API is waiting for migrations to be triggered" | <p>I got this error:</p>
<pre><code>MLRunPreconditionFailedError: 412 Client Error: Precondition Failed for url: http://localhost:8080/api/v1/projects: Failed creating project tutorial-<name> details:
MLRunPreconditionFailedError('API is waiting for migrations to be triggered. Send POST request to [/api/operatio... | <python><mlops><mlrun> | 2023-04-15 17:38:36 | 1 | 1,390 | JIST |
76,023,652 | 17,724,172 | Trouble with assigning colored categories on a broken bar chart | <p>Why am I getting such extended final colors (green) parts to these bars?</p>
<p>Each GUI box should take two comma-separated integers for start and duration of that category. The numbers should get a little larger for each category, so that the colors don't overlap. This can be entered in all the rows of the GUI, ... | <python><matplotlib> | 2023-04-15 17:14:04 | 1 | 418 | gerald |
76,023,593 | 713,200 | Storing a value from ios-xe router command output in python | <p>After making a connection to a cisco device using python, and executing a command I get a output as shown below,
Basically I want to get only one value, that the value for <code>Services</code> which is shown as <code>1</code> below and store it in a variable.</p>
<pre><code>#show ethernet cfm domain brief
Domain Na... | <python><python-3.x><list><dictionary><cisco-ios> | 2023-04-15 17:01:06 | 1 | 950 | mac |
76,023,559 | 4,172,765 | Python selenium waiting to download file completely | <p>I am writing code to download an Android APK file. It worked. However, I faced trouble in the process of waiting for the file to download completely. I want to download many files, and each file has a different size, so I can't set the <code>time.sleep(time)</code> in general.</p>
<p>I try to combine a <code>Thread... | <python><python-3.x><selenium-webdriver> | 2023-04-15 16:53:07 | 1 | 917 | ThanhLam112358 |
76,023,557 | 3,070,181 | Can I create an executable Python zip archive with dependencies? | <p>I have a small python application developed on Nix that I wish to distribute to some M$ Windows users. It seems that an <a href="https://docs.python.org/3/library/zipapp.html" rel="nofollow noreferrer">executable Python zip archive</a> is an excellent way to achieve this.</p>
<p>However, I would like to include dep... | <python><python-packaging><zipapp> | 2023-04-15 16:52:34 | 2 | 3,841 | Psionman |
76,023,530 | 3,034,631 | All other transforms disappear after broadcasting my custom odom to base_link transform (ROS2 Foxy) | <p>I have made a node to broadcast the odometry transform and publish the odometry topic.
Before I run this new node, everything looks good. However, when I run my odometry node, and broadcast the tf odom to base_link, all other transforms to base_link disappear.</p>
<p>I have searched the internet a lot but I can't fi... | <python><ros> | 2023-04-15 16:47:03 | 1 | 342 | guidout |
76,023,269 | 5,561,875 | How to apply a rotation to a node in trimesh | <p>I have a <code>.glb</code> glTF file that specifies a character.
The character has 75 nodes, and no animation track.</p>
<p>I wrote the following code to render the character, and now I would like to apply some rotation to specific nodes before I render it.</p>
<p>My rendering code is:</p>
<pre class="lang-py pretty... | <python><gltf><trimesh> | 2023-04-15 15:43:55 | 1 | 6,344 | Amit |
76,023,246 | 15,724,084 | inside nested loops appending list to a new list gives unexpected result | <p>I have tried to write my error issue in reproducible manner for platform to be seen and guided. I cannot see my logic gap why this error happens.
I have a inner loop which brings new elements while scraping and appends it to list named <code>list_inner</code>. Then in outer loop list named <code>list_outer</code> ap... | <python> | 2023-04-15 15:39:36 | 2 | 741 | xlmaster |
76,023,235 | 19,553,193 | Cannot reinitialise DataTable in Django | <p>I'm confused on how can I infuse my json format from django to Datatable , what I tried below using loop in the script</p>
<p><code>{% for json in company %}</code> <code><script>..</script></code> <code>{% endfor% }</code></p>
<p>but It persist error <code>DataTables warning: table id=DataTables_Tabl... | <python><django> | 2023-04-15 15:36:57 | 1 | 335 | marivic valdehueza |
76,023,117 | 1,488,363 | Scrapy in python - save within the parse function -thread safe? | <p>I'm using scrapy to download pages. I would like to save all the downloaded pages in a single file. I have the following code for the constructor and parse:</p>
<pre><code> def __init__(self):
self.time = time_utils.get_current_time_hr()
self.folder = f"{ROOT_DIR}/data/tickers/scrapy/{self.ti... | <python><scrapy> | 2023-04-15 15:13:30 | 1 | 1,554 | dotan |
76,023,089 | 20,646,254 | How to connect DigitalOcean Function to MySQL? | <p>I have created a simple Python Function (section Functions and NOT Apps). The function needs to access the MySQL database (the database is also created on DigitalOcean). When running the function I get an error: "2023-04-15T13:55:42.402632917Z stderr: The function exceeded its time limits of 6000 milliseconds. ... | <python><function><digital-ocean> | 2023-04-15 15:07:33 | 1 | 447 | TaKo |
76,023,085 | 912,873 | Native messaging not working from host to chrome extension | <p>I am working on a chrome extension native messaging with the host on Python. The communication from extension to python works perfectly fine. But when I am trying to send the message from the host to the extension, it is not working. I am getting no errors. Even I have enabled logging for the browser. I have tested ... | <javascript><python><google-chrome><google-chrome-extension><chrome-native-messaging> | 2023-04-15 15:06:55 | 0 | 2,841 | pvnarula |
76,022,985 | 7,987,455 | Web Scraping by BeautifulSoup if the data shown only if I click "show details" | <p>I am trying to scrape data from selling cars website, when I enter the website I see a table of cars (type, price, year), but if I want to know more details about the car I have to click on the car and then it shows more details. How can i scrape data from the those details without Selenium?</p>
<pre><code>import he... | <python><web-scraping><beautifulsoup> | 2023-04-15 14:51:31 | 1 | 315 | Ahmad Abdelbaset |
76,022,890 | 6,528,055 | Why are my deep learning models giving unreasonably high accuracy on test data? | <p>I'm trying to do sarcasm detection on Twitter data to replicate the results mentioned in this <a href="https://aclanthology.org/2020.wnut-1.2.pdf" rel="nofollow noreferrer">paper</a>. Binary classification problem. For that I used a separate set of <strong>unlabeled</strong> tweets to create the embedding matrix usi... | <python><keras><deep-learning><nlp><text-classification> | 2023-04-15 14:34:58 | 0 | 969 | Debbie |
76,022,501 | 1,804,027 | How can I capture raw messages that are coming out to OpenAI API? | <p>I'm using LangChain to build prompts that are later sent to the OpenAI API. I've built an agent, but it's behaving a bit differently than I expected. It looks like it's missing some of my instructions that I included in the prompt. Specifically: it seems to not remember past messages. I'm looking for a way to debug ... | <python><openai-api><langchain> | 2023-04-15 13:15:59 | 2 | 11,299 | Piotrek |
76,022,365 | 13,078,279 | Why does the jacobian of the metric tensor give zero? | <p>I am trying to compute the derivatives of the <a href="https://en.wikipedia.org/wiki/Metric_tensor" rel="nofollow noreferrer">metric tensor</a> given as follows:</p>
<p><img src="https://quicklatex.com/cache3/e6/ql_b24e8838c420fed42f5ae46a5346c9e6_l3.png" alt="Metric tensor in spherical coordinates" /></p>
<p>As par... | <python><pytorch><autograd> | 2023-04-15 12:49:01 | 1 | 416 | JS4137 |
76,022,351 | 885,764 | Python lists always assign reference not value | <p>I want to copy list values to another list because I modify the original one and use the new one. Bu t whatever I try it will alwasy assign reference not value.</p>
<pre><code>class Chromosome:
def __init__(self):
self.matrix = [[0 for x in range(LENGTH)] for y in range(LENGTH)]
class Population:
... | <python><python-3.x><list><reference> | 2023-04-15 12:44:48 | 1 | 2,234 | Hakan SONMEZ |
76,022,291 | 13,492,584 | Get list of latest installed python packages | <p>I am trying to get an ordered list of the lastest installed packages in Python. I am using pip (I cannot use -conda or terminal). The instruction <code>pip list</code> returns all the packages I have ever installed. Since I installed a package which damaged the older ones, I need the list of the latest installed pac... | <python><pip><package> | 2023-04-15 12:32:25 | 2 | 644 | hellomynameisA |
76,022,237 | 2,663,585 | working examples of js.amcharts in python | <p>I came across this <a href="https://pypi.org/project/js.amcharts" rel="nofollow noreferrer">link</a> for using js.amcharts in python, but couldn't find any working examples of the same. I did try googling but no luck. Can someone please help me on this? I like the 3d charts in amcharts and thus want to generate a PD... | <python><amcharts> | 2023-04-15 12:20:33 | 1 | 2,561 | Iowa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.