QuestionId int64 74.8M 79.8M | UserId int64 56 29.4M | QuestionTitle stringlengths 15 150 | QuestionBody stringlengths 40 40.3k | Tags stringlengths 8 101 | CreationDate stringdate 2022-12-10 09:42:47 2025-11-01 19:08:18 | AnswerCount int64 0 44 | UserExpertiseLevel int64 301 888k | UserDisplayName stringlengths 3 30 ⌀ |
|---|---|---|---|---|---|---|---|---|
77,511,043 | 15,414,616 | Python faster JWE decryption | <p>I have python code that decrypt JWE, but my issue is that I need to keep up with quite high load of data to decode per second and my code is too slow...</p>
<p>Does someone maybe has a suggestion on how to make this code work faster?</p>
<p>This is the decryption code which should return <code>{"test": "test"}</code></p>
<pre><code>from jwcrypto import jwe, jwk
DATA = "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoiZDgzNTIyNGItNmJlOS00MWQ0LTkyYWEtYzEyOGZkNWU5ZWNlIn0.Gadr3iydQTwKzDKp7wYeDX4gzu8_hD9t8iylgtklGdrKDOtK4pScUNuoBX92R9gnvWapNXpwcr2CEdQ45_POJ-HpFONOFCUDFuOxTfHn7ncytEDCv7a5TTbDAVBAmcH9mbkeo0DRok6vJxrprgl1USzK3UjhXzdUPTWhp8tMYtXXNzaPVbgthNqe4Hy4TX-K1Mcl_ZFcJn_JeLFE9kOWid1Dwaltzqh4pXQQoFMosumSNDGApY-DKpLpzcy_8UV890B1cnsceuggg88iPXM_GpJzKMuxkzt-451h7V500UOkdxz6M4PgAf8YLNmwziyJe3dOSEIlub0fqiZhhRNUvA.e3vioHj1RvZb58UL.-cBm-2fjYZB_EczWj78byA.3M3UqyaPUZIekudlT3aTjg"
DECRYPTION_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCs/yqrB8VjupUov9zApR6iEkEAPRzWrKvn+ZKlx6Rt/qTDNg0jjKahsHqTultndcB+58z+RQ/wAGGAoPm1f1JmY9P7pOGOOyGGEEsyonfa3PVwJ8Yryw3Cu0nwm2q0r9Pdv9d+BGdpPBubZ6Io5OIAtVrR7tjj8OZkGs3UXmMruXc8MTkXkO5Hccf7z+GNCu+ebNrM7sDVT+akjB2swRfHgsgwtLnnsCslyu55G6xiQIk2M7WURl7q37Y0pG4glYj4401n9lK0b8YbiuXhoeOY7799zd7gGSL1KdA14U0YSiHfbPLOV2e1Tjfv1adY97b2cSgt3ml6rbFj3siOyxyFAgMBAAECggEACu5Qlt/10/hdJmcBHtcQGXOH0ekKonHkptK5Nmpn9F9Lr94BdIaVnM/W3vC+h8oD8MDazhI1EJglkQga3yH9ZeTW5yai7ebEloD/D2L+qcCebYjF18yLwQsuf9qCIoqdm3xctGS42AhpQieJMoZL1XmgFHXAFJ8LH7Yl3U5de8ywqKdUq41YqdpklMGY3p1tS8R3R9l1x8repGyV6xQvUUsvJZ9Edkh9UBEmWG2AbEX8J5TN8h+P7Pg5dBj3sZYrcF4YvuYEIMPtfuVGqtX0SNiAWMngaYjFqG3fyfrFmxNUjF5A0GoALWF/Z4VaNtCudF4M+wptN0O77h/1gdC/PQKBgQDT1hL8LlVMRceTkZNyH8JvGN+G5m2YMsXV/GysGT3jVU2ErIvFydEhkh7fNk9jJ7vpSfIiQ2SKr+/+uh7iSa94h09AJVO5+WzcWCYa4Fen81/gaM5Hpf8bOWcQXBJRtvTN8IfjaznebYH2w2ckHLS8yZLXYSB2DGI8EaG4kgTeAwKBgQDREDAVidenvlaocYUZDNMMSVpyPCRzTIGhbEQk4JjBfdx2OKaxIXW4P4FgtH71GreJ4TFYh2BvXhpooxymM+K5bbZa+Cfhcf9fivcmXooGTsdf5hAFzIs2VXnpN82lxI9G+C4e/JDrTgADCuDGHXs3rxf5EgSYopknrtpbfAw41wKBgFdiuQQ0rNVA99plNDjg5xljXlpM1irxzvC+J6o642/TMZ4oe6RE47OAjqGvysHxky/iZDNEL8aSW2NuLe1VTkBfOQ8SFt7iCMlAx79QinhrCkMNmQKvdHQrktuJz7jLy2Lk9XmYMxARhopgAz0/ZkN2t8+Hbpej9iYnc9oqyj03AoGBAMEKM3wP1YNcK2RJvd5NiyqTKOLGSdn00NWexKVQhXxUnRbEZJa2EJ7adLo4r+nei47S0t+t0QvEVpo70p5c1oLlnTYOYbS3sFgmVuOk88mzQEF6i1zva7P15SXFkyv3fVzImL2f9KhxU217w+TrH/VgxcAENR5DNSwBNjq3JgntAoGBALYsMibwoh7PRkaqvIMpKW0bbkKIvk36MhVXcUx8Xi0UMvvd/6FBTBieWoKELAvQ4X1bL1FISHibok+/ofMAhxn9/Zt4StQYdTWtxyht6YhUFi1VKEWO1IqxLrXReIR9JAm5/gtwJBuKPh3DPw8HDlCtX8AQlh2EOInRp8hcUdPl"
KEY_ID = "d835224b-6be9-41d4-92aa-c128fd5e9ece"
def key_to_pem(key: str, is_public: bool = True) -> bytes:
pem = [f"-----BEGIN {'PUBLIC' if is_public else 'PRIVATE'} KEY-----"]
for group in grouper(key, 64):
pem.append(''.join(group))
pem.append(f"-----END {'PUBLIC' if is_public else 'PRIVATE'} KEY-----")
return str.encode('\n'.join(pem))
def decrypt_data(encrypted_data: str, pem_decryption_key: bytes, key_id: str) -> str:
private_key = jwk.JWK.from_pem(pem_decryption_key)
protected_header = {
"alg": "RSA-OAEP-256",
"enc": "A256GCM",
"kid": key_id,
}
jwetoken = jwe.JWE(protected=protected_header)
jwetoken.deserialize(encrypted_data, key=private_key)
payload = jwetoken.payload
return payload.decode("utf-8")
if __name__ == '__main__':
decrypt_key = key_to_pem(DECRYPTION_KEY, is_public=False)
print(decrypt_data(DATA, decrypt_key, KEY_ID))
</code></pre>
| <python><encryption><jwe> | 2023-11-19 14:02:53 | 0 | 437 | Ema Il |
77,511,011 | 8,030,746 | What's wrong with this search query (Python and SQLite3)? | <p>I'm trying to search my database and show the results, but my code is returning nothing, and I can't figure out where the mistake is.</p>
<p>This is how I'm scraping the data and inserting it into the database:</p>
<pre><code>def getJobsData(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0'}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
data = []
for e in soup.select('.card'):
data.append({
'title': e.h2.text,
'desc': e.ul.get_text('\n', strip=True)
})
try:
for item in data:
c.execute('''INSERT INTO job VALUES(?,?)''',
(item['title'], item['desc']))
return
except:
return
</code></pre>
<p>And this is the search code:</p>
<pre><code>@app.route("/search", methods=['GET', 'POST'])
def search():
error = ""
user_input = None
data = None
try:
if request.method == "POST":
conn = sqlite3.connect('jobs.db')
c = conn.cursor()
c.execute('''SELECT * FROM job WHERE title = (?,)''', (request.form["search"],))
data = c.fetchall()
user_input = (request.form["search"],)
return render_template("search.html", data=data, user_input=user_input)
except Exception as e:
error = (str(e))
return render_template("search.html", error=error, user_input=user_input)
</code></pre>
<p>HTML:</p>
<pre><code><form class="navbar-form navbar-left" action="{{ url_for('search') }}" method="POST" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="search" value="{{ request.form.search }}">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</code></pre>
<p>I'm using Python, Flask and SQLite3.
What did I do wrong and how do I fix this? Thank you!</p>
<p><strong>EDIT:</strong> I've realized that the code does return the data from the database, but the search query has to match exactly to the title. Trying to figure out how to solve this. Here's what I updated, print statements are there just for testing:</p>
<pre><code>if request.method == "POST":
conn = sqlite3.connect('jobs.db')
c = conn.cursor()
user_input = request.form["search"]
data = c.execute('''SELECT * FROM job WHERE title LIKE ?''', (user_input,)).fetchall()
print("USER INPUT:" + user_input)
print(data)
for d in data:
print(d)
return render_template("search.html", data=data, user_input=user_input)
</code></pre>
| <python><sqlite> | 2023-11-19 13:52:22 | 1 | 851 | hemoglobin |
77,510,981 | 4,878,911 | 'Go to Definition' from a Python file in a symlinked directory redirects me to the canonical path | <p>Example:</p>
<ul>
<li>I Have <code>/mnt/extra-drive/Git</code> that contains multiple projects</li>
<li>I symlinked this directory to <code>~/Git</code>
<ul>
<li><code>ln -s /mnt/extra-drive/Git ~/Git</code></li>
</ul>
</li>
<li>And I open the projects using vscode from this new directory <code>~/Git</code></li>
<li>When I open any file from the sidebar it opens from <code>~/Git/project</code> as normal</li>
<li>But if I tried to "Go to Defenition" from Python class (I'm using the <a href="https://marketplace.visualstudio.com/items?itemName=ms-python.python" rel="nofollow noreferrer"><code>ms-python.python</code></a> extension), it redirects me to the Python file from <code>/mnt/extra-drive/Git/project</code>, I want it to open from <code>~/Git/project</code> to reflect on the sidebar "Explorer View" correctly</li>
</ul>
<p>Any Solution to that?</p>
| <python><visual-studio-code><symlink><go-to-definition> | 2023-11-19 13:44:54 | 1 | 645 | Ahmed Kamal |
77,510,935 | 19,694,624 | Can't delete bot message discord.py / pycord) | <p>I am having trouble deleting discord bot's message. Here is the code to replicate the problem I am having:</p>
<pre><code>import discord
from tools.config import TOKEN
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.slash_command(name="chat", description="Тут можно добавить описание")
async def chat(ctx, msg):
bot_msg = await ctx.respond(f'some message with tagging {ctx.author.mention}')
await bot_msg.delete(delay=5)
bot.run(TOKEN)
</code></pre>
<p>And I get the error:</p>
<pre><code>await bot_msg.delete(delay=5)
AttributeError: 'Interaction' object has no attribute 'delete'
</code></pre>
<p>I am using <strong>py-cord==2.4.1</strong> but I believe it's the same thing as <strong>discord.py</strong></p>
| <python><python-3.x><discord><discord.py><pycord> | 2023-11-19 13:28:28 | 1 | 303 | syrok |
77,510,858 | 284,932 | CUDA 11.8 not recognized by Tensorflow but Pytorch does | <p>I am currently working on a machine learning project using Ubuntu 23 with an RTX 3060 Ti GPU. I have successfully installed CUDA 11.8, and <strong>PyTorch is functioning perfectly</strong>, recognizing and utilizing the GPU without any issues.</p>
<p>However, I am encountering difficulties with TensorFlow. Despite installing the <code>tensorflow[and-cuda]</code> package, TensorFlow does not seem to recognize the GPU. I have checked and confirmed that the CUDA toolkit and cuDNN are correctly installed:</p>
<pre><code>2023-11-19 10:04:21.667041: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-11-19 10:04:22.398453: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
2023-11-19 10:04:23.228798: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:995] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero. See more at https://github.com/torvalds/linux/blob/v6.0/Documentation/ABI/testing/sysfs-bus-pci#L344-L355
2023-11-19 10:04:23.257218: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1960] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
</code></pre>
<p>When I try:</p>
<pre><code>from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
</code></pre>
<p>returns only:</p>
<pre><code>[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 5180605997013099642
xla_global_id: -1
]
</code></pre>
<p>Here are the relevant details:</p>
<ul>
<li>Operating System: Ubuntu 23</li>
<li>GPU: RTX 3060 Ti</li>
<li>CUDA version: 11.8</li>
</ul>
<p>PyTorch is running smoothly with GPU support, but TensorFlow refuses to acknowledge the GPU presence.</p>
<p>I have followed the usual installation steps, including the installation of the CUDA toolkit, cuDNN, and the TensorFlow package with GPU support. However, when I run TensorFlow code, it defaults to CPU execution.</p>
<p>Any insights or guidance on resolving this issue would be greatly appreciated. If there are specific steps or configurations for TensorFlow on Ubuntu 23 with an RTX 3060 Ti that I might be missing, please let me know.</p>
| <python><tensorflow><ubuntu> | 2023-11-19 13:06:02 | 0 | 474 | celsowm |
77,510,855 | 13,014,274 | Android write problems PermissionError: [Errno 13] Permission denied | <p>I wrote a script that updates exif data of the WhatsApp images. I wanted to run it on my Android phone using Pydroid app, however I end up with the PermissionError: [Errno 13] Permission denied error.</p>
<pre><code>import os
import piexif
import datetime
dir_path = '/storage/emulated/0/Android/media/com.whatsapp/WhatsApp/Media/WhatsApp Images'
img_count = 1
for root, dirs, files in os.walk(dir_path):
for fname in files:
if fname.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
img_path = os.path.join(root, fname)
exif_dict = piexif.load(img_path)
if not exif_dict['Exif'].get(piexif.ExifIFD.DateTimeOriginal, ""):
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(img_path)).strftime("%Y:%m:%d %H:%M:%S")
exif_dict['Exif'][piexif.ExifIFD.DateTimeOriginal] = mtime
exif_bytes = piexif.dump(exif_dict)
piexif.insert(exif_bytes, img_path)
print(f"[{img_count}] DateTimeOriginal of {img_path} updated successfully to {mtime}")
img_count += 1
</code></pre>
<p>I found that some of the people recommend adding these lines to the code in order to request write permissions:</p>
<pre><code>from android.permissions import request_permissions, Permission
request_permissions([Permission.WRITE_EXTERNAL_STORAGE, ...])
</code></pre>
<p>However I am ending up with another issues:</p>
<pre><code>Error importing module "android": this module is a part of Kivy
You cannot use it from elsewhere and you barely need it at all
This is not a bug, please do not report it via email or Google Play reviews, thank you for your understanding
</code></pre>
<p>Is there any other option to grant WRITE permissions on Android? Or any other solution on performing a batch exif data update on Android files?
I am familiar with Java as well, so I could possibly try with that if I'm Python it's not possible.</p>
| <python><android><kivy><exif> | 2023-11-19 13:05:19 | 1 | 437 | Filip Szczybura |
77,510,803 | 22,221,987 | How to make a simple HTTPS server in Python 3x | <p>How can i create the simpliest python server, which will receive just one response and than die?</p>
<p>I've tried <a href="https://stackoverflow.com/a/19706670/22221987">this</a>, but modified it a bit, because of deprecation of some methods.</p>
<pre class="lang-py prettyprint-override"><code>import http.server
from ssl import SSLContext
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
print(post_data.decode('utf-8'))
server_address = ('127.0.0.1', 5000)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = SSLContext().wrap_socket(sock=httpd.socket,
server_side=True,
do_handshake_on_connect=False,
suppress_ragged_eofs=True)
httpd.serve_forever()
</code></pre>
<p>But it doesn't work.</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\mikha\Desktop\Mika\Projects\yummy_slack\test_1.py:14: DeprecationWarning: ssl.SSLContext() without protocol argument is deprecated.
httpd.socket = SSLContext().wrap_socket(sock=httpd.socket,
C:\Users\mikha\Desktop\Mika\Projects\yummy_slack\test_1.py:14: DeprecationWarning: ssl.PROTOCOL_TLS is deprecated
httpd.socket = SSLContext().wrap_socket(sock=httpd.socket,
----------------------------------------
Exception occurred during processing of request from ('127.0.0.1', 51828)
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\socketserver.py", line 316, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Program Files\Python310\lib\socketserver.py", line 347, in process_request
self.finish_request(request, client_address)
File "C:\Program Files\Python310\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Program Files\Python310\lib\http\server.py", line 668, in __init__
super().__init__(*args, **kwargs)
File "C:\Program Files\Python310\lib\socketserver.py", line 747, in __init__
self.handle()
File "C:\Program Files\Python310\lib\http\server.py", line 433, in handle
self.handle_one_request()
File "C:\Program Files\Python310\lib\http\server.py", line 401, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "C:\Program Files\Python310\lib\socket.py", line 705, in readinto
return self._sock.recv_into(b)
File "C:\Program Files\Python310\lib\ssl.py", line 1274, in recv_into
return self.read(nbytes, buffer)
File "C:\Program Files\Python310\lib\ssl.py", line 1130, in read
return self._sslobj.read(len, buffer)
ssl.SSLError: [SSL: NO_SHARED_CIPHER] no shared cipher (_ssl.c:2578)
----------------------------------------
</code></pre>
<p>And this error continues for a bunch of ports in a row.</p>
<p>I'm not a genius in networks, but really trying to understand what's going wrong here.</p>
<p>The main task is to receive the redirected response from Slack OAuth link.</p>
<p><strong>UPD</strong>:
I've tried to use certificate and key, when starting server. But script stucks on <code>load_cert_chain</code>. No crashes or something.</p>
<p>I've used this command to create a certificate and key <code>openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365</code>
Here the example:</p>
<pre><code>import http.server
import ssl
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
print(post_data.decode('utf-8'))
server_address = ('127.0.0.1', 5000)
httpd = http.server.HTTPServer(server_address, MyHandler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()
</code></pre>
| <python><ssl><https><request><slack> | 2023-11-19 12:45:06 | 1 | 309 | Mika |
77,510,638 | 3,943,162 | How to use a second retriever in LangChain to get extra info? | <p>In the following LangChain code, how can I add a second retriever to get extra info when the information is not found in the first documents?</p>
<pre class="lang-py prettyprint-override"><code># Build prompt
from langchain.prompts import PromptTemplate
template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. Use three sentences maximum. Keep the answer as concise as possible. Always say "thanks for asking!" at the end of the answer.
{context}
Question: {question}
Helpful Answer:"""
QA_CHAIN_PROMPT = PromptTemplate(input_variables=["context", "question"],template=template,)
# Run chain
from langchain.chains import RetrievalQA
question = "Is probability a class topic?"
qa_chain = RetrievalQA.from_chain_type(llm,
retriever=vectordb.as_retriever(),
return_source_documents=True,
chain_type_kwargs={"prompt": QA_CHAIN_PROMPT})
result = qa_chain({"query": question})
result["result"]
</code></pre>
<p>What I want is to change the prompt and use a second retriever (created with a different set of documents than the first one).</p>
<p>Something like:</p>
<pre class="lang-py prettyprint-override"><code>#...similar code...different prompt
template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, try to look at the extra text, and if still impossible to find a good answer, just say that you don't know, don't try to make up an answer. Use three sentences maximum. Keep the answer as concise as possible. Always say "thanks for asking!" at the end of the answer.
{context}
Extra: {extra_information}
Question: {question}
Helpful Answer:"""
QA_CHAIN_PROMPT = PromptTemplate(input_variables=["context", "extra", "question"],template=template,)
#...similar code...
qa_chain = RetrievalQA.from_chain_type(llm,
retriever=vectordb.as_retriever(),
extra_retriever=extradb.as_retriever(), #I know this parameter don't exist
return_source_documents=True,
chain_type_kwargs={"prompt": QA_CHAIN_PROMPT})
</code></pre>
<p>What is the correct way to use a second set of documents in LangChain?</p>
| <python><langchain><large-language-model> | 2023-11-19 11:48:01 | 0 | 1,789 | James |
77,510,636 | 519,779 | Where is /tmp/q debugging file on macOS? | <p>On macOS, when I execute this simple Python code using <a href="https://github.com/zestyping/q" rel="nofollow noreferrer">q package</a>:</p>
<pre><code>import q
q('test')
</code></pre>
<p>I have not the file <code>/tmp/q</code> created as my zsh session shows:</p>
<pre><code>cat /tmp/q
cat: /tmp/q: No such file or directory
</code></pre>
<p>However the documentation states <a href="https://github.com/zestyping/q#q" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>All output goes to /tmp/q (or on Windows, to $HOME/tmp/q)</p>
</blockquote>
| <python><python-3.x><macos><debugging> | 2023-11-19 11:47:26 | 1 | 2,425 | Jean-Pierre Matsumoto |
77,510,573 | 1,405,689 | Python: Extract different columns and assign to a new dataframe | <p>I have this df:</p>
<pre><code>A B C D
1 2 3 4
</code></pre>
<p>I want to extract columns 0:1 and 3rd one</p>
<p>But first thought would be:</p>
<pre><code>X = DS.iloc[:, 0:1:3].values
</code></pre>
<p>But, this approach does not work</p>
| <python><pandas><dataframe> | 2023-11-19 11:25:02 | 1 | 2,548 | Another.Chemist |
77,510,571 | 5,618,856 | Is .diff(period=-10) working on pandas series? | <p>I have a dataframe like so:</p>
<pre><code>import pandas as pd
import numpy as np
date_rng = pd.date_range(start="2023-11-18", periods=3, freq="10S")
values = [4, 2, 3]
df = pd.DataFrame(data={"values": values}, index=date_rng)
df["dt"] = df.index.to_series().diff().dt.seconds
df["dt"] = df.index.to_series().diff(periods=2).dt.seconds
df["dt_neg"] = df.index.to_series().diff(periods=-1).dt.seconds
print(df)
</code></pre>
<p>gives</p>
<pre><code> values dt dt_neg
2023-11-18 00:00:00 4 NaN 86390.0
2023-11-18 00:00:10 2 NaN 86390.0
2023-11-18 00:00:20 3 20.0 NaN
</code></pre>
<p>Shouldn't negative values work, too?</p>
<p>I read the answers <a href="https://stackoverflow.com/questions/16777570/calculate-time-difference-between-pandas-dataframe-indices">here</a> and <a href="https://stackoverflow.com/questions/31551099/pandas-difference-in-index-with-date-values">here</a>.</p>
| <python><pandas><dataframe><series> | 2023-11-19 11:24:23 | 1 | 603 | Fred |
77,510,519 | 8,157,102 | How can I bookmark all search results in PyCharm/JetBrains IDE? | <p>In a large-scale project, sometimes the number of search results is large, and I want to bookmark all the ones found in the search so that I can edit them later. How can I do it?</p>
<p>For example, in the following search, more than 100 items were found, and I want all 100 lines of code to be marked.</p>
<p><a href="https://i.sstatic.net/oyKA3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oyKA3.png" alt="enter image description here" /></a></p>
| <python><android-studio><pycharm><webstorm><jetbrains-ide> | 2023-11-19 11:06:42 | 1 | 961 | kamyarmg |
77,510,368 | 14,978,092 | How can i read csv from zip file python? | <p>I am trying to read csv which is in zip file. My task is to read the file rad_15min.csv file but the issue is when i read zip file (I copied link address by clicking on download button) it gives me error:</p>
<p><strong>Code:</strong></p>
<pre><code>import pandas as pd
df = pd.read_csv('https://www.kaggle.com/datasets/lucafrance/bike-traffic-in-munich/download?datasetVersionNumber=7')
</code></pre>
<p><strong>Error:</strong>
ParserError: Error tokenizing data. C error: Expected 1 fields in line 9, saw 2</p>
<p>Data: <a href="https://www.kaggle.com/datasets/lucafrance/bike-traffic-in-munich" rel="nofollow noreferrer">https://www.kaggle.com/datasets/lucafrance/bike-traffic-in-munich</a></p>
<p>Zip file Link: <a href="https://www.kaggle.com/datasets/lucafrance/bike-traffic-in-munich/download?datasetVersionNumber=7" rel="nofollow noreferrer">https://www.kaggle.com/datasets/lucafrance/bike-traffic-in-munich/download?datasetVersionNumber=7</a></p>
<p>I have to read this csv dynamically, I dont want to download it, All just to make a download link and then read csv dynamically. Is there any other approach which i can try ?</p>
| <python><python-3.x><pandas><csv> | 2023-11-19 10:12:56 | 1 | 590 | Hamza |
77,510,160 | 15,222,211 | How to strikethrough substrings without spaces in Sphinx? | <p>I need to <strike>strike</strike> substrings without spaces in Sphinx .rst file to transform it to HTML in a similar manner as <code><span style="text-decoration: line-through;">strike</span>substring</code>. The following example is not working for me. Is it possible?</p>
<p>conf.py</p>
<pre class="lang-py prettyprint-override"><code>extensions = ["sphinxnotes.strike"]
</code></pre>
<p>index.rst</p>
<pre><code>:strike:`strike`substring
</code></pre>
| <python><python-sphinx><restructuredtext><font-style> | 2023-11-19 08:41:15 | 2 | 814 | pyjedy |
77,510,115 | 2,840,697 | Effective way to iterate through all directories in python | <p>Let's say we want the following:</p>
<p>directory A contains directory B, and directory B contains three directories: C_one, C_two
We want to combine lists (all named 'features') in C_one, C_Two, C_three</p>
<p>we want</p>
<pre><code>from A.B import C_one, C_two, C_three
my_list = C_one.features + C_two.features + C_three.features
</code></pre>
<p>However, this seems a bit inefficient as you manually have to specify that which ones to import</p>
<pre><code>from A.B import C_one, C_two, C_three
</code></pre>
<p>from A.B and manually have to specify</p>
<pre><code>C_one.features + C_two.features + C_three.features
</code></pre>
<p>Is there a way to combine this one one sitting? Like</p>
<pre><code>my_list = []
for directory in A.B:
my_list.extend(A.B.directory.features)
</code></pre>
<p>any help would be greatly appreciated. Thanks.</p>
| <python><list><directory> | 2023-11-19 08:26:17 | 1 | 942 | user98235 |
77,510,100 | 15,063,341 | How to step into standard library while debugging? | <p>I was curious to see how <code>pickle</code> works and wanted to learn with debugging.</p>
<p>I have already searched for this question and disabled <code>justMyCode</code>, below is my <code>launch.json</code> file:</p>
<pre class="lang-json prettyprint-override"><code>{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": false,
}
]
}
</code></pre>
<p>Below is a simple program I tried to debug, I have put breakpoint on line 4, hoping to get inside <code>dumps</code> call, even I put break point in standard library <code>_dumps</code> method as well. It is not working, not allowing me to step into that function.</p>
<pre class="lang-py prettyprint-override"><code>import pickle
obj = {'x': [1, 2, 3], 'y': [4, 5, 6]}
serialized_obj = pickle.dumps(obj)
print(serialized_obj)
</code></pre>
| <python><visual-studio-code><debugging> | 2023-11-19 08:20:00 | 1 | 762 | Visrut |
77,509,988 | 4,584,863 | Streamlit fixed text search box and a clickable button at the bottom of streamlit app | <p>I'm trying hard to fix both a text search box and a voice search button at the bottom of the streamlit app UI but only textbox is getting fixed at the bottom. Button is not getting fixed but instead getting scrolled as I scroll the page. I tried many combinations in python, below is one straightforward approach</p>
<pre><code> text_col, button_col = st.columns([4, 1])
# Define styling for both elements
style = """
<style>
#stButtonVoice {
position: fixed;
bottom: 0;
right: 0;
margin-left: 1rem;
}
.stTextInput {
position: fixed;
bottom: 0;
left: 0;
margin-right: 1rem;
}
</style>
"""
# Inject the styling code for both elements
st.markdown(style, unsafe_allow_html=True)
# Add your text input and button
with text_col:
text_input = st.text_input(
"Any further query?", placeholder="search here...", key="text_input")
with button_col:
voice_search_button = st.button("Voice Search", key="stButtonVoice")
</code></pre>
<p>Here is how the output is looking like</p>
<p><a href="https://i.sstatic.net/s5ed4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/s5ed4.png" alt="enter image description here" /></a></p>
<p>Appreciate any work around for this problem. Note that i want voice search bottom too aligned along the line of the search text box</p>
| <python><html><css><streamlit> | 2023-11-19 07:27:37 | 1 | 510 | Bhanu Chander |
77,509,924 | 3,637,646 | If statement inside for-loop for assigning values to dictionary in python | <p>I am trying to assign values to a dictionary <code>test_dict</code> based on the values in an array <code>array_type</code>. Namely, I would like to assign a value of <code>beta</code> to <code>test_dict</code> in correspondence of the positions in which <code>array_type</code> is equal to 1. For this I use a for-loop with an internal if-statement.
In practice, if the value of a given element in <code>array_type</code> is 1, then assign a value of <code>beta</code> at the same position of <code>test_dict</code>.</p>
<p>I wrote the code below. However when I check the <code>counter</code> dictionary, which is supposed to contain the number of occurrences of 1 and 0, I do not get consistent results between the expectation and the results in the <code>counter</code>. The expectation for the <code>counter</code> results would be: <code>{'0' : 1000, '0.01' : 500}</code>.</p>
<p>Any advise?</p>
<pre><code>import numpy as np
#create a 0-based array of 1500 zeros
array_type = np.zeros(1500)
#create a 1-based array with 500 elements.
vals_n = np.ones(500)
#replace 500 elements in array_type with 1.
array_type = np.insert(array_type, np.random.choice(len(array_type), size=500), vals_n)
beta = 0.01
#initialize a counter dictionary with the two possible values
counter = {}
counter[0] = 0
counter[beta] = 0
test_dict = {}
indx = 0
for _ in range(0,1500,1):
if array_type[indx] == 1.0:
test_dict[indx] = beta
counter[beta] +=1
else:
test_dict[indx] = 0.0
counter[0] += 1
indx += 1
</code></pre>
| <python><for-loop><if-statement> | 2023-11-19 07:01:18 | 2 | 1,268 | CafféSospeso |
77,509,904 | 14,250,641 | Not able to see results from trained huggingface model | <p>I'm new to huggingface and after reading the documentation, I've been trying to fine-tune DNABERT2 on my simple dataset.</p>
<p>Basically, the idea is I have some DNA sequences that are labeled as '1' or '0', and I want to use the pre-trained DNABERT2 model to predict the label.</p>
<p>Example:</p>
<pre><code>AATTGGC 1
TCTC 0
TGTTA 1
</code></pre>
<p>I pretty much have all of the steps down, I think-- but I'm running into an error at the very last line-- <code>TypeError: '_TensorSliceDataset' object is not subscriptable</code>.</p>
<p>Here is all of the code I used (derived the steps from here: <a href="https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb" rel="nofollow noreferrer">https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb</a>):</p>
<pre><code>import pandas as pd
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("zhihan1996/DNABERT-2-117M", trust_remote_code=True)
model = AutoModel.from_pretrained("zhihan1996/DNABERT-2-117M", trust_remote_code=True).to('cuda')
# Assuming 'sequences' is a list of DNA sequences and 'labels' is a list of binary labels (0 or 1)
# Split the data into training and testing sets
df = pd.read_csv('/content/dev.csv', nrows=10)
df1 = pd.read_csv('/content/test.csv', nrows=10)
train_sequences=df.iloc[:, 0].tolist()
test_sequences=df1.iloc[:, 0].tolist()
train_labels=df.iloc[:, 1].tolist()
test_labels =df1.iloc[:, 1].tolist()
# Tokenize and format the data
train_encodings = tokenizer(train_sequences, truncation=True, padding=True)
test_encodings = tokenizer(test_sequences, truncation=True, padding=True)
# convert encodings
import tensorflow as tf
train_dataset = tf.data.Dataset.from_tensor_slices((
dict(train_encodings),
train_labels
))
test_dataset = tf.data.Dataset.from_tensor_slices((
dict(test_encodings),
test_labels
))
from transformers import TrainingArguments
training_args = TrainingArguments(output_dir="test_trainer")
import numpy as np
import evaluate
metric = evaluate.load("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
compute_metrics=compute_metrics,
)
</code></pre>
<p>Everything runs fine until I run the final line:</p>
<pre><code>trainer.train()
</code></pre>
| <python><tensorflow><huggingface-transformers><bert-language-model><large-language-model> | 2023-11-19 06:52:58 | 1 | 514 | youtube |
77,509,892 | 5,790,653 | check if the value of one json field is true based on yaml | <p>This is my <code>yaml</code>:</p>
<pre><code>-
dedicatedip: 1.1.1.1
status: active
type: typeA
-
dedicatedip: 2.2.2.2
status: active
type: typeB
-
dedicatedip: 2.2.2.2
status: active
type: typeA
-
</code></pre>
<p>This is <code>json</code>:</p>
<pre><code>{
"error": false,
"data": {
"licenses": [
{
"id": 167689,
"type": "typeA",
"ip": "1.1.1.1",
"status": "Active",
"automated": false,
"notes": ""
},
{
"id": 167689,
"type": "typeA",
"ip": "2.2.2.2",
"status": "Active",
"automated": false,
"notes": ""
},
{
"id": 167689,
"type": "typeB",
"ip": "2.2.2.2",
"status": "Active",
"automated": true,
"notes": ""
}
]
}
}
</code></pre>
<p>I'm trying to find if the IP in <code>yaml</code> has the same type in the <code>json</code> (one IP may have different types, and each type is going to be checked separately), and then check the <code>automated</code> field in the <code>json</code>.</p>
<p>Expected output is:</p>
<pre><code>IP 2.2.2.2, type typeA, automated is false.
IP 1.1.1.1, type typeA, automated is false.
</code></pre>
<p>This is my failed attempt so far:</p>
<pre><code>import json, yaml
with open ("file.yaml", "r", encoding="utf-8") as yf, open("file.json", "r", encoding="utf-8") as jf:
ydata = list(yaml.safe_load_all(yf))
jdata = json.load(jf)
delta = [
(yd["dedicatedip"], jd["type"], yd["status"], jd["status"])
for yd in ydata[0] for jd in jdata["data"]["licenses"]
if yd and yd["dedicatedip"] == jd["ip"]
and yd["type"].replace("Type ", "").lower() == jd["type"].lower()
and jd["automated"] != 'true'
]
for vars in delta:
print('IP {}, license type {} automate is false in json.\n'.format(*vars))
</code></pre>
<p>I get this output when I run, which is not correct:</p>
<pre><code>IP 1.1.1.1, license type typeA, automate is false is json.
IP 2.2.2.2, license type typeB, automate is false is json.
IP 2.2.2.2, license type typeA, automate is false is json.
</code></pre>
| <python> | 2023-11-19 06:49:02 | 1 | 4,175 | Saeed |
77,509,875 | 10,200,497 | Finding the longest streak of numbers, sum the values of that group and create an new dataframe | <p>This is an extension to this <a href="https://stackoverflow.com/questions/77505772/finding-the-largest-groups-with-conditions-after-using-groupby/77505997#77505997">post</a>.</p>
<p>My dataframe is:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{
'a': [
'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b',
],
'b': [
-20, 20, 20, 20,-70, -70, 10, -1000, -10, 100, 100,
-11, -100, -1, -1, -100, 100, 1, 90, -1, -2, 1000, 900
],
'c': [
'f', 'f', 'f', 'f', 'f', 'x', 'x', 'x', 'y', 'y', 'y', 'a',
'k', 'k', 'k', 'k', 'k', 't', 't', 't', 't', 's', 'e',
],
}
)
</code></pre>
<p>And this is the output that I want. I want a dataframe with six columns:</p>
<pre><code>a direction length sum start end
a -1 2 -1010 x y
a 1 3 60 f f
b -1 4 -202 k k
b 1 3 191 k t
</code></pre>
<p>I want to get the largest positive and negative streak in column <code>b</code> for each group in column <code>a</code> and sum the values of column <code>b</code> after that. This issue has already been solved <a href="https://stackoverflow.com/a/77505943/10200497">here</a>. In the post that is noted on top I explained the issue in more detail.</p>
<p>Now what I want to add is: After finding the sum of longest negative and positive streak in <code>b</code>, I need the start and end values of column <code>c</code> of those streaks.</p>
<p>In this image I highlighted the groups that have the longest streak:</p>
<p><a href="https://i.sstatic.net/lhNBC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lhNBC.png" alt="enter image description here" /></a></p>
<p>What I have tried is:</p>
<pre><code>df['sign'] = np.sign(df.b)
group = df['sign'].ne(df['sign'].shift()).cumsum()
out = (df
.assign(direction=np.sign(df['b']))
.groupby(['a', 'direction', group], as_index=False)
.agg(length=('b', 'count'),
sum=('b', 'sum'))
.sort_values(by='sum', key=abs, ascending=False)
.loc[lambda d: d.groupby(['a', 'direction'])['length'].idxmax(),
['a','direction', 'length', 'sum']]
)
df['streak'] = df['sign'].ne(df['sign'].shift()).cumsum()
df['length'] = df.groupby('streak')['b'].transform('size')
df['sum'] = df.groupby('streak', as_index=False)['b'].transform(sum)
dfm = df.merge(out, on=['a', 'length', 'sum'], how='inner')
</code></pre>
<p>It is getting close but it feels like this is not the way to do it.</p>
| <python><pandas><dataframe> | 2023-11-19 06:39:48 | 2 | 2,679 | AmirX |
77,509,556 | 1,377,354 | How to check whether Python code raised any exceptions | <p>I want to test that a large chunk of Python code doesn't raise any exceptions. Both because they're a bit expensive so I want to avoid them under "normal" execution, and because I want my debugger's ability to break on any raised exception to pinpoint the earliest sign of something going wrong.</p>
<p>I can manually run this code with the debugger to test that my code is free of raised exeptions, but I'd like to automate this to avoid regressions.</p>
<p>I tried to use <a href="https://docs.python.org/3/library/sys.html#sys.settrace" rel="nofollow noreferrer"><code>sys.settrace()</code></a>, but I keep observing <code>"exception"</code> events. I suspect they happen deep inside Python library code and the debugger ignores those. Should I attempt to filter out only the exceptions in my code? Or is there a better way to go about this?</p>
| <python> | 2023-11-19 03:56:04 | 0 | 840 | Nicolas Capens |
77,509,047 | 3,107,664 | h2ogpt custom Prompt wrong: invalid syntax. Maybe you meant '==' or ':=' instead of '='? (<unknown>, line 1) | <p>my prompt looks like this:</p>
<pre><code>GPT4 User: {prompt}<|end_of_turn|>GPT4 Assistant:
</code></pre>
<p>I tried to set it up like this:</p>
<pre><code>--prompt_type=custom \
--prompt_dict="{humanstr=GPT4 User: ,terminate_response=<|end_of_turn|>, botstr=GPT4 Assistant: }" \
</code></pre>
<p>but getting the error:</p>
<pre><code> File "/h2ogpt_conda/lib/python3.10/site-packages/fire/core.py", line 475, in _Fire
component, remaining_args = _CallAndUpdateTrace(
File "/h2ogpt_conda/lib/python3.10/site-packages/fire/core.py", line 691, in _CallAndUpdateTrace
component = fn(*varargs, **kwargs)
File "/workspace/src/gen.py", line 1215, in main
get_generate_params(model_lower,
File "/workspace/src/gen.py", line 4015, in get_generate_params
raise RuntimeError("Prompt wrong: %s" % error0)
RuntimeError: Prompt wrong: invalid syntax. Maybe you meant '==' or ':=' instead of '='? (<unknown>, line 1)
</code></pre>
<p>I am following the guide <a href="https://github.com/h2oai/h2ogpt/blob/main/docs/FAQ.md#adding-prompt-templates" rel="nofollow noreferrer">here</a>.</p>
<p>what am I missing?</p>
| <python><large-language-model><h2ogpt> | 2023-11-18 23:15:15 | 1 | 1,932 | Shery |
77,508,980 | 998,291 | Pydantic list containing two different types of dictionaries but never either | <p>I can't seem to get around this problem.
Consider the following JSON</p>
<pre><code> {"sourceInfo": {
"list": [
{
"Ec2AssetSourceSimple": {
"instanceType": "t2.micro",
"subnetId": "subnet-xxxxxxxx",
"imageId": "ami-xxxxxxxx",
"groupName": "AutoScaling-Security-Group-1",
"accountId": "xxxxxxxxx",
"macAddress": "12:5e:2e:xxxxxxx",
"reservationId": "r-xxxxxxx",
"instanceId": "i-xxxxxxxxx",
"monitoringEnabled": "false",
"spotInstance": "false",
"zone": "VPC",
"instanceState": "RUNNING",
"privateDnsName": "ip-xxxxxxx.ec2.internal",
"vpcId": "vpc-xxxxxxx",
"type": "EC_2",
"availabilityZone": "us-east-1b",
"privateIpAddress": "xxxxxx",
"firstDiscovered": "2022-08-18T22:23:04Z",
"ec2InstanceTags": {
"tags": {
"list": []
}
},
"publicIpAddress": "xxxxxxxx",
"lastUpdated": "2022-08-31T01:09:09Z",
"region": "us-east-1",
"assetId": xxxxxxx,
"groupId": "sg-xxxxxxx",
"localHostname": "ip-xxxxxxxx.ec2.internal",
"publicDnsName": "ec2-xxxxxx.compute-1.amazonaws.com"
}
},
{
"AssetSource": {}
}
]
}}
</code></pre>
<p>The corresponding Pydantic class defitions</p>
<pre><code>class Ec2AssetSourceSimple(BaseModel):
instanceType: str
subnetId: str
imageId: str
groupName: str
accountId: str
macAddress: str
reservationId: str
...
class AssetSource(BaseModel):
pass
class SourceInfoItem(BaseModel):
Ec2AssetSourceSimple: Optional[Ec2AssetSourceSimple] = None
AssetSource: Optional[AssetSource] = None
class SourceInfo(BaseModel):
list: List[SourceInfoItem]
</code></pre>
<p>Always results in the following exception</p>
<pre><code>ValidationError: 2 validation errors for QualysHost
sourceInfo.list.0.AssetSource
Field required [type=missing, input_value={'Ec2AssetSourceSimple': ...mpute-1.amazonaws.com'}}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.5/v/missing
sourceInfo.list.1.Ec2AssetSourceSimple
Field required [type=missing, input_value={'AssetSource': {}}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.5/v/missing
</code></pre>
<p>The internal dictionaries don't have a key so Pydantic is looking for both classes to appear which clearly isn't the case.
How do I force it to be Optional?</p>
| <python><json><pydantic> | 2023-11-18 22:44:23 | 1 | 881 | shluvme |
77,508,717 | 1,447,207 | Where to find the code for ESRK1 and RSwM1 in the Julia library source code? | <p>I'm trying to implement the SDE solver called ESRK1 and the adaptive stepsize algorithm called RSwM1 from Rackauckas & Nie (2017). I'm writing a python implementation, mainly to confirm to myself that I've understood the algorithm correctly. However, I'm running into a problem already at the implementation of ESRK1: When I test my implementation with shorter and shorter timesteps on a simple SDE describing geometric Brownian motion, the solution does not converge as <code>dt</code> becomes smaller, indicating that I have a mistake in my code.</p>
<p>I believe this algorithm is implemented as part of the library DifferentialEquations.jl in Julia, so I thought perhaps I could find some help by looking at the Julia code. However, I have had some trouble locating the relevant code. If someone could point me to the implementation of ESRK1 and RSwM1 in the relevant Julia librar(y/ies) (or indeed any other readable and correct implementation) of these algorithms, I would be most grateful.</p>
<p>I searched for ESRK and RSwM in the github repo of StochasticDiffEq.jl, but I didn't find anything I could really recognise as the method from the paper I'm reading:</p>
<p><a href="https://github.com/search?q=repo%3ASciML%2FStochasticDiffEq.jl+rswm&type=code" rel="nofollow noreferrer">https://github.com/search?q=repo%3ASciML%2FStochasticDiffEq.jl+rswm&type=code</a></p>
<p><strong>Update:</strong>
I found the code for ESRK1, as shown in my answer below, but I'm still unable to find the code for RSwM1.</p>
<p>For completeness, here is my own not-yet-correct implementation of ESRK1 in python:</p>
<pre><code>def ESRK1(U, t, dt, f, g, dW, dZ):
# Implementation of ESRK1, following Rackauckas & Nie (2017)
# Eq. (2), (3) and (4) and Table 1
# Stochastic integrals, taken from Eqs. (25) - (30) in Rackauckas & Nie (2017)
I1 = dW
I11 = (I1**2 - dt) / 2
I111 = (I1**3 - 3*dt*I1) / 6
I10 = (I1 + dZ/np.sqrt(3))*dt / 2
# Coefficients, taken from Table 1 in Rackauckas & Nie (2017)
# All coefficients not included below are zero
c0_2 = 3/4
c1_2, c1_3, c1_4 = 1/4, 1, 1/4
A0_21 = 3/4
B0_21 = 3/2
A1_21 = 1/4
A1_31 = 1
A1_43 = 1/4
B1_21 = 1/2
B1_31 = -1
B1_41, B1_42, B1_43 = -5, 3, 1/2
alpha1, alpha2 = 1/2, 2/3
alpha_tilde1, alpha_tilde2 = 1/2, 1/2
beta1_1, beta1_2, beta1_3 = -1, 4/3, 2/3
beta2_1, beta2_2, beta2_3 = -1, 4/3, -1/3
beta3_1, beta3_2, beta3_3 = 2, -4/3, -2/3
beta4_1, beta4_2, beta4_3, beta4_4 = -2, 5/3, -2/3, 1
# Stages in the Runge-Kutta approximation
# Eqs. (3) and (4) and Table 1 in Rackauckas & Nie (2017)
# First stages
H0_1 = U # H^(0)_1
H1_1 = U
# Second stages
H0_2 = U + A0_21 * f(t, H0_1)*dt + B0_21 * g(t, H1_1)*I10/dt
H1_2 = U + A1_21 * f(t, H0_1)*dt + B1_21 * g(t, H1_1)*np.sqrt(dt)
# Third stages
H0_3 = U
H1_3 = U + A1_31 * f(t, H0_1) * dt + B1_31 * g(t, H1_1) * np.sqrt(dt)
# Fourth stages
H0_4 = U
H1_4 = U + A1_43 * f(t, H0_3) * dt + (B1_41 * g(t, H1_1) + B1_42 * g(t+c1_2*dt, H1_2) + B1_43 * g(t+c1_3*dt, H1_3)) * np.sqrt(dt)
# Construct next position
# Eq. (2) and Table 1 in Rackauckas & Nie (2017)
U_ = U + (alpha1*f(t, H0_1) + alpha2*f(t+c0_2*dt, H0_2))*dt \
+ (beta1_1*I1 + beta2_1*I11/np.sqrt(dt) + beta3_1*I10/dt ) * g(t, H1_1) \
+ (beta1_2*I1 + beta2_2*I11/np.sqrt(dt) + beta3_2*I10/dt ) * g(t + c1_2*dt, H1_2) \
+ (beta1_3*I1 + beta2_3*I11/np.sqrt(dt) + beta3_3*I10/dt ) * g(t + c1_3*dt, H1_3) \
+ (beta4_4*I111/dt ) * g(t + c1_4*dt, H1_4)
# Calculate error estimate
# Eq. (9) and Table 1 in Rackauckas & Nie (2017)
E = -dt*(f(t, H0_1) + f(t + c0_2*dt, H0_2))/6 \
+ (beta3_1*I10/dt + beta4_1*I111/dt)*g(t, H1_1) \
+ (beta3_2*I10/dt + beta4_2*I111/dt)*g(t + c1_2*dt, H1_2) \
+ (beta3_3*I10/dt + beta4_3*I111/dt)*g(t + c1_3*dt, H1_3) \
+ (beta4_4*I111/dt)*g(t + c1_4*dt, H1_4)
# Return next position and error
return U_, E
</code></pre>
<p>Rackauckas & Nie (2017): <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5844583/pdf/nihms920388.pdf" rel="nofollow noreferrer">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5844583/pdf/nihms920388.pdf</a></p>
| <python><math><julia><stochastic><differentialequations.jl> | 2023-11-18 21:07:16 | 1 | 803 | Tor |
77,508,682 | 6,063,706 | Correct way to do Lagrange dual optimization PyTorch? | <p>I am trying to optimize a simple dual of a linear program using PyTorch. This is my code, but I keep getting an error with the backwards pass after the first loop:</p>
<pre><code>c_t = torch.tensor(c).float()
A_t = torch.tensor(A).float()
b_t = torch.tensor(b).float()
x_t = torch.rand(n, 1, requires_grad=True)
def max_grad(grad):
return -grad
_lagrange_multiplier = torch.rand(m, requires_grad=True)
_lagrange_multiplier.register_hook(max_grad) # because we maximize wrt lambda
lagrange_multiplier = torch.nn.functional.softplus(_lagrange_multiplier)
opt_weights = torch.optim.Adam([x_t], lr=0.1)
opt_lagrange = torch.optim.Adam([_lagrange_multiplier], lr=0.1)
for i in range(10):
print(i)
opt_weights.zero_grad()
opt_lagrange.zero_grad()
objective = c_t.T @ x_t
constraint = (A_t @ x_t).squeeze() - b_t
lagrangian = objective + lagrange_multiplier.T @ constraint
lagrangian.backward()
opt_weights.step()
opt_lagrange.step()
</code></pre>
<p>However, I keep getting the following error:</p>
<pre><code>RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.
</code></pre>
<p>I thought that since I was zero_grading I could recall backwards?</p>
<p>Thanks for the help.</p>
| <python><pytorch><linear-programming> | 2023-11-18 20:54:24 | 1 | 1,035 | Tob |
77,508,603 | 843,458 | python finding indexes of strings does not work | <p>I have a list of filenames and a filename. Now I want to get the index.</p>
<p>I can check that an entry exists, does that match only for identical entries?</p>
<pre><code>count = tfilename.count(filename)
if count > 0:
print(f'{filename} is present in the list for {count} times.')
</code></pre>
<p>I can also get the index of the first</p>
<pre><code>indexT = tfilename.index(filename)
</code></pre>
<p>However my search function always returns empty</p>
<pre><code>def findMatches(s, l1):
matched_indexes = []
i = 0
length = len(l1)
while i < length:
listElement = l1[i]
if listElement.find(s) > 0:
matched_indexes.append(i)
i += 1
return matched_indexes
indexesT = findMatches(filename, tfilename)
</code></pre>
<p>Now I do not have a solution for finding substrings in a list and returning an array with all indexes. It seems like a simple task but does not work.</p>
| <python><find> | 2023-11-18 20:28:32 | 1 | 3,516 | Matthias Pospiech |
77,508,528 | 2,813,606 | How to reverse order of pandas string column | <p>I have a tennis dataset that looks similar to the following:</p>
<pre><code>import pandas as pd
player_name = ['Novak Djokovic','Rafael Nadal','Roger Federer','Andy Murray']
match_id = [202, 202, 203, 203]
score = ['6-3 5-7 6-4', '6-3 5-7 6-4', '6-4 7-6', '6-4 7-6']
outcome = [1,0,1,0]
df = pd.DataFrame(
{'player_name': player_name,
'match_id': match_id,
'score': score,
'outcome':outcome
})
df["sets"]= df["score"].str.split(" ", n = 3, expand = False)
df['set1_score'] = df['sets'].str[0]
df['set2_score'] = df['sets'].str[1]
df['set3_score'] = df['sets'].str[2]
</code></pre>
<p>The outcome variable equates to a value of 1 with a win and a value of 0 for a loss. Currently, the score is written from the perspective of the winner. I want to be able to switch the order of the set1_score, set2_score, set3_score columns conditioned on the value of 0 (ie: for the loser of the match).</p>
<p>So, I would ideally like for the data frame to look like this:</p>
<pre><code>player_name match_id score outcome sets set1_score set2_score set3_score
Novak Djokovic 202 6-3 5-7 6-4 1 [6-3, 5-7, 6-4] 6-3 5-7 6-4
Rafel Nadal 202 6-3 5-7 6-4 0 [6-3, 5-7, 6-4] 3-6 7-5 4-6
Roger Federer 203 6-4 7-6 1 [6-4, 7-6] 6-4 7-6 NaN
Andy Murray 203 6-4 7-6 0 [6-4, 7-6] 4-6 6-7 NaN
</code></pre>
<p>How should I go about this process?</p>
<p>Thank you!</p>
| <python><pandas><string><reverse> | 2023-11-18 20:04:51 | 1 | 921 | user2813606 |
77,508,513 | 19,694,624 | Check if message was sent in a thread (discord.py / pycord) | <p>I need my discord bot to check if slash command is being executed in a thread or not. Couldn't find anything related in the discord.py docs <a href="https://discordpy.readthedocs.io/en/stable/api.html" rel="nofollow noreferrer">https://discordpy.readthedocs.io/en/stable/api.html</a> and there's no info on that on stackoverflow or anywhere else :(</p>
<p>I basically need something like <code>is_thread()</code> function. If it's even possible. Thanks for your help.</p>
| <python><python-3.x><discord><discord.py><pycord> | 2023-11-18 19:59:13 | 1 | 303 | syrok |
77,508,476 | 3,903,337 | pandas: groupby, add new column of unique occurances in one column with condition on a different column | <p>I've seen a lot of variants of this question on stack overflow but none of them seem to work for this specific case.</p>
<p>I have a dataframe with 3 columns, as follows:</p>
<pre><code>df = pd.DataFrame({
'col1': ['a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'a'],
'col2': [1,2,1,4,5,6,6,6,9,1],
'col3': ['LOW', 'HIGH', 'LOW','LOW','HIGH', 'LOW', 'HIGH', 'LOW', 'HIGH', 'HIGH']
})
</code></pre>
<p>I now want to add two new columns, <code>low-count</code> and <code>high-count</code>, to this dataframe. For each value of <code>col1</code>, <code>low-count</code> is the number of unique values in <code>col2</code> when <code>col3=='LOW'</code>, and <code>high-count</code> is the number of unique values in <code>col2</code> when <code>col3=='HIGH'</code>.</p>
<p>So resulting dataframe would be:</p>
<pre><code>pd.DataFrame({
'col1': ['a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'a'],
'col2': [1,2,1,4,5,6,6,6,9,1],
'col3': ['LOW', 'HIGH', 'LOW','LOW','HIGH', 'LOW', 'HIGH', 'LOW', 'HIGH', 'HIGH'],
'low-count': [1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
'high-count': [2, 2, 1, 1, 1, 2, 2, 2, 2, 2]
})
</code></pre>
<p>because, for example, for value <code>b</code> in <code>col1</code>, there are 2 unique values of <code>col2</code> when <code>col3=='LOW'</code>, hence the <code>low-count</code> for all rows where <code>col1=='b'</code>, we'll have <code>low-count</code> to be 2.</p>
<p>I've tried the following with <code>groupby</code> and <code>apply</code>, but I can't figure out how to add it as a new column to the original dataframe:</p>
<p><code>df.groubpy('col1').apply(lambda x: x[x['col3']=='LOW']['col2'].unique()</code></p>
<p>I'd appreciate any help!</p>
| <python><pandas><group-by> | 2023-11-18 19:48:45 | 2 | 308 | kpriya |
77,508,414 | 13,950,870 | Using BCP to write data to azure sql database not (much) faster than pandas to_sql | <p>I have written this quick test script to compare the performance of bcp (using <code>bcpandas</code> package) to the performance of regular pandas <code>df.to_sql</code>. See the script below:</p>
<pre class="lang-py prettyprint-override"><code>import time
import pandas as pd
import os
import numpy as np
from dotenv import load_dotenv
from db import create_con
from bcpandas import SqlCreds, to_sql
load_dotenv(override=True)
creds = SqlCreds(
os.environ['SQL_SERVER'],
os.environ['SQL_DB'],
os.environ['SQL_USER'],
os.environ['SQL_PW']
)
df = pd.DataFrame(
data=np.ndarray(shape=(100000, 6), dtype=int),
columns=[f"col_{x}" for x in range(6)]
)
#Using BCP
start = time.time()
print('Starting...')
to_sql(df, 'bcp_test_src', creds, index=False, if_exists='replace', schema='test', batch_size=10000)
print('Ending...')
end = time.time()
elapsed = end - start
print(f'Elapsed time: {elapsed} seconds')# 15.5 seconds
# Using Pandas to_sql
start = time.time()
print('Starting...')
con = create_con()
df.to_sql('bcp_test_src', con=con, index=False, if_exists='replace', schema='test')
print('Ending...')
end = time.time()
elapsed = end - start
print(f'Elapsed time: {elapsed} seconds')# 17.2 seconds
</code></pre>
<p>However, the difference between BCP and Pandas is very small. BCP takes 15.5 seconds and df.to_sql 17.2. Reading about BCP I was expecting it to just take a few seconds maximum to finish it all. What am I doing wrong? The database I am writing it to is an Azure SQL Database with the pricing tier of <code>Standard S0: 10 DTUs</code>. Could this have anything to do with it?</p>
| <python><pandas><bcp> | 2023-11-18 19:27:45 | 0 | 672 | RogerKint |
77,508,343 | 1,725,553 | memory leak reading video frames to numpy array using ffmpeg as a python subprocess | <p>I can stream videos frame by frame to an OpenGL Texture2D OK in python (pi3d module, example in pi3d_demos/VideoWalk.py) but I've noticed that it gradually leaks memory. Below is a stripped down version of the code that shows the problem.</p>
<p>Can anyone see where I'm leaking? The memory seems to be recovered when python stops. I've tried explicitly setting things to <code>None</code> or calling the garbage collector manually.</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python
import os
import numpy as np
import subprocess
import threading
import time
import json
def get_dimensions(video_path):
probe_cmd = f'ffprobe -v error -show_entries stream=width,height,avg_frame_rate -of json "{video_path}"'
probe_result = subprocess.check_output(probe_cmd, shell=True, text=True)
video_info_list = [vinfo for vinfo in json.loads(probe_result)['streams'] if 'width' in vinfo]
if len(video_info_list) > 0:
video_info = video_info_list[0] # use first if more than one!
return(video_info['width'], video_info['height'])
else:
return None
class VideoStreamer:
def __init__(self, video_path):
self.flag = False # use to signal new texture
self.kill_thread = False
self.command = [ 'ffmpeg', '-i', video_path, '-f', 'image2pipe',
'-pix_fmt', 'rgb24', '-vcodec', 'rawvideo', '-']
dimensions = get_dimensions(video_path)
if dimensions is not None:
(self.W, self.H) = dimensions
self.P = 3
self.image = np.zeros((self.H, self.W, self.P), dtype='uint8')
self.t = threading.Thread(target=self.pipe_thread)
self.t.start()
else: # couldn't get dimensions for some reason - assume not able to read video
self.W = 240
self.H = 180
self.P = 3
self.image = np.zeros((self.H, self.W, self.P), dtype='uint8')
self.t = None
def pipe_thread(self):
pipe = None
while not self.kill_thread:
st_tm = time.time()
if pipe is None:
pipe = subprocess.Popen(self.command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)
self.image = np.frombuffer(pipe.stdout.read(self.H * self.W * self.P), dtype='uint8') # overwrite array
pipe.stdout.flush() # presumably nothing else has arrived since read()
pipe.stderr.flush() # ffmpeg sends commentary to stderr
if len(self.image) < self.H * self.W * self.P: # end of video, reload
pipe.terminate()
pipe = None
else:
self.image.shape = (self.H, self.W, self.P)
self.flag = True
step = time.time() - st_tm
time.sleep(max(0.04 - step, 0.0)) # adding fps info to ffmpeg doesn't seem to have any effect
if pipe is not None:
pipe.terminate()
pipe = None
def kill(self):
self.kill_thread = True
if self.t is not None:
self.t.join()
vs = None
try:
while True:
for (path, _, videos) in os.walk("/home/patrick/Pictures/videos"):
for video in videos:
print(video)
os.system("free") # shows gradually declining memory available
vs = VideoStreamer(os.path.join(path, video))
for i in range(500):
tries = 0
while not vs.flag and tries < 5:
time.sleep(0.001)
tries += 1
# at this point vs.image is a numpy array HxWxP bytes
vs.flag = False
vs.kill()
except KeyboardInterrupt:
if vs is not None:
vs.kill()
os.system("free")
</code></pre>
| <python><numpy><ffmpeg><memory-leaks><subprocess> | 2023-11-18 19:05:24 | 1 | 2,277 | paddyg |
77,508,096 | 6,296,821 | How to scrape past a "Show More" button using BeautifulSoup | <p>I've seen a number of questions on this topic, but it seems like what really matters is how the "show more" button functions, and I'm not fluent enough to figure that out.</p>
<p>I'm trying to scrape <a href="https://www.llbean.com/llb/shop/630?page=womens-footwear&csp=f&bc=474&gnrefine=1*BRAND*L.L.Bean&sort_field=relevance&start=1&viewCount=48&nav=gnro2-hp&newPla=1" rel="nofollow noreferrer">this page</a>, but I want to get all results and not just the ones above the "show more" button at the bottom. My code below already works fine for the results above the button.</p>
<pre><code>import requests as re
import bs4
import pandas as pd
url = 'https://www.llbean.com/llb/shop/630?page=womens-footwear&csp=f&bc=474&gnrefine=1*BRAND*L.L.Bean&sort_field=relevance&start=1&viewCount=48&nav=gnro2-hp&newPla=1'
result = re.get(url)
soup = bs4.BeautifulSoup(result.text, 'lxml')
products = soup.find_all('li', class_='ProductThumbnail_container')
product_data = {'Image':[], 'Style Name':[], 'Style Type':[], 'Color Offering':[], 'Price Point':[], 'Sale Price Point':[],
'Description':[], '"Why we love it" LLBEAN SPECIFIC':[], 'F&B/construction':[], 'Reviews Rating':[], 'Number of Reviews':[],
'Review Notes':[], 'Merch Notes':[], 'Link':[]}
for i in products:
product_image = i.find('img')
product_name = i.find('a', class_='ProductThumbnail_name Anchor_not-underlined Anchor_anchor')
product_colors = i.find('div', class_='ProductThumbnail_color-count')
product_price = i.find('span', class_='')
product_sales_price = i.find('span', class_='sale')
product_rating = i.find('span', itemprop='ratingValue')
product_number_of_reviews = i.find('a', class_='Rating_count Anchor_anchor')
product_link = i.find('a', class_='ProductThumbnail_product')
product_data['Image'].append(product_image.attrs['src'])
product_data['Style Name'].append(product_name.string)
product_data['Style Type'].append('')
try:
product_data['Color Offering'].append(product_colors.string.split('"')[1])
except:
product_data['Color Offering'].append('')
try:
product_data['Price Point'].append(product_price.string)
except:
product_data['Price Point'].append('')
try:
product_data['Sale Price Point'].append(product_sales_price.string)
except:
product_data['Sale Price Point'].append('')
product_data['Description'].append('')
product_data['"Why we love it" LLBEAN SPECIFIC'].append('')
product_data['F&B/construction'].append('')
try:
product_data['Reviews Rating'].append(product_rating.string)
except:
product_data['Reviews Rating'].append('')
try:
product_data['Number of Reviews'].append(product_number_of_reviews.string)
except:
product_data['Number of Reviews'].append('')
product_data['Review Notes'].append('')
product_data['Merch Notes'].append('')
product_data['Link'].append(product_link.attrs['href'])
df = pd.DataFrame(product_data)
df.to_csv('llbean_womens.csv')
</code></pre>
| <python><web-scraping><beautifulsoup> | 2023-11-18 17:55:48 | 2 | 569 | bkula |
77,508,041 | 998,291 | Normalize two different jsons according to shared values | <p>I have two data sources that I retrieve different format Json's from and I want to create a normalized object that will represent the merged Json's according to distinct values.</p>
<p>For example, the first json:</p>
<pre><code>[
{
"zone_group": "us-east-1b",
"kernel_version": "5.10.130-118.517.amzn2.x86_64",
"chassis_type": "1",
"chassis_type_desc": "Other",
"connection_ip": "172.xx.xx.xx",
"default_gateway_ip": "172.xx.xx.xx",
"connection_mac_address": "12-5e-2e-db-xx-xx"
...
}
]
</code></pre>
<p>the second json:</p>
<pre><code>[
{
"sourceInfo": {
"list": [
{
"Ec2AssetSourceSimple": {
"instanceType": "t2.micro",
"groupName": "AutoScaling-Group-1",
"macAddress": "12-5e-2e-db-xx-xx",
"monitoringEnabled": "false",
"spotInstance": "false",
"zone": "VPC",
"instanceState": "RUNNING",
"type": "EC_2",
"availabilityZone": "us-east-1b",
"privateIpAddress": "172.xx.xx.xx",
"firstDiscovered": "2022-08-18T22:23:04Z"
...
}
]
</code></pre>
<p>I want to normalize the Json's and create a unified representation of them based on values, in this example the IP address "172.xx.xx.xx" will be represented once in the normalized object (name taken from the first Json, but doesn't really matter).</p>
<p>How do I go about and do this?</p>
| <python><pandas><normalize><data-pipeline> | 2023-11-18 17:41:34 | 2 | 881 | shluvme |
77,507,844 | 4,285,386 | Poetry not installing via official method successfully - ModuleNotFound: No module named 'poetry.core.toml' | <p>I'm on MacOS, with a 2020 MBP. When I tried updating <code>poetry</code> (which I think was on 1.3, to 1.7.1, the current version as of writing) via <code>poetry self update</code>, I got this error:</p>
<pre><code>ModuleNotFoundError: No module named 'poetry.core.toml'
</code></pre>
<p>I deleted every trace of <code>poetry</code> I could find - <code>rm -rf</code>ing from my Python's site-packages, using the official uninstall script, nothing in my .zshrc file, removed <code>~/.local/bin/poetry</code>, tried different versions, I get the exact same error every single time when I do the simple <code>poetry --version</code>.</p>
<p>I have no idea what could be going on, I installed via the official installer and there was no pip nonsense because I wanted to avoid issues like this.</p>
<p>Does anyone have any idea why this would be?</p>
| <python><python-poetry> | 2023-11-18 16:46:31 | 1 | 896 | Daniel Soutar |
77,507,817 | 11,356,272 | Override the __str__ of ExceptionGroup to include the exceptions' message | <p>I was trying to use the new API of <code>ExceptionGroup</code> (reference <a href="https://docs.python.org/3/library/exceptions.html#exception-groups" rel="nofollow noreferrer">https://docs.python.org/3/library/exceptions.html#exception-groups</a>)</p>
<p>And it was just great, so for example if I do:</p>
<pre><code>raise ExceptionGroup('Some message', [Exception('first'), Exception('second')])
</code></pre>
<p>The exception error looks like this:</p>
<pre><code>+ Exception Group Traceback (most recent call last):
| File "<string>", line 1, in <module>
| ExceptionGroup: Some message (2 sub-exceptions)
+-+---------------- 1 ----------------
| Exception: first
+---------------- 2 ----------------
| Exception: second
+------------------------------------
</code></pre>
<p>But when I try it in try except clause, it seems like the to string of Exception is to show only the ExceptionGroup's message without the messages of the exceptions as well, so for example if I do this:</p>
<pre class="lang-py prettyprint-override"><code>try:
raise ExceptionGroup('Some message', [Exception('first'), Exception('second')])
except Exception as e:
print('Exception:', e)
</code></pre>
<p>The output would be:</p>
<pre><code>Exception: Some message (2 sub-exceptions)
</code></pre>
<p>So my idea is to have a new class, let's say <code>class Errors(ExceptionGroup)</code> that would override the <code>__str__</code> to include also the messages of the exception list, but I'm not sure how to do it, is there a reference to this messages exceptions? In the same way they are created in the traceback?</p>
| <python><exception> | 2023-11-18 16:39:58 | 0 | 1,199 | Dorki |
77,507,745 | 843,458 | Python hickle SerializedWarning when using dataclass | <p>I have a dataclass</p>
<pre><code>@dataclass
class ImageFile:
path: str
folder: str
</code></pre>
<p>when trying to save this list using hickle</p>
<pre><code>hkl.dump(ImageList)
</code></pre>
<p>it leads to this warning</p>
<pre><code>\lib\site-packages\hickle\lookup.py:1491: SerializedWarning: 'ImageFile' type not understood, data is serialized:
</code></pre>
<p>should I be worried?</p>
| <python> | 2023-11-18 16:22:46 | 1 | 3,516 | Matthias Pospiech |
77,507,627 | 11,751,609 | Using tensorflow model maker how to save checkpoints during training | <p>I am using the <a href="https://www.tensorflow.org/lite/models/modify/model_maker" rel="nofollow noreferrer">TensorflowLite model maker</a> and I would like to know how I can during training regularily save checkpoints so I can check the loss graphs with tensorboard. How is this done?</p>
<p>This function I call when I want to train but there seems to be no argument for additional settings like writing checkpoints or specifying a directory for it.</p>
<p><code>model = object_detector.create(train_data, model_spec=spec, batch_size=8, train_whole_model=True, validation_data=validation_data)</code></p>
| <python><tensorflow><tensorflow-lite> | 2023-11-18 15:50:16 | 2 | 1,647 | finisinfinitatis |
77,507,580 | 159,072 | UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown plt.show() | <p>I am using</p>
<ul>
<li>Windows 10</li>
<li>PyCharm 2021.3.3 Professional Edition</li>
<li>python 3.11.5</li>
<li>matplotlib 3.8.1</li>
</ul>
<p>How can I permanently resolve this issue in my development environment?</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# Read data from file, skipping the first row (header)
data = np.loadtxt('cm.dat', skiprows=1)
# Initialize reference point
x0, y0, z0 = data[0]
# Compute squared displacement for each time step
SD = [(x - x0)**2 + (y - y0)**2 + (z - z0)**2 for x, y, z in data]
# Compute the cumulative average of SD to get MSD at each time step
MSD = np.cumsum(SD) / np.arange(1, len(SD) + 1)
# Generate time steps
t = np.arange(1, len(SD) + 1)
# Create a log-log plot of MSD versus t
plt.figure(figsize=(8, 6))
plt.loglog(t, MSD, marker='o')
plt.title('Mean Squared Displacement vs Time')
plt.xlabel('Time step')
plt.ylabel('MSD')
plt.grid(True, which="both", ls="--")
plt.show()
</code></pre>
<pre class="lang-none prettyprint-override"><code>C:\Users\pc\AppData\Local\Programs\Python\Python311\python.exe C:/git/RouseModel/tau_plot.py
C:\git\RouseModel\tau_plot.py:29: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
Process finished with exit code 0
</code></pre>
| <python><matplotlib><pycharm> | 2023-11-18 15:40:11 | 12 | 17,446 | user366312 |
77,507,537 | 5,801,127 | Pandas how to vectorize this loop | <p>I am currently trying to calculate the pnl of a portfolio and I am having difficulties thinking about a way to vectorize the following code</p>
<pre><code>df_test_copy = df.copy()
df_test_copy['NV'] = 10000
df_test_copy['pnl'] = 0
last_nw = 10000
for idx, row in df.iterrows():
shares = last_nw / row['close_t+1']
if row['pred_label'] == 2: # long
pnl = (shares * row['close_t+16']) - (shares * row['close_t+1'])
last_nw += pnl
df_test_copy.loc[idx, 'pnl'] = pnl
elif row['pred_label'] == 1:
pnl = (shares * row['close_t+16']) - (shares * row['close_t+1'])
last_nw -= pnl
df_test_copy.loc[idx, 'pnl'] = -1*pnl
df_test_copy.loc[idx, 'NV'] = last_nw
</code></pre>
<p>I feel like the only thing that is giving me struggle is the fact that <code>last_nw</code> information from the last iteration.</p>
<p>Edit: I added a reproducible example where the dataframe looks like this:</p>
<pre><code>sample_df = pd.DataFrame(
{'open_time' : ['2022-08-16 07:20:00', '2022-08-16 07:21:00', '2022-08-16 07:22:00',
'2022-08-16 07:23:00', '2022-08-16 07:24:00', '2022-08-16 07:25:00',
'2022-08-16 07:26:00', '2022-08-16 07:27:00', '2022-08-16 07:28:00'],
'pred_label' : [1, 1, 1,
2, 1, 1,
2, 0, 0],
'close_t+1' : [1875.9, 1877.79, 1878.55,
1878.46, 1878.44, 1878.70,
1879.87, 1879.40, 1878.15],
'close_t+16' : [1878.30, 1878.90, 1877.51,
1879.44, 1880.38, 1880.11,
1881.25, 1880.18, 1881.85]}
)
</code></pre>
<p>And as for the output it should look something like this:</p>
<p><a href="https://i.sstatic.net/47NXu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/47NXu.png" alt="dataframe output" /></a></p>
| <python><pandas><dataframe> | 2023-11-18 15:29:29 | 1 | 1,011 | PutsandCalls |
77,507,520 | 13,955,154 | cannot import name 'LangchainEmbedding' from 'llama_index' | <p>I'm trying to build a simple RAG, and I'm stuck at this code:</p>
<pre><code>from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from llama_index import LangchainEmbedding, ServiceContext
embed_model = LangchainEmbedding(
HuggingFaceEmbeddings(model_name="thenlper/gte-large")
)
service_context = ServiceContext.from_defaults(
chunk_size=256,
llm=llm,
embed_model=embed_model
)
index = VectorStoreIndex.from_documents(documents, service_context=service_context)
</code></pre>
<p>where I get ImportError: cannot import name 'LangchainEmbedding' from 'llama_index'
How can I solve? Is it related to the fact that I'm working on Colab?</p>
| <python><google-colaboratory><embedding><langchain><llama-index> | 2023-11-18 15:26:32 | 6 | 720 | Lorenzo Cutrupi |
77,507,403 | 667,301 | How do I get the interface IP address from of a Cisco IOS configuration? | <p>When using the following Cisco IOS configuration, how do you get the interface IP address of <code>GigabitEthernet1/3</code> with <code>CiscoConfParse()</code>?</p>
<pre><code>!
hostname Example
!
interface GigabitEthernet1/1
description Example interface
ip address 192.0.2.1 255.255.255.128
no ip proxy-arp
!
interface GigabitEthernet1/2
shutdown
!
interface GigabitEthernet1/3
ip address 192.0.2.129 255.255.255.128
no ip proxy-arp
!
end
</code></pre>
<p>I tried using this, but it throws an AttributeError...</p>
<pre class="lang-py prettyprint-override"><code>from ciscoconfparse2 import CiscoConfParse
config = """!
hostname Example
!
interface GigabitEthernet1/1
description Example interface
ip address 192.0.2.1 255.255.255.128
no ip proxy-arp
!
interface GigabitEthernet1/2
shutdown
!
interface GigabitEthernet1/3
ip address 192.0.2.129 255.255.255.128
no ip proxy-arp
!
end
"""
parse = CiscoConfParse(config.splitlines(), syntax='ios', factory=False)
intf = parse.find_objects("interface GigabitEthernet1/3")[0]
print(f"GigabitEthernet1/3 address: {intf.ipv4}")
</code></pre>
<p>This throws an AttributeError...</p>
<pre class="lang-py prettyprint-override"><code>AttributeError: The ipv4 attribute does not exist
</code></pre>
| <python><cisco><ciscoconfparse> | 2023-11-18 14:59:33 | 1 | 43,231 | Mike Pennington |
77,507,389 | 893,254 | Python project directory structure. ModuleNotFoundError | <p>I have attempted to follow what I believe to be a standard Python project directory structure to create a minimal working test example.</p>
<p>Here is the structure I am currently using.</p>
<pre><code>python-project-test/
.venv/...
scripts/
main.py
src/
__init__.py
liblocal/
__init__.py
module1.py
</code></pre>
<p>This is what the import statement looks like in <code>main.py</code>:</p>
<pre><code>from src.liblocal.module1 import my_function
</code></pre>
<p>I have tried to run <code>main.py</code> from the project root.</p>
<pre><code>python3 scripts/main.py
</code></pre>
<p>Since <code>src</code> is a module (it contains an <code>__init__.py</code> file, I would have expected python to look in all adjacent directories to scripts and thus find the <code>src</code> module. This isn't working as I expected, which suggests I have misunderstood how python is expected to find the <code>src</code> module.</p>
<p>I have a few closely related questions:</p>
<ol>
<li>Why is this not working, and what might I do to fix it?</li>
<li>Does it matter what directory I run <code>main.py</code> from? (eg: from within <code>scripts</code> vs the project root)</li>
<li>I am using a virtual environment. If I understand correctly it should be possible to set up the virtual environment so that python knows where to find the module <code>src</code> and any sub-modules. If this is correct, how do I do that?</li>
<li>Does this project follow the expected "typical" python project directory structure? If not, what have I midunderstood or done differently?</li>
</ol>
| <python> | 2023-11-18 14:55:37 | 2 | 18,579 | user2138149 |
77,507,372 | 9,964,625 | pickle fails to load data: TypeError: _unpickle_timestamp() takes exactly 3 positional arguments (4 given) | <p>I have a dataset, stored in a pandas dataframe, that I have built and pickled in one environment. The pickle file loads fine in that environment (environment 1). However, when I try to load it in a different environment (environment 2), I get an error regarding unpickling timestamps. The error and the pickle versions are below.</p>
<p>The pickle versions are the same for both environments, although the build versions for the cloudpickle packages are different. Another difference is that environment 1 is python==3.10.12 and environment 2 is python==3.9.12.</p>
<p>I have tried installing the specific cloudpickle build, but conda fails to find a solution. I'm hesitant to try upgrading the python version of environment 2, as getting the keras dependencies to install along with the other packages I need in that environment is ... fussy.</p>
<p>Any suggestions would be appreciated.</p>
<pre><code>runfile('D:/driver_backprop.py', wdir='D:')
Traceback (most recent call last):
File "C:\Users\jerem\anaconda3\envs\keras\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec
exec(code, globals, locals)
File "d:\driver_backprop.py", line 14, in <module>
data_df = pickle.load(f)
File "pandas\_libs\tslibs\timestamps.pyx", line 132, in pandas._libs.tslibs.timestamps._unpickle_timestamp
TypeError: _unpickle_timestamp() takes exactly 3 positional arguments (4 given)
</code></pre>
<p>The code I'm using to load the file:</p>
<pre><code>import pickle
with open('data_w-solar.pickle','rb') as f:
data_df = pickle.load(f)
station_dict = pickle.load(f)
</code></pre>
<p>The pickle versions in environment 1 (which successfully loads):</p>
<pre><code>(shadow) C:\Users\jerem>conda list pickle
# packages in environment at C:\Users\jerem\anaconda3\envs\shadow:
#
# Name Version Build Channel
cloudpickle 2.2.1 py310haa95532_0
pickleshare 0.7.5 pyhd3eb1b0_1003
</code></pre>
<p>The pickle versions in environment 2 (which fails to load):</p>
<pre><code>(keras) C:\Users\jerem>conda list pickle
# packages in environment at C:\Users\jerem\anaconda3\envs\keras:
#
# Name Version Build Channel
cloudpickle 2.2.1 py39haa95532_0
pickleshare 0.7.5 pyhd3eb1b0_1003
</code></pre>
| <python><timestamp><pickle> | 2023-11-18 14:48:06 | 1 | 737 | Jeremy Matt |
77,507,370 | 11,833,435 | create multiple objects in model serializer create method | <p>I need the below DRF API View to list and create <code>Withdraw</code> records in my Django project.</p>
<pre class="lang-py prettyprint-override"><code>class WithdrawListCreateAPIView(PartnerAware, WithdrawQuerySetViewMixin, generics.ListCreateAPIView):
permission_classes = (TokenMatchesOASRequirements,)
required_alternate_scopes = {
"GET": [[OTCScopes.WITHDRAW_READ]],
"POST": [[OTCScopes.WITHDRAW_CREATE]],
}
def get_serializer_class(self, *args, **kwargs):
if self.request.method == "POST":
return WithdrawCreateSerializer
return WithdrawSerializer
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
self.get_partner_info()
def perform_create(self, serializer):
serializer.save(partner=self.partner, created_by=self.request.user)
</code></pre>
<p>My API construction must be for a single record, but it is possible that this amount may be greater than a specific amount called <code>SETTLEMENT_MAX_AMOUNT</code>, and I have to break it down to more than one <code>Withdraw</code> record and also I must create a separate record for each one, and I should return all these records that have been created in one list to the user.Here is the related serializer I've implemented for this case:</p>
<pre class="lang-py prettyprint-override"><code>class WithdrawCreateSerializer(serializers.ModelSerializer):
target_uuid = serializers.UUIDField(write_only=True)
def validate_target_uuid(self, value):
partner = self.context["view"].partner
try:
target = WithdrawTarget.objects.get(active=True, uuid=value, partner=partner)
except WithdrawTarget.DoesNotExist:
raise serializers.ValidationError("Target does not exist for the current partner.")
return target.uuid
def create(self, validated_data):
target_uuid = validated_data.pop("target_uuid")
partner = self.context["view"].partner
target = WithdrawTarget.objects.get(uuid=target_uuid, partner=partner)
amount = validated_data["amount"]
num_withdrawals = amount // SETTLEMENT_MAX_AMOUNT
remaining_amount = amount % SETTLEMENT_MAX_AMOUNT
withdrawals = []
for _ in range(num_withdrawals):
withdraw_data = {
"target": target,
"amount": SETTLEMENT_MAX_AMOUNT,
"partner": validated_data["partner"],
"created_by": validated_data["created_by"],
"description": validated_data.get("description"),
}
withdrawal = Withdraw.objects.create(**withdraw_data)
withdrawals.append(withdrawal)
if remaining_amount > 0:
withdraw_data = {
"target": target,
"amount": remaining_amount,
"partner": validated_data["partner"],
"created_by": validated_data["created_by"],
"description": validated_data.get("description"),
}
withdrawal = Withdraw.objects.create(**withdraw_data)
withdrawals.append(withdrawal)
return withdrawals
class Meta:
model = Withdraw
fields = ("uuid",
"amount",
"target_uuid",
"description",
"status",
"tracker_id",
"created_at",)
extra_kwargs = {
"amount": {"required": True, "allow_null": False},
"target_uuid": {"required": True, "allow_null": False},
}
read_only_fields = ("state", "tracker_id", "created_at")
</code></pre>
<p>Now by sending this request:</p>
<pre><code>curl --location '127.0.0.1:8000/withdraws/' \
--header 'Authorization: Bearer blob' \
--form 'amount="2240"' \
--form 'target_uuid="d4d92a38-4193-443c-b11e-8022e64543a4"'
</code></pre>
<p>for example, the value of <code>SETTLEMENT_MAX_AMOUNT</code> is 1000, and with the above request I should get 3 "Withdraw" records with amount of: 1000, 1000, 240.</p>
<p>I receive the following error in response:</p>
<pre><code>AttributeError at /withdraws/
Got AttributeError when attempting to get a value for field `amount` on serializer `WithdrawCreateSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `list` instance.
The original exception text was: 'list' object has no attribute 'amount'.
</code></pre>
<p>How can I change the above view or serializer the system behaves as I want?</p>
| <python><python-3.x><django><django-rest-framework><django-views> | 2023-11-18 14:48:00 | 1 | 2,133 | Javad |
77,507,319 | 2,304,735 | How can I read CSV file from function attribute into a pandas dataframe? | <p>I wrote a function that calculates the log returns of a dataframe. The arguments of the function takes the csv file name and should return a dataframe of the log returns of the csv file. The csv file is already located on my machine. Below is the code I am trying to execute.</p>
<pre><code>import pandas as pd
import numpy as np
def portfolio_log_returns(portfolio):
dataset = pd.read_csv(portfolio)
log_returns = pd.DataFrame(columns=dataset.columns)
for col in dataset.columns:
log_returns[col] = np.log(dataset[col]/dataset[col].shift(1))
log_returns = log_returns.dropna()
return log_returns
log_returns_df = portfolio_log_returns('some_csv_file.csv')
</code></pre>
<p>I get the following error when I try to execute the code:</p>
<pre><code>log_returns_df = portfolio_log_returns('some_csv_file.csv')
Traceback (most recent call last):
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\ops\array_ops.py:171 in _na_arithmetic_op
result = func(left, right)
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\computation\expressions.py:239 in evaluate
return _evaluate(op, op_str, a, b) # type: ignore[misc]
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\computation\expressions.py:128 in _evaluate_numexpr
result = _evaluate_standard(op, op_str, a, b)
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\computation\expressions.py:70 in _evaluate_standard
return op(a, b)
TypeError: unsupported operand type(s) for /: 'str' and 'NoneType'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
Cell In[4], line 1
log_returns_df = portfolio_log_returns('some_csv_file.csv')
Cell In[1], line 9 in portfolio_log_returns
log_returns[col] = np.log(dataset[col]/dataset[col].shift(1))
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\ops\common.py:81 in new_method
return method(self, other)
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\arraylike.py:210 in __truediv__
return self._arith_method(other, operator.truediv)
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\series.py:6112 in _arith_method
return base.IndexOpsMixin._arith_method(self, other, op)
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\base.py:1348 in _arith_method
result = ops.arithmetic_op(lvalues, rvalues, op)
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\ops\array_ops.py:232 in arithmetic_op
res_values = _na_arithmetic_op(left, right, op) # type: ignore[arg-type]
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\ops\array_ops.py:178 in _na_arithmetic_op
result = _masked_arith_op(left, right, op)
File D:\Users\Mahmoud\anaconda3\Lib\site-packages\pandas\core\ops\array_ops.py:116 in _masked_arith_op
result[mask] = op(xrav[mask], yrav[mask])
TypeError: unsupported operand type(s) for /: 'str' and 'str'
</code></pre>
<p>What is the problem and how can I fix it?</p>
| <python><python-3.x><pandas><dataframe> | 2023-11-18 14:33:09 | 1 | 515 | Mahmoud Abdel-Rahman |
77,507,293 | 7,169,895 | Why am I failing to get the IP Address of one website url using networkx and requests? | <p>I am trying to map website urls to their ip addresses and graph it using networkx. My code looks for all links on a webpage using BeautifulSoup and follows those links. I had trouble assigning attributes directly to the node, so I used networkx <code>set_node_attributes</code> with two lists containing the urls and the ip addresses. However, one url constantly fails to get an ip address assigned.</p>
<p>My code:</p>
<pre><code># Gets the links to traverse as well as the IP Address and returns them.
def get_links(url):
response = requests.get(url, stream=True)
ip_address = response.raw._connection.sock.getsockname()
soup = BeautifulSoup(response.text, 'lxml')
return [urljoin(url, a['href']) for a in soup.find_all('a', href=True)], ip_address
</code></pre>
<pre><code># Traverses the urls and
def bfs_traversal(start_url, num_layers, graph):
visited = []
visited_ip_addresses = []
queue = deque([(start_url, 0)])
attrs = {}
while queue:
url, layer = queue.popleft()
if layer > num_layers:
# add our attrs
for url, ip_address in zip(visited, visited_ip_addresses):
attrs[url] = ip_address
# Need to set the node attributes manually see below
nx.set_node_attributes(graph, values=attrs, name='ip_address')
break
if url not in visited:
visited.append(url)
connections, ip_address = get_links(url)
visited_ip_addresses.append(ip_address)
# No longer seems to work hence the above code
graph.add_node(url, ip_address=ip_address)
# throws error graph.add_node(url, {'ip_address':ip_address})
for x in connections:
graph.add_edge(url, x)
queue.append((x, layer + 1))
</code></pre>
<p>I then create the graph and assign the position:</p>
<pre><code>scan_layers = 1
entrance = "https://www.youtube.com/"
graph = nx.Graph()
seed = 0
bfs_traversal(entrance, scan_layers, graph)
pos = nx.spring_layout(graph, seed=seed)
# Add pos to the node
for n, p in pos.items():
graph.nodes[n]['pos'] = p
</code></pre>
<p>However, since I am having trouble correctly assigning the attributes to the nodes, my next code fails.</p>
<pre><code> ip_addresses = []
for node in graph.nodes(data=True):
print(node, '\n')
ip_address = node[1]['ip_address'][0]
ip_addresses.append(ip_address)
</code></pre>
<p>with</p>
<pre><code>('https://www.youtube.com/about/#content', {'pos': array([-0.48220751, -0.4565694 ])})
Traceback (most recent call last):
File "C:\Users\Owner\PycharmProjects\WebsiteMapper\gui.py", line 125, in <module>
gp = GraphPage()
^^^^^^^^^^^
File "C:\Users\Owner\PycharmProjects\WebsiteMapper\gui.py", line 36, in __init__
fig_json = create_network_graph()
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Owner\PycharmProjects\WebsiteMapper\graphs.py", line 89, in create_network_graph
ip_address = node[1]['ip_address'][0]
~~~~~~~^^^^^^^^^^^^^^
KeyError: 'ip_address'('https://www.youtube.com/about/#content', {'pos': array([-0.48220751, -0.4565694 ])})
Traceback (most recent call last):
File "C:\Users\Owner\PycharmProjects\WebsiteMapper\gui.py", line 125, in <module>
gp = GraphPage()
^^^^^^^^^^^
File "C:\Users\Owner\PycharmProjects\WebsiteMapper\gui.py", line 36, in __init__
fig_json = create_network_graph()
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Owner\PycharmProjects\WebsiteMapper\graphs.py", line 89, in create_network_graph
ip_address = node[1]['ip_address'][0]
~~~~~~~^^^^^^^^^^^^^^
KeyError: 'ip_address'
</code></pre>
<p>We can see an ip address was not assigned for <code>https://www.youtube.com/about/#content'</code> Why is this? What am I doing wrong?</p>
<p>Thanks for any pointers.</p>
| <python><networkx> | 2023-11-18 14:27:43 | 1 | 786 | David Frick |
77,507,263 | 3,368,201 | Create a static instance of the same class | <p>I'd like to create a static instance of a class. Assume I have the following data class:</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass
@dataclass(frozen=True)
class MyTag:
tag: str
</code></pre>
<p>(i.e. a class with a string member called tag).</p>
<p>Now I want to create a specific version of this tag (the <code>GLOBAL</code> value, with tag <code>'<<GLOBAL>>'</code> to be stored as a class member, and I want it to be a class member so that I can call <code>MyTag.GLOBAL</code>.</p>
<p>What I came up with is this code:</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass
@dataclass(frozen=True)
class MyTag:
tag: str
GLOBAL = None
'''The global value'''
MyTag.GLOBAL = MyTag(tag='<<GLOBAL>>')
</code></pre>
<p>Now, this seems a bit ugly to me, so I'm wondering whether there is a prettier way to do this.</p>
<p>I first went with this syntax:</p>
<pre class="lang-py prettyprint-override"><code>[...]
GLOBAL = MyTag(tag='<<GLOBAL>>')
'''The global value'''
</code></pre>
<p>But even with <code>from __future__ import annotations</code> at the beginning it complained because <code>MyTag</code> was not defined.</p>
<p>I'm using Python 3.11 at present, if the answer is influenced by the version</p>
| <python><python-3.11> | 2023-11-18 14:18:27 | 0 | 2,880 | frarugi87 |
77,507,255 | 22,466,650 | How to get the metadata of a file compressed in a gzip archive? | <p>I have a very basic request.</p>
<p>All I need is to retreive the modification time of <code>my_text.txt</code> compressed in <code>my_archive.gz</code>.</p>
<p><a href="https://i.sstatic.net/bbOen.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bbOen.png" alt="enter image description here" /></a></p>
<pre><code>from gzip import GzipFile
with GzipFile('my_archive.gz') as gzip_file:
print(gzip_file.getinfo('my_text.txt').date_time)
</code></pre>
<p>This code is giving me this error : <code>AttributeError: 'GzipFile' object has no attribute 'getinfo'</code></p>
<p>When I try <code>print(gzip_file.mtime)</code>, I get <code>None</code>.</p>
<p>I expect this output : <code>(2023, 11, 13, 10, 9, 42)</code></p>
<p>I'm so confused guys. Why Python can't retrieve this info while a tool like <code>7zip</code> can ?</p>
| <python><metadata><gzip> | 2023-11-18 14:15:36 | 1 | 1,085 | VERBOSE |
77,507,225 | 233,516 | Extracting feature embeddings from an image | <p>I'm trying to use TensorFlow.js to extract feature embeddings from images.</p>
<p>Elsewhere I'm using PyTorch and ResNet152 to extract feature embeddings to good effect.</p>
<p>The following is a sample of how I'm extracting those feature embeddings.</p>
<pre class="lang-py prettyprint-override"><code>import torch
import torchvision.models as models
from torchvision import transforms
from PIL import Image
# Load the model
resnet152_torch = models.resnet152(pretrained=True)
# Enumerate all of the layers of the model, except the last layer. This should leave
# the average pooling layer.
layers = list(resnet152_torch.children())[:-1]
resnet152 = torch.nn.Sequential(*(list(resnet152_torch.children())[:-1]))
# Set to evaluation model.
resnet152_torch.eval()
# Load and preprocess the image, it's already 224x224
image_path = "test.png"
img = Image.open(image_path).convert("RGB")
# Define the image transformation
preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# Apply the preprocessing steps to the image
img_tensor = preprocess(img).unsqueeze(0)
with torch.no_grad():
# Get the image features from the ResNet-152 model
img_features = resnet152(img_tensor)
print(img_features.squeeze())
</code></pre>
<p>Essentially, I'm using the pre-trained model and dropping the last layer to get my feature embeddings.</p>
<p>The result of the above script is:</p>
<pre><code>tensor([0.2098, 0.4687, 0.0914, ..., 0.0309, 0.0919, 0.0480])
</code></pre>
<p>So now, I want to do something similar with TensorFlow.js.</p>
<p>The first thing that I need is an instance of the ResNet152 model that I can use with TensorFlow.js. So I created the following Python script to export ResNet152 to the Keras format...</p>
<pre class="lang-py prettyprint-override"><code>from tensorflow.keras.applications import ResNet152
from tensorflow.keras.models import save_model
# Load the pre-trained ResNet-152 model without the top (fully connected) layer
resnet152 = ResNet152(weights='imagenet')
# Set the model to evaluation mode
resnet152.trainable = False
# Save the ResNet-152 model
save_model(resnet152, "resnet152.h5")
</code></pre>
<p>And then I exported the Keras (.h5) model to the TensorFlow.js format using the "tensorflowjs_converter" utility...</p>
<pre class="lang-bash prettyprint-override"><code>tensorflowjs_converter --input_format keras resnet152.h5 resnet152
</code></pre>
<p>Once I have the model in the appropriate format (I think), I switch over to Javascript.</p>
<pre class="lang-js prettyprint-override"><code>import * as tf from '@tensorflow/tfjs-node';
import fs from 'fs';
async function main() {
const model = await tf.loadLayersModel('file://resnet152/model.json');
const modelWithoutFinalLayer = tf.model({
inputs: model.input,
outputs: model.getLayer('avg_pool').output
});
// Load the image from disk
const image = fs.readFileSync('example_images/test.png'); // This is the exact same image file.
const imageTensor = tf.node.decodeImage(image, 3);
const preprocessedInput = tf.div(tf.sub(imageTensor, [123.68, 116.779, 103.939]), [58.393, 57.12, 57.375]);
const batchedInput = preprocessedInput.expandDims(0);
const embeddings = modelWithoutFinalLayer.predict(batchedInput).squeeze();
embeddings.print();
return;
}
await main();
</code></pre>
<p>The result of the above script is:</p>
<pre class="lang-bash prettyprint-override"><code>Tensor
[0, 0, 0, ..., 0, 0, 0.029606]
</code></pre>
<p>Looking at the first three values of the outputs between the two versions of the script, I expected there to be some variation but not THIS MUCH.</p>
<p>Where do I go from here? Is this much variation expected? Am I just doing this wrong?</p>
<p>Any help would be greatly appreciated.</p>
| <python><tensorflow><keras><pytorch><tensorflow.js> | 2023-11-18 14:06:54 | 0 | 1,347 | Tombatron |
77,507,167 | 1,390,993 | Random error "AttributeError: 'NoneType' object has no attribute 'find_all'" | <p>I have written the following code and it works most times. However, i get a random error</p>
<pre><code>error "AttributeError: 'NoneType' object has no attribute 'find_all'"
</code></pre>
<p>sometimes on consecutive runs.</p>
<p>It mostly indicates line 13 find_all for <code>products</code>.</p>
<p>What could be happening here and how to rectify it?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import requests
import bs4
import pandas as pd
url = 'https://www.hollandandbarrett.com/search/?query=prebiotic&page=1'
resp = requests.get(url)
html = bs4.BeautifulSoup(resp.content, 'html.parser')
row = {}
catalog = html.find('div', attrs = {'class':'ProductListContainer-module__list___yHwue','data-test':True}) #'list-Products'
if catalog is not None:
products = catalog.find_all('a', attrs = {'class':'ProductCard-module__link___FyAjR','data-test':True}) #'product-card'
data = []
for product in products:
if product is not None:
t = product.find('div', attrs =
{
'class':'ProductCard-module__title___dPGk8 Typography-module_base__h-bPx Typography-module_brandon__Es-DX Typography-module_bold__NNV5t',
'data-test':'product-card-title'
})
title = t.text.strip() if t else None
r = product.find('div', attrs =
{
'class':'RatingStars-module_star__3j5m8'
})
rating = r['title'].strip() if r else None
rr = product.find('div', attrs =
{
'class':'RatingStars-module_reviewCount__H8VBI Typography-module_base__h-bPx Typography-module_helvetica__-8F7V'
})
rating_review = rr.text.strip().replace('(','').replace(')','') if rr else None
#('product-card-price' or 'product-card-final-price') #'ProductCard-module__price___Sbmvg Typography-module_base__h-bPx Typography-module_helvetica__-8F7V Typography-module_bold__NNV5t'
p = product.find('div', attrs = {'class': 'ProductCard-module__priceBlock___5GV3W'}).findChild(attrs = {'data-test':True})
price = p.text.strip() if p else None
sp = product.find('div', attrs = {'class': 'ProductCard-module__priceBlock___5GV3W'}).findChild(attrs = {'data-test':'product-card-sale-price'})
sale_price = sp.text.strip() if sp else None
pu = product.find('div', attrs =
{
'class':'ProductCard-module__pricePerUnit___Lewj6 Typography-module_base__h-bPx Typography-module_helvetica__-8F7V',
'data-test':'price-per-unit'
})
price_per_unit = pu.text.strip() if pu else None
row = {
'title':title,
'rating':rating,
'rating_review':rating_review,
'price':price,
'sale_price':sale_price,
'price_per_unit':price_per_unit
}
data.append(row)
df = pd.DataFrame.from_dict(data, orient='columns')
# print(df)
df.to_csv('hollandandbarrett_products.csv',encoding='utf-8',index=True, header=True )
else:
print('Catalog not found!')</code></pre>
</div>
</div>
</p>
| <python><python-3.x><web-scraping><beautifulsoup> | 2023-11-18 13:50:53 | 1 | 1,158 | sifar |
77,506,997 | 15,222,211 | python sphinx autodoc exclude __init__ | <p>I have 2 classes.
Class1 needs to display all docstrings,
while Class2 needs to display only method docstrings.
In the following example, I am trying to disable Class2 without success,
docstrings of Class2 still displayed.
Please help me disable class and init docstrings in Class2.</p>
<p>conf.py</p>
<pre class="lang-py prettyprint-override"><code>autoclass_content = "both"
</code></pre>
<p>index.rst</p>
<pre><code>Title
=====
.. autoclass:: classes.Class1
:members:
.. autoclass:: classes.Class2
:members: method
:exclude-members: __init__, __weakref__
</code></pre>
<p>classes.py</p>
<pre class="lang-py prettyprint-override"><code>
class Class1:
"""Docstring1"""
def __init__(self):
"""Init1"""
def method(self):
"""Method1"""
class Class2:
"""Docstring2"""
def __init__(self):
"""Init2"""
def method(self):
"""Method2"""
</code></pre>
<p>expected result</p>
<pre><code>Title
class classes.Class1
Docstring1
Init1
method()
Method1
class classes.Class2
method()
Method2
</code></pre>
<p>actual result</p>
<pre><code>Title
class classes.Class1
Docstring1
Init1
method()
Method1
class classes.Class2
Docstring2
Init2
method()
Method2
</code></pre>
| <python><python-sphinx><autodoc> | 2023-11-18 13:02:56 | 0 | 814 | pyjedy |
77,506,884 | 590,335 | How is it possible to convert a polars dataframe to a huggingface dataset? | <p>Both formats are based on arrow, but I couldn't find a way to transform one to the other.</p>
<p>The best I could find is:</p>
<p>The dataset library has a <a href="https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.from_buffer" rel="nofollow noreferrer"><code>from_buffer</code></a> method that expects a <code>pyarrow.Buffer</code> object. Moreover, the polars library has a <a href="https://pola-rs.github.io/polars/py-polars/html/reference/dataframe/api/polars.DataFrame.to_arrow.html" rel="nofollow noreferrer"><code>to_arrow</code></a> method that returns a <code>pyarrow.Table</code> object</p>
| <python><python-polars><pyarrow><huggingface-datasets> | 2023-11-18 12:29:20 | 2 | 8,467 | Ophir Yoktan |
77,506,840 | 140,367 | How can I generalize this model_post_init in Pydantic? | <p>I have a human-editable YAML configuration where I'd like to allow fields that are either strings or lists:</p>
<pre class="lang-yaml prettyprint-override"><code>examples:
foo: red
bar: red, green
qaz:
- red
- green
- blue
</code></pre>
<p>This is intended to be deserialized as</p>
<pre class="lang-py prettyprint-override"><code>{
"examples": {
"foo": ["red"],
"bar": ["red", "green"],
"qaz": ["red", "green", "blue"]
}
}
</code></pre>
<p>I've implemented a function that takes a <code>list[str] | str</code> and performs this transformation and I'm using it like this:</p>
<pre class="lang-py prettyprint-override"><code>class SomeMode(BaseModel):
foo: str | list[str]
bar: str | list[str]
def model_post_init(self, __context):
self.foo = process_composite_list(self.foo, separator=",")
self.bar = process_composite_list(self.bar, separator=",")
return super().model_post_init(__context)
</code></pre>
<p>This works very well, but I'm finding that I want to introduce the same behavior in various other models. Humans who edit this YAML will expect this mechanism everywhere. Is there a way to annotate fields in such a way that this function is called automatically when data is being deserialized (in any model, without having to one-by-one add a model_post_init)? (serialization is not a concern, only deserialization).</p>
| <python><pydantic> | 2023-11-18 12:16:36 | 2 | 24,101 | Tamás Szelei |
77,506,789 | 843,458 | python fails to run due to a call of jupiter notebook in another file (not related) | <p>I simply want to run a .py file in a folder where a .ipynb file exists. It results (using visual studio code) in this error</p>
<pre><code>(venv) PS Z:\python> & 'z:\python\venv\Scripts\python.exe' 'c:\Users\matth\.vscode\extensions\ms-python.python-2023.20.0\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '55920' '--' 'Z:\python\OrganiseAndFindDubplicatePicture.py'
Traceback (most recent call last):
File "c:\Users\matth\.vscode\extensions\ms-python.python-2023.20.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 876, in get_abs_path_real_path_and_base_from_file
return NORM_PATHS_AND_BASE_CONTAINER[filename]
KeyError: 'vscode-notebook-cell:/z%3A/python/OrganisePictures.ipynb#W3sZmlsZQ%3D%3D'
During handling of the above exception, another exception occurred:
</code></pre>
<p>How can I solve this ?</p>
| <python><visual-studio-code> | 2023-11-18 11:58:16 | 1 | 3,516 | Matthias Pospiech |
77,506,782 | 3,225,420 | How to convert key value pairs of rcParams to dictionary | <p>I want to get <code>key:value</code> pairs of <code>rcParams</code> for further manipulation.</p>
<pre><code>from matplotlib import rcParams
x = rcParams
print(x)
</code></pre>
<p>Yeilds:</p>
<pre><code>_internal.classic_mode: False
agg.path.chunksize: 0
animation.bitrate: -1
animation.codec: h264
animation.convert_args: ['-layers', 'OptimizePlus']
animation.convert_path: convert
...
</code></pre>
<p>I tried this approach:</p>
<pre><code>for line in x:
print(line)
</code></pre>
<p>It only yielded the <code>keys</code> but not the <code>values</code>:</p>
<pre><code>_internal.classic_mode
agg.path.chunksize
animation.bitrate
animation.codec
animation.convert_args
animation.convert_path
...
</code></pre>
<p>Lastly I tried this:</p>
<pre><code>for line in x:
for key, value in line:
print(key, value)
</code></pre>
<p>And received the following error:</p>
<pre><code>ValueError: not enough values to unpack (expected 2, got 1)
</code></pre>
<p>What should I try next?</p>
| <python><matplotlib> | 2023-11-18 11:57:17 | 2 | 1,689 | Python_Learner |
77,506,714 | 1,046,474 | How does Psycopg2 handle sessions and transactions concurrency on high traffic apps? | <p>I've been going through <strong>psycopg2</strong> documentation to understand how it handles transactions and so on and so forth.</p>
<p>I got that a transaction is <strong>created on a connection level</strong>, regardless of the cursor you use, the <strong>session is visible to all</strong> of them.</p>
<blockquote>
<p><strong>Warning</strong> By default even a simple SELECT will start a transaction: in long-running programs, if no further action is taken, the session will remain “idle in transaction”, an undesirable condition for several reasons (locks are held by the session, tables bloat…). For long-lived scripts, either make sure to terminate a transaction as soon as possible or use an autocommit connection.</p>
</blockquote>
<p>So I was wondering how a <strong>high-traffic API</strong> would deal with this to avoid weird situations where multiple queries are committed or rolled back because a different API request was completed and as the session is shared ... everything falls inside the same transaction.</p>
<p><strong><a href="https://www.psycopg.org/docs/pool.html" rel="nofollow noreferrer">Connection pools</a></strong> seem to be the answer but still, the number of connections is limited so virtually you could encounter the same issue if the same connection from the pool is given to different API requests.</p>
<p>Is it a matter of having a pool big enough to reduce the risk of a connection being shared by 2 different processes or am I missing something on how this works?</p>
<p>Thanks in advance ^^ sorry for the long question.</p>
| <python><database><transactions><psycopg2> | 2023-11-18 11:35:12 | 1 | 572 | BrunoX |
77,506,563 | 5,790,653 | how to check two json and yaml files to compare | <p>This is the <code>yaml</code> file (the <code>type</code> field is both in Persian and English, and also <code>Type TypeB</code> is correct and is not a typo):</p>
<pre><code>-
dedicatedip: 1.1.1.1
status: Active
type: 'نوع اول'
-
dedicatedip: 2.2.2.2
status: Active
type: 'Type TypeB'
-
dedicatedip: 2.2.2.2
status: Active
type: 'نوع اول'
-
dedicatedip: 3.3.3.3
status: Suspended
type: 'Type TypeC'
-
dedicatedip: 3.3.3.3
status: Active
type: 'نوع اول'
-
</code></pre>
<p>This is the <code>json</code> file:</p>
<pre><code>{
"error": false,
"data": {
"licenses": [
{
"id": 167689,
"cycle": "monthly",
"type": "typeA",
"ip": "1.1.1.1",
"renewDate": "2023-12-22 09:10:00",
"status": "Active",
"hostname": "some.fqdn.co.com",
"autoRenew": true
},
{
"id": 167689,
"cycle": "monthly",
"type": "typeB",
"ip": "2.2.2.2",
"renewDate": "2023-12-22 09:10:00",
"status": "Suspended",
"hostname": "some.fqdn.co.com",
"autoRenew": true
},
{
"id": 167689,
"cycle": "monthly",
"type": "typeA",
"ip": "2.2.2.2",
"renewDate": "2023-12-22 09:10:00",
"status": "Active",
"hostname": "some.fqdn.co.com",
"autoRenew": true
},
{
"id": 167689,
"cycle": "monthly",
"type": "typeC",
"ip": "3.3.3.3",
"renewDate": "2023-12-22 09:10:00",
"status": "Active",
"hostname": "some.fqdn.co.com",
"autoRenew": true
},
{
"id": 167689,
"cycle": "monthly",
"type": "typeA",
"ip": "3.3.3.3",
"renewDate": "2023-12-22 09:10:00",
"status": "Active",
"hostname": "some.fqdn.co.com",
"autoRenew": true
}
]
}
}
</code></pre>
<p>I'm going to to this over iterating both files:</p>
<pre><code>check if the ip of json and yaml match, if it matches then check the type of both (case-insensitive), then if they both match, now if status don't match then print something.
Since one IP may have several license types, the `type` should be matched too.
</code></pre>
<p>The expected output:</p>
<pre><code>ip 2.2.2.2, license typeB "active" in "yaml" but "suspended" in "json".
ip 3.3.3.3, license typeA "suspended" in "yaml" but "active" in json.
</code></pre>
<p>I tried to write a code, but this is my attempt so far:</p>
<pre><code>import json
from ruamel.yaml import YAML
file_name = 'file.json'
with open(file_name) as file:
data = json.load(file)
json_names = []
for r in data:
for j in r['data']:
if j is not None and 'licenses' in j and j['licenses'] is not None and 'ip' in j['licenses']:
json_names.append({'licenses': j['licenses']['ip'] })
yaml = YAML()
with open('file.yaml') as file:
code = yaml.load(file)
yaml_names = []
for d in code:
yaml_names.append({'ip': d['dedicatedip']})
</code></pre>
<p>But I'm not sure what to do next for what I'm trying to reach.</p>
| <python> | 2023-11-18 10:49:15 | 1 | 4,175 | Saeed |
77,506,217 | 3,834,483 | 16-bit texture through PyOpenGL | <p>I am trying to create a 16-bit texture in PyOpenGL using below statement.</p>
<pre><code>img_data = cv2.imread("Texture.png",cv2.IMREAD_UNCHANGED)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16UI, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT, img_data)
</code></pre>
<p>But it throws invalid operation with traceback a sbelow:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\gurubhat\PycharmProjects\OpenGL\TextureSample.py", line 106, in <module>
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16UI, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT, img_data)
File "src\latebind.pyx", line 39, in OpenGL_accelerate.latebind.LateBind.__call__
File "src\wrapper.pyx", line 318, in OpenGL_accelerate.wrapper.Wrapper.__call__
File "src\wrapper.pyx", line 311, in OpenGL_accelerate.wrapper.Wrapper.__call__
File "C:\Users\gurubhat\PycharmProjects\VENV\venv\Lib\site-packages\OpenGL\platform\baseplatform.py", line 415, in __call__
return self( *args, **named )
^^^^^^^^^^^^^^^^^^^^^^
File "src\errorchecker.pyx", line 58, in OpenGL_accelerate.errorchecker._ErrorChecker.glCheckError
OpenGL.error.GLError: GLError(
err = 1282,
description = b'invalid operation',
baseOperation = glTexImage2D,
</code></pre>
<p>16-bit textures are not supported on Window? (or may be graphics card?)</p>
<p>Loading of 8-bit images like below works perfectly fine (I guess GL_RGB stores textures internlly in float32 format)</p>
<pre><code>img_data = cv2.imread("8bitimage.png",cv2.IMREAD_UNCHANGED)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data)
</code></pre>
| <python><opengl><pyopengl> | 2023-11-18 08:50:38 | 1 | 472 | bsguru |
77,506,060 | 386,861 | Date filtering in pandas | <p>I'm trying to filter some data based around datetime and particular years. Tried two approaches and neither works. What's wrong?</p>
<p>This is the data.</p>
<pre><code>surname forename initials age_text honours_awards date_of_death date_of_death2 rank regiment unitshipsquadron country servicenumberExport cemeterymemorial gravereference additionalinformation
0 ABBERLEY BERTRAM B NaN NaN 1916-11-18 NaN Private North Staffordshire Regiment 8th Bn. France '21850' THIEPVAL MEMORIAL Pier and Face 14 B and 14 C. NaN
1 ABBERLEY THOMAS FREDERICK T F NaN NaN 1917-09-20 NaN Serjeant North Staffordshire Regiment 8th Bn. Belgium '40791' TYNE COT MEMORIAL Panel 124 to 125 and 162 to 162A. NaN
2 ABBOTTS ALBERT EDWARD A E 20.0 NaN 1917-09-26 NaN Serjeant North Staffordshire Regiment 2nd/6th Bn. Belgium '240926' TYNE COT MEMORIAL Panel 124 to 125 and 162 to 162A. SON OF MARY JANE DICKEN (FORMERLY ABBOTTS), OF...
3 ABBOTTS ERNEST E 29.0 NaN 1916-04-20 NaN Private North Staffordshire Regiment 7th Bn. Iraq '16414' BASRA MEMORIAL Panel 34. SON OF MR. AND MRS. JAMES ABBOTTS, OF 21, ABBE...
4 ABBOTTS FREDERICK F 32.0 NaN 1915-10-13 NaN Private North Staffordshire Regiment
</code></pre>
<p>My code is:</p>
<pre><code>path = "CasualtySearch_31_10_2012_03_04.csv"
df = pd.read_csv(path)
#Convert date_of_death field to datetime
df['date_of_death'] = pd.to_datetime(df['date_of_death'])
#Crop out casualties outside WW1
#Approach 1
df = df[df['date_of_death'].dt.year.between(2014, 2018)]
#Approach 1
df = df[(df['date_of_death'].dt.year >= 2014) & (df['date_of_death'].dt.year <= 2018)]
df.describe()
</code></pre>
<p>But both return</p>
<pre><code> age_text date_of_death
count 0.0 0
mean NaN NaT
min NaN NaT
25% NaN NaT
50% NaN NaT
75% NaN NaT
max NaN NaT
std NaN NaN
</code></pre>
<p>Why is this when <code>df['date_of_death'].dt.year</code> returns a series of years and df['date_of_death'].dt.year.dtype returns "int32"?</p>
<p>(Full data can be found here: <a href="https://www.dropbox.com/scl/fi/p4zfen4c50dtw1egtdr5t/CasualtySearch_31_10_2012_03_04.csv?rlkey=yi67e73es4c3ginwl8tqvk51g&dl=0" rel="nofollow noreferrer">https://www.dropbox.com/scl/fi/p4zfen4c50dtw1egtdr5t/CasualtySearch_31_10_2012_03_04.csv?rlkey=yi67e73es4c3ginwl8tqvk51g&dl=0</a></p>
| <python><pandas><datetime> | 2023-11-18 07:48:11 | 3 | 7,882 | elksie5000 |
77,505,898 | 11,953,250 | Exception: InvalidRequestError: Resource not found | <p>I want to transcribe a audio file using openai whisper model. And I am able to do it locally. But when the same code I am trying to run azure functions by creating python api. I am getting this error <code> Exception: InvalidRequestError: Resource not found</code> I tried resolving it. but not able find why I am getting this. Anyone if has any idea then please help me.</p>
<p>Error: Executed 'Functions.audio_translation' (Failed, Id=c7ae69cf-5090-46c6-b2c4-169a70e1b3ec, Duration=30574ms)
[2023-11-18T06:14:13.621Z] System.Private.CoreLib: Exception while executing function: Functions.audio_translation. System.Private.CoreLib: Result: Failure
[2023-11-18T06:14:13.621Z] Exception: InvalidRequestError: Resource not found</p>
<p><strong>init</strong>.py</p>
<pre><code>import logging
import openai
import azure.functions as func
from shared_code.helper_translation import process_audio,read_audio_from_azure,read_local_files
import os
import os
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from pydub import AudioSegment
from pydub.utils import make_chunks
from moviepy.editor import AudioFileClip
# from openai import OpenAI
from azure.storage.blob import BlobClient
import requests
import openai
import logging
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_version = os.getenv("OPENAI_API_VERSION")
openai.api_base = os.getenv("OPENAI_API_BASE")
openai.api_type = os.getenv("OPENAI_API_TYPE")
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
if req.method != "POST":
return func.HttpResponse("Only POST requests are allowed.", status_code=405)
elif req.method=="POST":
#input_json = req.get_json()
response_status = {}
status_code_resp =200
data = read_audio_from_azure()
logging.info(data)
return func.HttpResponse("Request processed sucessfully", status_code=405)
</code></pre>
<p>helper_translation.py</p>
<pre><code>import os
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from pydub import AudioSegment
from pydub.utils import make_chunks
from moviepy.editor import AudioFileClip
# from openai import OpenAI
from azure.storage.blob import BlobClient
import requests
import openai
import logging
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_version = os.getenv("OPENAI_API_VERSION")
openai.api_base = os.getenv("OPENAI_API_BASE")
openai.api_type = os.getenv("OPENAI_API_TYPE")
output_folder = "audio_chunk"
def convert_to_mp3(audio_file_path):
mp3_file_path = os.path.join(output_folder, os.path.splitext(os.path.basename(audio_file_path))[0] + ".mp3")
if audio_file_path.lower().endswith(".mp4"):
# Convert MP4 to MP3
file_to_convert = AudioFileClip(audio_file_path)
file_to_convert.write_audiofile(mp3_file_path)
file_to_convert.close()
elif audio_file_path.lower().endswith(".m4a"):
# Convert M4A to MP3
track = AudioSegment.from_file(audio_file_path, format='m4a')
file_handle = track.export(mp3_file_path, format='mp3')
else:
raise ValueError("Unsupported audio file format for conversion. Please provide an MP4 or M4A file.")
return mp3_file_path
def audio_chunk(audio_file_path):
chunk_names = []
my_audio = AudioSegment.from_file(audio_file_path)
chunks_length_ms = 600000
chunks = make_chunks(my_audio, chunks_length_ms)
for i, chunk in enumerate(chunks):
chunk_name = "{0}_{1}".format(i, os.path.basename(audio_file_path))
logging.info(chunk_name)
if(os.path.exists(output_folder)):
file_path = os.path.join(output_folder, chunk_name)
else:
os.mkdir(output_folder)
file_path = os.path.join(output_folder, chunk_name)
chunk_names.append(file_path)
chunk.export(file_path, format="mp3")
return chunk_names
def whisper_transcription(file):
# client = OpenAI()
defaults = {
"engine": "whisper",
}
options = defaults.copy()
logging.info(options)
audio_file = open(file, "rb")
transcript = openai.Audio.transcribe(
model='whisper',
file=audio_file,
# **options
)
return transcript
def process_audio(audio_file_path):
starttime = datetime.now()
if audio_file_path.lower().endswith(".mp3"):
# No need to convert, directly process the MP3 file
audio_file_path = audio_file_path
elif audio_file_path.lower().endswith((".m4a", ".mp4")):
# Convert M4A or MP4 file to MP3
audio_file_path = convert_to_mp3(audio_file_path)
else:
raise ValueError("Unsupported video/audio file format. Please provide an MP3, M4A, or MP4 file.")
chunk_names = audio_chunk(audio_file_path)
with ThreadPoolExecutor() as executor:
futures = [executor.submit(whisper_transcription,chunk) for chunk in chunk_names]
transcript_file_path = os.path.join(output_folder, "transcript.txt")
with open(transcript_file_path, "w+") as transcript_file:
for future in futures:
transcript = future.result()
transcript_file.write(transcript + ".")
file_data = open(transcript_file_path,"r")
end_t = datetime.now() - starttime
logging.info("Total Process Time")
logging.info(end_t)
return file_data
def read_audio_from_azure():
blob = BlobClient.from_connection_string(conn_str="", container_name="outputfiles", blob_name="GMT20231107-075636_Recording.m4a")
downloaded_file_path = "downloaded_audio.mp3"
with open(downloaded_file_path, "wb") as audio_file:
audio_file.write(blob.download_blob().readall())
logging.info("File downloaded calling proces audio now!")
data = process_audio(downloaded_file_path)
return data
</code></pre>
| <python><azure><azure-functions><openai-api><openai-whisper> | 2023-11-18 06:27:06 | 1 | 546 | Nitin Saini |
77,505,812 | 3,487,441 | Dynamically add methods to a python class | <p>I have to create a decent number of classes with attributes that all follow the same pattern. I want to create a succinct way to do this with the goal of using a script to lay out all the classes so I can avoid repetitive work.</p>
<pre><code>add_get_for(class_type, property):
class_type[property] = lambda self: self._attributes[property]
class A:
def __init__(self, input_object):
self._attributes = process(input_object)
add_get_for(A, 'attrib1')
add_get_for(A, 'attrib2')
</code></pre>
<p>The <code>add_get_for</code> method is failing because of item assignment on the class. I can't figure out a way to assign the lambda function without knowing the name of the method in advance which is pointless for my goal.</p>
| <python><python-3.x> | 2023-11-18 05:42:15 | 1 | 1,361 | gph |
77,505,772 | 10,200,497 | Finding the largest groups with conditions after using groupby | <p>This is my dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{
'a': ['a', 'a', 'a', 'c', 'b', 'a', 'a', 'b', 'c'],
'b': [20, 20, 20,-70, 70, -10, -10, -1, -1],
}
)
</code></pre>
<p>And this is the output that I want. I want to create a dataframe with two rows:</p>
<pre><code> direction length sum
0 long 3 60
1 short 2 -20
</code></pre>
<p>I want to get the largest streak of positive (long) and negative(short) numbers in <code>b</code>. And then get the <code>length</code> and <code>sum</code> of <code>b</code> values in that streak and create a new dataframe. Note that if for example the largest streak is two and there are more than one streak with that size, I want the streak that its sum of <code>b</code> is more that the rest.</p>
<p>In my <code>df</code>, the largest long streak is the first three values. And the largest short streak is two. Since there are more than one streak with that size, I want the one that its <code>sum</code> is more. So I want rows 5 and 6.</p>
<p>This is what I have tried but I don't know how to follow up:</p>
<pre><code>df['streak'] = df['b'].ne(df['b'].shift()).cumsum()
df['size'] = df.groupby('streak')['b'].transform('size')
a b streak size
0 a 20 1 3
1 a 20 1 3
2 a 20 1 3
3 c -70 2 1
4 b 70 3 1
5 a -10 4 2
6 a -10 4 2
7 b -1 5 2
8 c -1 5 2
</code></pre>
| <python><pandas> | 2023-11-18 05:18:05 | 2 | 2,679 | AmirX |
77,505,611 | 16,808,528 | Matching the criteria and return the result | <p>I have a jason file like this:</p>
<pre><code>{
"Rank": 1259,
"Title": "Ischemic Nerve Block to Improve Hand Function in Stroke Patients",
"Status": "Completed",
"Study Results": "No Results Available",
"Conditions": "Cerebrovascular Accident",
"Interventions": "Procedure: Transient deafferentation",
"Locations": "National Institute of Neurological Disorders and Stroke (NINDS), Bethesda, Maryland, United States",
"URL": "https://ClinicalTrials.gov/show/NCT00056706"
},
{
"Rank": 1260,
"Title": "Transcranial Direct Current Stimulation for Post-stroke Motor Recovery",
"Status": "Recruiting",
"Study Results": "No Results Available",
"Conditions": "Stroke, Ischemic|Motor Activity|Upper Extremity Paralysis",
"Interventions": "Device: Sham|Device: Low dose tDCS|Device: High dose tDCS|Behavioral: mCIMT",
"Locations": "University of Alabama, Birmingham, Alabama, United States|University of California Los Angeles, Los Angeles, California, United States|MedStar National Rehabilitation Hospital, Washington, District of Columbia, United States|Emory University, Atlanta, Georgia, United States|University of Kentucky, Lexington, Kentucky, United States|Barnes Jewish Hospital, Saint Louis, Missouri, United States|Burke Rehabilitation Institute, White Plains, New York, United States|University of Cincinnati, Cincinnati, Ohio, United States|Moss Rehabilitation Research Institute, Elkins Park, Pennsylvania, United States|Medical University of South Carolina, Charleston, South Carolina, United States|Texas Medical Center, Houston, Texas, United States",
"URL": "https://ClinicalTrials.gov/show/NCT03826030"
},
{
"Rank": 1261,
"Title": "Transient Ischemic Attack (TIA) Triage and Evaluation of Stroke Risk",
"Status": "Completed",
"Study Results": "No Results Available",
"Conditions": "Cerebrovascular Accident",
"Interventions": "",
"Locations": "UC Davis Medical Center, Davis, California, United States|Stanford University School of Medicine, Stanford, California, United States|Michigan State University, Grand Rapids, Michigan, United States",
"URL": "https://ClinicalTrials.gov/show/NCT01423201"
},
{
"Rank": 1282,
"Title": "Atrial Fibrillation as a Cause of Stroke and Intracranial Hemorrhage Study (The FibStroke Study)",
"Status": "Unknown status",
"Study Results": "No Results Available",
"Conditions": "Stroke|Transient Ischemic Attacks|Intracranial Hemorrhage|Atrial Fibrillation",
"Interventions": "",
"Locations": "Keski-Suomi Central Hospital, Jyväskylä, Finland|Kuopio University Hospital, Kuopio, Finland|Satakunta Central Hospital, Pori, Finland|Turku University Hospital, Turku, Finland",
"URL": "https://ClinicalTrials.gov/show/NCT02146040"
},
{
"Rank": 1287,
"Title": "Magnetic Resonance Imaging to Investigate Silent Strokes During Neck and Skull Angioplasty",
"Status": "Completed",
"Study Results": "No Results Available",
"Conditions": "Brain Ischemia",
"Interventions": "",
"Locations": "National Institute of Neurological Disorders and Stroke (NINDS), Bethesda, Maryland, United States",
"URL": "https://ClinicalTrials.gov/show/NCT00015717"
}
</code></pre>
<p>The task is that "Find which clinical trials are being conducted at NINDS Bethesda, Maryland, United States".</p>
<p>So, I first import this jason as data called clinical_trials_data</p>
<pre><code>import json
import pandas as pd
# Load dataset
with open("./data/IschemicStroke_Clinical_Trials.json") as file:
clinical_trials_data = json.load(file)
</code></pre>
<p>Second, because the some Location contains multiple locations and use delimiter "|" to separate them, so I use code to retrieve the each location and store in location_info:</p>
<pre><code>target_location = "National Institute of Neurological Disorders and Stroke (NINDS) Bethesda, Maryland, United States"
trials_with_location = pd.DataFrame(clinical_trials_data)[pd.DataFrame(clinical_trials_data)["Locations"].notnull()]
location_info = trials_with_location["Locations"].str.split("|")
</code></pre>
<p>from there, I do not write the rest code to achieve the conditional or filter like if target_location in location_info, then print Title which is the trial's name.</p>
<p>i tried this code:</p>
<pre><code># Check if target_location is in location_info
if any(target_location in locations for locations in location_info):
# If true, print the titles of trials conducted at the target location
for title in clinical_trials_data["Title"]:
print(title)
else:
print("No trials conducted at the target location.")
</code></pre>
<p>But it does not return any record even the location is in the location_info.</p>
<p>Can someone help to point how to do that task?</p>
<p>Thanks~!</p>
| <python> | 2023-11-18 03:39:12 | 1 | 477 | Rstudyer |
77,505,480 | 7,077,532 | Dataframe: Using "Name" Column as Segmentation, Get all dates between Startdate and Enddate columns While Excluding Weekend Dates | <p>Let's say I have the starting input table below.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>_leavestartdate</th>
<th>_leaveenddate</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jerry Rice</td>
<td>2023-12-26</td>
<td>2023-12-26</td>
</tr>
<tr>
<td>Pablo Picasso</td>
<td>2023-08-15</td>
<td>2023-08-21</td>
</tr>
<tr>
<td>Ray Ramon</td>
<td>2023-03-16</td>
<td>2023-03-17</td>
</tr>
</tbody>
</table>
</div>
<p>The Python code to create it is:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'name':["Jerry Rice","Pablo Picasso","Ray Ramon"],'_leavestartdate':["2023-12-26","2023-08-15","2023-03-16"],'_leaveenddate':["2023-12-26","2023-08-21","2023-03-17"]})
</code></pre>
<p>First, I want to get all dates between the _leavestartdate and _leaveenddate <strong>split based on Name column</strong>. The list of dates would populate under new column "Date". I also want to exclude <strong>any weekend dates</strong> in the newly reformatted table.</p>
<p>So my desired output table is shown below. Note that it only shows weekday dates and excludes the 2 dates (8/19/2023 and 8/20/2023) from Pablo Picasso that are weekend dates.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>_leavestartdate</th>
<th>_leaveenddate</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jerry Rice</td>
<td>2023-12-26</td>
<td>2023-12-26</td>
<td>2023-12-26</td>
</tr>
<tr>
<td>Pablo Picasso</td>
<td>2023-08-15</td>
<td>2023-08-15</td>
<td>2023-08-21</td>
</tr>
<tr>
<td>Pablo Picasso</td>
<td>2023-08-16</td>
<td>2023-08-15</td>
<td>2023-08-21</td>
</tr>
<tr>
<td>Pablo Picasso</td>
<td>2023-08-17</td>
<td>2023-08-15</td>
<td>2023-08-21</td>
</tr>
<tr>
<td>Pablo Picasso</td>
<td>2023-08-18</td>
<td>2023-08-15</td>
<td>2023-08-21</td>
</tr>
<tr>
<td>Pablo Picasso</td>
<td>2023-08-21</td>
<td>2023-08-15</td>
<td>2023-08-21</td>
</tr>
<tr>
<td>Ray Ramon</td>
<td>2023-03-16</td>
<td>2023-03-16</td>
<td>2023-03-17</td>
</tr>
<tr>
<td>Ray Ramon</td>
<td>2023-03-17</td>
<td>2023-03-16</td>
<td>2023-03-17</td>
</tr>
</tbody>
</table>
</div>
<p>I looked at previous solutions in StackOverflow and tried the following code:</p>
<pre><code>date = pd.DataFrame(pd.date_range(start=df.min()._leavestartdate,
end=df.max()._leaveenddate), columns=['Date'])
df_final = pd.merge(left=date, right=df, left_on='Date', right_on='_leavestartdate',
how='outer').fillna(method='ffill')
</code></pre>
<p>But the solution produces the following wrong table because it's not accounting for the "Name" column:</p>
<p><a href="https://i.sstatic.net/WVYty.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WVYty.png" alt="enter image description here" /></a></p>
<p>How can I fix the code to get my desired output table?</p>
| <python><pandas><dataframe><date><group-by> | 2023-11-18 02:18:57 | 1 | 5,244 | PineNuts0 |
77,505,378 | 1,245,262 | Why are histograms incorrectly displayed when the distribution is tightly clustered? | <p>I'm trying to display some data in a histogram, but when the data is too tightly clustered, I get either an empty graph, or one I believe to be inaccurate.</p>
<p>Consider the following code:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
# Generate data
nums = np.random.rand(1000)+1000
# Make Histogram
plt.hist(nums, bins=1000, alpha=0.6, color='blue')
plt.xlim([900,1100])
plt.yscale('linear')
plt.grid(True)
plt.show()
</code></pre>
<p>This give the following graph:</p>
<p><a href="https://i.sstatic.net/cNqCO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cNqCO.png" alt="Plot 1" /></a></p>
<p>However, if I change the xlim values to:</p>
<pre><code>plt.xlim([990,1010])
</code></pre>
<p>I get:</p>
<p><a href="https://i.sstatic.net/zsNh0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zsNh0.png" alt="Plot 2" /></a></p>
<p>If I change it, yet again, to</p>
<pre><code>plt.xlim([999,1001])
</code></pre>
<p>I get</p>
<p><a href="https://i.sstatic.net/qGKdH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qGKdH.png" alt="Plot 3" /></a></p>
<p>With each bin covering a smaller range of numbers, I would've expected the peaks of the bins to decrease, rather than increase. Is there something I'm not understanding here, or is this a problem with matplotlib? (Note: This seems very similar to <a href="https://stackoverflow.com/questions/69357913/empty-histogram-in-matplotlib-data-in-small-interval">Empty histogram in matplotlib - data in small interval</a>, but I think I've laid out the problem more explicitly and noticed an additional problem even when the resulting plots are not blank (i.e. highest value of a bin was greater for the narrower bins of my 3rd plot than it was for the second)</p>
| <python><matplotlib><histogram><dpi><antialiasing> | 2023-11-18 01:34:33 | 2 | 7,555 | user1245262 |
77,505,367 | 219,153 | How can I derive axis index from mouse click event? | <p>This Python 3.11 script displays two graphs (axes):</p>
<pre><code>import numpy as np, matplotlib.pyplot as plt
def onclick(event):
print(event.inaxes)
fig, axs = plt.subplots(ncols=2, nrows=1, figsize=(3.5, 2.5), layout="constrained")
axs[0].plot(np.random.rand(10))
axs[1].plot(np.random.rand(10))
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
</code></pre>
<p>Clicking first on the left graph, then on the right one, produces:</p>
<pre><code>Axes(0.102541,0.111557;0.385554x0.871775)
Axes(0.602541,0.111557;0.385554x0.871775)
</code></pre>
<p>I see the first of <code>Axes</code> properties changing depending on the graph I clicked on: <code>0.102541</code> for the left one and <code>0.602541</code> for the right one. What is this property's name? Is there a simple way to derive an index of <code>axs</code>, which was clicked on from the <code>event</code>?</p>
| <python><matplotlib><onclick> | 2023-11-18 01:29:47 | 3 | 8,585 | Paul Jurczak |
77,505,351 | 1,492,613 | how to save/load pandas dataframe that contain non-ordered dictonary as field without knowing possible key name and value type to/from parquet? | <p>In our application, we need to append segments of dataframe to parquet storage.
However the following code will fail at the load time, due to unmatched type</p>
<pre><code>import pyarrow as pa
import pyarrow.parquet as pq
import pandas as pd
df_test1 = pd.DataFrame({'a': [1, 2], 'b': [{'k1': 0, 'k2':1}, {'k3': 'ok'}]})
df_test2 = pd.DataFrame({'a': [1, None], 'b': [{'k1': None}, {'k3': None}]})
pq_dir = "/tmp/test.pq"
for _df in [df_test1, df_test2]:
pa_data = pa.Table.from_pandas(_df)
display(pa_data)
pq.write_to_dataset(pa_data,root_path=pq_dir)
pd.read_parquet(pq_dir)
</code></pre>
<p>The reason is the df_test1 will be convert to a table:</p>
<pre><code>pyarrow.Table
a: double
b: struct<k1: int64, k2: int64, k3: string>
child 0, k1: int64
child 1, k2: int64
child 2, k3: string
</code></pre>
<p>the df_test2 will be onvert to another kind of schema:</p>
<pre><code>pyarrow.Table
a: double
b: struct<k1: null, k3: null>
child 0, k1: null
child 1, k3: null
</code></pre>
<p>one would suggest to make our own schema to match all b value, however, this is impossible, we do not have much constrain on that except the key must be string. the value can be string, int, float, list, etc.</p>
<p>I wonder, how can we deal with this kind of problem?</p>
<p>one solution is:</p>
<pre><code>pd.concat(d.to_table().to_pandas() for d in pa.dataset.dataset(pq_dir).get_fragments())
</code></pre>
<p>But if I do this I cannot use feature like read from row N to row M, I have to read in the entire dataset, which is unlikely to happen for very big ones.</p>
<p>another way is to dump the dict to json, however, this wastes lots of memory, since the json is not very efficient.</p>
<p>fastparquet can do this easily</p>
<pre><code>import fastparquet
df_test1 = pd.DataFrame({'a': [1., 2], 'b': [{'k1': 0, 'k2':1}, {'k3': 'ok'}]})
df_test2 = pd.DataFrame({'a': [1., None], 'b': [{'k1': None}, {'k3': None}]})
pq_dir = "/tmp/test1.pq"
for _i, _df in enumerate([df_test1, df_test2]):
fastparquet.write(pq_dir, _df, file_scheme="hive", append=_i>0)
fastparquet.ParquetFile(pq_dir).to_pandas()
</code></pre>
<p>But their code quality still looks too young, sigh.
I looked into the detail:
pyarrow actually save the data into 4 columns: a, b.k1, b.k2, b.k3. that is why it cannot handle the dictionary data very well.
In other hand fastparquet did a nasty trick in behind.
It automatically convert the dict object to a plain text json:</p>
<pre><code><pyarrow._parquet.ParquetSchema object at 0x7f6f80d9fd00>
required group field_id=-1 schema {
optional double field_id=-1 a;
optional binary field_id=-1 b (JSON);
}
</code></pre>
<p>We can see the string like this:</p>
<pre><code>pqt = pq.read_table('/tmp/test1.pq')
pqt[1][1].as_py().decode()
# '{"k3":"ok"}'
</code></pre>
<p>So though it sees fastpqrquet can handle this, but it actually handle it in an very inefficient way.</p>
<p>If I were in their position, I probably will at least try to use jsonb or bson.</p>
<p>IN summary, It expect the data have fixed schema (relationship data model), though the parquet in general actually support shcema evolution.
More weird thing is in <a href="https://arrow.apache.org/docs/r/reference/concat_tables.html" rel="nofollow noreferrer">R api</a> there is <code>unify_schema=True</code> in concat_table, in pyarrow this option did not correctly exposed.
So it seems the pyarrow is somehow incomplete.</p>
<p>It cannot handle dict in cell or array in cell very well just like most sql-like database.</p>
<p>so maybe any one data require a bit non-relationship data model, pyarrow is not a goo choice here?</p>
| <python><pandas><parquet><pyarrow> | 2023-11-18 01:22:57 | 0 | 8,402 | Wang |
77,505,227 | 3,171,007 | Returning a Python dataframe (or other) into a Powershell datatable (or other) | <p>I have a lot of automation in Powershell but am trying to branch off into Python. I have written some Python scripts and are executing them from PS, but have hit a wall where I am trying to pass arguments from PS into py, and return values from py back to PS.</p>
<p>My PS:</p>
<pre><code>$qry = "SELECT COUNT(*)
FROM source
WHERE the_DATE = DATEADD(DAY ,-1, CURRENT_DATE)"
$results = python C:\User\Python\Small_Data_Retr.py $qry
</code></pre>
<p>The py runs but then returns nothing. The rest of my (functioning) scripts write to a SQL table so I'm in foreign lands on this. My py wraps up this way:</p>
<pre><code>def main(query):
snf_conn = read_snowflake()
try:
pd.read_sql(query, snf_conn)
except Exception as e:
print(f"Some error you don't know how to handle {e}")
if __name__ == "__main__":
main(sys.argv[1])
</code></pre>
<p>The <code>read_snowflake</code> function contains the configuration for the connection, this all works. I just can't figure out how to dump the <code>pd.read_sql(query, snf_conn)</code> back out to PS. I've tried <code>return pd.read_sql(query, snf_conn)</code> and various other things.</p>
| <python><pandas><dataframe><powershell> | 2023-11-18 00:25:02 | 2 | 1,744 | n8. |
77,505,030 | 12,954,896 | OpenAI API error: "You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0" | <p>I am currently working on a chatbot, and as I am using Windows 11 it does not let me migrate to newer OpenAI library or downgrade it. Could I replace the <code>ChatCompletion</code> function with something else to work on my version?</p>
<p>This is the code:</p>
<pre><code>import openai
openai.api_key = "private"
def chat_gpt(prompt):
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message['content'].strip()
if __name__ == "__main__":
while True:
user_input = input("You: ")
if user_input.lower() in ["quit", "exit", "bye"]:
break
response = chat_gpt(user_input)
print("Bot:", response)
</code></pre>
<p>And this is the full error:</p>
<blockquote>
<p>...
You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at <a href="https://github.com/openai/openai-python" rel="noreferrer">https://github.com/openai/openai-python</a> for the API.</p>
<p>You can run <code>openai migrate</code> to automatically upgrade your codebase to use the 1.0.0 interface.</p>
<p>Alternatively, you can pin your installation to the old version, e.g. <pip install openai==0.28></p>
<p>A detailed migration guide is available here: <a href="https://github.com/openai/openai-python/discussions/742" rel="noreferrer">https://github.com/openai/openai-python/discussions/742</a></p>
</blockquote>
<p>I tried both upgrading and downgrading through pip.</p>
| <python><pip><artificial-intelligence><openai-api><chatgpt-api> | 2023-11-17 23:09:08 | 2 | 353 | Petrutz |
77,504,855 | 11,890,443 | Website detects selenium despite trying a lot of measures | <p>I have a toolset for (ebay) kleinanzeigen.de to post and delete old adds. Lastweek everything worked fine. As I wanted to use the script today it didn't work anymore.</p>
<p>Even without any automated action they block you.</p>
<p>try this code. It just opens a window and kleinanzeigen.de</p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
import time
Driverpath="C:\your path the driver/chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(Driverpath,options=options)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source":
"const newProto = navigator.__proto__;"
"delete newProto.webdriver;"
"navigator.__proto__ = newProto;"
})
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => null
})
"""
})
driver.maximize_window()
driver.get("https://www.kleinanzeigen.de")
time.sleep(1)
driver.execute_script('window.key = \"ASSH\";"')
</code></pre>
<p>Try then to login with your account. You have to use a slider and after that you get a message that you have been blocked. Opening a normal chrome, not controlled by selenium is no problem, you can login there. So it is not a problem with IP-Adress.</p>
<p>Also tried with selenium stealth as suggested in this thread <a href="https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver">Can a website detect when you are using Selenium with chromedriver?</a>. Didn't help neither. As you can see I also used other workarounds recommended in this thread.</p>
<p>Any ideas what they do and how to prevent it? It is really annoying creating Ads by hand. I mean they provide no API thats so oldschool, so you are more or less forced using selenium.</p>
<p>I also used <code>perl -pi -e 's/cdc_/ash_/g' chromedriver.exe</code> and using this driver with code above, but that also doesn't help.</p>
| <python><selenium-webdriver> | 2023-11-17 22:06:28 | 0 | 326 | Hannes |
77,504,794 | 1,543,042 | python importlib.import_module into current scope | <p>I'm following in a long line of people struggling with <code>importlib</code> (<a href="https://stackoverflow.com/questions/301134/how-can-i-import-a-module-dynamically-given-its-name-as-string">1</a>, <a href="https://stackoverflow.com/questions/67631/how-can-i-import-a-module-dynamically-given-the-full-path">2</a>) (I have also <a href="https://docs.python.org/3/library/importlib.html#importlib.import_module" rel="nofollow noreferrer">read the docs</a>).</p>
<p>I want to import all the elements in a list into the current scope as if I had done <code>import my_package1; import my_package2' ...</code>. The problem is that <code>importlib.import_module(module)</code> returns the module rather than adding it to the scope so it can be used. I am trying to expose submodules which is why I don't want them in a variable</p>
| <python><python-import> | 2023-11-17 21:47:28 | 1 | 3,432 | user1543042 |
77,504,781 | 11,329,736 | Read 4 lines at a time, in parallel, from text file | <p>I have these two data sets:</p>
<p>data1.txt:</p>
<pre><code>@SRR14820084.1 A00794:192:HJNGKDRXX:1:1101:1208:1047/1
CCCCCCTCTCACGGGCTTCTCGGACACAAACGGGAAGGCACACAGCCAGACGGAGCACCGGAGGCACACCAGGGAATGGGAAGCGCCACCACCAGCTCAGAAGCA
+
FFFFFFFFFFFFFFFF::F:FFF:F,F:,FFFFFF,FFFFFFFFFFF,FFFFFFFFFFFFFFFFF:FFFF:FFFF,FFFFF,FFFFF,FF,FFFFFFFFFF,FF:
@SRR14820084.2 A00794:192:HJNGKDRXX:1:1101:1371:1047/1
ATCCATTTATGGTTCTGACAAAACACACTCACCATAGATACTCATGATAGATTTGTTTTTAATTATTAAAAAACTGAAATACAACCTAGGTAGTGGTAGCATACA
+
FFFFFFFFFFFF:FFFFFFFFFFFFFFFF::FFFFF:FFFFF:FFFFFFFF:FFFFFFFFFF,FFFFFFFFFFFFF:FFFFFFFFF:,FFFFFFFFFF,FF:FF:
</code></pre>
<p>data2.txt</p>
<pre><code>@SRR14820084.1 A00794:192:HJNGKDRXX:1:1101:1208:1047/2
GGTTTGTCTCCTAGGTGCCTGCTTCTGAGCTGGTGGTGGCGCTTCCCATTCCCTGGTGTGCCTCCGGTGCTCCGTCTGGCTGTGTGCCTTCCCGTTTGTGTCCGA
+
F:FFFFFFFFF,FFFFFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFF:FFFFFFFFFFFFF,FFFFFFFFFF
@SRR14820084.2 A00794:192:HJNGKDRXX:1:1101:1371:1047/2
CAAGATTTCTCTGTGTAGTCTTGTCTGTCCTGGAACTAGCTATGTAGACCAGGCTAGTCTTGAACTCACAGAAGTCCACCTGCTTCTGCCTCCTGAGTGCTAGGA
+
F::FF:FFFFFFFFFFFFF:FFFFFFFFFFFFFF,FFFFFFFFFFFFFFF,FFFF,FFFFFFFFFFF:F::FFFFFFFFFFFFFF:FFFFFFFFFFFFFFF:FFF
</code></pre>
<p>The goal of my script is to do something on the first 4 lines, then the 5th to 8th lines, etc. on these two files.</p>
<p>I do this with this function:</p>
<pre><code>def process_read_pairs(input_file_1, input_file_2):
total_read_pairs = 0
out_file1 = "dataset1_out.txt"
out_file2 = "dataset2_out.txt"
with open(input_file_1, 'r') as file1, open(input_file_2, 'r') as file2, open(out_file1, 'w') as output_file1, open(out_file2, 'w') as output_file2:
while True:
### Read four lines at a time of each read pair ###
# Read first line of each read pair (i.e. name)
name1 = file1.readline().strip()
name2 = file2.readline().strip()
# Stop if end of file is reached
if not name1 or not name2:
break
# Read second line of each read pair (i.e. sequence)
seq1 = file1.readline().strip()
seq2 = file2.readline().strip()
# Read third line of each read pair (i.e. +)
plus1 = file1.readline().strip()
plus2 = file2.readline().strip()
# Read fourth line of each read pair (i.e. quality)
quality1 = file1.readline().strip()
quality2 = file2.readline().strip()
# Here would be some code that would manipulate the lines that would be read
...
...
# Write read pair to output files (each on a separate line)
# read1
output_file1.write(f"{name1}\n"
output_file1.write(f"{read1}\n"
output_file1.write(f"{plus1}\n"
output_file1.write(f"{quality1}\n"
#read2
output_file2.write(f"{read2}\n"
output_file2.write(f"{read2}\n"
output_file2.write(f"{plus2}\n"
output_file2.write(f"{quality2}\n"
</code></pre>
<p>This works well. The only problem is that it is quite slow (the actual data files can be up to 40GB).</p>
<p>I want to parallelise the <code>while</code> loop. One way would be to read all the lines at once using <code>readlines()</code> and assign different sections of all the lines to different parallel processes, but this would require a lot of memory.</p>
<p>Is there a way to parallelise the current <code>while</code> loop without reading all the data into memory?</p>
<p>The important thing to keep in mind is that for both files the same lines would have to be read (the data is paired), but in the output it would not matter if for example the first 4 lines come last and lines 5 to 8 first (as long as it is the same for both data sets).</p>
| <python><parallel-processing> | 2023-11-17 21:42:58 | 0 | 1,095 | justinian482 |
77,504,754 | 10,520,077 | Editor suggestions for function arguments with **kwargs in Python | <p>I'm currently working on a Python project and using an editor to write my code. I have a function that takes **kwargs, and I was wondering how I can enable suggestions for the keyword arguments in my editor. I'm looking for a more efficient way to explore and use these arguments during development.</p>
<p>Is there a specific configuration or setting I need to enable in my editor to get autocompletion suggestions for the function arguments with **kwargs? I'm using Visual Studio Code/Spyder.</p>
<pre><code>def function(**kwargs):
for key, value in kwargs.items():
if key == "key1":
print(value)
if key == "key2":
print(value)
print("Done")
</code></pre>
<p>I want the editor to display both key options ("key1" and "key2") when typing <em>function(</em>.</p>
| <python><visual-studio-code><ide><spyder> | 2023-11-17 21:35:49 | 1 | 911 | DomDunk |
77,504,715 | 1,167,890 | Downloading an attachment from Trello cards | <p>I am trying to download all the attachments from my cards on a Trello board using <code>py-trello</code>.</p>
<p>Here is the sample code (private information removed):</p>
<pre><code>from trello import TrelloClient
import requests
personal_token = ''
account_token = ''
client = TrelloClient(api_key=personal_token, api_secret=account_token)
board = client.get_board('')
cards = board.all_cards()
for card in cards:
for attachment in card.get_attachments():
response = requests.get(attachment.url)
if response.status_code == 200:
with open(attachment.name, 'wb') as file:
file.write(response.content)
else:
print(response.status_code, response.text)
break
break
</code></pre>
<p>The issue is that I get <code>401 Unauthorised</code> error when I try to get the URL using <code>requests</code>. I've tried adding basic auth like so:</p>
<pre><code>basic = HTTPBasicAuth(personal_token, account_token)
</code></pre>
<p>Same issue. I've also tried adding it to the URL like so:</p>
<pre><code>url = f'{url}?key={personal_token}&token={account_token}'
</code></pre>
<p>But it also fails. I had a look at the <code>py-trello</code> code but I wasn't able to easily see if it has a download attachment function.</p>
| <python><python-3.x><python-requests><trello> | 2023-11-17 21:23:40 | 1 | 9,347 | Simon O'Doherty |
77,504,680 | 4,403,891 | regex to find string between repeating markers | <p>I have a string that looks like this:</p>
<pre><code>**** SOURCE#24 ****
[1] Source Location [Local/Remote] : Remote
Remote Host Name : PNQ
User Name : foo
[2] Source directory : HDPGWRF
[3] Directory poll interval : 30
[4] File name format : ACR_FILEFORMAT
[5] Delete files from source : y
**** SOURCE#25 ****
[1] Source Location [Local/Remote] : Remote
Remote Host Name : PNR
User Name : foo
[2] Source directory : HDPGWRF
[3] Directory poll interval : 30
[4] File name format : ACR_FILEFORMAT
[5] Delete files from source : y
**** SOURCE#26 ****
etc.....
</code></pre>
<p>I want a capture group that captures everything after the '[1]' up to the ends of the line that starts with [5], based on the Remote Host Name (eg PNR or PNQ). So only lines [1] through [5] around the selected name.</p>
<p>I've been trying lookahead and lookbehind and just can't figure this out. It looks like lookbehind is greedy, so if I search for the PNR section, it won't stop at the first [1] but grabs everything up to the first [1] in the PNQ section.</p>
<p>This is the closest I've got to making it work, but it only works if I search for the PNQ section:</p>
<pre><code>re.search('SOURCE#.*?\[1\](.*?PNQ.*?.*?HDPGWRF.*?)\*', buf, flags=re.DOTALL).group(1)
</code></pre>
<p>This after combing through stackoverflow all afternoon :(</p>
| <python><regex><multiple-occurrence> | 2023-11-17 21:15:49 | 4 | 381 | musca999 |
77,504,633 | 7,176,676 | Order pandas dataframe on contiguous points | <p>Suppose I have a dataframe in which each row has a <em>row_id</em> as well as the boundary coordinates (left and right) of a line. The dataframe consists of lines that can be ordered such that each line connects to another one, i.e., the lines are contiguous. The way to easily see this is when the right boundary of the line at row i is equal to the left boundary of the line at row (i+1).</p>
<p>My goal is to find a way to achieve such an ordering based on an arbitrary initial ordering of such lines.</p>
<p>A simplistic example is given below. Consider the following pandas dataframe</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'row_id':[1,2,3,4],
'left_coord': [(0,0), (0,1), (4,4), (1,1)],
'right_coord':[(0,1),(1,1),(5,7),(4,4)]
})
</code></pre>
<p>being</p>
<pre><code> row_id left_coord right_coord
0 1 (0, 0) (0, 1)
1 2 (0, 1) (1, 1)
2 3 (4, 4) (5, 7)
3 4 (1, 1) (4, 4)
</code></pre>
<p>For the example above, the expected result is:</p>
<pre><code> row_id left_coord right_coord
0 1 (0, 0) (0, 1)
1 2 (0, 1) (1, 1)
3 4 (1, 1) (4, 4)
2 3 (4, 4) (5, 7)
</code></pre>
<p>Note that in this particular case, it would suffice to order by the column <code>left_coord</code>, but in general it would not be correct.</p>
| <python><pandas><dataframe> | 2023-11-17 21:06:09 | 2 | 395 | flow_me_over |
77,504,626 | 2,568,521 | scrapy.core.scraper ERROR: Error downloading -- OSError: Errno 24 Too many open files | <p>I inherited a scrapy application which crawls through several 1000 pages on a domain and writes the final results out to a json file. The author had been running this on a mac and had encountered a limitation with OS where it complained the limit on open files had been reached. He addressed this by overriding the upper limit at the os level:</p>
<blockquote>
<p>$ ulimit -n 2048</p>
</blockquote>
<p>I am running this on windows, which apparently has no upper limit, but I am still encounter the same issue. After scrapy runs for a bit it, it throws a bunch of errors like this and then gives up:</p>
<pre><code>2023-11-17 14:30:14 [scrapy.core.scraper] ERROR: Error downloading <GET https://some_page>
Traceback (most recent call last):
File ".venv\lib\site-packages\twisted\internet\defer.py", line 1445, in _inlineCallbacks
result = current_context.run(g.send, result)
File ".venv\lib\site-packages\scrapy\core\downloader\middleware.py", line 43, in process_request
File ".venv\lib\site-packages\scrapy\downloadermiddlewares\httpcache.py", line 77, in process_request
File ".venv\lib\site-packages\scrapy\extensions\httpcache.py", line 302, in retrieve_response
File ".venv\lib\site-packages\scrapy\extensions\httpcache.py", line 354, in _read_meta
OSError: [Errno 24] Too many open files: 'path to file\\pickled_meta'
</code></pre>
<p>I've read this is a python issue and tried applying this fix, which was no help:</p>
<pre><code>import win32file
win32file._setmaxstdio(2048)
</code></pre>
<p>At the moment, the cache shows that 63,744 files have been created. So, I don't know if this is an OS problem, a python problem, some bug in scrapy or some misuse of it. I can post some of the code here, but I don't know what would be relevant - the spider, the item pipeline, the parse method or the settings file. Any ideas to try to address this would be appreciated. Please let me know what other details I can provide.</p>
<p>Here are relevant project settings:</p>
<pre><code>CONCURRENT_REQUESTS = 16
DOWNLOAD_DELAY = 1
ITEM_PIPELINES = {
'pipelines.JsonWriterPipeline': 301
}
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 5
AUTOTHROTTLE_MAX_DELAY = 60
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
AUTOTHROTTLE_DEBUG = False
HTTPCACHE_ENABLED = True
HTTPCACHE_EXPIRATION_SECS = 0
def is_running_in_container():
"""Determines if we are running in a container"""
cgroup_path = '/proc/1/cgroup'
if not os.path.isfile(cgroup_path):
return False
with open(cgroup_path, 'r') as cgroup_file:
for line in cgroup_file:
parts = line.rstrip().split(":")
if len(parts) < 3:
return False
if parts[2] != "/":
return True
return False
def get_httpcache_dir():
"""Returns the appropriate httpcache directory to use
depending on envrionment"""
if is_running_in_container():
parent_dir = "/scrapyd/scrapyd/data"
if os.path.isdir(parent_dir):
return f'{parent_dir}/httpcache'
return os.path.join(os.path.expanduser('~'), "scrapy_httpcache")
# Return a relative dir
return 'httpcache'
HTTPCACHE_DIR = get_httpcache_dir()
HTTPCACHE_IGNORE_HTTP_CODES = []
# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.DbmCacheStorage'
</code></pre>
<p>This is output from the log after the last run:</p>
<pre><code> 023-11-18 12:50:51 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 4205141,
'downloader/request_count': 9859,
'downloader/request_method_count/GET': 9859,
'downloader/response_bytes': 418300317,
'downloader/response_count': 8188,
'downloader/response_status_count/200': 8188,
'dupefilter/filtered': 701,
'elapsed_time_seconds': 12209.725667,
'finish_reason': 'shutdown',
'finish_time': datetime.datetime(2023, 11, 18, 17, 50, 51, 249912, tzinfo=datetime.timezone.utc),
'httpcache/firsthand': 9859,
'httpcache/miss': 9859,
'httpcache/store': 9859,
'item_scraped_count': 7763,
'log_count/DEBUG': 3,
'log_count/ERROR': 1671,
'log_count/INFO': 228,
'log_count/WARNING': 1,
'request_depth_max': 1,
'response_received_count': 8188,
'scheduler/dequeued': 9859,
'scheduler/dequeued/memory': 9859,
'scheduler/enqueued': 9859,
'scheduler/enqueued/memory': 9859,
'start_time': datetime.datetime(2023, 11, 18, 14, 27, 21, 524245, tzinfo=datetime.timezone.utc)}
</code></pre>
<p>Adding the pipeline code here:</p>
<pre><code>class JsonWriterPipeline:
"""Use to save items to JSON files"""
def __init__(self):
self.file = None
self.logging: Final = logging.getLogger('jsonwriter')
self.fileName: Final = 'items.json'
# counter of number of scrapes read in so far, used to provide some helpful debug later
self.recordsScraped = 0
def open_spider(self, _):
"""Callback called when a spider is opened"""
self.file = open(self.fileName, 'w')
def close_spider(self, _):
"""Callback called when a spider is closed"""
self.file.close()
if self.recordsScraped > 0:
self.logging.info(f'Wrote {self.recordsScraped} records to file: {self.fileName}')
def process_item(self, item, _):
"""Use to save an item yielded from a spider in a JSON file"""
line = json.dumps(ItemAdapter(item).asdict()) + "\n"
self.file.write(line)
self.recordsScraped += 1
return item
</code></pre>
| <python><windows><scrapy> | 2023-11-17 21:04:07 | 1 | 4,487 | Mark Wojciechowicz |
77,504,574 | 345,427 | How to import a generated python module | <p>I am generating python modules (using antlr).
e.g. foo_pb2.py, bar_pb2.py</p>
<p>If I generate them into my python source directory; then, importing those modules works as expected.
However, I do not want to contaminate my source directory with generated files; so, I generate the files into a <code>gen_module</code> directory.
The problem is how to import those modules?</p>
<p>I have used the approach of modifying the <code>sys.path</code> and inserting the <code>gen_module</code> path.
I do this in the <code>__init__.py</code> of the module which uses the generated code.</p>
<p>Is there a more pythonic approach?</p>
<ul>
<li>Put the generated modules is a package?</li>
<li>Using <code>import_module</code>? I have tried it but modules imported from within the imported modules are not found.</li>
</ul>
| <python><import><code-generation> | 2023-11-17 20:52:53 | 0 | 1,869 | phreed |
77,504,424 | 19,694,624 | Get active threads in a discord channel (Discord.py / Pycord) | <p>I am having an issue fetching active threads on a discord channel. There is not much info about it, or maybe I just couldn't find it. So maybe it's not even possible idk</p>
<p>My code:</p>
<pre><code>import discord
from tools.config import TOKEN
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.slash_command(name="chat", description="some desc")
async def chat(ctx, msg):
channel = bot.get_channel(CHANNEL_ID)
user_name = ctx.author
await ctx.response.defer(ephemeral=True)
thread = await channel.create_thread(name=f"Thread was created {user_name}", type=None)
await thread.send("Message in a thread")
await ctx.respond(f'Some message with tagging after creating a thread. {user_name.mention}')
bot.run(TOKEN)
</code></pre>
<p>What I am trying to implement is this:
user executes slash command, then the bot creates a thread where all the communications with the user are done in, but before creating a thread bot needs to verify that the user is not in any active threads in the current channel. To do that, I need to fetch active threads in the current channel.</p>
| <python><python-3.x><discord><discord.py><pycord> | 2023-11-17 20:18:23 | 1 | 303 | syrok |
77,504,345 | 9,386,819 | I'm trying to generate synthetic data using Python. The data should be bivariate and have a specified correlation. Why doesn't my code work? | <p>Here is what I've tried. I've been playing with this for a very long time and cannot figure out what I'm doing wrong. Can anyone help identify what I'm not seeing?</p>
<p>I'm trying to create 1,000 samples, each containing two variables, where one variable is correlated to the other with r=0.85 (or whatever correlation I specify). I don't really understand the cholesky decomposition, so I'm assuming that the problem lies somewhere in that step.</p>
<pre><code># Create random normal bivariate data with r=0.85
rng = np.random.default_rng(0)
correlation = 0.85
corr_matrix = np.array([[1, correlation], [correlation, 1]])
L = np.linalg.cholesky(corr_matrix)
n = 1000
random_data = rng.normal(size=(n, 2))
synthetic_data = np.dot(random_data, L)
# Check the correlation
r = stats.pearsonr(synthetic_data.T[0], synthetic_data.T[1])[0]
# r computes to 0.646.
</code></pre>
| <python><numpy><linear-algebra><correlation> | 2023-11-17 20:03:05 | 1 | 414 | NaiveBae |
77,504,217 | 446,347 | Using NewRelic monitor of Django Channels/asyncio/asgi | <p>NewRelic doesn't have a documented example of how to monitor a Django Channels application. Mostly concern about monitoring the eventloop, using the methods provided <a href="https://docs.newrelic.com/docs/apm/agents/python-agent/python-agent-api/asgiapplication-python-agent-api/" rel="nofollow noreferrer">here</a> don't seem to work as ProtocolRouter in Channels is the "application" and seems layers deep since we are running Gunicorn with Uvicorn workers.</p>
<p>Love to see someone who has implemented this.</p>
| <python><django><django-channels><newrelic><asgi> | 2023-11-17 19:36:43 | 0 | 634 | LiteWait |
77,504,063 | 4,398,966 | Difference between colon and exclamation point | <p>In Python 3 is there a difference between <code>{0:s}</code> and <code>{0!s}</code> when used in a print statement? For example:</p>
<pre><code>print("Hello {0:s} and {0!s}".format('foo'))
</code></pre>
<p>prints out the same thing twice.</p>
<p>From the documentation it says:</p>
<blockquote>
<p>The <em>field_name</em> is optionally followed by a conversion field, which is preceded by an exclamation point <code>'!'</code>, and a <em>format_spec</em>, which is preceded by a colon <code>':'</code>. These specify a non-default format for the replacement value.</p>
</blockquote>
<p>Does that mean <code>!</code> is like casting?</p>
| <python> | 2023-11-17 19:02:53 | 0 | 15,782 | DCR |
77,503,953 | 1,094,836 | Why annual granularity of annotation? | <p>I import a simple data frame from Excel. Seven dates, 12/2021 - 12/2027, each date a year apart, each associated with a number. I want to add an annotation (a vertical line separating the actual historical value from forecasted numbers), and text making this clear.</p>
<pre><code>df.plot()
#annotation
plt.axvline(pd.to_datetime('2023-6-01'))
plt.text(pd.to_datetime('2022-06-01'), 20**6, 'actual')
plt.text(pd.to_datetime('2023-06-01'), 20**6, 'forecast')
plt.show()
</code></pre>
<p>The system rounds my placements to the nearest year-end. So with the code above, all three placements are set six months earlier than I want them to be.</p>
<p><a href="https://i.sstatic.net/BNbbk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BNbbk.png" alt="frustrating graph" /></a></p>
<p>How can I get the line and text to appear in the specified months?</p>
| <python><matplotlib> | 2023-11-17 18:39:57 | 1 | 487 | Michael Stern |
77,503,938 | 11,154,841 | Setting a new value for a NumPy array item saves a much smaller value. How can I just set the value? | <p>Code:</p>
<pre><code>import numpy as np
data = '12345\n54321\n13542\n12354\n53124'
n = data.find('\n')
mat = np.array(list(data.replace('\n','')), dtype=np.uint8).reshape(-1, n)
mat
</code></pre>
<p>Out:</p>
<pre><code>array([[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[1, 3, 5, 4, 2],
[1, 2, 3, 5, 4],
[5, 3, 1, 2, 4]], dtype=uint8)
</code></pre>
<p>Code:</p>
<pre><code>mat2 = np.full_like(mat, 0)
mat2[0,0] = 9999999
mat2[0,1] = 8888
mat2[0,2] = 77777
</code></pre>
<p>Out:</p>
<pre><code>array([[127, 184, 209, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]], dtype=uint8)
</code></pre>
<p>Thus, Python does not set the needed NumPy array item value, only a random and tiny value gets saved instead for a wide range of number sizes. How can I fix this?</p>
| <python><arrays><python-3.x><numpy> | 2023-11-17 18:37:17 | 1 | 9,916 | questionto42 |
77,503,667 | 5,592,430 | Get asyncio results not empty | <p>I have some problem in using of the asyncio for Web Scraping task. I'd like to collect the information about realtors on cian site - I use asyncio because on this site the pagination is used. I encountered two problems . When I use fully async approach I cannot receive requested information - I receive message about used VPN:</p>
<pre><code>async def async_get_all_realtors(session, url):
async with session.get(url) as response:
html = await response.text()
bsobj = soup(html, 'html.parser')
agent_names = []
for i in bsobj.findAll('div', {'class': '_9400a595a7--name--ipaRv'}):
agent_names.append(i.span.text.strip())
return agent_names
</code></pre>
<p>I have made small changes like:</p>
<pre><code>async def async_get_all_realtors(url):
html = urlopen(url)
bsobj = soup(html, 'html.parser')
agent_names = []
for i in bsobj.findAll('div', {'class': '_9400a595a7--name--ipaRv'}):
agent_names.append(i.span.text.strip())
return agent_names
</code></pre>
<p>After this fix I can receive requested information.</p>
<p>The second problem is the following - I receive empty result although dump print of the all_agent_names variable shows that all are Okey. Below is full code:</p>
<pre><code>from urllib.request import urlopen
import aiohttp
from bs4 import BeautifulSoup as soup
import asyncio
import pandas as pd
url = "https://www.cian.ru/realtors/?dealType=sale&offerType%5B0%5D=flat&regionId=1"
def get_num_pages(url):
html = urlopen(f"{url}&page=1")
bsobj = soup(html.read(), 'html.parser')
return int(bsobj.findAll('span', {'class': '_9400a595a7--content--sGuO7'})[-1].text)
async def async_get_all_realtors(url):
html = urlopen(url)
bsobj = soup(html, 'html.parser')
agent_names = []
for i in bsobj.findAll('div', {'class': '_9400a595a7--name--ipaRv'}):
agent_names.append(i.span.text.strip())
return agent_names
async def main(url, num_pages):
tasks = []
for page_num in range(1, num_pages + 1):
page_url = f"{url}&page={page_num}"
task = asyncio.create_task(async_get_all_realtors(page_url))
tasks.append(task)
results = await asyncio.gather(*tasks)
# Here all are Ok this variable contains full information
all_agent_names = [name for result in results for name in result]
print(all_agent_names)
return all_agent_names
num_of_pages = get_num_pages(url)
result = await main(url, num_of_pages) # Empty result, why?
</code></pre>
<p>Please help where is my mistake?</p>
<p>P.S. I use JupiterNotebook to run code...</p>
| <python><web-scraping><python-asyncio> | 2023-11-17 17:46:52 | 1 | 981 | Roman Kazmin |
77,503,593 | 4,000,113 | python tabulate tablefmt=rounded_outline prints 3 spaces instead of 1 space between columns | <p>How can i avoid extra spaces in the tabulate grid?</p>
<pre><code>rows = [
["A1", "B2"],
["C3", "D4"],
["E5", "E6"],
]
print(tabulate(rows, headers="firstrow", tablefmt='rounded_outline'))
</code></pre>
<p>gives me 2 extra spaces in every cell</p>
<pre><code>╭──────┬──────╮
│ A1 │ B2 │
├──────┼──────┤
│ C3 │ D4 │
│ E5 │ E6 │
╰──────┴──────╯
</code></pre>
<p>how can i solve it to get</p>
<pre><code>╭────┬────╮
│ A1 │ B2 │
├────┼────┤
│ C3 │ D4 │
│ E5 │ E6 │
╰────┴────╯
</code></pre>
| <python><tabulate> | 2023-11-17 17:32:28 | 2 | 423 | gsxr1300 |
77,503,516 | 16,623,197 | How do I make a plotly graph where I can change the coloring parameter interactively? | <p>In plotly express I can create scatter plots using data.frames easily:</p>
<pre><code>import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", log_x=True, color='continent')
</code></pre>
<p>Is there a way to add a dropdown menu into the plot so I can choose also the other parameters as a color? Doing so should not reset the zoom.</p>
<p>I could not figure out how to do that except by using a dash app, but I still have some problems there: The hover does not change and it is not possible to switch between categorical and numerical coloring. Let me give you what I have achieved so far:</p>
<pre><code>import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import numpy as np
df = px.data.gapminder()
df["moreData1"] = np.random.normal(size = len(df))
labels = df.columns[df.dtypes=="float64"]
#labels = df.columns
options = [{'label': v, 'value': v} for v in labels]
app = dash.Dash(__name__)
fig = px.scatter(df,
x="gdpPercap",
y="lifeExp",
log_x=True,
color=labels[1],
#color='continent',
render_mode='webgl'
)
# somehow this line prevents from resetting the zoom. Do not really understand why.
fig.update_layout(uirevision='some_unique_value')
# Define the layout
app.layout = html.Div([
dcc.Dropdown(
id='color-dropdown',
options=options,
value=labels[-1]
),
dcc.Graph(
id='scatter-plot',
figure=fig
)
])
# Define the callback to update the scatter plot based on the selected color
@app.callback(
Output('scatter-plot', 'figure'),
[Input('color-dropdown', 'value')]
)
def update_scatter_plot(selected_color):
fig.update_traces(
marker_color=df[selected_color]
)
return fig
# Run the app
if __name__ == '__main__':
app.run(debug=True, port=8052)
</code></pre>
<p>It works somehow, but I would like to have two improvements: I want to be able to display categoric values too (does not work as you can see by setting <code>labels = df.columns</code> instead of only numeric columns.</p>
<p>And more importantly I want to show the coloring information in hover.</p>
<p>There is no need in using a dash app, I think I would be even happier about a pure plotly-plot.</p>
| <python><plotly> | 2023-11-17 17:17:54 | 1 | 896 | Noskario |
77,503,434 | 6,865,225 | Why this multi-threaded code behaves in a safer way when I add thread.join()? | <pre class="lang-py prettyprint-override"><code>import threading
# Shared variable
shared_variable = 0
NUM_THREADS = 999
NUM_INCREMENT = 1_000_000
# Function to increment the shared variable
def increment():
global shared_variable
for _ in range(NUM_INCREMENT):
shared_variable += 1
# Creating multiple threads to increment the shared variable concurrently
threads = []
for _ in range(NUM_THREADS):
thread = threading.Thread(target=increment)
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
# Display the value of the shared variable after concurrent increments
print(
f"The value of the shared variable is: {shared_variable}, expected : {NUM_THREADS * NUM_INCREMENT}"
)
</code></pre>
<p>This code always print the expected number when I join the thread. But if I comment this code then some increment fails (which is the result I actually expected !).</p>
<pre class="lang-py prettyprint-override"><code># for thread in threads:
# thread.join()
</code></pre>
<p>Why this code behaves in a thread safe way when I add join?</p>
| <python><thread-safety> | 2023-11-17 17:03:30 | 2 | 779 | Anis Smail |
77,503,327 | 21,864,938 | Why do I get "This field is required" error from Django imageField? | <p>I have problems with Django's image field. It says that the image field is empty even though I have selected an image
This is my models.py:</p>
<pre><code>from django.db import models
class Post(models.Model):
picture = models.ImageField(upload_to="uploads")
</code></pre>
<p>This is my forms.py:</p>
<pre><code>from django import forms
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = '__all__'
</code></pre>
<p>This is my views.py:</p>
<pre><code>from django.shortcuts import render, redirect
from .forms import PostForm
def postsite(request):
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
form.save()
else:
print(form.errors)
return redirect('post')
context = {'form':form}
return render(request, 'post.html', context)
</code></pre>
<p>And this is my post.html:</p>
<pre><code> <form action="" method="POST" enctyppe="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit Post">
</form>
</code></pre>
<p>After I have selected an image for the imageField and submitted the form, the output of this code <code>print(form.errors)</code> is:</p>
<pre><code><ul class="errorlist"><li>picture<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
</code></pre>
<p>Because of other discussions about this error I tried to add this to my form:</p>
<pre><code> enctyppe="multipart/form-data"
</code></pre>
<p>However, the error still persisted.</p>
| <python><django><django-models><django-forms> | 2023-11-17 16:46:20 | 1 | 478 | Lukinator |
77,503,315 | 5,036,928 | Near-neighbor Point Cloud Downsampling/Decimation | <p>I'm looking for a way to downsample a point cloud based on the proximity of points to their neighbors (from what I can tell, this is synonymous with "decimation"). While I am currently using PyVista as my main library, I'm not seeing any class/methods that seem to achieve what I am looking for since the <code>decimate</code> method that does belong to the <a href="https://docs.pyvista.org/version/stable/api/core/_autosummary/pyvista.PolyDataFilters.decimate.html#pyvista.PolyDataFilters.decimate" rel="nofollow noreferrer">PolyDataFilter</a> class is only for points that have been meshed (and I want to decimate my point cloud before meshing).</p>
<p>Without developing my own method from scratch, how can I achieve this decimation?</p>
| <python><nearest-neighbor><downsampling><pyvista><decimation> | 2023-11-17 16:44:29 | 1 | 1,195 | Sterling Butters |
77,503,313 | 586,424 | aiohttp: infinite streaming with long wait periods | <p>I am trying to connect to a REST API which will stream data infinitely when events are happening. In the meantime no data is sent through the API.</p>
<p>I have the following code:</p>
<pre><code>async with self.client_session.get(
self._url(path),
headers=self._headers,
timeout=aiohttp.ClientTimeout(total=0, connect=0, sock_connect=0, sock_read=0),
) as response:
async for message in response.content:
# do something
</code></pre>
<p>Every ~10 minutes I receive the error <code>Unexpected exception: ClientPayloadError('Response payload is not completed')</code> from <code>aiohttp</code>.</p>
<p>Is there a possibility to achieve that? Yes, I have another while around that which restarts the whole process currently; however, doing this every ~10 minutes is not too efficient.</p>
| <python><asynchronous><python-asyncio><aiohttp> | 2023-11-17 16:44:24 | 0 | 675 | Daniel Mühlbachler-P. |
77,503,261 | 5,765,649 | Changing examples value in langchain chain | <p>Assuming we have langchain chain <code>my_chain</code> created using <code>my_schema</code> via:</p>
<pre><code>from langchain.chat_models import ChatOpenAI
from kor.extraction import create_extraction_chain
from kor.nodes import Object, Text, Number
from langchain.chat.models import ChatOpenAI
from langchain.llms import OpenAI
schema = Object(
id="bank_statement_info",
description="bank statement information about a given person.",
attributes=[
Text(
id="first_name",
description="The first name of the person",
examples=[("John Smith", "John")],
),
Text(
id="last_name",
description="The last name of the person",
examples=[("John Smith", "Smith")],
),
Text(
id="account_number",
description="Account Number of the person in Bank statement.",
examples=[("Account Number: 122-233-566-800", "122-233-566-800")],
),
Text(
id="address",
description="address of the person in Bank statement.",
),
Text(
id="opening_balance",
description="opening blance of the person in Bank statement.",
examples=[("opening Balance: 245,800.00","245,800.00")]
),
Text(
id="closing_balance",
description="closing blance of the person in Bank statement.",
examples=[("Closing Balance: 591,800.00","591,800.00")]
),
],
examples=[
(
"""ya 231 Valley Farms Street
FIRST Santa Monica, CA 90403 STATEMENT OF ACCOUNT
CITIZENS __firstcitizensbank@domain.com
BANK
Account Number: 122-233-566-800
Statement Date: 11/22/2019 Page 1 of 1
Period Covered: 05/22/2019 to 11/22/2019
Eric Nam Opening Balance: 175,800.00
240 st, apt 15, hill road, Total Credit Amount: 510,000.00
Baverly Hills, LA, 90209 Total Debit Amount: 94,000.00
Closing Balance: 591,800.00
Branch - Baverly Hills Account Type: Saving Account""",
[
{"first_name": "John", "last_name": "Smith", "account_number": '122-233-566-800',"address":"240 st, apt 15, hill road,Baverly Hills, LA, 90209",
"Closing Balance": "458,589.00","opening Balance": "800.00"},
{"first_name": "Jane", "last_name": "Doe", "age": '923-533-256-205',"address":"850 st, apt 82, hill road,Baverly Hills, New york, 82044",
"Closing Balance": "1000.00","opening Balance": "125,987.00"},
],
)
],
many=True,
)
llm = ChatOpenAI(temperature=0.0, openai_api_key='', open_api_base='', model_kwargs={'engine': 'openai_gpt_4'}
my_chain = create_extraction_chain(llm, my_schema, encoder_or_encoder_class='json')
</code></pre>
<p>I want to have access to <code>examples</code> of <code>my_chain</code> after creating it. I tried to take access by accesing <code>my_chain.prompt</code> but afterwards could not get to examples. In particular, I would like to be able to dynamically change the <code>examples</code> of <code>my_chain</code>. Is that possible?</p>
| <python><nlp><langchain><large-language-model><chatgpt-api> | 2023-11-17 16:36:32 | 1 | 827 | singa1994 |
77,503,260 | 3,385,948 | Can we stop the Dash "POST /dash/_dash-update-component HTTP/1.1" log messages? | <p>Has anyone figured out how to stop the following Dash log messages? They clutter up my logs, and on a busy website, make it almost impossible to see actual, useful log messages when errors occur.</p>
<pre><code>[17/Nov/2023:16:28:10 +0000] "POST /dash/_dash-update-component HTTP/1.1" 204 0 "https://example.com/" "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1"
</code></pre>
<p>I've tried the suggestion <a href="https://community.plotly.com/t/prevent-post-dash-update-component-http-1-1-messages/11132/2?u=seanrez" rel="nofollow noreferrer">here</a> by the creator of Dash. He says to try the following, but it doesn't do anything for me:</p>
<pre class="lang-py prettyprint-override"><code>import logging
logging.getLogger('werkzeug').setLevel(logging.ERROR)
</code></pre>
<p>Here's a fuller example from <a href="https://community.plotly.com/t/prevent-post-dash-update-component-http-1-1-messages/11132/3?u=seanrez" rel="nofollow noreferrer">this link</a> if you want to try it:</p>
<pre class="lang-py prettyprint-override"><code>import logging
from dash import Dash
from flask import Flask
logging.getLogger('werkzeug').setLevel(logging.ERROR)
URL_BASE_PATHNAME = '/'+'example/'
server = Flask(__name__)
app = Dash(name=__name__, server=server,
url_base_pathname=URL_BASE_PATHNAME)
if __name__ == "__main__":
app.run()
</code></pre>
<p>Here's more like what mine looks like in production with Docker Swarm:</p>
<pre><code>import logging
import os
import time
from datetime import datetime, timezone
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import List
from dotenv import load_dotenv
from flask import Flask, current_app, redirect, render_template, request, url_for
from flask.globals import _request_ctx_stack
from flask.logging import default_handler
from flask_assets import Environment
from flask_bcrypt import Bcrypt
from flask_bootstrap import Bootstrap
from flask_caching import Cache
from flask_flatpages import FlatPages
from flask_htmlmin import HTMLMIN as HTMLMin
from flask_login import LoginManager, current_user
from flask_mail import Mail
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from werkzeug.exceptions import NotFound
from werkzeug.middleware.proxy_fix import ProxyFix
from app import databases
from app.assets import compile_assets
# Dictionary pointing to classes of configs
from app.config import (
INSTANCE_PATH,
PROJECT_FOLDER,
ROLE_ID_CUSTOMER_ADMIN,
ROLE_ID_IJACK_ADMIN,
ROLE_ID_IJACK_SERVICE,
STATIC_FOLDER,
TEMPLATE_FOLDER,
app_config,
)
from app.dash_setup import register_dashapps
from app.utils import error_send_email_w_details
# Ensure the .env file doesn't contain copies of the variables in the .flaskenv file, or it'll get confusing...
load_dotenv(PROJECT_FOLDER, override=True)
# Set log level globally so other modules can import it
log_level = None
db = SQLAlchemy()
login_manager = LoginManager()
bcrypt = Bcrypt()
cache = Cache()
mail = Mail()
pages = FlatPages()
assets_env = Environment()
# noqa: C901
def create_app(config_name=None):
"""Factory function that creates the Flask app"""
app = Flask(
__name__,
instance_path=INSTANCE_PATH,
static_folder=STATIC_FOLDER,
template_folder=TEMPLATE_FOLDER,
static_url_path="/static",
)
# Import the config class from config.py (defaults to 'development' if not in the .env file)
if config_name is None:
config_name = os.getenv("FLASK_CONFIG", "development")
config_obj = app_config[config_name]
app.config.from_object(config_obj)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
# Set up logging
global log_level
log_level = app.config.get("LOG_LEVEL", logging.INFO)
app.logger.setLevel(log_level)
# The default handler is a StreamHandler that writes to sys.stderr at DEBUG level.
default_handler.setLevel(log_level)
# Change default log format
log_format = (
"[%(asctime)s] %(levelname)s: %(name)s: %(module)s: %(funcName)s: %(message)s"
)
default_handler.setFormatter(logging.Formatter(log_format))
# Stop the useless 'dash-component-update' logging? (Unfortunately this doesn't seem to work...)
# https://community.plotly.com/t/prevent-post-dash-update-component-http-1-1-messages/11132
# https://community.plotly.com/t/suppressing-component-update-output-message-in-the-terminal/7613
logging.getLogger("werkzeug").setLevel(logging.ERROR)
# NOTE != means running the Flask application through Gunicorn in my workflow.
if __name__ != "__main__" and not app.debug and app.env != "development":
# Add a FileHandler to the Flask logger
Path("logs").mkdir(exist_ok=True)
file_handler = RotatingFileHandler(
"logs/myijack.log", maxBytes=10240, backupCount=10
)
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(logging.Formatter(log_format))
app.logger.addHandler(file_handler)
app.logger.error(
"Just testing Gunicorn logging in Docker Swarm service container ✅..."
)
app.logger.info("myijack.com startup now...")
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)
# Initialize extensions
Bootstrap(app)
db.init_app(app) # SQLAlchemy
databases.init_app(app) # other custom database functions
cache.init_app(
app, config=config_obj.cache_config
) # Simple if dev, otherwise Redis for test/prod
login_manager.init_app(app)
Migrate(app, db)
mail.init_app(app)
bcrypt.init_app(app)
pages.init_app(app)
# By default, when a user attempts to access a login_required view without being logged in,
# Flask-Login will flash a message and redirect them to the log in view.
# (If the login view is not set, it will abort with a 401 error.)
login_manager.login_view = "auth.login"
# login_manager.login_message = "You must be logged in to access this page."
# Register blueprints
if ALL0_DASH1_FLASK2_ADMIN3 in (0, 2):
pass
app.logger.debug("Importing blueprint views...")
from app.auth.oauth import azure_bp, github_bp, google_bp
from app.auth.views import auth as auth_bp
from app.dashapp.views import dash_bp
from app.home.views import home as home_bp
from app.pwa import pwa_bp
app.logger.debug("Registering blueprint views...")
app.register_blueprint(auth_bp)
app.register_blueprint(home_bp)
app.register_blueprint(pwa_bp)
app.register_blueprint(dash_bp)
app.register_blueprint(github_bp, url_prefix="/login")
app.register_blueprint(azure_bp, url_prefix="/login")
app.register_blueprint(google_bp, url_prefix="/login")
# Register API for saving Flask-Admin views' metadata via JavaScript AJAX
from app.api import api
api.init_app(app)
if ALL0_DASH1_FLASK2_ADMIN3 in (0, 3):
pass
# Setup Flask-Admin site
app.logger.debug("Importing Flask-Admin views...")
from app.flask_admin.views_admin import admin_views
from app.flask_admin.views_admin_cust import admin_cust_views
app.logger.debug("Adding Flask-Admin views...")
admin_views(app, db)
admin_cust_views(app, db)
with app.app_context():
# Flask-Assets must come before the Dash app so it
# can first render the {% assets %} blocks
assets_env.init_app(app)
compile_assets(assets_env, app)
# HTMLMin must come after Dash for some reason...
# app.logger.debug("Registering HTMLMin...")
app.config["MINIFY_HTML"] = True
HTMLMin(
app,
remove_comments=True,
remove_empty_space=True,
# This one can cause a bug...
# disable_css_min=False,
)
return app, dash_app
</code></pre>
<p>The issue has been <a href="https://github.com/plotly/dash/issues/270" rel="nofollow noreferrer">on Github since 2018</a> and apparently it's closed/fixed, but not for me...</p>
<p>I'm using the following <code>pyproject.toml</code> in production:</p>
<pre><code>[tool.poetry.dependencies]
python = ">=3.8,<3.12"
dash = {extras = ["compress"], version = "^2.11.1"}
scikit-learn = "1.1.3"
pandas = "^1.5.3"
flask-login = "^0.5.0"
keras = "^2.4.3"
joblib = "^1.2.0"
boto3 = "^1.26.12"
click = "^8.1.3"
dash-bootstrap-components = "^1.4.2"
dash-table = "^5.0.0"
flask-caching = "2.0.1"
flask-migrate = "^2.5.3"
flask-sqlalchemy = "^2.4.4"
flask-testing = "^0.8.0"
gevent = "^22.10.2"
greenlet = "^2.0.1"
gunicorn = "^20.0.4"
python-dotenv = "^0.19.2"
python-dateutil = "^2.8.1"
requests = "^2.24.0"
email_validator = "^1.1.1"
flask-redis = "^0.4.0"
numexpr = "^2.7.1"
flask-mail = "^0.9.1"
python-jose = "^3.3.0"
sqlalchemy = "^1.3"
Flask-FlatPages = "^0.7.2"
flask-bootstrap4 = "^4.0.2"
colour = "^0.1.5"
tenacity = "^6.3.1"
psycopg2-binary = "^2.8.6"
twilio = "^6.54.0"
openpyxl = "^3.0.7"
phonenumbers = "^8.12.29"
celery = "^5.1.2"
flower = "^1.0.0"
Flask-Assets = "^2.0"
webassets = "^2.0"
cssmin = "^0.2.0"
rjsmin = "^1.2.0"
Flask-HTMLmin = "^2.2.0"
ipinfo = "^4.2.1"
dash-mantine-components = "^0.12.1"
Flask = "^2.1.2"
Flask-Bcrypt = "^1.0.1"
Werkzeug = "2.0.3"
Flask-WTF = "^1.0.1"
flask-restx = "^0.5.1"
flask-admin-plus = "^1.6.18"
Pillow = "^9.2.0"
multidict = "^6.0.2"
gcld3 = "^3.0.13"
plotly = "^5.14.1"
flask-dance = "^7.0.0"
blinker = "^1.6.2"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
</code></pre>
<p>Here's my <code>gunicorn.conf.py</code>:</p>
<pre><code># -*- encoding: utf-8 -*-
bind = "0.0.0.0:5005"
# The Access log file to write to, same as --access-logfile
# Using default "-" makes gunicorn log to stdout - perfect for Docker
accesslog = "-"
# Same as --log-file or --error-logfile. Default "-" goes to stderr for Docker.
errorlog = "-"
# We overwrite the below loglevel in __init__.py
# loglevel = "info"
# Redirect stdout/stderr to specified file in errorlog
capture_output = True
enable_stdio_inheritance = True
# gevent setup
# workers = 4 # 4 threads (2 per CPU)
# threads = 2 # 2 CPUs
# Typically Docker handles the number of workers, not Gunicorn
workers = 1
threads = 2
worker_class = "gevent"
# The maximum number of simultaneous clients.
# This setting only affects the Eventlet and Gevent worker types.
worker_connections = 20
# Timeout in seconds (default is 30)
timeout = 30
# Directory to use for the worker heartbeat temporary file.
# Use an in-memory filesystem to avoid hanging.
# In AWS an EBS root instance volume may sometimes hang for half a minute
# and during this time Gunicorn workers may completely block.
# https://docs.gunicorn.org/en/stable/faq.html#blocking-os-fchmod
worker_tmp_dir = "/dev/shm"
</code></pre>
<p>Here's the Dockerfile I'm using in production:</p>
<pre><code># Builder stage ############################################################################
# Build args available during build, but not when container runs.
# They can have default values, and can be passed in at build time.
ARG ENVIRONMENT=production
FROM python:3.8.15-slim-buster AS builder
ARG POETRY_VERSION=1.2.2
# Use Docker BuildKit for better caching and faster builds
ARG DOCKER_BUILDKIT=1
ARG BUILDKIT_INLINE_CACHE=1
# Enable BuildKit for Docker-Compose
ARG COMPOSE_DOCKER_CLI_BUILD=1
# Python package installation stuff
ARG PIP_NO_CACHE_DIR=1
ARG PIP_DISABLE_PIP_VERSION_CHECK=1
ARG PIP_DEFAULT_TIMEOUT=100
# Don't write .pyc bytecode
ENV PYTHONDONTWRITEBYTECODE=1
# Don't buffer stdout. Write it immediately to the Docker log
ENV PYTHONUNBUFFERED=1
ENV PYTHONFAULTHANDLER=1
ENV PYTHONHASHSEED=random
# Tell apt-get we're never going to be able to give manual feedback:
ENV DEBIAN_FRONTEND=noninteractive
WORKDIR /project
RUN apt-get update && \
apt-get install -y --no-install-recommends gcc redis-server libpq-dev sass \
g++ protobuf-compiler libprotobuf-dev && \
# Clean up
apt-get autoremove -y && \
apt-get clean -y && \
rm -rf /var/lib/apt/lists/*
# The following only runs in the "builder" build stage of this multi-stage build.
RUN pip3 install "poetry==$POETRY_VERSION" && \
# Use a virtual environment for easy transfer of builder packages
python -m venv /venv && \
/venv/bin/pip install --upgrade pip wheel
# Poetry exports the requirements to stdout in a "requirements.txt" file format,
# and pip installs them in the /venv virtual environment. We need to copy in both
# pyproject.toml AND poetry.lock for this to work!
COPY pyproject.toml poetry.lock ./
RUN poetry config virtualenvs.create false && \
poetry export --no-interaction --no-ansi --without-hashes --format requirements.txt \
$(test "$ENVIRONMENT" != "production" && echo "--with dev") \
| /venv/bin/pip install -r /dev/stdin
# Make sure our packages are in the PATH
ENV PATH="/project/node_modules/.bin:$PATH"
ENV PATH="/venv/bin:$PATH"
COPY wsgi.py gunicorn.conf.py .env .flaskenv entrypoint.sh postcss.config.js ./
COPY assets assets
COPY app app
RUN echo "Building flask assets..." && \
# Flask assets "clean" command may fail, in which case just run "build"
flask assets clean || true && \
flask assets build
# Final stage of multi-stage build ############################################################
FROM python:3.8.15-slim-buster as production
# For setting up the non-root user in the container
ARG USERNAME=user
ARG USER_UID=1000
ARG USER_GID=$USER_UID
# Use Docker BuildKit for better caching and faster builds
ARG DOCKER_BUILDKIT=1
ARG BUILDKIT_INLINE_CACHE=1
# Enable BuildKit for Docker-Compose
ARG COMPOSE_DOCKER_CLI_BUILD=1
# Don't write .pyc bytecode
ENV PYTHONDONTWRITEBYTECODE=1
# Don't buffer stdout. Write it immediately to the Docker log
ENV PYTHONUNBUFFERED=1
ENV PYTHONFAULTHANDLER=1
ENV PYTHONHASHSEED=random
# Tell apt-get we're never going to be able to give manual feedback:
ENV DEBIAN_FRONTEND=noninteractive
# Add a new non-root user and change ownership of the workdir
RUN addgroup --gid $USER_GID --system $USERNAME && \
adduser --no-create-home --shell /bin/false --disabled-password --uid $USER_UID --system --group $USERNAME && \
# Get curl and netcat for Docker healthcheck
apt-get update && \
apt-get -y --no-install-recommends install nano curl netcat g++ && \
apt-get clean && \
# Delete index files we don't need anymore:
rm -rf /var/lib/apt/lists/*
WORKDIR /project
# Make the logs directory writable by the non-root user
RUN mkdir -p /project/logs && \
chown -R $USER_UID:$USER_GID /project/logs
# Copy in files and change ownership to the non-root user
COPY --chown=$USER_UID:$USER_GID --from=builder /venv /venv
# COPY --chown=$USER_UID:$USER_GID --from=builder /node_modules /node_modules
COPY --chown=$USER_UID:$USER_GID --from=builder /project/assets assets
COPY --chown=$USER_UID:$USER_GID app app
COPY --chown=$USER_UID:$USER_GID tests tests
COPY --chown=$USER_UID:$USER_GID wsgi.py gunicorn.conf.py .env .flaskenv entrypoint.sh ./
# Set the user so nobody can run as root on the Docker host (security)
USER $USERNAME
# Just a reminder of which port is needed in gunicorn.conf.py (in-container, in production)
# EXPOSE 5005
# Make sure we use the virtualenv
ENV PATH="/venv/bin:$PATH"
RUN echo PATH = $PATH
CMD ["/bin/bash", "/project/entrypoint.sh"]
</code></pre>
<p>My <code>entrypoint.sh</code> file starts everything as follows:</p>
<pre><code>#!/bin/bash
# Enable exit on non 0
set -euo pipefail
# Finally, start the Gunicorn app server for the Flask app.
# All config options are in the gunicorn.conf.py file.
echo "Starting Gunicorn with gunicorn.conf.py configuration..."
gunicorn --config /project/gunicorn.conf.py wsgi:app
</code></pre>
<p>Here's the <code>wsgi.py</code> file to which the above <code>entrypoint.sh</code> is referring:</p>
<pre><code>print("Starting: importing app and packages...")
try:
from app import cli, create_app, db
except Exception as err:
print(f"ERROR: {err}")
print("ERROR: Unable to import cli, create_app, and db from app. Exiting...")
exit(1)
print("Creating app...")
try:
app, _ = create_app()
cli.register(app)
except Exception as err:
print(f"ERROR: {err}")
print("ERROR: Unable to create app. Exiting...")
exit(1)
print("App is ready ✅")
</code></pre>
<p>UPDATE Nov 20, 2023:
I've added the following to the code, and it still outputs the useless Dash <code>POST /dash/_dash-update-component</code> logs...</p>
<pre class="lang-py prettyprint-override"><code>gunicorn_logger = logging.getLogger("gunicorn.error")
gunicorn_logger.setLevel(logging.ERROR)
dash_logger = logging.getLogger("dash")
dash_logger.setLevel(logging.ERROR)
</code></pre>
| <python><flask><plotly-dash> | 2023-11-17 16:36:20 | 1 | 5,708 | Sean McCarthy |
77,503,140 | 12,016,688 | What does RESUME opcode actually do? | <p>The <a href="https://docs.python.org/3/library/dis.html#opcode-RESUME" rel="noreferrer">documentation</a> is not very informative (at least for me):</p>
<blockquote>
<p>opcode:: RESUME (context)</p>
<p>A no-op. Performs internal tracing, debugging and optimization
checks.</p>
<p>The <code>context</code> oparand consists of two parts. The lowest two bits
indicate where the <code>RESUME</code> occurs:</p>
<ul>
<li><p><code>0</code> The start of a function, which is neither a generator,
coroutine
nor an async generator</p>
</li>
<li><p><code>1</code> After a <code>yield</code> expression</p>
</li>
<li><p><code>2</code> After a <code>yield from</code> expression</p>
</li>
<li><p><code>3</code> After an <code>await</code> expression</p>
</li>
</ul>
<p>The next bit is <code>1</code> if the RESUME is at except-depth <code>1</code>, and
<code>0</code> otherwise.</p>
</blockquote>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>>>> import dis
>>>
>>> def f(): ...
...
>>> dis.dis(f)
1 0 RESUME 0
2 LOAD_CONST 0 (None)
4 RETURN_VALUE
</code></pre>
<p>Can someone provide an explanation of what this opcode really does?</p>
| <python><cpython><python-internals> | 2023-11-17 16:19:54 | 1 | 2,470 | Amir reza Riahi |
77,503,138 | 4,999,991 | Developing a FreeCAD Plugin Using PyFlow: Issues with Python Interpreter and Module Import | <p>I'm working on developing a plugin for FreeCAD that leverages the PyFlow library. To clarify and avoid an XYZ problem, I aim to create a FreeCAD plugin using PyFlow.</p>
<p>For development, I face a dilemma:</p>
<ul>
<li>I can't find the Freecad module using a separate Python interpreter when installing it via pip.</li>
<li>Using FreeCAD's bundled Python interpreter, I seem to successfully install packages (like PyFlow) using FreeCAD's pip. However, I can't locate the installed Pyflow folder, nor can I import PyFlow within the interpreter.</li>
</ul>
<p>FreeCAD's Python interpreter apparently installs packages to a location I cannot determine. I've tried checking the site-packages directory, but the Pyflow folder isn't present.</p>
<p>Has anyone experienced similar issues, or can you offer guidance on correctly setting up the environment for developing a FreeCAD plugin using external libraries like PyFlow?</p>
<p>the <code>pip install freecad</code> retunrs</p>
<blockquote>
<p>ERROR: Could not find a version that satisfies the requirement freecad (from versions: none)<br/> ERROR: No matching distribution found for freecad</p>
</blockquote>
<p>I checked the folders:</p>
<pre><code>C:\Users\Foo\AppData\Roaming\Python\Python38\site-packages
C:\Program Files\FreeCAD 0.20\bin\Lib\site-packages
</code></pre>
<p>I see the folder <code>pyflow-0.3.1.dist-info</code>, but it does not contain the relevant files, such as an <code>__init__.py</code> file or a PyFlow subdirectory.</p>
<p>I tried purging with</p>
<pre><code>"C:\Program Files\FreeCAD 0.20\bin\python.exe" -m pip cache purge
</code></pre>
<p>and reinstalling with</p>
<pre><code>"C:\Program Files\FreeCAD 0.20\bin\python.exe" -m pip install --force-reinstall pyflow
</code></pre>
<p>that returns</p>
<blockquote>
<p>Defaulting to user installation because normal site-packages is not writeable<br/> Collecting pyflow<br/> Using cached pyflow-0.3.1-py3-none-win_amd64.whl (5.3 MB)<br/> Installing collected packages: pyflow<br/> Successfully installed pyflow-0.3.1</p>
</blockquote>
| <python><python-3.x><pip><freecad> | 2023-11-17 16:19:15 | 0 | 14,347 | Foad S. Farimani |
77,503,109 | 10,036,039 | How to fix InvalidManifestError for pre-commit with black? | <p>Running python <code>pre-commit</code> with <code>black</code> latest version <code>23.11.0</code> leads to a wired <code>InvalidManifestError</code>.</p>
<p>snippet from <code>.pre-commit-config.yaml</code></p>
<pre class="lang-yaml prettyprint-override"><code>repos:
- repo: https://github.com/psf/black
rev: 23.11.0
hooks:
- id: black
types: []
files: ^.*.pyi?$ # format .py and .pyi files`
</code></pre>
<p>output message:</p>
<pre class="lang-bash prettyprint-override"><code>│ │ stdout = 'An error has occurred: InvalidManifestError: \n==> File │ │
│ │ /Users/robot/.cache/pre-c'+329 │ │
│ │ stdout_list = [ │ │
│ │ │ 'An error has occurred: InvalidManifestError: \n', │ │
│ │ │ '==> File │ │
│ │ /Users/robot/.cache/pre-commit/repoxhmwyits/.pre-commit-hooks.yaml\n', │ │
│ │ │ "==> At Hook(id='black')\n", │ │
│ │ │ '==> At key: stages\n', │ │
│ │ │ '==> At index 0\n', │ │
│ │ │ '=====> Expected one of commit, commit-msg, manual, merge-commit, │ │
│ │ post-checkout, '+86, │ │
│ │ │ 'Check the log at /Users/robot/.cache/pre-commit/pre-commit.log\n' │ │
│ │ ]
</code></pre>
| <python><pre-commit><pre-commit.com><python-black> | 2023-11-17 16:15:11 | 3 | 12,920 | zerocewl |
77,503,093 | 7,869,636 | Why in Python the parent's init calls child's overridden method? | <p>I have two classes. The <em>Child</em> has a different signature (number of arguments). Take a look at this MRE (minimal reproducible example):</p>
<pre class="lang-py prettyprint-override"><code>class Parent:
def __init__(self, arg):
self.some_method(arg) # it was intended to call the Parent's some_method
def some_method(self, arg1): # why this method is not called from Parent's __init__?
print(f"Parent method called with arg1: {arg1}")
class Child(Parent):
def __init__(self):
Parent.__init__(self, "Hello")
# the child __init__ does not need to call some_method
def some_method(self, arg1, arg2): # child has two arguments. Why Child's some_method called from Parent's __init__?
print(f"Child method called with arg1: {arg1} and arg2: {arg2}")
super().some_method(arg1)
child = Child() # getting an exception
</code></pre>
<p>Expected result:</p>
<pre><code>Parent method called with arg1: Hello
</code></pre>
<p>Actual result:</p>
<pre><code>TypeError: Child.some_method() missing 1 required positional argument: 'arg2'
</code></pre>
<p>As can be seen, it was called <strong>Child</strong>.some_method().</p>
<p>Why this is happening? Is it possible to keep different number of arguments and keep this working?</p>
<hr />
<p>There is a similar <a href="https://stackoverflow.com/q/51514472/7869636">question</a>, but its intention was opposite to mine - he <em>wanted</em> that parent called the child method.</p>
| <python><oop> | 2023-11-17 16:12:43 | 1 | 839 | Ashark |
77,503,083 | 12,320,370 | Accessing BitBucket Variables directly inside a Python Script | <p>I've set up some Repository Variables (also tried deployment variables) that hold some secrets for DB connections.</p>
<p>I would like to use these variables directly in my .py file, trouble is I have no idea how to, I tried accessing them a few different ways and the error is always the variables being null. Although if I expr the variables in the .yml file it is being read correctly.</p>
<p>Current Config:</p>
<p><a href="https://i.sstatic.net/geiKF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/geiKF.png" alt="enter image description here" /></a></p>
<p><strong>inside of main.py</strong></p>
<pre><code>connection_parameters = {
"account": os.getenv('$account'),
"user": os.getenv('$user'),
"password": os.getenv('$password')
</code></pre>
<p>Proof the variable can be accessed from .yml file(it has the value of 10):</p>
<p><a href="https://i.sstatic.net/C6zL8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/C6zL8.png" alt="enter image description here" /></a></p>
<p>So I guess my question is, how do I access these variables stored on BitBucket, inside of my python script, upon deployment?</p>
| <python><variables><bitbucket><bitbucket-pipelines> | 2023-11-17 16:10:29 | 1 | 333 | Nairda123 |
77,503,042 | 238,230 | How to access Python dependencies when SSH'ing to Paketo image? | <p>I have an image built using the <a href="https://paketo.io/docs/howto/python/" rel="nofollow noreferrer">Paketo Python Buildpack</a>. It executes the command in the <code>Procfile</code> fine including python dependencies. However, when I exec on to the running instance e.g. using <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html" rel="nofollow noreferrer">ecs exec</a> in order to run an ad-hoc script I've found it doesn't have access to the installed python dependencies e.g.</p>
<pre><code>$ python3 -m scripts.my_script
Traceback (most recent call last):
File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/workspace/scripts/my_script", line 4, in <module>
from app import app
File "/workspace/app.py", line 1, in <module>
import connexion
ModuleNotFoundError: No module named 'connexion'
</code></pre>
<p>Is it possible to run python in a way which includes the dependencies in the path?
This was possible using the <code>/tmp/lifecycle/shell</code> <a href="https://docs.cloudfoundry.org/devguide/deploy-apps/ssh-apps.html#ssh-env" rel="nofollow noreferrer">command</a> on Cloudfoundry but is a similar thing possible when using a Paketo image?</p>
| <python><buildpack><paketo> | 2023-11-17 16:05:17 | 1 | 752 | Gids |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.