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,628,449 | 17,639,970 | how to scramble an image into regular patches? | <p>I need to patch images into let say 3x3 patches, or any regualr patches, then shuffle them and after that reassemble the image. I tried to use <code>patchify</code> but it gives eerror for unpatchify.</p>
<pre><code>import numpy as np
from PIL import Image
from patchify import patchify, unpatchify
import matplotlib.pyplot as plt
from random import shuffle
import torch
import torchvision
import torchvision.transforms as transforms
import requests
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Resize((224,224)),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
url = 'https://hips.hearstapps.com/hmg-prod/images/bright-forget-me-nots-royalty-free-image-1677788394.jpg'
image = Image.open(requests.get(url, stream=True).raw)
plt.imshow(transform(image).permute(1,2,0))
</code></pre>
<p>I looks like the following before shuffling or patchfying</p>
<p><a href="https://i.sstatic.net/8laD5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8laD5.png" alt="enter image description here" /></a></p>
<pre><code>patched_image = patchify(np.array(image), (100, 100, 3), 100)
shuffled_patches = np.random.shuffle(patched_image)
output_image = unpatchify(shuffled_patches, np.array(image).shape)
</code></pre>
<p>The error message:</p>
<pre><code>AttributeError Traceback (most recent call last)
<ipython-input-34-0b9963e642b8> in <cell line: 1>()
----> 1 output_image = unpatchify(shuffled_patches, np.array(image).shape)
/usr/local/lib/python3.10/dist-packages/patchify/__init__.py in unpatchify(patches, imsize)
52 """
53
---> 54 assert len(patches.shape) / 2 == len(
55 imsize
56 ), "The patches dimension is not equal to the original image size"
AttributeError: 'NoneType' object has no attribute 'shape'
</code></pre>
| <python><python-3.x><numpy><pytorch> | 2023-07-06 11:39:01 | 1 | 301 | Rainbow |
76,628,399 | 19,130,803 | Celery: one task at a time | <p>I am using <code>celery</code> in my Python web project. I have 2 pages on which 2 different long running functions are there as tasks. Both these functions have or share a common queue.</p>
<p>What I am trying to achieve is the following:</p>
<p>When a task runs or is started from any page, if the user switches to another page and tries to start the task from that page (default behavior: this tasks gets added to the queue) I want to display a message "one task is already in progress, try after some time" and thereby user will have to click the button again later to initiate the task.</p>
<p>I tried setting <code>--concurrency=1</code></p>
<p>Are there any more settings that I need to set?</p>
| <python><celery> | 2023-07-06 11:34:19 | 1 | 962 | winter |
76,628,358 | 4,551,325 | Python built-in function for exponential weighting with half-life parameter | <p>In Python, is there a built-in function that achieves the following, perhaps with better performance?</p>
<pre><code>def exponential_weights(n, halflife):
"""Generate weights with length=`n` that decays exponentially for distant elements.
Output weights are sorted from old to new. So output[0] is the most distant weight and output[-1] is the newest.
"""
return np.array([.5**((n-ii-1)/(halflife-1)) for ii in range(0, n)])
</code></pre>
| <python><numpy><statistics> | 2023-07-06 11:29:30 | 0 | 1,755 | data-monkey |
76,628,091 | 1,961,574 | pandas: loss of precision when specifying seconds as floating point | <p>I need to create an datetime index with 5000 elements, an unknown offset and an unknown delta between the elements. The delta value and the offset are parameters and the only certainty is that they will be expressed in seconds as an integer or floating-point number.</p>
<p>I use <code>pd.Timedelta(value, "s")</code> to compute this delta (since <code>np.timedelta64()</code> does not accept floating-point values).</p>
<pre><code>pd.to_datetime(1687957943.122, unit="s") + np.arange(0, 5000) * pd.Timedelta(0.002, "s")
</code></pre>
<p>unfortunately, the floating-point arithmetic causes loss of precision (the following numbers aren't exactly 0.002 seconds apart):</p>
<blockquote>
<p>array(['2023-06-28T13:12:23.121999872', '2023-06-28T13:12:23.123999872',
'2023-06-28T13:12:23.125999872', ...,
'2023-06-28T13:12:33.115999872', '2023-06-28T13:12:33.117999872',
'2023-06-28T13:12:33.119999872'], dtype='datetime64[ns]')</p>
</blockquote>
<p>compare:</p>
<pre><code># offset manually upgraded to integer number and unit specified as ms
pd.to_datetime(1687957943122, unit="ms") + np.arange(0, 5000) * pd.Timedelta(0.002, "s")
</code></pre>
<p>this gets me the desired result:</p>
<blockquote>
<p>array(['2023-06-28T13:12:23.122000000', '2023-06-28T13:12:23.124000000',
'2023-06-28T13:12:23.126000000', ...,
'2023-06-28T13:12:33.116000000', '2023-06-28T13:12:33.118000000',
'2023-06-28T13:12:33.120000000'], dtype='datetime64[ns]')</p>
</blockquote>
<p>However, since I don't know the time precision of the offset, I cannot simply do this.</p>
<p>I could probably write some code to determine the correct unit, but it feels like this shoudl be some built-in functionality already. Any clues? +1 if I don't need pandas at all.</p>
| <python><pandas><numpy> | 2023-07-06 10:57:02 | 1 | 2,712 | bluppfisk |
76,628,083 | 4,575,197 | SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: | <p>i'm trying to send a request to a website then get the scrape the Text out of the website. however i get warning.</p>
<blockquote>
<p>SettingWithCopyWarning:
A value is trying to be set on a copy of a
slice from a DataFrame</p>
<p>See the caveats in the documentation:
<a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy</a> _df['text']=remove_one_words_from_list(website_text,_df['language']).copy()</p>
</blockquote>
<p>i already tried <code>.copy()</code> and the issue still remains and also with <code>_df.loc</code> i get <code>too many indexers</code> error. <strong>It's important to note that</strong> the dataframe that i pass is in for loop soi call <code>get_the_text2</code> method in a for loop then pass a row each time</p>
<pre><code> def get_the_text2(_df):
'''
sending a request for second time with a different method to recieve the Text of the Articles
Parameters
----------
_df : DataFrame
Returns
-------
only the text contained in the url
'''
df['text']=''
# for k,i in enumerate(_df['url']):
if str(_df):
website_text=list()
print(_df)
#time.sleep(2)
try:
response=requests.get(_df['url'],headers={"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"})
status_code=response.status_code
soup = BeautifulSoup(response.content, 'html.parser')
if len(website_text)<=10:
website_text=list()
if soup.article:
if soup.article.find_all(['p',re.compile("^h\d{1}")]):
for data in soup.article.find_all(['p',re.compile("^h\d{1}")]):
website_text.append(data.get_text(strip=True))
#df.at[k,'text']=remove_one_words_from_list(website_text,df.at[k,'language'])
_df['text']=remove_one_words_from_list(website_text,_df['language']).copy()
print('****ARTICLE P & H{1}****',remove_one_words_from_list(website_text,_df['language']))
for _index,item in enumerate(df['status_code']):
if item !=200:
get_the_text2(df.loc[_index])
</code></pre>
<h2><strong>EDIT</strong>:</h2>
<p>just to show the error message with <code>.loc</code></p>
<p>my Code:</p>
<p><code>_df['text']=remove_one_words_from_list(website_text,_df.loc[:,'language']).copy()</code></p>
<p>error message:</p>
<pre><code>IndexingError Traceback (most recent call last)
Cell In[14], line 102
100 for _index,item in enumerate(df['status_code']):
101 if item !=200:
--> 102 get_the_text2(df.loc[_index])
File c:\Users\\anaconda3\envs\GDELT\Lib\site-packages\pandas\core\indexing.py:939, in _LocationIndexer._validate_key_length(self, key)
937 raise IndexingError(_one_ellipsis_message)
938 return self._validate_key_length(key)
--> 939 raise IndexingError("Too many indexers")
940 return key
IndexingError: Too many indexers
</code></pre>
<h2>EDIT 2</h2>
<p>found out if i use this <code>.loc['language']</code> it won't throw error although the <code>SettingWithCopyWarning</code> is still there.</p>
<pre><code>_df['text']=remove_one_words_from_list(website_text,_df.loc['language']).copy()
</code></pre>
<p>according to <a href="https://stackoverflow.com/a/53954986/4575197">this post</a> i know why it's happened but don't know how to fix it.</p>
| <python><pandas><dataframe><view><copy> | 2023-07-06 10:55:39 | 1 | 10,490 | Mostafa Bouzari |
76,628,056 | 7,095,530 | Nested 'if else' functions | <p>Let's say we have to download a file, check if a value is True and if so, we need to alert the admin by email.</p>
<p>I would like to split up all the different things to do in easy to manage steps (functions). And then call each function one by one.</p>
<p>This create the following function:</p>
<pre><code>def alert_admin():
if download_file() == True: # File is downloaded, check if file is present
if extract_file() == True: # Zip file contains the correct file
if read_file() == True: # Read the file and the value is there
if value_in_file() == True:
# send the admin an email
pass
else:
pass
else:
pass
else:
pass
else:
pass
</code></pre>
<p>This just doesn't feel right, is there a better way (a more pythonic) to check the outcome of certain functions and proceed to the next?</p>
| <python> | 2023-07-06 10:52:32 | 1 | 315 | Kevin D. |
76,628,014 | 6,951,419 | Cmake cannot not find include/lib directories generated by Conan | <p>I am trying to define both a recipe file and a <code>test_package</code> for NATS 3rd party library.
Here is the folder structure which I have:</p>
<pre><code>nats
|--conanfile.py
|--test_package
|--CMakeLists.txt
|--conanfile.py
|--test.cpp
</code></pre>
<p>After running command</p>
<pre class="lang-shell prettyprint-override"><code>conan create . "nats/3.6.1@myname/test" -pr <some_profile_file>
</code></pre>
<p>both <code>nats</code> library and its dependency - <code>openssl</code> are being successfully built, because after running <code>conan search nats</code> and <code>conan search openss</code> I can see the following packages in localhost:</p>
<pre><code>Existing package recipes:
nats/3.6.1@myname/test
openssl/3.1.1_0@jenkins/stable
</code></pre>
<p><code>conanfile.py</code> recipe file for <code>nats</code> has the following structure:</p>
<pre><code>import os
from conan import ConanFile
from conan.tools.scm import Git
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout
required_conan_version = ">=1.59.0"
class NatsConan(ConanFile):
name = "nats"
description = "NATS is a simple, secure and high-performance messaging system."
version = "3.6.1"
license = "Apache-2.0"
settings = "os", "compiler", "build_type", "arch"
options = {
"shared" : [True, False],
"nats_tls" : [True, False],
"nats_build_streaming" : [True, False],
"windows_sdk" : "ANY",
"full_compiler_version" : "ANY"
}
default_options = {
"shared" : False,
"nats_tls" : False,
"nats_build_streaming" : False,
"windows_sdk" : "10.0",
"full_compiler_version" : ""
}
short_paths = True
def config_options(self):
if self.settings.os != "Windows":
del self.options.windows_sdk
def layout(self):
cmake_layout(self)
def generate(self):
cmake = CMakeDeps(self)
cmake.generate()
tc = CMakeToolchain(self)
tc.variables["NATS_BUILD_STREAMING"] = self.options.nats_build_streaming
tc.variables["NATS_BUILD_WITH_TLS"] = self.options.nats_tls
tc.variables["BUILD_SHARED_LIBS"] = self.options.shared
#tc.variables["NATS_BUILD_OPENSSL_STATIC_LIBS"] = True
tc.generate()
def source(self):
git = Git(self)
git.clone(url = "https://github.com/nats-io/nats.c.git", target = ".")
git.checkout("v3.6.1")
def requirements(self):
self.requires("openssl/3.1.1_0@jenkins/stable")
if self.options.nats_build_streaming:
self.requires("protobuf/3.18.0_13@jenkins/stable")
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def package(self):
cmake = CMake(self)
cmake.install()
def package_info(self):
self.cpp_info.libs = ["nats"]
</code></pre>
<p><code>test_packages</code>'s <code>CMakeLists.txt</code> file see below:</p>
<pre><code>cmake_minimum_required(VERSION 3.5.1)
project(test_application CXX)
find_package(nats CONFIG REQUIRED)
add_executable(test_application test.cpp)
target_link_libraries(test_application nats::nats)
</code></pre>
<p>And the <code>conanfile.py</code> file for that:</p>
<pre><code>import os
from conan import ConanFile
from conan.tools.cmake import CMake, cmake_layout
from conan.tools.build import can_run
class TestApplicationConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "CMakeDeps", "CMakeToolchain"
def requirements(self):
self.requires(self.tested_reference_str)
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def layout(self):
cmake_layout(self)
def test(self):
if can_run(self):
cmd = os.path.join(self.cpp.build.bindir, "test_application")
self.run(cmd, env="conanrun")
</code></pre>
<p>The problem is that when <code>conan</code> command runs <code>test()</code> for the <code>test_package</code> it just can't find neither include directories (I have <code>#include <nats/nats.h></code> in the <code>test.cpp</code> file and called a function from <code>nats</code>) nor library directories.
I have tried to add this line in the <code>CMakeLists.txt</code> file:</p>
<pre class="lang-cmake prettyprint-override"><code>include_directories(${CMAKE_INCLUDE_PATH})
</code></pre>
<p>and resolved only compile error. But unfortunately I can't resolve the linkage error, because, I guess, I need to somehow specify in the <code>CMakeLists.txt</code> file where the generated <code>lib</code> folder is located.</p>
<p>Also, I don't think that including <code>${CMAKE_INCLUDE_PATH}</code> explicitly is the right solution (it seems to me like a workaround).
IMO, there should be a generated file which should be included and nothing else, e.g., I have added this generated file</p>
<pre class="lang-cmake prettyprint-override"><code>include(C:/.conan/d6e9bb/1/lib/cmake/cnats/cnats-config.cmake)
</code></pre>
<p>in the <code>CMakeLists.txt</code>, but this didn't help either :(.</p>
<p>I don't understand what I am missing or maybe I misunderstood something related to Conan and CMake interaction. My <code>Conan</code> version is <strong>1.59.0</strong>.</p>
| <python><cmake><conan><conan-2> | 2023-07-06 10:47:11 | 0 | 646 | David Hovsepyan |
76,627,915 | 20,220,485 | How do I rename a dataframe index and make it count from 1 without fragmenting the header? | <p>I want a dataframe where the index starts from <code>1</code>. I also want to rename the index.</p>
<p>It doesn't matter what order these operations are performed, I just want to ensure that the header isn't fragmented.</p>
<p>This is surely a duplicate question, but I can't seem to find it(!)</p>
<p>This doesn't work:</p>
<pre><code>df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.index += 1
df.rename_axis('rank')
>>>
A B
rank
1 1 4
2 2 5
3 3 6
</code></pre>
<p>Nor does this:</p>
<pre><code>df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.rename_axis('rank')
df.index += 1
>>>
A B
1 1 4
2 2 5
3 3 6
</code></pre>
<p>Desired result:</p>
<pre><code>rank A B
1 1 4
2 2 5
3 3 6
</code></pre>
| <python><pandas><dataframe> | 2023-07-06 10:33:06 | 2 | 344 | doine |
76,627,849 | 814,074 | Store dataframe into json fromat with group by | <p>I have DF in below format</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>type</th>
<th>application</th>
<th>number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>test</td>
<td>spark</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>test</td>
<td>kafka</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>test1</td>
<td>spark</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>test2</td>
<td>kafka</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>test2</td>
<td>kafka</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>test</td>
<td>spark</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>o/p I am looking for is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>type</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>{"test":{"spark":2,"kafka":1},"test1":{"spark":2}}</td>
</tr>
<tr>
<td>2</td>
<td>{"test2":{"kafka":1}}</td>
</tr>
<tr>
<td>3</td>
<td>{"test":{"spark":2}}</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried several approaches but nothing returned me expected format</p>
| <python><python-3.x><dataframe><group-by> | 2023-07-06 10:24:58 | 2 | 3,594 | Sachin |
76,627,814 | 426,332 | Kafka Broker on Gitpod | <p>I've setup a very basic kafka broker on gitpod.<br>
I would now like to access it from a python notebook using kafka-python</p>
<pre><code>producer = KafkaProducer(bootstrap_servers=['localhost:9092'])
</code></pre>
<p>I must replace <code>localhost</code> with the IP of my Gitpod workspace but this would not work 'as is'</p>
<p>Gitpod provides http endpoints with a format that do not meet the standard/usual connection chain (seeb below) <br>
(this is recurring fo all such technologies served on a port, like elasticsearch and such)</p>
<p><strong>My question is :</strong> <br>
<em>What should I enter instead of `localhost' to be able to acces my Kafka Broker remotely ?</em></p>
<p>I would be glad to provide additional context, just ask.</p>
<p><a href="https://i.sstatic.net/590LP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/590LP.png" alt="enter image description here" /></a></p>
| <python><apache-kafka><gitpod> | 2023-07-06 10:20:48 | 1 | 11,645 | Mehdi LAMRANI |
76,627,766 | 7,214,714 | Word Vector Features preprocessing for ML | <p>I'm training a classifier, where the input is a 300-dimensional word vector.
Usually in machine learning problems, I would scale my inputs to 0-mean and unit variance.</p>
<p>However, scaling the vector inputs in this manner changes their relative similarity, as below:</p>
<pre><code>from numpy import dot
from numpy.linalg import norm
from sklearn.preprocessing import StandardScaler, Normalizer
def cos_sim(a, b):
return dot(a, b.T)/(norm(a)*norm(b))
unscaled = cos_sim(X[301, :].reshape(1,-1), X[302, :].reshape(1,-1))
ss = StandardScaler()
X_scaled = ss.fit_transform(X)
scaled = cos_sim(X_scaled[301, :].reshape(1,-1), X_scaled[302, :].reshape(1,-1))
print(f'unscaled = {unscaled} \n scaled = {scaled}')
>>> unscaled = [[0.72310966]]
scaled = scaled = [[-0.2791]]
</code></pre>
<p>Which (apart from sklearn.preprocessing.Normalizer) are standard steps of preprocessing these kinds of inputs for standard downstream ML problems, such as (multi-class) classification?</p>
| <python><scikit-learn><nlp><word2vec><data-preprocessing> | 2023-07-06 10:15:01 | 1 | 302 | Vid Stropnik |
76,627,765 | 6,225,526 | Pandas: How can I concatenate 2 columns as a multiline string? | <p>I have a pandas dataframe and I want to concatenate them using multiline string. Below is my pandas dataframe,</p>
<pre><code>pd.DataFrame([[1,"This is the desc of id 1"],[4,"This is the desc of id 2"]], columns=["id","desc"])
</code></pre>
<p>I wanted string like below,</p>
<pre><code>functionalRequirement 1{{
id: 1
text: This is the desc of id 1
risk: high
verifymethod: test
}}
</code></pre>
<p>I tried below code but it didnt work.</p>
<pre><code>df['res'] = f"""
functionaRequirement {df['id']} {{
id: {df['id']}
text: {df['desc']}
risk: high
verifymethod: test
}}
"""
</code></pre>
<p>How can I do it?</p>
| <python><pandas> | 2023-07-06 10:14:33 | 3 | 1,161 | Selva |
76,627,671 | 726,730 | python - pyqt5 - QFileDialog - problem with greek characters in specified path | <p>In QFileDialog (pyqt5), there is a problem when the specified path has greek characters.</p>
<p>Example path: C:/Users/cpapp/OneDrive/Υπολογιστής -> select desktop</p>
<p>Problem:</p>
<p><a href="https://i.sstatic.net/ZJd5Z.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZJd5Z.png" alt="enter image description here" /></a></p>
<p>I search in the web for the solution. It says to change some registry entries for desktop path. But i don't know what change should i apply, because the specified path may be correct.</p>
| <python><pyqt5><qfiledialog> | 2023-07-06 10:02:03 | 0 | 2,427 | Chris P |
76,627,502 | 7,816,606 | Calling a python script from a Node js file gives error Python3 not found | <p>I am calling a Python file from a node js function</p>
<pre><code> let argument = "'hoodie'";
const result = execSync(`python3 -c "import poc4; print(poc4.giveMe(${argument}))"`, { encoding: 'utf8', maxBuffer: 50 * 1024 * 1024, shell: '/bin/sh'});
console.log('result', result.toString().trim())
</code></pre>
<p>The file in python is like this</p>
<pre><code>def giveMe(hoodie):
return hoodie
</code></pre>
<p>When I am executing the node js script it is giving me the error</p>
<pre><code> {"output":[null,"","/bin/sh: python3: not found\n"],"pid":220,"signal":null,"status":127,"stderr":"/bin/sh: python3: not found\n","stdout":"","timestamp":"2023-07-06T09:35:07.254Z"}
</code></pre>
<p>This is the Docker config that is being used</p>
<pre><code>FROM python:3.9-alpine3.17
FROM node:14-alpine
WORKDIR /usr/app
COPY . ./
RUN npm install
CMD ["node", "index.js"]
EXPOSE 8000
</code></pre>
<p>Though I have Python3.11 and Node js v16.13.2 installed in my system.
Please suggest the fix.</p>
| <python><node.js><docker><express><child-process> | 2023-07-06 09:42:22 | 0 | 1,816 | Aayushi |
76,627,459 | 15,098,472 | Finding the index of the first row in a Pandas DataFrame, starting from a specific index and moving backwards, until condition is met | <p>I have a Pandas DataFrame and I'm trying to find the index of the first row where two column values differ. However, I need to start searching in reverse order.</p>
<p>Here's an example:</p>
<pre><code>import pandas as pd
data = {'Column1': [1, 2, 3, 5, 5],
'Column2': [1, 1, 3, 5, 5]}
df = pd.DataFrame(data)
</code></pre>
<p>Here, for example, I want to start from the second last index until I find the first index, where the column values differ. Thus, the desired Output would be "1".</p>
| <python><pandas> | 2023-07-06 09:37:05 | 1 | 574 | kklaw |
76,627,289 | 8,618,242 | Mediapipe pose_landmarks out of range [0, 1] | <p>It is written in the <a href="https://github.com/google/mediapipe/blob/master/docs/solutions/pose.md#pose_landmarks" rel="nofollow noreferrer">documentation</a> of Mediapipe that: "<em>x and y: Landmark coordinates normalized to [0.0, 1.0] by the image width and height respectively.</em>", however I'm getting values out of that range.</p>
<blockquote>
<p>mediapip <code>0.10.1</code>,
Python <code>3.8.10</code></p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
import numpy as np
import cv2
import mediapipe as mp
import time
class HumanPoseDetection:
def __init__(self):
# TODO: change the path
model_path = "/home/user/models/pose_landmarker_full.task"
BaseOptions = mp.tasks.BaseOptions
self.PoseLandmarker = mp.tasks.vision.PoseLandmarker
PoseLandmarkerOptions = mp.tasks.vision.PoseLandmarkerOptions
self.result = mp.tasks.vision.PoseLandmarkerResult
VisionRunningMode = mp.tasks.vision.RunningMode
self.options = PoseLandmarkerOptions(
base_options=BaseOptions(model_asset_path=model_path),
running_mode=VisionRunningMode.LIVE_STREAM,
result_callback=self.callback
)
def callback(self, result, output_image, timestamp_ms):
if(result.pose_landmarks):
self.result = result.pose_landmarks[0]
for idx, elem in enumerate(self.result):
if(0 <= elem.x <= 1 and 0 <= elem.y <= 1):
pass
else:
print("Warning out of range values: {}".format(elem))
def detect_pose(self):
cap = cv2.VideoCapture(0)
with self.PoseLandmarker.create_from_options(self.options) as landmarker:
while cap.isOpened():
_, image = cap.read()
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (224, 224))
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=image)
frame_timestamp_ms = int(time.time() * 1000)
landmarker.detect_async(mp_image, frame_timestamp_ms)
if __name__=="__main__":
HPD_ = HumanPoseDetection()
HPD_.detect_pose()
</code></pre>
<p>A workaround proposed <a href="https://github.com/google/mediapipe/issues/1192#issuecomment-712532600" rel="nofollow noreferrer">here</a> is to use <code>min</code>, in my case I need the normalized x, y and not the pixel coordinates! also this workaround doesn't seem to be accurate!</p>
<pre class="lang-py prettyprint-override"><code>x_px = min(math.floor(normalized_x * image_width), image_width - 1)
y_px = min(math.floor(normalized_y * image_height), image_height - 1)
</code></pre>
<p>Can you please tell me how can I solve this issue please? thanks in advance.</p>
<p><a href="https://github.com/google/mediapipe/issues/4598" rel="nofollow noreferrer">Related Issue</a></p>
| <python><mediapipe><pose-detection> | 2023-07-06 09:16:09 | 1 | 4,115 | Bilal |
76,627,134 | 11,354,959 | Parse a pdf file with a python flask API without saving the file | <p>I have built a flask API and my users are allowed to upload pdf file so my server can parse it and retrieve information about it.
To extract text from a pdf file I use the package pdfminer with the method extract_text but if I understand correctly this method requires a file or a filename to open it.</p>
<pre><code>@app.route("/parse-data", methods=["POST"])
def file_to_resume():
file = request.files['file']
if file.filename != '':
file_ext = os.path.splitext(file.filename)[1]
if file_ext not in app.config['UPLOAD_EXTENSIONS']:
return "Wrong file format", 400
else:
data = extract_text(file.name)
data_parsed = parse_file(data)
return jsonify(data_parsed), 200
</code></pre>
<p>With the file.name in the method it returns an error <code>FileNotFoundError: [Errno 2] No such file or directory: 'file'</code>
The request.files gives an object of type FileStorage so I cannot give it to my method directly.</p>
<p>I am not sure how to proceed from here if I want to avoid to upload the file to my server.</p>
<p>EDIT:
I could not find really what I wanted to I had to temporary save the file in a folder and delete it afterwards:</p>
<pre><code>if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.mkdir(app.config['UPLOAD_FOLDER'])
tmp_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(tmp_path)
data = extract_text(tmp_path) # I do what I want to do here with the file
os.remove(os.path.join(tmp_path)
</code></pre>
| <python><flask> | 2023-07-06 08:57:46 | 1 | 370 | El Pandario |
76,626,997 | 5,401,672 | What type of tests should I use for writing a test with TDD? | <p>I come from a PHP (Laravel) background and have just switched to Python. I am a big fan of TDD and have previously been writing 'feature' tests. Now I am writing AWS Lambdas (which are making lots of 3rd part API calls), I'm not really sure what type of tests to write? Should I switch to unit tests?</p>
<p>Now I don't have a database what should I be asserting? I think I can only mock the API calls and check that they have been called and that the correct parameters have been passed to them?</p>
<p>Any recommended reading?</p>
| <python><amazon-web-services><testing><tdd> | 2023-07-06 08:39:49 | 1 | 1,601 | Mick |
76,626,848 | 12,799,032 | Problem with reading string and its pattern? [python] | <p>I am running a code on a fasta file (the structure is shown below). This file has multiple entries where the header (seq id) of the entries starts with the ">" sign. The following lines after the header is the actual entry.</p>
<pre><code>>AF528955.1 Octopus vulgaris isolate 2 16S ribosomal RNA gene, partial sequence; mitochondrial gene for mitochondrial product
UAACUUAUCUUCUAAGCAAAAAACUUGGUUUAUUCUUCAACUAAACUCAAAAUUAAGGAAGUUAAUACAA
UACUUUAAAUUAAUUUUAUUCCUUGAUCACCCCAACCAAAGUUAUUUACAAAUAAAUUAUAUAUAUACAU
AUAUAUCUAUAUAAUAACA
>AF528954.1 Octopus vulgaris isolate 1 16S ribosomal RNA gene, partial sequence; mitochondrial gene for mitochondrial product
UAACUUAUCUUCUAAGCAAAAAACUUGGUUUAUUCUUCAACUAAACUCAAAAUUAAGGAAGUUAAUACAA
UACUUUAAAUUAAUUUUAUUCCUUGAUCACCCCAACCAAAGUUAUUUACAAAUAAAUUAUAUAUAUACAU
AUAUAUCUAUAUAAUAACA
</code></pre>
<p>What I am facing is that a part of the does not go through as expected. Here is the part where I always get the "NOTE" when running it on my fasta file.</p>
<pre><code>def count_rrna_subunits(full_species_name, seq_filename):
counts = {}
with MultiSequenceFile(seq_filename, ignore_missing_file=True) as input_seqs:
for seq_id, seq_desc, seq in input_seqs:
m = re.search(rb'^([^0-9]+)_([0-9][^_]+)', seq_id)
if m:
species = m.group(1).replace(b'_', b' ')
subunit = m.group(2)
if species == full_species_name.encode('ascii'):
if subunit in counts:
counts[subunit] += 1
else:
counts[subunit] = 1
else:
print("NOTE: could not parse rRNA subunits information for entry:\n{}Reference rRNA subunit listing may be unavailable in miRTrace reports generated using this database. Actual read mapping not affected.\n".format(seq_id), file=sys.stderr)
return counts
</code></pre>
<p>In my fasta file, the full_species_name is "Octopus vulgaris".</p>
<p>Based on my search I found that the error could be because of having strings instead of byte strings in the headers of the fasta file. I tried multiple ways to convert the headers to byte string but I was not successful and the Python code was giving the "NOTE" message again. I prefer not to change the big code since it is part of a tool but the fasta file header so it matches the Python code.</p>
<p>How can I solve this? Thank you.</p>
| <python><string><ascii> | 2023-07-06 08:20:17 | 0 | 1,096 | Apex |
76,626,629 | 7,214,714 | SKlearn classifier's predict_proba doesn't sum to 1 | <p>I have a classifier (in this case, it is the sklearn.MLPClassifier), with which I'm trying to perform classification into one of 18 classes.</p>
<p>The class is thus <strong>multi-class</strong>, not multi-label. I'm trying to predict only a single class.</p>
<p>I have my training data: X <code>X.shape = (103393, 300)</code> and Y <code>Y.shape = (103393, 18)</code>, where the target Y is a one-hot encoded vetctor, denoting the target class.</p>
<blockquote>
<p>EDIT in response to @Dr. Snoopy: I do not supply any labels -- I simply pass the 18-dimensional vector with the corret class' index corresponding to the 1 in the vector, and all others being 0 (One hot encoded vector).
To prove that the vectors are correctly 1-hot encoded, I can run</p>
</blockquote>
<pre><code>import pandas as pd
pd.DataFrame(Y.sum(axis=1)).value_counts()
</code></pre>
<blockquote>
<p>This returns 103393 counts of 1. Vectors are correctly 1-hot encoded, even upon examination.</p>
</blockquote>
<p>When I fit the model, and return the class probability for all classes, the probability vector does not sum up to 1. Why might that be?</p>
<p>Here is an example of how I run the fitting:</p>
<pre><code>from sklearn.neural_network import MLPClassifier
X_train, Y_train, X_test, Y_test = get_data()
model = MLPClassifier(max_iter=10000)
model.fit(X_train,Y_train)
probability_vector = model.predict_proba(X_test[0, :].respahe(1,-1))
</code></pre>
<p>Some of the time, the outputs are pretty close to 1. I suspect the error is probably due to rounding.</p>
<p>In other cases, the outputs sum to ~0.5 or less. Example output:</p>
<pre><code>probability_vector = list(model.predict_proba(X_test[301,:].reshape(1,-1))[0])
print(probability_vector)
>>> [1.7591416e-06,
3.148203e-05,
3.9732524e-05,
0.3810972,
0.059248358,
0.00032832936,
8.5996935e-06,
9.0914684e-05,
9.377927e-07,
0.0007674346,
1.5543707e-06,
0.0008467222,
0.009655427,
2.5728454e-05,
1.07812774e-07,
0.00022920035,
0.00050288404,
0.013878004]
len(probability_vecto)
>>> 18
sum(probability_vector)
>>> 0.46675437349917814
</code></pre>
<p>Why might this be happening? Is my model initialized incorrectly?</p>
<blockquote>
<p>Note: A couple of possible reasons for the error & my comments on them:</p>
<ul>
<li><p>Class imbalance: The classes in the dataset are indeed, imbalanced. However, the non-1 summation problem is happening in well represented classes too, not just the underrepresented ones. Could this be a consequence of a model, which is not expressive enough?</p>
</li>
<li><p>Model uncertainty: "The model may not have a high level of confidence in its predictions for every input. " Is that all it is?</p>
</li>
</ul>
</blockquote>
| <python><machine-learning><scikit-learn> | 2023-07-06 07:51:28 | 1 | 302 | Vid Stropnik |
76,626,594 | 1,397,843 | Numpy.unique(): How to get an ordered "inverse index" efficiently? | <p>I would like to get an <em>ordered</em> inverse value from <code>numpy.unique(return_inverse=True)</code>, which normally returns an (unordered) inverse, as follows:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
arr = np.array([2, 2, 3, 1])
arr_unq, arr_inv = np.unique(arr, return_inverse=True)
print(arr_inv)
# output: [1 1 2 0]
</code></pre>
<p>Notice that the inverse index is not ordered.
In contrast, I like to get an ordered inverse, like below:</p>
<pre class="lang-py prettyprint-override"><code># output: [0 0 1 2]
</code></pre>
<p>If relevant, you may consider the total number of elements to be around 100k, and number of unique elements to be around 10k.</p>
| <python><numpy><indexing> | 2023-07-06 07:46:40 | 2 | 386 | Amin.A |
76,626,207 | 6,086,115 | Add line breaks to Dash AG grid custom tooltip | <p>I added a custom tooltip to my Dash AG grid according to these instructions: <a href="https://dash.plotly.com/dash-ag-grid/tooltips" rel="nofollow noreferrer">https://dash.plotly.com/dash-ag-grid/tooltips</a>. Now, the cell that contains my tooltip data may have one or multiple line breaks (indicated by \n), and they are ignored in the tooltip. However, I want them to be displayed.</p>
<p>Here is a minimum example of my .py code:</p>
<pre><code>import dash_ag_grid as dag
from dash import Dash, html, dcc
import pandas as pd
data = {
"ticker": ["AAPL", "MSFT", "AMZN", "GOOGL"],
"company": ["Apple or a very long name to describe Apple in some sense in which line breaks HERE \n would be very nice for readability.", "Microsoft", "Amazon", "Alphabet"],
}
df = pd.DataFrame(data)
columnDefs = [
{
"headerName": "Stock Ticker",
"field": "ticker",
"tooltipField": 'ticker',
"tooltipComponentParams": { "color": '#d8f0d3' },
},
{
"headerName": "Company",
"field": "company",
}
]
grid = dag.AgGrid(
id="tooltip-simple-example",
columnDefs=columnDefs,
rowData=df.to_dict("records"),
columnSize="sizeToFit",
defaultColDef={"editable": False, "tooltipComponent": "CustomTooltip"},
dashGridOptions={"tooltipShowDelay": 100}
)
app = Dash(__name__)
app.layout = html.Div(
[dcc.Markdown("Example of custom tooltip"), grid],
style={"margin": 20},
)
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>And then the underlying .js code:</p>
<pre><code>var dagcomponentfuncs = window.dashAgGridComponentFunctions = window.dashAgGridComponentFunctions || {};
dagcomponentfuncs.CustomTooltip = function (props) {
info = [
React.createElement('h5', {}, props.data.ticker),
React.createElement('div', {}, props.data.company),
React.createElement('div', {}, props.data.price),
];
return React.createElement(
'div',
{
style: {
border: '2pt solid white',
backgroundColor: props.color || 'grey',
padding: 10,
},
},
info
);
};
</code></pre>
<p>Hope anyone can help me out!</p>
| <python><grid><tooltip><ag> | 2023-07-06 06:57:13 | 0 | 351 | Jordi |
76,626,184 | 6,224,975 | Where is "current-folder" i.e "./" in imported functions? | <p>Say I have a folder structure</p>
<pre><code>main_folder/
├─ sub_folder/
│ ├─ sub_file.py
├─ main_file.py
</code></pre>
<p>and in <code>sub_file.py</code></p>
<pre class="lang-py prettyprint-override"><code>def read_data():
with open("./datafile.txt", "rb") as f:
data = f.readlines()
return data
</code></pre>
<p>where is <code>"datafile.txt"</code> then supposed to be located such that any other script, which imports <code>sub_file.py</code> can use it i.e where is currentfolder (<code>./</code>) when that function is executed?
Furthermore, does the path change if I publish it as a package instead of using it locally?</p>
| <python><path> | 2023-07-06 06:53:02 | 2 | 5,544 | CutePoison |
76,626,134 | 15,320,579 | Extract relevant rows from pandas dataframe when duplicate column values are present | <p>I have a pandas data frame as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>left</th>
<th>top</th>
<th>width</th>
<th>height</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>12</td>
<td>34</td>
<td>12</td>
<td>34</td>
<td>commercial</td>
</tr>
<tr>
<td>2</td>
<td>99</td>
<td>42</td>
<td>99</td>
<td>42</td>
<td>general</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>47</td>
<td>9</td>
<td>4</td>
<td>liability</td>
</tr>
<tr>
<td>4</td>
<td>10</td>
<td>69</td>
<td>32</td>
<td>67</td>
<td>commercial</td>
</tr>
<tr>
<td>5</td>
<td>99</td>
<td>72</td>
<td>79</td>
<td>88</td>
<td>available</td>
</tr>
</tbody>
</table>
</div>
<p>I want to <strong>extract specific rows based on the column value</strong> <code>Text</code>. So I want to search for certain keyphrases like <code>liability commercial</code> using <code>re.search</code> in the column <code>Text</code> and if I get a match then extract the rows i.e. 3rd and 4th row. So if the input is <code>liability commercial</code> then the output should be the following rows extracted:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>left</th>
<th>top</th>
<th>width</th>
<th>height</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<tr>
<td>3</td>
<td>1</td>
<td>47</td>
<td>9</td>
<td>4</td>
<td>liability</td>
</tr>
<tr>
<td>4</td>
<td>10</td>
<td>69</td>
<td>32</td>
<td>67</td>
<td>commercial</td>
</tr>
</tbody>
</table>
</div>
<p>Keep in mind that the column <code>Text</code> <strong>may contain duplicate values</strong>. So in the above case, there are 2 rows with the word <code>commerial</code> present.</p>
<p><strong>Thanks in advance!</strong></p>
| <python><python-3.x><pandas><dataframe><numpy> | 2023-07-06 06:43:16 | 1 | 787 | spectre |
76,626,069 | 19,238,204 | Python matplotlib animation: Create solid of revolution toward y-axis for sin(x/2) | <p>I am trying to create a solid of revolution for <strong>sin(x/2)</strong> toward y-axis from x=0 to x=2pi.</p>
<p>I am able to create the solid of revolution toward x-axis:</p>
<p><a href="https://i.sstatic.net/tCVMc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tCVMc.png" alt="1" /></a></p>
<p>this is the code:</p>
<pre><code>import gif
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
@gif.frame
def plot_volume(angle):
fig = plt.figure(figsize = (20, 15))
ax2 = fig.add_subplot(1, 1, 1, projection = '3d')
angles = np.linspace(0, 360, 20)
x = np.linspace(0, 2*np.pi, 60)
v = np.linspace(0, 2*angle, 60)
U, V = np.meshgrid(x, v)
Y1 = np.sin(U/2)*np.cos(V)
Z1 = np.sin(U/2)*np.sin(V)
X = U
ax2.plot_surface(X, Y1, Z1, alpha = 0.2, color = 'blue', rstride = 6, cstride = 6)
ax2.set_xlim(-3,3)
ax2.set_ylim(-3,3)
ax2.set_zlim(-3,3)
ax2.view_init(elev = 50, azim = 30*angle)
ax2.plot_wireframe(X, Y1, Z1, color = 'black')
ax2._axis3don = False
frames = []
for i in np.linspace(0, 4*np.pi, 20):
frame = plot_volume(i)
frames.append(frame)
gif.save(frames, '/home/browni/LasthrimProjection/Python/solidofrevolutionxaxis.gif', duration = 500)
</code></pre>
<p>The question and the problem is:</p>
<ol>
<li>Why the function of numpy <code>np.arcsin</code> can't be used as the inverse of sine function to create the solid of revolution for sin(x/2) toward the y axis?</li>
</ol>
<p>This is the code for trying to rotate sin(x/2) from x=0 to x=2pi toward y-axis. And it fails</p>
<pre><code>import gif
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
@gif.frame
def plot_volume(angle):
fig = plt.figure(figsize = (20, 15))
ax2 = fig.add_subplot(1, 1, 1, projection = '3d')
angles = np.linspace(0, 360, 20)
x = np.linspace(0, 1, 60)
v = np.linspace(0, 2*angle, 60)
U, V = np.meshgrid(x, v)
Y1 = 2*np.arcsin(U)*np.cos(V)
Z1 = 2*np.arcsin(U)*np.sin(V)
X = U
ax2.plot_surface(X, Y1, Z1, alpha = 0.2, color = 'blue', rstride = 6, cstride = 6)
ax2.set_xlim(-3,3)
ax2.set_ylim(-3,3)
ax2.set_zlim(-3,3)
ax2.view_init(elev = 50, azim = 30*angle)
ax2.plot_wireframe(X, Y1, Z1, color = 'black')
ax2._axis3don = False
frames = []
for i in np.linspace(0, 4*np.pi, 20):
frame = plot_volume(i)
frames.append(frame)
gif.save(frames, '/home/browni/LasthrimProjection/Python/solidofrevolutionyaxis.gif', duration = 500)
</code></pre>
<p>it should look like half circle not like this:
<a href="https://i.sstatic.net/qD4lr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qD4lr.png" alt="2" /></a></p>
| <python><numpy><matplotlib> | 2023-07-06 06:31:13 | 0 | 435 | Freya the Goddess |
76,625,791 | 7,216,834 | Group values of a key if another key has got same values that are list type in list of dictionary | <p>I have a list of dictionary,</p>
<pre><code> data = [{"service":"1","unit":["A","B"]},{"service":"2","unit":["A","B"]},{"service":"1","unit":["C"]}]
</code></pre>
<p>I want the output to be:</p>
<pre><code> output = [{"service":["1","2"],"unit":["A","B"]},{"service":["1"],"unit":["C"]}]
</code></pre>
<p>I tried different codes that groups the key values if the value of another key is similar, but as unit are in list, I am unsure how to deal with this.</p>
<p>Tried Code:</p>
<pre><code> for dd in data:
d.setdefault(dd['service'], set()).update(dd['unit'])
newlst = [{'service':k, 'unit':list(v)} for k,v in d.items()]
print(newlst)
</code></pre>
<p>Kindly help.</p>
| <python> | 2023-07-06 05:37:10 | 2 | 1,325 | Jennifer Therese |
76,625,768 | 7,339,624 | ImportError: cannot import name 'CustomLLM' from 'llama_index.llms' | <p>I'm having difficulties to work with <code>llama_index</code>. I want to load a custom LLM to use it. Fortunately, they have the exact <a href="https://gpt-index.readthedocs.io/en/latest/how_to/customization/custom_llms.html#example-using-a-huggingface-llm" rel="nofollow noreferrer">example</a> for my need on their documentation, unfortunately, it does not work!
They have these imports in their example:</p>
<pre><code>from llama_index.llms import CustomLLM, CompletionResponse, LLMMetadata
</code></pre>
<p>And when I run it I'll get this error:</p>
<pre><code>ImportError: cannot import name 'CustomLLM' from 'llama_index.llms'
</code></pre>
<p>My <code>llama_index</code> version is 0.7.1 (the last current version). Do you know any workaround for me to use a custom dataset in llama_index?</p>
<p>P.S. If their full code is needed here it is:</p>
<pre><code>import torch
from transformers import pipeline
from typing import Optional, List, Mapping, Any
from llama_index import (
ServiceContext,
SimpleDirectoryReader,
LangchainEmbedding,
ListIndex
)
from llama_index.llms import CustomLLM, CompletionResponse, LLMMetadata
# set context window size
context_window = 2048
# set number of output tokens
num_output = 256
# store the pipeline/model outisde of the LLM class to avoid memory issues
model_name = "facebook/opt-iml-max-30b"
pipeline = pipeline("text-generation", model=model_name, device="cuda:0", model_kwargs={"torch_dtype":torch.bfloat16})
class OurLLM(CustomLLM):
@property
def metadata(self) -> LLMMetadata:
"""Get LLM metadata."""
return LLMMetadata(
context_window=context_window, num_output=num_output
)
def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:
prompt_length = len(prompt)
response = pipeline(prompt, max_new_tokens=num_output)[0]["generated_text"]
# only return newly generated tokens
text = response[prompt_length:]
return CompletionResponse(text=text)
def stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen:
raise NotImplementedError()
# define our LLM
llm = OurLLM()
service_context = ServiceContext.from_defaults(
llm=llm,
context_window=context_window,
num_output=num_output
)
# Load the your data
documents = SimpleDirectoryReader('./data').load_data()
index = ListIndex.from_documents(documents, service_context=service_context)
# Query and print response
query_engine = index.as_query_engine()
response = query_engine.query("<query_text>")
print(response)
</code></pre>
| <python><nlp><llama-index><large-language-model> | 2023-07-06 05:32:46 | 1 | 4,337 | Peyman |
76,625,548 | 4,744,901 | Jenkins jobs fails with error "The batch file cannot be found. Build step 'Execute Windows batch command' marked build as failure" | <p>I have batch script calling some python files configured in Jenkins jobs as below:</p>
<p>'''python script.py --commandline_parameter1 value1'''</p>
<p>If the script.py execute for longer time, sometimes I am seeing an error as mentioned below while the script execution is successful and I am getting the expected output also. But only the Jenkins job status will be Failure.</p>
<p><em>The batch file cannot be found.
Build step 'Execute Windows batch command' marked build as failure
Finished: FAILURE</em></p>
<p>The Job is Success when the script runs for shorter time without any failure.</p>
<p>Why is it happening? And what can be the fix for this ?</p>
<p>I can't put a exit 0 as I actually need to know if there is an actual failure in the script also.</p>
<p>Regards
Sreevalsa</p>
| <python><jenkins><jenkins-pipeline> | 2023-07-06 04:42:00 | 1 | 996 | Sreevalsa E |
76,625,547 | 14,963,549 | How can I to read a csv file from ADLS GEN2 using Python? | <p>I’d like to read a file from ADLS (Azure) by using Python cron my desktop, by now I Just have the https string to get inri the container, there is any option to make it?</p>
| <python><pandas><azure><koala> | 2023-07-06 04:41:44 | 1 | 419 | Xkid |
76,625,415 | 2,519,046 | invalid literal for int() with base 10: when try to convert a string literal | <p>I am trying to read text from a file and then go through the characters in the string one by one and convert those to numbers and do some arithmetic operations after that. I have not included the arithmetic operation part in the code provided here. I tried accessing the type of the fo.read(c) line before the loop and it gave me the type as a string.
But when I tried to convert it to an integer it gave me the error <code>line 9, in <module> num = int(text)ValueError: invalid literal for int() with base 10: ''</code></p>
<p>I ensured the characters I included in the text file were numbers.</p>
<p>Below is the code I tried.</p>
<pre><code>fn = 0
fo=open("SSS.txt",'r')
c = 0
num = 0
while c < 10:
text = fo.read(c)
print(text)
num = int(text)
fo.close()
</code></pre>
| <python><casting><type-conversion><integer> | 2023-07-06 04:03:36 | 2 | 784 | ChathurawinD |
76,625,095 | 7,662,164 | Replace specified elements in numpy array | <p>Suppose I have a numpy array defined by <code>A = np.zeros((4, 4, 4))</code>. Now suppose I want to set the elements <code>A[0, 2, 3], A[1, 1, 2], A[2, 1, 0], A[3, 0, 3]</code> to 1. Is there a way to do it in one line of code?</p>
<p>Edit: I tried <code>A[[0, 2, 3], [1, 1, 2], [2, 1, 0], [3, 0, 3]] = 1</code> but this didn't work.</p>
| <python><arrays><numpy> | 2023-07-06 02:13:37 | 1 | 335 | Jingyang Wang |
76,624,970 | 28,804 | How can I change the parameter signature in the help docs of a decorated function? | <p>I have a class that includes a method that takes two parameters, <code>a</code> and <code>b</code>, like so:</p>
<pre><code>class Foo:
def method(self, a, b):
"""Does something"""
x, y, z = a.x, a.y, b.z
return do(x, y, z)
</code></pre>
<p>When running <code>help(Foo)</code> in the Python REPL, you would see something like this:</p>
<pre><code>class Foo(builtins.object)
| Methods defined here:
|
| method(self, a, b)
| Does something
</code></pre>
<p>I have updated the class with a decorator that manipulates the arguments passed into the method so instead of taking <code>a</code> and <code>b</code> and unpacking them, the decorator will do the unpacking and pass <code>x</code>, <code>y</code>, and <code>z</code> into the method:</p>
<pre><code>def unpack(fn):
def _unpack(self, a, b):
x, y, z = a.x, a.y, b.z
return fn(self, x, y, z)
return _unpack
class Foo:
@unpack
def method(self, x, y, z):
"""Does something"""
return do(x, y, z)
</code></pre>
<p>This works fine except that the help string isn't very helpful anymore:</p>
<pre><code>class Foo(builtins.object)
| Methods defined here:
|
| method = _unpack(self, a, b)
</code></pre>
<p>The standard way to fix this is to use <code>functools.wraps</code>:</p>
<pre><code>from functools import wraps
def unpack(fn):
@wraps(fn)
def _unpack(self, a, b):
x, y, z = a.x, a.y, b.z
return fn(self, x, y, z)
return _unpack
</code></pre>
<p>And that works great, too, <em>except</em> that it shows the method as taking <code>x</code>, <code>y</code>, and <code>z</code> as arguments, when really it still takes <code>a</code> and <code>b</code> (that is, 2 arguments instead of 3), so the help doc is a bit misleading:</p>
<pre><code>class Foo(builtins.object)
| Methods defined here:
|
| method(self, x, y, z)
| Does something
</code></pre>
<p><strong>Is there a way to modify the function wrapper so it correctly grabs the doc string and other attributes as in <code>functools.wraps</code> <em>but</em> also shows the arguments accepted by the wrapper?</strong></p>
<p>For example, I would like the help string to show:</p>
<pre><code>class Foo(builtins.object)
| Methods defined here:
|
| method(self, a, b)
| Does something
</code></pre>
<p>even when the method is wrapped by <code>unpack</code>.</p>
<p>(I have examined the <a href="https://github.com/python/cpython/blob/13aefd175e3c04529251f175c23cb3ed88451fd0/Lib/functools.py#L65" rel="nofollow noreferrer">source code</a> of <code>functools.wraps</code> but I could not figure out if that can copy the function signature or not.)</p>
| <python><python-decorators><functools> | 2023-07-06 01:31:08 | 1 | 413,546 | mipadi |
76,624,753 | 19,459,262 | Skip lines when reading from csv in pandas | <p>I have a large csv file containing weather observations from the Bureau of Meteorology. When reading from this file, I need to skip over some lines at the start.</p>
<p>The file looks like this:</p>
<pre><code>"Daily Weather Observations..."
"Prepared..."
,"Date","Minimum temperature (�C)", ...
# data here
</code></pre>
<p>When reading from the file, I want to skip over the lines at the start which are not the data. However, the number of these lines vary from file to file. (I have many files.)</p>
<p>My current approach is:</p>
<pre><code>import pandas as pd
actuals = pd.read_csv(path_here, skiprows=5, encoding='latin1')
</code></pre>
<p>However, this only works when I hardcode in the rows, and I need it to be able to dynamically skip over the rows.</p>
<p>How can I skip over these 'commentary' lines when reading from the csv file?</p>
| <python><pandas><csv> | 2023-07-06 00:08:12 | 2 | 784 | Redz |
76,624,713 | 48,956 | How can Process.close raise error for a .joined process? | <p>In some large codebase, I'm running I'm calling Process.close as follows:</p>
<pre><code>async def run():
result = asyncio.Future()
def waiter():
# Notify result when process is done
p.start()
p.join()
if not result.done():
# await result may caused result.cancelled on interupt
result.set_result(p.exitcode)
p = Process(target=myfunc,
args=args,
kwargs=kwargs,
daemon=constants.SUB_PROCESS_IS_DAEMON,
name=name)
threading.Thread(
target=waiter,
daemon=True,
).start()
try:
await result
except asyncio.CancelledError:
p.join() # Yes, p.join. Added because of the exception
if p.is_alive():
p.close()
</code></pre>
<p>Above, p.close raise the error:</p>
<pre><code> raise ValueError("Cannot close a process while it is still running. "
ValueError: Cannot close a process while it is still running. You should first call join() or terminate().
</code></pre>
<p>but I obviously have called p.join(). What's up with that?</p>
<p>I thought perhaps p.start wasn't called, but I added logging and found it was.</p>
<p>How can this error ever happen?</p>
| <python> | 2023-07-05 23:54:52 | 0 | 15,918 | user48956 |
76,624,483 | 5,067,372 | How to create a new column in Polars based on the most recent occurrence of a specific value in another column (before the next occurrence)? | <p>I have a<code>polars</code> <code>DataFrame</code> with three columns: <code>Patient_id</code>, <code>Event</code> and <code>Date</code>. I want to create a new column, <code>latest_admission</code>, that records the most recent<code>Event == "Admission"</code> (by <code>Date</code>). The "latest" value should be recorded in each row until the next <code>"Admission"</code>. How can I achieve this using Polars?</p>
<p>Here's an example of the DataFrame:</p>
<pre><code>import polars as pl
df1 = (pl.DataFrame
._from_dict({
'Patient_id': [1, 1, 1, 1,1,2,2,2],
'Event': ["Admission", "Discharge", "Admission",
"Other", "Discharge", "Admission", "Discharge", "Admission"],
'Date': ["2020/01/01","2020/01/02","2021/04/18","2021/04/19","2021/04/20",
"2020/12/01","2020/12/02","2022/08/17"]})
.with_columns(
pl.col(["Date"]).str.strptime(pl.Date, format="%Y/%m/%d")))
</code></pre>
<p>And this is the expected output:</p>
<pre><code>shape: (8, 4)
┌────────────┬───────────┬────────────┬──────────────────┐
│ Patient_id ┆ Event ┆ Date ┆ latest_admission │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ date ┆ date │
╞════════════╪═══════════╪════════════╪══════════════════╡
│ 1 ┆ Admission ┆ 2020-01-01 ┆ 2020-01-01 │
│ 1 ┆ Discharge ┆ 2020-01-02 ┆ 2020-01-01 │
│ 1 ┆ Admission ┆ 2021-04-18 ┆ 2021-04-18 │
│ 1 ┆ Other ┆ 2021-04-19 ┆ 2021-04-18 │
│ 1 ┆ Discharge ┆ 2021-04-20 ┆ 2021-04-18 │
│ 2 ┆ Admission ┆ 2020-12-01 ┆ 2020-12-01 │
│ 2 ┆ Discharge ┆ 2020-12-02 ┆ 2020-12-01 │
│ 2 ┆ Admission ┆ 2022-08-17 ┆ 2022-08-17 │
└────────────┴───────────┴────────────┴──────────────────┘
</code></pre>
| <python><dataframe><python-polars> | 2023-07-05 22:44:19 | 1 | 2,053 | Rodrigo Zepeda |
76,624,477 | 10,824,322 | What's the Raku equivalent of the super keyword as used in JavaScript and Python? | <p>Whenever you extend a class in JavaScript or Python, the derived class must use the <code>super</code> keyword in order to set attributes and/or invoke methods and constructor in the base class. For example:</p>
<pre class="lang-js prettyprint-override"><code>class Rectangle {
constructor(length, width) {
this.name = "Rectangle";
this.length = length;
this.width = width;
}
shoutArea() {
console.log(
`I AM A ${this.name.toUpperCase()} AND MY AREA IS ${this.length * this.width}`
);
}
rectHello() {
return "Rectanglish: hello";
}
}
class Square extends Rectangle {
constructor(length) {
super(length, length);
this.name = "Square"
}
squaHello() {
const h = super.rectHello();
return "Squarish:" + h.split(':')[1];
}
}
const rect = new Rectangle(6, 4);
rect.shoutArea(); //=> I AM A RECTANGLE AND MY AREA IS 24
const squa = new Square(5);
squa.shoutArea(); //=> I AM A SQUARE AND MY AREA IS 25
console.log(squa.squaHello()); //=> Squarish: hello
</code></pre>
| <javascript><python><oop><inheritance><raku> | 2023-07-05 22:43:52 | 2 | 3,175 | uzluisf |
76,624,371 | 2,951,230 | Python Post Request works, but the same PHP (CURL) does not work | <p>I was trying to write the same post request via php as i did in python. In python it works well, while in php it does not even reach the server at all. This is php 7.4. Also I can access the server http://someip:2080/api/
via browser. So http://someip:2080/api/ is a public IP, I can even access via browser, so it should work from anywhere.</p>
<p>PHP code:</p>
<pre><code>$payload = array(
'data' => 'data0',
);
// Setup cURL
$ch = curl_init('http://someip:2080/api/');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($payload)
));
$response = curl_exec($ch);
if($response === FALSE){
die(curl_error($ch));
}
</code></pre>
<p>and python code:</p>
<pre><code>import requests
import json
headers = {'Content-Type': 'application/json'}
resp = requests.post("http://someip:2080/api/" , data = json.dumps(allparams), headers=headers)
thepara = resp.json()
</code></pre>
<p>I have no idea what is wrong I tried around 10 ways to make post request from php and nothing worked.</p>
| <python><php><curl><post><python-requests> | 2023-07-05 22:17:22 | 1 | 1,239 | Brana |
76,624,335 | 4,518,341 | Is there a way to show the linter status in VSCode? | <p>I just had an issue with my Python linter (Pylama) where it was crashing, but VSCode didn't show any indication of that, even in the "Python output" (<code>python.viewOutput</code>). Only when I ran it manually in the terminal did I find out there was a issue. So is there a way to have VSCode tell me if a linter crashes?</p>
<p>Next, after fixing the issue, the linter takes a long time to run, and while it's running it removes any "problems", which is confusing, because the problems haven't gone away, it just hasn't found them yet. So is there a way to have VSCode show that the the linter is running?</p>
<p>If it's relevant, I'm using VSCodium with Jedi (though I don't think Jedi is involved here).</p>
<p>I googled <code>vscode linter status</code>, checked <a href="https://code.visualstudio.com/docs/python/linting" rel="nofollow noreferrer">Linting Python in Visual Studio Code</a>, and searched "status" and "linter" in the settings but didn't see anything relevant.</p>
<p>If it helps, the full command line in the "Python output" is:
<code>~/Programs/anaconda3/bin/conda run -p ~/Programs/miniconda3/envs/anaconda3_11 --no-capture-output python ~/.vscode-oss/extensions/ms-python.python-2023.6.1-universal/pythonFiles/get_output_via_markers.py ~/.vscode-oss/extensions/ms-python.python-2023.6.1-universal/pythonFiles/linter.py -m pylama --options=.pylama.ini ./tmp_ana.py</code></p>
| <python><visual-studio-code> | 2023-07-05 22:07:49 | 1 | 33,775 | wjandrea |
76,624,324 | 5,383,097 | How to limit elevation over distance using the A* search algorithm? | <p>My application finds or constructs routes that are shortest for trekkers in a hilly/mountain terrain using the A* search algorithm. Input files are .dem (Digital Elevation Model) and a roadmap file that contains existing routes. Code is in Python, libraries used are pygdal, NumPy and PyQGIS.</p>
<p>The routes provided by the algorithm are very steep. I want my route to follow the gradient guidelines, for every 30m only 1m of elevation. A* finds the shortest route from peak to valley in a straight line, which is not practical. Output should descend from one contour line to another at less than 1.91 degrees.</p>
| <python><algorithm><graph-theory><a-star><heightmap> | 2023-07-05 22:06:12 | 2 | 963 | Navneet Srivastava |
76,624,164 | 6,458,245 | Pytorch Transformer: Embed dimension (d_model) is same dimension as src embedding but is also total dimension of model? | <p>I have been trying to use torch.nn.Transformer. I am confused about the embed_dim (aka d_model). If I have an input of size (10, 7) where 7 is my embedding dimension and 10 is my sequence length, does d_model = 7? The MHA component says <a href="https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html</a></p>
<blockquote>
<p>embed_dim – Total dimension of the model.
num_heads – Number of parallel attention heads. Note that embed_dim
will be split across num_heads (i.e. each head will have dimension
embed_dim // num_heads).</p>
</blockquote>
<p>How can embed_dim be both num_heads * dim_per_head and also the embedding size of each token? This doesn't make sense. In other words, why do none of these code versions work?</p>
<p><code>x = nn.Transformer(nhead=2, d_model=7)</code> leads to</p>
<blockquote>
<p>AssertionError: embed_dim must be divisible by num_heads</p>
</blockquote>
<pre><code>x = nn.Transformer(nhead=2, d_model=14)
a = torch.rand((10,7))
x(a,a)
</code></pre>
<p>leads to</p>
<blockquote>
<p>RuntimeError: the feature number of src and tgt must be equal to
d_model</p>
</blockquote>
| <python><deep-learning><pytorch><nlp> | 2023-07-05 21:31:26 | 1 | 2,356 | JobHunter69 |
76,624,161 | 4,372,237 | Pandas updating a column with .loc does not work as expected | <p>As far as I understood it is preferable to update the column values using <code>.loc</code> method rather than slicing <code>[]</code>, because of the potential SettingWithCopy issue. When I use slicing I frequently get these warnings, and I understand that there is a concern when using multindexing.</p>
<p>However, when I am using .loc method, my column is not updated when the column's values are used in the right-hand side:</p>
<pre><code>a=pd.DataFrame({'A':['2023-01-01','2023-01-02']},[0,1])
a
Out[128]:
A
0 2023-01-01
1 2023-01-02
a.dtypes
Out[130]:
A object
dtype: object
</code></pre>
<p>When I am running either of the following commands to convert object into the datetime, the dtype of the column "A" remains object. Thus there is no effect:</p>
<pre><code>a.loc[:,'A']=pd.to_datetime(a.loc[:,'A'])
a.loc[:,'A']=pd.to_datetime(a['A'])
</code></pre>
<p>When I am using</p>
<pre><code>a['A']=pd.to_datetime(a['A'])
</code></pre>
<p>My dtype is converted into datetime. I am curious why .loc method does not work in this case?</p>
<p>Thanks</p>
| <python><pandas><datetime> | 2023-07-05 21:30:12 | 1 | 3,470 | Mikhail Genkin |
76,624,057 | 825,227 | Multiple Inheritance and Wrappers in Python | <p>Apologies for the noob question, but a bit confused by inheritance and wrapper classes in Python and hoping for input.</p>
<p>I'm familiar with this pattern for inheritance in Python:</p>
<pre><code>from api.client import Client
from api.wrapper import Wrapper
class TestClient(Client):
def __init__(self, wrapper):
Client.__init__(self, wrapper)
class TestWrapper(Wrapper):
def __init__(self):
Wrapper.__init__(self)
def updateMktDepth(self, reqId: TickerId, position: int, operation: int,
side: int, price: float, size: int):
super().updateMktDepth(reqId, position, operation, side, price, size)
print("UpdateMarketDepth", "ReqId:", reqId, "Position:", position, "Operation:",
operation, "Side:", side, "Price:", price, "Size:", size)
def updateMktDepthL2(self, reqId: TickerId, position: int, marketMaker: str,
operation: int, side: int, price: float, size: int, isSmartDepth: bool):
super().updateMktDepthL2(reqId, position, marketMaker, operation, side,
price, size, isSmartDepth)
print("UpdateMarketDepthL2", "ReqId:", reqId, "Position:", position, "MarketMaker:", marketMaker, "Operation:",
operation, "Side:", side, "Price:", price, "Size:", size, "isSmartDepth:", isSmartDepth)
def main():
wrapper = TestWrapper()
client = TestClient(wrapper)
client.connect('127.0.0.1', 3847, 100)
print('Connection successful')
client.disconnect()
</code></pre>
<p>In follow up, how is <code>wrapper</code> passed to instantiate <code>TestClient</code> without reference to this parameter in its class definition? Is this similar/related to the *args/**kwargs mechanism?</p>
<p>I also found this pattern (and class definition for <code>Client</code> included as well):</p>
<pre><code>from api.client import Client
from api.wrapper import Wrapper
class TestApp(Client, Wrapper):
def __init__(self):
Client.__init__(self, self)
def updateMktDepth(self, reqId: TickerId, position: int, operation: int, side: int, price: float, size: int):
super.updateMktDepth(reqId, position, operation, side, price, size)
print("UpdateMarketDepth", "ReqId:", reqId, "Position:", position, "Operation:", operation, "Side:", side, "Price:", price, "Size:", size)
def updateMktDepthL2(self, reqId: TickerId, position: int, marketMaker: str, operation: int, side: int, price: float, size: int, isSmartDepth: bool):
super.updateMktDepthL2(reqId, position, operation, side, price, size)
print("UpdateMarketDepthL2", "ReqId:", reqId, "Position:", position, "MarketMaker:", marketMaker, "Operation:",
operation, "Side:", side, "Price:", price, "Size:", size, "isSmartDepth:", isSmartDepth)
class Client(object):
(DISCONNECTED, CONNECTING, CONNECTED, REDIRECT) = range(4)
def __init__(self, wrapper):
self.msg_queue = queue.Queue()
self.wrapper = wrapper
self.decoder = None
self.reset()
</code></pre>
<p>(1) How does the super operator know where the specified method exists when two base classes are inherited (*note, the method in question exists in only one of the two inherited classes).</p>
<p>(2) How does the <code>Client.__init__(self, self)</code> work to pass the self object twice? Obviously familiar with passing self, but how does it work to be passed twice?</p>
| <python><inheritance><wrapper><multiple-inheritance> | 2023-07-05 21:09:43 | 0 | 1,702 | Chris |
76,624,050 | 12,596,824 | How to filter from a list based on multiple wildcards in python without using a loop | <p>I have the following list I want to filter to get everything that starts with peter and steve. I eventually want to add more conditions as well. How can I filter this list given a set of patterns without looping through the entire list? I have something with fnmatch but i can only get it for one pattern adn I don't want to loop. Is there a more pythonic way of doing this?</p>
<pre><code>12 = ['peter_1', 'peter_2', 'peter_3', 'jerry', 'tim', 'johnson', 'steve_1', 'steve_2']
pattern = 'peter*'
fnmatch.filter(l2, pattern)
</code></pre>
| <python><pandas> | 2023-07-05 21:08:37 | 4 | 1,937 | Eisen |
76,624,004 | 4,493,212 | Python not printing entire string as URL | <p>I have a URL like <code>https://...com?var-Table_Type=*&var-DC=abc</code></p>
<p>When I print the URL, the entire URL is printed but only half of it is highlighted in blue as a URL, so when I click the output it doesn't take me to the actual link.</p>
<p><a href="https://i.sstatic.net/HTFWE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HTFWE.png" alt="enter image description here" /></a></p>
| <python><python-3.x><url> | 2023-07-05 21:00:12 | 1 | 1,092 | John Constantine |
76,623,953 | 1,839,674 | Seaborn Confusion Matrix - Set Data for Colorbar | <p>The follow code works, however, I want the colorbar and color to represent the %, not the count.
I can't see to find a way to specify what data the colorbar should use.
Anyone know how to do this?</p>
<pre><code>truth_labels = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
pred_labels = [1, 1, 1, 1, 0, 1, 1, 0, 0, 0]
TITLE_FONT_SIZE = {"size":"40"}
LABEL_FONT_SIZE = {"size":"40"}
LABEL_SIZE = 40
conf_matrix = confusion_matrix(pred_labels, truth_labels, labels=[1, 0])
group_counts = ["{0:0.0f}".format(value) for value in conf_matrix.flatten()]
group_normalized_percentages = (conf_matrix / np.sum(conf_matrix, axis=0, keepdims=True)).ravel()
group_normalized_percentages = ["{0:.2%}".format(value) for value in group_normalized_percentages]
cell_labels = [f"{v1}\n{v2}" for v1, v2 in zip(group_counts,group_normalized_percentages)]
cell_labels = np.asarray(cell_labels).reshape(2, 2)
sns.set(font_scale=4.0)
sns.heatmap(conf_matrix, annot=cell_labels, cmap="Blues", fmt="", ax=ax)
# Titles, axis labels, etc.
title = "Confusion Matrix\n"
ax.set_title(title, fontdict=TITLE_FONT_SIZE)
ax.set_xlabel("Actual", fontdict=LABEL_FONT_SIZE)
ax.set_ylabel("Predicted", fontdict=LABEL_FONT_SIZE)
ax.tick_params(axis="both", which="major", labelsize=LABEL_SIZE)
ax.set_xticklabels(["1", "0"])
ax.set_yticklabels(["1", "0"], rotation=90, va="center")
</code></pre>
<p><a href="https://i.sstatic.net/Cs6s3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Cs6s3.png" alt="enter image description here" /></a></p>
| <python><matplotlib><seaborn> | 2023-07-05 20:49:49 | 1 | 620 | lr100 |
76,623,767 | 3,684,433 | Why don't pydevd breakpoints work in callbacks? | <p>I've tried this in both VS Code and PyCharm, and both behave the same way. I've got a python application that uses <a href="https://github.com/stlehmann/pyads/tree/master/pyads" rel="nofollow noreferrer"><code>pyads</code></a>, but I'm not sure there's anything interesting about <code>pyads</code> in particular. The problem is that in either IDE, if I put a breakpoint on a line that will execute as a <code>pyads</code> callback/notification, the code executes but does NOT break.</p>
<p>In the case of <code>pyads</code>, I set up notifications for particular PLC tags. This associates a callback function with that tag, so if the tag's value changes, my callback executes. <code>pyads</code> is just a wrapper around <code>TcAdsDll.dll</code>, and it looks like <code>pyads</code> uses <code>ctypes</code> to do a lot of the heavy lifting. When I place a breakpoint inside the callback and run the code in VS Code or PyCharm (both of which use pydevd), the code executes but the breakpoint does not get hit.</p>
<p>Furthermore, when I print process IDs, thread IDs, and stack traces at different places in the application, I can see that the process ID is the same, but the thread ID is different inside the <code>pyads</code> callback. The stacktrace is particularly interesting. Outside of the <code>pyads</code> callback, the call chain looks like:</p>
<pre><code>runpy.py -> __main__.py -> cli.py -> pydevd_runpy.py -> my actual code
</code></pre>
<p>Inside the callback, though, the call chain looks like</p>
<pre><code>pyads\pyads_ex.py -> my callback
</code></pre>
<p>I don't know much about pydevd, but I know that all the <code>runpy.py -> __main__.py -> cli.py -> pydevd_runpy.py</code> stuff is done by VS Code to set up the debugger. I would expect (though could easily be wrong) that pydevd would also need to be part of the call chain in the callback in order for my breakpoints to work.</p>
<p>Does anyone have any more insight on this, or is there something that I've misunderstood completely? Any thoughts on how I can set breakpoints in callbacks like this? Thanks!</p>
<h2>Edit 07/06/2023 08:19 AM:</h2>
<p>My VS Code launch configuration is very basic:</p>
<pre class="lang-json prettyprint-override"><code>{
"name": "run-my-thing",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/run-my-thing.py",
"console": "integratedTerminal",
"justMyCode": true
}
</code></pre>
| <python><visual-studio-code><dll><pycharm><twincat-ads> | 2023-07-05 20:16:19 | 1 | 447 | maldata |
76,623,651 | 4,850,343 | Storage of floating point numbers in memory in Python | <p>I know that Python maintains an internal storage of small-ish integers rather than creating them at runtime:</p>
<pre><code>id(5)
</code></pre>
<pre><code>4304101544
</code></pre>
<p>When repeating this code after some time in the same kernel, the <code>id</code> is stable over time:</p>
<pre><code>id(5)
</code></pre>
<pre><code>4304101544
</code></pre>
<p>I thought that this wouldn't work for floating point numbers because it can't possibly maintain a pre-calculated list of all floating point numbers.</p>
<p>However this code returns the same <code>id</code> twice.</p>
<pre><code>id(4.33+1), id(5.33)
</code></pre>
<pre><code>(5674699600, 5674699600)
</code></pre>
<p>After some time repeating the same code returns some different location in memory:</p>
<pre><code>id(4.33 + 1), id(5.33)
</code></pre>
<pre><code>(4962564592, 4962564592)
</code></pre>
<p>What's going on here?</p>
| <python><python-internals> | 2023-07-05 19:56:21 | 2 | 17,634 | Sebastian Wozny |
76,623,208 | 12,458,212 | Run threadpool on multiple spark nodes? | <p>I've run a dual multiprocessing and multithreading solution in python before using the <em>multiprocessing</em> and <em>concurrent futures</em> python modules. However, since the multiprocessing module only runs on the driver node in spark, I have to instead use sc.parallelize to distribute workload to the worker nodes. I'm having a bit of trouble and would appreciate input on troubleshooting (code below). Here, I'm just trying to split a list of 100 values across 10 worker nodes and implement threading on each of those worker nodes.</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor
import time
def multithread(task, l):
with ThreadPoolExecutor() as executor:
results = list(executor.map(task, l))
return results
def square(x):
time.sleep(1)
return x**2
def partition(l, n):
# this function just partitions an input list into 'n' chunks
for i in range(0, len(l), n):
yield l[i:i +n]
num = list(range(100))
workers = 10
chunks = list(partition(num, workers))
rdd = sc.parallelize(chunks, numSlices=workers)
results = rdd.map(lambda x: multithread(x)).collect()
</code></pre>
<p>UPDATE:
In addition to the solution Ahmad has kindly provided, if you'd like to make the 'workers' variable dynamic, please remember not to os.cpu_count(), instead you'll need to grab this with a spark getConf() method. Also, recommend passing this to the ThreadPoolExecutor() method (ie. 'max_workers')</p>
| <python><multithreading><pyspark><parallel-processing><databricks> | 2023-07-05 18:43:01 | 1 | 695 | chicagobeast12 |
76,623,045 | 759,051 | Complete recursive transitive dependencies per row in pandas dataframe | <p>Here is a simple program that transitively maps sets of columns:</p>
<pre><code>import pandas as pd
df1vals = [{'c1': '1', 'c2': "2"}]
df1 = pd.DataFrame(df1vals, columns = ['c1' , 'c2'])
df2vals = [{'c2': '2', 'c3': "100"}]
df2 = pd.DataFrame(df2vals, columns = ['c2' , 'c3'])
df3vals = [{'c3': '100', 'c4': "x"}]
df3 = pd.DataFrame(df3vals, columns = ['c3' , 'c4'])
df4vals = [{'c1': '1', 'c4': "m"}]
df4 = pd.DataFrame(df4vals, columns = ['c1' , 'c4'])
df5vals = [{'c2': '2', 'c4': "k"}]
df5 = pd.DataFrame(df5vals, columns = ['c2' , 'c4'])
dfs = [df1,df2, df3, df4, df5]
merged_df = dfs[0]
for df in dfs[1:]:
common_cols = list(set(merged_df.columns) & set(df.columns))
merged_df = pd.merge(merged_df, df, on=common_cols, how='outer')
display(merged_df)
</code></pre>
<p>This works to produce this output:</p>
<pre><code> c1 c2 c3 c4
0 1 2 100 x
1 1 NaN NaN m
2 NaN 2 NaN k
</code></pre>
<p>This data is all good, but it's missing the fact that c1 1 is associated with c4 k through c2 2. So, I would also want this row:</p>
<pre><code>1 2 NaN k
</code></pre>
<p>I would think that the same logic that maps 1 -> 2 -> 100 -> x would also work on this, but it does not. Why?</p>
| <python><pandas><dataframe><transitive-closure> | 2023-07-05 18:16:54 | 2 | 5,463 | Jeremy |
76,622,916 | 16,284,229 | Converting desired capabilities to options in selenium python | <p>I want to convert a set of desired capabilities to options in selenium Python.
In the below code i want to find the equivalent of <code>dc["goog:loggingPrefs"] = {"browser":"INFO"}</code>
for options in selenium python.</p>
<p>I've looked at: <a href="https://peter.sh/experiments/chromium-command-line-switches/" rel="noreferrer">https://peter.sh/experiments/chromium-command-line-switches/</a>
To see if there is an equivalent loggingPrefs switch for options but there doesn't seem to be one.
The below code works for Selenium 4.7.2, but the problem is if we update to Selenium 4.10(latest) desired_capabilities is no longer supported when passing as a keyword argument to the webdriver. As far as i can see, most of the basic desired capabilities are supported by options such as brower version, name. How can we convert loggingPrefs desired capability to options for selenium webdriver.</p>
<pre><code> def printConsoleLogs():
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
#includes INFO level console messages, otherwise only SEVERE show
dc = DesiredCapabilities.CHROME.copy()
dc["goog:loggingPrefs"] = {"browser":"INFO"}
driver = webdriver.Chrome(service=service, options=options, desired_capabilities=dc)
driver.get("http://www.thepools.com")
time.sleep(5)
for entry in driver.get_log('browser'):
print(entry)
</code></pre>
<p><strong>EDIT, FOUND THE SOLUTION, LEFT FOR PEOPLE LOOKING FOR THE SAME ANSWER IN THE FUTURE:</strong></p>
<p>use <code>options.set_capability("goog:loggingPrefs", {browser: "INFO"})</code></p>
<p><strong><code>.set_capability(name, value)</code></strong>, allows you to convert your desired_capabilities to selenium options</p>
| <python><selenium-webdriver><selenium-chromedriver> | 2023-07-05 17:57:37 | 0 | 305 | Tech Visionary |
76,622,654 | 1,916,112 | I need help crafting a tricky regular expression | <p>I am trying to write some Python code that will parse some text files that use the <code>'#'</code> character to start a comment. I am looking for a way to remove trailing comments from a line in the file.</p>
<p>At first I tried <code>str.rfind('#')</code> but that was not sufficient because some of the files have comments starting with <code>"##"</code> or have multiple comments (eg. <code>#comment1 #comment2</code>).</p>
<p>I next tried a few combinations of <code>re.sub</code> to remove them but ran into problems where lines in the files contain the comment character inside of a string (eg. <code>"attempt #3"</code>).</p>
<p>In these files, as with C, string literals are surrounded by double quotes and character literals are surrounded by single quotes.</p>
<p>What I am looking for is a way, in Python, to strip trailing comments from a line without bothering them when the comment character is inside of single or double quotes.</p>
<p>Here are examples of the lines that are causing me problems for which I need an all-encompassing solution:</p>
<pre><code>variable_name ## sometimes used ## variable:L"name####":
variable_name = "Update Gen11 E5 ROM version to 1.34_04_25_2023 (#24201)"
file_name #comment1 #comment2
</code></pre>
<p>The output for these should be:</p>
<pre><code>variable_name
variable_name = "Update Gen11 E5 ROM version to 1.34_04_25_2023 (#24201)"
file_name
</code></pre>
<p>In the first case, the <code>'#'</code> inside the quotes is seen as part of the comment and is removed because there is a prior <code>'#'</code> that is not inside of quotes.</p>
<p>In the second case, the <code>'#'</code> is inside of quotes and there is no prior <code>'#'</code> so the line is left unaltered.</p>
<p>In the last case, the line is stripped staring with the first comment because that <code>'#'</code> is the left most not inside of quote.</p>
| <python><regex> | 2023-07-05 17:19:51 | 2 | 379 | Cyberclops |
76,622,435 | 850,781 | Can a python class have a class variable of this same class? | <p>I want my class to have a class variable whose value is of that same class:</p>
<pre><code>class XY:
Origin = XY(0,0)
def __init__(self, x, y):
self.x = x
self.y = y
</code></pre>
<p>however, this fails with</p>
<pre><code> Origin = XY(0,0)
NameError: name 'XY' is not defined
</code></pre>
<p>Apparently, I can do</p>
<pre><code>class XY:
...
XY.Origin = XY(0,0)
</code></pre>
<p>instead - is this really the right way?</p>
| <python><class><class-variables> | 2023-07-05 16:48:39 | 3 | 60,468 | sds |
76,622,398 | 1,485,877 | Test if Polars Series values are equal | <p>Polars has the <code>Series.series_equal</code> method for testing if two series are equal. Part of this test is that the name of each series is equal also. Is there a way to test only if the values are equal?</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
a = pl.Series("a", [1,2,3])
b = pl.Series("b", [1,2,3])
a.series_equal(b)
# False
</code></pre>
| <python><python-polars> | 2023-07-05 16:43:37 | 3 | 9,852 | drhagen |
76,622,208 | 21,055 | Preload unique related object in Django | <p>This works just fine and only performs one DB query:</p>
<pre><code>qs = Blog.objects.filter(post=Subquery(
Post.objects.filter(blog=OuterRef("pk"))
.order_by("-date").values("pk")[:1]
))
for bt, pt in qs.values_list("title", "post__title"):
print(f"The latest post in {bt} is about {pt}")
</code></pre>
<p>However, how can I have Django construct Blog and Post objects out of such a queryset without needing additional queries? Something like the following:</p>
<pre><code>for blog in qs.select_related("post"):
print(f"The latest post in {blog.title} is about {blog.post.title}")
</code></pre>
<p>Assume it’s not possible to reverse the queryset (Post.objects.select_related("blog")), because, for example, there are other related models that need the same treatment as Post.</p>
| <python><django><orm><foreign-keys> | 2023-07-05 16:14:16 | 2 | 2,951 | Roman Odaisky |
76,622,157 | 9,415,280 | tensorflow probabitily wrong output type | <p>UP DATE and ANSWER:
My error was using tf.dataset to feed my model like y_hat=model(x_tst)
using numpy array data give me the good type of output and work as supposed</p>
<p>I try to run tensorflow probality, but get stuck on output type problem.
Followinfg this <a href="https://colab.research.google.com/drive/1f2KNIFRT1I7GDI6ZPGpBpyyjp6Kt7n6Z#scrollTo=zLRRNTkJ_VWt" rel="nofollow noreferrer">exemple</a> at cell #3, with</p>
<pre><code>y_hat=model(x_tst)
</code></pre>
<p>the y_hat type is:
<code> tensorflow_probability.python.layers.internal.distribution_tensor_coercible._TensorCoercible</code></p>
<p>my input are dataset type build like that (2 heads model)</p>
<pre><code>input_1 = tf.data.Dataset.from_tensor_slices(X)
input_2 = tf.data.Dataset.from_tensor_slices(Xphysio)
output = tf.data.Dataset.from_tensor_slices(y)
combined_dataset = tf.data.Dataset.zip(((input_1, input_2), output))
input_dataset = combined_dataset.batch(32)
</code></pre>
<p>but if I use directly (like in exemple)</p>
<pre><code>y_hat=model(x_tst)
</code></pre>
<p>instead of (who seem work well and produce results):</p>
<pre><code>y_hat=model.predict(x_tst)
</code></pre>
<p>I get this error</p>
<pre><code>TypeError: Inputs to a layer should be tensors. Got: <BatchDataset element_spec=((TensorSpec(shape=(None, 120, 9), dtype=tf.float32, name=None), TensorSpec(shape=(None, 24), dtype=tf.float32, name=None)), TensorSpec(shape=(None,), dtype=tf.float32, name=None))>
</code></pre>
<p>If I use model.predict() the next step using tf probability don't work</p>
| <python><tensorflow2.0><tensor><tensorflow-probability> | 2023-07-05 16:08:56 | 1 | 451 | Jonathan Roy |
76,622,109 | 10,811,334 | NewType incompatible with bounded types | <p>I’m trying to create some new types in Python. For example:</p>
<pre class="lang-py prettyprint-override"><code>Time = NewType("Time", float)
Frequency = NewType("Frequency", float)
</code></pre>
<p>And it’s checked by mypy.</p>
<p>However say have a function <code>f: Callable[[Time], None]</code> and use it like <code>f(0.1)</code>, it gives an incompatible error until I wrap the <code>0.1</code> into <code>Time(0.1)</code>, which is quite verbose.</p>
<p>What I want is when I try to pass down a <code>Frequency</code> into <code>f</code> the type checker gives an error but not normal <code>float</code>s. Also <code>Time</code> * <code>float</code> should gives <code>Time</code>, etc.</p>
<p>Are there any ways to accomplish this?</p>
| <python><python-3.x><mypy> | 2023-07-05 16:04:03 | 0 | 554 | xiaoyu2006 |
76,622,087 | 1,445,660 | aws cdk - a target group that targets a container | <p>I have a <code>CfnTaskDefinition</code> with a <code>container_definitions</code> property and <code>requires_compatibilities=['FARGATE']</code>. A <code>Cluster</code>, a <code>CfnService</code>, a CfnLoadBalancer with <code>type='application'</code>, a <code>CfnTargetGroup</code>.
How do I set a listener for the target group with port 80, and a target that targets the container I defined, to port 8080?</p>
<p>my code:</p>
<pre><code>app_cluster = _ecs.Cluster(self, 'Cluster', cluster_name='app-cluster', vpc=default_vpc)
app_env_vars = [
_ecs.CfnTaskDefinition.KeyValuePairProperty(
name='API_ENABLED',
value='true'
)]
app_container_definitions = [
_ecs.CfnTaskDefinition.ContainerDefinitionProperty(
name='container-name',
image='ubuntu:20',
repository_credentials=_ecs.CfnTaskDefinition.RepositoryCredentialsProperty(
credentials_parameter="arn:aws:secretsmanager:eu-west-1:2222243:secret:prod/credentials-TTR3d"),
essential=True,
cpu=0,
memory=1024,
memory_reservation=1024,
log_configuration=_ecs.CfnTaskDefinition.LogConfigurationProperty(
log_driver='awslogs',
options={'awslogs-stream-prefix': 'ecs',
'awslogs-group': app_log_group.log_group_name,
'awslogs-region': 'eu-west-1'},
),
port_mappings=[
_ecs.CfnTaskDefinition.PortMappingProperty(
container_port=8080,
host_port=8080,
protocol='tcp'
)],
environment=app_env_vars)]
app_task_definition = _ecs.CfnTaskDefinition(self, 'TaskDefinition',
family='task-prod',
memory='2048',
network_mode='awsvpc',
requires_compatibilities=['FARGATE'],
execution_role_arn=role_ecs_task.role_arn,
cpu='512',
tags=[aws_cdk.CfnTag(
key='Environment',
value='prod'
)],
container_definitions=app_container_definitions)
app_target_group = _elbv2.CfnTargetGroup(self, 'TargetGroup',
name='target-group',
health_check_enabled=True,
health_check_interval_seconds=60,
health_check_timeout_seconds=30,
healthy_threshold_count=5,
unhealthy_threshold_count=5,
health_check_path='/health',
target_type='ip',
protocol='HTTP',
port=8080,
vpc_id=default_vpc.vpc_id
)
app_application_load_balancer = _elbv2.CfnLoadBalancer(self, "LB",
subnets=default_vpc.select_subnets(
subnet_type=_ec2.SubnetType.PUBLIC).subnet_ids,
name='app-lb',
type='application',
security_groups=[app_container.security_group_id],
scheme='internet-facing')
app_service = _ecs.CfnService(self, 'Service',
cluster=app_cluster.cluster_arn,
task_definition=app_task_definition.attr_task_definition_arn,
service_name='app-service',
desired_count=1,
launch_type=_ecs.LaunchType.FARGATE.name,
network_configuration=_ecs.CfnService.NetworkConfigurationProperty(
awsvpc_configuration=_ecs.CfnService.AwsVpcConfigurationProperty(
subnets=default_vpc.select_subnets(
subnet_type=_ec2.SubnetType.PUBLIC).subnet_ids,
# the properties below are optional
assign_public_ip="ENABLED",
security_groups=[
app_container.security_group_id]
)
),
load_balancers=[_ecs.CfnService.LoadBalancerProperty(
container_port=8080,
container_name='app-broker',
target_group_arn=app_target_group.attr_target_group_arn
)]
)
app_listener = _elbv2.CfnListener(self, 'Listener', port=80, default_actions=[_elbv2.CfnListener.ActionProperty(type='forward',target_group_arn=app_target_group.attr_target_group_arn,
)],
load_balancer_arn=
aws_cdk.Fn.select(0, infuse_ocpi_target_group.attr_load_balancer_arns))
</code></pre>
| <python><amazon-ecs><aws-cdk><amazon-elb><aws-fargate> | 2023-07-05 16:01:36 | 1 | 1,396 | Rony Tesler |
76,622,009 | 3,247,006 | How to experiment when session is and isn't saved in Django? | <p>I'm trying to experiment when session is and isn't saved with the 4 cases of code below in <a href="https://docs.djangoproject.com/en/4.2/topics/http/sessions/#when-sessions-are-saved" rel="nofollow noreferrer">When sessions are saved</a> but I don't know how to do it:</p>
<pre class="lang-py prettyprint-override"><code># Session is modified.
request.session["foo"] = "bar" # The 1st case
# Session is modified.
del request.session["foo"] # The 2nd case
# Session is modified.
request.session["foo"] = {} # The 3rd case
# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session["foo"]["bar"] = "baz" # The 4th case
</code></pre>
<p>I'm not going to use the code below:</p>
<pre class="lang-py prettyprint-override"><code>request.session.modified = True
</code></pre>
<p>And, I set <a href="https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-SESSION_SAVE_EVERY_REQUEST" rel="nofollow noreferrer">SESSION_SAVE_EVERY_REQUEST</a> <code>False</code> in <code>settings.py</code> as shown below:</p>
<pre class="lang-py prettyprint-override"><code># "settings.py"
SESSION_SAVE_EVERY_REQUEST = False
</code></pre>
<p>So, how can I experiment when session is and isn't saved with the 4 cases of code above?</p>
| <python><django><session><save><django-sessions> | 2023-07-05 15:51:13 | 2 | 42,516 | Super Kai - Kazuya Ito |
76,621,933 | 12,827,931 | Draw rectangles based on values in list matplotlib | <p>Suppose there's a list</p>
<pre><code>lst = [0,0,0,1,1,0,1,1]
</code></pre>
<p>I'd like to draw:</p>
<p><a href="https://i.sstatic.net/sRxXv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sRxXv.png" alt="enter image description here" /></a></p>
<p>So here's the code:</p>
<pre><code>fig, ax = plt.subplots()
ax.axvspan(-0.5, 2.5, alpha=0.4, color='yellow')
ax.axvspan(2.5, 4.5, alpha=0.4, color='red')
ax.axvspan(4.5, 5.5, alpha=0.4, color='yellow')
ax.axvspan(5.5, 7.5, alpha=0.4, color='red')
</code></pre>
<p>However, for longer lists, it takes forever to achieve that. Is there a faster way to do it?</p>
| <python><matplotlib> | 2023-07-05 15:40:37 | 3 | 447 | thesecond |
76,621,920 | 8,164,958 | Referring to other class properties in comprehension | <p>Say I define some class property based on another:</p>
<pre class="lang-py prettyprint-override"><code>class X:
foo = 42
bar = foo + 5
# X.bar == 47
</code></pre>
<p>this works fine. However, <code>foo</code> is not available if I use a list (or dict, etc.) comprehension:</p>
<pre class="lang-py prettyprint-override"><code>class X:
foo = 42
bar = [foo + i for i in range(3)]
# NameError: name 'foo' is not defined
</code></pre>
<p>This raises two questions:</p>
<ol>
<li>Why are the <code>locals()</code> at the point of assignment of <code>bar</code> not passed to the comprehension? (The "class definition" scope behaves a lot like any other scope otherwise (even allowing <code>if</code> statements and such) so this surprised me.)</li>
<li>Is there an alternative way to reference <code>foo</code> in the comprehension? (Note that <code>X.foo</code> also causes a <code>NameError</code> as <code>X</code> is not defined at that point.)</li>
</ol>
<p>I've tested this on Python 3.8, 3.9 and 3.10 and all behave identically.</p>
| <python><list-comprehension><dictionary-comprehension><class-properties> | 2023-07-05 15:39:03 | 1 | 4,605 | Seb |
76,621,886 | 9,008,261 | Cython advice for cppclass - Should I write cpp file and extern? Or should I write a python cppclass? | <p>I have a large body of python code that I am wanting to optimize. There are a few routines that can be cythonized for a significant speedup. In order to port the code to cython in a less painful manner, it would be nice to use the <code>==</code> and <code>+</code> operators for a struct that I am defining.</p>
<p>To be clear, I am not interfacing with already existing c++ code, but rather I want to use c++ structs to be able to create arrays from these structs, but still use constructors, operators and the like.</p>
<p>Firstly, I have a question. Is there any way besides using <code>extern</code> to define operator overloading.</p>
<p>For example, in python like so</p>
<pre class="lang-py prettyprint-override"><code>cdef cppclass Foo:
int bar
Foo(int)
bint operator==(Foo)
</code></pre>
<p>etc... (where would I even get to define the <code>==</code> operator?)</p>
<p>Or is it necessary to actually write c++ code and extern it in python (which seems quite verbose honestly).</p>
<p>e.g.<br />
<code>foo.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>struct Foo{
int bar;
Foo(int b){bar = b;};
bool operator == (Foo &other){
if (bar == other.bar){
return true;
} else {
return false;
};
};
};
</code></pre>
<p>and have accompanying extern code in python</p>
<pre class="lang-py prettyprint-override"><code>cdef extern from 'foo.cpp':
cdef cppclass Foo:
int bar
Foo(int)
bint operator==(Foo)
</code></pre>
<p>I find it a bit silly writing c++ code just to extern it into python. But if the support for c++ structs is not there in cython it might be the best option going forward? I have no idea what the "best practice" might be.</p>
<p>Another option I was considering is using cdef classes, but I am under the impression not to do so because</p>
<ol>
<li>Operator overloading would be a slow python operation</li>
<li>I wouldn't be able to define an array of cdef classes</li>
</ol>
<p>If I am wrong about this, please tell me.</p>
<p>Also, clearly I am not fluent in c++, so if there are symmantic (or syntactic) errors in my code please let me know (especially commas, brackets and semicolons).</p>
| <python><c++><cython> | 2023-07-05 15:33:27 | 0 | 305 | Todd Sierens |
76,621,650 | 2,437,514 | Propagate a generic type hint starting at the base class | <p>I know that I can have a generic parent class and child class, like this:</p>
<pre class="lang-py prettyprint-override"><code>from typing import Generic, TypeVar
T = TypeVar('T')
class Parent(Generic[T]):
member_x: T
class Child1(Parent[T]):
pass
</code></pre>
<p>Now let's say I have many child classes, <code>Child2</code>, <code>Child3</code>, etc, which all inherit from <code>Parent[T]</code>. Inside of my_module.py, I can give them all typing information like this:</p>
<pre class="lang-py prettyprint-override"><code># my_module.py
from project.my_types import Child1, Child2, Child3
T = float
obj1 = Child1[T]()
obj1.member_x = 1 # no typecheck error
obj2 = Child2[T]()
obj2.member_x = 2 # no typecheck error
obj3 = Child3[T]()
obj3.member_x = '3' # typecheck error!!
</code></pre>
<p>But what I would like to do is tell the type checker that in my_module, ALL of the instances that are from child classes of <code>Parent</code> should have <code>member_x</code> the type, <code>float</code>, and then just write the code ignoring typing syntax after that, like so:</p>
<pre class="lang-py prettyprint-override"><code># my_module.py
from project.my_types import Parent, Child1, Child2, Child3
# incantation goes here informing type checker that the type T for Parent and all its children is `float`
obj1 = Child1()
obj1.member_x = 1 # no typecheck error
obj2 = Child2()
obj2.member_x = 2 # no typecheck error
obj3 = Child3()
obj3.member_x = '3' # typecheck error!!
</code></pre>
<p>Can I do it?</p>
| <python><python-typing> | 2023-07-05 15:03:38 | 1 | 45,611 | Rick |
76,621,598 | 10,158,066 | How can I reshape my dataframe into a 3-dimensional numpy array? | <p>My dataframe contains a multivariate time series per user id. The first column <code>id</code> is the user id (there are N users), the second <code>dt</code> is the date (each user has T days worth of data, i.,e T rows for each user) and the other columns are metrics (basically, each column is a time series per id.) Here's a code to recreate a similar dataframe</p>
<pre><code>import pandas as pd
from datetime import datetime
import numpy as np
N=5
T=100
dfs=[]
datelist = pd.date_range(datetime.today(), periods=T).tolist()
for id in range(N):
test = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
test['dt'] = datelist
test['id']=id
dfs.append(test)
dfs = pd.concat(dfs)
</code></pre>
<p>The output would look something like this, where 'A','B' and so on are metrics (like total purchases):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: right;"></th>
<th style="text-align: right;">A</th>
<th style="text-align: right;">B</th>
<th style="text-align: right;">C</th>
<th style="text-align: right;">D</th>
<th style="text-align: left;">dt</th>
<th style="text-align: right;">id</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">0</td>
<td style="text-align: right;">58</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">52</td>
<td style="text-align: right;">5</td>
<td style="text-align: left;">2023-07-05 14:34:12.852460</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">34</td>
<td style="text-align: right;">28</td>
<td style="text-align: right;">88</td>
<td style="text-align: left;">2023-07-06 14:34:12.852460</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: right;">2</td>
<td style="text-align: right;">27</td>
<td style="text-align: right;">98</td>
<td style="text-align: right;">74</td>
<td style="text-align: right;">81</td>
<td style="text-align: left;">2023-07-07 14:34:12.852460</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: right;">3</td>
<td style="text-align: right;">96</td>
<td style="text-align: right;">13</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">52</td>
<td style="text-align: left;">2023-07-08 14:34:12.852460</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td style="text-align: right;">4</td>
<td style="text-align: right;">80</td>
<td style="text-align: right;">69</td>
<td style="text-align: right;">22</td>
<td style="text-align: right;">12</td>
<td style="text-align: left;">2023-07-09 14:34:12.852460</td>
<td style="text-align: right;">0</td>
</tr>
</tbody>
</table>
</div>
<p>I want to transform this data into a numpy matrix X, of shape N x T x F, where N is the number of users, T is the number of days in the time series (T is constant for all ids) and F is the number of metrics (in the example above, F=4.)</p>
<p>This means that X[0] returns a TxF array, that should look exactly like the output of <code>dfs.query('id==0')[['A','B','C','D']].values</code></p>
<p>So far, I've tried using <code>pivot</code> and <code>reshape</code> but the elements in the final matrix are not arranged as I would like. Here's what I've tried:</p>
<pre><code># Pivot the dataframe
df_pivot = dfs.sort_values(['id','dt']).pivot(index='id', columns='dt')
# Get the values from the pivot table
X = df_pivot.values.reshape(dfs['id'].nunique(), -1, len([x for x in dfs.columns if x not in ['dt','id']]))
</code></pre>
<p>If I do <code>X[0]</code>, the result I get it:</p>
<pre><code>[58, 6, 27, 96],
[80, 65, 41, 39],
[30, 26, 38, 13],
[50, 60, 60, 73],
...
</code></pre>
<p>From which you can see that the result is not what I would want. This is what I need:</p>
<pre><code>[58, 3, 52, 5],
[ 6, 34, 28, 88],
[27, 98, 74, 81],
[96, 13, 7, 52],
...
</code></pre>
<p>Any help appreciated!</p>
| <python><pandas><dataframe><numpy> | 2023-07-05 14:58:08 | 4 | 445 | Steven Cunden |
76,621,589 | 11,829,398 | How to run async methods in langchain? | <p>I have a basic chain that classifies some text based on the Common European Framework of Reference for Languages. I'm timing the difference between normal <code>chain.apply</code> and <code>chain.aapply</code> but can't get it to work.</p>
<p>What am I doing wrong?</p>
<pre class="lang-py prettyprint-override"><code>import os
from time import time
import openai
from dotenv import load_dotenv, find_dotenv
from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
_ = load_dotenv(find_dotenv())
openai.api_key = os.getenv('OPENAI_API_KEY')
llm = ChatOpenAI(temperature=0)
prompt = ChatPromptTemplate.from_template(
'Classify the text based on the Common European Framework of Reference '
'for Languages (CEFR). Give a single value: {text}',
)
chain = LLMChain(llm=llm, prompt=prompt)
texts = [
{'text': 'Hallo, ich bin 25 Jahre alt.'},
{'text': 'Wie geht es dir?'},
{'text': 'In meiner Freizeit, spiele ich gerne Fussball.'}
]
start = time()
res_a = chain.apply(texts)
print(res_a)
print(f"apply time taken: {time() - start:.2f} seconds")
print()
start = time()
res_aa = chain.aapply(texts)
print(res_aa)
print(f"aapply time taken: {time() - start:.2f} seconds")
</code></pre>
<p>Output</p>
<pre><code>[{'text': 'Based on the given text "Hallo, ich bin 25 Jahre alt," it can be classified as CEFR level A1.'}, {'text': 'A2'}, {'text': 'A2'}]
apply time taken: 2.24 seconds
<coroutine object LLMChain.aapply at 0x0000025EA95BE3B0>
aapply time taken: 0.00 seconds
C:\Users\User\AppData\Local\Temp\ipykernel_13620\1566967258.py:34: RuntimeWarning: coroutine 'LLMChain.aapply' was never awaited
res_aa = chain.aapply(texts)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
</code></pre>
| <python><langchain><py-langchain> | 2023-07-05 14:57:02 | 1 | 1,438 | codeananda |
76,621,542 | 785,404 | How can I kill a "perf record" command after a timeout with subprocess? | <p>I have this code:</p>
<pre class="lang-py prettyprint-override"><code>subprocess.run(['perf', 'record', 'yes'], timeout=1)
</code></pre>
<p>This code kills the <code>perf</code> subprocess after 1 second; however, its child <code>yes</code> process is left running.</p>
<p>I expected that this code would behave similarly to running <code>perf record yes</code> in a terminal and Ctrl+C'ing it after 1 second. When you do that, the Ctrl+C kills both <code>perf</code> and <code>yes</code>.</p>
<p>How can I write the code such that both the <code>perf</code> child process and the <code>yes</code> grandchild process are killed?</p>
| <python><subprocess> | 2023-07-05 14:50:42 | 1 | 2,085 | Kerrick Staley |
76,621,424 | 1,456,253 | Cause of pytest ValueError: fixture is being applied more than once to the same function | <p>I have a unit test I'm running with a particular fixture. The fixture is pretty simple and looks like so:</p>
<pre><code>@pytest.fixture
def patch_s3():
# Create empty bucket
bucket = s3_resource().create_bucket(Bucket=BUCKET)
bucket.objects.all().delete()
yield
bucket.objects.all().delete()
</code></pre>
<p>and the test isn't all that complicated either. Here is the signature for the test:</p>
<pre><code>def test_task_asg(patch_s3, tmp_path, monkeypatch)
</code></pre>
<p>However, when I run pytest, I get the following error:</p>
<pre><code>tests/test_task_asg.py:313: in <module>
@pytest.fixture
home/ubuntu/miniconda/envs/pipeline/lib/python3.7/site-packages/_pytest/fixtures.py:1150: in fixture
fixture_function
home/ubuntu/miniconda/envs/pipeline/lib/python3.7/site-packages/_pytest/fixtures.py:1011: in __call__
"fixture is being applied more than once to the same function"
E ValueError: fixture is being applied more than once to the same function
</code></pre>
<p>This is weird to me, as it seems to imply I'm somehow including <code>patch_s3</code> more than once in <code>test_task_asg</code>. What could be causing this?</p>
| <python><unit-testing><pytest><pytest-fixtures> | 2023-07-05 14:36:16 | 1 | 2,397 | code11 |
76,621,374 | 3,595,026 | How to mock SQLAlchemy's limit and offset functions using MagicMock? | <p>I am trying to write a unit test for SQLAlchemy's Limit Offset functions. I am new to Python unit testing and I am not sure how to mock the <code>session.query(table).limit(20).offset(20)</code> part. I use <code>unittest.mock.patch</code> to mock the <code>load_session</code> function. Any help would be appreciated. Thanks in advance.
I have tried a few syntaxes but none of them worked. Example:</p>
<p>Source code:</p>
<pre><code> def execute():
...
db2_engine = get_db2_engine()
session = load_session(db2_engine)
result_set = session.query(Table).limit(20).offset(20)
db2_session.close()
...
</code></pre>
<p>Test code:</p>
<pre><code> import unittest
from unittest.mock import MagicMock, patch
def setUp(self):
self.worker = MyClass(
...
)
@patch("source_class.load_session")
def test_execute(self, mock_load_session):
...
mock_session = MagicMock()
mock_session.query.return_value = MagicMock()
mock_session.query.return_value.limit.return_value = MagicMock()
mock_session.query.return_value.limit.return_value.offset.return_value = [...]
mock_load_session.return_value = mock_session
...
self.worker.execute()
...
</code></pre>
| <python><unit-testing><sqlalchemy><python-unittest><magicmock> | 2023-07-05 14:30:32 | 0 | 629 | user3595026 |
76,621,344 | 4,466,255 | How can I weigh each batch differently in pytorch CrossEntropyLoss | <p>My understanding is that torch.nn.CrossEntropyLoss creates loss value for each item of the batch and sums it to give final loss. Suppose in the following toy example we want to multiply the loss of each of 3 items in batch with corresponding elements in an array <code>multiplier</code> before summing. How do I achieve this?</p>
<pre><code>import torch
import numpy as np
multiplier = torch.from_numpy(np.array([1.0, -2.0, 5.0]))
source = torch.from_numpy(
np.array([[0.5, -0.6],
[-3.0, -2.0],
[-4.0, 2.3]]))
target = torch.from_numpy(np.array([0, 1, 0]))
loss_fn = torch.nn.CrossEntropyLoss()
loss_fn(source, target)
</code></pre>
<p>Note that the weight argument of the function weighs the various target indices differently, that is not what I want.</p>
| <python><pytorch> | 2023-07-05 14:27:01 | 1 | 1,208 | Kushdesh |
76,621,250 | 12,691,626 | Efficiently subset a 2D numpy array iteratively | <p>I have a large image on which I want to perform an operation from a moving window over the whole window. Here is a reproducible example:</p>
<p>Given an array named <code>image</code> with shape (5, 5), I need to extract subsets from the array in 3x3 windows.</p>
<pre><code>import numpy as np
# example dada
image = np.array([[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]])
</code></pre>
<p><strong>Out[1]:</strong></p>
<pre><code>array([[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5]])
</code></pre>
<p>For a 3x3 window the first subset is:</p>
<pre><code># first iteration
window_size = 3
image[0:window_size, 0:window_size] # from 1st to 3th row and from 1st to 3th col
</code></pre>
<p><strong>Out[2]:</strong></p>
<pre><code>array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
</code></pre>
<p>So I can access to the different subsets using a nested loop:</p>
<pre><code>for i in range(0, image.shape[0]-window_size+1):
for j in range(0, image.shape[1]-window_size+1):
a = (j,i) # top left value
b = (j,i+window_size) # top right value
c = (j+window_size,i) # bottom left value
d = (j+window_size,i+window_size) # bottom right value
print('Window position', a,b,c,d)
subset = image[i:i+window_size, j:j+window_size]
print(subset)
</code></pre>
<p>Is there a more efficient way to perform this operation and avoid doing these two loops?</p>
| <python><numpy><performance><nested-loops> | 2023-07-05 14:14:54 | 2 | 327 | sermomon |
76,621,154 | 17,487,457 | summary plot with FastTreeSHAP | <p>I fitted a random forest classifier, and wanted to use the <code>FastTreeSHAP</code> to understand predictors contribution to model predictions.</p>
<pre class="lang-py prettyprint-override"><code>import fasttreeshap
explainer = fasttreeshap.TreeExplainer(model, algorithm='auto' ,n_jobs=-1)
shap_values = explainer(X_test).values
shap_values.shape
(40682, 24, 5)
# plotting
fasttreeshap.summary_plot(shap_values, X_test, plot_type = 'bar')
</code></pre>
<p>However, this produces an interaction plot instead (see below).</p>
<p><a href="https://i.sstatic.net/ASSpG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ASSpG.png" alt="enter image description here" /></a></p>
<p><strong>Required</strong></p>
<p>A bar plot showing predictors' contribution, such as example in figure below (from <code>FastTreeSHAP</code> docs).</p>
<p><a href="https://i.sstatic.net/9H9sP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9H9sP.png" alt="enter image description here" /></a></p>
<p>Is <code>FastTreeSHAP</code>'s <code>summary_plot()</code> different from that of <code>SHAP</code>, or did something change?</p>
| <python><shap> | 2023-07-05 14:05:12 | 1 | 305 | Amina Umar |
76,620,968 | 4,715,567 | How to flatten a list of dict and get specific text | <p>I have a pandas dataframe with 2 columns. The first is an id and the second column contains a list of nested dict and some rows have NaN value. My dataframe have a lot of rows so below you will find a snapshot.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Id</th>
<th style="text-align: center;">list_dict</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">NaN</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">[{'type': 'paragraph','content': [{'type': 'text','text': 'XXX'}]},{'type': 'paragraph','content': [{'type': 'text','text': 'XXX'}]},{'type': 'paragraph','content': [{'type': 'hardBreak'},{'type': 'text','text': 'XXX'},{'type': 'hardBreak'}]},{'type': 'paragraph','content': [{'type': 'text','text': 'XXX'}]}]</td>
</tr>
<tr>
<td style="text-align: left;">3</td>
<td style="text-align: center;">NaN</td>
</tr>
</tbody>
</table>
</div>
<p>My goal is to get the key ('text'), value ('XXX') and concatenate the values (XXX XXX XXX). Please keep in mind that value XXX is a text so in every value('text') I have different content.</p>
| <python><pandas><dataframe><dictionary> | 2023-07-05 13:44:22 | 1 | 377 | Jimmys |
76,620,938 | 1,014,217 | { "message": "Error : An error occurred: 'str' object does not support item assignment." } | <p>I have a blob storage account where I dropped a single file.
Then I want to add a record on pinecone based on this file using langchain:</p>
<pre><code>@app.get("/BlobStorage")
def IndexContainer(storageContainer: str, indexName: str, namespace_name: str):
logging.info('Python HTTP trigger function IndexContainer processed a request.')
try:
pinecone.init(
api_key=os.getenv("pineconeapikey"),
environment=os.getenv("pineconeenvironment")
)
connect_str = os.getenv('blobstorageconnectionstring')
loader = AzureBlobStorageContainerLoader(conn_str=connect_str, container=storageContainer)
embeddings = OpenAIEmbeddings(deployment=os.getenv("openai_embedding_deployment_name"),
model=os.getenv("openai_embedding_model_name"),
chunk_size=1)
openai.api_type = "azure"
openai.api_version =os.getenv("openai_api_version")
openai.api_base =os.getenv("openai_api_base")
openai.api_key =os.getenv("openai_api_key")
documents = loader.load()
texts = []
metadatas = []
for doc in documents:
texts.append(doc.page_content)
metadatas.append(doc.metadata['source'])
docsearch = Pinecone.from_texts(
texts,
embeddings,
index_name=indexName,
metadatas=metadatas,
namespace=namespace_name
)
return {
"message":f"File indexed. This HTTP triggered function executed successfully."
}
except Exception as e:
error_message = f"An error occurred: {str(e)}"
logging.exception(error_message)
return {
"message":f"Error : {error_message}."
}
</code></pre>
<p>I debugged this code line by line and all variables are setup correctly and the exception is only thrown until the <em>from_texts</em> method.</p>
<p>However I get this error:</p>
<blockquote>
<p>An error occurred: 'str' object does not support item assignment.</p>
</blockquote>
<p>loader.load is below:</p>
<pre><code>[Document(page_content="long content", metadata={'source': 'C:\\Users\\xx\\AppData\\Local\\Temp\\tmpk5cqh4nd/abc/filenameAI sorting_Project Description.docx'})]
</code></pre>
<h3>Stack trace</h3>
<p><a href="https://i.sstatic.net/00Toc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/00Toc.png" alt="Enter image description here" /></a></p>
<p>What am I missing?</p>
<p>I based my code on the unit tests of langchain:</p>
<p><a href="https://github.com/hwchase17/langchain/blob/e27ba9d92bd2cc4ac9ed7439becb2d32816fc89c/tests/integration_tests/vectorstores/test_pinecone.py#L118" rel="nofollow noreferrer">https://github.com/hwchase17/langchain/blob/e27ba9d92bd2cc4ac9ed7439becb2d32816fc89c/tests/integration_tests/vectorstores/test_pinecone.py#L118</a></p>
<p>If it helps, the Blob Storage Container loader from Langchain is implemented here:</p>
<p><a href="https://github.com/hwchase17/langchain/blob/e27ba9d92bd2cc4ac9ed7439becb2d32816fc89c/langchain/document_loaders/azure_blob_storage_container.py" rel="nofollow noreferrer">https://github.com/hwchase17/langchain/blob/e27ba9d92bd2cc4ac9ed7439becb2d32816fc89c/langchain/document_loaders/azure_blob_storage_container.py</a></p>
| <python><azure-blob-storage><langchain><pinecone> | 2023-07-05 13:39:58 | 1 | 34,314 | Luis Valencia |
76,620,914 | 11,329,736 | Read the docs build module not found error, but no local issue | <p>I am trying to use the <code>sphinx-click</code> module in my rst file for my documentation on Read the Docs. It normally auto-builds from the git repo without any issues but now that I want to use <code>sphinx-click</code> I run into issues:</p>
<pre><code>Running Sphinx v5.3.0
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/pycrispr/envs/latest/lib/python3.7/site-packages/sphinx/registry.py", line 459, in load_extension
mod = import_module(extname)
File "/home/docs/checkouts/readthedocs.org/user_builds/pycrispr/envs/latest/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'sphinx_click'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/pycrispr/envs/latest/lib/python3.7/site-packages/sphinx/cmd/build.py", line 280, in build_main
args.pdb)
File "/home/docs/checkouts/readthedocs.org/user_builds/pycrispr/envs/latest/lib/python3.7/site-packages/sphinx/application.py", line 223, in __init__
self.setup_extension(extension)
File "/home/docs/checkouts/readthedocs.org/user_builds/pycrispr/envs/latest/lib/python3.7/site-packages/sphinx/application.py", line 398, in setup_extension
self.registry.load_extension(self, extname)
File "/home/docs/checkouts/readthedocs.org/user_builds/pycrispr/envs/latest/lib/python3.7/site-packages/sphinx/registry.py", line 463, in load_extension
err) from err
sphinx.errors.ExtensionError: Could not import extension sphinx_click (exception: No module named 'sphinx_click')
Extension error:
Could not import extension sphinx_click (exception: No module named 'sphinx_click')
</code></pre>
<p>My <code>conf.py</code> includes the following line:</p>
<pre><code>extensions = ['sphinx_click']
</code></pre>
<p>And my <code>setup.py</code> includes <code>sphinx-click</code>:</p>
<pre><code>install_requires=['numpy','pandas','pyyaml','Click','sphinx-click'
]
</code></pre>
<p>When I build the docs locally, it runs without any errors (although with one warning):</p>
<pre><code>Running Sphinx v5.3.0
WARNING: html_static_path entry '_static' does not exist
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: 0 added, 1 changed, 0 removed
reading sources... [100%] execution/userguide
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index
generating indices... genindex done
writing additional pages... search done
copying images... [100%] execution/report.png
copying static files... done
copying extra files... done
dumping search index in English (code: en)... done
dumping object inventory... done
build succeeded, 1 warning.
The HTML pages are in temp.
</code></pre>
<p>How can I tell the remote server to install the <code>sphinx-click</code> module?</p>
| <python><python-sphinx><read-the-docs> | 2023-07-05 13:37:36 | 1 | 1,095 | justinian482 |
76,620,873 | 2,587,931 | Normalization in Keras | <p>When I use the normalization with keras:</p>
<pre><code>tf.keras.layers.Normalization()
</code></pre>
<p><strong>Where should I use it?</strong></p>
<p>I adapt it with train data:</p>
<pre><code>x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
normalization_layer = tf.keras.layers.Normalization()
normalization_layer.adapt(x_train)
</code></pre>
<p>And then, I can normalize the data (train and test) prior to use in model.fit and model.evaluate:</p>
<pre><code>x_train = normalization_layer(x_train)
x_test = normalization_layer(x_test)
</code></pre>
<p>Or include the layer in de network model, as the FIRST layer</p>
<pre><code>model = tf.keras.models.Sequential()
model.add(normalization_layer)
...
</code></pre>
<p>If I use the latter option:</p>
<ul>
<li>Does this normalization is applied to train (on model.fit) and test (on model.evaluate) or is only aplplied on mode.fit?</li>
<li>During training (model fit) is this normalization applied ON EACH batch/epoch or the algorithm is smart enough to only apply the normalization once?</li>
</ul>
| <python><tensorflow><keras> | 2023-07-05 13:33:15 | 1 | 1,105 | Kaikus |
76,620,835 | 10,381,546 | QhullError (QH6019) in scipy.interpolate.griddata | <p>As part of a larger analysis I am interpolating data at points to a grid using scipy.interpolate.griddata. (scipy version 1.9.3)
Since recently it worked without problems. Now I am getting QHullError QH6019 on one computer, however not on another system. Both are Linux systems with same Python version (3.9.13), venv setup etc. One difference is that on the system that throws the error qhull is installed from the system repositories, while the other does not have qhull as such (I believe scipy brings its own then).</p>
<p>The function that does the interpolation is:</p>
<pre class="lang-py prettyprint-override"><code>def grid_interp(data, name, xgrid, ygrid):
'''
Interpolates point data from geopandas geoseries to a numpy 2D-array of regularly spaced grid points.
'''
points = np.vstack((data.geometry.x, data.geometry.y)).T
values = griddata(
points, data[name],
(xgrid, ygrid),
method=Config.interpolation_method, # 'linear' and 'cubic' will result in nan outside of the convex hull of data points
)
nan_mask = np.isnan(values) # if there are any nan points re-interpolate them using method 'nearest'
if np.any(nan_mask):
values2 = griddata(
points, data[name],
(xgrid, ygrid), method='nearest',
)
values[nan_mask] = values2[nan_mask]
return values
</code></pre>
<p>with <code>data</code> being a geopandas dataframe (with geometry projection as EPSG25832), <code>name</code> the column name that holds the values to interpolate, and <code>xgrid</code> and <code>ygrid</code> are the gridpoints resulting from:</p>
<pre class="lang-py prettyprint-override"><code>xgrid, ygrid = np.meshgrid(np.arange(xmin, xmax + xres, xres), np.arange(ymin, ymax + yres, yres))
</code></pre>
<p>I have seen in other question, that qhull has problems with some projections (e.g. <a href="https://stackoverflow.com/questions/59638716/qhullerror-when-plotting-wind-barbs">here</a>), however, I know that it works with the current projection from the second system where I don't get the error.</p>
<p>The full error message is:</p>
<pre class="lang-py prettyprint-override"><code>---------------------------------------------------------------------------
QhullError Traceback (most recent call last)
/home/ts/analysis/analysis_geospatial.ipynb Cell 11 in 8
3 xgrid, ygrid = np.meshgrid(np.arange(xmin, xmax + xres, xres),
4 np.arange(ymin, ymax + yres, yres),
5 )
7 # target_values = grid_interp(station_data, target, xgrid, ygrid)
----> 8 target_values = grid_interp(station_data, 'MassConcentration', xgrid, ygrid)
9 sedDBD_values = grid_interp(station_data, 'SedDryBulkDensity', xgrid, ygrid)
11 target_clipped = grid_clip(target_values, poly, xgrid, ygrid)
/home/ts/analysis/analysis_geospatial.ipynb Cell 11 in 7
2 '''
3 Interpolates point data from geopandas geoseries to a numpy 2D-array of regularly spaced grid points.
4 '''
6 points = np.vstack((data.geometry.x, data.geometry.y)).T
----> 7 values = griddata(
8 points, data[name],
9 (xgrid, ygrid),
10 method=Config.interpolation_method, # 'linear' and 'cubic' will result in nan outside of the convex hull of data points
11 # qhull_options='Qz',
12 )
13 nan_mask = np.isnan(values) # if there are any nan points re-interpolate them using method 'nearest'
15 if np.any(nan_mask):
File ~/.local/share/virtualenvs/ts/lib/python3.9/site-packages/scipy/interpolate/_ndgriddata.py:260, in griddata(points, values, xi, method, fill_value, rescale)
258 return ip(xi)
259 elif method == 'linear':
--> 260 ip = LinearNDInterpolator(points, values, fill_value=fill_value,
261 rescale=rescale)
262 return ip(xi)
263 elif method == 'cubic' and ndim == 2:
File interpnd.pyx:280, in scipy.interpolate.interpnd.LinearNDInterpolator.__init__()
File _qhull.pyx:1846, in scipy.spatial._qhull.Delaunay.__init__()
File _qhull.pyx:358, in scipy.spatial._qhull._Qhull.__init__()
QhullError: QH6019 qhull input error (qh_scalelast): can not scale last coordinate to [ 0, inf]. Input is cocircular or cospherical. Use option 'Qz' to add a point at infinity.
While executing: | qhull d Q12 Qt Qbb Qc Qz
Options selected for Qhull 2019.1.r 2019/06/21:
run-id 559977496 delaunay Q12-allow-wide Qtriangulate Qbbound-last
Qcoplanar-keep Qz-infinity-point _pre-merge _zero-centrum Qinterior-keep
Pgood _maxoutside 0
</code></pre>
| <python><scipy><interpolation><qhull> | 2023-07-05 13:28:17 | 0 | 304 | roble |
76,620,726 | 2,836,175 | How do I run many Singularity/Apptainer containers from one Python script, using multiple CPUs and nodes? | <h2>Problem statement</h2>
<p>I have a Python program that needs to launch a number of Singularity containers in parallel.</p>
<p><strong>Is it possible to do this, exploiting all of the available hardware, using only built-in libraries (<code>subprocessing</code>, <code>concurrent.futures</code>, etc)?</strong></p>
<p>The 'host' script runs on 1 CPU. It is launched by SLURM. The 'host' needs to launch the containers, wait for them to complete, do some analysis, repeat.</p>
<p>For example, if I have 40 containers each needing 2 CPUs, and two nodes each with 76 CPUs, then there should be something like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Node 1 (76 CPUs)</th>
<th>Node 2 (76 CPUs)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Host script (1 CPU)</td>
<td>3 containers (6 CPUs)</td>
</tr>
<tr>
<td>37 containers (74 CPUs)</td>
<td>70 spare CPUs</td>
</tr>
<tr>
<td>1 spare CPU</td>
<td></td>
</tr>
</tbody>
</table>
</div><h2>MWE</h2>
<h4>Singularity recipe (<code>stress.def</code>)</h4>
<p>We use <code>stress</code> to fully utilise a given number of CPUs:</p>
<pre><code>Bootstrap: docker
From: ubuntu:16.04
%post
apt update -y
apt install -y stress
%runscript
echo $(uname -n)
stress "$@"
</code></pre>
<p>Build with <code>singularity build stress.simg stress.def</code>.</p>
<h4>Python host script (<code>main.py</code>)</h4>
<p>Spin up 40 containers, each running the <code>stress</code> image with 2 CPUs for 10s:</p>
<pre class="lang-py prettyprint-override"><code>from subprocess import Popen
n_processes = 40
cpus_per_process = 2
stress_time = 10
command = [
"singularity",
"run",
"stress.simg",
"-c",
str(cpus_per_process),
"-t",
f"{stress_time}s",
]
processes = [Popen(command) for i in range(n_processes)]
for p in processes:
p.wait()
</code></pre>
<h4>SLURM script</h4>
<pre><code>#!/bin/bash
#SBATCH -J stress
#SBATCH -A myacc
#SBATCH -p mypart
#SBATCH --output=%x_%j.out
#SBATCH --nodes=2
#SBATCH --ntasks=40
#SBATCH --cpus-per-task=2
#SBATCH --time=24:00:00
python main.py
</code></pre>
<h2>Results</h2>
<p>The above only runs on one of the two nodes. Total execution time is around 20s, and the Singularity containers are run sequentially - the first 38 are run, and then the last two.</p>
<p>As such, it does not have the desired effect.</p>
| <python><subprocess><hpc><singularity-container> | 2023-07-05 13:16:17 | 2 | 939 | theo-brown |
76,620,653 | 5,462,551 | Default (nested) dataclass initialization in hydra when no arguments are provided | <p>I have the following code, using the <a href="https://hydra.cc/" rel="nofollow noreferrer">hydra</a> framework</p>
<pre class="lang-py prettyprint-override"><code># dummy_hydra.py
from dataclasses import dataclass
import hydra
from hydra.core.config_store import ConfigStore
from omegaconf import DictConfig, OmegaConf
@dataclass
class Foo:
x: int = 0
y: int = 1
@dataclass
class Bar:
a: int = 0
b: int = 1
@dataclass
class FooBar:
foo: Foo
bar: Bar
cs = ConfigStore.instance()
cs.store(name="config_schema", node=FooBar)
@hydra.main(config_name="dummy_config", config_path=".", version_base=None)
def main(config: DictConfig):
config_obj: FooBar = OmegaConf.to_object(config)
print(config_obj)
if __name__ == '__main__':
main()
</code></pre>
<p>(This is a simplified code of my actual use case, of course)</p>
<p>As you can see, I have a nested dataclass - the <code>FooBar</code> class contains instances of <code>Foo</code> and <code>Bar</code>. <strong>Both <code>Foo</code> and <code>Bar</code> have default attribute values</strong>. Hence, I thought I can define a yaml file that does not necessarily initializes <code>Foo</code> and/or <code>Bar</code>. Here's the file I use:</p>
<pre class="lang-yaml prettyprint-override"><code># dummy_config.yaml
defaults:
- config_schema
- _self_
foo:
x: 123
y: 456
</code></pre>
<p>When I run this code, surprisingly (?) it does not initialize <code>Bar</code> (which is not mentioned in the yaml config file), but throws an error:</p>
<pre class="lang-bash prettyprint-override"><code>omegaconf.errors.MissingMandatoryValue: Structured config of type `FooBar` has missing mandatory value: bar
full_key: bar
object_type=FooBar
</code></pre>
<p><strong>What's the proper way to use this class structure such that I don't need to explicitly initialize classes with non-mandatory fields (such as <code>Bar</code>)?</strong></p>
| <python><fb-hydra><omegaconf> | 2023-07-05 13:07:56 | 2 | 4,161 | noamgot |
76,620,602 | 16,383,578 | Optimized Quick sort in Python | <p>I have read that Quick sort is one of the most efficient sorting algorithms (if not THE most), but I don't understand why it is so slow.</p>
<p>Before you try to close as duplicate, of course I have read <a href="https://stackoverflow.com/questions/18262306/quicksort-with-python">this question</a>, but it was posted almost a decade ago, and none of the answers were optimized.</p>
<p>I tested code from many answers and found them all inefficient, and I implemented a version of mine own with rudimentary optimization:</p>
<pre class="lang-py prettyprint-override"><code>import random
from collections import deque
def qsort(arr):
if len(arr) <= 1:
return arr
else:
return qsort([x for x in arr[1:] if x < arr[0]]) + [arr[0]] + qsort([x for x in arr[1:] if x >= arr[0]])
def quick_sort(arr):
if len(arr) <= 1:
return arr
lt = deque()
ge = deque()
e0 = arr.popleft()
for e in arr:
if e < e0:
lt.append(e)
else:
ge.append(e)
return quick_sort(lt) + deque([e0]) + quick_sort(ge)
def quick_sort_helper(arr):
return quick_sort(deque(arr))
order = list(range(256))
chaos = random.choices(range(666), k=256)
</code></pre>
<pre><code>In [2]: %timeit qsort(chaos)
480 µs ± 2.83 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [3]: %timeit qsort(order)
4.05 ms ± 45.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [4]: %timeit quick_sort_helper(chaos)
394 µs ± 9.6 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [5]: %timeit quick_sort_helper(order)
3.06 ms ± 57.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>They are all extremely slow, but my optimization did help a little. (I have done many other tests, they are not included for brevity)</p>
<p>For comparison, here is the performance of a version of insertion sort I wrote in under 3 minutes:</p>
<pre><code>def bisect_right(a, x):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if x < a[mid]:
hi = mid
else:
lo = mid + 1
return lo
def insertion_sort(arr):
out = deque()
for e in arr:
out.insert(bisect_right(out, e), e)
return out
</code></pre>
<pre><code>In [12]: %timeit insertion_sort(chaos)
311 µs ± 6.28 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [13]: %timeit insertion_sort(order)
267 µs ± 7.93 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
</code></pre>
<p>How to optimize the algorithm so as to reduce recursion and identify sorted sub sequences to eliminate unnecessary computation?</p>
<hr />
<p>The code from the <a href="https://stackoverflow.com/a/31102672/16383578">answer</a> linked in a comment below is surprisingly <em><strong>NOT</strong></em> faster than mine:</p>
<pre><code>In [22]: %timeit qsort(chaos, 0, 255)
391 µs ± 6.95 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
</code></pre>
<p>It seems to perform better in the worst case, but that's about it.</p>
<pre><code>In [28]: %timeit qsort(order, 0, 255)
360 µs ± 6.43 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
</code></pre>
| <python><python-3.x><algorithm><sorting><optimization> | 2023-07-05 13:00:29 | 1 | 3,930 | Ξένη Γήινος |
76,620,574 | 1,493,192 | Convert a datatime with milliseconds from a given data and a fiven fractional seconds | <p>I have a given data, for example:</p>
<pre><code>"2021-12-01 12:00:00" (i.e., %Y-%m-%d %H:%M:%S)
</code></pre>
<p>and a given millisecond: <code>3599.9</code>. I wish to add this millisecond to the previus date in order to have the following format:</p>
<p><code>%Y-%m-%d %H:%M:%S.%f</code> or <code>%Y-%m-%d %H:%M:%S:%f</code></p>
<p>I found some example, but all starting with <code>datetime.utcnow()</code>. For example:</p>
<pre><code>>>> from datetime import datetime
>>> (dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
>>> "%s.%03d" % (dt, int(micro) / 1000)
'2016-02-26 04:37:53.133'
</code></pre>
| <python><datetime><java-dateformat><milliseconds> | 2023-07-05 12:57:22 | 1 | 8,048 | Gianni Spear |
76,620,464 | 1,991,502 | mypy doesn't catch a type error if the error is in main(). Why? | <p>mypy will catch an incompatible type error in this case</p>
<pre><code>class MyClass():
def __init__(self, a: int):
pass
channel = MyClass(0.)
</code></pre>
<p>but not this case</p>
<pre><code>class MyClass():
def __init__(self, a: int):
pass
def main():
channel = MyClass(0.)
if __name__ == "__main__":
main()
</code></pre>
<p>Why?</p>
<p>I am running python3.7.9 in Windows 10.</p>
| <python><mypy> | 2023-07-05 12:43:25 | 1 | 749 | DJames |
76,620,362 | 20,920,790 | How to check all pd.DataFrame for regular expression? | <p>I need check few dataframes.
If df do not contain regular expression, I need to clear it.
I don't know column there it should be.</p>
<p>How to check all DataFrame for containing regular expression?
Without loop to check column?</p>
<p>This is how I do it now:</p>
<pre><code>import pandas as pd
import numpy as np
import re
import codecs
# read file
folder = 'folder_path'
file = 'file_name.html'
html_df = pd.read_html(folder + '/' + file)
# check dataframes
html_match = re.compile(r'_TOM$|_TOD$')
# add DF number with html_match
df_check = []
for i, df in enumerate(html_df):
for col in df.columns:
try:
if len(df[df[col].str.contains(html_match) == True]) != 0:
df_check.append(i)
else:
continue
except AttributeError:
continue
</code></pre>
| <python><pandas><python-re> | 2023-07-05 12:32:11 | 2 | 402 | John Doe |
76,620,341 | 9,018,649 | How to mount a Azure Blob in databricks notebook based on IF-condition? | <p>Current working setup: I have one file in blob-storage, and in the current solution this file mounts in the notebook:</p>
<pre><code>fileIn = '/mnt/myfile'
</code></pre>
<p>This file needs to be split into two files, separated by year. Now I have two files:</p>
<pre><code>fileInA = '/mnt/myfile2015'
fileInB = '/mnt/myfile2022'
</code></pre>
<p>The current databricks Notebook take 'year' as inputparameter, eg:</p>
<pre><code># dbutils.widgets.text("year", "2019")
</code></pre>
<p>Based on input-year I need to spesify what file to mount.
First I tried by SQL:</p>
<pre><code>> fileIn = SELECT if(year < 2022, 'fileInA', 'fileInB ');
</code></pre>
<p>but that returns the actual SQL statement as fileIn, and does not mount the file.</p>
<p>I alos tried with python:</p>
<pre><code>def mountbyyear(year):
# if(int(year)<2022):
# fileIn = '/mnt/myfile2015'
# else:
# fileIn = '/mnt/myfile2022'
mountbyyear(year)
</code></pre>
<p>How can i mount a blob-file based on a IF-statement in Databricks Notebook?</p>
| <python><sql><azure><databricks> | 2023-07-05 12:29:30 | 1 | 411 | otk |
76,620,067 | 2,930,793 | CDK + copy encrypted s3 artifacts between cross aws account | <p>I have a few ml models trained in dev environment s3. I want to copy that into stage and prod account s3 using cdk.
Previously, I was doing it in cdk synth time using this code[ <em><strong>s3 artifacts was not encrypted then</strong></em>]</p>
<pre><code>boto3.resource("s3").meta.client.copy(
{"Bucket": source_bucket_name, "Key": source_file},
destination_bucket_name,
source_file,
)
</code></pre>
<p>It worked completely fine. But now AWS s3 by default encrypts every object with the type
<code>Server-side encryption with AWS Key Management Service keys (SSE-KMS)</code></p>
<p>Now my code does not work for encrypted files. It throws an error.
<code> botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the UploadPartCopy operation: Access Denied</code></p>
<p>Any suggestion?</p>
<p>Update 1: I added this permission to the cdk user/role which did not work.</p>
<pre><code> {
"Sid": "AllowKMSDecryptFromSourceBucket",
"Effect": "Allow",
"Action": [
"kms:*"
],
"Resource": [
"arn:aws:kms:eu-west-1:source-account-key-arn
]
},
{
"Sid": "AllowKMSEncryptToDestinationBucket",
"Effect": "Allow",
"Action": [
"kms:*"
],
"Resource": [
"arn:aws:kms:us-east-2:destination-account-key-arn"
]
}
</code></pre>
| <python><amazon-web-services><amazon-s3><encryption><aws-cdk> | 2023-07-05 11:55:30 | 0 | 903 | Sazzad |
76,620,012 | 2,163,392 | Loading model with a custom layer error Tensorflow 2.6.2 | <p>I have the following custom layer in my Vision Transformer</p>
<pre><code>class DataAugmentation(Layer):
def __init__(self, norm, SIZE):
super(DataAugmentation, self).__init__()
self.norm = norm
self.SIZE = SIZE
self.resize = Resizing(SIZE, SIZE)
self.flip = RandomFlip('horizontal')
self.rotation = RandomRotation(factor=0.02)
self.zoom = RandomZoom(height_factor=0.2, width_factor=0.2)
def call(self, X):
x = self.norm(X)
x = self.resize(x)
x = self.flip(x)
x = self.rotation(x)
x = self.zoom(x)
return x
def get_config(self):
config = super().get_config()
config.update({
"norm": self.norm,
"SIZE": self.SIZE,
})
return config
</code></pre>
<p>I have saved the weights after training but whenever I load the weights I have the following error:</p>
<pre><code> File "test_vit.py", line 313, in <module>
best_model = keras.models.load_model("ViT-Model-new.h5")
File "/usr/local/lib/python3.6/dist-packages/keras/saving/save.py", line 201, in load_model
compile)
File "/usr/local/lib/python3.6/dist-packages/keras/saving/hdf5_format.py", line 181, in load_model_from_hdf5
custom_objects=custom_objects)
File "/usr/local/lib/python3.6/dist-packages/keras/saving/model_config.py", line 52, in model_from_config
return deserialize(config, custom_objects=custom_objects)
File "/usr/local/lib/python3.6/dist-packages/keras/layers/serialization.py", line 212, in deserialize
printable_module_name='layer')
File "/usr/local/lib/python3.6/dist-packages/keras/utils/generic_utils.py", line 678, in deserialize_keras_object
list(custom_objects.items())))
File "/usr/local/lib/python3.6/dist-packages/keras/engine/functional.py", line 663, in from_config
config, custom_objects)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/functional.py", line 1273, in reconstruct_from_config
process_layer(layer_data)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/functional.py", line 1255, in process_layer
layer = deserialize_layer(layer_data, custom_objects=custom_objects)
File "/usr/local/lib/python3.6/dist-packages/keras/layers/serialization.py", line 212, in deserialize
printable_module_name='layer')
File "/usr/local/lib/python3.6/dist-packages/keras/utils/generic_utils.py", line 681, in deserialize_keras_object
deserialized_obj = cls.from_config(cls_config)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py", line 748, in from_config
return cls(**config)
TypeError: __init__() got an unexpected keyword argument 'name'
</code></pre>
<p>What I tried:</p>
<p>1- I put @tf.keras.utils.register_keras_serializable() before the class definition</p>
<p>2- I loaded the model with the custom object scope</p>
<pre><code>with tf.keras.utils.custom_object_scope({"DataAugmentation": DataAugmentation}):
model = load_model("ViT-Model-new.h5")
</code></pre>
<p>For both solutions I have the same error.</p>
<p>My tensorflow version is 2.6.2</p>
| <python><tensorflow><keras><vision-transformer> | 2023-07-05 11:49:19 | 1 | 2,799 | mad |
76,619,556 | 1,493,192 | convert millisecond to datetime in Python | <p>I have a set of data whose time is esper in milliseconds (time.stamp), where each value represent a misure (10 Hz it's the working time of the instrument):</p>
<p><a href="https://i.sstatic.net/LMceb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LMceb.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/lb2ik.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lb2ik.png" alt="enter image description here" /></a></p>
<p>What I want to do knowing the year, month, day, hour, minutes and seconds of the start of the measurement is to transform into a datetime of the type</p>
<pre><code>yyyy-mm-dd hh:min:sec.milliseconds
</code></pre>
<p>I perform this operation with a few lines of code in python by creating the datetime column:</p>
<pre><code>flist = os.listdir(data_files)
for f in flist:
df = pd.read_csv(data_files + "/" + f)
yyyymmdd, hhmm, _ = f.split(".")
yyyy = yyyymmdd[0:4]
mm = yyyymmdd[4:6]
dd = yyyymmdd[6:8]
hh = hhmm[0:2]
minute = hhmm[2:4]
lst = []
for ind in df.index:
ts: float = df['time.stamp'][ind]
d = f'{yyyy}-{mm}-{dd} {hh}:{minute}:{0}.{0}'
dt = datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f')
result = dt + timedelta(milliseconds=ts)
lst.append(str(result))
df['datetime'] = lst
df.to_csv(os.path.normpath(data_dummy_files + "/" + f), index=False)
</code></pre>
<p><a href="https://i.sstatic.net/V5Wg0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/V5Wg0.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/HdOE9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HdOE9.png" alt="enter image description here" /></a></p>
<p>the problem is the final data is <code>2021-05-01 00:00:03.599900</code> This means that about 4 minutes passed between the start and end of the measurements, in reality the instrument was running for about 60 minutes (1 hour).</p>
| <python><datetime><timedelta><date-conversion><milliseconds> | 2023-07-05 10:44:27 | 0 | 8,048 | Gianni Spear |
76,619,522 | 14,282,714 | Jupyter Notebook Slides in VScode | <p>In <code>Jupyter Notebook</code> we could create slides, like explained <a href="https://medium.com/@mjspeck/presenting-code-using-jupyter-notebook-slides-a8a3c3b59d67" rel="nofollow noreferrer">here</a>. Here you can see a reproducible example to create Jupyter notebook slides via Anaconda-navigator:</p>
<p><a href="https://i.sstatic.net/gcerb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gcerb.png" alt="enter image description here" /></a></p>
<p>When running this command in the terminal:</p>
<pre><code>jupyter nbconvert slides_test.ipynb --to slides --post serve
</code></pre>
<p>It will outputs this in your browser:</p>
<p><a href="https://i.sstatic.net/vqLcim.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vqLcim.png" alt="enter image description here" /></a></p>
<p>And for the code cell output:</p>
<p><a href="https://i.sstatic.net/0T7Urm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0T7Urm.png" alt="enter image description here" /></a></p>
<p>This is very nice and I would like to use this but in <code>VScode</code>.</p>
<p>In the Jupyter notebook of Anaconda navigator we can create slides when clicking on <code>View</code> -> <code>Cell Toolbar</code> -> <code>Slideshow</code> in the header bar. Unfortunately, this is not possible in VScode. So I was wondering if anyone knows how to create Jupyter Notebook slides in VScode?</p>
| <python><visual-studio-code><jupyter-notebook><slideshow> | 2023-07-05 10:39:09 | 1 | 42,724 | Quinten |
76,619,274 | 4,576,519 | Ensuring constant figure size when using matplotlib colorbar | <p>I'm creating multiple plots with a colorbar in <code>matplotlib</code>, saving them in tight layout. I noticed that the size of the figures and the size of the axes differ for each image because the colorbar takes more/less space depending on the number of decimals of the data. For example, consider this script:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
order = 0
x = np.tile(np.arange(10), 10).reshape((10,10))
y = np.repeat(np.arange(10),10).reshape((10,10))
z = np.sort(np.random.rand(100)*10**order).reshape((10,10))
fig, ax = plt.subplots(figsize=(8,6))
cs = ax.pcolor(x,y,z)
cbar = plt.colorbar(cs)
plt.tight_layout()
fig.savefig(f'order_{order}.jpg', bbox_inches='tight')
plt.show()
</code></pre>
<p>Running this with <code>order=-3</code> and <code>order=0</code> gives the below figures, which evidently have (a) different sizes and (b) differently sized axis for the main plot.</p>
<img src="https://i.sstatic.net/lfvRx.jpg" width="300">
<img src="https://i.sstatic.net/gcZH6.jpg" width="300">
<p><strong>How can I ensure that the images and the axes are the same size regardless of the number of decimals of the data?</strong> I know that my data has at most 3 decimals. I tried using the <code>fraction</code> argument on the colorbar to "reserve" space, but the value has no effect when doing <code>bbox_inches='tight</code>. I essentially need to maintain some padding on the right side of the figure.</p>
| <python><matplotlib><axis><image-resizing><colorbar> | 2023-07-05 10:07:18 | 1 | 6,829 | Thomas Wagenaar |
76,619,095 | 1,396,516 | How to to convert raw contents of a large file stored on github to correct bytes array? | <p>I believe the recommended method to get the contents of a large file stored on GitHub is to use <a href="https://docs.github.com/en/rest/repos/contents?apiVersion=2022-11-28" rel="nofollow noreferrer"><code>REST API</code></a>. For the files which size is 1MB-100MB, it's only possible to <a href="https://docs.github.com/en/rest/repos/contents?apiVersion=2022-11-28" rel="nofollow noreferrer">get raw contents</a> (in <code>string</code> format).</p>
<p>I need to use this content to write into a file. If I use <code>pygithub</code> package, I get exactly what I need (in <code>bytes</code> format, and the response object contains <code>encoding</code> field which value is <code>base64</code>). Unfortunately, this package does not work for files which size is greater than 1MB.</p>
<p>So it seems that I only need to find the correct way to convert <code>string</code> to <code>bytes</code>. There are many ways to do it, I have tried 4 so far, and neither matches the output of <code>pygithub</code> package. See the output of several <code>guinea pig</code> files below. How to do the conversion correctly?</p>
<pre><code>from github import Github, ContentFile
import requests
from requests.structures import CaseInsensitiveDict
import base64
token = ...
repo_name = ...
owner = ...
filename = ...
# pygithub method
github_object = Github(token)
github_user = github_object.get_user()
repo = github_user.get_repo(repo_name)
cont_obj = repo.get_contents(filename)
print('encoding', cont_obj.encoding) # prints base64
content_ref = cont_obj.decoded_content # this works correctly for <1MB files
#REST API method
url = f"https://api.github.com/repos/{owner}/{repo_name}/contents/{filename}"
headers = CaseInsensitiveDict()
headers["Accept"] = "application/vnd.github.v3.raw"
headers["Authorization"] = f"Bearer {token}"
headers["X-GitHub-Api-Version"] = "2022-11-28"
contents_str = requests.get(url, headers=headers).text
contents = []
# https://stackoverflow.com/questions/72037211/how-to-convert-a-base64-file-to-bytes
contents.append(base64.b64decode(contents_str.encode() + b'=='))
# https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
contents.append(bytes(contents_str, encoding="raw_unicode_escape"))
# https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
message_bytes = contents_str.encode('utf-8')
contents.append(base64.b64encode(message_bytes))
#contents.append(base64.decodebytes(message_bytes + b'==')) same as method 0
print(type(content_ref), len(content_ref), content_ref[:50])
for i, c in enumerate(contents):
print(i, type(c), len(c), c[:50])
</code></pre>
<p>The output of the <code>guinea pig</code> files:</p>
<ul>
<li><p>The text file that contains <code>tiny text</code> allows telling that all but method 1 are incorrect</p>
<p><class 'bytes'> 10 b'tiny text\n'</p>
<p>0 <class 'bytes'> 6 b'\xb6)\xf2\xb5\xecm'</p>
<p>1 <class 'bytes'> 10 b'tiny text\n'</p>
<p>2 <class 'bytes'> 16 b'dGlueSB0ZXh0Cg=='</p>
</li>
<li><p>for <a href="https://www.africau.edu/images/default/sample.pdf" rel="nofollow noreferrer">this pdf file</a>, the length of the output of method 1 is slightly bigger, and the contents is slightly</p>
<p><class 'bytes'> 3028 b'%PDF-1.3\r\n%\xe2\xe3\xcf\xd3\r\n\r\n1 0 obj\r\n<<\r\n/Type /Catalog\r\n/O'</p>
<p>0 <class 'bytes'> 1504 b'<1u\xdf](n?\xd3\xca\x97\xbf\t\xabZ\x96\x88?:\xebe\x8aw\xac\xdbD\x7f=\xa8\x1e\xb3}\x11zwhn=\xb4\xa1\xb8\xffO*^\xfc\xeb\xad\x96)'</p>
<p>1 <class 'bytes'> 3048 b'%PDF-1.3\r\n%\ufffd\ufffd\ufffd\ufffd\r\n\r\n1 0 obj\r\n<<'</p>
<p>2 <class 'bytes'> 4048 b'JVBERi0xLjMNCiXvv73vv73vv73vv70NCg0KMSAwIG9iag0KPD'</p>
</li>
<li><p>For <a href="https://commons.wikimedia.org/wiki/File:Sunflower_as_gif_small.gif" rel="nofollow noreferrer">this image</a>, the size and the contents of output 1 are very different</p>
<p><class 'bytes'> 57270 b'GIF89a\xfa\x00)\x01\xe7\xff\x00\x06\t\r\x0f\n\x08\x19\r\x0c \x0e\n,\x12\x0b"\x18\x17\x1f\x1a\x16"\x1b\x12&\x18\x18&!\x17%!\x1b* \x1d,'</p>
<p>0 <class 'bytes'> 329 b'\x18\x81|\xf5\xa17\xebo\xb6\xf3^\x1b\x03]\x02\xdb\xcd\x04\xfc\x8e\xc7\xd8\xb1D\x0c\xa36\xe8\xd3\x00\xbf\x9e\x94\xf5$\xbcT\x04D\xf9\x11\xfa\_U\x14\x05\xd5\xfce'</p>
<p>1 <class 'bytes'> 169079 b'GIF89a\ufffd\x00)\x01\ufffd\ufffd\x00\x06\t\r\x0f\n\x08\x19\r\x0c \x0e\n,\x12\x0b"\x18\x17\x1f\x1a\x16"'</p>
<p>2 <class 'bytes'> 132656 b'R0lGODlh77+9ACkB77+977+9AAYJDQ8KCBkNDCAOCiwSCyIYFx'</p>
</li>
</ul>
| <python><github><encoding><character-encoding><pygithub> | 2023-07-05 09:44:04 | 3 | 3,567 | Yulia V |
76,618,935 | 15,915,737 | Download post from chatter in salesforce with Python | <p>I'm currently using simple-salesforce to retrieve data from various the object in salesforce, but I would also need to download the post in chatter of the associated object.</p>
<p>For instance, with an object <code>project_table__c</code> I need to get the associated post of each project.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Project_id</th>
<th>Chatter post</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>test</td>
</tr>
<tr>
<td>2</td>
<td>hello</td>
</tr>
<tr>
<td>2</td>
<td>word</td>
</tr>
<tr>
<td>2</td>
<td>bird</td>
</tr>
</tbody>
</table>
</div>
<p>I might also be possible to get it with the rest API but I don't where I should go from here:</p>
<pre class="lang-py prettyprint-override"><code>from simple_salesforce import Salesforce
import os
username="username"
password=os.environ['SALESFORCE_PASSWORD']
security_token=os.environ['SALESFORCE_SECURITY_TOKEN']
domain="test"
sf = Salesforce(username=username,password=password, security_token=security_token,domain=domain)
report_results = sf.restful('chatter', method='GET')
print(report_results)
</code></pre>
<p>How could I achieve it?</p>
| <python><salesforce><simple-salesforce> | 2023-07-05 09:25:39 | 1 | 418 | user15915737 |
76,618,492 | 10,353,865 | View vs. copy - how to decide based on attributes? | <p>In pandas it is always important to know if something is a view on a DataFrame.
I just wanted to know if there is some special attribute or way to distinguish a view from a genuine DataFrame. I tried the following without success (see below)</p>
<pre><code>#Create toy data and a view
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
view = df[:]
#Check if there are any attributes unique to proper dfs vs views and vice versa
view_vars = set((x for x in dir(view) if not x.startswith("_")))
df_vars = set((x for x in dir(df) if not x.startswith("_")))
view_vars ^ df_vars # no differences
#Repeat check for all attributes (i.e. including attributes with underscore in front)
view_vars = set((x for x in dir(view) ))
df_vars = set((x for x in dir(df) ))
view_vars ^ df_vars # still no differences
#Check numpy base values -> same
df.values.base
view.values.base
</code></pre>
<p>Can anyone provide me with some advice on how to programmatically disentangle a view from a genuine (copy of a) DataFrame?</p>
| <python><pandas> | 2023-07-05 08:33:41 | 1 | 702 | P.Jo |
76,618,213 | 9,476,917 | Python CX_Oracle - Multiple Connections to different databases possible? | <p>I am trying to connect to two databases (two different hosts) using cx_Oracle in python. It appears that the client is still set to the first connection <code>db1</code> when I create instance of <code>db2</code>. Trying to close the connection and delete the variable in the process didn't help.</p>
<pre><code>#Retrieve Data from Databases
db1 = OracleDatabaseConnector(".env_db1")
df_db1 = db1.execute_query(qry)
db1.con.close()
del db1
db2 = OracleDatabaseConnector(".env_db2") #db2 is not correctly initialized - instance has still information of db1
df_db2 = db2.execute_query(qry2) #Error is: Ora-00942 Table or View does not exist - as still connected to db1
db2.con.close()
del db2
</code></pre>
<p>OracleDatabaseConnector's <code>db.con</code> is based on <code>cx_Oracle.connect()</code></p>
<p>I found this <a href="https://github.com/oracle/python-cx_Oracle/issues/389#issuecomment-631769320" rel="nofollow noreferrer">Github Comment</a>, but the provided code does not work on my setup <code>Oracle 19c on-prem</code>.</p>
<p>Any help much appreciated!</p>
<p><strong>Edit</strong> Additional Info for <code>OracleDatabaseConnector</code></p>
<pre><code>class OracleDatabaseConnector:
def __init__(self, env_file_path: str):
self.env = env_file_path
load_dotenv(self.env)
self.con = self.__get_connection()
def __get_connection(self):
dsn = oracledb.ConnectParams(host=os.environ.get("HOSTNAME")
, port=os.environ.get("PORT")
, service_name=os.environ.get("SERVICE_NAME")
).get_connect_string()
return oracledb.connect(user=os.environ.get("USER")
, password=os.environ.get("PASS")
, dsn=dsn)
def execute_query(self, sql_qry: str):
try:
return pd.read_sql_query(sql_qry, self.con)
except:
print("Error executing SQL Query!")
raise Exception
</code></pre>
<p><strong>EDIT 2</strong> Added DSN Info of both connections (after upgrade to python-oracledb library).</p>
<pre><code>db1.con.dsn
Out[5]: '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname_db1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=db1_SERVICE_NAME_APP)))'
db2.con.dsn
Out[6]: '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname_db1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=db1_SERVICE_NAME_APP)))'
</code></pre>
<p>DSN String for both connections the same. I checked the two <code>.env</code> files. They include the corresponding correct credentials and client information.</p>
| <python><oracle-database><cx-oracle> | 2023-07-05 07:57:45 | 1 | 755 | Maeaex1 |
76,618,209 | 847,338 | What is the best design pattern when creating an interface for functions that can return a variety of responses? | <p>I am writing parsers for GNU/Linux commands. For example:</p>
<pre><code>from pydantic import BaseModel
from mmiac.core.system import run_cmd
from mmiac.core.parsing import create_key
class HostnamectlResponse(BaseModel):
static_hostname: str
transient_hostname: str | None
pretty_hostname: str | None
icon_name: str | None
chassis: str | None
deployment: str | None
location: str | None
virtualization: str | None
cpe_os_name: str | None
operating_system: str | None
os_support_end: str | None
os_support_expired: str | None
os_support_remaining: str | None
kernel: str | None
machine_id: str | None
boot_id: str | None
kernel: str | None
hardware_vendor: str | None
hardware_model: str | None
firmware_version: str | None
firmware_date: str | None
def parse() -> dict:
"""Parses output from hostnamectl command.
The only required field is static hostname. Output fields from hostnamectl can be found below:
https://github.com/systemd/systemd/blob/main/src/hostname/hostnamectl.c
"""
content = run_cmd("hostnamectl").split("\n")
data = {}
for line in content:
try:
k, v = line.strip().split(":", 1)
except ValueError:
continue
k = create_key(k)
data[k] = v.strip()
return HostnamectlResponse(**data)
</code></pre>
<p>I was thinking about making each command parser a class, but at the moment I feel like a function suffices. I imagine I'll create some sort of dispatch table that dynamically loads modules in that have a <code>parse()</code> method defined then call the functions using that.</p>
<p>But anyway, my question is related to the response. I'd love to make it such that the response is generic, but unfortunately, <code>ps</code> output is much different than <code>lspci</code> (and so on). I'm curious if there is a design pattern that I can reference, or anything really, when the functions you create have a common interface (parse()) but lack a common response.</p>
<p>Beyond the question itself, I appreciate any input here with regards to the design of this. My goal here is to make using the library as intuitive as possible without having to constantly reference docs.</p>
| <python><oop><design-patterns> | 2023-07-05 07:56:35 | 1 | 874 | Franz Kafka |
76,618,112 | 3,121,975 | Calling class method on generic type for class in Python | <p>Suppose I have an abstract base class, <code>Base</code> that is inherited by another class, <code>Derived</code>:</p>
<pre><code>T = TypeVar('T', bound = Foo)
class Base(Generic[T]):
def do_thing(self):
# This won't work
result = T.class_method(...)
class Derived(Base[Bar]):
def do_other_thing(self):
result = self.do_thing()
</code></pre>
<p>The goal here is that when <code>do_other_thing</code> is called, <code>Bar.class_method</code> is called, returning result. According to <a href="https://stackoverflow.com/questions/48572831/how-to-access-the-type-arguments-of-typing-generic">this question</a>, I could accomplish this using <code>get_args( Derived.__orig_bases__[0] )[0].class_method()</code> but I don't see how I can do this without hardcoding the class type. How can I get this code to work?</p>
| <python><generics> | 2023-07-05 07:42:18 | 2 | 8,192 | Woody1193 |
76,618,105 | 3,908,025 | PyQt pyqtgraph window resize causes colormap to reset to grayscale | <p>I'm facing an issue where the colormap of a pyqtgraph <code>ImageItem</code> seems to be reset to grayscale when the widget is being resized. Consider the following code</p>
<pre><code># PyQt6==6.4.2
# pyqtgraph==0.13.3
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui
# Interpret image data as row-major instead of col-major
pg.setConfigOptions(imageAxisOrder='row-major')
pg.mkQApp()
win = pg.GraphicsLayoutWidget()
# A plot area (ViewBox + axes) for displaying the image
p1 = win.addPlot(title="")
# Item for displaying image data
img = pg.ImageItem()
p1.addItem(img)
# Contrast/color control
hist = pg.HistogramLUTItem()
hist.setImageItem(img) # removing this line prevents the colorMap from changing when resizing the window
win.addItem(hist)
# Generate image data
data = np.random.normal(size=(200, 100))
img.setImage(data)
img.setColorMap(pg.colormap.get('CET-R4'))
hist.setLevels(data.min(), data.max())
win.show()
if __name__ == '__main__':
pg.exec()
</code></pre>
<p>When running this, the window appears as expected with the 'CET-R4' colormap:
<a href="https://i.sstatic.net/DXq97.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DXq97.png" alt="enter image description here" /></a></p>
<p>However, as soon as I resize the window, the image turns into grayscale:</p>
<p><a href="https://i.sstatic.net/glotC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/glotC.png" alt="enter image description here" /></a></p>
<p>I think it has to do with the <code>HistogramLUTItem</code>, since the same behaviour appears when sliding the gradient editor in the <code>HistogramLUTItem</code>.
If the <code>hist.setImageItem(img)</code> line is removed when running the code and the <code>HistogramLUTItem</code> was never linked to the <code>ImageItem()</code>, the colormap remains unchanged.</p>
<p>Am I doing something wrong or is it a bug?
Any ideas on how to fix or work around it?</p>
| <python><pyqt><pyqtgraph><colormap><pyqt6> | 2023-07-05 07:41:53 | 1 | 589 | Teun |
76,618,083 | 19,598,212 | Defining callback functions for C++in Python | <p>I am trying to write a binding to a C++ function that uses callback function. The callback function looks like.</p>
<pre class="lang-cpp prettyprint-override"><code>typedef enum
{
CB_Event_TermRegister = 101,
...
}enSdkCbType;
typedef enum
{
TSDK_DEV_TYPE_UNDEF = 0,
...
}enSdkDevType;
typedef struct
{
enSdkDevType eTermType;
...
}TSdkEventTermRegister;
typedef int (CALLBACK* ON_CTS_SDK_CALL_BACK)(enSdkCbType eCbType, LPVOID pParam, DWORD dwSize, int usr_data);
</code></pre>
<p>Wherein, <code>enSdkCbType</code> is a customized <code>enum</code> types. <code>pParam</code> points to different <code>struct</code> based on <code>eCbType</code>.<br />
I define this callback in python like this:</p>
<pre class="lang-py prettyprint-override"><code>from ctypes import *
class enSdkCbType(c_int):
CB_Event_TermRegister = 101
...
class enSdkDevType(c_int):
TSDK_DEV_TYPE_UNDEF = 0
...
class TSdkEventTermRegister(Structure):
_fields_ = [
("eTermType", enSdkDevType),
...
]
def callback(eCbType, pParam, dwParamLen, usr_data):
if eCbType == enSdkCbType.CB_Asw_OpenTermAudVid:
assert dwParamLen == sizeof(TSdkEventTermRegister)
p = POINTER(TSdkEventTermRegister).from_address(pParam)
print(p.contents.eTermType)
return 0
dll = CDLL('my_dll')
CallbackType = CFUNCTYPE(c_int, enSdkCbType, c_void_p, c_ulong)
dll.func(CallbackType(callback))
</code></pre>
<p>But the <code>if eCbType == enSdkCbType.CB_Asw_OpenTermAudVid</code> doesn't work cause the parameters send in this callback is like this:<code><enSdkCbType object at 0x01F10F80>, 101, 159492072, 72</code> and their types are <code><class '__main__.enSdkCbType'> <class 'int'> <class 'int'> <class 'int'> </code><br />
Obviously, the format of the parameters is not the same as when I defined them. Besides, it seems that one more parameter(<code><enSdkCbType object at 0x01F10F80></code>) was send to the callback because by definition, the parameter should be like this <code>101(eCbType), 159492072(pParam), 72(dwSize), usr_data</code>.<br />
I don't know where my Python code went wrong, but I can provide a well running C++ version of the callback function.</p>
<pre class="lang-cpp prettyprint-override"><code>int CALLBACK CSdkMp3Dlg::OnTzlSdkCallback(enSdkCbType eCbType, LPVOID pParam, DWORD dwSize, int usr_data)
{
switch(eCbType)
{
case CB_Event_TermRegister:
{
ASSERT(dwSize == sizeof(TSdkEventTermRegister));
TSdkEventTermRegister * pEventTermRegister = (TSdkEventTermRegister*)pParam;
...
}
...
}
return 0;
}
</code></pre>
| <python><c++><callback><ctypes> | 2023-07-05 07:38:39 | 1 | 331 | 肉蛋充肌 |
76,617,969 | 3,868,743 | Sphinx Autodoc: display the choices of a param from a variable | <p>I have some parameters that accept only a set of values and these authorized values are stored into a list. Is it possible to use the content of this list in the docstring?</p>
<p>For example:</p>
<pre><code>authorized_values = [1, 2, 3]
def foo(a: int):
"""Print an integer between 1 and 3.
Args:
a: The integer to print. The authorized values are: <authorized_values>.
"""
if a not in authorized_value:
raise ValueError(f"The authorized values are: {authorized_values}.")
print(a)
</code></pre>
<p>This would ensure the docs is synchronized with the code. Because if I want to add a new authorized value, I have to update the code and the docstrings to ensure they are in sync, which I would like to avoid.</p>
| <python><python-sphinx><docstring><autodoc> | 2023-07-05 07:24:32 | 2 | 492 | StormRider |
76,617,876 | 14,912,118 | How to check programmatically job cluster is unity catalog enabled or not in databricks | <p>Is there any way to check job cluster is unity catalog enabled or not in databricks using python.</p>
<p>I tried with jobs api <code>https://{host_name}/api/2.0/jobs/get?job_id={job_id}</code>, but I didn't that cluster is unity catalog enabled or not.</p>
<p>Could anyone suggest how to get that programmatically, it would be great help.</p>
| <python><databricks><databricks-workflows> | 2023-07-05 07:12:08 | 1 | 427 | Sharma |
76,617,834 | 6,021,482 | selenium web driver something went wrong | <p>I am using selenium python to scrape a website and below is my close</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.businesstimes.com.sg")
</code></pre>
<p>whenever I run this code I see the below error
<a href="https://i.sstatic.net/slRo2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/slRo2.png" alt="enter image description here" /></a></p>
<p>It works fine for "https://www.reutersagency.com" but not working for the above. How can I access that and solve this error?</p>
<p>Thanks.</p>
| <python><selenium-webdriver><web-scraping><selenium-chromedriver> | 2023-07-05 07:07:07 | 1 | 377 | Azeem112 |
76,617,723 | 3,909,896 | Clearing messages from the client cache in a ServiceBusQueue with prefetch_count > 0 and mode = receiveanddelete | <p>I want to improve the performance of my Python ingestion from a ServiceBusQueue. At first I tried to increase the <code>max_wait_time</code> and the <code>max_message_count</code>, but I usually only get between 20-40% of the <code>max_message_count</code> per call of <code>receive_messages(max_message_count)</code>. The call returns in ~1.2 seconds even though the <code>max_wait_time</code> is 30 seconds (I suppose the function prefers returning early over filling the <code>max_message_count</code> completely).</p>
<p>So I wanted to decrease the time it takes to receive messages by configuring the <code>prefetch_count = 10000</code> so the client caches messages and whenever I call <code>receive_messages(max_message_count=3000)</code> next, it can pull messages from the cache instead of making a separate call to the Queue each time.</p>
<p>At the same time my ingestion mode is <code>receive and delete</code>, meaning any message retrieved from the queue is instantly deleted.</p>
<p>My Problem: I believe if my client application terminates before processing all the prefetched messages, <strong>the remaining messages in the prefetch buffer will be lost</strong> (since they are already removed from the Queue) - which is undesirable.</p>
<ul>
<li>How can I "clear out" (and process) all prefetched messages without retrieving a new batch from the Queue once I decide to stop my ingestion application?</li>
<li>Or should I just never set the <code>prefetch_count</code> > 0 with <code>receiveanddelete</code> mode?</li>
</ul>
<p>My configuration of the ServiceBusReceiver:</p>
<pre><code>prefetch_count = 10000 # on get_queue_receiver()
max_wait_time = 30 # on get_queue_receiver()
receive_mode = receiveanddelete # on get_queue_receiver()
max_messages_count = 3000 # on receive_messages()
</code></pre>
<p>Pseudo example:</p>
<pre><code>service_bus_client = ServiceBusClient.from_connection_string(current_connection_string)
queue_receiver = service_bus_client.get_queue_receiver(
current_queue_name,
max_wait_time=30,
receive_mode='receiveanddelete',
prefetch_count=10000,
)
# Get messages (including prefetch for the next call of 'receive_messages')
# and immediately remove all of it from the queue.
msgs_1 = queue_receiver.receive_messages(max_message_count=3000)
# This call might not even need to contact the Queue, but can
# just get pre-fetched messages from the cache:
msgs_2 = queue_receiver.receive_messages(max_message_count=3000)
# If I stop now - how do I make sure that my client-side cache
# (due to prefetch_count > 0 ) is actually empty?
</code></pre>
<p>In theory, in my example I prefetched 10.000 messages during my first call of <code>receive_messages()</code>, but only called <code>receive_messages()</code> once again afterwards: 10.000 - 3.000 = 7.000</p>
<p>How do I make sure that I do not loose ~7.000 prefetched messages which reside in my client cache? Maybe even more as I do not always get 3000 messages back on each call of 'receive_messages'.</p>
| <python><azure><azure-servicebus-queues> | 2023-07-05 06:49:32 | 1 | 3,013 | Cribber |
76,617,707 | 710,955 | Pytorch DataLoader: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow | <p>When I create a PyTorch DataLoader and trying to train the model, I got this User Warning:</p>
<blockquote>
<p>/usr/local/lib/python3.10/dist-packages/sentence_transformers/SentenceTransformer.py:547:
UserWarning: Creating a tensor from a list of numpy.ndarrays is
extremely slow. Please consider converting the list to a single
numpy.ndarray with numpy.array() before converting to a tensor.
(Triggered internally at ../torch/csrc/utils/tensor_new.cpp:245.)<br />
labels = torch.tensor(labels)</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code> from torch.utils.data import DataLoader
from sentence_transformers import losses
from sentence_transformers import ParallelSentencesDataset
from sentence_transformers import models
from sentence_transformers import SentenceTransformer
xlmr = models.Transformer('xlm-roberta-base')
pooler = models.Pooling(
xlmr.get_word_embedding_dimension(),
pooling_mode_mean_tokens=True
)
student = SentenceTransformer(modules=[xlmr, pooler])
teacher = SentenceTransformer('paraphrase-distilroberta-base-v2')
data = ParallelSentencesDataset(
student_model=student,
teacher_model=teacher,
batch_size=32,
use_embedding_cache=True
)
data.load_data('/path/to/somefile', max_sentence_length=512)
loader = DataLoader(data, shuffle=True, batch_size=32)
loss = losses.MSELoss(model=student)
epochs=1
student.fit(
train_objectives=[(loader, loss)],
epochs=epochs,
warmup_steps=int(len(loader) * epochs * 0.1), # 10% of data
output_path='./xlmr-ted',
optimizer_params={'lr': 2e-5, 'eps': 1e-6},
save_best_model=True,
show_progress_bar=True
)
</code></pre>
<p>Can I covert from a <code>DataLoader()</code> dataset to a tensor, or is there a better way of approaching the issue?</p>
| <python><pytorch><multiprocessing><pytorch-dataloader><dataloader> | 2023-07-05 06:47:43 | 1 | 5,809 | LeMoussel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.