QuestionId
int64 74.8M
79.8M
| UserId
int64 56
29.4M
| QuestionTitle
stringlengths 15
150
| QuestionBody
stringlengths 40
40.3k
| Tags
stringlengths 8
101
| CreationDate
stringdate 2022-12-10 09:42:47
2025-11-01 19:08:18
| AnswerCount
int64 0
44
| UserExpertiseLevel
int64 301
888k
| UserDisplayName
stringlengths 3
30
⌀ |
|---|---|---|---|---|---|---|---|---|
76,258,761
| 11,009,630
|
How to save grayscale image with proper colormap using opencv python
|
<p>I want to write/save this grayscale(2d) image with unique pixel values [0, 2, 3, 4, 5, 6] <a href="https://i.sstatic.net/X3gGB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/X3gGB.png" alt="image" /></a></p>
<p>with opencv, but when I save it using this</p>
<pre class="lang-py prettyprint-override"><code>cv2.imwrite('test.jpg', image)
</code></pre>
<p>I see a dark image with very faint pixels for the above values</p>
<p><a href="https://i.sstatic.net/Q4w6j.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Q4w6j.jpg" alt="cv image" /></a></p>
<p>How can I save my image using opencv and still ensure proper colormap is followed? Is there a better library to save this kind of low pixel grayscale images?</p>
|
<python><opencv><matplotlib>
|
2023-05-16 01:00:52
| 1
| 646
|
Deep
|
76,258,710
| 905,620
|
Boto3 - How to combine TransferConfig and Config?
|
<p>I have this Python code and I am trying to find a way to combine two configs:</p>
<pre><code>...
from boto3.s3.transfer import TransferConfig
from botocore.client import Config
...
transfer_config = TransferConfig(max_concurrency=XXX, ...)
config = Config(retries=XX,region_name=XX, ...)
s3 = boto3.Session().resource("s3", config = [__HOW I can combibe "transfer_config" and "config" here?])
</code></pre>
<p>I need two configurations because, for example, <code>max_concurrency</code> can<code>t be applied to </code>Config<code>and</code>signature_version<code>to</code>TransferConfig`. I need all these paremeters (and more)</p>
|
<python><boto3><botocore>
|
2023-05-16 00:41:01
| 1
| 1,545
|
prosto.vint
|
76,258,698
| 2,180,570
|
PyYAML customize loader to include depth level
|
<p>I'm using PyYAML, and I'm trying to attach line numbers to dicts in my nested YAML structure, but only at the topmost level, e.g.:</p>
<pre class="lang-yaml prettyprint-override"><code>- id: 123
__line: 1
links:
- name: "abc"
# no line number here
- name: "def"
</code></pre>
<p>There is <a href="https://stackoverflow.com/a/53647080/2180570">this answer that shows how to attach line numbers</a> by overriding <code>SafeLoader</code>, but this attaches the <code>__line</code> field to all dicts at any nesting level.</p>
<p>I ask in one of the comments there how to make this only apply to the top-most level of a structure, and @augurar gives an idea for a solution, but I need more help.</p>
<blockquote>
<p>Since the constructor performs a depth-first traversal, you could add an attribute to track current depth and override construct_object() to increment/decrement it appropriately. You'd need some extra logic to handle anchors correctly, if needed for your use case.</p>
</blockquote>
<p>Here is what I've tried so far:</p>
<pre class="lang-py prettyprint-override"><code>class SafeLineLoader(SafeLoader):
def construct_mapping(self, node, deep=True):
mapping = super(SafeLineLoader, self).construct_mapping(node, deep=deep)
if node.get("depth") == 0:
mapping["line"] = node.start_mark.line + 1
print(node)
return mapping
def construct_object(self, node, deep=False, depth=0):
return super().construct_object(node, deep=deep, depth=depth + 1)
</code></pre>
<p>But I get the following error:</p>
<pre class="lang-bash prettyprint-override"><code> return super().construct_object(node, deep=deep, depth=depth + 1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BaseConstructor.construct_object() got an unexpected keyword argument 'depth'
</code></pre>
<p>I guess because PyYAML's <code>construct_object</code> function is not expecting that <code>depth</code> argument. This may end up being a Python noob question about wrapping class methods and adding new arguments, or it may be that I just don't understand the architecture of this PyYAML library.</p>
|
<python><python-3.x><yaml>
|
2023-05-16 00:34:43
| 1
| 1,981
|
V. Rubinetti
|
76,258,666
| 11,065,874
|
FastAPI returns 405 Method Not Allowed response when mounting a StaticFiles instance
|
<p>I have this FastAPI application</p>
<pre class="lang-py prettyprint-override"><code>import uvicorn
from fastapi import FastAPI
from starlette.responses import FileResponse
app = FastAPI()
@app.get("/a")
async def read_index():
return FileResponse('static/index.html')
@app.get("/a/b")
def download():
return "get"
@app.post("/a/b")
def ab():
return "post"
def main():
uvicorn.run("run:app", host="0.0.0.0", reload=True, port=8001)
if __name__ == "__main__":
main()
</code></pre>
<p>and in <code>static/index.html</code> I have:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<section>
<form method="post" action="/a/b" enctype="multipart/form-data">
<div>
<p>Download:</p>
</div>
<div>
<input type="submit" value="Download"/>
</div>
</form>
</section>
</body>
</html>
</code></pre>
<p>I send a get request to <code>http://127.0.0.1:8001/a</code> and click on the <code>download</code> button it loads, it returns "get"</p>
<p>However, I change the application to</p>
<pre><code>import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/a", StaticFiles(directory="static", html=True))
@app.get("/a/b")
def download():
return "get"
@app.post("/a/b")
def ab():
return "post"
def main():
uvicorn.run("run:app", host="0.0.0.0", reload=True, port=8001)
if __name__ == "__main__":
main()
</code></pre>
<p>with the same HTML file, I click on the download button, and I get <code>detail: "Method Not Allowed"</code> because it is doing <code>INFO: 127.0.0.1:58109 - "POST /b HTTP/1.1" 405 Method Not Allowed</code></p>
<p>I want to use mount becuase I want to put js and css files there as well, to be used by the index.html file. how should I do this?</p>
|
<javascript><python><html><css><fastapi>
|
2023-05-16 00:22:13
| 1
| 2,555
|
Amin Ba
|
76,258,582
| 19,506,623
|
How to add elements before each occurence of string in list?
|
<p>I have a list for which I'm trying to add the 3 consecutive elements <code>'A','B','C'</code> before each occurrence of 'D' and when the previous element be different than 'C'. I'm using <code>startwith()</code> since instead of letters in actual data are words.</p>
<p>This is my current attempt but is not changing anything.</p>
<pre><code>mylist = ['A', 'B', 'C', 'D', 'E', 'D', 'E', 'W', 'B', 'D', 'W']
for idx,el in enumerate(mylist):
if el.startswith('D') and not mylist[mylist.index(el)-1].startswith('C'):
mylist.insert(idx,'A|B|C'.split('|'))
</code></pre>
<p>My expected output would be like this:</p>
<pre><code>mylist = ['A', 'B', 'C', 'D', 'E', ['A','B','C'], 'D', 'E', 'W', 'B', ['A','B','C'],'D', 'W']
</code></pre>
<p>Then, I would flatten this output to finally get</p>
<pre><code>out = ['A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E', 'W', 'B','A','B','C','D', 'W']
</code></pre>
<p>Thanks for any help.</p>
|
<python>
|
2023-05-15 23:53:05
| 3
| 737
|
Rasec Malkic
|
76,258,496
| 107,245
|
Python module vs class confusion
|
<p>I'm trying to use Python to customize my GDB sessions. I'm copying code from GDB docs, but instead of working properly, they give errors. Confusing ones. I'm a Python noob, so to be honest, the error makes no sense, neither the fix.</p>
<pre><code>class MyFrameDecorator(gdb.FrameDecorator):
# Blah, blah.
# TypeError: module() takes at most 2 arguments (3 given)
</code></pre>
<p>Say what now? Where does this '2 arguments vs. 3' come from? I see zero arguments. The following code compiles without complaints:</p>
<pre><code>class MyFrameDecorator(gdb.FrameDecorator.FrameDecorator):
# Blah, blah.
</code></pre>
<p>Why? I don't get it. Why does repeating the class name fix the type error? Note that GDB automatically adds <code>import gdb</code> to all python scripts so that is not the issue (in fact, when the code compiles it doesn't have <code>import gdb</code> in it).</p>
<p>Update:</p>
<p>Since people requested a link to the GDB docs:
<a href="https://sourceware.org/gdb/onlinedocs/gdb/Writing-a-Frame-Filter.html#Writing-a-Frame-Filter" rel="nofollow noreferrer">https://sourceware.org/gdb/onlinedocs/gdb/Writing-a-Frame-Filter.html#Writing-a-Frame-Filter</a></p>
|
<python><gdb>
|
2023-05-15 23:23:49
| 0
| 9,533
|
Lajos Nagy
|
76,258,307
| 413,653
|
Python Django Docker - You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
|
<p>I'm running a Django application via Docker. How do I get past the following error message:</p>
<p><code>django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.</code></p>
<p>I do have STATIC_ROOT declared in my <strong>settings.py</strong> file</p>
<pre><code>import environ
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env()
env_path = BASE_DIR / ".env"
if env_path.is_file():
environ.Env.read_env(env_file=str(env_path))
...
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
...
</code></pre>
<p>Some web searching led me to believe the <strong>settings.py</strong> file isn't even being referenced, but I could be wrong. I think that's shown in the <strong>manage.py</strong> file below.</p>
<pre><code>#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_aws.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
</code></pre>
<p>The files are created in Windows, but the Docker container is not running Windows. I was getting some errors related to line endings, so I threw in the first 4 lines of this <strong>Dockerfile</strong>:</p>
<pre><code>FROM ubuntu:latest
RUN apt-get update && apt-get install -y dos2unix
COPY manage.py /manage-clean.py
RUN dos2unix /manage-clean.py && apt-get --purge remove -y dos2unix && rm -rf /var/lib/apt/lists/*
FROM python:3.10-slim-buster
# Open http port
EXPOSE 8000
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV DEBIAN_FRONTEND noninteractive
# Install pip and gunicorn web server
RUN pip install --no-cache-dir --upgrade pip
RUN pip install gunicorn==20.1.0
# Install requirements.txt
COPY requirements.txt /
RUN pip install --no-cache-dir -r /requirements.txt
# Moving application files
WORKDIR /app
COPY . /app
RUN python manage.py collectstatic --no-input
</code></pre>
<p>Here's my project directory. Master project is DJANGO-AWS with 2 sub projects <strong>django-aws-backend</strong> and <strong>django-aws-infrastructure</strong>.</p>
<p><a href="https://i.sstatic.net/L5CQ8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/L5CQ8.png" alt="enter image description here" /></a></p>
|
<python><django><docker><dockerfile>
|
2023-05-15 22:32:28
| 1
| 1,537
|
Mark
|
76,258,191
| 1,997,735
|
Python logger with adjusted timestamp?
|
<p>We've got two Windows machines that are talking back and forth, the problem is that the two machines haven't always had their system times set to the same values which makes it hard to figure out what happened when looking at the log files.</p>
<p>The primary machine is on the Internet so we call his timestamp "correct", and we can send his timestamp over the LAN so the secondary machine knows the primary machine's timestamp, but the program on the secondary machine doesn't have the necessary authorization to update its Windows system time.</p>
<p>Is there any way to set the Python logger so the timestamp that gets written to the secondary machine's log is different from the Windows system timestamp? That is, if the secondary machine thinks it's 12:00:00 but the primary machine says it's actually 12:00:05, can the Python logger on the secondary machine be set so it adds 5 seconds to the Window system time when generating its timestamp?</p>
|
<python><windows><time>
|
2023-05-15 22:04:23
| 0
| 3,473
|
Betty Crokker
|
76,258,090
| 6,561,375
|
What causes an mss.exception.ScreenShotError: gdi32.GetDIBits() failed
|
<p>I'm trying to write some code to use screencaptures to export the position from a online-go.server. I only got a few lines in, when I got this error from this code</p>
<p>error</p>
<pre><code>c:\Go\sgo>py ogs2kgs.py
top left position : 220 149
bottom right position : 719 650
Dimensions: (46, 47) Total pixels: 2162
Traceback (most recent call last):
File "c:\Go\sgo\ogs2kgs.py", line 24, in <module>
pos = imagesearcharea("BlackStone.png", x, y, 30, 30)
File "C:\Python39\lib\site-packages\python_imagesearch\imagesearch.py", line 60, in imagesearcharea
im = region_grabber(region=(x1, y1, x2, y2))
File "C:\Python39\lib\site-packages\python_imagesearch\imagesearch.py", line 36, in region_grabber
return sct.grab(region)
File "C:\Python39\lib\site-packages\mss\base.py", line 90, in grab
screenshot = self._grab_impl(monitor)
File "C:\Python39\lib\site-packages\mss\windows.py", line 252, in _grab_impl
raise ScreenShotError("gdi32.GetDIBits() failed.")
mss.exception.ScreenShotError: gdi32.GetDIBits() failed.
c:\Go\sgo>py ogs2kgs.py
top left position : 220 149
bottom right position : 719 650
Dimensions: (46, 47) Total pixels: 2162
0
</code></pre>
<p>code</p>
<pre><code>from python_imagesearch.imagesearch import *
from PIL import Image
import os
top_left = imagesearch("top_left.png")
if top_left[0] != -1:
print("top left position : ", top_left[0], top_left[1])
else:
print("image not found")
bottom_right = imagesearch("bottom_right.png")
if bottom_right[0] != -1:
print("bottom right position : ", bottom_right[0], bottom_right[1])
else:
print("image not found")
img = Image.open("bottom_right.PNG")
width, height = img.size
print("Dimensions:", img.size, "Total pixels:", width * height)
stones = 0
for x in range(top_left[0],bottom_right[0]+30,30):
for y in range(top_left[1],bottom_right[1]+30,30):
try:
pos = imagesearcharea("BlackStone.png", x, y, 30, 30)
if pos != -1:
print(pos)
stones = stones + 1
except:pass
print(stones)
</code></pre>
<p>What's that all about? Any ideas ...</p>
|
<python><python-mss><baduk>
|
2023-05-15 21:39:30
| 0
| 791
|
SlightlyKosumi
|
76,257,950
| 6,396,199
|
Local pyspark cannot import
|
<p>I'm trying to run Spark locally using pyspark but I keep getting the following error when I try to import pyspark.</p>
<pre><code>Traceback (most recent call last):
File "spark_test.py", line 6, in <module>
import pyspark
File "C:\SPARK/spark-2.4.3-bin-hadoop2.8\python\pyspark\__init__.py", line 51, in <module>
from pyspark.context import SparkContext
File "C:\SPARK/spark-2.4.3-bin-hadoop2.8\python\pyspark\context.py", line 31, in <module>
from pyspark import accumulators
File "C:\SPARK/spark-2.4.3-bin-hadoop2.8\python\pyspark\accumulators.py", line 97, in <module>
from pyspark.serializers import read_int, PickleSerializer
File "C:\SPARK/spark-2.4.3-bin-hadoop2.8\python\pyspark\serializers.py", line 71, in <module>
from pyspark import cloudpickle
File "C:\SPARK/spark-2.4.3-bin-hadoop2.8\python\pyspark\cloudpickle.py", line 145, in <module>
_cell_set_template_code = _make_cell_set_template_code()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\SPARK/spark-2.4.3-bin-hadoop2.8\python\pyspark\cloudpickle.py", line 126, in _make_cell_set_template_code
return types.CodeType(
^^^^^^^^^^^^^^^
TypeError: code expected at least 16 arguments, got 15
</code></pre>
<p>This is my Python code:</p>
<pre class="lang-py prettyprint-override"><code># Find Spark location
import findspark
findspark.init("C:/SPARK/spark-2.4.3-bin-hadoop2.8")
# Imports
import pyspark
if __name__ == "__main__":
spark = pyspark.SparkContext(appName="SparkTest")
</code></pre>
<p>Does anyone know what might be wrong? I'm using Windows 10 64-bit and Python 3.11.</p>
|
<python><pyspark>
|
2023-05-15 21:11:26
| 0
| 847
|
syy
|
76,257,939
| 3,380,902
|
Spark DataFrame apply Databricks geospatial indexing functions
|
<p>I have a spark DataFrame with <code>h3</code> hex ids and I am trying to obtain the polygon geometries.</p>
<pre><code>from pyspark.sql import SparkSession
from pyspark.sql.functions import col, expr
from pyspark.databricks.sql.functions import *
from mosaic import enable_mosaic
enable_mosaic(spark, dbutils)
# Create a Spark session
spark = SparkSession.builder.appName("Mosaic").getOrCreate()
# Create a DataFrame with hex IDs
df = spark.createDataFrame([
(1, "87422c2a9ffffff"),
(2, "87422c2a9000000"),
(3, "87422c2a8ffffff")
], ("id", "h3hex_id"))
sdf2 = sdf1.withColumn("geometry", h3_boundaryaswkt(col("h3hex_id")))
sdf2.sample(fraction=0.1).show()
AnalysisException: [H3_NOT_ENABLED] h3_boundaryaswkt is disabled or unsupported. Consider enabling Photon or switch to a tier that supports H3 expressions;
sdf2 = sdf1.withColumn("geometry", grid_boundary(col("h3hex_id"), format_name="WKT"))
sdf2.sample(fraction=0.1).show()
AnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name `WKT` cannot be resolved. Did you mean one of the following? ..
</code></pre>
<p>I have installed <code>databricks-mosaic 0.3.10</code> on the cluster.</p>
<p>How do I resolve the exception and apply the function spark DataFrame?</p>
<p><a href="https://databrickslabs.github.io/mosaic/api/spatial-indexing.html" rel="nofollow noreferrer">https://databrickslabs.github.io/mosaic/api/spatial-indexing.html</a></p>
<p><a href="https://docs.databricks.com/sql/language-manual/functions/h3_boundaryaswkt.html#examples" rel="nofollow noreferrer">https://docs.databricks.com/sql/language-manual/functions/h3_boundaryaswkt.html#examples</a></p>
|
<python><apache-spark><pyspark><databricks><h3>
|
2023-05-15 21:10:23
| 1
| 2,022
|
kms
|
76,257,899
| 6,084,014
|
Getting numpy to run in parallel
|
<p>I'm trying to use the <a href="https://github.com/brianhie/scanorama" rel="nofollow noreferrer">scanorama</a> package in R and am having some troubles with the parallelization. The readme of the scanorama package links to <a href="https://roman-kh.github.io/numpy-multicore/" rel="nofollow noreferrer">this</a> set of instructions for how to make sure numpy is using multiple cpus. My situation is a little different because I'm using a miniconda installation of python, but I tried to adapt this.</p>
<p>First, I created the <code>test.py</code> script that is listed in the above link and I ran it. When I run top to check it, I see:</p>
<p><a href="https://i.sstatic.net/Z0v2A.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Z0v2A.png" alt="enter image description here" /></a></p>
<p>Which indicates to me that it's NOT using multiple cpus. I don't have (or am not aware of the location of) the <code>dist-packages</code> referenced in that link, all I can find is <code>/home/lab/miniconda3/lib/python3.7/site-packages/numpy/core</code>, which contains:</p>
<pre><code>_multiarray_tests.cpython-37m-x86_64-linux-gnu.so
_multiarray_umath.cpython-37m-x86_64-linux-gnu.so
</code></pre>
<p>Running <code>ldd</code> on both of those give me:</p>
<pre><code>ldd _multiarray_tests.cpython-37m-x86_64-linux-gnu.so
linux-vdso.so.1 (0x00007ffd0bfb9000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f6d5831c000)
/lib64/ld-linux-x86-64.so.2 (0x00007f6d5870d000)
ldd _multiarray_umath.cpython-37m-x86_64-linux-gnu.so
linux-vdso.so.1 (0x00007fff5a5a8000)
libcblas.so.3 => /home/lab/miniconda3/lib/python3.7/site-packages/numpy/core/../../../../libcblas.so.3 (0x00007f9eb1179000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9eb0ddb000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9eb0bbc000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9eb07cb000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9eb1a4e000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9eb05c7000)
</code></pre>
<p>Which doesn't appear to have any sort of link to openBLAS. I installed openBLAS via conda following <a href="https://anaconda.org/anaconda/openblas" rel="nofollow noreferrer">this link</a>. Additionally, I tried to re-install numpy using the conda-forge version (which <a href="https://numpy.org/install/#numpy-packages--accelerated-linear-algebra-libraries" rel="nofollow noreferrer">this link</a> says should use openBLAS).</p>
<p>In python, if I check the numpy configuration, I get:</p>
<pre><code>Python 3.7.10 (default, Jun 4 2021, 14:48:32)
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> numpy.show_config()
blas_info:
libraries = ['cblas', 'blas', 'cblas', 'blas']
library_dirs = ['/home/lab/miniconda3/lib']
include_dirs = ['/home/lab/miniconda3/include']
language = c
define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
define_macros = [('NO_ATLAS_INFO', 1), ('HAVE_CBLAS', None)]
libraries = ['cblas', 'blas', 'cblas', 'blas']
library_dirs = ['/home/lab/miniconda3/lib']
include_dirs = ['/home/lab/miniconda3/include']
language = c
lapack_info:
libraries = ['lapack', 'blas', 'lapack', 'blas']
library_dirs = ['/home/lab/miniconda3/lib']
language = f77
lapack_opt_info:
libraries = ['lapack', 'blas', 'lapack', 'blas', 'cblas', 'blas', 'cblas', 'blas']
library_dirs = ['/home/lab/miniconda3/lib']
language = c
define_macros = [('NO_ATLAS_INFO', 1), ('HAVE_CBLAS', None)]
include_dirs = ['/home/lab/miniconda3/include']
</code></pre>
<p>Which I'm not entirely sure how to interpret. I can see that there is information regarding blas, but neither <code>/home/lab/miniconda3/lib</code> nor <code>/home/lab/miniconda3/include</code> contain any of the four libraries indicated above.</p>
<p>I also found <a href="https://stackoverflow.com/questions/15639779/why-does-multiprocessing-use-only-a-single-core-after-i-import-numpy">this</a> post and <a href="https://bugs.python.org/issue17038#msg180663" rel="nofollow noreferrer">this</a> about making sure the cpu affinities aren't overwritten. Running through those, however, it appears that all of the cpus ARE available to be used:</p>
<pre><code>>>> import psutil
>>> p = psutil.Process()
>>> p.cpu_affinity()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
>>> all_cpus = list(range(psutil.cpu_count()))
>>> p.cpu_affinity(all_cpus)
>>> p.cpu_affinity()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
</code></pre>
<p>But if I run the above and then run:</p>
<pre><code>import numpy as np
a = np.random.random_sample((size, size))
b = np.random.random_sample((size, size))
n = np.dot(a,b)
</code></pre>
<p>in the same session and check top, I'm still seeing 100% CPU usage and a small amount of memory usage.</p>
<p>The final thing I tried was to use python multiprocessing as described in <a href="https://urban-institute.medium.com/using-multiprocessing-to-make-python-code-faster-23ea5ef996ba" rel="nofollow noreferrer">this link</a>. Here is how it looks in R:</p>
<pre><code># Python module loading in R
library(reticulate)
scanorama <- import("scanorama")
mp <- import("multiprocessing")
pool <- mp$Pool()
# Read in data (list of matrices and list of genes, as described in scanorama usage)
assaylist <- readRDS("./assaylist.rds")
genelist <- readRDS("./genelist.rds")
# Run the scanorama command from within pool$map
integrated.corrected.data <- pool$map(scanorama$correct(assaylist, genelist, return_dense = T, return_dimred = T), range(0,23))
</code></pre>
<p>Which still gives similar <code>top</code> results:</p>
<p><a href="https://i.sstatic.net/8XhDx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8XhDx.png" alt="enter image description here" /></a></p>
<p>I know this isn't the cleanest/most straightforward question due to the interfacing between R and python, but wanted to put this out there to see if anyone had a similar experience or has any tips to point me in the right direction of figuring this out. I appreciate any feedback, thanks!</p>
|
<python><r><numpy><parallel-processing><reticulate>
|
2023-05-15 21:02:14
| 0
| 518
|
Qwfqwf
|
76,257,827
| 9,576,988
|
SQLAlchemy isn't batching rows / using server side cursor via `yield_per`
|
<p>Following documentation, and the code snippet provided from <a href="https://docs.sqlalchemy.org/en/14/core/connections.html#streaming-with-a-fixed-buffer-via-yield-per" rel="nofollow noreferrer">https://docs.sqlalchemy.org/en/14/core/connections.html#streaming-with-a-fixed-buffer-via-yield-per</a> (posted directly below), my query is not being batched into 50_000 rows.</p>
<pre class="lang-py prettyprint-override"><code>with engine.connect() as conn:
result = conn.execution_options(yield_per=100).execute(text("select * from table"))
for partition in result.partitions():
# partition is an iterable that will be at most 100 items
for row in partition:
print(f"{row}")
</code></pre>
<p>Here I am writing the results of a SQL query to a CSV file:</p>
<pre class="lang-py prettyprint-override"><code>with engine.connect() as conn: # connect to database
with open(csv_path, mode='w', newline='') as f:
c = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
c.writerow(columns) # write column headers
result = conn.execution_options(yield_per=50_000).execute(sql_string) # execute query that results in 110k rows, expecting batches of 50k rows
for partition in result.partitions():
for row in tqdm.tqdm(partition): # each partition only has 1 row, when I expect 50k rows
c.writerow(row)
</code></pre>
<p>This <code>sql_string</code> results in 110k rows, so I expect 3 iterations of <code>result.partitions()</code>, however, I am seeing 110k iterations. I fear this is equivalent to DDOS-ing my own SQL Server database.</p>
<p>I've also tried doing this without <code>partitions()</code>, and the same thing happens - no batching.</p>
<pre class="lang-py prettyprint-override"><code> with engine.connect() as conn:
with open(csv_path, mode='w', newline='') as f:
c = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
c.writerow(columns)
for row in tqdm.tqdm(conn.execution_options(yield_per=50_000).execute(sql_string)): # I expect 3 iterations, but I get 110k.
c.writerow(row)
</code></pre>
<p>The server seems to handle this ok, I get 22k iterations / second, but I still wonder, am I DDOS-ing myself?</p>
<p>I am using SQL Alchemy 1.4.42 (<code>pip install --upgrade 'sqlalchemy==1.4.42'</code>) and Microsoft SQL Server 2019 - 15.0.X (X64)</p>
|
<python><sqlalchemy><batch-processing><execute><chunking>
|
2023-05-15 20:48:57
| 1
| 594
|
scrollout
|
76,257,795
| 2,056,201
|
Flask + React, run without `npm run build` every time
|
<p>If I have the Flask <code>App.py</code> pointed to the <code>frontend/build</code> folder, the frontend works fine currently, but I have to rebuild with <code>npm run build</code> every time I make changes to frontend code</p>
<p><code>app = Flask(__name__, static_url_path='', static_folder='frontend/build')</code></p>
<p>I tried changing this to</p>
<p><code>app = Flask(__name__, static_url_path='', static_folder='frontend/public')</code> where the source <code>index.html</code> resides, but this did not work</p>
<p>Is there a way I can run the React frontend without building it every time? For debugging purposes, not for release.</p>
<p>Thanks,</p>
|
<javascript><python><reactjs><flask>
|
2023-05-15 20:41:47
| 1
| 3,706
|
Mich
|
76,257,695
| 10,527,135
|
Aggregate Data Frame After Using Pandas Grouped Map UDF - Java Error
|
<p>My pyspark environment:</p>
<ul>
<li>AWS EMR release label 6.1.0</li>
<li>Spark 3.0.0</li>
<li>Pandas 1.1.0</li>
<li>Pyarrow 0.15.1</li>
<li>Python 3.7.16</li>
</ul>
<p>I am troubleshooting this error in a Jupyter Notebook attached to my cluster.</p>
<p>I have a dataframe called my_df that I am passing to a Pandas Grouped Map function called my_function, which is created using my_schema.</p>
<pre><code>@pandas_udf(my_schema, PandasUDFType.GROUPED_MAP)
def my_function(my_df):
*do stuff*
return my_df
</code></pre>
<p>I am calling my_function in this way:</p>
<pre><code>my_df_new = (my_df.drop('some_column').groupby('some_other_column').apply(my_function))
</code></pre>
<p>With the returned my_df_new, I create a temporary view and use spark sql to query it. <code>select * from my_df_new</code> returns results successfully, but when I try to aggregate, like <code>select count(*) from my_df_new</code>, it throws the java error at bottom.</p>
<p>Here is what I've tried to fix this to no avail:</p>
<ul>
<li>Altering the spark session with the following configurations:
<ul>
<li>"spark.driver.maxResultSize": "0"</li>
<li>"spark.sql.execution.arrow.pyspark.enabled": "true"</li>
<li>"spark.sql.execution.pandas.udf.buffer.size": "2000000000"</li>
<li>"spark.sql.execution.arrow.maxRecordsPerBatch": "33554432"</li>
</ul>
</li>
<li>Updating pyarrow to 1.0.1 and 12.0.0</li>
</ul>
<p>I don't know what else to try. Anyone have any ideas?</p>
<pre><code>An error occurred while calling o147.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 151 in stage 20.0 failed 4 times, most recent failure: Lost task 151.3 in stage 20.0 (TID 14659, ip-xx-xxx-xx-xxx.my_domain.com, executor 47): java.lang.IndexOutOfBoundsException: index: 0, length: 1073741824 (expected: range(0, 0))
at io.netty.buffer.ArrowBuf.checkIndex(ArrowBuf.java:716)
at io.netty.buffer.ArrowBuf.setBytes(ArrowBuf.java:954)
at org.apache.arrow.vector.BaseVariableWidthVector.reallocDataBuffer(BaseVariableWidthVector.java:508)
at org.apache.arrow.vector.BaseVariableWidthVector.handleSafe(BaseVariableWidthVector.java:1239)
at org.apache.arrow.vector.BaseVariableWidthVector.setSafe(BaseVariableWidthVector.java:1066)
at org.apache.spark.sql.execution.arrow.StringWriter.setValue(ArrowWriter.scala:248)
at org.apache.spark.sql.execution.arrow.ArrowFieldWriter.write(ArrowWriter.scala:127)
at org.apache.spark.sql.execution.arrow.ArrayWriter.setValue(ArrowWriter.scala:300)
at org.apache.spark.sql.execution.arrow.ArrowFieldWriter.write(ArrowWriter.scala:127)
at org.apache.spark.sql.execution.arrow.ArrowWriter.write(ArrowWriter.scala:92)
at org.apache.spark.sql.execution.python.ArrowPythonRunner$$anon$1.$anonfun$writeIteratorToStream$1(ArrowPythonRunner.scala:90)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1377)
at org.apache.spark.sql.execution.python.ArrowPythonRunner$$anon$1.writeIteratorToStream(ArrowPythonRunner.scala:101)
at org.apache.spark.api.python.BasePythonRunner$WriterThread.$anonfun$run$1(PythonRunner.scala:383)
at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1932)
at org.apache.spark.api.python.BasePythonRunner$WriterThread.run(PythonRunner.scala:218)
</code></pre>
|
<python><pandas><pyspark><user-defined-functions><pyarrow>
|
2023-05-15 20:22:03
| 1
| 349
|
fjjones88
|
76,257,553
| 14,672,356
|
Control the distance between stacked bars plotly
|
<p>Is there a means to control the distance between the stacked bars in the example below, i.e. between the “cat” and “dog” (black arrow) and between “10 minutes” and “30 minutes” (yellow arrow)?</p>
<pre><code>import plotly.graph_objects as go
x = [
["10 minutes", "10 minutes", "30 minutes", "30 minutes", "60 minutes", "60 minutes"],
["Cat", "Dog", "Cat", "Dog", "Cat", "Dog"]
]
fig = go.Figure()
fig.add_bar(x=x,y=[1,2,3,4,5,6], name="increase")
fig.add_bar(x=x,y=[9,8,7,6,5,4], name="decrease")
fig.add_bar(x=x,y=[5,5,5,5,5,5], name="unchanged")
fig.update_layout(barmode="stack", showlegend=True, template='plotly',
#bargap=0.3,
bargroupgap=0.2,
#height=500,
#width=1000,
)
fig.update_yaxes(ticks='outside',
dtick=2,
ticklen=10,
linewidth=1,
linecolor="black",
tickfont=dict(size=20)
)
fig.update_xaxes(ticks="", tickfont=dict(size=12),
)
fig.show()
</code></pre>
<p>gives</p>
<p><a href="https://i.sstatic.net/MQbpQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MQbpQ.png" alt="Generated plot from code" /></a></p>
|
<python><plotly><stacked-bar-chart><grouped-bar-chart>
|
2023-05-15 19:54:52
| 1
| 353
|
hans
|
76,257,416
| 8,676,226
|
Python Nextion communication delay
|
<p>I have an RPi3 with a Nextion HMI 2.8" display connected through the FT232 converter and I am testing the possibility of reading from it. I would like to call a certain function after pressing a button on the screen. I managed to do it, but there was a lot of delay - I have to hold the button for more than 1 second to receive result on RPi. Do you have any idea how to improve it? On Arduino I use Nextion.h library and I don't have such problem.</p>
<pre><code>import binascii
ser = serial.Serial('/dev/ttyUSB1', 9600)
while True:
if ser.in_waiting > 0:
data = ser.read(ser.in_waiting)
hex_data = binascii.hexlify(data).decode('utf-8')
if hex_data == '65010200ffffff':
print("Button 1")
elif hex_data == '65010300ffffff':
print("Button 2")
elif hex_data == '65010400ffffff':
print("Button 3")```
</code></pre>
|
<python><serial-port><nextion>
|
2023-05-15 19:32:36
| 0
| 321
|
Michal Grzelak
|
76,257,392
| 14,890,683
|
Python Plotly Multi-Box Plot Additional Formatting
|
<p>Looking to annotate a plotly multi-box plot show which datapoints have a value of <code>True</code> for column <code>"is_fail"</code>. Ie. add a red-circle around x, y datapoints where <code>df["is_fail"] == True</code></p>
<pre class="lang-py prettyprint-override"><code>import random
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame(
{
"x": random.choices(range(1, 6), k=100),
"y": random.choices(np.linspace(0, 12, num=1000), k=100),
"group": random.choices(list(map(chr, range(65, 71))), k=100),
"is_fail": random.choices([True, False], k=100),
"points": "all",
}
)
fig = px.box(df, x="x", y="y", color="group")
# code to annotate all df["is_fail"] == True
fig.show()
</code></pre>
<p>Thanks so much for the help!</p>
|
<python><plotly>
|
2023-05-15 19:29:19
| 1
| 345
|
Oliver
|
76,257,356
| 138,169
|
How to download files with different extensions using Beuautiful Soup
|
<p>I have built a web scraper in Python that takes a list of URLs and downloads a file on each page of that URL. When saving the file, the files do not have extensions (though they do open and are readable). It turns out there are several extension types: pdf, .rtf, and .docx. I need to know how to save the file with its original extension so I can better work with the files. The ultimate goal is to convert each file to .txt.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import urllib.request
import pandas as pd
import os
import textract
import glob
#list of urls to visit
commission_links = pd.read_csv(list_of_urls)
url_list = commission_links['Url'].tolist()
for url in url_list:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
link_div = soup.find('div', {'class': 'pull-right v-img dropdown icone-info bgc-comissao'})
file_link = link_div.find('a')['href']
file_response = requests.get(file_link, stream = True)
#extract the file type from the file_link using split and indexing
filename = os.path.basename(file_link)
extension = os.path.splitext(filename)[1]
print(extension)
with open(f"file_{filename}{extension}", "wb") as f:
f.write(file_response.content)
print(f"File saved: file_{filename}{extension}")
</code></pre>
<p>Edit: to test solutions, here are some urls</p>
<pre><code>commission_links = ['https://legis.senado.leg.br/comissoes/reuniao?reuniao=10944&codcol=50',
'https://legis.senado.leg.br/comissoes/reuniao?reuniao=10892&codcol=50',
'https://legis.senado.leg.br/comissoes/reuniao?reuniao=10891&codcol=50',
'https://legis.senado.leg.br/comissoes/reuniao?reuniao=10866&codcol=50',
'https://legis.senado.leg.br/comissoes/reuniao?reuniao=10844&codcol=50']
</code></pre>
|
<python><beautifulsoup>
|
2023-05-15 19:21:42
| 1
| 568
|
Tony C
|
76,257,088
| 850,781
|
Python: How do I find all functions that return tuples explicitly?
|
<p>I would like to find all functions that return an explicit tuple.
E.g.,</p>
<pre><code> ...
return x, y
</code></pre>
<p>would be in, but</p>
<pre><code> ...
return {"x":x, "y":y}
</code></pre>
<p>would be out, so regexp searching for <code>return .*,</code> would return too many false positives.</p>
<p>I suspect that <code>pylint</code>/<code>astroid</code> might do what I want, but I am open to <em>all</em> suggestions.</p>
<p>PS. There are no type annotations - I would rather have something generate them automatically, like in <code>ocaml</code>.</p>
|
<python><refactoring><pylint><astroid>
|
2023-05-15 18:40:59
| 2
| 60,468
|
sds
|
76,256,940
| 9,363,181
|
How to run commands in the docker image via makefile
|
<p>I have a Python project and now I am trying to create a <code>Makefile</code> that should run specific commands, such as <code>apt-get</code>, and access variable values that are passed to make commands as arguments. Below is my <code>Makefile</code> code:</p>
<pre><code>VENV = venvs
PYTHON = $(VENV)/bin/python3
PIP = $(VENV)/bin/pip
run : $(VENV)/bin/activate
$(PYTHON) jobs/first_file.py
$(VENV)/bin/activate:
docker run -it python:3.8-buster /bin/bash
python3 -m venv $(VENV)
$(PIP) install --upgrade pip
$(PIP) install -r requirements.txt
clean :
rm -rf __pycache__
rm -rf $(VENV)
</code></pre>
<p>Now, my intention is to invoke the docker image and run the <code>pip commands</code> and later on all the further commands on that docker image. It also includes connecting to an AWS account whose values would be passed in the make command as arguments.</p>
<p>But when I run make in the project's root directory. It just connects to the docker bash and does nothing. What exactly am I missing here?</p>
|
<python><bash><docker><makefile>
|
2023-05-15 18:18:58
| 3
| 645
|
RushHour
|
76,256,910
| 4,451,315
|
Can all time zones be represented as 'Area/Location'?
|
<p>If I look at</p>
<pre class="lang-py prettyprint-override"><code>import zoneinfo
zoneinfo.available_timezones()
</code></pre>
<p>in Python, then there are:</p>
<ul>
<li>'Area/Location' time zones, such as <code>'US/Mountain'</code>,</li>
<li>abbreviated time zones, such as 'GMT',</li>
<li>other time zones, such as <code>'Cuba'</code></li>
</ul>
<p>Does 'UTC' and 'Area/Location' cover all time zones?</p>
<p>Context: I'm making a library which wraps pandas, and would like to validate what can be passed to pandas as a time zone. Pandas currently accepts fixed offsets like '+01:00' and also abbreviations like <code>'GMT'</code> and <code>'Cuba'</code>.</p>
<p>If I restricted it to <code>'UTC'</code> or <code>'Area/Location'</code> time zones, would that cut off any time zones? All the ones I've seen have an <code>'Area/Location'</code> equivalent: for example, instead of <code>'GMT'</code> users can pass <code>'Europe/London'</code> if they wanted UK time, and instead of <code>'Cuba'</code> they can pass <code>'America/Havana'</code></p>
|
<python><timezone>
|
2023-05-15 18:13:04
| 0
| 11,062
|
ignoring_gravity
|
76,256,900
| 14,509,475
|
Query very slow when using psycopg2 with TimescaleDB
|
<p>I am using psygopg2 to connect to a TimescaleDB instance. I want to query the latest entries from a big table (35 million rows) containing price information of assets with the columns <code>datetime</code>, <code>asset_id</code>, <code>price</code>, <code>created_at</code>:</p>
<pre class="lang-sql prettyprint-override"><code>create table prices
(
datetime timestamptz not null,
asset_id integer references assets (asset_id),
price real not null,
created_at timestamptz not null default now(),
unique (datetime, asset_id)
);
</code></pre>
<p>This table was turned into a TimescaleDB hypertable with</p>
<pre class="lang-sql prettyprint-override"><code>select create_hypertable('"prices"', 'datetime');
</code></pre>
<p>and from <a href="https://www.timescale.com/blog/select-the-most-recent-record-of-many-items-with-postgresql/" rel="nofollow noreferrer">this article</a>'s suggestion created the following index:</p>
<pre class="lang-sql prettyprint-override"><code>create index latest_prices_idx on prices (asset_id, datetime desc);
</code></pre>
<p>I use "Option 3" from this article to query the most recent price of each asset:</p>
<pre class="lang-sql prettyprint-override"><code>select distinct on (asset_id) datetime, asset_id, price
from prices
order by asset_id, datetime desc;
</code></pre>
<p>which takes ~300 ms via my IDE's console. However, when doing the same query via psycopg2 it takes about 10 seconds:</p>
<pre class="lang-py prettyprint-override"><code>cursor.execute("""
select distinct on (asset_id) datetime, asset_id, price
from prices
order by asset_id, datetime desc;
""")
res = cursor.fetchall()
</code></pre>
<p>Why might this be the case?</p>
<p>Prepending <code>explain</code> in front of the query outputs the exact same result for both the IDE and psycopg.</p>
<p><strong>Edit</strong>: Answers to questions/suggestions in the comments:</p>
<ul>
<li>The database is running in a local docker container.</li>
<li>The IDE is PyCharm, I do the queries from its database console and from a Python script within the IDE.</li>
<li>Using a server side cursor (<a href="https://stackoverflow.com/a/48734989/14509475">like this</a>) did not change anything.</li>
<li>PyCharm gives the query time in its console output. For getting the time of the Python code, I measure the execution time of the <code>cursor.execute(...)</code> call with <code>time.perf_counter()</code>.</li>
<li>Using psql in the shell in the container has the <em>bad</em> performance as well (~10 s).</li>
<li>When dropping the index the performance flips: psql and psycopg take about 6 seconds, PyCharm's console about 13 seconds. The original behavior is reproducible when re-creating the index.</li>
</ul>
|
<python><sql><postgresql><psycopg2><timescaledb>
|
2023-05-15 18:10:35
| 0
| 496
|
trivicious
|
76,256,897
| 21,420,742
|
How to make a conditional statement using two different dataframes in pandas
|
<p>I have two datasets first one is all employees and who thet report to. The second dataset is all managers with non active employees.</p>
<p>DF1</p>
<pre><code> ID Name Status Manager ID Manager Name
101 Ashley Active 106 Kyle
102 Ben Non-Active 106 Kyle
103 Chris Non-Active 123 Taylor
104 Dave Non-Active 123 Taylor
105 Emily Active 167 Paul
</code></pre>
<p>DF2</p>
<pre><code>Manager_ID Manager_Name Replacing Request Num
106 Kyle Ben 5678
138 Taylor Dave 1234
</code></pre>
<p>I want to create a new column called <code>Vacancy</code> that shows if <code>ID</code> in DF1 is Non-Active and not in DF2 then vacant.</p>
<p>Desired Output</p>
<pre><code> Manager_ID Manager_Name Vacancy
106 Kyle 0
123 Taylor 1
167 Paul 0
</code></pre>
<p>I have tried:</p>
<p><code>np.where(((df1['Status'] == 'Non-Active') & (df2['Replacing'].isna())),1,0)</code></p>
<p>Any suggestions? Please and thank you.</p>
|
<python><pandas><dataframe>
|
2023-05-15 18:10:32
| 2
| 473
|
Coding_Nubie
|
76,256,864
| 209,882
|
Enforce reduced logging from certain logging sources for Python/PySpark applications
|
<p>I'm running a Spark application for which I want to have INFO level logging.</p>
<p>However, along with my application logs, it seems like other loggers are producing massive amounts of output on the INFO level, drowning out the useful information I'm trying to log. Example:</p>
<pre><code>[/var/log/yarn/userlogs/application_1683930949263_0001/container_1683930949263_0001_01_000009/stderr] 2023-05-13 00:10:40,556 INFO executor.Executor: Finished task 389.0 in stage 1043.0 (TID 146334). 3284 bytes result sent to driver
[/var/log/yarn/userlogs/application_1683930949263_0001/container_1683930949263_0001_01_000009/stderr] 2023-05-13 00:10:40,556 INFO storage.ShuffleBlockFetcherIterator: Getting 0 (0.0 B) non-empty blocks including 0 (0.0 B) local and 0 (0.0 B) host-local and 0 (0.0 B) remote blocks
[/var/log/yarn/userlogs/application_1683930949263_0001/container_1683930949263_0001_01_000009/stderr] 2023-05-13 00:10:40,556 INFO storage.ShuffleBlockFetcherIterator: Started 0 remote fetches in 0 ms
[/var/log/yarn/userlogs/application_1683930949263_0001/container_1683930949263_0001_01_000009/stderr] 2023-05-13 00:10:40,556 INFO mapred.SparkHadoopMapRedUtil: No need to commit output of task because needsTaskCommit=false: attempt_202305130010406528291275413594211_1043_m_000243_146190
[/var/log/yarn/userlogs/application_1683930949263_0001/container_1683930949263_0001_01_000009/stderr] 2023-05-13 00:10:40,557 INFO executor.Executor: Finished task 243.0 in stage 1043.0 (TID 146190). 3284 bytes result sent to driver
</code></pre>
<p>Is there an easy way to filter the logs <em>not</em> coming from my application logger (assuming I can figure out which one it is) so that only the logs I create are produced?</p>
|
<python><apache-spark><logging><log4j>
|
2023-05-15 18:06:41
| 1
| 2,826
|
Bar
|
76,256,796
| 10,637,188
|
What is the proper way to implement retry behavior on a python client?
|
<p>I often run into the task of writing some sort of wrapper for a python client. For example, I might write a wrapper for the Spotipy module to encapsulate credentials and/or specific data transformations etc. I also might write a wrapper for the requests module to interact with my api. Regardless, this is a common task...</p>
<p>One of the most common features that is part of writing these types of client, is some sort of retry behavior if the request fails. On the surface, this is a very simple task - you just encapsulate the request in a while loop that breaks when the request succeeds or the retry limit is reached. However, because I write so many methods and separate classes that all need this exact behavior, it's obviously something I'd rather turn into a decorator that I can implement in any client wrapper.</p>
<p>I imagine there's a standard way of doing this, given that it seems like one of the most common features of a client. Does anybody know of a good, clean way of implementing this behavior such that whenever I write a client method, I can just wrap it like so:</p>
<p>(This is pure pseudo-code, I know this doesn't work, this is just a way I might imagine it happening)</p>
<pre><code>
class Retry:
def __init__(self, max_retries=3, delay=1):
self.max_retries = max_retries
self.delay = delay
def __call__(self, func):
def wrapper(*args, **kwargs):
for i in range(self.max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
if i == self.max_retries - 1: # If this was the last attempt
raise # Re-raise the last exception
time.sleep(self.delay) # Wait for a bit before retrying
return wrapper
class MyAPIClass:
def __init__(self, max_retries=3, delay=1):
self.retry = Retry(max_retries, delay)
@retry
def method_that_might_fail(self):
# Code that might raise an exception
pass
</code></pre>
<p>The code fails because <code>@retry</code> is a class method which requires <code>self</code> as a parameter which isn't defined yet.</p>
<p>I've been trying to use chatGPT to figure out a method that works, but I keep going in circles always running into some sort of problem like this.</p>
<p>Does anybody know of a good clean way of decoupling the retry behavior so that it can be implemented in any client wrapper?</p>
|
<python>
|
2023-05-15 17:57:57
| 1
| 868
|
Alec Mather
|
76,256,790
| 3,977,233
|
Different results when plotting histogram using DataFrame.plot.hist and Series.plot.hist
|
<p>The data for this question can be downloaded from <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/00492/Metro_Interstate_Traffic_Volume.csv.gz" rel="nofollow noreferrer">University of California Irvine</a>.</p>
<pre><code>import pandas as pd
i_94 = pd.read_csv('./Downloads/Guided_Project_ Finding_Heavy_Traffic_Indicators_on I-94/Metro_Interstate_Traffic_Volume.csv')
import matplotlib.pyplot as plt
%matplotlib inline # for my Jupyter notebook
i_94.plot.hist(column='traffic_volume', bins=10)
traffic_volume = i_94['traffic_volume']
traffic_volume.plot.hist(bins=10)
</code></pre>
<p>That's all my code. I assumed that my histograms should be identical since they're both plotting the same column. However, I'm seeing the following</p>
<p><a href="https://i.sstatic.net/la24M.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/la24M.png" alt="enter image description here" /></a></p>
<p>Why are the two histograms different?</p>
<p>Quickly load the sample data</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import requests
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00492/Metro_Interstate_Traffic_Volume.csv.gz'
file = 'Metro_Interstate_Traffic_Volume.csv.gz'
content = requests.get(url).content
with open(file, 'wb') as f:
f.write(content)
i_94 = pd.read_csv(file, compression='gzip')
</code></pre>
|
<python><pandas><histogram>
|
2023-05-15 17:57:40
| 1
| 2,384
|
Gwater17
|
76,256,748
| 12,603,110
|
Huggingface, The illogical question why "WordLevelTrainer can only train a WordLevel"?
|
<p>As part of an NLP course I was provided this code:</p>
<pre><code>MIN_FREQ = 3 # words appearing fewer than 3 times are treated as 'unknown'
unk_token = '[UNK]'
pad_token = '[PAD]'
tokenizer = Tokenizer(WordLevel(unk_token=unk_token))
tokenizer.pre_tokenizer = Whitespace()
tokenizer.normalizer = normalizers.Lowercase()
trainer = WordLevelTrainer(min_frequency=MIN_FREQ, special_tokens=[pad_token, unk_token])
tokenizer.train_from_iterator(train_data['text'], trainer=trainer)
</code></pre>
<p>And I wondered "why is the trainer split from the model? why would you want to be able to train a model with the wrong trainer?" so I did the only reasonable thing one has to do and changed the models and trainers.</p>
<p>Short story shorter, they only train their own respective models and error out otherwise.
eg: "WordLevelTrainer can only train a WordLevel"</p>
<p>Thus I ask again, why are they, interface-wise two different objects and are initialized in different parts of the code? what benefit is there other than my own perplexity about software engineering?</p>
|
<python><huggingface-tokenizers><huggingface>
|
2023-05-15 17:52:28
| 0
| 812
|
Yorai Levi
|
76,256,710
| 959,460
|
Python requests_oauthlib OAUTH V2 BackendClient fetch_token() error
|
<p>I am attempting to use the BackendClient workflow for creating a OAUTH V2.0 connection. Using the requests_oauthlib package. Documentation is at: <a href="https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow" rel="nofollow noreferrer">https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow</a></p>
<p>The code works fine in PowerShell, but the equivalent in python is giving the error:</p>
<pre><code> token = session.fetch_token(token_url=tokenURL, client_id=ClientID, client_secret=secret)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\1455765990E\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests_oauthlib\oauth2_session.py", line 251, in fetch_token
raise ValueError(
ValueError: Please supply either code or authorization_response parameters.
</code></pre>
<p>It makes no sense to ask for a response url (since this is a backend workflow) and the code is what the fetch_token is going to give, so I don't have one yet!</p>
<p>This is the PowerShell that works fine:</p>
<pre><code>function GetToken($secret) {
$uri = $LoginURL + $tenant + '/oauth2/v2.0/token'
$body = @{
"client_id" = $ClientID
"scope" = "https://dod-graph.microsoft.us/.default"
"username" = $tenant
"password" = $client_secret
"grant_type" = "client_credentials"
"client_secret" = $secret
}
$response = Invoke-RestMethod -Uri $uri -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
return $response
$token = $response.access_token
$exp = $response.expires_in
$token
}
</code></pre>
<p>and this is what we think is the equivalent in Python</p>
<pre><code>def getToken(store):
""" Get OAUTH Token and session"""
tokenURL = LoginURL + TenantID + '/oauth2/v2.0/token'
scope = "https://dod-graph.microsoft.us/.default"
client = oauthlib.oauth2.BackendApplicationClient(client_id=ClientID, scope=scope)
session = requests_oauthlib.OAuth2Session(client)
session.verify = False
secret = store['secret']
print(f"--token URL: {tokenURL}")
token = session.fetch_token(token_url=tokenURL, client_id=ClientID, client_secret=secret)
print(f"--token: {token}")
return session
</code></pre>
|
<python><oauth-2.0><requests-oauthlib>
|
2023-05-15 17:48:23
| 1
| 7,671
|
Dr.YSG
|
76,256,656
| 1,662,332
|
Watson Discovery v2, count documents into a collection
|
<p>I know that this might be trivial, but I need to find a simple way to count documents within a Watson Discovery Collection (v2).</p>
<p>Before moving to v2, this is what I used to do:</p>
<pre><code>## Discovery v2
def collection_length(env, collection):
total = 0
for coll in collection:
details = discovery.get_collection(env).get_result()
total += details["document_counts"]["available"]
return total
</code></pre>
<p>The same method into Watson SDK using Discovery v2 does not have any field for counting. I cannot query the whole collection and manually counts document since it takes a lot of time (timeout risk!).</p>
|
<python><ibm-watson><watson-discovery>
|
2023-05-15 17:41:11
| 1
| 732
|
Giacomo Bartoli
|
76,256,504
| 12,363,158
|
How can I convert a spatial dataset (raster and vector) to COCO format for object detection?
|
<p>I am doing an object detection project using detectron2, which requires datasets to be in COCO format. This format needs images as png and polygons in a JSON file. However, spatial images (e.g. satellites or drones) are georeferenced (<code>tif</code> format), and the annotations/labels also have geographical coordinates (<code>shp</code>/<code>geojson</code> format). Getting a regular image from a <code>tif</code> file is pretty straightforward using <code>rasterio</code> and <code>numpy</code>, but getting the annotations in the correct coordinate system has been difficult because they need to point to the position of the polygons in the <code>png</code>, not the georeferenced image.</p>
<p>As an example, say I have a 300*300 px satellite image bounded by these coordinates: 75W 10N, 70W 5N. The coordinates of the polygons will be within the region of the geographical box. Once I transform the geo-image to a normal image, it will lose its geographical reference, so the coordinates of the polygons should be in (0, 300), (0, 300).</p>
<p>Is there a way to translate the polygons from geographical coordinates to positional coordinates in an image so that I can make a dataset in COCO format?</p>
|
<python><deep-learning><gis><geospatial><detectron>
|
2023-05-15 17:20:27
| 0
| 497
|
Andres Camilo Zuñiga Gonzalez
|
76,256,434
| 338,248
|
SSL error on file upload with HTTP chunked encoding
|
<p>Trying to upload file using chunked encoding manner .</p>
<p>Getting the following error</p>
<pre><code>urllib3.exceptions.SSLError: EOF occurred in violation of protocol (_ssl.c:2423)
</code></pre>
<p>Below is the code</p>
<pre><code>from io import BytesIO
import requests
from werkzeug.datastructures import FileStorage
def test_upload_large_file():
file_data = BytesIO(b'0' * (25 * 1024 * 1024))
file = FileStorage(stream=file_data, filename='test.txt')
headers = {'Transfer-Encoding': 'chunked'}
url = "<url>"
response = requests.post(url, headers=headers, files={'file': file})
print(response.status_code)
assert response.status_code == 200
test_upload_large_file()
</code></pre>
<p>However i change from chunked encoding to 'Content-Type': 'multipart/form-data', it works.</p>
<p>Not sure why chunked encoding is throwing SSL error. I understand every HTTP 1.1 server supports chunked encoding and does not need any enabling.</p>
<p>I am new to python , hence might be missing something.</p>
<p><strong>UPDATE</strong></p>
<p>Based on the answer i rewrote the code to below where the content is picked up from a file but i still get the same error</p>
<pre><code>import requests
def upload_file_chunked(url, file_path, chunk_size):
with open(file_path, 'rb') as file:
headers = {'Transfer-Encoding': 'chunked'}
response = requests.post(url, headers=headers, data=file, stream=True)
print("Response Code:", response.status_code)
print("Response:", response.text)
# Example usage
url = "<url>"
file_path = "<file-path>"
chunk_size = 1024 # Specify the desired chunk size in bytes
upload_file_chunked(url, file_path, chunk_size)
</code></pre>
|
<python>
|
2023-05-15 17:11:16
| 1
| 6,056
|
saurav
|
76,256,412
| 8,079,611
|
Altair - Remove ellipsis ("...") from legend with long strings
|
<p>Via Python, I am using Altair to plot bar graphs. I was able to move the legend to be at the top, however, it is adding ellipsis (i.e. "...") at the end of each legend because my strings are too long. Is there any work around this? I tried <code>gradientlength</code> but it does not do the trick. Also, and as my strings are pretty long, would be possible to jump lines between each legend?</p>
<pre><code>alt.Chart(df).mark_bar().encode(
x=alt.X("fund:O", axis=alt.Axis(title=None, labels=False, ticks=False)),
y=alt.Y("value:Q", axis=alt.Axis(title="Percentage", grid=True)),
color=alt.Color("fund:N", legend=alt.Legend(orient="top")),
tooltip=["data point info:O", "fund:N", "value", "bucket"],
column=alt.Column(
"bucket:N",
header=alt.Header(title=None, labelOrient="bottom", labelAngle=x_angle),
sort=list_to_sort,
spacing=40,
),
).configure_view(stroke="transparent").interactive()
</code></pre>
<p>This is how it current looks like:</p>
<p><a href="https://i.sstatic.net/pKPUw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pKPUw.png" alt="enter image description here" /></a></p>
<p>One example of the legends is:</p>
<ul>
<li>"Morningstar - FOUSA08OZU: Vanguard Total Bond Market II Index Fund Institutional Shares"</li>
</ul>
<p>Documentation is here - <a href="https://altair-viz.github.io/user_guide/generated/core/altair.Legend.html" rel="nofollow noreferrer">https://altair-viz.github.io/user_guide/generated/core/altair.Legend.html</a></p>
<p>Similar ish question - <a href="https://stackoverflow.com/questions/55443485/changing-size-of-legend-in-altair">Changing Size of Legend in Altair</a></p>
|
<python><legend><altair>
|
2023-05-15 17:08:55
| 1
| 592
|
FFLS
|
76,256,407
| 10,164,750
|
Match the string data inside a group - Pandas
|
<p>I have dataframe like this:</p>
<pre><code>+--------+------------+----------+--------------+--------------+----------------+--------------+--------------+
| company| id|ann_rtn_dt|share_class_nb|shrhldr_seq_nb|shrhldr_first_nm|shrhldr_mid_nm|shrhldr_sur_nm|
+--------+------------+----------+--------------+--------------+----------------+--------------+--------------+
|SYNTHE01|SYNTHE01_1_1|2022-11-28| 1| 1| NIEL| ANDREW| HOPSON|
|SYNTHE01|SYNTHE01_3_1|2022-11-28| 3| 1| NICOLE| CLAIRE| MORE|
|SYNTHE01|SYNTHE01_1_2|2022-11-28| 1| 2| N| C| MORE|
|SYNTHE01|SYNTHE01_2_1|2022-11-28| 2| 1| NEIL| ANDREW| HOPSON|
|SYNTHE01|SYNTHE01_3_1|2022-11-28| 3| 1| NICOLE| CLAIRE| MORE|
|SYNTHE02|SYNTHE02_1_1|2022-11-28| 1| 1| MIKE| | LOPSON|
|SYNTHE02|SYNTHE02_3_1|2022-11-28| 3| 1| NIMIKE| | LOPSON|
|SYNTHE02|SYNTHE02_1_2|2022-11-28| 1| 2| MIKE| | LOPSON|
|SYNTHE02|SYNTHE02_2_1|2022-11-28| 2| 1| MIKE| | LOPSON|
+--------+------------+----------+--------------+--------------+----------------+--------------+--------------+
</code></pre>
<p>The whole dataframe can be grouped 2 distinct <code>company</code> column i.e. <code>SYNTE01</code> and <code>SYNTHE02</code>.</p>
<p>My use case is to do matching inside the <code>company</code>.</p>
<p><code>STATUS_1</code> is set to <code>min</code> of <code>id</code>, when there is full match of <code>shrhldr_first_nm</code>, <code>shrhldr_mid_nm</code> and <code>shrhldr_sur_nm</code> in the grouop.</p>
<p><code>STATUS_2</code> is set to <code>min</code> of <code>id</code>, when there is match of first byte of <code>shrhldr_first_nm</code> and <code>shrhldr_mid_nm</code> in the group. And <code>shrhldr_sur_nm</code> matches exactly.</p>
<p>For eg. in <code>COMPANY</code> <code>SYNTHE01</code>, NIEL ANDREW HOPSON in row1 matches with NIEL ANDREW HOPSON in row4. The column <code>STATUS_1</code> is set to <code>min</code> of <code>id</code> column for both.</p>
<p>For eg. in <code>COMPANY</code> <code>SYNTHE01</code>, the first byte of NICOLE CLAIRE MORE in row2 matches with N C More in row3. The column <code>STATUS_2</code> is set to <code>min</code> of <code>id</code> column for both.</p>
<p>My output dataframe would look like below:</p>
<pre><code>+--------+------------+----------+--------------+--------------+----------------+--------------+--------------+-------------+-------------+
| company| id|ann_rtn_dt|share_class_nb|shrhldr_seq_nb|shrhldr_first_nm|shrhldr_mid_nm|shrhldr_sur_nm| STATUS_1| STATUS_2|
+--------+------------+----------+--------------+--------------+----------------+--------------+--------------+-------------+-------------+
|SYNTHE01|SYNTHE01_1_1|2022-11-28| 1| 1| NIEL| ANDREW| HOPSON| SYNTHE01_1_1| |
|SYNTHE01|SYNTHE01_3_1|2022-11-28| 3| 1| NICOLE| CLAIRE| MORE| SYNTHE01_3_1| SYNTHE01_1_2|
|SYNTHE01|SYNTHE01_1_2|2022-11-28| 1| 2| N| C| MORE| | SYNTHE01_1_2|
|SYNTHE01|SYNTHE01_2_1|2022-11-28| 2| 1| NEIL| ANDREW| HOPSON| SYNTHE01_1_1| |
|SYNTHE01|SYNTHE01_3_2|2022-11-28| 3| 1| NICOLE| CLAIRE| MORE| SYNTHE01_3_1| SYNTHE01_1_2|
|SYNTHE02|SYNTHE02_1_1|2022-11-28| 1| 1| MIKE| | LOPSON| SYNTHE02_1_1| |
|SYNTHE02|SYNTHE02_3_1|2022-11-28| 3| 1| NIMIKE| | LOPSON| | |
|SYNTHE02|SYNTHE02_1_2|2022-11-28| 1| 2| MIKE| | LOPSON| SYNTHE02_1_1| |
|SYNTHE02|SYNTHE02_2_1|2022-11-28| 2| 1| MIKE| | LOPSON| SYNTHE02_1_1| |
+--------+------------+----------+--------------+--------------+----------------+--------------+--------------+-------------+-------------+
</code></pre>
<p>We tried this in <code>Pyspark</code>, could not achieve it. We are now trying to do it in <code>Pandas</code>. Please suggest any possible approach. Thank you.</p>
|
<python><pandas>
|
2023-05-15 17:07:50
| 1
| 331
|
SDS
|
76,256,380
| 2,547,570
|
Python dtrace + bpftrace
|
<p>I built Python 3.12 with dtrace support and <code>python:function__entry</code> is not properly called.</p>
<p><code>python:line</code> probe works well, but <code>python:function__entry</code> rarely prints things.</p>
<pre><code>❯ sudo bpftrace -e 'usdt:/usr/lib/libpython3.12.so.1.0:python:line { printf("%s %s %d\n", str(arg0), str(arg1), arg2); }'
❯ sudo bpftrace -e 'usdt:/usr/lib/libpython3.12.so.1.0:python:function__entry { printf("%s %s\n", str(arg0), str(arg1)); }'
❯ python3.12 -m http.server
Attaching 1 probe...
<frozen getpath> <genexpr>
<frozen getpath> <genexpr>
/usr/lib/python3.12/enum.py <genexpr>
/usr/lib/python3.12/enum.py <genexpr>
/usr/lib/python3.12/enum.py <genexpr>
/usr/lib/python3.12/enum.py <genexpr>
/usr/lib/python3.12/email/_policybase.py <genexpr>
/usr/lib/python3.12/email/_policybase.py <genexpr>
/usr/lib/python3.12/email/_policybase.py <genexpr>
/usr/lib/python3.12/email/_policybase.py <genexpr>
/usr/lib/python3.12/email/_policybase.py <genexpr>
</code></pre>
<p>Also bcc's <code>ustats</code> and <code>ucalls</code> attach but report nothing.</p>
<pre><code>PID CMDLINE METHOD/s GC/s OBJNEW/s CLOAD/s EXC/s THR/s
6857 /bin/python /home/xx 0 0 0 0 0 0
</code></pre>
<p>I expected it to print every python function call. Why is it skipping most calls?</p>
|
<python><linux><ebpf><bpf><bcc>
|
2023-05-15 17:03:59
| 1
| 1,319
|
mq7
|
76,256,290
| 1,176,873
|
Why does chrome driver chrash in ubuntu WSL?
|
<p>Trying to get a simple selenium script working</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-dev-shm-usage')
print("options assigned")
path = '/usr/bin/chromedriver'
browser = webdriver.Chrome(executable_path=path, options=chrome_options)
</code></pre>
<p>I get this error:</p>
<pre><code>python testscript.py
/home/guc3xq/anaconda3/envs/sas/lib/python3.9/site-packages/requests/__init__.py:109: RequestsDependencyWarning: urllib3 (1.26.15) or chardet (5.1.0)/charset_normalizer (2.0.12) doesn't match a supported version!
warnings.warn(
options assigned
Traceback (most recent call last):
File "/home/guc3xq/dev/chromedriverdev/testscript.py", line 14, in <module>
browser = webdriver.Chrome(executable_path=path, options=chrome_options)
File "/home/guc3xq/anaconda3/envs/sas/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 76, in __init__
RemoteWebDriver.__init__(
File "/home/guc3xq/anaconda3/envs/sas/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "/home/guc3xq/anaconda3/envs/sas/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/home/guc3xq/anaconda3/envs/sas/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/guc3xq/anaconda3/envs/sas/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed.
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
</code></pre>
<p>ChromeDriver 113.0.5672.63
Google Chrome 113.0.5672.92</p>
<p>I tried downgrading too and that doesn't work</p>
<p>Running with Python 3.9 Ubuntu WSL as root user (I tried non-root but I can't install all the things I need)</p>
|
<python><google-chrome><selenium-webdriver><selenium-chromedriver><windows-subsystem-for-linux>
|
2023-05-15 16:50:43
| 1
| 2,425
|
mogoli
|
76,256,099
| 11,913,986
|
Pyspark window function to generate rank on data based on sequence of the value of a column
|
<p>I have a dataframe df as :</p>
<pre><code>df =
A B type
X 11 typeA
X 12 typeA
X 13 typeB
X 14 typeB
X 15 typeC
X 16 typeC
Y 17 typeA
Y 18 typeA
Y 19 typeB
Y 20 typeB
Y 21 typeC
Y 22 typeC
</code></pre>
<p>Now I want to create a new column rank where based on the window partition of column 'A' and order by column 'type'.</p>
<p>But I want a specific sequence, typeA - typeB - typeC - typeA - typeB - typeC----.
The result dataframe I am looking for is:</p>
<pre><code>result =
A B type rank
X 11 typeA 1
X 13 typeB 2
X 15 typeC 3
X 12 typeA 4
X 14 typeB 5
X 16 typeC 6
Y 17 typeA 1
Y 19 typeB 2
Y 21 typeC 3
Y 18 typeA 4
Y 20 typeB 5
Y 22 typeC 6
</code></pre>
<p>What I am doing right now:</p>
<pre><code>from pyspark.sql import Window
result = (df
.withColumn("rank", row_number()
.over(Window.partitionBy('A')
.orderBy(col('type').desc())
)
)
).persist()
</code></pre>
<p>Which comes not quite the sequence I am looking for.</p>
<pre><code>A B type rank
X 11 typeA 1
X 12 typeA 2
X 13 typeB 3
X 14 typeB 4
X 15 typeC 5
X 16 typeC 6
Y 17 typeA 1
Y 18 typeA 2
Y 19 typeB 3
Y 20 typeB 4
Y 21 typeC 5
Y 22 typeC 6
</code></pre>
<p>Any idea on how to generate the sequence when defining the window function?</p>
|
<python><dataframe><join><pyspark><apache-spark-sql>
|
2023-05-15 16:23:23
| 1
| 739
|
Strayhorn
|
76,255,977
| 3,541,631
|
Compact/simplify code where multipe conditions force repeating the code, and replace passing a multiple dict to be modified
|
<p>I have the code below:</p>
<p>In the code I have multiple branches/conditions and some repeated code(<code>process</code>).
I'm looking if is possible for a more compact version.</p>
<p>Also in the <code>process</code> function a defaultdict(mutable) is passed as an argument(to function process), which I don't like it, I'm trying to find a solution with no side effect that doesn't complicate the code.</p>
<pre><code># data iterable
direct_cotainer = defaultdict(set)
if config.a: #check a bool value in a config
a = get_a() # get from a file or database - abstract -an iterable
if not a: #
# log something
return
else: # a has elements
for el in a:
if valid(el):
proces(el, direct_container)
else:
for el in a:
proces(el, direct_container)
# ===================================
def proces(el, direct_container)
rel = self.get_rel(el)
if rel is None:
add_without_rel(el)
else:
direct_container["32"].add(rel)
</code></pre>
|
<python><python-3.x>
|
2023-05-15 16:06:30
| 0
| 4,028
|
user3541631
|
76,255,967
| 5,924,264
|
Is there a way to inherit a class only if a runtime flag is true in python?
|
<p>I would like to have an existing class <code>A</code> inherit <code>B</code> only if a runtime flag is turned on. Is this possible?</p>
<p>Usually for these cases, I either</p>
<ol>
<li><p>Just have <code>A</code> inherit <code>B</code> by default, and not use <code>B</code> if that flag is False</p>
</li>
<li><p>Create another class <code>A_mod</code>, that inherits from <code>A</code> and <code>B</code>, and use this class when that flag is true.</p>
</li>
</ol>
|
<python>
|
2023-05-15 16:04:45
| 3
| 2,502
|
roulette01
|
76,255,952
| 2,987,488
|
Always infeasible solution in or-tools scheduling problem
|
<p>Let a list of predefined hubs with each one having a specific demand in drivers, a set of drivers and the relationship between drivers and hubs. In my example the number of drivers is way higher than the number of hubs, i.e. 400 vs 45 hubs and their demand per day is around 250 drivers. I set the constraint that each driver must have a day off as well. However, I do not get a solution to the problem and to facilitate the solution further, I even set that each driver can work at any hub (driver_hubs_relationships) and still DO not get a solution. Any ideas?</p>
<pre><code>def create_schedule(drivers,
hubs,
hubs_and_demand,
driver_hubs_relationships):
drivers_list = copy.deepcopy(drivers)
hubs_list = copy.deepcopy(hubs)
hubs_list_and_demand = copy.deepcopy(hubs_and_demand)
driver_hubs_list_relationships = copy.deepcopy(driver_hubs_relationships)
model = cp_model.CpModel()
# Define an extra "hub" that represents a day off
hubs_list.append('OFF')
for e in drivers_list:
driver_hubs_list_relationships[e].append('OFF')
# Create variables total size len(drivers)*(1+len(hubs))*len(days)
schedule = {}
for e in drivers_list:
for d in days:
for r in hubs_list:
schedule[(e, d, r)] = model.NewBoolVar(f'schedule_{e}_{d}_{r}')
# Define a variable for each day representing the number of drivers having that day off
off_days = {d: model.NewIntVar(0, len(drivers_list), f'off_{d}') for d in days}
# Add constraints to link the off_days variable with the schedule variable
for d in days:
model.Add(off_days[d] == sum(schedule[(e, d, 'OFF')] for e in drivers_list))
# Add a constraint to distribute the off days evenly across the week
average_off_days = len(drivers_list) // len(days)
for d in days:
model.Add(off_days[d] >= average_off_days)
# Each driver must have one day off per week
for e in drivers_list:
model.Add(sum(schedule[(e, d, 'OFF')] for d in days) == 1)
# Each driver works at most one day at a specific hub
for e in drivers_list:
for d in days:
model.Add(sum(schedule[(e, d, r)] for r in hubs_list) == 1)
# Create variables for the number of drivers needed at each hub on each day
drivers_needed = {}
for d in days:
for r in hubs_list:
if r != 'OFF':
hub_demand = hubs_list_and_demand.loc[hubs_list_and_demand['hub'] == r, 'drivers_needed']
if len(hub_demand) > 0:
drivers_needed_at_hub = int(hub_demand.values[0])
else:
drivers_needed_at_hub = 0 # or some other default value
drivers_needed[(d, r)] = model.NewIntVar(drivers_needed_at_hub,
int(hubs_list_and_demand.max().values[1]),
f'drivers_needed_{d}_{r}')
# Each hub needs to have the required number of drivers each day
for d in days:
for r in hubs_list:
if r != 'OFF':
model.Add(10 * sum(schedule[(e, d, r)] for e in drivers_list) >=
9 * drivers_needed[(d, r)])
# Assign each driver to their specific hub
for e in drivers_list:
for r in hubs_list:
if r not in driver_hubs_list_relationships[e]:
for d in days:
model.Add(schedule[(e, d, r)] == 0)
# Solve and print schedule
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = 500.0
solver.parameters.log_search_progress = True
status = solver.Solve(model)
print(f"status code {status}")
if status == cp_model.OPTIMAL:
solution = {}
for e in drivers_list:
solution[e] = {}
for d in days:
for r in hubs_list:
if solver.Value(schedule[(e, d, r)]) == 1:
print(f"{e} works at {r} on {d}")
solution[e][d] = r
return solution
else:
return None
</code></pre>
|
<python><optimization><scheduling><or-tools>
|
2023-05-15 16:02:46
| 1
| 1,272
|
azal
|
76,255,853
| 344,669
|
Python 3.10.10 extracting filename from fullpath, not working with Path
|
<p>Using <code>Python 3.10.10</code> I want to extract file name from fullpath, using <code>Path</code> from <code>pathlib</code> module.</p>
<p>From below code, I expect to get <code>test.pdf</code> name, but this code prints full pathname</p>
<pre><code>from pathlib import Path
Path(r"C:\Users\work\test.pdf").name
</code></pre>
<blockquote>
<p>'C:\Users\work\test.pdf'</p>
</blockquote>
<p>May I know why it's not giving the filename from above path? How to get the file from full path name?</p>
<p>Thanks</p>
|
<python><python-3.x><pathlib>
|
2023-05-15 15:51:09
| 1
| 19,251
|
sfgroups
|
76,255,692
| 7,684,584
|
Oracle NetSuit ERP Connect Using Python
|
<p>I am trying to connect with Oracle ERP Netsuit using a JDBC driver in python code but it is giving me an error below, also I am not sure about connection string if its the correct way of setting up.</p>
<p>Error:</p>
<pre><code>Connection error: java.sql.SQLNonTransientConnectionException: Internal network error, connection closed.
</code></pre>
<p>Code:</p>
<pre><code>import jaydebeapi
def main():
connection = None
try:
# Load the Netsuite JDBC driver
driver = "com.netsuite.jdbc.openaccess.OpenAccessDriver"
jar_path = "NQjc.jar" # Path to the NQjc.jar file
conn_str = "jdbc:ns://https://<ServiceHost>:1708;" \
"ServerDataSource=NetSuite.com;" \
"Encrypted=1;" \
"NegotiateSSLClose=false;" \
"CustomProperties=(AccountID=<accountID>;RoleID=1000)"
user = "USERNAME"
password = "PASSWORD"
# Establish the connection
connection = jaydebeapi.connect(driver, conn_str, [user, password], jars=jar_path)
print("Connection success")
except Exception as e:
print(f"Connection error: {str(e)}")
finally:
if connection is not None:
connection.close()
if __name__ == "__main__":
main()
</code></pre>
|
<python><netsuite><jaydebeapi>
|
2023-05-15 15:32:44
| 2
| 1,812
|
DKM
|
76,255,523
| 15,028,448
|
How can I create a custom tweening function to randomize mouse movements?
|
<p>I'm currently experimenting with pyautogui and am trying to randomize my program's actions as much as possible to mimic human inputs.</p>
<p>Right now, i'm using a built-in tweening function for the mouse movements as such :</p>
<pre><code>pyautogui.moveTo(x, y, duration=2, tween=pyautogui.easeInOutQuad)
</code></pre>
<p>That works as expected, but the mouse is still doing a straight line to the destination point. I want to know if there's a way to code my own tweening function to randomize the mouse movements. The documentation is very evasive on that point and i can't seem to find any examples.</p>
<p>Thanks in advance !</p>
|
<python><python-3.x><pyautogui>
|
2023-05-15 15:15:28
| 0
| 492
|
nlouis56
|
76,255,486
| 14,014,925
|
How to stop spaCy tokenizer from tokenizing words enclosed within brackets
|
<p>I'm trying to make the spaCy tokenizer avoid certain words enclosed by brackets, like <code>[intervention]</code>. However, no matter what I try, I cannot get the right code to include a rule or an exception. Here is an example of some input and the expected output:</p>
<p><strong>Example input:</strong></p>
<blockquote>
<p>A randomized, prospective study of [intervention]endometrial resection[intervention] to prevent [condition]recurrent endometrial polyps[condition]</p>
</blockquote>
<p><strong>Example output:</strong></p>
<pre class="lang-none prettyprint-override"><code>A
randomized
,
prospective
study
of
[intervention]
endometrial
resection
[intervention]
to
prev
... et cetera
</code></pre>
<p>I've tried adding a special case like this:</p>
<pre class="lang-py prettyprint-override"><code>nlp = spacy.load('en_core_web_sm')
case = [{ORTH: "[intervention]"}]
nlp.tokenizer.add_special_case('[intervention]',case)
# Test the custom tokenizer
text = combined_abstracts
doc = nlp(text)
for token in doc:
print(token.text)
</code></pre>
<p>But the tokenizer is still splitting the word. Does anybody know a way to either make the tokenizer ignore certain words or all of the words enclosed by brackets? Either option would be useful to me.</p>
|
<python><string><nlp><spacy><tokenize>
|
2023-05-15 15:11:31
| 1
| 345
|
ignacioct
|
76,255,401
| 839,497
|
how to get the path to file with python when working directory is different
|
<p>Consider the following Python file structure</p>
<pre><code>Root
|---- SubFolder
| |---- generator.py
| |---- config.json
|
|---- main.py
</code></pre>
<p><strong>main.py:</strong></p>
<pre><code>import os
def main():
from SubFolder.generator import start
start(__file__)
if __name__ == '__main__':
main()
</code></pre>
<p><strong>generator.py</strong></p>
<pre><code>import os
def start(caller: str):
file_path_s = "./config.json"
file_path_l = "./SubFolder/config.json"
exist_s = os.path.exists(file_path_s)
exist_l = os.path.exists(file_path_l)
print(f"Caller: {caller}")
print(f"cwd:{os.getcwd()}")
print(f"exist {file_path_s}: {exist_s}")
print(f"exist {file_path_l}: {exist_l}")
if __name__ == '__main__':
start(__file__)
</code></pre>
<p><strong>The probplem:</strong></p>
<ol>
<li><p><code>generator.start()</code> can be called from <code>main.py</code> as well as from <code>generator.py</code> itself (executed as main)</p>
</li>
<li><p>accordigly the working directory is different</p>
</li>
<li><p>when <code>start()</code> wants to read the json, the path to to the json is different each case.</p>
<p>when called from main it should use <em>./SubFolder/config.json</em><br />
when called from generator it should use <em>./config.json</em></p>
</li>
</ol>
<p>Is there a way to figure out the path to use without the <code>start()</code> will do something like the following:</p>
<pre><code>def _get_config_path():
work_dir = os.getcwd()
sub_folder = "SubFolder"
index = work_dir.rfind(sub_folder)
expected = len(work_dir) - len(sub_folder)
if index == expected:
return "./config.json"
else:
return "./SubFolder/config.json"
</code></pre>
<p>how this can be achived?</p>
|
<python><io><working-directory>
|
2023-05-15 15:03:23
| 1
| 818
|
OJNSim
|
76,255,149
| 10,695,495
|
Profiling fastAPI endpoint with pyinstrument
|
<p>I am trying to profile my fastapi endpoints with pyinstrument. After some searching online I see that starting from pyinstrument 4.0 there is async support.</p>
<p>When using the code snippet provided in the documentation of Pyinstrument:</p>
<pre><code>from pyinstrument import Profiler
PROFILING = True # Set this from a settings model
if PROFILING:
@app.middleware("http")
async def profile_request(request: Request, call_next):
profiling = request.query_params.get("profile", False)
if profiling:
profiler = Profiler(interval=settings.profiling_interval, async_mode="enabled")
profiler.start()
await call_next(request)
profiler.stop()
return HTMLResponse(profiler.output_html())
else:
return await call_next(request)
</code></pre>
<p>I see a nice callstack appear when calling an endpoint, however as soon as the actual (synchronous) code is run, I only see <code>[await]</code> in the stack trace...</p>
<p><a href="https://i.sstatic.net/pvQom.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pvQom.png" alt="enter image description here" /></a></p>
<p>Putting the <code>Profiler</code> inside the code that is being executed within the endpoints solves the issue, but I have many endpoints and would like a solution that is more generic.</p>
|
<python><profiling><fastapi>
|
2023-05-15 14:33:37
| 1
| 857
|
Erik
|
76,255,062
| 20,051,041
|
How to change file path for testing function in Pytest?
|
<p>In my <code>config.py</code> I define:</p>
<pre class="lang-py prettyprint-override"><code>import os
from some_file import PROJECT_PATH
DATA_FILES = os.getenv("DATA_FILES", f"{PROJECT_PATH}/data/elements")
</code></pre>
<p>In another <code>.py</code>, I have written a function, let's say:</p>
<pre class="lang-py prettyprint-override"><code>def function_1():
file_path = f'{DATA_FILES}/Image_{file_id}_{i + 1}.png
</code></pre>
<p>In a <code>.py</code> file with Pytest tests:</p>
<pre class="lang-py prettyprint-override"><code>from project_file import config
def test_function(monkeypatch):
monkeypatch.setattr(config, "DATA_FILES", f"
{PROJECT_PATH}/tests/test_data/file_1")
print(config.DATA_FILES)
function_1()
</code></pre>
<p>When I check printed path that <code>monkeypatch</code> should have passed to <code>function_1</code>, I get changed value "{PROJECT_PATH}/tests/test_data/file_1". However, it is not passed to the <code>function_1</code> which uses the original path still. Do you know any idea why and how to improve the code? Is there a more convenient way of changing variables in Pytests than monkeypatching?</p>
|
<python><pytest><monkeypatching>
|
2023-05-15 14:21:51
| 0
| 580
|
Mr.Slow
|
76,254,948
| 1,888,460
|
How to loop trough rows and search for value in another dataframe
|
<p>I have two data sets with the following data:</p>
<p><a href="https://i.sstatic.net/3j6BN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/3j6BN.png" alt="enter image description here" /></a></p>
<p>Given the interchange_rate value in the source file, I need to get the closest match of rebate_rate from the lookup table. In the image you can see that the transaction_id 2 has the highest interchange_rate and therefore, I need to get the highest rebate_rate; transaction_id 1 is the lowest interchange_rate and therefore get the lowest rebate_rate.</p>
<p>The red column I did manually using Excel just to show it as an example, but that's the expected output.</p>
<p>My initial idea is to loop through the rows in the source file, and for each line search for the closest match in the lookup table. But I'm not a very experienced PySpark developer. I'm looking for help to write code to accomplish this task.</p>
<p>My first try was to use the foreach() method in the source file dataframe, but I get a PicklingError: Could not serialize object: TypeError: cannot pickle '_thread.RLock' object</p>
<pre><code>def get_rebate(row):
buyer_name = row["buyer_name"]
df_buyer = df_lookup.where(f"buyer_name == '{buyer_name}'")
row["rebate_rate"] = df_buyer.select("rebate_rate").first()
return row
# df_final is the source file after a few cosmetics transformations. I need to add a new column "rebate_rate" to it
df_final.foreach(lambda x: get_rebate(x))
</code></pre>
|
<python><apache-spark><pyspark>
|
2023-05-15 14:08:06
| 1
| 400
|
Croves
|
76,254,848
| 6,059,213
|
Why is querying a pandas DataFrame slower after a SQL join operation?
|
<p>I'm working with a pandas DataFrame that is created from a SQL query involving a join operation on three tables using <code>pd.read_sql()</code>. The DataFrame has about 1 million rows. When I try to query rows based on the value of one column (<code>doi</code>), it takes about 0.1 to 0.2 seconds for each query.</p>
<p>Interestingly, if I export the DataFrame to a CSV file and then load it back into memory, the same query operation is 5 to 10 times faster.</p>
<p>More interestingly, if I only query the main table (the resulting DataFrame has the same number of rows and two short string columns less), the resulting DataFrame is as fast as the CSV one. <strong>Even keeping only one column (<code>doi</code>) in the DataFrame obtained from the join operation doesn't improve the performance, and it's still slower than the single-table DataFrame with the same number of rows and more columns.</strong></p>
<p>Could you help me understand this phenomenon and show me how to solve the performance issue without exporting to CSV?</p>
<p><strong>Some clarifications:</strong></p>
<p>I am referring to the difference in the query performance of DataFrames generated by SQL query with/without table joins, not the performance of joining DataFrames.</p>
<p>My codes to read data from the SQL Server database and query the resulting DataFrame:</p>
<pre><code>conn = pyodbc.connect(driver='{ODBC Driver 17 for SQL Server}', server='XXX', database='XXX', uid='XXX', trusted_connection='yes')
query_string = """
SELECT
t1.*,
t2.short_string_column1,
t3.short_string_column2
FROM
t1
LEFT JOIN
t2
ON
t1.doi = t2.doi
LEFT JOIN
t3
ON
t1.doi = t3.doi
"""
# ~1M rows
df = pd.read_sql(query_string, conn)
# ~20K dois
doi_list = {some interested dois to query}
# this is very slow
for doi in doi_list:
# I achieved satisfying performance on the single-table DataFrame
# but I needed more fields to do my work, so I have to join tables.
required_intermediate_results = df[df.doi.values == doi]
......
# this is 5 to 10 times faster
df.to_csv('df.csv', index=False)
df2 = pd.read_csv('df.csv')
for doi in doi_list:
# I achieved satisfying performance on the single-table DataFrame
# but I needed more fields to do my work, so I have to join tables.
required_intermediate_results = df2[df2.doi.values == doi]
......
</code></pre>
|
<python><sql-server><pandas><dataframe>
|
2023-05-15 13:56:19
| 1
| 374
|
Tom Leung
|
76,254,822
| 5,533,595
|
Finding/replacing/dropping a string which is partially duplicated
|
<p>I have a pandas dataframe which contains company names.
Sometimes it also includes the location or a subdivision in the name (e.g. McDonalds Boston, McDonalds Washington. PwC accounting, PwC advisory).
I am only interested in getting the company name (i.e. McDonalds), not the locality.</p>
<p>To make this more complicated, some words will show up in multiple company names, but should remain there. (e.g. airlines). Now, I can create a list with these exceptions. I just don't know how to implement a search for partial matches, or how to use an exclusion list to make sure we don't capture these cases.</p>
<p>So, I currently have:</p>
<pre><code> PwC advisory
PwC accounting
American airlines
McDonalds Boston
McDonalds Washington
Spirit airlines
</code></pre>
<p>What I need is:</p>
<pre><code> PwC
American airlines
McDonalds
Spirit airlines
</code></pre>
<p>I was thinking that I might have to resort to splitting each string into its words, excluding the words from my exclusion list (like airlines) and then checking if any of the parts of 1 string are in any of the parts of any of the other strings. This seems like a very roundabout way of doing it, and I wouldn't know how to do it.</p>
|
<python><pandas><regex>
|
2023-05-15 13:53:10
| 2
| 441
|
Peter
|
76,254,816
| 7,773,783
|
Call custom logger after initializing in a file in all other files in Python
|
<p>I have created a <code>logger.py</code> file like so:</p>
<pre><code>import logging
Log_Format = "%(levelname)s %(asctime)s - %(message)s"
log_file = get_log_filename()
def setup_logger(name, log_file, level=logging.INFO):
handler = logging.FileHandler(log_file, mode="a")
handler.setFormatter(Log_Format)
handler.setLevel(level)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger
logger = setup_logger("Logger", log_file)
</code></pre>
<p>Then I have multiple files where I have to use logging. So I call them like this:</p>
<p><strong>file1.py</strong>
<strong>file2.py</strong>
<strong>file3.py</strong></p>
<pre><code>from logger import logger
logger.info('This is a log info')
</code></pre>
<p>The whole app is called by calling one file like so: <code>python3 main_file.py</code></p>
<p><strong>main_file.py</strong></p>
<pre><code>from logger import logger
from file1 import func1
from file2 import func2
from file3 import func3
logger.info("This log is in the main file")
</code></pre>
<p>In the main file there is no <code>main</code> function. It is just a python script which is executed line by line.
My problem is that there are no logs being saved in the file or shown in the console. What am I doing wrong here? How to rectify this?</p>
<p>But if I write this in <code>main_file.py</code></p>
<pre><code>Log_Format = "%(levelname)s %(asctime)s - %(message)s"
log_file = get_log_filename()
logging.basicConfig(
filename=log_file,
filemode="a",
format=Log_Format,
level=logging.INFO,
)
logger = logging.getLogger("Logger")
</code></pre>
<p>Then import it in other files like so:</p>
<pre><code>import logging
logger = logging.getLogger("Logger")
</code></pre>
<p>Then the above code works. But I want to intialize like I have said in the first example. Can I do it?</p>
|
<python><python-3.x><python-logging>
|
2023-05-15 13:52:44
| 0
| 1,139
|
Lax_Sam
|
76,254,386
| 12,040,751
|
Dictionary update method for DataFrames
|
<p>Dictionaries have an <code>update</code> method which can be used to add new items based on those of another dictionary. Here it is an example:</p>
<pre><code>d1 = {"asd": 0, "lol": 1}
d2 = {"lol": 2, "foo": 3}
d1.update(d2)
assert d1 == {'asd': 0, 'lol': 2, 'foo': 3}
</code></pre>
<p>I am trying to obtain a similar result with DataFrames, this is what I have.</p>
<pre><code>>>> df1 = pd.DataFrame(0, index=range(3), columns=["a"])
>>> df1
a
0 0
1 0
2 0
>>> df2 = pd.DataFrame(1, index=range(2, 4), columns=["a"])
>>> df2
a
2 1
3 1
</code></pre>
<p>I have tried with <code>update</code>, which gives the following result:</p>
<pre><code>>>> df1.update(df2)
>>> df1
a
0 0.0
1 0.0
2 1.0
</code></pre>
<p>The conversion from int to float is mildly infuriating, but the main problem is that the rows which are present in df2 only are not added. The expected result is:</p>
<pre><code> a
0 0
1 0
2 1
3 1
</code></pre>
|
<python><pandas>
|
2023-05-15 13:05:09
| 2
| 1,569
|
edd313
|
76,254,339
| 17,136,258
|
Generate a dataframe sample
|
<p>I have a problem. I want to create a sample dataframe.
As you can see there are 11 tasks. And special for <code>Task2</code>, <code>Task3</code> and <code>Task7</code> you have an option - so you can only choose on path.</p>
<p>I would like to create a sample dataframe with a start and end time for each task. How could I do that?
The important thing is that every the end should be in the future as the start. And the furhter task should be also in the future e.g. <code>Task2_Start > Task1_End</code> or <code>Task5_End > Task5_Start</code>. <strong>Attention</strong> Special Case you can go back from <code>Task8</code> to <code>Task7</code>. <code>So Task7_Start > Task8_End > Task8_Start > Task7_End</code>, because you can go back to <code>task7</code>.</p>
<p>How could I create a sample dataframe?</p>
<p>I want three columns (below you can find an example)</p>
<pre class="lang-py prettyprint-override"><code>d = {'id': [],
'step': [],
'timestamp': []}
</code></pre>
<p><a href="https://i.sstatic.net/zKNSJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zKNSJ.png" alt="enter image description here" /></a></p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import random
steps = ['Task1', 'Task2', 'Task3', 'Task4', 'Task5', 'Task6', 'Task7', 'Task8', 'Task9', 'Task10', 'Task11']
num_ids = 10
data = []
for id in range(1, num_ids + 1):
current_step = 'Task1'
for _ in range(len(steps)):
data.append({'id': id, 'step': current_step})
if current_step == 'Task2':
next_step = random.choice(['Task3', 'Task4'])
elif current_step == 'Task7':
next_step = random.choice(['Task8', 'Task9'])
elif current_step == 'Task3':
next_step = random.choice(['Task5', 'Task11'])
else:
next_step = random.choice(steps)
current_step = next_step
df = pd.DataFrame(data)
df['timestamp'] = pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')
</code></pre>
<hr />
<p>Example with only three and without an condition</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
d = {'id': [1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2],
'step': ['Task1_Start', 'Task1_End1', 'Task2_Start', 'Task2_End', 'Task3_Start', 'Task3_End',
'Task1_Start', 'Task1_End1', 'Task2_Start', 'Task2_End', 'Task3_Start', 'Task3_End',],
'timestamp': ['2023-01-01', '2023-01-05', '2023-01-10', '2023-01-12', '2023-02-12', '2023-02-14',
'2023-01-01', '2023-01-05', '2023-01-10', '2023-01-12', '2023-01-15', '2023-02-16',]}
df = pd.DataFrame(data=d,)
</code></pre>
<p><a href="https://i.sstatic.net/AbfuN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AbfuN.png" alt="enter image description here" /></a></p>
|
<python><pandas><dataframe>
|
2023-05-15 12:59:54
| 1
| 560
|
Test
|
76,254,327
| 12,176,973
|
local docker image using python packages - ModuleNotFoundError
|
<p>So I have an image that contains a machine learning model api, but it needs some specific python packages. I tried to setup a virtualenv with all the packages needed in the dockerfile so when I build the image, the python env is built properly and then it can build and run my local image. When I run docker build : <code>docker build my-container/ -f dockerfile -t my-detector</code>, everything seems to work properly, but then when I run it using this command : <code>docker run -d --name my-container/ my-detector</code>, the container starts and then stops. So I took a look at the logs, and this is the error :</p>
<pre><code>Downloading: "https://github.com/ultralytics/yolov5/zipball/master" to /root/.cache/torch/hub/master.zip
Traceback (most recent call last):
File "/usr/local/bin/uvicorn", line 8, in <module>
sys.exit(main())
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/uvicorn/main.py", line 408, in main
run(
File "/usr/local/lib/python3.8/dist-packages/uvicorn/main.py", line 576, in run
server.run()
File "/usr/local/lib/python3.8/dist-packages/uvicorn/server.py", line 60, in run
return asyncio.run(self.serve(sockets=sockets))
File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/usr/local/lib/python3.8/dist-packages/uvicorn/server.py", line 67, in serve
config.load()
File "/usr/local/lib/python3.8/dist-packages/uvicorn/config.py", line 479, in load
self.loaded_app = import_from_string(self.app)
File "/usr/local/lib/python3.8/dist-packages/uvicorn/importer.py", line 24, in import_from_string
raise exc from None
File "/usr/local/lib/python3.8/dist-packages/uvicorn/importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/usr/src/app/./worker.py", line 9, in <module>
model = torch.hub.load("ultralytics/yolov5", "custom", path="best.onnx")
File "/usr/local/lib/python3.8/dist-packages/torch/hub.py", line 540, in load
model = _load_local(repo_or_dir, model, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/torch/hub.py", line 569, in _load_local
model = entry(*args, **kwargs)
File "/root/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 83, in custom
return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
File "/root/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 33, in _create
from models.common import AutoShape, DetectMultiBackend
File "/root/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 28, in <module>
from utils.dataloaders import exif_transpose, letterbox
File "/root/.cache/torch/hub/ultralytics_yolov5_master/utils/dataloaders.py", line 31, in <module>
from utils.augmentations import (Albumentations, augment_hsv, classify_albumentations, classify_transforms, copy_paste,
File "/root/.cache/torch/hub/ultralytics_yolov5_master/utils/augmentations.py", line 15, in <module>
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
File "/root/.cache/torch/hub/ultralytics_yolov5_master/utils/general.py", line 38, in <module>
from ultralytics.yolo.utils.checks import check_requirements
ModuleNotFoundError: No module named 'ultralytics'.
</code></pre>
<p>The issue here is that I have this package and all the sub dependencies listed in requirements.txt, and so after activating the venv, upgrading pip and installing the requirements it should have everything needed to build my-detector.</p>
<p>This is my dockerfile :</p>
<pre><code>FROM python:3.8 as python
WORKDIR my-container
RUN python3 -m venv venv
ENV PYTHONPATH my-container/venv/bin
COPY requirements.txt requirements.txt
RUN . ./venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt
FROM my-detector:1.0.0
EXPOSE 80
</code></pre>
<p>Finally, here is the content of requirements.txt :</p>
<pre><code>certifi==2023.5.7
charset-normalizer==3.1.0
contourpy==1.0.7
cycler==0.11.0
filelock==3.12.0
fonttools==4.39.4
idna==3.4
importlib-resources==5.12.0
Jinja2==3.1.2
kiwisolver==1.4.4
MarkupSafe==2.1.2
matplotlib==3.7.1
mpmath==1.3.0
networkx==3.1
numpy==1.24.3
opencv-python==4.7.0.72
packaging==23.1
pandas==2.0.1
Pillow==9.5.0
psutil==5.9.5
pyparsing==3.0.9
python-dateutil==2.8.2
pytz==2023.3
PyYAML==6.0
requests==2.30.0
scipy==1.10.1
seaborn==0.12.2
sentry-sdk==1.22.2
six==1.16.0
sympy==1.12
thop==0.1.1.post2209072238
torch==2.0.1
torchvision==0.15.2
tqdm==4.65.0
typing_extensions==4.5.0
tzdata==2023.3
ultralytics==8.0.100
urllib3==1.26.15
zipp==3.15.0
</code></pre>
|
<python><docker>
|
2023-05-15 12:58:16
| 1
| 311
|
arlaine
|
76,254,196
| 16,627,522
|
environment.yml: ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied:
|
<p>I would like to install a Conda environment with Pip dependencies from an <code>environment.yml</code> file which I have included at the bottom of this post.</p>
<p>However, I get the following error:</p>
<pre><code>Pip subprocess error:
ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\\Users\\me\\AppData\\Local\\Temp\\pip-uninstall-8vvj24wt\\normalizer.exe'
Consider using the `--user` option or check the permissions.
</code></pre>
<p>The <code>pip-uninstall-8vvj24wt</code> directory appears during installation of the Pip dependencies. How do I resolve this?</p>
<pre><code>name: nb_classification_py310
channels:
- anaconda
- conda-forge
- defaults
dependencies:
- aiohttp=3.8.4=py310h8d17308_0
- aiohttp-retry=2.8.3=pyhd8ed1ab_0
- aiosignal=1.3.1=pyhd8ed1ab_0
- amqp=5.1.1=pyhd8ed1ab_0
- antlr-python-runtime=4.9.3=pyhd8ed1ab_1
- anyio=3.5.0=py310haa95532_0
- appdirs=1.4.4=pyh9f0ad1d_0
- argon2-cffi=21.3.0=pyhd3eb1b0_0
- argon2-cffi-bindings=21.2.0=py310h2bbff1b_0
- asttokens=2.0.5=pyhd3eb1b0_0
- async-timeout=4.0.2=pyhd8ed1ab_0
- asyncssh=2.13.1=pyhd8ed1ab_0
- atpublic=3.0.1=pyhd8ed1ab_0
- attrs=22.2.0=pyh71513ae_0
- babel=2.11.0=py310haa95532_0
- backcall=0.2.0=pyhd3eb1b0_0
- backports=1.0=pyhd8ed1ab_3
- backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0
- beautifulsoup4=4.12.2=py310haa95532_0
- billiard=3.6.4.0=py310h8d17308_3
- black=23.3.0=py310h5588dad_0
- blas=1.0=mkl
- bleach=4.1.0=pyhd3eb1b0_0
- bottleneck=1.3.5=py310h9128911_0
- brotli=1.0.9=h2bbff1b_7
- brotli-bin=1.0.9=h2bbff1b_7
- brotlipy=0.7.0=py310h8d17308_1005
- bzip2=1.0.8=he774522_0
- ca-certificates=2023.5.7=h56e8100_0
- celery=5.2.7=pyhd8ed1ab_0
- certifi=2023.5.7=pyhd8ed1ab_0
- cffi=1.15.1=py310h628cb3f_3
- click=8.1.3=win_pyhd8ed1ab_2
- click-didyoumean=0.3.0=pyhd8ed1ab_0
- click-plugins=1.1.1=py_0
- click-repl=0.2.0=pyhd8ed1ab_0
- colorama=0.4.6=py310haa95532_0
- comm=0.1.2=py310haa95532_0
- configobj=5.0.8=pyhd8ed1ab_0
- contourpy=1.0.5=py310h59b6b97_0
- cryptography=38.0.4=py310h52f42fa_0
- cudatoolkit=11.2.2=h933977f_10
- cudnn=8.1.0.77=h3e0f4f4_0
- cycler=0.11.0=pyhd3eb1b0_0
- debugpy=1.5.1=py310hd77b12b_0
- decorator=5.1.1=pyhd8ed1ab_0
- defusedxml=0.7.1=pyhd3eb1b0_0
- dictdiffer=0.9.0=pyhd8ed1ab_0
- diskcache=5.6.1=pyhd8ed1ab_0
- distro=1.8.0=pyhd8ed1ab_0
- dpath=2.1.5=py310h5588dad_0
- dulwich=0.21.3=py310h8d17308_0
- dvc=2.55.0=pyhd8ed1ab_0
- dvc-data=0.47.2=pyhd8ed1ab_0
- dvc-http=2.30.2=pyhd8ed1ab_2
- dvc-objects=0.21.1=pyhd8ed1ab_0
- dvc-render=0.3.1=pyhd8ed1ab_0
- dvc-ssh=2.22.1=pyhd8ed1ab_0
- dvc-studio-client=0.7.0=pyhd8ed1ab_0
- dvc-task=0.2.0=pyhd8ed1ab_0
- eigen=3.3.7=h59b6b97_1
- entrypoints=0.4=py310haa95532_0
- et_xmlfile=1.1.0=py310haa95532_0
- executing=0.8.3=pyhd3eb1b0_0
- ffmpeg=4.2.2=he774522_0
- fftw=3.3.9=h2bbff1b_1
- filelock=3.12.0=pyhd8ed1ab_0
- flatten-dict=0.4.2=pyhd8ed1ab_1
- flufl.lock=7.1=pyhd8ed1ab_0
- fonttools=4.25.0=pyhd3eb1b0_0
- freetype=2.12.1=ha860e81_0
- frozenlist=1.3.3=py310h8d17308_0
- fsspec=2023.4.0=pyh1a96a4e_0
- funcy=2.0=pyhd8ed1ab_0
- future=0.18.3=pyhd8ed1ab_0
- giflib=5.2.1=h8cc25b3_3
- gitdb=4.0.10=pyhd8ed1ab_0
- gitpython=3.1.31=pyhd8ed1ab_0
- glib=2.69.1=h5dc1a3c_2
- grandalf=0.7=pyhd8ed1ab_0
- gst-plugins-base=1.18.5=h9e645db_0
- gstreamer=1.18.5=hd78058f_0
- hdf5=1.10.6=h1756f20_1
- hydra-core=1.3.2=pyhd8ed1ab_0
- icc_rt=2022.1.0=h6049295_2
- icu=58.2=ha925a31_3
- idna=3.4=pyhd8ed1ab_0
- importlib-metadata=6.5.0=pyha770c72_0
- importlib_resources=5.12.0=pyhd8ed1ab_0
- intel-openmp=2021.4.0=haa95532_3556
- ipykernel=6.19.2=py310h9909e9c_0
- ipympl=0.9.3=pyhd8ed1ab_0
- ipython=8.12.0=py310haa95532_0
- ipython_genutils=0.2.0=pyhd3eb1b0_1
- ipywidgets=8.0.4=py310haa95532_0
- iterative-telemetry=0.0.8=pyhd8ed1ab_0
- jedi=0.18.1=py310haa95532_1
- jinja2=3.1.2=py310haa95532_0
- joblib=1.1.1=py310haa95532_0
- jpeg=9e=h2bbff1b_1
- json5=0.9.6=pyhd3eb1b0_0
- jsonschema=4.17.3=py310haa95532_0
- jupyter=1.0.0=py310haa95532_8
- jupyter_client=8.1.0=py310haa95532_0
- jupyter_console=6.6.3=py310haa95532_0
- jupyter_core=5.3.0=py310haa95532_0
- jupyter_server=1.23.4=py310haa95532_0
- jupyterlab=3.5.3=py310haa95532_0
- jupyterlab_pygments=0.1.2=py_0
- jupyterlab_server=2.22.0=py310haa95532_0
- jupyterlab_widgets=3.0.5=py310haa95532_0
- kiwisolver=1.4.4=py310hd77b12b_0
- kombu=5.2.4=py310h5588dad_2
- krb5=1.19.4=h5b6d351_0
- lerc=3.0=hd77b12b_0
- libbrotlicommon=1.0.9=h2bbff1b_7
- libbrotlidec=1.0.9=h2bbff1b_7
- libbrotlienc=1.0.9=h2bbff1b_7
- libclang13=14.0.6=default_h8e68704_1
- libdeflate=1.17=h2bbff1b_0
- libffi=3.4.2=hd77b12b_6
- libgit2=1.6.4=hc6d37dd_0
- libiconv=1.16=h2bbff1b_2
- libogg=1.3.5=h2bbff1b_1
- libpng=1.6.39=h8cc25b3_0
- libprotobuf=3.20.3=h23ce68f_0
- libsodium=1.0.18=h62dcd97_0
- libssh2=1.10.0=h680486a_3
- libtiff=4.5.0=h6c2663c_2
- libvorbis=1.3.7=he774522_0
- libwebp=1.2.4=hbc33d0d_1
- libwebp-base=1.2.4=h2bbff1b_1
- libxml2=2.10.3=h0ad7f3c_0
- libxslt=1.1.37=h2bbff1b_0
- libzlib=1.2.13=hcfcfb64_4
- lxml=4.9.2=py310h2bbff1b_0
- lz4-c=1.9.4=h2bbff1b_0
- markdown-it-py=2.2.0=pyhd8ed1ab_0
- matplotlib=3.7.1=py310haa95532_1
- matplotlib-base=3.7.1=py310h4ed8f06_1
- matplotlib-inline=0.1.6=py310haa95532_0
- mdurl=0.1.0=pyhd8ed1ab_0
- mistune=0.8.4=py310h2bbff1b_1000
- mkl=2021.4.0=haa95532_640
- mkl-service=2.4.0=py310h2bbff1b_0
- mkl_fft=1.3.1=py310ha0764ea_0
- mkl_random=1.2.2=py310h4ed8f06_0
- multidict=6.0.4=py310h8d17308_0
- munkres=1.1.4=py_0
- mypy_extensions=1.0.0=pyha770c72_0
- nanotime=0.5.2=py_0
- nbclassic=0.5.5=py310haa95532_0
- nbclient=0.5.13=py310haa95532_0
- nbconvert=6.5.4=py310haa95532_0
- nbformat=5.7.0=py310haa95532_0
- nest-asyncio=1.5.6=py310haa95532_0
- networkx=3.1=pyhd8ed1ab_0
- notebook=6.5.4=py310haa95532_0
- notebook-shim=0.2.2=py310haa95532_0
- numexpr=2.8.4=py310hd213c9f_0
- numpy-base=1.23.5=py310h04254f7_0
- omegaconf=2.3.0=pyhd8ed1ab_0
- opencv=4.6.0=py310h4ed8f06_3
- openpyxl=3.0.10=py310h2bbff1b_0
- openssl=1.1.1t=hcfcfb64_0
- orjson=3.8.10=py310h48ea969_0
- pandas=1.5.3=py310h4ed8f06_0
- pandocfilters=1.5.0=pyhd3eb1b0_0
- parso=0.8.3=pyhd3eb1b0_0
- pathlib2=2.3.7.post1=py310h5588dad_2
- pathspec=0.11.1=pyhd8ed1ab_0
- pcre=8.45=hd77b12b_0
- pickleshare=0.7.5=pyhd3eb1b0_1003
- pillow=9.4.0=py310hd77b12b_0
- pip=23.0.1=py310haa95532_0
- platformdirs=3.2.0=pyhd8ed1ab_0
- ply=3.11=py310haa95532_0
- prometheus_client=0.14.1=py310haa95532_0
- prompt-toolkit=3.0.38=pyha770c72_0
- prompt_toolkit=3.0.38=hd8ed1ab_0
- psutil=5.9.5=py310h8d17308_0
- pure_eval=0.2.2=pyhd3eb1b0_0
- pycparser=2.21=pyhd8ed1ab_0
- pydot=1.2.4=py_0
- pygit2=1.12.0=py310h8d17308_0
- pygments=2.15.1=pyhd8ed1ab_0
- pygtrie=2.5.0=pyhd8ed1ab_0
- pyopenssl=23.1.1=pyhd8ed1ab_0
- pyparsing=3.0.9=py310haa95532_0
- pyqt=5.15.7=py310hd77b12b_0
- pyqt5-sip=12.11.0=py310hd77b12b_0
- pyrsistent=0.18.0=py310h2bbff1b_0
- pysocks=1.7.1=pyh0701188_6
- python=3.10.10=h966fe2a_2
- python-dateutil=2.8.2=pyhd3eb1b0_0
- python-fastjsonschema=2.16.2=py310haa95532_0
- python-gssapi=1.8.2=py310hf7a0c3d_1
- python_abi=3.10=2_cp310
- pytz=2022.7=py310haa95532_0
- pywin32=304=py310h00ffb61_2
- pywin32-on-windows=0.1.0=pyh07e9846_2
- pywinpty=2.0.10=py310h5da7b33_0
- pyyaml=6.0=py310h8d17308_5
- pyzmq=23.2.0=py310hd77b12b_0
- qt-main=5.15.2=he8e5bd7_8
- qt-webengine=5.15.9=hb9a9bb5_5
- qtconsole=5.4.2=py310haa95532_0
- qtpy=2.2.0=py310haa95532_0
- qtwebkit=5.212=h2bbfb41_5
- requests=2.28.2=pyhd8ed1ab_1
- rich=13.3.4=pyhd8ed1ab_0
- ruamel=1.0=py310haa95532_2
- ruamel.yaml=0.17.21=py310h2bbff1b_0
- ruamel.yaml.clib=0.2.6=py310h2bbff1b_1
- scikit-learn=1.2.0=py310hd77b12b_1
- scipy=1.9.3=py310h86744a3_0
- scmrepo=1.0.2=pyhd8ed1ab_0
- seaborn=0.12.2=py310haa95532_0
- send2trash=1.8.0=pyhd3eb1b0_1
- setuptools=66.0.0=py310haa95532_0
- shortuuid=1.0.11=pyhd8ed1ab_0
- shtab=1.6.1=pyhd8ed1ab_0
- sip=6.6.2=py310hd77b12b_0
- six=1.16.0=pyhd3eb1b0_1
- smmap=3.0.5=pyh44b312d_0
- sniffio=1.2.0=py310haa95532_1
- soupsieve=2.4=py310haa95532_0
- sqlite=3.41.2=h2bbff1b_0
- sqltrie=0.3.1=pyhd8ed1ab_0
- sshfs=2023.4.1=pyhd8ed1ab_1
- stack_data=0.2.0=pyhd3eb1b0_0
- tabulate=0.9.0=pyhd8ed1ab_1
- terminado=0.17.1=py310haa95532_0
- threadpoolctl=2.2.0=pyh0d69192_0
- tinycss2=1.2.1=py310haa95532_0
- tk=8.6.12=h2bbff1b_0
- toml=0.10.2=pyhd3eb1b0_0
- tomli=2.0.1=pyhd8ed1ab_0
- tomlkit=0.11.7=pyha770c72_0
- tornado=6.2=py310h2bbff1b_0
- tqdm=4.65.0=py310h9909e9c_0
- traitlets=5.7.1=py310haa95532_0
- typing=3.10.0.0=pyhd8ed1ab_0
- typing-extensions=4.5.0=hd8ed1ab_0
- typing_extensions=4.5.0=pyha770c72_0
- tzdata=2023c=h04d1e81_0
- ucrt=10.0.22621.0=h57928b3_0
- urllib3=1.26.15=pyhd8ed1ab_0
- vc=14.2=h21ff451_1
- vine=5.0.0=pyhd8ed1ab_1
- voluptuous=0.13.1=pyhd8ed1ab_0
- vs2015_runtime=14.34.31931=h4c5c07a_10
- wcwidth=0.2.6=pyhd8ed1ab_0
- webencodings=0.5.1=py310haa95532_1
- websocket-client=0.58.0=py310haa95532_4
- wheel=0.38.4=py310haa95532_0
- widgetsnbextension=4.0.5=py310haa95532_0
- win_inet_pton=1.1.0=pyhd8ed1ab_6
- winpty=0.4.3=4
- xz=5.2.10=h8cc25b3_1
- yaml=0.2.5=h8ffe710_2
- yarl=1.8.2=py310h8d17308_0
- zc.lockfile=3.0.post1=pyhd8ed1ab_0
- zeromq=4.3.4=hd77b12b_0
- zipp=3.15.0=pyhd8ed1ab_0
- zlib=1.2.13=hcfcfb64_4
- zstd=1.5.5=hd43e919_0
- pip:
- absl-py==1.4.0
- astunparse==1.6.3
- cachetools==5.3.0
- charset-normalizer==3.1.0
- dvclive==2.6.4
- flatbuffers==23.3.3
- gast==0.4.0
- google-auth==2.17.3
- google-auth-oauthlib==0.4.6
- google-pasta==0.2.0
- grpcio==1.54.0
- h5py==3.8.0
- keras==2.10.0
- keras-preprocessing==1.1.2
- libclang==16.0.0
- markdown==3.4.3
- markupsafe==2.1.2
- numpy==1.24.2
- oauthlib==3.2.2
- opt-einsum==3.3.0
- packaging==23.1
- protobuf==3.19.6
- pyasn1==0.4.8
- pyasn1-modules==0.2.8
- requests-oauthlib==1.3.1
- rsa==4.9
- tensorboard==2.10.1
- tensorboard-data-server==0.6.1
- tensorboard-plugin-wit==1.8.1
- tensorflow==2.10.1
- tensorflow-estimator==2.10.0
- tensorflow-io-gcs-filesystem==0.31.0
- termcolor==2.2.0
- werkzeug==2.2.3
- wrapt==1.15.0
prefix: C:\Users\me\anaconda3\envs\nb_classification_py310
</code></pre>
|
<python><pip><anaconda><conda><virtual-environment>
|
2023-05-15 12:42:34
| 1
| 634
|
Tommy Wolfheart
|
76,254,097
| 1,574,551
|
Azure function code in python how to print out dataframe for https-request
|
<p>I would like to print dataframe on azure function with func.HttpRequest. The function works okey but no output. How can I update my code to ouput dataframe? Please help.
Thank you</p>
<pre class="lang-py prettyprint-override"><code>config = {
'host':' ',
'database' : '',
'user' : '',
'password' : '',
'port':'',
'client_flags': [mysql.connector.ClientFlag.SSL],
'ssl_ca': 'DigiCertGlobalRootG2.crt.pem'
}
def select_table():
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
myresult=cursor.execute("SELECT * FROM events")
return myresult
def main(req: func.HttpRequest) -> func.HttpResponse:
data=select_table()
print(data)
return func.HttpResponse(f"{data}")
</code></pre>
|
<python><azure><azure-functions>
|
2023-05-15 12:30:35
| 1
| 1,332
|
melik
|
76,253,911
| 12,436,050
|
Regex to extract multiple groups and atore in dataframe column in python 3.9
|
<p>I have a dataframe from which I would like to extract some information through regex.</p>
<pre><code>name
?|{Type 2 diabetes mellitus, susceptibility to}, 125853 (3)
{Type 2 diabetes mellitus}, 125854 (3)
17,20-lyase deficiency, isolated, 202110 (3)
17-alpha-hydroxylase/17,20-lyase deficiency, 202110 (3)
?Agammaglobulinemia 4, 613502 (3)
?[Dysalbuminemic hypertriiodothyroninemia], 615999 (3)
3p- syndrome (4)
3m-syndrome (4)
</code></pre>
<p>I would like extract the text and the digits after the comma. The final dataframe should be like this.</p>
<pre><code>name newColumn0 newColumn1
?|{Type 2 diabetes mellitus, susceptibility to} Type 2 diabetes mellitus, susceptibility to 125853
{Type 2 diabetes mellitus}, 125854 (3) Type 2 diabetes mellitus 125854
17,20-lyase deficiency, isolated, 202110 (3) 17,20-lyase deficiency, isolated 202110
17-alpha-hydroxylase/17,20-lyase deficiency, 202110 (3) 17-alpha-hydroxylase/17,20-lyase deficiency 202110
?Agammaglobulinemia 4, 613502 (3) Agammaglobulinemia 4 613502
?[Dysalbuminemic hypertriiodothyroninemia], 615999 (3) Dysalbuminemic hypertriiodothyroninemia 615999
3p- syndrome (4) 3p- syndrome
3m-syndrome (4) 3m-syndrome
</code></pre>
<p>I am using following regular expression which only works for first 2 rows.</p>
<pre><code>
df_new = df.join(df[name].str.extractall("{(.*)}, (.*) \(")[0]
.unstack()
.add_prefix('newColumn'))
</code></pre>
<p>How can I modify it to include other patterns as well?</p>
|
<python><pandas><regex>
|
2023-05-15 12:08:28
| 1
| 1,495
|
rshar
|
76,253,873
| 14,559,436
|
Consecutive Difference Checker
|
<p>I'm writing a program that accepts a 2 or 3 or 4 digit number. The program checks the difference between each two consecutive digits of the number. If the difference between any two consecutive digits is the same, the program print True. Otherwise it will print False.
In addition, the difference between the last digit and the first digit of the number should also be checked.</p>
<p>Example1: 4840 returns <strong>True</strong> <br />
The difference between 4 and 8 is 4 <br />
and the difference between 8 and 4 is 4 <br />
and the difference between 4 and 0 is 4<br />
and the difference between 4 and 0 is 4 (first and last digits)</p>
<p>Example2: 59 returns <strong>True</strong> <br />
The difference between 5 and 9 is 4
and difference between 9 and 5 is 4.</p>
<p>Example3: 131 returns <strong>False</strong> <br />
The difference between 1 and 3 is 2 <br />
and difference between 3 and 1 is 2 <br />
BUT the difference between 1 and 1 is 0.</p>
<p>Example4: 2420 returns <strong>True</strong> <br />
The difference between 2 and 4 is 2 <br />
and the difference between 4 and 2 is 2 <br />
and the difference between 2 and 0 is 2<br />
and the difference between 2 and 0 is 2 (first and last digits)</p>
<p>Note that, I'm not using function, loops, if/else statements.</p>
<p>I tried the following code, but I realized it doesn't work for all option (2,3 or 4 digits), it works only if I knew how many digits before I run the program:</p>
<pre><code>num = int(input("Enter a number: "))
ones = num % 10
tens = (num % 100) // 10
hundreds = (num % 1000) // 100
thousands = num // 1000
bool1 = thousands and abs(thousands - hundreds) == abs(hundreds - tens) == abs(tens - ones) == abs(thousands - ones)
bool2 = hundreds and abs(hundreds - tens) == abs(tens - ones) == abs(hundreds - ones)
bool3 = bool2 and tens and abs(tens - ones) == abs(tens - ones)
check = bool1 and bool2 and bool3
print(check)
</code></pre>
<p>So basically I'm trying to convert this code but without using if/else:</p>
<pre><code>num = int(input("Enter a number: "))
if len(num) == 2:
diff1 = abs(int(num[0]) - int(num[1]))
diff2 = abs(int(num[1]) - int(num[0]))
result = (diff1 == diff2)
elif len(num) == 3:
diff1 = abs(int(num[0]) - int(num[1]))
diff2 = abs(int(num[1]) - int(num[2]))
diff3 = abs(int(num[2]) - int(num[0]))
result = (diff1 == diff2 == diff3)
else:
diff1 = abs(int(num[3]) - int(num[0]))
diff2 = abs(int(num[3]) - int(num[2]))
diff3 = abs(int(num[2]) - int(num[1]))
diff4 = abs(int(num[1]) - int(num[0]))
result = (diff1 == diff2 == diff3 == diff4)
print(result)
</code></pre>
|
<python><algorithm>
|
2023-05-15 12:03:08
| 3
| 2,069
|
001
|
76,253,753
| 14,014,925
|
Combining strings which have been altered
|
<p>I have the following three strings:</p>
<pre class="lang-py prettyprint-override"><code>"A randomized, prospective study of [intervention]endometrial resection[intervention] to prevent recurrent endometrial polyps in women with breast cancer receiving tamoxifen. To assess the role of endometrial resection in preventing recurrence of tamoxifen-associated endometrial polyps in women with breast cancer.
"A randomized, prospective study of endometrial resection to prevent [condition]recurrent endometrial polyps[condition] in women with breast cancer receiving tamoxifen. To assess the role of endometrial resection in preventing recurrence of tamoxifen-associated endometrial polyps in women with breast cancer.
"A randomized, prospective study of endometrial resection to prevent recurrent endometrial polyps in [eligibility]women with breast cancer receiving tamoxifen[eligibility]. To assess the role of endometrial resection in preventing recurrence of tamoxifen-associated endometrial polyps in women with breast cancer.
</code></pre>
<p>Is there a way to efficiently combine the three strings into one, where you can see all the annotations (between brackets) that I have made? I cannot come up with anything efficient by myself. The result should look like:</p>
<pre class="lang-py prettyprint-override"><code>"A randomized, prospective study of [intervention]endometrial resection[intervention] to prevent [condition]recurrent endometrial polyps[condition] in [eligibility]women with breast cancer receiving tamoxifen[eligibility]. To assess the role of endometrial resection in preventing recurrence of tamoxifen-associated endometrial polyps in women with breast cancer.
</code></pre>
<p>Thanks in advance!</p>
|
<python><string><data-science>
|
2023-05-15 11:47:09
| 1
| 345
|
ignacioct
|
76,253,698
| 5,079,088
|
Problem displaying multiple robots in Gazebo and RViz
|
<p>I use ROS2/Python/Gazebo project. I need to show multiple (in the code below just two) robots. To do it I use the following code snippet:</p>
<pre><code># Define commands for spawing the robots into Gazebo
spawn_robots_cmds = []
for robot in robots:
robot_description_config = xacro.process_file(urdf)
params = {
'robot_description': robot_description_config.toxml(),
'use_sim_time': use_sim_time,
#'odom_topic': robot['name'] + '/odom',
}
start_robot_state_publisher_cmd = launch_ros.actions.Node(
condition=IfCondition(use_robot_state_pub),
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
namespace=robot['name'],
output='screen',
#tf_prefix=robot['name'],
# remappings=[
# ('/cmd_vel', "/" + robot['name'] + '/cmd_vel'),
# ('/odom', "/" + robot['name'] + '/odom')
# ],
# remappings=[
# ('/tf', '/' + robot['name'] + '/tf'),
# ('/tf_static', '/' + robot['name'] + '/tf_static'),
# ],
remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')],
parameters=[params]
)
spawn_robots_cmds.append(start_robot_state_publisher_cmd)
params = { 'use_sim_time': use_sim_time}
joint_state_publisher_node = launch_ros.actions.Node(
package='joint_state_publisher',
executable='joint_state_publisher',
name='joint_state_publisher',
namespace=robot['name'],
parameters=[params],
#condition=launch.conditions.UnlessCondition(LaunchConfiguration('gui'))
# remappings=[
# #('/cmd_vel', "/" + robot['name'] + '/cmd_vel'),
# ('/robot_description', "/" + robot['name'] + '/robot_description'),
# ('/joint_states', "/" + robot['name'] + '/joint_states'),
# ],
#remappings = [('/tf', 'tf'), ('tf_static', 'tf_static')],
)
spawn_robots_cmds.append(joint_state_publisher_node)
spawn_robots_cmds.append(
IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(bringup_dir, 'launch',
'spawn_launch.py')),
launch_arguments={
'x_pose': TextSubstitution(text=str(robot['x_pose'])),
'y_pose': TextSubstitution(text=str(robot['y_pose'])),
'z_pose': TextSubstitution(text=str(robot['z_pose'])),
'robot_name': robot['name'],
}.items()))
# spawn_robots_cmds.append(
# launch_ros.actions.Node(
# package='rviz2',
# executable='rviz2',
# name='rviz2',
# namespace=robot['name'],
# arguments=['-d', rviz_config_file],
# # remappings=[
# # ("/" + robot['name'] + '/cmd_vel', '/cmd_vel'),
# # ("/" + robot['name'] + '/robot_description', '/robot_description'),
# # ("/" + robot['name'] + '/joint_states', '/joint_states'),
# # ("/" + robot['name'] + '/odom', '/odom')
# # ],
# output='screen'))
spawn_robots_cmds.append(IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(launch_dir, 'rviz_launch.py')),
condition=IfCondition(use_rviz),
launch_arguments={
'name': robot['name'],
'namespace': robot['name'],
'use_namespace': 'True',
'rviz_config': rviz_config_file}.items()))
</code></pre>
<p>Then the topic list doesn't contain odom, and robots are not displayed in Gazebo:</p>
<pre><code>$ ros2 topic list
/clock
/joint_states
/parameter_events
/performance_metrics
/received_global_plan
/robot1/cmd_vel
/robot1/goal_pose
/robot1/imu
/robot1/initialpose
/robot1/joint_states
/robot1/odom
/robot1/robot_description
/robot1/tf
/robot1/tf_static
/robot2/cmd_vel
/robot2/goal_pose
/robot2/imu
/robot2/initialpose
/robot2/joint_states
/robot2/odom
/robot2/robot_description
/robot2/tf
/robot2/tf_static
/robot_description
/rosout
/tf
/tf_static
</code></pre>
<p>My robot spawn:</p>
<pre><code>def generate_launch_description():
return LaunchDescription([
launch_ros.actions.Node(package='gazebo_ros', executable='spawn_entity.py',
arguments=
[
'-topic', 'robot_description',
'-entity', launch.substitutions.LaunchConfiguration('robot_name'),
'-robot_namespace', launch.substitutions.LaunchConfiguration('robot_name'),
'-x', launch.substitutions.LaunchConfiguration('x_pose'),
'-y', launch.substitutions.LaunchConfiguration('y_pose'),
'-z', launch.substitutions.LaunchConfiguration('z_pose'),
],
remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')],
output='screen')
])
</code></pre>
<p>Then only one robot moves in Gazebo (as expected), but in both copies of RViz robot "jumps" between two base_links.</p>
<p>How can I teach each copy of RViz to only show its robot?</p>
<p>P.S. I don't mind having two distinct robots in one RViz, but I do not know how to do it.</p>
|
<python><ros><robotics><ros2><gazebo-simu>
|
2023-05-15 11:41:43
| 1
| 449
|
Steve Brown
|
76,253,612
| 10,981,411
|
How do I create scrollbar on the frame using tkinter
|
<p>snippets of my codes are attached.</p>
<pre><code>import tkinter
from tkinter import *
root = tkinter.Tk()
root.geometry("1500x900")
root.title("ddw")
frame = tkinter.Frame(root)
#frame.grid(row=0,column=0,padx=20,pady=10)
frame.pack(fill="both", expand=True)
scrollbar = Scrollbar(frame)
scrollbar.pack(side="left",fill="y")
ls = [(x+1)*5 for x in range(10)]
for x in ls:
cnn_info_frame = tkinter.LabelFrame(frame, text="cn")
cnn_info_frame.grid(row=x, column=0, padx=20, pady=10)
vv1_label = tkinter.Label(cnn_info_frame, text="vv1")
vv1_label.grid(row=0, column=0)
vv2_label = tkinter.Label(cnn_info_frame, text="vv2")
vv2_label.grid(row=1, column=0)
vv3_label = tkinter.Label(cnn_info_frame, text="vv3")
vv3_label.grid(row=2, column=0)
vv1_entry = tkinter.Entry(cnn_info_frame)
vv2_entry = tkinter.Entry(cnn_info_frame)
vv3_entry = tkinter.Entry(cnn_info_frame)
vv1_entry.grid(row=0, column=1, padx=5, pady=5)
vv2_entry.grid(row=1, column=1, padx=5, pady=5)
vv3_entry.grid(row=2, column=1, padx=5, pady=5)
root.mainloop()
</code></pre>
<p>I am really new to tkinter and tech is not my background so any help is most appreciated. I want to create a scroll bar on the left so I added</p>
<pre><code>scrollbar = Scrollbar(frame)
scrollbar.pack(side="left",fill="y")
</code></pre>
<p>but that gives me this error</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/kamathp/PycharmProjects/CFOptimisation/00tkinter_eg4.py", line 20, in <module>
cnn_info_frame.grid(row=x, column=0, padx=20, pady=10)
File "C:\Users\kamathp\Anaconda3\envs\PA36\lib\tkinter\__init__.py", line 2226, in grid_configure
+ self._options(cnf, kw))
_tkinter.TclError: cannot use geometry manager grid inside .!frame which already has slaves managed by pack
</code></pre>
<p>how do I fix it?
My actually code has a lot of labelFrames button etc, but my main issue not able to add the scroll bar to the left.</p>
|
<python><tkinter>
|
2023-05-15 11:29:51
| 1
| 495
|
TRex
|
76,253,465
| 769,486
|
How to configure Celery to work as a reliable send queue
|
<p>I’m trying to use Celery in order to queue up HTTP-requests for sending to another service. The most important thing is that no data is lost, so every request is sent at least once. Additionally I want to know why tasks have failed even if they are retried.</p>
<p>I’ve had multiple failures with this so my current solution is to use a broad <code>autoretry_for</code> with <code>retry_backoff</code> and <code>acks_late</code>:</p>
<pre class="lang-py prettyprint-override"><code>class SendTask(celery.Task):
"""Celery task to send data."""
name = "app_name.send_data"
autoretry_for = (Exception,)
retry_backoff = 2 # This is the initial retry delay in seconds.
retry_backoff_max = 24 * 3600 # This is the maximum amount of time between retries.
max_retries = None # Never stop trying.
# Risk sending one event more than once rather than losing it when Celery fails.
acks_late = True
reject_on_worker_lost = True
def __init__(self, client):
self.client = client # Wrapper around the requests library
def run(self, data, *args, **kwargs): # pylint: disable=arguments-differ
"""Send data using a post request."""
data.setdefault("date", datetime.utcnow().isoformat())
self.client.post("endpoint", json=data) # throws an exception on any failure or non 2xx HTTP response.
</code></pre>
<p>Global configuration is just the broker:</p>
<pre class="lang-py prettyprint-override"><code>CELERY = {
"broker_url": "redis://localhost:6379/0",
}
</code></pre>
<ol>
<li>Tasks keep being retried even if the retry succeeds, leading to a huge amount of duplicates. → No log messages. Also no reliable way of monitoring the queue.</li>
<li>Restarting the worker leads to lost tasks: Although I get the message in the logs that says <code>Restoring xxx unacknowledged message(s)</code> the worker never takes up retrying after the restart. Data is lost.</li>
</ol>
<p>Is this something that Celery is able and suitable to handle? If so is anything obviously wrong with my configuration / expectations of how it should work?</p>
|
<python><celery>
|
2023-05-15 11:09:42
| 1
| 956
|
zwirbeltier
|
76,253,420
| 17,136,258
|
Calculate the avg days between two process steps
|
<p>I have a problem. I would like to calculate the time between two process steps ( <code>taskN+1_start - taskN_end</code> ) and avg it. How could I do that and later one I would like to merge it with the avg days of the process?</p>
<p>I tried something to calculate the time between the two process steps. The avg duration of the process worked for me.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
d = {'id': [1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2],
'step': ['Task1_Start', 'Task1_End1', 'Task2_Start', 'Task2_End', 'Task3_Start', 'Task3_End',
'Task1_Start', 'Task1_End1', 'Task2_Start', 'Task2_End', 'Task3_Start', 'Task3_End',],
'timestamp': ['2023-01-01', '2023-01-05', '2023-01-10', '2023-01-12', '2023-02-12', '2023-02-14',
'2023-01-01', '2023-01-05', '2023-01-10', '2023-01-12', '2023-01-15', '2023-02-16',]}
df = pd.DataFrame(data=d,)
[OUT]
id step timestamp
0 1 Task1_Start 2023-01-01
1 1 Task1_End1 2023-01-05
2 1 Task2_Start 2023-01-10
3 1 Task2_End 2023-01-12
4 1 Task3_Start 2023-02-12
5 1 Task3_End 2023-02-14
6 2 Task1_Start 2023-01-01
7 2 Task1_End1 2023-01-05
8 2 Task2_Start 2023-01-10
9 2 Task2_End 2023-01-12
10 2 Task3_Start 2023-01-15
11 2 Task3_End 2023-02-16
</code></pre>
<pre class="lang-py prettyprint-override"><code>df['task'] = df['step'].str.split('_').str[0]
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['duration'] = df.groupby('task')['timestamp'].diff().dt.days
avg_duration = df.groupby('task')['duration'].mean().reset_index()
print(avg_duration)
[OUT]
task duration
0 Task1 1.333333
1 Task2 0.666667
2 Task3 1.333333
</code></pre>
<pre class="lang-py prettyprint-override"><code>df['inter_task_duration'] = df.groupby('id')['timestamp'].diff().dt.days
avg_inter_task_duration = df.groupby('step')['inter_task_duration'].mean().reset_index()
print(avg_inter_task_duration)
[OUT]
step inter_task_duration
0 Task1_End1 4.0
1 Task1_Start NaN
2 Task2_End 2.0
3 Task2_Start 5.0
4 Task3_End 17.0
5 Task3_Start 17.0
# calculate the avg days between two process steps
</code></pre>
<p>What I want</p>
<pre class="lang-py prettyprint-override"><code> task duration
0 Task1 1.333333
1 Task2 0.666667
2 Task3 1.333333
3 Task1_to_Task2 ...
4 Task2_to_Task3 ...
</code></pre>
|
<python><pandas><dataframe>
|
2023-05-15 11:03:34
| 1
| 560
|
Test
|
76,253,353
| 13,381,632
|
How do I run inference on a Sagemaker endpoint?
|
<p>I am using AWS Sagemaker and Python to deploy an endpoint for a machine learning model, specifically to run inference on a set of image chips. However, when I execute the script to perform the inference, I get an error stating that the model container header exceeds a specified number of bytes. Below is a sample image (array) I am using to test the script and the output message captured.</p>
<pre><code>import numpy as np
arr = np.ones([2,320,320,1], dtype=np.uint8)
from sagemaker.predictor import Predictor, numpy_deserializer, NumpySerializer, NumpyDeserializer
predictor = Predictor(endpoint_name_serialzer=NumpySerializer(), deserializer=NumpyDeserizlier())
result=predictor.predict(arr)
print(result.shape)
-> Error in <virtual_env>/python3.8/site-packages/sagemaker/predictory.py in line 161
response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
ModelError: An error occurred (modelError) when calling the InvokeEndpoint operation:
Received server error (O) from model with message "Response received from the model container
has headers with length greater than 4096 bytes. Reduce the length of your containers's
response headers and update your endpoint See https://us-iso-east-
1.console.aws.amazon.com/cloudwatch/home?region=us-iso-east-
1#logEventViewer:group=/aws/sagemaker/Endpoints/ModelTest-mdl-1 in account 12345679012"
</code></pre>
<p>The error I receive occurs when trying to use the prediction function against the endpoint for "result=predictor.predict(arr)". I am trying to otherwise find examples of Sagemaker model container headers, but I am not having much luck. Any assistance is most appreciated.</p>
|
<python><amazon-web-services><machine-learning><amazon-sagemaker><endpoint>
|
2023-05-15 10:53:22
| 1
| 349
|
mdl518
|
76,253,298
| 5,168,463
|
"PyODBC [Error 10054] : TCP Provider: An existing connection was forcibly closed by the remote host" with fast_executemany=True
|
<p>I am trying to upload a sql into a sql server running in a docker container.
Below is the docker-compose.yml:</p>
<pre><code>version: '3.4'
services:
sqlserver:
image: mcr.microsoft.com/mssql/server
container_name: sqlserver
environment:
- ACCEPT_EULA=Y
- SA_PASSWORD=Password123
ports:
- "1433:1433"
volumes:
- ./sqldata:/var/opt/mssql/data
- ./data:/app/scripts
</code></pre>
<p>And here is my python code to load the csv into db:</p>
<pre><code>def connectSQLServer():
# Set up the connection information
server = 'localhost'
database = 'SLQBook'
username = 'sa'
password = 'Password123'
# Connect to the database
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password, autocommit=True)
# Set up a cursor to execute SQL statements
cursor = conn.cursor()
return conn, cursor
def loadDataBulk(cursor, mapping, tableName, delim = ','):
dataFileLoc = mapping[tableName.lower()]
print("dataFileLoc=", dataFileLoc)
cursor.fast_executemany = True
with open (dataFileLoc, 'r') as f:
reader = csv.reader(f, delimiter = delim)
headers = next(reader)
data = list(reader)[1:]
query = 'insert into {0} values ({1})'
query = query.format(tableName, ','.join('?' * len(headers)))
cursor.executemany(query, data)
print(f'{len(data)} rows inserted to the {tableName} table')
conn, cursor = connectSQLServer()
mapping = {"subscribers":"data/Subscribers.txt"}
loadDataBulk(cursor, mapping, tableName='subscribers', delim = '\t')
</code></pre>
<p>When i run this code, i am getting an error as:</p>
<pre><code>pyodbc.OperationalError: ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: An existing connection was forcibly closed by the remote host.\r\n (10054) (SQLExecute); [08S01] [Microsoft][ODBC Driver 17 for SQL Server]Communication link failure (10054)')
</code></pre>
<p>Where as when I load the data without <code>cursor.fast_executemany = True</code>, or when I load the data one by one using <code>cursor.execute(query, data)</code>, the data is loading successfully, but very slowly. Can someone help me understand why this error is coming only when I bulk load data with <code>cursor.fast_executemany = True</code>.</p>
|
<python><sql-server><pyodbc>
|
2023-05-15 10:46:58
| 1
| 515
|
DumbCoder
|
76,253,291
| 2,727,843
|
URI and package arguments are required while testing mobile browser automation with python and appium
|
<p>I am trying to run mobile browser automation with python and appium. I am providing required desired capabilities. But after running the script it is returning the error following</p>
<pre><code>selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: URI and package arguments are required Stacktrace:UnknownError: An unknown server-side error occurred while processing the command. Original error: URI and package arguments are required
at getResponseForW3CError (C:\Program Files\Appium Server GUI\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\errors.js:804:9)
at asyncHandler (C:\Program Files\Appium Server GUI\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\protocol.js:380:37)
</code></pre>
<p>My source code is provided below</p>
<pre><code>from appium import webdriver
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = {
'platformName': 'Android',
'deviceName': 'AQE6MVWWAEVOZLTO-r1HMVZ',
'udid': '22e051b70d1783d3',
'appPackage': 'com.android.chrome',
'appActivity': 'com.google.android.apps.chrome.Main',
'showChromedriverLog': True,
'automationName': 'UiAutomator2',
'noReset': False
}
web_driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
# Open a website
web_driver.get('https://www.google.com')
web_driver.find_element(By.XPATH, '//*[@id="js-search-autocomplete"]').send_keys("USA")
wait = WebDriverWait(web_driver, 10)
date = wait.until(ec.element_to_be_clickable((By.XPATH, '//*[@id="js-date-range-display"]')))
date.click()
time.sleep(125)
web_driver.execute_script('mobile: shell', {'command': 'pm', 'args': ['clear', 'https://www.rentbyowner.com']})
# Close the browser
web_driver.quit()
</code></pre>
<p>Please help me . If there is any something I am missing in desired capability?
Thanks in advance</p>
|
<python><android><selenium-webdriver><appium>
|
2023-05-15 10:46:05
| 1
| 793
|
Mahboob Nur
|
76,253,242
| 4,665,335
|
Celery - retrieving children from group identifier
|
<p>Is it possible to retrieve a list of tasks using only a group identifier?</p>
<pre class="lang-py prettyprint-override"><code>from celery import group
def f1():
task_group = group(task1, task2)
return task_group().id
def f2(group_id):
pass
# TODO: return task1.id and task2.id
</code></pre>
<p><code>GroupResult(id=f1()).children</code> returns <code>None</code></p>
|
<python><redis><celery>
|
2023-05-15 10:39:36
| 1
| 400
|
michal111
|
76,253,162
| 8,028,981
|
Resize image with PIL and keep orientation
|
<p>I use the following commands to resize some JPGs:</p>
<pre><code>from PIL import Image
im = Image.open(...)
im = im.resize(...)
im.save(...)
</code></pre>
<p>Some images that are shown on my screen in portrait orientation are after the resizing operation shown in landscape.</p>
<p>Is there a quick way to assure that the resized images have the same orientation as the original?</p>
<p>This is the full script that I use:</p>
<pre><code>from PIL import Image
import os, sys
final_size = 1200;
def resize_aspect_fit(dir):
dirs = os.listdir(dir)
print("resizing " + dir)
for item in dirs:
if item == 'resize.py':
continue
if item == 'resized':
continue
if os.path.isdir(dir + item):
resize_aspect_fit(dir + item + "\\")
elif os.path.isfile(dir + item):
print("processing " + item)
im = Image.open(dir + item)
f, e = os.path.splitext(item)
size = im.size
ratio = float(final_size) / max(size)
new_image_size = tuple([int(x*ratio) for x in size])
im = im.resize(new_image_size, Image.ANTIALIAS)
if not os.path.isdir("resized\\" + dir):
os.makedirs("resized\\" + dir)
im.save("resized\\" + dir + f + '_%ipix.jpg'%final_size, 'JPEG', quality=90)
else:
print(dir + item + " not a file")
resize_aspect_fit(".\\")
</code></pre>
|
<python><image><python-imaging-library><image-resizing>
|
2023-05-15 10:28:31
| 1
| 1,240
|
Amos Egel
|
76,253,092
| 6,400,443
|
Airflow - Task not stopping correctly when setting it to Failed state
|
<p>We have a task A inside a dag B, running a big Redshift query, that can take up to 3 hours to run.
For some business reason that task can be "killed" by an other task, to perform that, we are first detecting if a dag B is running, if it's the case, we are requesting the running tasks, in our case, it's task A most of the time. We are using <code>ti.set_state(State.FAILED)</code> to set the state to Failed. Ultimately, we are setting the full dag run to state Failed with <code>dag.set_state(DagRunState.FAILED)</code></p>
<p>Theorically, the task run should kill the running query, close the session, and Redshift on it side should release the lock shortly after since the session is supposed to be terminated.</p>
<p>However, we can see in our "redshift lock viewer" that, not only the lock is not released, but the query is still running after the task as been set to Failed. We check that by requesting the table <code>STV_RECENTS</code> with the right PID.</p>
<p>We tried to use a SIGTERM handler, to gracefully perform <code>cursor.close()</code> but it's giving weird error, and Airflow has to use SIGKILL after a short period of time. Also we tried with</p>
<pre><code>try:
... Do the query ...
finally:
cursor.close()
</code></pre>
<p>But we end up with the same problem than the handler.</p>
<p>Is there a way to gracefully kill the task and be sure the lock is released ?</p>
|
<python><sql><airflow><amazon-redshift>
|
2023-05-15 10:19:32
| 0
| 737
|
FairPluto
|
76,252,996
| 13,770,014
|
How to input() after reading stdin in python?
|
<p>This simple code:</p>
<pre><code>#!/usr/bin/env python3
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode()
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ') #input does not return after new line or even EOF (ctrl-d)
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print('User terminated.')
self.socket.close()
sys.exit()
def listen(self):
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Net Tool',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent(
'''Examples:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''
)
)
parser.add_argument('-c', '--command', action='store_true', help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int, default=5555, help='specified port')
parser.add_argument('-t', '--target', default='127.0.0.1', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read() # stdin is used here, but should that change behaviour of subsequence reading - input() ?
nc = NetCat(args, buffer.encode())
nc.run()
</code></pre>
<p>After <code>input('> ')</code>, the prompt never returns, neither after newline nor EOF. Is it because of previous <code>sys.stdin.read()</code>? Whats going on</p>
<p>The file is triggered</p>
<ol>
<li>without input: <code>$ python3 test.py -p 9998</code> or <code>$ ./test.py -p 9998</code>. Then it waits after I enter a message, it is send to server and <code>'> '</code> prompt appear (for another message). At which point comes situation described above - after typing the new message, after new line or EOF, nothing happens. The <code>input()</code> does not return.</li>
<li>with some stdin redirection, e.g <code>$ echo 'ABC' | python3 test.py -p 9998</code> in which case, the message <code>ABC</code> is sent, but <code>input()</code> immediately throws <code>EOFError: EOF when reading a line</code>. So there is no prompt at all.</li>
</ol>
|
<python><input><io><stdin>
|
2023-05-15 10:07:03
| 0
| 2,017
|
milanHrabos
|
76,252,954
| 2,562,058
|
How to reload a package when it is installed in editable mode?
|
<p>I know that to reload a package installed with e.g. <code>pip install .</code> you can</p>
<pre><code>import importlib
importlib.reload(module)
</code></pre>
<p>but this approach does not seem to work when the package is installed with <code>pip install -e .</code>.</p>
<p>Is there any way to reload a package when it is installed in editable mode?</p>
|
<python><python-3.x>
|
2023-05-15 10:01:45
| 1
| 1,866
|
Barzi2001
|
76,252,878
| 2,932,907
|
How to get the value of a key, value pair in a list of dictionaries
|
<p>I've got a list of dictionaries with key, value pairs. I am trying to create a function that retrieves the value when a specific key is given. I've done the following but I'm not getting any further.</p>
<pre><code>my_list = [
{'name': 'address', 'value': 'Testraat 100'},
{'name': 'ripeID', 'value': 'nan'},
{'name': 'name', 'value': 'Admin Account'},
{'name': 'phone', 'value': '+31 6 12345678'},
{'name': 'email', 'value': 'admin@domein.nl'}
]
def get_value(lst, key):
for d in lst:
for k, v in d.items():
if v == key:
print(v)
address = get_value(my_list, 'address')
# prints: address
# desired answer: Teststraat 100
</code></pre>
|
<python><python-3.x><list><dictionary>
|
2023-05-15 09:53:21
| 3
| 503
|
Beeelze
|
76,252,844
| 3,719,167
|
Pandas remove time format from date object when json serializing
|
<p>I using pandas to get analytics based on date, where the time passed is datetime. When JSON serializing, the date object is converted to string including time like</p>
<pre class="lang-py prettyprint-override"><code># Extract date from scan_time
df['date'] = pd.to_datetime(df['scan_time'], format='%Y-%m-%d').dt.date
# Extract analytics
grouped_total = df.groupby('date').size().reset_index(name='total_count')
grouped_false = df[df['is_from_qr_code_scan'] == False].groupby('date').size().reset_index(name='false_count')
grouped_true = df[df['is_from_qr_code_scan'] == True].groupby('date').size().reset_index(name='true_count')
# Merge result
result = pd.merge(grouped_total, grouped_false, on='date', how='outer')
result = pd.merge(result, grouped_true, on='date', how='outer')
# Format date
# result['date'] = result['date'].dt.strftime('%Y-%m-%d')
# Fill missing dates with 0
result = result.set_index('date')
date_range = pd.date_range(start=result.index.min(), end=result.index.max(), freq='D')
result = result.fillna(0)
result = result.reindex(date_range, fill_value=0)
count_total = result[['total_count']].reset_index().values.tolist()
count_url = result[['false_count']].reset_index().values.tolist()
count_qr = result[['true_count']].reset_index().values.tolist()
data = {
'all': count_total,
'qr': count_qr,
'url': count_url
}
</code></pre>
<p>Output</p>
<pre><code>{'all': [[Timestamp('2023-04-27 00:00:00'), 91],
[Timestamp('2023-04-28 00:00:00'), 269],
[Timestamp('2023-04-29 00:00:00'), 0],
[Timestamp('2023-04-30 00:00:00'), 0],
[Timestamp('2023-05-01 00:00:00'), 111],],
'qr': [[Timestamp('2023-04-27 00:00:00'), 36.0],
[Timestamp('2023-04-28 00:00:00'), 45.0],
[Timestamp('2023-04-29 00:00:00'), 0.0],
[Timestamp('2023-04-30 00:00:00'), 0.0],
[Timestamp('2023-05-01 00:00:00'), 26.0],],
'url': [[Timestamp('2023-04-27 00:00:00'), 55],
[Timestamp('2023-04-28 00:00:00'), 224],
[Timestamp('2023-04-29 00:00:00'), 0],
[Timestamp('2023-04-30 00:00:00'), 0],
[Timestamp('2023-05-01 00:00:00'), 85],]}
</code></pre>
<p>I only want date <code>2023-04-28</code> and not the time part in the final result to return in API response.</p>
<p>I tried using <code>result['date'] = result['date'].dt.strftime('%Y-%m-%d')</code> but it gives error</p>
<pre><code>AttributeError: Can only use .dt accessor with datetimelike values
</code></pre>
|
<python><pandas><date><datetime>
|
2023-05-15 09:49:13
| 2
| 9,922
|
Anuj TBE
|
76,252,827
| 11,208,548
|
Django: static files not served locally
|
<p>I know this question was previously asked and I already tried many different configurations to fix this. I had no problem serving my static files locally when developing but, if I remember correctly (don't know exactly because of the browser cache), I ran <code>python manage.py collectstatic</code> and then all static files were nowhere to be found:</p>
<pre class="lang-bash prettyprint-override"><code>[15/May/2023 08:55:59] "GET /static/js/script.js HTTP/1.1" 404 179
[15/May/2023 08:55:59] "GET /static/admin/css/responsive.css HTTP/1.1" 404 179
...
</code></pre>
<p>Here is my <code>settings.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>DEBUG = ENV.bool("DEBUG") # set to True
INSTALLED_APPS = [
"django.contrib.staticfiles",
...
]
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / STATIC_PATH # I have checked that the path is correct
STATICFILES_DIRS = [ # I tried with and without STATICFILES_DIRS
BASE_DIR / "vhsapp" / "static"
]
</code></pre>
<p><code>urls.py</code></p>
<pre class="lang-py prettyprint-override"><code>...
if settings.DEBUG:
urlpatterns += [
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT),
]
</code></pre>
<p><code>base_site.html</code></p>
<pre class="lang-html prettyprint-override"><code>{% extends "admin/base_site.html" %}
{# TEMPLATE EXTENSION FOR THE DEFAULT ADMIN INTERFACE #}
{% load static %}
{% block extrahead %}
{{ block.super }}
<link rel="icon" type="image/x-icon" href="{% static 'img/favicon.png' %}"> <!-- 404 error -->
<script>
const APP_NAME = "{{ APP_NAME }}"; // variable defined correctly
</script>
{% endblock %}
</code></pre>
<p><code>Project arborescence</code></p>
<pre><code>project_root/
├── staticfiles/ # all static files are inside this directory
├── templates/
│ └── admin/
│ └── base_site.html
├── vhs/
│ ├── .env
│ ├── urls.py
│ └── settings.py
├── vhsapp/
│ ├── static/ # additional static files (collectstatic put them inside staticfiles/)
│ ├── templates/ # additional templates
│ └── __init__.py
└── manage.py
</code></pre>
<p>I have read the <a href="https://docs.djangoproject.com/en/dev/howto/static-files/" rel="nofollow noreferrer">docs</a> but I really cannot see what might have happened. I know the project arborescence is a little weird but everything used to work!</p>
<p>Do you have any idea what i am missing?</p>
<p>Thank you X1000</p>
|
<python><django><django-templates><django-staticfiles>
|
2023-05-15 09:46:45
| 1
| 501
|
Seglinglin
|
76,252,762
| 14,728,691
|
In Kubernetes Python pod, how to notify by email only one time everytime new file arrive in PVC?
|
<p>In Kubernetes I am trying to monitor and notify by email new files arriving in Persistent Volume Claim. So I tried this in Python :</p>
<pre><code>import os
import time
import smtplib
from email.mime.text import MIMEText
# Email configuration
smtp_server = 'V'
smtp_port = 25
sender_email = 'X'
receiver_email = 'Y'
# Set up the directory to monitor
dir_to_monitor = '/mnt/'
# Set up a list to store processed files
processed_files = []
# Function to recursively explore directories and detect new files
def explore_directory(directory):
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
if file_path not in processed_files:
# New file detected
processed_files.append(file_path)
print("New file:", file_path)
send_notification_email(file_path)
# Function to send email notification
def send_notification_email(file_path):
subject = 'New file arrived'
message = f"A new file has arrived:\n\nDirectory: {os.path.dirname(file_path)}\nFile: {file_path}"
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.sendmail(sender_email, receiver_email, msg.as_string())
# Continuously monitor the directory for new files
while True:
explore_directory(dir_to_monitor)
time.sleep(5)
</code></pre>
<p>Problem is that I receive same email concerning same new file.
Also if my pod is KO and deployed again, processed_files list will be empty again and all files will be considered as new ones.</p>
<p>What can I modify in Kubernetes to have only one mail when a new file arrive in PVC ?</p>
|
<python><kubernetes>
|
2023-05-15 09:38:57
| 0
| 405
|
jos97
|
76,252,721
| 11,009,630
|
How to get same color when plotting numpy image array for same pixel value multiple times
|
<p>I am trying to work on some pixel manipulation on a sequence of images. I encountered an issue when plotting same value of pixel having different color when plotted with different range of pixels.</p>
<p>For example, I have an image with six different pixel values(0, 2, 3, 4, 5, 6):</p>
<p>Code #1 :</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
import cv2
image = np.zeros(shape=[256, 256], dtype=np.uint8)
cv2.circle(image, center=(50, 50), radius=10, color=(2, 2), thickness= -1)
cv2.circle(image, center=(100, 100), radius=10, color=(3, 3), thickness= -1)
cv2.circle(image, center=(150, 150), radius=10, color=(4, 4), thickness= -1)
cv2.circle(image, center=(75, 200), radius=10, color=(5, 5), thickness= -1)
cv2.circle(image, center=(200, 89), radius=10, color=(6, 6), thickness= -1)
plt.imshow(image)
plt.show()
</code></pre>
<p>Output:
<a href="https://i.sstatic.net/e8idk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/e8idk.png" alt="image 1" /></a></p>
<p>Now when I add two more shapes in the image with different pixel value(7, 12), then color for all the existing pixels changes</p>
<p>Code #2 :</p>
<pre class="lang-py prettyprint-override"><code>image = np.zeros(shape=[256, 256], dtype=np.uint8)
cv2.circle(image, center=(50, 50), radius=10, color=(2, 2), thickness= -1)
cv2.circle(image, center=(100, 100), radius=10, color=(3, 3), thickness= -1)
cv2.circle(image, center=(150, 150), radius=10, color=(4, 4), thickness= -1)
cv2.circle(image, center=(75, 200), radius=10, color=(5, 5), thickness= -1)
cv2.circle(image, center=(200, 89), radius=10, color=(6, 6), thickness= -1)
cv2.circle(image, center=(21, 230), radius=5, color=(7, 7), thickness= -1)
cv2.circle(image, center=(149, 250), radius=5, color=(12, 12), thickness= -1)
plt.imshow(image)
plt.show()
</code></pre>
<p>Output:
<a href="https://i.sstatic.net/WfeZj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WfeZj.png" alt="enter image description here" /></a></p>
<p>How can I ensure same value of pixel gives me same color irrespective of any other pixel present or not?</p>
|
<python><image><numpy><matplotlib>
|
2023-05-15 09:33:39
| 1
| 646
|
Deep
|
76,252,583
| 12,466,687
|
Plotly express bar plot doesn't sort properly in streamlit (cache issues or bug in streamlit). Need Rerun from top 3lines each time to fix?
|
<p>I have created a <strong>dashboard</strong> using <code>polars(python)</code>, <code>streamlit</code> which includes some <strong>bar plots</strong> that I need to keep it <strong>sorted</strong>.</p>
<p><strong>Webapp link</strong>: <a href="https://vineet-eda-mmm.streamlit.app/" rel="nofollow noreferrer">https://vineet-eda-mmm.streamlit.app/</a></p>
<p><strong>Github Repo py file link</strong>: <a href="https://github.com/johnsnow09/EDA_APP_MMM_LargeFile/blob/main/MMM_EDA-whole_data.py" rel="nofollow noreferrer">https://github.com/johnsnow09/EDA_APP_MMM_LargeFile/blob/main/MMM_EDA-whole_data.py</a></p>
<p>I would like my data to stay sorted as in below image:
<a href="https://i.sstatic.net/2fTCh.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2fTCh.png" alt="Desired sorted chart" /></a></p>
<p>But by default when I open the weblink it comes like below:
<a href="https://i.sstatic.net/rNO18.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rNO18.png" alt="Unsorted chart" /></a></p>
<p><strong>Note:</strong></p>
<ol>
<li>When I open the app it comes <strong>unsorted</strong> even in <code>incognito mode</code>.</li>
<li>It doesn't sort even on refreshing the page.</li>
<li>It doesn't sort even on <code>clearing cache</code> & then refreshing the page.</li>
<li>It <strong>Sorts</strong> and shows correct plot when I <strong>"Rerun"</strong> from the top right hand corner 3 lines.</li>
<li>Same is happening in other bar plots in this webapp as well.</li>
</ol>
<p>Why would anyone visiting the link would know to click "Rerun" from the top3 lines. It looks like a <strong>bug or cache problem to me</strong>.</p>
<p><strong>Code</strong> I have used to sort:</p>
<pre><code>fig_pincode_gmv_facet = px.bar(df_pincode_gmv_facet(),
x='total_gmv',y='pincode',facet_col='Year',
orientation='h',
# hover_name='Party',
labels={
"total_gmv": "Total GMV"
},
category_orders={'Year':[2015,2016]},
title=f'<b>Top 15 Pincodes by Total GMV in respective Years</b>'
).update_yaxes(type='category', categoryorder='max ascending') #
st.plotly_chart(fig_pincode_gmv_facet,use_container_width=True, config = config)
</code></pre>
<p>It doesn't seems like a code issue but would appreciate any help.</p>
<p><strong>UPDATE</strong>:</p>
<p><strong>1.</strong></p>
<p>If I comment <code>categoryorder</code> part of the code then graph changes to ascending sort of order</p>
<pre><code>).update_yaxes(type='category') # , categoryorder='max ascending'
</code></pre>
<p><a href="https://i.sstatic.net/YJgId.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YJgId.png" alt="graph changed on commenting categoryorder" /></a></p>
<p><strong>2.</strong></p>
<p>I also have doubt on how <strong>plotly express</strong> <code>categoryorder='max ascending'</code> works. I ran code <strong>locally</strong> on <code>vscode</code> without <code>streamlit</code> and got <strong>unsorted</strong> graph, shown below:</p>
<p><a href="https://i.sstatic.net/uAVJc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uAVJc.png" alt="unsorted plot result in local vscode jupyter notebook" /></a></p>
|
<python><pandas><plotly><streamlit><python-polars>
|
2023-05-15 09:20:13
| 0
| 2,357
|
ViSa
|
76,252,498
| 1,433,751
|
How to simplify a logical expression with several FiniteSets
|
<p>Using the Python package <code>sympy</code> (version 1.12) I have several <code>FiniteSet</code>s and an expression I want to simplify/optimize.</p>
<p>As an example says more than thousand words:</p>
<pre class="lang-py prettyprint-override"><code>from sympy import Symbol, FiniteSet, simplify_logic, Contains
a = Symbol("a")
x = FiniteSet("1", "2")
y = FiniteSet("2", "3")
z = FiniteSet("3", "4")
>>> simplify_logic(Contains(a, x) & Contains(a, z))
Returned: Contains(a, {1, 2}) & Contains(a, {3, 4})
Expected: False
>>> simplify_logic(Contains(a, x) & Contains(a, y))
Returned: Contains(a, {1, 2}) & Contains(a, {2, 3})
Expected: Contains(a, {2})
>>> simplify_logic(Contains(a, x) | Contains(a, y))
Returned: Contains(a, {1, 2}) & Contains(a, {2, 3})
Expected: Contains(a, {1, 2, 3})
>>> simplify_logic(Contains(a, x) | Contains(a, z))
Returned: Contains(a, {1, 2}) | Contains(a, {3, 4})
Expected: Contains(a, {1, 2, 3, 4})
</code></pre>
<p>For clarity, in case of an additional symbol <code>b = Symbol("b")</code>, the following would be expected:</p>
<pre class="lang-py prettyprint-override"><code>>>> simplify_logic(Contains(a, x) & Contains(b, x))
Returned/Expected: Contains(a, {1, 2}) & Contains(b, {1, 2})
>>> simplify_logic(Contains(a, x) | Contains(b, x))
Returned/Expected: Contains(a, {1, 2}) | Contains(b, {1, 2})
</code></pre>
<p>It seems that <code>sympy</code> does not handle such simplifications (yet).
For my particular use-case, the examples/simplifications given above would already cover my use-cases as my application only uses <code>FiniteSet</code>s.</p>
<p><strong>Question:</strong>
Is there already a way to let <code>sympy</code> do the simplifications as shown above directly out of the box? If not, would it be possible (and how) to e.g. extend the <code>FiniteSet</code> class to cover such cases?<br />
Or is this not possible/advised as there are any edge-cases I could not think of?</p>
<p>Note: To play around, one needs to use the current master as a recent bug <a href="https://github.com/sympy/sympy/issues/25115" rel="nofollow noreferrer">preventing <code>Contains</code> to be simplified at all</a> has been fixed (Thanks!)</p>
|
<python><logic><sympy><logical-operators>
|
2023-05-15 09:09:28
| 2
| 384
|
Noxx
|
76,252,415
| 5,881,882
|
Python: mask array, process subarrays and concatenate the results together following original ordering
|
<p>Here is my working example. I either check whether at least one entry of the events is 1 or only the first entry is 1 depending on whether the id exists.</p>
<pre><code>import numpy as np
import pandas as pd
data = pd.DataFrame({"id": [None, 'a', None, 'b', 'c', 'd', 'e']})
events = np.array([[0, 0, 0, 1, 0, 0, 0],
[1, 0, 1, 1, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 1]]).T
# expectations to be either aggressive or normal
# 1 - no id and event2
# 0 - no events
# 1 - no id and event2 and event3
# 1 - id but event1
# 0 - id thus event2 neglected
# 0 - id thus event3 neglected
# 0 - id thus event2 and event 3 neglected
mask = data['id'].notna()
result = np.zeros(len(data))
result[mask] = events[mask].T[0].astype(float)
result[~mask] = np.any(events[~mask], axis=1).astype(float)
</code></pre>
<p>it returns <code>array([1., 0., 1., 1., 0., 0., 0.])</code> as expected.</p>
<p>I am asking myself, whether there is a more elegant and / or also more performant way to achieve the same.</p>
<p>A list comprehension would be a one liner, but I assume it would be slower (?)</p>
<p>edit: <code>arr = events</code>. I wanted to make a better naming</p>
<p>logic:</p>
<pre><code>if id != None, return the first bit of the events array
else check whether at least one bit of the events array is 1
</code></pre>
|
<python><pandas><numpy>
|
2023-05-15 08:58:48
| 1
| 388
|
Alex
|
76,252,232
| 2,955,827
|
How to use multiprocess in decorator
|
<p>I want to create a decorator which make function accept single argument to deal with iterable arguments parallel.</p>
<p>Here is the example code:</p>
<pre class="lang-py prettyprint-override"><code>import functools
import time
from multiprocessing import Pool
def parallel(func):
def wrapper(iterable):
with Pool() as pool:
result = pool.map(func, iterable)
return result
return wrapper
@parallel
def test(i):
time.sleep(1)
print(f"{i}: {i * i}")
def main():
test(range(10))
if __name__ == "__main__":
main()
</code></pre>
<p>But I got</p>
<pre><code>Traceback (most recent call last):
File "/home/user/projects/amdb/s2.py", line 29, in <module>
main()
File "/home/user/projects/amdb/s2.py", line 25, in main
test(range(10))
File "/home/user/projects/amdb/s2.py", line 10, in wrapper
result = pool.map(func, iterable)
File "/usr/lib/python3.10/multiprocessing/pool.py", line 367, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "/usr/lib/python3.10/multiprocessing/pool.py", line 774, in get
raise self._value
File "/usr/lib/python3.10/multiprocessing/pool.py", line 540, in _handle_tasks
put(task)
File "/usr/lib/python3.10/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "/usr/lib/python3.10/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function test at 0x7fef63309120>: it's not the same object as __main__.test
</code></pre>
<p>I know I could fix this by not using decorator, something like <code>test_multi = parallel(test)</code> , but the problem is how to use it in decorator.</p>
|
<python><multiprocessing>
|
2023-05-15 08:35:01
| 1
| 3,295
|
PaleNeutron
|
76,252,214
| 11,805,922
|
How to parse google search result the numbers
|
<pre><code>import requests
from bs4 import BeautifulSoup
# Make a request to Google Search
response = requests.get("https://www.google.com/search?q=book")
soup = BeautifulSoup(response.content, 'html.parser')
phrase_extract = soup.find_all(id="result-stats")
print(phrase_extract)
</code></pre>
<p>The output is</p>
<pre><code>[]
</code></pre>
<p>I checked the web source directly on Chrome browser, I can see this:</p>
<pre><code><div id="result-stats">About 13,120,000,000 results<nobr> (0.51 seconds)&nbsp;</nobr></div>
</code></pre>
<p>However, if I print the <code>response.text</code>, I can't find this string.</p>
<p><strong>Update:</strong>
This code will work:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
# Make a request to Google Search
response = requests.get("https://www.google.com/search?q=book",
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59'})
soup = BeautifulSoup(response.content, 'html.parser')
phrase_extract = soup.find_all(id="result-stats")
print(phrase_extract)
</code></pre>
<p>The only difference is the <code>headers</code></p>
|
<python><web-scraping><beautifulsoup><python-requests>
|
2023-05-15 08:33:18
| 1
| 1,065
|
Mark Kang
|
76,252,112
| 4,576,519
|
How to skip objects when unpickling in Python
|
<p>I'm dumping many large objects in a file using <code>pickle</code> sequentially. Afterwards, I would like to read one of the objects <em>without loading all the objects in front of it</em>. As an example, consider a simple file containing only numbers.</p>
<pre class="lang-py prettyprint-override"><code>import pickle
# Save data
with open('example.p', 'ab') as f:
for i in range(10):
pickle.dump(i, f)
</code></pre>
<p>Afterwards, I would like to get the object at some given index. I have written a function as follows:</p>
<pre class="lang-py prettyprint-override"><code># Load data
def get_ith_object (index):
with open('example.p', 'rb') as f:
for i in range(index+1):
obj = pickle.load(f)
if i == index:
return obj
print(get_ith_object(5)) # prints "5"
</code></pre>
<p>While this works, it can take very long to reach the <code>i</code>th object when the file contains many large objects. Is there a way I can skip objects, and jump to the <code>i</code>th object directly (or reasonably fast)?</p>
<p>Related question: <a href="https://stackoverflow.com/questions/55809976/seek-on-pickled-data">Seek on Pickled Data</a></p>
|
<python><indexing><io><pickle>
|
2023-05-15 08:16:51
| 1
| 6,829
|
Thomas Wagenaar
|
76,251,915
| 1,150,683
|
Adding environment vars to remote development in PyCharm
|
<p>There are already a number of posts about using remote development in PyCharm but as far as I can tell none of them describe this specific question.</p>
<p>In PyCharm we can use Remote Development, for instance by using an SSH environment and running everything off a server. I am using this successfully and apart from a quirk here and there I am quite satisfied.</p>
<p>One issue that I am facing, however, is that I sometimes need to run GPU-accelerated code. Usually, if I were to submit/run a job I would just use <code>CUDA_VISIBLE_DEVICES=0</code> or something similar to specify which device to run my job on. My question is, how can I tell PyCharm to <em>always</em> use this environment variable for this remote development and not having to specify it each time when trying to run a script? This way, I could ask the rest of my team to each do the same so everyone has their one dedicated GPU to work on.</p>
<p>I am aware that I can still use the terminal to run my scripts or use the script-specific configs in PyCharm, but those are specific to one single command. I want the environment variable to be used for <em>all</em> python call to the remote server. How can I do that?</p>
|
<python><pycharm><environment-variables><remote-debugging>
|
2023-05-15 07:48:56
| 0
| 28,776
|
Bram Vanroy
|
76,251,837
| 6,472,878
|
Default values for TypedDict
|
<p>Let's consider I have the following TypedDict:</p>
<pre class="lang-py prettyprint-override"><code>class A(TypedDict):
a: int
b: int
</code></pre>
<p>What is the best practice for setting default values for this class?</p>
<p>I tried to add a constructor but it doesn't seem to work.</p>
<pre class="lang-py prettyprint-override"><code>class A(TypedDict):
a: int
b: int
def __init__(self):
TypedDict.__init__(self)
a = 0
b = 1
</code></pre>
<p>EDIT:
I don't want to use dataclass because I need to serialize and deserialize to JSON files and dataclasses have some problem with it.</p>
<p>What do you think?</p>
|
<python><typeddict>
|
2023-05-15 07:38:18
| 6
| 348
|
Gil Ben David
|
76,251,705
| 17,136,258
|
Create a heatmap for a process
|
<p>I have a problem. I want to create a process with a heatmap. To see how long each step took.
I created the process with <code>PyDot</code> and created a <code>dataframe</code> for the individuall steps.</p>
<p>How could I create a heatmap for my process?</p>
<p>The calculation should be also include the from-step-to-step time.
So you can calculate the edges time e.g <code>task1_start - start</code> / <code>task2_start - task1_end</code>
And you can calculate the nodes time e.g. <code>task1_end - task1_start</code> / <code>task2_end - task2_start</code>.</p>
<p>My MVP only changes the color of the border. But I want to create a real heatmap.</p>
<p><a href="https://i.sstatic.net/0n0Kc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0n0Kc.png" alt="enter image description here" /></a></p>
<p><strong>Process</strong></p>
<pre class="lang-py prettyprint-override"><code>import pydot
from IPython.display import SVG
graph = pydot.Dot(graph_type='digraph')
task_node1 = pydot.Node("Task1", shape="box",)
task_node2 = pydot.Node("Task2", shape="box",)
graph.add_node(task_node1)
graph.add_node(task_node2)
task1_to_task2_edge = pydot.Edge("Task1", "Task2",)
graph.add_edge(task1_to_task2_edge)
graph.write_svg("diagram.svg")
SVG('diagram.svg')
</code></pre>
<p><a href="https://i.sstatic.net/Ek3bB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Ek3bB.png" alt="enter image description here" /></a></p>
<p><strong>Dataframe</strong></p>
<pre class="lang-py prettyprint-override"><code>
id step timestamp
0 1 task1_start 2023-01-01
1 1 task1_End 2023-01-05
2 1 task2_start 2023-01-10
3 1 task2_end 2023-01-12
4 2 task1_start 2023-01-01
5 2 task1_End 2023-01-05
6 2 task2_start 2023-01-10
7 2 task2_end 2023-01-12
</code></pre>
<p><strong>MVP</strong></p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
d = {'id': [1, 1, 1, 1,
2, 2, 2, 2,],
'step': ['task1_start', 'task1_End', 'task2_start', 'task2_end',
'task1_start', 'task1_End', 'task2_start', 'task2_end',],
'timestamp': ['2023-01-01', '2023-01-05', '2023-01-10', '2023-01-12',
'2023-01-01', '2023-01-05', '2023-01-10', '2023-01-12',]}
df = pd.DataFrame(data=d,)
df['timestamp'] = pd.to_datetime(df['timestamp'])
g = df.groupby('id')
out = (df
.assign(duration=df['timestamp'].sub(g['timestamp'].shift()),
step=lambda d: (df['step']+'/'+g['step'].shift()).str.replace(
r'([^_]+)[^/]*/([^_]+)[^/]*',
lambda m: m.group(1) if m.group(1)==m.group(2) else f"{m.group(2)}_to_{m.group(1)}",
regex=True)
)
[['id', 'step', 'duration']].dropna(subset=['duration'])
)
df = out
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
colors = mcolors.LinearSegmentedColormap.from_list(
'LightBlueGreenYellowRed', ['#B0E0E6', '#87CEEB', '#00FF00', '#ADFF2F', '#FFFF00', '#FFD700', '#FFA500', '#FF4500', '#FF0000', '#FF6347', '#FF7F50', '#FFA07A', '#FFC0CB', '#FFB6C1', '#FF69B4', '#DB7093', '#FF1493', '#C71585', '#FF00FF']
)
def get_color(value, vmin, vmax):
norm = (value - vmin) / (vmax - vmin)
cmap = colors(norm)
return mcolors.to_hex(cmap)
vmin = df['duration'].min()
vmax = df['duration'].max()
df['color'] = df['duration'].apply(lambda x: get_color(x, vmin, vmax))
def get_color(id):
if (df['step'] == id).any():
color = df.loc[df['step'] == id, 'color'].values[0]
if pd.isnull(color):
return '#808080'
else:
return color
else:
return '#808080'
import pydot
from IPython.display import SVG
graph = pydot.Dot(graph_type='digraph')
task_node1 = pydot.Node("Task1", shape="box", color = get_color('task1'))
task_node2 = pydot.Node("Task2", shape="box", color = get_color('task2'))
graph.add_node(task_node1)
graph.add_node(task_node2)
task1_to_task2_edge = pydot.Edge("Task1", "Task2", color = get_color('task1_to_task2'))
graph.add_edge(task1_to_task2_edge)
graph.write_svg("diagram.svg")
SVG('diagram.svg')
</code></pre>
<p><a href="https://i.sstatic.net/atrdQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/atrdQ.png" alt="enter image description here" /></a></p>
|
<python><pandas><svg><pydot>
|
2023-05-15 07:18:58
| 2
| 560
|
Test
|
76,251,638
| 3,110,621
|
Chunked or Streamed output of Azure Function Response with python
|
<p>the question is very simple. I am in an azure function environment using python as programming language. My goal is to create a nd-json because I have a huge result and I want it to be returned to the caller as nd-json in a stream so I can easily consume it chunk by chunk or better line by line.</p>
<p>The problem is that the</p>
<pre><code>import azure.functions as func
func.HttpResponse
</code></pre>
<p>that has to be returned does only accept bytes, string or integer. There is no possibility to put a generator here.</p>
<p>I read on stackoverflow somebody who suggested to use a django StreamingHttpResponse. However this also does not help because in the end I have to encapslulate it into the HttpResponse object from python.</p>
<p>So is there really no way in azure function context to create a real nd-json ? This would be really a shame because I don't want to use orchestration or some other overly sophisticated solution when I could just stream my data.</p>
|
<python><stream><azure-functions><chunks><ndjson>
|
2023-05-15 07:09:30
| 1
| 956
|
tuxmania
|
76,251,548
| 14,468,588
|
TypeError: 'numpy.complex128' object is not iterable
|
<p>Here is the object I am using in my code:</p>
<pre><code>def AF(self, cur, theta):
AF_out = 1
self.cur = np.array(cur)
for m in list(range(int(RING_NUM))):
for i in list(range(RING_ELEMENT_NUM[m], int(np.sum(np.fromiter((RING_ELEMENT_NUM[0:m]), float))))):
AF_out = 1 + np.sum(np.fromiter((np.sum(np.fromiter((self.cur[i] * exp(1j * K * (m * WAVELENGTH / 2) *
sin(theta) * cos(
PHI - 2 * pi * (i - 1) / RING_ELEMENT_NUM[m]))), float))), int))
return AF_out
</code></pre>
<p>When I run my code, the following error appears:</p>
<pre><code>File "D:\download\metaheuristic algorithm\exercise_files\14. Genetic Algorithms Implementation - Simple Example __ 5.1 GeneticAlgorithmElitism.py", line 122, in AF
AF_out = 1 + np.sum(np.fromiter((np.sum(np.fromiter((self.cur[i] * exp(1j * K * (m * WAVELENGTH / 2) *
TypeError: 'numpy.complex128' object is not iterable
</code></pre>
<p>I've found a lot of similar topic for this error, but I could not solve this error. What is wrong with my code?</p>
|
<python><numpy><typeerror>
|
2023-05-15 06:56:47
| 1
| 352
|
mohammad rezza
|
76,251,529
| 8,510,149
|
Pandas transform with conditions
|
<p>The code below make a groupby and then replaces all values below 3 with na and then use the last value instead.</p>
<p>However, for ID 11, the first observation in group B get the value 9 using this method, the last value of group A. This is not desirable. This happens because the mask returns NaN when True and the ffill() doesn't take the groupby into consideration.</p>
<p>Is there a smart way to solve this, to replace values below 3 with the last value, and, when the first value of a group is below 3, use another method, perhaps x.mean() to replace.</p>
<pre><code>import pandas as pd
import numpy as np
data = pd.DataFrame({'ID':list(range(1,21)),
'group':['A']*10 + ['B']*10,
'value':[4,6,2,9,7,5,1,9,8, 9, np.nan, 4,5,6,1,2,3,4,2,6]
})
data.groupby('group').transform(lambda x: x.mask(x < 3)).ffill()
</code></pre>
|
<python><pandas>
|
2023-05-15 06:53:10
| 1
| 1,255
|
Henri
|
76,251,415
| 14,152,751
|
Using assume_role to connect to dynamodb using boto3 in databricks python notebook is giving NoCredentialsError: Unable to locate credentials
|
<p>I am trying to connect to dynamodb using boto3 with assume_role on databricks.</p>
<p>Here is the example code where I am getting error</p>
<pre class="lang-py prettyprint-override"><code>%pip install boto3
import boto3
sts_client = boto3.client("sts")
# Getting error here
credentials = sts_client.assume_role(
RoleArn="arn:aws:iam::<account id>:role/<role name>",
RoleSessionName="test"
)
session = boto3.Session(aws_access_key_id=credentials["Credentials"]['AccessKeyId'], aws_secret_access_key=credentials["Credentials"]['SecretAccessKey'], aws_session_token=credentials["Credentials"]['SessionToken'])
dynamodb = session.client("dynamodb")
dict = dynamodb.scan(TableName='table_name', Limit=1)
</code></pre>
<p>I am getting error:</p>
<pre><code>NoCredentialsError: Unable to locate credentials
</code></pre>
<p>How to resolve?</p>
|
<python><amazon-web-services><amazon-dynamodb><boto3><databricks>
|
2023-05-15 06:34:09
| 0
| 647
|
Vinit Khandelwal
|
76,251,308
| 2,000,548
|
How to use Python to create a custom read data source for Apache Spark 3?
|
<p>I have a lot of TDMS files produced by National Instruments's LabVIEW which saved in S3. I am hoping to create a custom read data source for Apache Spark 3, then later I can read by something like this</p>
<pre class="lang-scala prettyprint-override"><code>val df = spark.readStream
.format("tdms")
.option("limit", "10000")
</code></pre>
<p>Right now there is no Java or Scala library to read TDMS, but there is a good Python library <a href="https://github.com/adamreeve/npTDMS" rel="nofollow noreferrer">npTDMS</a> which can read TDMS files. I hope to leverage of it.</p>
<p>I know I can build a custom read data source for Spark in Java or Scala.</p>
<p>I am wondering is it possible to use Python to create a custom read data source? Thanks!</p>
|
<python><apache-spark><apache-spark-sql>
|
2023-05-15 06:14:14
| 2
| 50,638
|
Hongbo Miao
|
76,251,296
| 11,082,866
|
Explode a column vertically top create new columns
|
<p>I have a Dataframe like this :</p>
<pre><code>name zones
aa []
bb [{"rack":11,"bin":22},{"rack":33,"bin":44}]
</code></pre>
<p>Now I want to transform into something like this:</p>
<pre><code>name rack bin
aa - -
bb 11 22
bb 33 44
</code></pre>
<p>I tried this:</p>
<p>cols = ['zones',]</p>
<p>df1 = (df.drop(cols, axis=1)
.join(pd.concat([pd.json_normalize(df[x].explode()).add_prefix(f'{x}.')
for x in cols], axis=1)))</p>
<p>But it only gives the values of first dictionary:</p>
<pre><code>name zones.rack zones.bin
0 aa NaN NaN
1 bb 11.0 22.0
</code></pre>
|
<python><pandas>
|
2023-05-15 06:11:53
| 3
| 2,506
|
Rahul Sharma
|
76,251,187
| 5,680,504
|
Mismatch version between pip and python
|
<p>I have the following versions for python and pip as below.</p>
<pre><code>ramirami-pc:lib sclee01$ pip --version
pip 22.3.1 from /opt/homebrew/anaconda3/lib/python3.10/site-packages/pip (python 3.10)
ramirami-pc:lib sclee01$ python --version
Python 3.8.16
ramirami-pc:lib sclee01$
</code></pre>
<p>As you can see, python is 3.8.16 but the pip is 3.10 in the anaconda3.</p>
<p>It can be a problems in managing python packages for development?</p>
<p>And if so, how to resolve this issue?</p>
<p>Thanks.</p>
|
<python>
|
2023-05-15 05:50:06
| 0
| 1,329
|
sclee1
|
76,251,041
| 2,825,403
|
Multiple dispatch - "function requires at least 1 positional argument"
|
<p>In a multiple dispatch situation I don't understand why I constantly run into an error saying: <code>TypeError: some_func requires at least 1 positional argument</code>.</p>
<p>For example, we have a following function:</p>
<pre><code>from functools import singledispatch
@singledispatch
def some_func(a, b):
...
@some_func.register
def _(a: str, b: int):
print(f'{a=}, {b=}')
@some_func.register
def _(a: str, b: bool):
print(f'{b=}, {a=}')
</code></pre>
<p>If I try to run:</p>
<pre><code>some_func(a='a', b=10)
</code></pre>
<p>I get the error message:</p>
<pre><code> 872 def wrapper(*args, **kw):
873 if not args:
--> 874 raise TypeError(f'{funcname} requires at least '
875 '1 positional argument')
877 return dispatch(args[0].__class__)(*args, **kw)
TypeError: some_func requires at least 1 positional argument
</code></pre>
<p>But it works fine if I make the first argument positional:</p>
<pre><code>some_func('a', b=10) # Out: a='a', b=10
</code></pre>
<p>Ok, then I'll try making them keyword-only...</p>
<pre><code>@singledispatch
def some_func(*, a, b):
...
@some_func.register
def _(*, a: str, b: int):
print(f'{a=}, {b=}')
@some_func.register
def _(*, a: str, b: bool):
print(f'{b=}, {a=}')
</code></pre>
<p>Now if I try to run with keyword arguments I get the same result, but with this change if I try to make the first argument as positional I get a more expected error:</p>
<pre><code>----> 1 some_func('a', b=10)
File C:\Python39\lib\functools.py:877, in singledispatch..wrapper(*args, **kw)
873 if not args:
874 raise TypeError(f'{funcname} requires at least '
875 '1 positional argument')
--> 877 return dispatch(args[0].__class__)(*args, **kw)
TypeError: _() takes 0 positional arguments but 1 positional argument (and 1 keyword-only argument) were given
</code></pre>
<p>So now the function simultaneously: <em>requires a positional-only argument</em> and <em>takes no positional arguments</em>.</p>
<p>I don't understand why this is happening? What is the reason for needing a positional-only arguments?</p>
|
<python><overloading><multiple-dispatch>
|
2023-05-15 05:17:14
| 1
| 4,474
|
NotAName
|
76,250,910
| 1,870,832
|
Scatter Plot Not Updating With Widget Selection in Python Panel Holoviz
|
<p>I want a Python Panel app with dynamic plots, and different plots depending on which menu/button is selected from a sidepanel, so I started from this great starting point: <a href="https://discourse.holoviz.org/t/multi-page-app-documentation/3108/2" rel="nofollow noreferrer">https://discourse.holoviz.org/t/multi-page-app-documentation/3108/2</a></p>
<p>Each page had a sine & cosine plot which updated based on widget values, using <code>@pn.depends</code>.</p>
<p>Then I updated the code so that the sine plot would be a scatter plot, and the widget would be a selection drop-down menu instead of a slider. But now that scatter plot is not updating when I update the selection drop-down widget. What am I doing wrong? Clearly I’m misunderstanding something about what <code>@pn.depends()</code> is doing or not doing. Any help would be super appreciated!</p>
<p>Full code (<code>app.py</code>) below:</p>
<pre><code>import pandas as pd
import panel as pn
import holoviews as hv
import hvplot.pandas
import numpy as np
import time
from datetime import datetime
pn.extension()
template = pn.template.FastListTemplate(title='My Dashboard')
# load detailed data
durations = np.random.randint(0, 10, size=10)
activity_codes = ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3', 'C3']
activity_categories = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']
df = pd.DataFrame({'Duration': durations,
'ActivityCode': activity_codes,
'ActivityCategory': activity_categories})
# Page 1 Widget Controls
ac_categories = ['A', 'B', 'C']
ac_cat_radio_button = pn.widgets.Select(name='Activity Category', options=ac_categories)
# Page 1 Plotting Code
@pn.depends(ac_cat=ac_cat_radio_button)
def scatter_detail_by_ac(df, ac_cat):
print(f"ac_cat is {ac_cat}")
print(f"ac_cat.value is {ac_cat.value}")
df_subset = df.loc[df.ActivityCategory==ac_cat.value]
print(f"number of records in df_subset to scatter plot: {len(df_subset):,}")
return df_subset.hvplot.scatter(x='ActivityCode', y='Duration')
freq2 = pn.widgets.FloatSlider(name="Frequency", start=0, end=10, value=2)
phase2 = pn.widgets.FloatSlider(name="Phase", start=0, end=np.pi)
@pn.depends(freq=freq2, phase=phase2)
def cosine(freq, phase):
xs = np.linspace(0,np.pi)
return hv.Curve((xs, np.cos(xs*freq+phase))).opts(
responsive=True, min_height=400)
page = pn.Column(sizing_mode='stretch_width')
content1 = [
pn.Row(ac_cat_radio_button), #grouping_vars_radio_button),
scatter_detail_by_ac(df, ac_cat_radio_button),
]
content2 = [
pn.Row(freq2, phase2),
hv.DynamicMap(cosine),
]
link1 = pn.widgets.Button(name='Scatter')
link2 = pn.widgets.Button(name='Cosine')
template.sidebar.append(link1)
template.sidebar.append(link2)
template.main.append(page)
def load_content1(event):
template.main[0].objects = content1
def load_content2(event):
template.main[0].objects = content2
link1.on_click(load_content1)
link2.on_click(load_content2)
template.show()
</code></pre>
<p>I serve this Panel app locally by running (from shell):</p>
<pre><code>panel serve app.py --autoreload
</code></pre>
<p>Also, here's the library versions I'm using, from my <code>requirements.in</code> (which I <code>pip-compile</code> into a requirements.txt/lockfile):</p>
<pre><code>panel==v1.0.0rc6
pandas==1.5.3
holoviews==1.16.0a2
hvplot
pandas-gbq>=0.19.1
</code></pre>
|
<python><pandas><hvplot><holoviz><holoviz-panel>
|
2023-05-15 04:37:24
| 1
| 9,136
|
Max Power
|
76,250,741
| 5,132,028
|
Read io.BytesIO with Pandas - Python
|
<p>I am totally new in Python and I am following a google drive tutorial to be able to read a file from the cloud:</p>
<pre><code>def download_file(real_file_id):
try:
service = authorize()
file_id = real_file_id
# pylint: disable=maybe-no-member
request = service.files().get_media(fileId=file_id)
file = io.BytesIO()
downloader = MediaIoBaseDownload(file, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print(F'Download {int(status.progress() * 100)}.')
except HttpError as error:
print(F'An error occurred: {error}')
file = None
return file.seek(0)
</code></pre>
<p>Then I am trying to read this file with pandas read_csv method:</p>
<pre><code>def read_file(item):
with open(item, 'rb') as file:
csvreader = pd.read_csv(file.read())
print(csvreader)
if __name__ == '__main__':
file = download_file("file_id")
read_file(file)
</code></pre>
<p>I am sure the download method is working because is tested but when I try to read with pandas it just hang and nothing happens... I need to cancel the script manually and I got this errors:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\tluce\PycharmProjects\pythonProject\main.py", line 23, in <module>
read_file(download_file(files[0]['id']))
File "C:\Users\tluce\PycharmProjects\pythonProject\main.py", line 15, in read_file
csvreader = pd.read_csv(file)
File "C:\Users\tluce\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\io\parsers\readers.py", line 912, in read_csv
return _read(filepath_or_buffer, kwds)
File "C:\Users\tluce\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\io\parsers\readers.py", line 577, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "C:\Users\tluce\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\io\parsers\readers.py", line 1407, in __init__
self._engine = self._make_engine(f, self.engine)
File "C:\Users\tluce\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\io\parsers\readers.py", line 1679, in _make_engine
return mapping[engine](f, **self.options)
File "C:\Users\tluce\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 93, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas\_libs\parsers.pyx", line 548, in pandas._libs.parsers.TextReader.__cinit__
File "pandas\_libs\parsers.pyx", line 637, in pandas._libs.parsers.TextReader._get_header
File "pandas\_libs\parsers.pyx", line 848, in pandas._libs.parsers.TextReader._tokenize_rows
File "pandas\_libs\parsers.pyx", line 859, in pandas._libs.parsers.TextReader._check_tokenize_status
File "pandas\_libs\parsers.pyx", line 2025, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Calling read(nbytes) on source failed. Try engine='python'.
</code></pre>
|
<python><pandas><bytesio>
|
2023-05-15 03:34:56
| 1
| 1,546
|
Tomas Lucena
|
76,250,624
| 11,141,816
|
How to download Bulk PDF of Arxiv from Amazon S3
|
<p>This post was a bit long but I wanted to show you the attempts I had tried. I'm new to this area so there might be some seemingly trivial mistakes. I've been trying to figure out how to download the bulk PDFs of the ArXiv and it's been over 12 hours and it was very confusing.</p>
<p>The Bulk PDF Access stated from:
<a href="https://info.arxiv.org/help/bulk_data/index.html" rel="nofollow noreferrer">https://info.arxiv.org/help/bulk_data/index.html</a></p>
<p>It listed three methods:</p>
<ol>
<li>AWS for PDF and or (La)TeX source files</li>
<li>Kaggle for PDF</li>
<li>Crawling export service</li>
</ol>
<p><strong>Issues with method 2</strong>: The Kaggle itslef does not actually host the PDF files but the Metadata, which was useful. On <a href="https://www.kaggle.com/datasets/Cornell-University/arxiv" rel="nofollow noreferrer">https://www.kaggle.com/datasets/Cornell-University/arxiv</a> the <strong>Bulk access</strong>, it listed the code to access the google cloud.</p>
<p>I tried search for <code>arxiv-dataset</code> in the Google Cloud's website, copied <code>gs://arxiv-dataset/arxiv/</code> and <code>gsutil cp gs://arxiv-dataset/arxiv/</code> cloud shell, didn't work. I tried <code>from google.cloud import storage</code> but <code>conda install -c conda-forge google-cloud-sdk</code> and <code>conda install -c conda-forge google-cloud</code> does not work, and <code>pip install google-cloud</code> did nothing, and the library could not used. I was able to install <code>conda install -c conda-forge gsutil</code>, however, as suggested on <a href="https://stackoverflow.com/questions/49866283/how-to-run-google-gsutil-using-python">How to run Google gsutil using Python</a> , it didn't work.</p>
<p><strong>Issue with method 3</strong>: I tried to download the file directly using the website addresses as suggested on Kaggle, that got me some 500 error message, and then <a href="https://stackoverflow.com/questions/20568216/python-handling-socket-error-errno-104-connection-reset-by-peer">Python handling socket.error: [Errno 104] Connection reset by peer</a>, even though I tried to limit the burst to a maximum of 4 requests per second as indicated on the website.</p>
<p>Eventually, I read <a href="https://arxiv.org/robots.txt" rel="nofollow noreferrer">https://arxiv.org/robots.txt</a> , that 1 article could be downloaded every 15 seconds continuously. That basically made the bulk download of the entire arxiv pdf bulk from an option to a necessity.</p>
<p><strong>Issue with method 1</strong>: I then tried to download the files from the Amazon S3. I thought it was supposed to be easy like the cloud, but it was not. The "Requester Pays buckets" on the <a href="https://info.arxiv.org/help/bulk_data_s3.html" rel="nofollow noreferrer">https://info.arxiv.org/help/bulk_data_s3.html</a> finally made sense. After register for the amazon cloud,</p>
<p>a. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/RequesterPaysBuckets.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AmazonS3/latest/userguide/RequesterPaysBuckets.html</a> from googling did not explain anything of how to use it, neither does <a href="https://s3.console.aws.amazon.com/s3/get-started?region=us-east-1&region=us-east-1" rel="nofollow noreferrer">https://s3.console.aws.amazon.com/s3/get-started?region=us-east-1&region=us-east-1</a> . However, on the <code>Common tasks</code>, I found the <code>Download an object</code> tab. This lead to <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/accessing-an-object.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AmazonS3/latest/userguide/accessing-an-object.html</a> titled <code>Step 3: Download an object</code>, and directed to <code>Amazon S3 console at https://console.aws.amazon.com/s3/</code>, but it just directed back to the <a href="https://console.aws.amazon.com/s3/get-started?region=us-east-2" rel="nofollow noreferrer">https://console.aws.amazon.com/s3/get-started?region=us-east-2</a>.</p>
<p>b. After clicking around for a while, I found the cloud shell. I typed <code>arxiv</code> and <code>arxiv-src</code> on both the <code>Search</code> box on the upper left corner and the cloud shell, and some commands from the arxiv website didn't work.</p>
<p>c. One of the link leaded to <a href="https://aws.amazon.com/s3/" rel="nofollow noreferrer">https://aws.amazon.com/s3/</a>, which didn't do anything but lead back to <a href="https://s3.console.aws.amazon.com/s3/buckets?region=us-east-2" rel="nofollow noreferrer">https://s3.console.aws.amazon.com/s3/buckets?region=us-east-2</a>. However, this time, on the upper left corner, I found the Amazon S3 side window, which had <code>a tab called "Buckets"</code>. I clicked Buckets, and it had a <code>Find Buckets by name</code>, so I typed <code>arxiv</code>, <code>arxiv-src</code>, <code>arxiv_src</code>, <code>arXiv</code>, <code>arXiv-src</code>, <code>arXiv_src</code>, etc. It showed up nothing.</p>
<p>d. Then I found <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/download-objects.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AmazonS3/latest/userguide/download-objects.html</a>. None of the SDKs worked with python. I don't have the access to <code>AWS CLI</code>, and have already tried <code>the S3 console</code>. The number of files needed to be downloaded were large, and not fixed for each given period of time, so it's important to write a script to gather the list of files and then download them in together.</p>
<p>e. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/ObjectsinRequesterPaysBuckets.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AmazonS3/latest/userguide/ObjectsinRequesterPaysBuckets.html</a> explained the <code>Requester Pays buckets</code>, but didn't say much of how to use it. It did state that a <code>x-amz-request-payer</code> has to be specified somewhere in some methods. However, in <a href="https://stackoverflow.com/questions/74400115/how-can-i-download-an-s3-object-in-a-requester-pays-bucket-using-the-aws-sdk-for">How can I download an S3 object in a Requester Pays bucket using the AWS SDK for .NET?</a>, the <code>x-amz-request-payer</code> was no where to be found.</p>
<p>f. Obviously, I wasn't the only one struggle with it.
<a href="https://stackoverflow.com/questions/56589748/how-to-bulk-download-from-arxiv-api-only-for-a-specific-field">How to bulk download from arXiv api only for a specific field?</a> was unanswered for almost 4 years, nether was this one <a href="https://stackoverflow.com/questions/75672158/need-help-in-downloading-pdfs-from-arxiv-dataset-which-is-in-kaggle">Need help in downloading PDFs from arxiv dataset which is in kaggle</a>.</p>
<p>g. I also learned that there's something called <code>boto3</code>, which can be used with python <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html" rel="nofollow noreferrer">https://boto3.amazonaws.com/v1/documentation/api/latest/index.html</a>. This seemed to be possible, but on <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-examples.html" rel="nofollow noreferrer">https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-examples.html</a>, I didn't see <code>x-amz-request-payer</code> or anyway to login/authenticate, so the example did not work for what I needed.</p>
<p>h. On <a href="https://github.com/mattbierbaum/arxiv-public-datasets/tree/a91018a0c0647ceea6fb6b2426519cebd5f0effc" rel="nofollow noreferrer">https://github.com/mattbierbaum/arxiv-public-datasets/tree/a91018a0c0647ceea6fb6b2426519cebd5f0effc</a> it listed a method <a href="https://github.com/mattbierbaum/arxiv-public-datasets/blob/master/bin/pdfdownload.py" rel="nofollow noreferrer">https://github.com/mattbierbaum/arxiv-public-datasets/blob/master/bin/pdfdownload.py</a> to download the bulk files from the <a href="https://github.com/mattbierbaum/arxiv-public-datasets/blob/a91018a0c0647ceea6fb6b2426519cebd5f0effc/arxiv_public_data/s3_bulk_download.py" rel="nofollow noreferrer">https://github.com/mattbierbaum/arxiv-public-datasets/blob/a91018a0c0647ceea6fb6b2426519cebd5f0effc/arxiv_public_data/s3_bulk_download.py</a>
However, the previous issue persisted, <code>HEADERS = {'x-amz-request-payer': 'requester'}</code> option. But where can I get that <code>requester</code> value?</p>
<p><strong>Question</strong>:</p>
<ol>
<li><p>How to find the list of files in the arxiv <code>Requester Pays buckets</code>? as in</p>
<p>src/arXiv_src_manifest.xml (s3://arxiv/src/arXiv_src_manifest.xml)</p>
</li>
<li><p>How to download the files in the arxiv <code>Requester Pays buckets</code>? as in</p>
<p>src/arXiv_src_1001_001.tar (s3://arxiv/src/arXiv_src_1001_001.tar in s3cmd URI style)
src/arXiv_src_1001_002.tar (s3://arxiv/src/arXiv_src_1001_002.tar)
src/arXiv_src_1001_003.tar (s3://arxiv/src/arXiv_src_1001_003.tar)</p>
</li>
</ol>
<p>It should be very simple code and functions in python, possibly with boto3. Also, how to get x-amz-request-payer.</p>
|
<python><amazon-web-services><amazon-s3><download><google-cloud-storage>
|
2023-05-15 02:57:22
| 1
| 593
|
ShoutOutAndCalculate
|
76,250,544
| 6,591,667
|
Python: Exit script when it sits Idle after a period of time
|
<p>I'm required to click a button when it appears onscreen over and over again to copy some files.</p>
<p>So I created a Python program that automatically clicks this button whenever it appears on screen until it's finished.
I screenshotted a PNG image of the button <code>the enum_buttom_image.png</code> file.</p>
<p>Here's my code:</p>
<pre><code>import pyautogui
import time
while True:
res = pyautogui.locateCenterOnScreen("C:\\Users\\ul340\\Desktop\\enum_button_image.PNG", confidence=0.8)
pyautogui.moveTo(res)
pyautogui.click()
time.sleep(2)
</code></pre>
<p>Right now I'm terminating the program manually once it finished (CTRL+C) on the command prompt window. I wanted to know how could I modify this program so it automatically exit the script once it doesn't find the button image for more than 30 minutes?</p>
|
<python><pyautogui>
|
2023-05-15 02:31:40
| 1
| 8,891
|
tadm123
|
76,250,518
| 9,443,671
|
How do I make the following plot with Seaborn? Grouping a dataframe by columns
|
<pre><code> model_name 1 2 3 4 5
0 ground_truth 41.333333 12.000000 12.666667 11.333333 22.666667
1 TL_model 73.333333 4.666667 2.666667 4.666667 14.666667
2 other-model 22.000000 21.333333 9.333333 31.333333 16.000000
</code></pre>
<p>Assume I have the above dataframe. I'm trying to achieve the following:</p>
<ol>
<li>I would like the x-axis to be [1,2,3,4,5]</li>
<li>I would like the y-axis to reflect the frequency of each entry in the dataframe, for example entry [ground_truth][1] -> 41.333 and so on</li>
<li>I would like to have 3 bars next to each other for each entry in the x-axis (15 bars in total). That is for x-value 1, I would like the first bar to reflect <code>ground_truth frequency-> 41.333</code>, 2nd value to reflect <code>TL_model's frequency -> 73.3333</code>; and the last value to reflect <code>other-model's frequency -> 22.0000</code>. So that would be 3 bars for value 1, 3 bars for 2,.... all the way to value 5.</li>
</ol>
<p>How do I do this using Seaborn? I'm struggling quite a lot and can't figure out how to set the "hue" parameter without setting the x and y axis properly. But I'm not sure how to set the y-axis in this case.</p>
<p>Any help would be greatly appreciated.</p>
|
<python><pandas><seaborn><visualization>
|
2023-05-15 02:24:35
| 1
| 687
|
skidjoe
|
76,250,388
| 1,324,833
|
Buttons not appearing on PYQT QVBoxLayout
|
<p>I'm trying to create a simple app with 5 functions each accessed from a button on the main page.</p>
<p>The App class looks like this</p>
<pre><code>import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self._main = QtWidgets.QWidget()
self.initUI_M()
def initUI_M(self):
self.setWindowTitle("QC Tool")
self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
layout =QtWidgets.QVBoxLayout( )
button1 = QtWidgets.QPushButton("GPS")
button1.clicked.connect(partial(self.plotFlight_map))
layout.addWidget(button1)
button2 = QtWidgets.QPushButton("XY")
button2.clicked.connect(partial(self.plot_xy))
layout.addWidget(button2)
button3 = QtWidgets.QPushButton("Accel")
button3.clicked.connect(partial(self.plot_accel))
layout.addWidget(button3)
button4 = QtWidgets.QPushButton("Gyro")
button4.clicked.connect(partial(self.plot_gyro))
layout.addWidget(button4)
button5 = QtWidgets.QPushButton("Altimeter")
button5.clicked.connect(partial(self.plot_Altimeter))
layout.addWidget(button5)
self._main.setLayout(layout)
self.center()
self.show()
</code></pre>
<p>This is what I get on running...
<a href="https://i.sstatic.net/cNvJ2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cNvJ2.png" alt="blank dialog" /></a></p>
<p>I've tried setting self._main, or just self as the parent on construction of the buttons and the QVBoxLayout, and I've tried not assigning methods to the buttons. All of the methods connected to the clicked.connect exist and were previously connected to a menu that worked.</p>
<p>I've even tried not creating the widget object and just adding the layout to self.</p>
<p>I get the exact same output no matter what I try.</p>
<p>I know it's a syntax issue, but I can't find it...</p>
|
<python><qt><pyqt5>
|
2023-05-15 01:35:41
| 1
| 1,237
|
marcp
|
76,250,336
| 6,737,797
|
Python: Using __self__ instead of self as first argument of "instance method"
|
<p>I recently came across this piece of code:</p>
<pre><code>class InlineParameterResolver:
def resolve(__self__, value: str) -> Any:
return value
</code></pre>
<p>Now, I am aware that this code is strange as the class itself has no instance methods, nor an init method to enable it to create an instance and operate on its internal attributes, but does having the __self__ as the first argument have any special function/behaviour?</p>
<p>I have tried to google for an answer, but couldn't find anything, I just want to know if this is an opportunity to learn something, or if I'm just reading Python from someone who didn't have a lot of experience with the language.</p>
<p>Cheers.</p>
|
<python>
|
2023-05-15 01:17:26
| 2
| 1,055
|
John Von Neumann
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.