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
β |
|---|---|---|---|---|---|---|---|---|
78,438,315
| 11,269,351
|
No module named βtorch._custom_opsβ in Jupyter Notebooks
|
<p>I'm not sure if this is the right place to ask, but I just installed cuda tools to run some GPU-based machine learning stuff on my computer, and I'm running into an issue importing torch.</p>
<p>I'm on Ubuntu 22.04
I've tried installing torch within a conda environment and locally. Unfortunately, when I try to import torch into a jupyter notebook, I get the error (Doing literally nothing else in the notebook but importing torch):</p>
<pre><code>ModuleNotFoundError: No module named 'torch._custom_ops'; 'torch' is not a package
</code></pre>
<p>When I run <code>nvcc -V</code> my output is:</p>
<pre><code>nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2024 NVIDIA Corporation
Built on Thu_Mar_28_02:18:24_PDT_2024
Cuda compilation tools, release 12.4, V12.4.131
Build cuda_12.4.r12.4/compiler.34097967_0
</code></pre>
<p>When I run <code>nvidia-smi</code> my output is:</p>
<pre><code>NVIDIA-SMI 550.67 Driver Version: 550.67 CUDA Version: 12.4
</code></pre>
<p>I have an NVIDIA GeForce RTX 3050 Ti.
Based on Table 3 of <a href="https://docs.nvidia.com/deploy/cuda-compatibility/index.html" rel="nofollow noreferrer">https://docs.nvidia.com/deploy/cuda-compatibility/index.html</a>, CUDA 12.4 seems like the right version for my NVIDIA driver.</p>
<p>I'm able to run <code>python3 -c 'import torch'</code> with no output, which I assume is good news.
That being said, when I try to import torch into a jupyter notebook, I get the error:</p>
<pre><code>ModuleNotFoundError: No module named 'torch._custom_ops'; 'torch' is not a package
</code></pre>
<p>I was able to find torch._custom_ops myself, so I know it exists, but I'm not sure why it isn't working in Jupyter Notebook?</p>
<p>I found this: <a href="https://stackoverflow.com/questions/77498488/loading-a-pretrained-model-from-torch-hub-in-sagemaker">Loading a pretrained model from torch.hub in Sagemaker</a> but that didn't seem relevant given I'm not using Sagemaker and simply trying to get my local machine ready to tackle GPU training tasks.</p>
<p>I see other posts such as <a href="https://stackoverflow.com/questions/54843067/no-module-named-torch">No module named "Torch"</a>
<code>pip3 install https://download.pytorch.org/whl/cpu/torch-1.0.1-cp36-cp36m-win_amd64.whl</code>, which I haven't done, but looks like it's for windows. Is that something I need?</p>
<p>I would appreciate any help, insight, or simply comments telling me a better place to be asking this question.
Thank you</p>
|
<python><jupyter-notebook><pytorch>
|
2024-05-06 17:48:37
| 2
| 411
|
EnigmaticBacon
|
78,438,233
| 18,764,592
|
Flask: how to return validation before full route code execution
|
<p>Sorry for newbie question - I am new in Python.</p>
<p>I have to return validation result of Flask route parameter before main code execution:</p>
<pre class="lang-py prettyprint-override"><code>@app.route('/', methods=['POST'])
def index():
validation = code_to_check_parameters()
if validation:
return make_response('Valid', 200)
else:
return make_response('Invalid', some_error_code)
# this line is unreachable because of returns, but required
video = request.files['video']
result = heavy_video_processing(video) # takes 4-5 minutes, so I can't wait for this
r = requests.post(URL, results)
return r.status_code
</code></pre>
<p>What expected:</p>
<ul>
<li>Check route parameters and return validation results</li>
<li>Continue execution of Python code and push video processing results after 4-5 minutes of heavy execution by requests.post.</li>
</ul>
<p>How to do it?</p>
|
<python><python-3.x><flask><python-asyncio>
|
2024-05-06 17:29:24
| 1
| 385
|
vbulash
|
78,438,128
| 903,011
|
Is it possible to dynamically set the template string?
|
<p>I would like to configure outside of my program a template string, and then apply it at runtime:</p>
<pre class="lang-py prettyprint-override"><code>my_string = "hello {country}" # β this string would be read in from an external configuration file
country = "France"
print(f%%my_string%%) # β the place where the magic happens
</code></pre>
<p>Is this possible or is there a proper way to do this?</p>
|
<python><string><templates>
|
2024-05-06 17:07:49
| 2
| 30,596
|
WoJ
|
78,438,018
| 7,695,845
|
Using parallelization in numba is better for one algorithm, but not for another similar algorithm?
|
<p>I am making a simulation of <code>N</code> particles with the same mass and random velocities. I want to compute the total energy and total momentum of the system. I considered 4 approaches and wanted to benchmark them to see which one performs best:</p>
<ol>
<li>Using regular numpy routines and computations.</li>
<li>Using <code>numba.jit</code> and writing the for loop myself.</li>
<li>Using <code>numba.jit</code> with <code>parallel=True</code> to utilize multiple cores.</li>
<li>Using a hybrid version of the last two approaches based on the number of particles. If we don't have enough particles, the overhead of parallelization isn't worth it.</li>
</ol>
<p>Here's the code for the energy calculation:</p>
<pre class="lang-py prettyprint-override"><code>from functools import wraps
import numpy as np
import numba as nb
import numpy.typing as npt
import perfplot
jit_opts = dict(
nopython=True, nogil=True, cache=False, error_model="numpy", fastmath=True
)
rng = np.random.default_rng()
def hybrid_parallel_jit(get_threshold, *hpj_args, default_threshold=None, **hpj_kwargs):
def _hybrid_parallel_jit(func):
if "parallel" in hpj_kwargs:
raise ValueError("Cannot specify 'parallel' for hybrid jitted function")
hpj_kwargs["parallel"] = True
func_parallel = nb.jit(*hpj_args, **hpj_kwargs)(func)
hpj_kwargs["parallel"] = False
func_non_parallel = nb.jit(*hpj_args, **hpj_kwargs)(func)
@wraps(func)
def hybrid_func(*args, threshold=None, **kwargs):
if threshold is None:
threshold = default_threshold
if threshold is None:
raise ValueError(
"`threshold` keyword argument was not provided, and a "
"default threshold was not set either."
)
return (
func_non_parallel(*args, **kwargs)
if get_threshold(*args, **kwargs) < threshold
else func_parallel(*args, **kwargs)
)
return hybrid_func
return _hybrid_parallel_jit
def random_unit_vectors(n: int) -> npt.NDArray[float]:
phi = rng.uniform(0, 2 * np.pi, n)
cos_theta = rng.uniform(-1, 1, n)
sin_theta = np.sqrt(1 - cos_theta**2)
return np.column_stack(
(sin_theta * np.cos(phi), sin_theta * np.sin(phi), cos_theta)
)
@nb.jit([nb.float64(nb.float64[:, :])], **jit_opts)
def total_energy(velocities: npt.NDArray[float]) -> float:
energy = 0
for i in range(velocities.shape[0]):
energy += velocities[i, 0] ** 2 + velocities[i, 1] ** 2 + velocities[i, 2] ** 2
return energy / 2
@nb.jit([nb.float64(nb.float64[:, :])], parallel=True, **jit_opts)
def total_energy_parallel(velocities: npt.NDArray[float]) -> float:
energy = 0
for i in nb.prange(velocities.shape[0]):
energy += velocities[i, 0] ** 2 + velocities[i, 1] ** 2 + velocities[i, 2] ** 2
return energy / 2
def total_energy_numpy(velocities: npt.NDArray[float]) -> float:
return np.einsum("ij, ij->", velocities, velocities) / 2
@hybrid_parallel_jit(
lambda v: v.shape[0],
[nb.float64(nb.float64[:, :])],
**jit_opts,
)
def total_energy_improved(velocities: npt.NDArray[float]) -> float:
energy = 0
for i in nb.prange(velocities.shape[0]):
energy += velocities[i, 0] ** 2 + velocities[i, 1] ** 2 + velocities[i, 2] ** 2
return energy / 2
perfplot.show(
setup=lambda n: random_unit_vectors(n),
kernels=[
lambda v: total_energy_numpy(v),
lambda v: total_energy(v),
lambda v: total_energy_parallel(v),
lambda v: total_energy_improved(v, threshold=10_000),
],
labels=["numpy", "numba", "numba parallel", "numba improved"],
n_range=[10**k for k in range(9)],
xlabel="len(a)",
)
</code></pre>
<p>The <code>@hybrid_parallel_jit</code> decorator basically calls the parallel version if <code>N</code> is bigger than a specified threshold and calls the non-parallel version otherwise. The results I got from running this:</p>
<p><a href="https://i.sstatic.net/YFRkLHtx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YFRkLHtx.png" alt="" /></a></p>
<p>These results match my expectations: The parallel versions are better for large <code>N</code> (larger than 10,000 on my machine) and the non-parallel versions are better for smaller <code>N</code>. It looks like the hybrid version (option 4) is the overall best option.</p>
<p>I modified the code to make a similar tests for the momentum calculations:</p>
<pre class="lang-py prettyprint-override"><code>from functools import wraps
import numpy as np
import numba as nb
import numpy.typing as npt
import perfplot
jit_opts = dict(
nopython=True, nogil=True, cache=False, error_model="numpy", fastmath=True
)
rng = np.random.default_rng()
def hybrid_parallel_jit(get_threshold, *hpj_args, default_threshold=None, **hpj_kwargs):
def _hybrid_parallel_jit(func):
if "parallel" in hpj_kwargs:
raise ValueError("Cannot specify 'parallel' for hybrid jitted function")
hpj_kwargs["parallel"] = True
func_parallel = nb.jit(*hpj_args, **hpj_kwargs)(func)
hpj_kwargs["parallel"] = False
func_non_parallel = nb.jit(*hpj_args, **hpj_kwargs)(func)
@wraps(func)
def hybrid_func(*args, threshold=None, **kwargs):
if threshold is None:
threshold = default_threshold
if threshold is None:
raise ValueError(
"`threshold` keyword argument was not provided, and a "
"default threshold was not set either."
)
return (
func_non_parallel(*args, **kwargs)
if get_threshold(*args, **kwargs) < threshold
else func_parallel(*args, **kwargs)
)
return hybrid_func
return _hybrid_parallel_jit
def random_unit_vectors(n: int) -> npt.NDArray[float]:
phi = rng.uniform(0, 2 * np.pi, n)
cos_theta = rng.uniform(-1, 1, n)
sin_theta = np.sqrt(1 - cos_theta**2)
return np.column_stack(
(sin_theta * np.cos(phi), sin_theta * np.sin(phi), cos_theta)
)
@nb.jit([nb.float64[:](nb.float64[:, :])], **jit_opts)
def total_momentum(velocities: npt.NDArray[float]) -> float:
momentum = np.zeros(3)
for i in range(velocities.shape[0]):
momentum += velocities[i]
return momentum
@nb.jit([nb.float64[:](nb.float64[:, :])], parallel=True, **jit_opts)
def total_momentum_parallel(velocities: npt.NDArray[float]) -> float:
momentum = np.zeros(3)
for i in nb.prange(velocities.shape[0]):
momentum += velocities[i]
return momentum
def total_momentum_numpy(velocities: npt.NDArray[float]) -> float:
return np.sum(velocities, axis=0)
@hybrid_parallel_jit(
lambda v: v.shape[0],
[nb.float64[:](nb.float64[:, :])],
**jit_opts,
)
def total_momentum_improved(velocities: npt.NDArray[float]) -> float:
momentum = np.zeros(3)
for i in nb.prange(velocities.shape[0]):
momentum += velocities[i]
return momentum
perfplot.show(
setup=lambda n: random_unit_vectors(n),
kernels=[
lambda v: total_momentum_numpy(v),
lambda v: total_momentum(v),
lambda v: total_momentum_parallel(v),
lambda v: total_momentum_improved(v, threshold=10_000),
],
labels=["numpy", "numba", "numba parallel", "numba improved"],
n_range=[10**k for k in range(9)],
xlabel="len(a)",
)
</code></pre>
<p>The momentum calculation is very similar to the energy calculation, so I expected to get a similar graph and the same conclusion that option 4 works best. However, when I ran the code I got:</p>
<p><a href="https://i.sstatic.net/YBOCeZx7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YBOCeZx7.png" alt="" /></a></p>
<p>The non-parallel numba version is the fastest both for small and large <code>N</code>. These results are very surprising to me. The momentum calculation is very similar to the energy. In both cases, I sum the velocities in some way that seems straight forward in terms of runtime cost. Can somebody explain why I get such different results for these two very similar calculations? More specifically, why using parallelization doesn't seem to help with the momentum calculation even for large <code>N</code>? Any insights into what's going on here would be appreciated.</p>
|
<python><numpy><benchmarking><numba>
|
2024-05-06 16:44:34
| 1
| 1,420
|
Shai Avr
|
78,437,949
| 10,927,888
|
Py4JJavaError -Running pyspark job locally using PyCharm IDE causing Py4JJavaError error while accessing s3 data
|
<p>I am new to python world of coding . While I try to run existing pyspark job in my location windows maching using PyCharm community editioin IDE <strong>I am getting error "Py4JJavaError"</strong> as show below.</p>
<p><strong>I am using python 3.10 version with pyspark 3.5.1 and spark-3.3.0-bin-hadoop3</strong></p>
<p>My python script which is a pyspark code which reads as S3 data. But when run my job localling in IDE I am facing below error. Not sure what went wrong and how to fix it.</p>
<p>Below is the error trace :</p>
<pre><code> File "D:\Softwares\python\Python310\lib\site-packages\py4j\protocol.py", line 326, in get_return_value
raise Py4JJavaError(
py4j.protocol.Py4JJavaError: An error occurred while calling o33.get.
: java.util.NoSuchElementException: spark.sql.execution.pythonUDF.arrow.enabled
at org.apache.spark.sql.errors.QueryExecutionErrors$.noSuchElementExceptionError(QueryExecutionErrors.scala:1660)
at org.apache.spark.sql.internal.SQLConf.$anonfun$getConfString$3(SQLConf.scala:4546)
at scala.Option.getOrElse(Option.scala:189)
at org.apache.spark.sql.internal.SQLConf.getConfString(SQLConf.scala:4546)
at org.apache.spark.sql.RuntimeConfig.get(RuntimeConfig.scala:72)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:282)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
at java.base/java.lang.Thread.run(Thread.java:1623)
Process finished with exit code 1
</code></pre>
|
<python><amazon-s3><pyspark><pycharm><py4j>
|
2024-05-06 16:30:39
| 0
| 501
|
Shasu
|
78,437,933
| 3,623,537
|
statically override function's argument and keep correct type hints and doc-strings
|
<p>I have a function <code>original</code> with specified arguments, their types and a doc-string.</p>
<p>How can I define a function <code>new</code> that what that it would basically call <code>original</code> but override <code>a</code> argument with some <code>A_DEFAULT</code> value. E.g. <code>new(x) == original(A_DEFAULT, x)</code>.</p>
<p>The most important part is that resulting <code>new</code></p>
<ul>
<li>should have original signature but without <code>a</code> argument</li>
<li>keep the original doc string</li>
<li>both signature and doc string should be visible from IDE</li>
</ul>
<p>The goal is to make those kind of partial functions without copying the original doc-strings and signatures explicitly.</p>
<p>Any ideas how it can be done? (even if you have some hacky idea)</p>
<pre class="lang-py prettyprint-override"><code>import functools
A_DEFAULT = ...
def original(a: int, b: str):
"description"
return a + b
# `new` should have in IDE tooltips and type checks:
# - __doc__ = "description"
# - signature = (b: int)
# new(x) = original(A_DEFAULT, x)
new = ...
</code></pre>
|
<python><python-typing>
|
2024-05-06 16:27:07
| 1
| 469
|
FamousSnake
|
78,437,909
| 12,974,079
|
side_effect not iterating on Mock in Pytho
|
<p>I'm trying to obtain different responses by each call on a Mock by using the <code>side_effect</code> attribute. However, I'm obtaining the first one each time. I would like to ask if I can get any help on it. Thank you in advance</p>
<pre><code>import json
from typing import Dict
from unittest.mock import Mock, patch
import requests
def mock_response_1() -> dict:
return {"data": {"users": [{"id": "AAA"}]}}
def mock_response_2() -> dict:
return {"data": {"users": [{"id": "BBB"}]}}
def mock_json_response(mocked_json: Dict, status_code: int = 200) -> Mock:
response_mock = Mock()
response_mock.configure_mock(**{
"return_value.status_code": status_code,
"return_value.headers": {"Content-Type": "application/json"},
"return_value.json.return_value": mocked_json,
"return_value.text.return_value": json.dumps(mocked_json),
})
return response_mock()
class ApiClient:
def get_response(self) -> dict:
request_r = requests.get(url="https://api.test.com")
request_r = request_r.json()
return request_r.get("data")
class MockClient(ApiClient):
@patch('ApiTest.requests.get')
def get_response(self, mocked_post: Mock):
mocked_post.side_effect = iter([
mock_json_response(mock_response_1()),
mock_json_response(mock_response_2())
])
return super().get_response()
class TestApiClient:
client = MockClient()
def test_get_response(self):
for i in (0, 1):
print(f"Iteration {i}: {self.client.get_response()}")
</code></pre>
<p>Result:</p>
<pre><code>Iteration 0: {'users': [{'id': 'AAA'}]}
Iteration 1: {'users': [{'id': 'AAA'}]}
</code></pre>
|
<python><python-3.x><python-unittest><python-unittest.mock>
|
2024-05-06 16:21:28
| 1
| 363
|
HouKaide
|
78,437,788
| 10,565,052
|
Pyiceberg catalog in GCS: I cannot use pyceberg with google Cloud storage
|
<p>I want to use the library <a href="https://pypi.org/project/pyiceberg/" rel="nofollow noreferrer">pyiceberg</a> with Google cloud storage.</p>
<p>I have a catalog created in Google Cloud storage using Pyspark and I would want to read this tables from there.</p>
<p>I see this <a href="https://py.iceberg.apache.org/configuration/" rel="nofollow noreferrer">documentation</a> to create a catalog object for GSC, but I really don't understand how to connect to it or how to create a config object for google cloud.</p>
<p>I tried:</p>
<pre class="lang-py prettyprint-override"><code>catalog = load_catalog(
uri="gs://catalog",
type="gcsfs"
)
</code></pre>
<p>but I get an error:</p>
<pre><code>---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[4], line 1
----> 1 catalog = load_catalog(
2 name="gcsfs",
File ~/opt/anaconda3/envs/pyceberg/lib/python3.11/site-packages/pyiceberg/catalog/__init__.py:212, in load_catalog(name, **properties)
210 catalog_type = None
211 if provided_catalog_type and isinstance(provided_catalog_type, str):
--> 212 catalog_type = CatalogType[provided_catalog_type.upper()]
213 elif not provided_catalog_type:
214 catalog_type = infer_catalog_type(name, conf)
File ~/opt/anaconda3/envs/pyceberg/lib/python3.11/enum.py:792, in EnumType.__getitem__(cls, name)
788 def __getitem__(cls, name):
789 """
790 Return the member matching `name`.
791 """
--> 792 return cls._member_map_[name]
KeyError: 'GCSFS'
</code></pre>
<p>I installed the package pypiceberg[gcsfs].</p>
<p>I see in the PYICEBERG github <a href="https://github.com/apache/iceberg-python/blob/main/pyiceberg/catalog/__init__.py" rel="nofollow noreferrer">repository</a></p>
<pre><code>AVAILABLE_CATALOGS: dict[CatalogType, Callable[[str, Properties], Catalog]] = {
CatalogType.REST: load_rest,
CatalogType.HIVE: load_hive,
CatalogType.GLUE: load_glue,
CatalogType.DYNAMODB: load_dynamodb,
CatalogType.SQL: load_sql,
}
</code></pre>
|
<python><google-cloud-storage><apache-iceberg>
|
2024-05-06 15:56:34
| 1
| 1,334
|
J.C Guzman
|
78,437,752
| 7,307,824
|
Flatten data from Pandas read_html but extracting the links
|
<p>I have a html table like the following:</p>
<pre><code>html_text = "<table>
<tr>
<th>Home</th>
<th>Score</th>
<th>Away</th>
<th>Report</th>
</tr>
<tr>
<td>Arsenal</td>
<td></td>
<td>Manchester Utd</td>
<td></td>
</tr>
<tr>
<td>Everton</td>
<td>2-0</td>
<td>Liverpool</td>
<td><a href="/asdasdasd/">Match Report</a></td>
</tr>
</table>"
</code></pre>
<p>I'm loading it via requests and using Panda to convert to a dataset:</p>
<pre class="lang-py prettyprint-override"><code>matches = pd.read_html(StringIO(str(html_text)), extract_links="all")[0]
</code></pre>
<p>This now gives me the following:</p>
<pre><code>(Home, None),(Score, None),(Away, None),(Report, None)
(Arsenal, None),(NaN, None),(Manchester Utd, None),(NaN, None)
(Everton, None),(2-0, None),(Liverpool, None),(Match Report, /asdasdasd/)
</code></pre>
<p>What is the simplest way to flatten the dataset to (keeping only link in the "Report" column and the text elsewhere):</p>
<pre><code>Home, Score, Away, Report
Arsenal, NaN, Manchester Utd, NaN
Everton, 2-0, Liverpool, /asdasdasd/
</code></pre>
|
<python><pandas>
|
2024-05-06 15:49:15
| 2
| 568
|
Ewan
|
78,437,677
| 1,028,270
|
How do I make 404s show up as errors or even warnings in locust log output?
|
<p>I'm trying to understand locust log levels. Why am I only seeing this in DEBUG output?</p>
<pre><code>[2024-05-06 15:25:54,465] e9d5c4e3e3eb/DEBUG/selenium.webdriver.remote.remote_connection: Remote response: status=404 | data={"value":{"error":"no such element","message":"no such element: Unable to locate element: {\"method\":\"css selector\",\"selector\":\"[id=\"dash_listener\"]\"}\n (Session info: chrome-headless-shell=124.0.6367.91)","stacktrace":"#0 ........
</code></pre>
<p>It's hard to debug with all the non error or warn level debug output.</p>
<p>Can I tell locust that 404s are warnings or errors so I can get cleaner output when troubleshooting?</p>
|
<python><locust>
|
2024-05-06 15:36:33
| 0
| 32,280
|
red888
|
78,437,508
| 474,597
|
Verifying constructor calling another constructor
|
<p>I want to verify <code>Foo()</code> calls <code>Bar()</code> without actually calling <code>Bar()</code>. And then I want to verify that <code>obj</code> is assigned with whatever <code>Bar()</code> returns.</p>
<p>I tried the following:</p>
<pre class="lang-py prettyprint-override"><code>class Bar:
def __init__(self, a):
print(a)
class Foo:
def __init__(self):
self.obj = Bar(1)
###
import pytest
from unittest.mock import Mock, patch
from mod import Foo, Bar
@pytest.fixture # With stdlib
def mock_bar():
with patch('mod.Bar') as mock:
yield mock
def test_foo(mock_bar):
result = Foo()
mock_bar.assert_called_once_with(1)
assert result.obj == mock_bar
</code></pre>
<p>But it would fail and say that:</p>
<pre><code>E AssertionError: assert <MagicMock na...='5265642864'> == <MagicMock na...='5265421696'>
E Full diff:
E - <MagicMock name='Bar' id='5265421696'>
E ? ^ ^^
E + <MagicMock name='Bar()' id='5265642864'>
E ? ++ + ^ ^
</code></pre>
|
<python><pytest><python-unittest.mock>
|
2024-05-06 15:05:44
| 1
| 18,040
|
lulalala
|
78,437,375
| 736,662
|
How to fail a test for an api call if json brackets are not empty
|
<p>I have a Pytest script making a HTTP call:</p>
<pre><code>def test_bid_submission_send():
# Act:
response = post_requests(token, '/xxx/api/xxx/bidsubmissions/send',
setpayload_bidsubmissions_send(powerplantId))
# Assert:
assert not response.json()["error"]
assert response.status_code == 200 # Validation of status code
</code></pre>
<p>The response is</p>
<pre><code>{"success":[],"error":[{"hpsId":10037,"powerPlant":{"name":"Saurdal","id":16606,"regionId":20,"priceArea":2,"timeSeries":null,"units":[]}}]}
</code></pre>
<p>I want to fail the test if the</p>
<pre><code>"error":[]
</code></pre>
<p>has content (which it has in my example above)</p>
<p>If the</p>
<pre><code>"success":[]
</code></pre>
<p>has content I would like to pass the test</p>
|
<python><json><pytest>
|
2024-05-06 14:41:08
| 1
| 1,003
|
Magnus Jensen
|
78,437,370
| 1,159,488
|
Trying to write a pwntools exploit to buffer-overflow a binary
|
<p>My goal is to buffer-overflow a binary written in C. That binary asks me to input a name.<br />
After having opened the binary with Ghidra, I discovered the following code that should help me to build an exploit :</p>
<pre><code>undefined8_8 main(void)
{
int iVar10;
char local_99 [106];
undefined4 local_j;
undefined2 local_gg;
setvbuf(stdin,(char *)0x0,2,0);
setvbuf(stdout,(char *)0x0,2,0);
setvbuf(stderr,(char *)0x0,2,0);
local_j = 0x64726570;
local_gg = 0x73;
puts(&DAT_00102008);
fgets(local_99,0x100,stdin);
iVar10 = strcmp((char *)&local_j,"gagne");
if (iVar10 == 0) {
win(local_99);
}
else {
puts("Bad try, try again");
}
return 0;
}
</code></pre>
<p>I see the line <code>iVar10 = strcmp((char *)&local_j,"gagne");</code> that should help. I guess this line compares the local_j variable to the string "gagne" but I'm not really sure. What's more, <code>local_j variable (0x64726570)</code> corresponds to the string <code>"perd"</code> after little-endian transformation.<br />
Anyway if I pass the test, I think I could buffer-overflow the binary and maybe get my flag.<br />
The thing I don't get is how to hack the equality in my payload ?</p>
<p>Here is a script I tried to build but it does obviously not work and don't have any other ideas :</p>
<pre><code>#!/usr/bin/env python
from pwn import *
con = remote("IP", Port)
data_ = con.recv(4096)
print(data_.decode())
payload = b"gagne" + p64(0x64726570)+b"\n"
print("payload to send =>",payload)
con.send(payload)
con.interactive()
</code></pre>
<p>Have you got some ideas ?<br />
Any help would be greatly appreciated, thanks !</p>
|
<python><binary><reverse><buffer-overflow><pwntools>
|
2024-05-06 14:40:03
| 1
| 629
|
Julien
|
78,437,296
| 9,021,875
|
Custom type from multiple inputs for click option
|
<p>I am using click library in python.
I am trying to create an option that create an object from multiple inputs in the command line.
For example if the command line is <code>python main.py --param1 a --param2 34 --param3 True --all 1</code> the option will take the 3 params (param1, param2, param3) and create a custom object from my class <code>Param</code>.
I tried to create a custom type using <code>click.ParamType</code> class but it only take a single argument.</p>
<p>Here is my Param type class</p>
<pre><code>class MyParamType(ParamType):
name = "my_type"
def convert(self, value, param, ctx):
return SpecialClass(value) # Todo - should use more values
</code></pre>
<p>I also tried to use a decorator</p>
<pre><code>def space_instance(func):
@click.option("--param1", type=str)
@click.option("--param3", type=str)
@click.option("--param3", type=str)
def param_dec(*args, param1, param2, param3, **kwargs):
param = SpicalClass(param1, param2, param3)
return func(*args, param=param, **kwargs)
return param_dec
</code></pre>
<p>This yielded the result I want but it failed when I tried to stack multiple decorator like this.</p>
<p>How can I create the option I want?</p>
|
<python><argparse>
|
2024-05-06 14:27:09
| 0
| 1,839
|
Yedidya kfir
|
78,437,281
| 7,758,213
|
Django renaming log level to 3 character format
|
<p>In python, using logging module, the log level format can be changed with:</p>
<pre><code>logging.addLevelName(logging.DEBUG, 'DBG')
</code></pre>
<p>How can I do it in Django?
My (working) logging configuration in settings.py:</p>
<pre><code>LOGGING: dict[Any, Any] = {
'version': 1,
'formatters': {
'app_log_format': {
'format': '%(asctime)s [%(levelname)s] %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S',
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': current_log_path,
'formatter': 'app_log_format',
},
},
'loggers': {
'': {
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
},
</code></pre>
<p>}</p>
<p>Thanks</p>
|
<python><django><python-logging>
|
2024-05-06 14:24:48
| 1
| 968
|
Izik
|
78,437,171
| 6,036,330
|
Import python package from zip
|
<p>In <a href="https://medium.com/snowflake/custom-packages-in-streamlit-in-snowflake-2-easy-ways-e70b453c57b8" rel="nofollow noreferrer">medium.com article</a> there is a section about accessing the packages stored in the ZIP file using code:</p>
<pre><code>import sys
sys.path.append("my_package.zip")
from my_package import my_code
</code></pre>
<p>To test this, I downloaded <code>optbinning 0.19.0</code> package from <a href="https://pypi.org/project/optbinning/#files" rel="nofollow noreferrer">PyPi</a>, extracted all files, then zipped the folder with <code>__init__.py</code> file inside and named my file as <code>optbinning_dwnl.zip</code>.</p>
<p>Now, if I try to load package as in the article using code</p>
<pre><code>import sys
import os
os.chdir("C:\\my_path")
sys.path.append('optbinning_dwnl.zip')
from optbinning_dwnl import OptimalBinning
</code></pre>
<p>I receive an error: "ModuleNotFoundError: No module named 'optbinning_dwnl". However, If I try to load package from unzipped folder, everything works fine:</p>
<pre><code>import sys
import os
os.chdir("C:\\my_path")
sys.path.append('optbinning_dwnl')
from optbinning_dwnl import OptimalBinning
</code></pre>
<p>So, is it possible to load packages from zip files or not? Maybe I am doing something wrong?</p>
|
<python><package><zip>
|
2024-05-06 14:05:26
| 1
| 655
|
neringab
|
78,437,162
| 3,813,424
|
How to mitigate some emojis consuming the whitespace character following them?
|
<p>I have a list of strings, like this:</p>
<pre><code>data = [
"- π T-SHIRT",
"- β±οΈ UMBRELLA",
"- π CAR",
"- π₯οΈ COMPUTER"
]
</code></pre>
<p>In Python, when I loop over <code>data</code>, most lines <code>print()</code> fine, however some emojis eat the single whitespace character that succeeds and divides them from their individual labels (i.e. text), and the terminal output turns out like this:</p>
<pre><code>for line in data:
print(line)
</code></pre>
<p>Terminal output:</p>
<pre><code> - π T-SHIRT
- β±οΈUMBRELLA
- π CAR
- π₯οΈCOMPUTER
</code></pre>
<p>In reality, I read the emojis and labels from a text file and don't know which emoji poses this problem and which outputs fine.</p>
<p>What is this behavior due to and how can I mitigate it?</p>
<hr />
<p><strong>Update</strong> (May 23, 2024)<strong>:</strong></p>
<p>With great insights that @Andj and @t.niese provided so far, I managed to understand that:</p>
<ol>
<li>it's most probably an issue with how the terminal emulator interprets and outputs the grapheme cluster (i.e. emoji), especially ones that include the variation selector-16</li>
<li>I can append a whitespace character to the grapheme cluster to remedy the issue above, if and only if I can faithfully identify problematic ones</li>
</ol>
<p>This is the update data set that I'm currently testing:</p>
<pre><code>DATA = [π, β±, π, π₯, π, π ]
</code></pre>
<p>The shirt and car emojis are fine. The rest pose issues.</p>
<p>I can identify the umbrella and the computer emoji with a modified, stripped down version of @Andj's code from below:</p>
<pre><code>import unicodedata
DATA = [
"π",
"β±οΈ ",
"π",
"π₯οΈ ",
"π ",
"π "
]
def codepoints(text):
return [(c, f"{ord(c):04X}", unicodedata.name(c)) for c in text]
for d in DATA:
cp = codepoints(d) + [len(d)]
print(cp)
</code></pre>
<p>This outputs:</p>
<pre><code>[('π', '1F455', 'T-SHIRT'), 1]
[('β±', '26F1', 'UMBRELLA ON GROUND'), ('οΈ', 'FE0F', 'VARIATION SELECTOR-16'), 2]
[('π', '1F697', 'AUTOMOBILE'), 1]
[('π₯', '1F5A5', 'DESKTOP COMPUTER'), ('οΈ', 'FE0F', 'VARIATION SELECTOR-16'), 2]
[('π', '1F58B', 'LOWER LEFT FOUNTAIN PEN'), 1]
[('π ', '1F6E0', 'HAMMER AND WRENCH'), 1]
</code></pre>
<p>The umbrella and computer can be identified by the <code>VARIATION SELECTOR-16</code>.
However, the fountain pen and hammer and wrench pass as single character emojis without <code>VARIATION SELECTOR-16</code>, but still cause the whitespace character in front to disappear.</p>
<p>Does anybody know how to nail down cases like these to?</p>
|
<python><python-3.x><emoji>
|
2024-05-06 14:03:13
| 2
| 319
|
St4rb0y
|
78,437,040
| 7,947,368
|
jupyter notebook removes left blank space of matplotlib
|
<p>The following code should display "ax" offset to the right (overlapping "ax1") with a padding on the left (where it was originally)</p>
<pre class="lang-py prettyprint-override"><code># Implementation of matplotlib function
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
Z = np.random.rand(6, 30)
fig, (ax, ax1) = plt.subplots(1, 2)
ax.pcolor(Z)
ax1.pcolor(Z)
chartBox = ax.get_position()
ax.set_position([chartBox.x0 + chartBox.width / 2,
chartBox.y0,
chartBox.width,
chartBox.height])
ax.set_title("Original Window")
ax1.set_title("Modified Window")
plt.show()
</code></pre>
<p>However in a jupyter notebook (tested on vscode and on colab) the left blank space is cut off, but when running the script in a .py file, it displays it correctly. How can I address this issue?</p>
<p>Both tested on a <code>Python 3.12</code> version in vscode (<code>jupyterlab==4.1.6</code>) and in terminal with <code>matplotlib==3.8.4</code>. Changing <code>plt.show()</code> by <code>plt.savefig()</code> produces the left blank space (<strong>even</strong> within notebook) I suspect the rendering from the notebook to be at fault but I do not know the exact setting.</p>
<p>Here is what the Jupyter Notebook displays:<a href="https://i.sstatic.net/BOSCl8Sz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BOSCl8Sz.png" alt="enter image description here" /></a></p>
<p>Here is what the <strong>same code</strong> running in a .py script file displays:<a href="https://i.sstatic.net/QZRtvonZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QZRtvonZ.png" alt="enter image description here" /></a></p>
<p><strong>Context</strong></p>
<p>I was iterating through some data and wanted to display multiple plots 2 by 2, on odd pairing I wanted to display the single plot centered and turned off the second empty plot. The idea was to use <code>.subplots(nrows=1,ncols=2)</code> (because I had no other idea) and offset the first plot to the right using <code>ax.set_position()</code>. As it turned out it did not work.</p>
|
<python><matplotlib><jupyter-notebook>
|
2024-05-06 13:42:57
| 1
| 639
|
Sheed
|
78,437,014
| 4,513,726
|
how to generate a coo matrix from two dataframes in sparse format
|
<p>I have two dataframes in sparse format with slightly different indices and columns. I need a coo version of a concatenated dataframe of both dataframes. When I try to generate a coo matrix from them I get zeros in the <code>data</code> attribute which is unexpected to me. Even if all the columns have a <code>pd.SparseDtype("float",0)</code> data type. It seems the fillna(0) method introduces some zeros that creep into the data of sparse formats... that shouldn't cointain zeros.</p>
<p>here some code to reproduce the behaviour</p>
<pre><code> import pandas as pd
A = pd.DataFrame(np.eye(3),index=['a','b','c'],
columns=['a','b','c']).astype(pd.SparseDtype("float",0))
B = pd.DataFrame(np.random.normal(size=(2,2)),
index=['d','e'],
columns=['a','b'],
).astype(pd.SparseDtype("float",0))
c = pd.concat([A,B],axis=0).fillna(0)
</code></pre>
<p>in that example both <code>c.sparse.to_coo().data</code> or simply <code>c.c.sparse.sp_values</code> cointain zeros, which defeats the purpose of using a sparse data format. I don't understand what is going on. How can I concatenate dataframes in sparse format and not get these taking space? I am using pandas version 2.2.2</p>
|
<python><pandas><scipy>
|
2024-05-06 13:37:48
| 1
| 1,646
|
mfastudillo
|
78,436,968
| 8,549,300
|
Cannot import module that is installed
|
<p>I have installed a Python module in a virtual environment on Ubuntu, but it is not found (<code>ModuleNotFoundError: No module named 'neuroHarmonize'</code>). I used <code>pip install neuroHarmonize</code>. When I activate my environment and run <code>pip show neuroHarmonize</code> I get:</p>
<pre><code>Name: neuroHarmonize
Version: 2.4.1
Summary: Harmonization tools for multi-center neuroimaging studies.
Home-page: https://github.com/rpomponio/neuroHarmonize
Author: Raymond Pomponio
Author-email: raymond.pomponio@outlook.com
License:
Location: /home/neuromod/ad_sz/scripts/env/lib/python3.10/site-packages
</code></pre>
<p>so it looks like it has installed correctly. I have tried everything <a href="https://stackoverflow.com/questions/14295680/unable-to-import-a-module-that-is-definitely-installed">here</a>. Grateful for any guidance, thank you!</p>
|
<python><installation>
|
2024-05-06 13:30:52
| 1
| 361
|
firefly
|
78,436,713
| 5,419,861
|
Getting "Missing Command Parameter" from winappdriver
|
<p>When we trying to switch the window handle from winappdriver,</p>
<pre><code>driver.swith_to.window(driver.window_handles[0])
</code></pre>
<p>We got the below error,</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\user_name\PycharmProjects\my_automation\test_ui,py", line 60, in test_login
self.driver.switch_to.window(self.driver.window_handles[o])
File "C:\Users\user_name\AppData\Local\anaconda3\envs\automation\Lib\site-packages\selenium\webdriver\remote\switch_to.py", line 130, in window
self._w3c_window(window_name)
File "C:\Users\user_name\AppData\Local\anaconda3\envs\automation\Lib\site-packages\selenium\webdriver\remote\switch_to.py", line 138, in _w3c_window
send_handle(window_name)
File "C:\Users\user_name\AppData\Local\anaconda3\envs\automation\Lib\site-packages\selenium\webdriver\remote\switch_to.py", line 134, in send_handle
self._driver.execute(Command.SWITCH_TO_WINDOW, {"handle": h})
File "C:\Users\user_name\AppData\Local\anaconda3\envs\automation\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 440 in execute
self.error_handLer.check_response(response)
File "C:\Users\user_name\AppData\Local\anaconda3\envs\automation\Lib\site-packages\appium\webdriver\errorhandLer.py", line 30, in check_response
raise wde
Fle "C:\Users\user_name\AppData\Local\anaconda3\envs\automation\Lib\site-packages\appium\webdriver\errorhandler.py", line 26 in check_response
super().check_response(response)
File "C:\Users\user_name\AppData\Local\anaconda3\envs\automation\Lib\site-packages\selenium\webdriver\enote\errorhandler.py" line 245 in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Missing Command Parameter: name
</code></pre>
|
<python><webdriver><winappdriver>
|
2024-05-06 12:45:03
| 0
| 695
|
Suresh Kumar
|
78,436,618
| 9,069,476
|
Finding link redirections with Python
|
<p>I have a dataframe with two rows, both correspond to apartment offers in a real estate website. The first offer has an invalid link, since the data was downloaded a long time ago and it was withdrawn; while the second one has a valid link.</p>
<pre><code>invalid=df.loc[0, "Link"]
valid=df.loc[1, "Link"]
</code></pre>
<p>The valid link is this: <a href="https://www.habitaclia.com/comprar-piso-oportunidad_grande_de_4_habitaciones_con_balcon_en_plena_ra_el_clot-barcelona-i45207000000035.htm?pag=1001&f=&geo=c&from=list&lo=55;" rel="nofollow noreferrer">https://www.habitaclia.com/comprar-piso-oportunidad_grande_de_4_habitaciones_con_balcon_en_plena_ra_el_clot-barcelona-i45207000000035.htm?pag=1001&f=&geo=c&from=list&lo=55;</a> and the invalid link is this: <a href="https://www.habitaclia.com/comprar-piso-poblenou_la_vila_olimpica_del_poblenou-barcelona-i3118004333089.htm?pag=413&f=&geo=c&from=list&lo=55" rel="nofollow noreferrer">https://www.habitaclia.com/comprar-piso-poblenou_la_vila_olimpica_del_poblenou-barcelona-i3118004333089.htm?pag=413&f=&geo=c&from=list&lo=55</a>. As you can notice, the invalid link, when trying to open it, redirects to <a href="https://www.habitaclia.com/viviendas-barcelona.htm?state=1;" rel="nofollow noreferrer">https://www.habitaclia.com/viviendas-barcelona.htm?state=1;</a> while the valid link, when trying to open it, stays at the same address.</p>
<p>I want to create a Python script that allows me to enter the links and see if they are still valid or not. I can check this because the invalid ones redirect to another address.</p>
<p>I have tried to do it with this code:</p>
<pre><code>response = requests.head(invalid, allow_redirects=True)
url_redirected = response.url
print(url_redirected)
</code></pre>
<p>But I get this link: <a href="https://www.habitaclia.com/comprar-piso-poblenou_la_vila_olimpica_del_poblenou-barcelona-i3118004333089.htm?pag=413&f=&geo=c&from=list&lo=55" rel="nofollow noreferrer">https://www.habitaclia.com/comprar-piso-poblenou_la_vila_olimpica_del_poblenou-barcelona-i3118004333089.htm?pag=413&f=&geo=c&from=list&lo=55</a>, when it should be this: <a href="https://www.habitaclia.com/viviendas-barcelona.htm?state=1" rel="nofollow noreferrer">https://www.habitaclia.com/viviendas-barcelona.htm?state=1</a>.</p>
|
<python><python-requests>
|
2024-05-06 12:26:27
| 0
| 307
|
JosΓ© Carlos Rojas
|
78,436,539
| 11,756,186
|
Superimpose plot with background (image) chart
|
<p>I am trying to use an existing graph as a background for new data that I want to plot on top of the graph.
I have been able to do so when using a graph with all information contained within the axes and using the <code>extent</code> parameter of <code>plt.imshow</code> because then I just have to scale the image.</p>
<p>I would like to scale and shift the background graph. Replotting the background is not an option in the real use case.</p>
<p>Here is what I tried so far :</p>
<ol>
<li>Generation of a background graph (reproducible example)</li>
</ol>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 5, 10], [8, 5, 12])
ax.set_xlim(0, 20)
ax.set_ylim(0, 15)
ax.set_title('Background graph')
fig.show()
fig.savefig('bg_graph.png')
</code></pre>
<p><a href="https://i.sstatic.net/0k4SFDYC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0k4SFDYC.png" alt="background_graph" /></a></p>
<ol start="2">
<li>Use <code>plt.imshow()</code> to add the background graph and then superimpose my data.</li>
</ol>
<pre><code>bg_img = plt.imread('bg_graph.png')
fig, ax = plt.subplots()
ax.imshow(bg_img, extent=[0,50,0,50])
ax.scatter([4.9, 5.2], [7, 4.9])
fig.show()
fig.savefig('result.png')
</code></pre>
<p><a href="https://i.sstatic.net/y96k970w.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/y96k970w.png" alt="superimposed_graph" /></a></p>
<p>I have made a mockup of the expected result using Excel :
<a href="https://i.sstatic.net/G9MCKHQE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/G9MCKHQE.png" alt="expected_result" /></a></p>
<p>Is there a method to stretch a new graph onto existing axis (from an image) in order to plot new pieces of data ? I assume that the coordinates of the axis in the image are known or can be guessed through trial an error. One way to rephrase this is to say that I would like to stretch the new plot to the image and not the other way around.</p>
|
<python><matplotlib><charts>
|
2024-05-06 12:12:16
| 1
| 681
|
Arthur
|
78,436,536
| 1,613,983
|
How do I prevent virtual environments having access to system packages?
|
<p>noob here. I have a dockerised jupyter lab instance where I have a bunch of packages installed for the root user, and now I want to add an additional kernel that has no packages at all (yet). Here's how I've tried to do that:</p>
<pre><code># SYSTEM SETUP
FROM python:3.11.5-bookworm
ADD requirements/pip /requirements/pip
RUN pip install -r /requirements/pip
RUN mkdir /venv/ \
&& cd /venv/ \
&& python -m venv blank \
&& /venv/blank/bin/pip install ipykernel \
&& /venv/blank/bin/python -m ipykernel install --user --name=blank-env
</code></pre>
<p>I expect the root python environment to have all the packages listed in my <code>requirements/pip</code> file and my <code>blank-env</code> environment to be empty.</p>
<p>However, when I run <code>jupyter lab</code> in the docker container and select the <code>blank-env</code> kernel, it appears to have access to all of the packages from my requirements file. What am I doing wrong here?</p>
|
<python><virtualenv>
|
2024-05-06 12:12:02
| 1
| 23,470
|
quant
|
78,436,430
| 1,552,080
|
Problems with starting waitress-serve via systemd service
|
<h2>Project Environment</h2>
<p>I have a Flask-based web service I can start from the command line. The project environment looks like this:</p>
<pre><code>BASEDIR/
startMyService.sh
|-venv/
|-/bin
|...
|-/WebService...
|-Flask-related directories
</code></pre>
<p>I am providing a virtual environment to make it run ($BASEDIR is the path, where the project environment is located):</p>
<pre><code>sudo python -m venv ./venv
source $BASEDIR/venv/bin/activate
waitress-serve --port=8080 --call 'WebService:create_app'
</code></pre>
<p>Note: when doing this, I see, that the venv has been activated by the <code>(venv)</code> prefixing the command line.</p>
<h2>Shell Script for Starting WebService</h2>
<p>I wrapped the commands above in a shell script <code>startMyService.sh</code> with the following code (<code>$BASEDIR</code> is the directory where the script is located):</p>
<pre><code>#!/bin/bash
# activate venv located in same directory as this file
python -m venv $BASEDIR/venv
source $BASEDIR/venv/bin/activate
pip install waitress
pip install flask
pip install ... whatever
# re-install the web application provided as wheel
$BASEDIR/venv/bin/pip3 uninstall myapp --yes
$BASEDIR/venv/bin/pip3 install $BASEDIR/dist/myapp-0.1.0-py3-none-any.whl --force-reinstall
# find already running instances of the service and kill them
PROCESSID=`ps aux | grep "WebService:create_app" | grep -v "grep" | awk '{print $2}'`
if [[ $PROCESSID != "" ]]
then
echo "killing existing instances of WebService with PID $PROCESSID"
kill -9 $PROCESSID
fi
# start webserver in the background
echo "Starting webService..."
waitress-serve --port=8080 --call 'WebService:create_app'
</code></pre>
<h2>Systemd Service causing Problems</h2>
<p>Now I would like to make a <code>systemd</code> service from that script. Currently, the <code>.service</code>-File looks like this:</p>
<pre><code>[Unit]
Description=My web application
Documentation=some url
[Service]
PIDFile=/run/pidfile.pid
Type=simple
ExecStart=theApplicationDirectory/startMyService.sh
ExecStop=/bin/kill -9 $MAINPID
[Install]
WantedBy=default.target
</code></pre>
<p>When I start the service via <code>sudo systemctl start myservice.service</code> the service ends up in status "dead"/incative. <code>journalctl</code> show some indication:</p>
<pre><code>...
Starting status webpage in testing mode
May 06 11:33:00 servername startMyService.sh[726211]: Error: Bad module 'WebViewer'
May 06 11:33:00 servername startMyService.sh[726211]: Usage:
May 06 11:33:00 servername startMyService.sh[726211]: waitress-serve [OPTS] MODULE:OBJECT
</code></pre>
<p>To me it seems that the activation of the virtual environment in the shell script does not happen and the service wants to start with the default Python instead of the venv.</p>
|
<python><flask><virtualenv><systemd><waitress>
|
2024-05-06 11:53:15
| 0
| 1,193
|
WolfiG
|
78,436,387
| 6,307,685
|
Clarification about the decorator of the step() method of the stochastic gradient descent class
|
<p>In the SGD class of pytorch, the <code>step()</code> method has the decorator <code>_use_grad_for_differentiable</code>:</p>
<pre class="lang-py prettyprint-override"><code>@_use_grad_for_differentiable
def step(self, closure=None):
...
</code></pre>
<p>Usually I would expect the <code>no_grad</code> decorator to be used instead.
I found no information about <code>_use_grad_for_differentiable</code> and have no idea what it does. The source code for the decorator can be found in the file <code>torch/optim/optimizer.py</code>, but it has no docstring or helpful comments, and the code is cryptic (for me). For completion, I paste it here:</p>
<pre class="lang-py prettyprint-override"><code>def _use_grad_for_differentiable(func):
def _use_grad(self, *args, **kwargs):
import torch._dynamo
prev_grad = torch.is_grad_enabled()
try:
# Note on graph break below:
# we need to graph break to ensure that aot respects the no_grad annotation.
# This is important for perf because without this, functionalization will generate an epilogue
# which updates the mutated parameters of the optimizer which is *not* visible to inductor, as a result,
# inductor will allocate for every parameter in the model, which is horrible.
# With this, aot correctly sees that this is an inference graph, and functionalization will generate
# an epilogue which is appended to the graph, which *is* visible to inductor, as a result, inductor sees that
# step is in place and is able to avoid the extra allocation.
# In the future, we will either 1) continue to graph break on backward, so this graph break does not matter
# or 2) have a fully fused forward and backward graph, which will have no_grad by default, and we can remove this
# graph break to allow the fully fused fwd-bwd-optimizer graph to be compiled.
# see https://github.com/pytorch/pytorch/issues/104053
torch.set_grad_enabled(self.defaults['differentiable'])
torch._dynamo.graph_break()
ret = func(self, *args, **kwargs)
finally:
torch._dynamo.graph_break()
torch.set_grad_enabled(prev_grad)
return ret
functools.update_wrapper(_use_grad, func)
return _use_grad
</code></pre>
<p>My question(s): what is the role of this decorator? Why not simply use <code>no_grad()</code> instead? And, finally, should I be using this decorator in my custom optimizers?</p>
|
<python><machine-learning><pytorch><gradient-descent>
|
2024-05-06 11:41:58
| 0
| 761
|
soap
|
78,436,275
| 2,695,082
|
Convert raw bytes image data received from Python into C++ Qt QIcon to be displayed in QStandardItem
|
<p>I am creating small GUI system and I would like to get an image in the form of raw bytes from Python code and then create QImage/QIcon using those raw bytes. For C++/Python interaction I am using Boost Python.</p>
<p>On Python code side I printed the raw bytes:
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00@\x00\x00\x00@\x08\x02\x00\x00\x00%\x0b\xe6\x89\x00\x00\x00\x03sBIT\x08\x08\x08\xdb\xe1O\xe0\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x06\xabIDATh\x81\xed\x9aOh\x13O\x14\xc7wv\x93\xdd\xfcQ1\xa9\x8d....</p>
<p>I send them as string from python to the C++ code like:</p>
<pre><code>data.rawBytes = str(thumbnail._raw_bytes)
</code></pre>
<p>On C++ side, I extract these bytes in the form of string as:</p>
<pre><code>std::string rawBytes = boost::python::extract<std::string>(obj.attr("rawBytes"));
</code></pre>
<p>The above rawBytes received on C++ side is same as the python print above.</p>
<p>Now in the UI code, I try to use these raw bytes to create QIcon like:</p>
<pre><code>std::string rawbytes = data.rawBytes;
QByteArray arr();
arr.append(rawbytes.c_str(), rawbytes.length());
bool flag = pixmap.loadFromData(arr, "PNG");
QStandardItem* item = new QStandardItem(name);
item->setIcon(QIcon(pixmap));
</code></pre>
<p>The icon doesn't get displayed in the UI and moreover, the 'flag' returned from pixmap.loadFromData is false which means there is some problem in conversion of the raw bytes. Can someone point out if there needs to be some kind of conversion from python to c++ code to properly render this image on the UI?</p>
|
<python><c++><python-3.x><qt>
|
2024-05-06 11:20:54
| 1
| 329
|
user2695082
|
78,435,795
| 3,941,671
|
pyside6 Is it possible to connect QSlider.valueChanged with QLabel.setText in one line?
|
<p>I have a GUI and I want to connect a slider and a label showing the current slider value.
The <code>QSlider.valueChanged</code> event returns an integer, while <code>QLabel.setText</code> needs a string. Is there a possibility, to connect these both elements in one line instead of writing an extra function?</p>
<p>The long (and only?) way:</p>
<pre><code>class MainWindow(QMainWindow):
def __init__():
...
self._label = QLabel('hello')
self._slider = QSlider()
self._slider.valueChanged.connect(self.set_value)
...
def set_value(self, value):
self._label.setText(str(value))
</code></pre>
<p>Is there a possibility to write it in one line? The following throws an error because it passes an <code>int</code> instead of a <code>string</code>.</p>
<pre><code>class MainWindow(QMainWindow):
def __init__():
...
self._label = QLabel('hello')
self._slider = QSlider()
self._slider.valueChanged.connect(self._label.setText)
...
</code></pre>
|
<python><pyside6>
|
2024-05-06 09:43:27
| 2
| 471
|
paul_schaefer
|
78,435,208
| 5,761,601
|
FastAPI background tasks do not work on Azure function apps
|
<p>I followed the <a href="https://fastapi.tiangolo.com/tutorial/background-tasks/" rel="nofollow noreferrer">documentation</a> to add background tasks to an Azure Function App with FastAPI:</p>
<pre class="lang-py prettyprint-override"><code>async def background_task():
logging.info("Background task started")
await asyncio.sleep(5)
logging.info("Background task finished")
@app.get("/do_background_task")
async def do_background_task(background_tasks: BackgroundTasks):
background_tasks.add_task(background_task)
return {"message": "Background task started, this response should return immediately."}
</code></pre>
<p>However it does not work as expected and the response is only returned after 5 seconds.</p>
<p>To reproduce this I forked the Microsoft FastAPI example repo and added the code above. The forked repository with reproduction case can be found <a href="https://github.com/warreee/fastapi-on-azure-functions-background-tasks" rel="nofollow noreferrer">here</a>.</p>
<p>It both fails when running locally and on Azure. Is this a limitation from Azure Functions or do I do something wrong?</p>
|
<python><python-3.x><azure><azure-functions>
|
2024-05-06 07:44:50
| 2
| 557
|
warreee
|
78,435,165
| 11,922,765
|
convert dataframe from florida EDT to the California timezone
|
<p>A database in Florida stores data from California in Florida day light saving time. Now, I want to convert it to the California time.</p>
<p>Code:</p>
<pre><code>import pandas as pd
from pytz import timezone
from datetime import datetime
# Sample DataFrame (ensure it is defined correctly in your script)
data = {
'Datetime': pd.date_range(start='2023-11-04', periods=10, freq='H'),
'Data': range(10)
}
invdf = pd.DataFrame(data)
invdf.set_index('Datetime', inplace=True)
# Time zone information
eastern = timezone('US/Eastern')
# Localize the datetime to Eastern time zone considering daylight saving time
invdf['Datetime'] = invdf.index
invdf['Datetime'] = invdf['Datetime'].dt.tz_localize('US/Eastern', ambiguous='infer')
# Convert to Los Angeles time (Pacific time)
invdf['Datetime'] = invdf['Datetime'].dt.tz_convert('America/Los_Angeles')
# Reset the index to updated datetime
invdf.set_index('Datetime', inplace=True, drop=True)
</code></pre>
<p>Response:</p>
<pre><code>---------------------------------------------------------------------------
AmbiguousTimeError Traceback (most recent call last)
Cell In[208], line 2
1 invdf['Datetime'] = invdf.index
----> 2 invdf['Datetime'] = invdf['Datetime'].dt.tz_localize('US/Eastern', ambiguous='infer')
3 # Convert to Los Angeles time (Pacific time)
4 invdf['Datetime'] = invdf['Datetime'].dt.tz_convert('America/Los_Angeles')
File /opt/conda/lib/python3.10/site-packages/pandas/core/accessor.py:112, in PandasDelegate._add_delegate_accessors.<locals>._create_delegator_method.<locals>.f(self, *args, **kwargs)
111 def f(self, *args, **kwargs):
--> 112 return self._delegate_method(name, *args, **kwargs)
File /opt/conda/lib/python3.10/site-packages/pandas/core/indexes/accessors.py:132, in Properties._delegate_method(self, name, *args, **kwargs)
129 values = self._get_values()
131 method = getattr(values, name)
--> 132 result = method(*args, **kwargs)
134 if not is_list_like(result):
135 return result
File /opt/conda/lib/python3.10/site-packages/pandas/core/indexes/datetimes.py:293, in DatetimeIndex.tz_localize(self, tz, ambiguous, nonexistent)
286 @doc(DatetimeArray.tz_localize)
287 def tz_localize(
288 self,
(...)
291 nonexistent: TimeNonexistent = "raise",
292 ) -> Self:
--> 293 arr = self._data.tz_localize(tz, ambiguous, nonexistent)
294 return type(self)._simple_new(arr, name=self.name)
File /opt/conda/lib/python3.10/site-packages/pandas/core/arrays/_mixins.py:81, in ravel_compat.<locals>.method(self, *args, **kwargs)
78 @wraps(meth)
79 def method(self, *args, **kwargs):
80 if self.ndim == 1:
---> 81 return meth(self, *args, **kwargs)
83 flags = self._ndarray.flags
84 flat = self.ravel("K")
File /opt/conda/lib/python3.10/site-packages/pandas/core/arrays/datetimes.py:1088, in DatetimeArray.tz_localize(self, tz, ambiguous, nonexistent)
1085 tz = timezones.maybe_get_tz(tz)
1086 # Convert to UTC
-> 1088 new_dates = tzconversion.tz_localize_to_utc(
1089 self.asi8,
1090 tz,
1091 ambiguous=ambiguous,
1092 nonexistent=nonexistent,
1093 creso=self._creso,
1094 )
1095 new_dates_dt64 = new_dates.view(f"M8[{self.unit}]")
1096 dtype = tz_to_dtype(tz, unit=self.unit)
File tzconversion.pyx:328, in pandas._libs.tslibs.tzconversion.tz_localize_to_utc()
File tzconversion.pyx:656, in pandas._libs.tslibs.tzconversion._get_dst_hours()
AmbiguousTimeError: 2023-11-05 01:00:00
</code></pre>
|
<python><pandas><dataframe><datetime><timezone>
|
2024-05-06 07:37:22
| 0
| 4,702
|
Mainland
|
78,435,157
| 12,571,870
|
Confusing conversion of types in pandas DataFrame
|
<p>Suppose I have a list of list of numbers that happen to be encoded as strings.</p>
<pre><code>import pandas as pd
pylist = [['1', '43'], ['2', '42'], ['3', '41'], ['4', '40'], ['5', '39']]
</code></pre>
<p>Now I want a dataframe where these numbers are integers.
I can see from pandas documentation that I can force a data type via <code>dtype</code>, but when I run the following:</p>
<pre><code>pyframe_1 = pd.DataFrame(pylist,dtype=int)
</code></pre>
<p>I get the following warning:</p>
<pre><code>FutureWarning: Could not cast to int32, falling back to object. This behavior is deprecated. In a future version, when a dtype is passed to 'DataFrame', either all columns will be cast to that dtype, or a TypeError will be raised.
</code></pre>
<p>and by inspection via <code>dtypes</code>:</p>
<p><code>pytypes_1 = pyframe_1.dtypes.to_list() # dtype[object_] of numpy module</code></p>
<p>my columns are <code>np.object</code> types.</p>
<p><strong>But</strong> I can cast my columns to integer via two ways:</p>
<p>First one is column by column:</p>
<pre><code>pyframe_2 = pd.DataFrame(pylist)
pyframe_2[0] = pyframe_2[0].astype(int)
pyframe_2[1] = pyframe_1[1].astype(int)
</code></pre>
<p>Second one is on the entire dataframe in an one-liner:</p>
<pre><code>pyframe_3 = pd.DataFrame(pylist).astype(int)
</code></pre>
<p>Both give me a dataframe of integer columns from a list of list of strings.</p>
<p>My question is why does the first case, where I explicitly use <code>dtype</code> when creating a dataframe raise a warning (or error) with no conversion for the types? Why even have it as an option in the first place?</p>
<p>EDIT:
Pandas version I'm running is 1.4.1.</p>
<p>EDIT:
As per suggestions of @mozway one workaround is using
<code>pyframe_1 = pd.DataFrame(pylist,dtype='Int32')</code></p>
<p>Which does convert to integer. I mean, to me it's kinda unnatural using a string (which <code>Int32</code> is) to force a cast instead of using much more intuitive <code>int</code>. Inspecting dtypes from the method, I get different integer types.
Casting with <code>dtype='Int32'</code> at instantiation level gets me <code>Int32Dtype object of pandas.core.arrays.integer module</code>. (Upon closer inspection it has an attribute of <code>numpy_dtype</code> which is <code>dtype[int32]</code> object of numpy module).
Casting with <code>.astype(int)</code> gives me <code>dtype[int32] object of numpy module</code>. So there's not much difference, I guess? IDK.</p>
|
<python><pandas><dataframe>
|
2024-05-06 07:35:19
| 1
| 438
|
ivan199415
|
78,435,139
| 12,556,481
|
Download a PDF using Selenium in Python
|
<p><em>I'm trying to download the following PDF from a browser's PDF viewer by clicking the download button.</em></p>
<p><a href="https://i.sstatic.net/VrJrnnth.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VrJrnnth.png" alt="image" /></a></p>
<p><em>I tried the following code using ID, CSS_SELECTOR, and XPATH locators, but it seems not to be working.
What could be the issue? Can someone help me with this?</em></p>
<pre><code>import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
download_url = "https://www.npci.org.in/PDF/nach/circular/2015-16/Circular-No.135.pdf"
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options)
driver.get(download_url)
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#icon')))
driver.find_element(By.ID, '#icon').click()
time.sleep(5)
driver.quit()
</code></pre>
|
<python><python-3.x><selenium-webdriver>
|
2024-05-06 07:31:45
| 3
| 309
|
dfcsdf
|
78,434,960
| 7,217,960
|
How to mock property with side effects based on self, using PyTest
|
<p>I've tried the code bellow, using <strong>new_callable=PropertyMock</strong> to mock a property call, and <strong>autospec=True</strong> to be able to access self in the side effect function:</p>
<pre><code>from unittest.mock import PropertyMock
def some_property_mock(self):
if self.__some_member == "some_value"
return "some_different_value"
else:
return "some_other_value"
mocker.patch.object(
SomeClass, "some_property", new_callable=PropertyMock, autospec=True, side_effect=some_property_mock)
</code></pre>
<p>It throws the following exception:
<strong>ValueError: Cannot use 'autospec' and 'new_callable' together</strong></p>
<p>Is there any alternative to achieve the expected behavior?</p>
<p>Edit:
I have tried the solution provided in this post <a href="https://stackoverflow.com/a/77940234/7217960">https://stackoverflow.com/a/77940234/7217960</a> but it doesn't seem to work with <strong>PropertyMock</strong>. Printing <strong>result</strong> gives <em>MyMock name='my_property()' id='136687332325264'</em> instead of <em>2</em> as expected.</p>
<pre><code>from unittest import mock
class MyClass(object):
def __int__(self):
self.my_attribute = 10
@property
def my_property(self):
return self.my_attribute + 1
def unit_under_test():
inst = MyClass()
return inst.my_property
class MyMock(mock.PropertyMock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print("MyMock __init__ called.")
with mock.patch.object(mock, 'MagicMock', MyMock):
with mock.patch.object(MyClass, 'my_property', autospec=True, side_effect=lambda self: 2) as spy:
result = unit_under_test()
assert result == 2
assert spy.call_count == 1
</code></pre>
|
<python><mocking><pytest>
|
2024-05-06 06:50:12
| 1
| 412
|
Guett31
|
78,434,891
| 7,204,691
|
How to prompt gpt so it does not make mistakes with time window
|
<p>I'm trying to extract property condition from estate description. In particular, any property being renovated in 2020 or above should be tagged as "JUST_RENOVATED" whereas if the renovation took place before 2020, it should simply be tagged as "GOOD".</p>
<p>Here is an example :</p>
<p>Given the following description :<br />
<code>Entièrement rénovée en 2017, cette jolie maison 2 chambres vous séduira par ses pièces épurées et lumineuses. PEB exceptionnel (PEB A) grÒce à la qualité d'isolation utilisée. Faible consommation de gaz pour le chauffage central. ChÒssis triple vitrage. Cuisine ouverte entièrement équipée. Installation électrique aux normes RGIE. Compteur bi-horaire. Pour plus de renseignements et pour participer aux prochaines visites, merci de contacter l'agence immobilière ASTON & PARTNERS au 081/30.44.44.</code></p>
<p>Property condition should be "GOOD".</p>
<p>However, GPT seems to have difficulties to understand time window. It will generally tag is as "JUST_RENOVATED" justifying it is in the renovation time window (despite 2017 being before 2020).</p>
<p>Here's the prompt I used, How can I improve it ?</p>
<pre><code>Extract the property condition based on descriptions.
Follow this order of decision :
1. Tag any property that has been renovated recently (i.e. 2020 and above) by "JUST_RENOVATED". If renovation have been made before 2020, tag by "GOOD".
2. Tag any property that has been recently build or is a project by "AS_NEW".
3. Tag any property with need of restorations by "TO_RENOVATE".
4. Tag any property in good condition (i.e. good energetic performance) by "GOOD".
5. If none of the above tag suit the description, tag by "NOT_FOUND".
Answer only with the tag.
</code></pre>
<p>Eventually, the python code if that can help:</p>
<pre class="lang-py prettyprint-override"><code>def debug_prompt(description):
intro_message = f"""
Extract the property condition based on descriptions.
Follow this order of decision :
1. Tag any property that has been renovated recently (i.e. 2020 and above) by "JUST_RENOVATED". If renovation have been made before 2020, tag by "GOOD".
2. Tag any property that has been recently build or is a project by "AS_NEW".
3. Tag any property with need of restorations by "TO_RENOVATE".
4. Tag any property in good condition (i.e. good energetic performance) by "GOOD".
5. If none of the above tag suit the description, tag by "NOT_FOUND".
Answer only with the tag.
"""
system_message = [{"role": "system", "content": intro_message}]
debug_prompt = [{
"role": "user",
"content": f"""
Extract the estate condition from the following description: '''{description}'''.
"""
}]
messages = system_message + debug_prompt
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=0,
)
for response in response.choices:
print(response.message.content.strip())
</code></pre>
|
<python><openai-api><large-language-model>
|
2024-05-06 06:35:52
| 1
| 307
|
Mathieu Rousseau
|
78,434,881
| 4,442,753
|
May I implement a classmethod calling instance attributes?
|
<p>I need a class function which creates a new instance from existing instance attributes.</p>
<p>This seems to me to be a factory function (hence the thought that it could be a class method), but it needs the class to be instanced.</p>
<p>Should/may I use the <code>@classmethod</code> decorator?</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass
@dataclass
class Coin:
obverse: str
reverse: str
def flip(self):
return Coin(self.reverse, self.obverse)
cent = Coin('cent_ob', 'cent_rev')
flipped_cent = cent.flip()
cent
Out[20]: Coin(obverse='cent_ob', reverse='cent_rev')
flipped_cent
Out[21]: Coin(obverse='cent_rev', reverse='cent_ob')
</code></pre>
<p>This works. But if I use the decorator, it does not.</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass
@dataclass
class Coin:
obverse: str
reverse: str
@classmethod
def flip(cls, self):
return cls(self.reverse, self.obverse)
cent = Coin('cent_ob', 'cent_rev')
flipped_cent = cent.flip()
TypeError: Coin.flip() missing 1 required positional argument: 'self'
</code></pre>
<p>What case am I dealing with here? Is there another decorator more suited to this case?</p>
<p>My primary goal is more to have a decorator explicitly indicating "hey, you have a factory function here".</p>
|
<python>
|
2024-05-06 06:33:30
| 1
| 1,003
|
pierre_j
|
78,434,832
| 8,723,790
|
Python Flask Blueprint routes always print request and response content
|
<p>In my Python Flask app I use Blueprint route to serve and handle API requests.</p>
<p>app/<strong>init</strong>.py</p>
<pre><code>from api.foo import foo_route
def create_app(config):
app = Flask(__name__)
app.register_blueprint(foo_route)
...
return app
</code></pre>
<p>api/foo.py</p>
<pre><code>from flask import Blueprint, request, jsonify
foo_route = Blueprint("foo", __name__)
@foo_route.route("/path/to/foo/API", methods=["POST"])
def handle_foo_api(request):
result = {"foo1": "foo1", "foo2": "foo2"}
return jsonify(result), 200
</code></pre>
<p>How can I print all API request headers/body and response headers/body?</p>
<p>I can print it inside each function. For example, to print the request header for function handle_foo_api:</p>
<pre><code>@foo_route.route("/path/to/foo/API", methods=["POST"])
def handle_foo_api(request):
logger.info(f"handle_foo_api request headers: {request.headers}")
logger.info(f"handle_foo_api request data: {request.json}")
result = jsonify({"foo1": "foo1", "foo2": "foo2"})
logger.info(f"handle_foo_api response headers: {resp.headers}")
logger.info(f"handle_foo_api response data: {resp.get_json()}")
return result, 200
</code></pre>
<p>But I would like to do it once and for all, instead of in each function. How can I do that?</p>
|
<python><flask>
|
2024-05-06 06:19:45
| 1
| 301
|
Paul Chuang
|
78,434,754
| 3,643,544
|
What is the space complexity of the following code?
|
<p>What is the space complexity of the following code?</p>
<pre><code>def f(n):
sum = 0
if n == 0:
return 1
else:
for i in range(n):
sum = sum + f(i)
return sum
</code></pre>
<p>So, this is a recursive function and I thought since every function is calling all the functions below it, the space complexity would be O(n!) since the stack would maintain all the function calls. But the correct answer is O(n). Can someone please explain in detail?</p>
|
<python><recursion><space-complexity>
|
2024-05-06 05:56:06
| 1
| 456
|
idpd15
|
78,434,699
| 11,922,765
|
Why does filtering based on a condition results in an empty DataFrame in pandas?
|
<p>I'm working with a DataFrame in Python using pandas, and I'm trying to apply multiple conditions to filter rows based on temperature values from multiple columns. However, after applying my conditions and using <code>dropna()</code>, I end up with zero rows even though I expect some data to meet these conditions.</p>
<p>The goal is compare with Ambient temp+40 C and if the value is more than this, replace it with NaN. Otherwise, keep the original value.</p>
<p>Here's a sample of my DataFrame and the conditions I'm applying:</p>
<pre><code>data = {
'Datetime': ['2022-08-04 15:06:00', '2022-08-04 15:07:00', '2022-08-04 15:08:00',
'2022-08-04 15:09:00', '2022-08-04 15:10:00'],
'Temp1': [53.4, 54.3, 53.7, 54.3, 55.4],
'Temp2': [57.8, 57.0, 87.0, 57.2, 57.5],
'Temp3': [59.0, 58.8, 58.7, 59.1, 59.7],
'Temp4': [46.7, 47.1, 80, 46.9, 47.3],
'Temp5': [52.8, 53.1, 53.0, 53.1, 53.4],
'Temp6': [50.1, 69, 50.3, 50.3, 50.6],
'AmbientTemp': [29.0, 28.8, 28.6, 28.7, 28.9]
}
df1 = pd.DataFrame(data)
df1['Datetime'] = pd.to_datetime(df1['Datetime'])
df1.set_index('Datetime', inplace=True)
</code></pre>
<p><strong>Code:</strong></p>
<pre class="lang-py prettyprint-override"><code>temp_cols = ['Temp1', 'Temp2', 'Temp3', 'Temp4', 'Temp5', 'Temp6']
ambient_col = 'AmbientTemp'
condition = (df1[temp_cols].lt(df1[ambient_col] + 40, axis=0))
filtered_df = df1[condition].dropna()
print(filtered_df.shape)
</code></pre>
<p><strong>Response:</strong></p>
<pre><code>(0, 99)
</code></pre>
<p><strong>Problem:</strong></p>
<p>Despite expecting valid data that meets the conditions, the resulting DataFrame is empty after applying the filter and dropping NaN values. What could be causing this issue, and how can I correct it?</p>
|
<python><pandas><dataframe><numpy>
|
2024-05-06 05:37:16
| 2
| 4,702
|
Mainland
|
78,434,560
| 10,132,474
|
lmdb read slow when file amout is a little larger
|
<p>I installed lmdb from python:</p>
<pre><code>python -m pip install lmdb
</code></pre>
<p>Then I write images into it, I have two settings, one is inserting 6800 images, and the other is 10000 images. All the images have size of 1024x2048, and they are in png format, and my memory size is 1T.</p>
<p>Here is part of the code piece with which I read images from it:</p>
<pre><code> def init_lmdb(self):
self.env = lmdb.open(
self.file_root,
map_size=2**40,
readonly=True,
max_readers=512,
readahead=False,
)
def get_bins(self, inds):
im_bins = []
with self.env.begin(write=False) as txn:
for ind in inds:
impth = self.im_paths[ind]
im_bin = txn.get(impth)
im_bins.append(np.frombuffer(im_bin, dtype=np.uint8))
return im_bins
</code></pre>
<p>I used identical code to read from the two lmdb files, I found that the first lmdb with 6800 images needs about 9s to read 6400 images in random order, while the second lmdb with 10000 images requires 16s to read same amount of images in random order.</p>
<p>Would you tell me what is the cause of the difference ?</p>
<p>PS: I do not read images for only once. Actually, I read from only half of the images. For the lmdb with 6800 images, I only read from the 3400 of them. Also, for the lmdb with 10000 images, I only read from the subset of 5000 images. The images are read in random order, and images can be read more than one time. Until the total amount of read reaches 6400, I tested the time.</p>
|
<python><memory><io><lmdb>
|
2024-05-06 04:38:21
| 0
| 1,147
|
coin cheung
|
78,434,495
| 1,613,983
|
How do I map new SQL Server functions to SQL Alchemy's ORM
|
<p>I want to call <code>SUSER_SNAME</code> using SQLAlchemy's ORM. I can call the <code>user()</code> function like this:</p>
<pre><code>res = connection.execute(sqlalchemy.sql.functions.user())
</code></pre>
<p>But If I replace <code>user()</code> with <code>suser_sname()</code> I get this:</p>
<blockquote>
<p>AttributeError: module 'sqlalchemy.sql.functions' has no attribute
'suser_sname'</p>
</blockquote>
<p>I know that I can just execute <code>sqlalchemy.text("SELECT SUSER_SNAME()")</code> but I would like to add a custom function to achieve this. Is this possible?</p>
|
<python><sqlalchemy>
|
2024-05-06 04:08:25
| 1
| 23,470
|
quant
|
78,434,489
| 2,597,146
|
Argparse How to add mutually exclusive group to argument group help text used as parent parser for all subparsers
|
<p>The <a href="https://docs.python.org/3.12/library/argparse.html#argparse.ArgumentParser.add_mutually_exclusive_group" rel="nofollow noreferrer">argparse docs</a> refer to an example of how to add a mutually exclusive group to an argument group to add title/description to those arguments. However, when used in <code>parents</code> to subparsers the mutually exclusive group is left out of the argument group help text description.</p>
<p>This snippet code:</p>
<pre><code>from argparse import ArgumentParser
parent_parser = ArgumentParser(add_help=False)
parent_parser.add_argument('--common')
parent_parser_group = parent_parser.add_argument_group('New Group', 'Description.')
parent_parser_group.add_argument('--non-mut')
meg = parent_parser_group.add_mutually_exclusive_group()
meg.add_argument('--mut1', dest='mut')
meg.add_argument('--mut2', dest='mut')
parser = ArgumentParser(description='The main parser.')
subparsers = parser.add_subparsers(dest='subcommand', required=True)
command1_parser = subparsers.add_parser('command1', parents=[parent_parser])
command1_parser.add_argument('--c1')
command2_parser = subparsers.add_parser('command2', parents=[parent_parser])
command2_parser.add_argument('--c2')
command1_parser.print_help()
</code></pre>
<p>Prints out</p>
<pre><code>usage: argparse_debug.py command1 [-h] [--common COMMON] [--non-mut NON_MUT] [--mut1 MUT | --mut2 MUT] [--c1 C1]
options:
-h, --help show this help message and exit
--common COMMON
--mut1 MUT
--mut2 MUT
--c1 C1
New Group:
Description.
--non-mut NON_MUT
</code></pre>
<p>But I was expecting</p>
<pre><code>usage: argparse_debug.py command1 [-h] [--common COMMON] [--non-mut NON_MUT] [--mut1 MUT | --mut2 MUT] [--c1 C1]
options:
-h, --help show this help message and exit
--common COMMON
--c1 C1
New Group:
Description.
--mut1 MUT
--mut2 MUT
--non-mut NON_MUT
</code></pre>
<p>Also note that <code>parent_parser.print_help()</code> has the expected behavior, so something is lost when set as a parent.</p>
<pre><code>usage: argparse_debug.py [--common COMMON] [--non-mut NON_MUT] [--mut1 MUT | --mut2 MUT]
options:
--common COMMON
New Group:
Description.
--non-mut NON_MUT
--mut1 MUT
--mut2 MUT
</code></pre>
<p>How can I get a common mutually exclusive group with its own title/description in the help message of a subcommand?</p>
|
<python><argparse><python-3.12>
|
2024-05-06 04:06:16
| 2
| 632
|
Phoenix
|
78,434,091
| 18,157
|
Apply shell expansion to arguments in run/debug configuration?
|
<p>I'm working on a Python script, in PyDev, which will be invoked from the command line. In that environment, shell expansion will be applied to the argument list, which is what I need.</p>
<p>When running or debugging in Eclipse/PyDev, that expansion is NOT applied, making it difficult to test under "real" conditions.</p>
<p>Is there a way to configure PyDev to run or debug within a sub-shell environment where expansion is applied?</p>
|
<python><eclipse><pydev>
|
2024-05-05 23:55:25
| 1
| 86,987
|
Jim Garrison
|
78,433,954
| 8,010,064
|
Find element in HTML text - Selenium Python
|
<p>I'm trying to find elements by plain or <code>innerHTML</code> text:</p>
<pre><code>newresults = driver.find_elements("xpath","//*[@class='card is-category-product']")
for result in newresults:
htmlEl = result.get_attribute('innerHTML')
</code></pre>
<p>So basically I want to search within my htmlEl variable<br />
<code>htmlEl</code> returns each block as so:</p>
<pre><code><figure class="card-figure card-link">
<picture class="card-picture ratio ratio-4x3">
<source srcset="url-to-image">
<source srcset="url-to-image"> <img src="url-to-image" class="card-img object-fit-contain is-contain" loading="lazy" alt="image-alt"> </picture>
<figcaption class="card-caption">
<h3 class="mb-0">TITLE OF CARD</h3>
<p class="small">Random text</p>
</figcaption>
<a href="/random-url" class="card-link-overlay" title="TITLE" aria-label="title"></a>
</figure>
</code></pre>
<p>So for examplem I want to find the H3 element with class "mb-0" that should return - TITLE OF CARD. I've tried</p>
<pre><code>foundname = driver.find_element(By.XPATH, "//h3[@class='mb-0']")
</code></pre>
<p>but obviously this searches in my original URL specified and not in my <code>htmlEl</code> variable.</p>
|
<python><selenium-webdriver>
|
2024-05-05 22:37:40
| 2
| 312
|
buzz
|
78,433,813
| 13,829,601
|
Pyglet - How can I add a bloom postprocessing step to my scene?
|
<p>I have a simple <a href="https://pyglet.readthedocs.io/en/latest/" rel="nofollow noreferrer">Pyglet</a> scene below. I would like to apply a postprocessing step to add bloom to the scene. How can this be done using pyglet?</p>
<p>I've tried looking through all the documentation for framebuffers and postprocessing steps but I can't see a way to intuitively do this in pyglet.</p>
<pre><code>import pyglet
from pyglet.graphics.shader import Shader, ShaderProgram
from pyglet.gl import *
from pyglet.math import Mat4, Vec3
window = pyglet.window.Window(width=1280, height=720, caption="Hello Pyglet", resizable=True)
vertex_source = """
#version 330
in vec2 vertices;
uniform mat4 vp;
uniform mat4 model;
void main() {
gl_Position = vp * model * vec4(vertices, 0.0, 1.0);
}
"""
fragment_source = """
#version 330
out vec4 fragColor;
void main() {
vec3 col = vec3(1.0,1.0,1.0);
col *= 5.0;
fragColor = vec4(col,1.0);
}
"""
vert_shader = Shader(vertex_source, "vertex")
frag_shader = Shader(fragment_source, "fragment")
program = ShaderProgram(vert_shader, frag_shader)
view_mat = Mat4.from_translation(Vec3(x=0, y=0, z=-1))
proj_mat = Mat4.orthogonal_projection(left=0, right=1280, bottom=0, top=720, z_near=0.1, z_far=100)
vp = proj_mat @ view_mat
program['vp'] = vp
translation_mat = Mat4.from_translation(Vec3(x=640,y=360,z=0))
program['model'] = translation_mat
batch = pyglet.graphics.Batch()
vertices = [(x - 1) * 100 for x in (-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5)]
vertices2 = [(x + 1) * 100 for x in (-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5)]
indices = (0, 1, 2, 2, 3, 0)
program.vertex_list_indexed(4, GL_TRIANGLES,
batch=batch,
indices=(0,1,2,2,3,0),
vertices=('f', vertices))
program.vertex_list_indexed(4, GL_TRIANGLES,
batch=batch,
indices=(0,1,2,2,3,0),
vertices=('f', vertices2))
@window.event
def on_draw():
window.clear()
batch.draw()
pyglet.app.run()
</code></pre>
|
<python><opengl><glsl><pyglet>
|
2024-05-05 21:27:37
| 0
| 416
|
Raga
|
78,433,757
| 8,785,574
|
telegram doesn't show white spaces correctly
|
<p>I create a text in Python, and it displays correctly in its true shape in the terminal. However, when I use the Telegram API to send it to my channel, the white space sizes are not shown correctly. Here is a picture of the text in the terminal, and the other one is in Telegram.</p>
<p>I use this Python code to generate the results:</p>
<pre><code>for name, price in prices:
text += f"{name:<20} {price}\n"
print(text)
</code></pre>
<p><a href="https://i.sstatic.net/8g9CNMTK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8g9CNMTK.png" alt="preview in terminal" /></a>
<a href="https://i.sstatic.net/mUNRX6Ds.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mUNRX6Ds.png" alt="preview in telegram" /></a></p>
<p>I tried using the U+00A0 character, but it didn't solve the problem.</p>
|
<python><telegram><telegram-bot>
|
2024-05-05 21:02:46
| 1
| 364
|
Mahdiyar Zerehpoush
|
78,433,740
| 7,267,141
|
How to prevent matplotlib Axes.imshow from destroying the plot layout?
|
<p>I have the following code which is supposed to draw an image at specific region on a red background. At first I did not draw any image, just making the background red:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
papersize = (8.5, 11)
fig = plt.figure(figsize=papersize)
ax = fig.add_axes(rect=(0, 0, 1, 1))
ax.add_patch(plt.Rectangle((0, 0), 1, 1, color="red", zorder=-1))
# this row changes the layount of the image
# ax.imshow(np.asarray([[0, 1], [1, 0]]), cmap="gray", extent=(0.25, 0.75, 0.25, 0.75))
fig.savefig("test.png", dpi=200)
</code></pre>
<p>Which creates this nice red A4-sized image</p>
<p><a href="https://i.sstatic.net/mdl9EqtD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mdl9EqtD.png" alt="enter image description here" /></a></p>
<p>But when I uncomment the line with <code>imshow</code>, instead of drawing a simple image in the middle, all hell breaks lose, resulting in the following image that spans the full width and other mess:</p>
<p><a href="https://i.sstatic.net/CbQ0Q2cr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CbQ0Q2cr.png" alt="enter image description here" /></a></p>
<p>I have no idea why this happens or how to prevent it. Please tell me what am I missing.
The goal is to be able to draw multiple images at locations specified by the extent, while NOT breaking the layout of everything else.</p>
<p>I want to have a figure of the specified size, have the axes span the whole figure and just have a drawing canvas for me to put images on.</p>
|
<python><matplotlib>
|
2024-05-05 20:52:54
| 1
| 603
|
Adam Bajger
|
78,433,719
| 14,943,540
|
Enable communication between two servers on local machine
|
<p>I want to send an HTTP request from a server to a flask app, both running on my local machine.
I'm sending the http request as:</p>
<p><code>var response = await httpClient.PostAsync("http://192.168.1.56:5000/api/forward-file", form);</code></p>
<p>I've used <code>telnet</code> command to check for connection on the flask app at</p>
<pre><code>telnet 192.168.1.56 5000
</code></pre>
<p>I've even added a firewall rule to allow the connection.
After sending the request, the flask app prints on console the following error:</p>
<pre><code>"ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
ERROR:websocket:[WinError 10061] No connection could be made because the target machine actively refused it - goodbye".
</code></pre>
<p>I'm sure that IP and Port are correct because flask prints:
<code>* Running on http://192.168.1.56:5000"</code></p>
<p>And the controller on the Flask app is at <code>/api/forward-file</code> because of these settings <code>@file_blueprint.route('/forward-file', methods=['POST'])</code> on the flask controller and <code>app.register_blueprint(file_blueprint, url_prefix='/api')</code></p>
|
<python><web-services><flask>
|
2024-05-05 20:47:11
| 0
| 321
|
federico D'Armini
|
78,433,575
| 18,494,333
|
Specify multiple values for one argument Python Argparser
|
<p>I've built a working CLI for my app using python's <code>argparse</code>. It's called <code>comicbot</code>, and it sends emails with comics in them. The <code>bulk</code> subparser allows a certain number of comics to be specified.</p>
<pre><code>usage: comicbot bulk [-h] [-e END | -c COUNT] email [email ...] comic start
positional arguments:
email recipient email addresses
comic comic on gocomics [calvin-and-hobbes]
start date of first strip [YYYY-MM-DD]
options:
-h, --help show this help message and exit
-e END, --end END date of last strip [YYYY-MM-DD]
-c COUNT, --count COUNT
number of comics to include
</code></pre>
<p>I have three positional arguments: <code>email</code>, <code>comic</code> and <code>date</code>. My problem is that <code>email</code> accepts one or more values. How can I specify that these values belong to <code>email</code>, rather than the second filling the <code>comic</code> slot, and the third the <code>date</code>?</p>
<p>I've tried the following.</p>
<pre><code>python -m comicbot bulk 123@gmail.com 456@gmail.com calvin-and-hobbes 1995-06-06 -c 5
# interprets 456@gmail.com as comic
python -m comicbot bulk {123@gmail.com, 456@gmail.com} calvin-and-hobbes 1995-06-06 -c 5
# interprets email as '{123@gmail.com, 456@gmail.com}'
</code></pre>
<p>Square brackets behave the same as {}, and () throw an error from terminal.</p>
<p>I am able to change the structure of my program to just accept a single argument for <code>email</code> and then give a string of addresses seperated by commas, but I'd rather find a solution to this.</p>
<p>Any suggestions? Any code changes required? Or just syntax?</p>
|
<python><syntax><command-line-interface><argparse>
|
2024-05-05 19:57:01
| 1
| 387
|
MillerTime
|
78,433,554
| 15,540,632
|
Python Pyspark dataframe Object to R sparklyr dataframe object, is the conversion possible?
|
<p>I want to execute python in R, I found <a href="https://rstudio.github.io/reticulate/" rel="nofollow noreferrer">reticulate</a>, it is R package to execute python code. However, the python code returns a <em><strong>pyspark dataframe object</strong></em>, how can I convert it to an R object (potentially sparklyr dataframe) then to data.table in R?</p>
<p>let's assume this is the code that generates a pyspark dataframe object that could be executed using reticulate:</p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql import SparkSession
from pyspark.sql.functions import rand
spark = SparkSession.builder.appName('random_dataframe').getOrCreate()
schema = ["id", "value"]
df = spark.range(0, 100).select("id", (rand(seed=42) * 100).alias("value"))
</code></pre>
<p>in R, I am doing the basics of reticulate package:</p>
<pre><code>library(reticulate)
use_python("/usr/local/bin/python")
py_run_string("<PYTHON CODE AS ONE LINE STRING>")
</code></pre>
<p>After that using <code>py_to_r()</code> to convert the python <code>df</code> to un R object gives an error <strong>(ERROR: Unwanted conversion type)</strong>, if I understood correctly, there isn't an implementation in reticulate package to convert pyspark dataframe to an R object.</p>
<h3>Question</h3>
<p>is there a solution for that? and is there a solution that invloves pyarrow instead of pyspark, for instance, if the python code returns pyarrow table, can I convert it to R object?</p>
<blockquote>
<p><em><strong>NOTE:</strong></em> reticulate has no problem converting pandas to data.table object in R, but Converting the pyspark dataframe to pandas then to data.table is not possible since it crashes machine which has 49GB RAM (I am dealing with big data)</p>
</blockquote>
<p>really appreciate any help!</p>
|
<python><r><pyspark><sparklyr><reticulate>
|
2024-05-05 19:48:58
| 0
| 414
|
Ali Massoud
|
78,433,277
| 262,748
|
How to deal with a python project dependency that "must exist" in the env but can't be installed?
|
<p>I don't have a lot of experience with python project organization, but I've been trying to follow modern best practices using a <a href="https://packaging.python.org/en/latest/discussions/setup-py-deprecated/" rel="nofollow noreferrer">pyproject.toml</a> and structure as in this <a href="https://www.youtube.com/watch?v=DhUpxWjOhME" rel="nofollow noreferrer">video</a> (minus the ci bits).</p>
<p>This is ultimately a geoprocessing tool for ArcGIS Pro, though I've tried to abstract the logic of the tool from the 'backend' calls to ArcGIS Pro so that I could create other backends in the future, for example for QGIS or geopandas and rasterio.</p>
<p>However, the <code>arcpy</code> module that allows one to interface with ArcGIS Pro is not a module you can just install into your environment from pypi. It simply "exists" in the conda environment provided by the install of ArcGIS Pro. I've been writing and running scripts by activating this conda env. I don't think it would work to list <code>arcpy</code> as a dependency in <code>pyproject.toml</code> since it can't be installed.</p>
<p>How do you deal with this situation? What are best practices?</p>
<p>Note: The <code>arcpy</code> package <em>might</em> be installable via conda, according to <a href="https://pro.arcgis.com/en/pro-app/latest/arcpy/get-started/available-python-libraries.htm" rel="nofollow noreferrer">this doc from esri</a>. At the very least, I can clone the default env provided by ArcGIS Pro and modify that (to install dev deps). As stated, I'm quite new to python project management (and it's rather confusing), but if I listed my deps in pyproject.toml, generated a requirements.txt, then installed them into a conda dev env from requirements.txt, might that work?</p>
<p>pip can see <code>arcpy</code> in the conda env:</p>
<pre><code>PS> pip list
Package Version
--------------------------------- -----------------
anyio 3.5.0
appdirs 1.4.4
arcgis 2.2.0.1
...
</code></pre>
|
<python><pip><conda><arcpy><pyproject.toml>
|
2024-05-05 18:10:21
| 1
| 5,320
|
Benny Jobigan
|
78,433,231
| 5,179,240
|
version `GLIBC_2.28' not found when running aws lambda python 3.9
|
<p>Suddenly, when I run my AWS lambda, I'm getting this error:</p>
<pre><code>"Unable to import module 'lambda_name': /lib64/libc.so.6: version `GLIBC_2.28' not found (required by /var/task/cryptography/hazmat/bindings/_rust.abi3.so)
</code></pre>
<p>I'm using Python runtime 3.9 with the following requirments.txt:</p>
<pre><code>boto3
botocore
pycparser
pyopenssl
certifi
cffi
</code></pre>
|
<python><amazon-web-services><aws-lambda>
|
2024-05-05 17:52:55
| 2
| 335
|
Dalal Alghomlas
|
78,433,181
| 4,212,158
|
How to correctly delete abandoned Python filelocks on Linux
|
<p>As mentioned elsewhere, Python's <code>FileLock</code>s do not delete themselves after being released on Linux (<a href="https://stackoverflow.com/questions/58098634/why-does-the-python-filelock-library-delete-lockfiles-on-windows-but-not-unix">[1]</a><a href="https://github.com/tox-dev/filelock/issues/31" rel="nofollow noreferrer">[2]</a>). This fails:</p>
<pre class="lang-py prettyprint-override"><code>import os
from filelock import FileLock
with FileLock("/tmp/test.lock"):
print("Lock acquired")
assert not os.path.exists("/tmp/test.lock") # Fails
</code></pre>
<p>My question, what is the correct way to clean up the lock files? In the official repo, <a href="https://github.com/tox-dev/filelock/issues/76#issuecomment-696409014" rel="nofollow noreferrer">someone suggests</a> to</p>
<blockquote>
<p>wrap your locking logic in a context manager at the application/stack level and remove the lock file on <strong>exit</strong>().</p>
</blockquote>
<p>...but doesn't provide code samples. How might someone do this on a multi-process job, like a Pytorch distributed run?</p>
|
<python><design-patterns><multiprocessing><file-locking>
|
2024-05-05 17:38:26
| 0
| 20,332
|
Ricardo Decal
|
78,433,026
| 18,313,927
|
coroutine was never awaited when running my test functions with pytest-asyncio and moto
|
<p>I have a function that lists and returns dynamodb tables</p>
<pre><code>async def func(connectionId: str | None) -> list[str]:
async with aioboto3.Session().client("dynamodb") as db:
response = await db.list_tables()
table_names = response.get('TableNames', [])
return table_names
</code></pre>
<p>I'm writing a unit test for this function with <a href="https://docs.getmoto.org/en/5.0.6/docs/getting_started.html" rel="nofollow noreferrer">moto</a></p>
<pre><code>@pytest.mark.asyncio
@mock_aws
async def test_func():
async with aioboto3.Session().client("dynamodb") as db:
exp_result = ['test']
await db.create_table(
TableName='test',
KeySchema=[{'AttributeName': 'connectionId', 'KeyType': 'HASH'}],
AttributeDefinitions=[{'AttributeName': 'connectionId', 'AttributeType': 'S'}],
ProvisionedThroughput={'ReadCapacityUnits': 1, 'WriteCapacityUnits': 1}
)
result = await func("2")
assert result == exp_result
</code></pre>
<p>This gives me an error</p>
<pre><code>RuntimeWarning: coroutine 'test_func' was never awaited
</code></pre>
<p>This seems to be happening only if I layer both <code>moto</code> and <code>pytest-asyncio</code></p>
<p>If I leave out the async parts and create my function, the tests do pass</p>
<p>Function</p>
<pre><code>def func(connectionId: str | None) -> list[str]:
db = boto3.client('dynamodb')
response = db.list_tables()
table_names = response.get('TableNames', [])
return table_names
</code></pre>
<p>Test</p>
<pre><code>@mock_aws
def test_func():
exp_result = ['test']
db = boto3.client("dynamodb")
db.create_table(
TableName='test',
KeySchema=[{'AttributeName': 'connectionId', 'KeyType': 'HASH'}],
AttributeDefinitions=[{'AttributeName': 'connectionId', 'AttributeType': 'S'}],
ProvisionedThroughput={'ReadCapacityUnits': 1, 'WriteCapacityUnits': 1}
)
result = func("2")
assert result == exp_result
</code></pre>
<p>I'd be happy with some other solution for my problem too. I don't have to use <code>moto</code></p>
<p><a href="https://stackoverflow.com/questions/49350821/runtimewarning-coroutine-was-never-awaited-in-tests">This question</a> seemed to mention that <code>pytest-asyncio</code> needs to be installed, but I have verified that it is installed.</p>
<pre><code>pip list --format=freeze | grep asyncio
>>>
pytest-asyncio==0.23.6
</code></pre>
|
<python><pytest><python-asyncio><moto>
|
2024-05-05 16:51:47
| 1
| 717
|
Vishal Balaji
|
78,432,974
| 5,722,359
|
Why are `_parent_pid` and `_parent_name` attributes of class BaseProcess(object) in multiprocessing/process.py assigned with current info?
|
<p>According to the <code>multiprocessing/process.py</code> file for Python 3.10.12:</p>
<pre><code>class BaseProcess(object):
'''
Process objects represent activity that is run in a separate process
The class is analogous to `threading.Thread`
'''
def _Popen(self):
raise NotImplementedError
def __init__(self, group=None, target=None, name=None, args=(), kwargs={},
*, daemon=None):
assert group is None, 'group argument must be None for now'
count = next(_process_counter)
self._identity = _current_process._identity + (count,)
self._config = _current_process._config.copy()
self._parent_pid = os.getpid()
self._parent_name = _current_process.name
self._popen = None
self._closed = False
self._target = target
self._args = tuple(args)
self._kwargs = dict(kwargs)
self._name = name or type(self).__name__ + '-' + \
':'.join(str(i) for i in self._identity)
if daemon is not None:
self.daemon = daemon
_dangling.add(self)
</code></pre>
<p>May I know why lines 86 & 87 write this:</p>
<pre><code>self._parent_pid = os.getpid()
self._parent_name = _current_process.name
</code></pre>
<p>and not</p>
<pre><code>self._parent_pid = os.getppid()
self._parent_name = _parent_process.name
</code></pre>
<p>Meaning, should not the parent info instead of the current info be used for the parent attributes?</p>
|
<python><python-multiprocessing>
|
2024-05-05 16:35:13
| 1
| 8,499
|
Sun Bear
|
78,432,724
| 15,140,144
|
Python stub: how to annotate properly a function that uses CPython PySequence_Check?
|
<p>I have a function implemented in C that is exposed to python (c extension) that accepts a sequence. Its signature looks something like this:</p>
<pre class="lang-py prettyprint-override"><code>from typing import Sequence
def my_c_func(my_sequence: Sequence[TypeDoesntMatter]):
...
</code></pre>
<p>But the thing is, <code>Sequence</code> generic is way more descriptive than what <code>PySequence_Check</code> validates as a sequence (<a href="https://github.com/python/typeshed/blob/8ff50fbea2f607380c23d9b120fccfb1926284e5/stdlib/typing.pyi#L527-L539" rel="nofollow noreferrer">source</a>), as documentation for <code>PySequence_Check</code> clearly <a href="https://github.com/python/typeshed/blob/8ff50fbea2f607380c23d9b120fccfb1926284e5/stdlib/typing.pyi#L527-L539" rel="nofollow noreferrer">states</a> that it returns <code>1</code> if an object has <code>__getitem__</code> magic method, unless it's a dict. Satisfying the first part is easy: creating a custom generic with <code>__getitem__</code>, but marking that the value cannot be a dictionary or its subclass? - at least according to this <a href="https://stackoverflow.com/a/60408302/15140144">answer</a> is impossible.</p>
<p><sup>Why I think that this question is not a duplicate of the already mentioned one? First of, the solution given there doesn't work for my use-case, and secondly, while excluding a dictionary is one of the solutions that could work (if it was possible), It isn't the only theoretical solution that could exist for my issue.</sup></p>
|
<python><mypy><python-typing><function-signature>
|
2024-05-05 15:24:01
| 0
| 316
|
oBrstisf8o
|
78,432,532
| 6,037,769
|
Django ordering with many to many relationship in model
|
<p>I am using Django-rest-framework modelviewset, I have a many-to-many relationship with my models below:</p>
<pre><code>class Data(TimestampMixin):
user = models.ForeignKey(
"User",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="files",
)
file = models.FileField(upload_to=user_directory_path, null=True, blank=True)
doc_id = models.TextField(null=True, blank=True)
url = models.CharField(max_length=255, null=True, blank=True)
deleted = models.BooleanField(default=False)
tags = models.ManyToManyField("Tag", blank=True, null=True)
class Tag(models.Model):
team = models.ForeignKey("Team", on_delete=models.CASCADE, blank=True, null=True)
name = models.TextField(max_length=255)
</code></pre>
<p>now here is my problem, I want to create a sorting for tag name, and here is what i've got in my Model-view-set:</p>
<pre><code>class UserDataViewSet(ModelViewSet):
queryset = Data.objects.all()
serializer_class = UserDataSerializer
ordering_fields = ["file"]
def get_queryset(self):
user = self.request.user
queryset = super().get_queryset()
owner_id = getattr(self.request.user.team, "owner_id", None)
if user is not None:
if owner_id is not None:
queryset = queryset.filter(user=owner_id, deleted=False)
else:
queryset = queryset.filter(user=user, deleted=False)
ordering = self.request.query_params.get("ordering", "")
if ordering == "tags":
pass
return queryset
</code></pre>
<p>as you can see i have a condition regarding <code>ordering == tags</code> , I want to perform the sorting inside the condition. Now i created also a raw query that will suite my needs but i don't know how to execute it on <code>drf</code> side:</p>
<pre><code>select
*
from
users_data ud
left join users_data_tags udt on
ud.id = udt.data_id
left join users_tag ut on
udt.tag_id = ut.id
where ud.user_id = 1
order by ut."name"
</code></pre>
|
<python><python-3.x><django><sorting><django-rest-framework>
|
2024-05-05 14:22:47
| 0
| 1,859
|
Jc John
|
78,432,498
| 172,677
|
How to avoid the joblib's parallel open many files?
|
<p>EDIT: I have <a href="https://github.com/joblib/joblib/issues/1581" rel="nofollow noreferrer">submit a issue on github</a>, in that version I remove the <code>user</code> limit in <code>lsof</code>, and the opened files are much more.</p>
<p>A simplified case as following(Python 3.11.8, joblib 1.4.0):</p>
<pre><code>## lsof.py
from joblib import Parallel, delayed
import time
import sys
def f():
time.sleep(5)
return 1.0
def get_num_of_opened_files() -> int:
from subprocess import run
return int(run('lsof -u eastsun| wc -l', shell=True, capture_output=True, text=True).stdout.strip())
f0 = get_num_of_opened_files()
xs = Parallel(n_jobs=32, return_as='generator')(delayed(f)() for _ in range(32))
time.sleep(2)
f1 = get_num_of_opened_files()
print(f'Opened files: before {f0}, after {f1}, delta: {f1 - f0}', flush=True)
print(sum(xs))
</code></pre>
<p>Run the above py script will show that the joblib has opened about <strong>3200 files</strong> when it is running.</p>
<pre><code> >> python lsof.py
>> Opened files: before 388, after 3647, delta: 3259
</code></pre>
<p>It become even worse if I change the function <code>f</code> to a method of an instance with some attributes:</p>
<pre><code>## lsof2.py
from joblib import Parallel, delayed
import time
import sys
import pandas as pd
class Tasker:
def __init__(self):
self.data = pd.Series([])
def run(self):
time.sleep(10)
return 1.0
def get_num_of_opened_files() -> int:
from subprocess import run
return int(run('lsof -u eastsun| wc -l', shell=True, capture_output=True, text=True).stdout.strip())
tasker = Tasker()
f0 = get_num_of_opened_files()
xs = Parallel(n_jobs=32, return_as='generator')(delayed(tasker.run)() for _ in range(32))
time.sleep(2)
f1 = get_num_of_opened_files()
print(f'Opened files: before {f0}, after {f1}, delta: {f1 - f0}', flush=True)
print(sum(xs))
</code></pre>
<p>The opened files has doubled:</p>
<pre><code> >> python lsof2.py
>> Opened files: before 399, after 6794, delta: 6395
</code></pre>
<p>It would open about 60,000 files If I running 10 programs like this, and the joblib will claim that:</p>
<blockquote>
<p>UserWarning: A worker stopped while some jobs were given to the
executor. This can be caused by a too short worker timeout or by a
memory leak.</p>
</blockquote>
<p><strong>How to decrease the opened files by joblib?</strong> I have confirmed that:</p>
<ol>
<li>The opened files will decreased to about 4 if I add <code>prefer='threads'</code> in <code>Parallel</code>. However I do need multi-processing rather than multi-threading.</li>
<li>Change the <code>return_as</code> parameter from <code>generator</code> to <code>list</code> has no effect.</li>
<li><strong>About 60% of the opened files are .so file</strong>, which confused me very much.</li>
</ol>
|
<python><concurrency><parallel-processing><joblib>
|
2024-05-05 14:10:48
| 0
| 18,929
|
Eastsun
|
78,432,398
| 988,125
|
Keras NLP finetuning dataset incompatibility
|
<p>I am running a python 3.11 instance on Google Colab to finetune a GPT-2 model. I install <code>keras-nlp</code> as follows, and my package versions become:</p>
<pre><code>!pip install keras_nlp
print(tf.__version__)
print(keras.__version__)
print(keras_nlp.__version__)
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
>>2.16.1
>>3.3.3
>>0.11.1
>>1
</code></pre>
<p>Below I prepared a minimally reproducible example that generates the error I get. By the way,the below code runs OK if I set up the environment as follows (from the <a href="https://colab.research.google.com/github/tensorflow/codelabs/blob/main/KerasNLP/io2023_workshop.ipynb" rel="nofollow noreferrer">original Google colab notebook</a>), the problem with this version is that it does not recognise the GPU:</p>
<pre><code>!pip install -q git+https://github.com/keras-team/keras-nlp.git@google-io-2023 tensorflow-text==2.12
print(tf.__version__)
print(keras.__version__)
print(keras_nlp.__version__)
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
>>2.12.1
>>2.12.0
>>0.5.0
>>0
</code></pre>
<p>So, it is a version compatibility issue I believe. The top configuration (that recognises GPU) runs fine until model fitting, and then throws the error below .</p>
<pre><code>import numpy as np
import keras_nlp
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_text as tf_text
from tensorflow import keras
from tensorflow.lite.python import interpreter
import time
from google.colab import files
from google.colab import runtime
gpt2_tokenizer = keras_nlp.models.GPT2Tokenizer.from_preset("gpt2_base_en")
gpt2_preprocessor = keras_nlp.models.GPT2CausalLMPreprocessor.from_preset(
"gpt2_base_en",
sequence_length=512,
add_end_token=True,
)
gpt2_lm = keras_nlp.models.GPT2CausalLM.from_preset("gpt2_base_en", preprocessor=gpt2_preprocessor)
# Create dummy train data to highlight the error
training_list_manual = ['This is a sentence that I like', 'I went to school today.', 'I have a bike, you can ride it if you like.']
tf_train_ds = tf.data.Dataset.from_tensor_slices(training_list_manual)
processed_ds = tf_train_ds.map(gpt2_preprocessor, tf.data.AUTOTUNE).batch(64).cache().prefetch(tf.data.AUTOTUNE)
# Attempt fine-tune
gpt2_lm.include_preprocessing = False
num_epochs = 1
lr = tf.keras.optimizers.schedules.PolynomialDecay(
5e-5,
decay_steps=part_of_ds.cardinality() * num_epochs,
end_learning_rate=0.0,
)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
gpt2_lm.compile(
optimizer=keras.optimizers.Adam(lr),
loss=loss,
weighted_metrics=["accuracy"])
gpt2_lm.fit(processed_ds, epochs=num_epochs)
</code></pre>
<p>In the final .fit() line, I get the below Value error. I understand it does not like the 'x' value I try to input. However I am at a loss as to what to replace it with. Any ideas?</p>
<pre><code>ValueError: Exception encountered when calling GPT2CausalLMPreprocessor.call().
Unsupported input for `x`. `x` should be a string, a list of strings, or a list of tensors. If passing multiple segments which should packed together, please convert your inputs to a list of tensors. Received `x={'token_ids': <tf.Tensor 'args_1:0' shape=(None, None, 1024) dtype=int32>, 'padding_mask': <tf.Tensor 'args_0:0' shape=(None, None, 1024) dtype=bool>}`
Arguments received by GPT2CausalLMPreprocessor.call():
β’ x={'token_ids': 'tf.Tensor(shape=(None, None, 1024), dtype=int32)', 'padding_mask': 'tf.Tensor(shape=(None, None, 1024), dtype=bool)'}
β’ y=tf.Tensor(shape=(None, None, 1024), dtype=int32)
β’ sample_weight=tf.Tensor(shape=(None, None, 1024), dtype=bool)
β’ sequence_length=None
</code></pre>
<p>The content of one data item looks as below. Does it expect me to only feed in the "token_ids" values to .fit()?</p>
<pre><code>for example in tf_train_ds.take(1):
print(gpt2_preprocessor(example))
({'token_ids': <tf.Tensor: shape=(1, 1024), dtype=int32, numpy=array([[50256, 1212, 318, ..., 0, 0, 0]], dtype=int32)>, 'padding_mask': <tf.Tensor: shape=(1, 1024), dtype=bool, numpy=array([[ True, True, True, ..., False, False, False]])>}, <tf.Tensor: shape=(1, 1024), dtype=int32, numpy=array([[1212, 318, 257, ..., 0, 0, 0]], dtype=int32)>, <tf.Tensor: shape=(1, 1024), dtype=bool, numpy=array([[ True, True, True, ..., False, False, False]])>)
</code></pre>
|
<python><tensorflow><keras><keras-nlp>
|
2024-05-05 13:39:31
| 1
| 11,996
|
Zhubarb
|
78,432,348
| 424,957
|
How to match video duration with music's duration?
|
<p>I have a video file and music files, I want to match the video duration with multiple musics in min diff = ideo duration, sum of musics duraion. I use code as below, but it looks like not all answers, what can I get all combination? do I have to use recursionοΌ</p>
<pre><code>musicList = [music filename list
timeList = [music file duraion list]]
tList = []
mList = []
dList = []
for i, (m1, t1) in enumerate(zip(musicList, timeList)):
if t1 > videoTime:
continue
time1 = t1
music1 = m1
for j in range(i + 1, len(musicList) - 1):
time2 = time1
music2 = music1
for m2, t2 in zip(musicList[j:], timeList[j:]):
if t2 > videoTime or time2 + t2 > videoTime:
continue
time = max(time2, t2, time2 + t2)
music2 = music2 if time == time2 else m2 if time == t2 else f'{music2}+{m2}'
time2 = time
mList.append(music2)
tList.append(time2)
dList.append(videoTime - time2)
</code></pre>
|
<python><recursion>
|
2024-05-05 13:23:59
| 0
| 2,509
|
mikezang
|
78,432,208
| 774,575
|
How to reverse axes when plotting a Series?
|
<p>How to swap x and y axes when plotting a time Series? Either by manipulating the Series or with <code>Series.plot()</code>. I know it's possible for a DataFrame, by plotting its <code>transpose</code>.</p>
<pre><code>import pandas as pd
import numpy.random as npr
def rand_data(n=5):
return npr.choice([1,5,6,8,9], size=n)
npr.seed(0)
n = 8
index = pd.date_range('2013/01/31 09:10:12', periods=n, freq='ME')
s = pd.Series(index=index, data=rand_data(n))
s.plot()
</code></pre>
<p><a href="https://i.sstatic.net/yrrbwdR0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yrrbwdR0.png" alt="enter image description here" /></a></p>
|
<python><pandas><matplotlib><series>
|
2024-05-05 12:34:49
| 1
| 7,768
|
mins
|
78,432,150
| 13,392,257
|
AttributeError: 'Depends' object has no attribute 'add'
|
<p>I am trying to use database session in the middleware (to write metrics to the database)</p>
<p>I am using <code>fastapi.params.Depends</code> in <code>@app.middleware("http")</code></p>
<p>I read this question <a href="https://stackoverflow.com/questions/72243379/fastapi-dependency-inside-middleware">FastAPI - dependency inside Middleware?</a> and was using solution from this question</p>
<p>My code:</p>
<p><strong>database.py</strong></p>
<pre><code>from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "postgresql://username@localhost/feast_db" # Checked that psql postgresql://username@localhost/feast_db is working
engine = create_engine(
SQLALCHEMY_DATABASE_URL
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
</code></pre>
<p>Main app:</p>
<pre><code>from fastapi import FastAPI, HTTPException, Request, Response, status
from fastapi.params import Depends
from myapp.metrics_service import models, schemas
from myapp.metrics_service.database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine) # create database table
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_app(store: "feast.FeatureStore"):
proto_json.patch()
app = FastAPI(dependencies=[Depends(get_db)])
request_id_contextvar = contextvars.ContextVar("request_id", default=None)
...
@app.middleware("http")
async def log_requests(request: Request, call_next, db: Session = Depends(get_db)):
response = await call_next(request)
...
curr_metric = models.Metric(rqid=request_id, name="request_duration", duration_ms=total_time_ms)
print("XXX_ curr_metric")
db.session.add(curr_metric)
db.session.commit()
return response
</code></pre>
<p>I have an error</p>
<pre><code>db.add(curr_metric)
AttributeError: 'Depends' object has no attribute 'add'
</code></pre>
<p>How to fix the error?</p>
|
<python><fastapi>
|
2024-05-05 12:16:07
| 2
| 1,708
|
mascai
|
78,431,835
| 8,543,025
|
Plotly Heatmap has Limit on Data Size
|
<p>Iβm trying to create a (very) large heatmap using <code>plotly</code>. My dataset is of shape <code>(10, 85000)</code>, and I noticed that I canβt display heatmaps when the row size is greater than 65k:</p>
<pre><code>row_size = 65000 # change this to 66000 and the figure is displayed empty
z = np.random.randint(0, 101, size=(10, row_size))
heatmap = go.Heatmap(z=z,
colorbar=dict(
thickness=25,
))
fig = go.Figure(data=[heatmap])
fig.update_layout(width=1500, height=500)
fig.show()
</code></pre>
<p>Is there a way to increase this limit?</p>
|
<python><python-3.x><plotly><heatmap>
|
2024-05-05 10:36:28
| 1
| 593
|
Jon Nir
|
78,431,743
| 1,832,767
|
Make mypy to understand, that the attribute is not None
|
<p>quick description of my environment:</p>
<pre><code>- django 4.2.11
- mypy 1.9.0
- django-stubs 4.2.5
</code></pre>
<p>Here is a synthetic example I made bellow, just for that post, please don't judge me for the meaning of names, etc. The point is how to handle the mypy error...</p>
<p>I have two models, one refers to another via ForeignKey:</p>
<pre><code>class Author(models.Model):
name = models.CharField()
class Book(models.Model):
author = models.ForeignKey(Author, blank=False, null=True, ...)
</code></pre>
<p>then I have a set of similar functions, for each of them there is a rule: we check, that author is not None, if it is - then raise an error: ImproperlyConfigured:</p>
<pre><code>def _check_configuration(book: Book) -> None:
if not book.author:
raise ImproperlyConfigured()
def func1(book: Book) -> int:
_check_configuration(book)
....
author_name = book.author.name # here it comes...
def func2(book: Book) -> str:
_check_configuration(book)
....
</code></pre>
<p>For DRY purpose, I use validation function. If I put <code>if book.author is None...</code> right into the func1 - then the error disappears.</p>
<p>Here is the error:</p>
<pre><code>error: ... "Author | None" has no attribute "name" [union-attr]
</code></pre>
<p>How to explain to mypy that the author is not None for sure?</p>
<p>Thanks!</p>
<p>ChatGPT and Googling. ChatGPT returns stupid advices about that problem and for Google, I even can't formulate the request, everything i've tried - guides me to another problems...</p>
|
<python><django-models><mypy><python-typing>
|
2024-05-05 09:58:00
| 1
| 449
|
AntonTitov
|
78,431,432
| 8,024,622
|
Reading zipped csv and adding new lines
|
<p>I have a zip file t.zip containing two csv files. The first one is s.csv (30kB) and the other is p.csv (60GB).</p>
<p>What I'm doing now is unzipping p.csv to the disk, reading the second last line, doing some logic and then adding new lines to p.csv. After that I'm zipping the file again.</p>
<p>Is there a better way to do this? Somithing without unzipping to disk an zipping again?</p>
<p>I'm using Python 3.12 and Pandas.</p>
<p>Thanks a lot!</p>
|
<python><pandas><zip><python-zipfile>
|
2024-05-05 07:52:54
| 1
| 624
|
jigga
|
78,431,171
| 14,244,880
|
Python list.remove() internals
|
<p>How does python <code>list.remove()</code> work internally?</p>
<p>For example, when adding to Java sets, Java compares both <code>hash()</code> and <code>equals()</code> methods. Does python compare the <code>__eq__()</code> method or something else?</p>
<p>Alternatively, does the implementation vary? If so, what is the implementation for CPython, or Anaconda Python (presumably CPython)?</p>
|
<python><list>
|
2024-05-05 05:38:23
| 1
| 306
|
z.x.99
|
78,430,960
| 7,674,262
|
presidio transformers package not available, despite being installed
|
<p>I'm trying to run the example code on <a href="https://microsoft.github.io/presidio/analyzer/nlp_engines/transformers/" rel="nofollow noreferrer">this</a> Microsoft documentation, but I am presented with a package not found error. I'm on a MAC and my friend had the same problem on his machine too. I'm sure that a I have installed the transformers package. I imported with no error. I'm on a virtual environment, on a jupyter notebook on vs code.</p>
<p>If I remove the <strong>config.yaml</strong> file, it runs with no errors, so maybe is something that's in it. But is kinda the same version that is on documentation.</p>
<p>Code:</p>
<pre><code>from presidio_analyzer import AnalyzerEngine, RecognizerRegistry
from presidio_analyzer.nlp_engine import NlpEngineProvider
conf_file = 'config.yaml'
provider = NlpEngineProvider(conf_file=conf_file)
nlp_engine = provider.create_engine()
analyzer = AnalyzerEngine(
nlp_engine=nlp_engine,
supported_languages=["en"]
)
results_english = analyzer.analyze(text="My name is Morris", language="en")
print(results_english)
</code></pre>
<p>Error stack:</p>
<pre><code>ValueError Traceback (most recent call last)
Cell In[3], line 6
4 # Create NLP engine based on configuration
5 provider = NlpEngineProvider(conf_file=conf_file)
----> 6 nlp_engine = provider.create_engine()
8 # Pass the created NLP engine and supported_languages to the AnalyzerEngine
9 analyzer = AnalyzerEngine(
10 nlp_engine=nlp_engine,
11 supported_languages=["en"]
12 )
File ~/Projects/pii/lib/python3.12/site-packages/presidio_analyzer/nlp_engine/nlp_engine_provider.py:81, in NlpEngineProvider.create_engine(self)
79 nlp_engine_name = self.nlp_configuration["nlp_engine_name"]
80 if nlp_engine_name not in self.nlp_engines:
---> 81 raise ValueError(
82 f"NLP engine '{nlp_engine_name}' is not available. "
83 "Make sure you have all required packages installed"
84 )
85 try:
86 nlp_engine_class = self.nlp_engines[nlp_engine_name]
ValueError: NLP engine 'transformers' is not available. Make sure you have all required packages installed
</code></pre>
<p>My config.yaml:</p>
<pre><code>nlp_engine_name: transformers
models:
-
lang_code: en
model_name:
spacy: en_core_web_sm
transformers: StanfordAIMI/stanford-deidentifier-base
ner_model_configuration:
labels_to_ignore:
- O
aggregation_strategy: simple # "simple", "first", "average", "max"
stride: 16
alignment_mode: strict # "strict", "contract", "expand"
model_to_presidio_entity_mapping:
PER: PERSON
LOC: LOCATION
EMAIL: EMAIL
PHONE: PHONE_NUMBER
low_confidence_score_multiplier: 0.4
low_score_entity_names:
- ID
</code></pre>
|
<python><huggingface-transformers><pii><presidio>
|
2024-05-05 03:27:58
| 1
| 442
|
NeoFahrenheit
|
78,430,938
| 6,077,239
|
How to partition a big Polars dataframe and save each one in parallel to a CSV file?
|
<p>I have a big <code>Polars</code> dataframe with a lot of groups. Now, I want to partition the dataframe by group and save all sub-dataframes. I can easily do this as follows:</p>
<pre class="lang-py prettyprint-override"><code>for d in df.partition_by(["group1", "group2"]):
d.write_csv(f"~/{d[0, 'group1']}_{d[0, 'group2']}.csv")
</code></pre>
<p>However, the approach above is sequential and slow when the <code>df</code> is very large and has a whole lot of partitions.</p>
<p>Is there any <code>Polars</code> native way to parallelize it (the code section above)?</p>
<p>If not, how can I do it in a <code>Python</code> native way instead?</p>
|
<python><dataframe><csv><partitioning><python-polars>
|
2024-05-05 03:15:58
| 3
| 1,153
|
lebesgue
|
78,430,760
| 13,461,081
|
Python - Kalman Filter (Unscented) not working corretly
|
<p>I am trying to implement a Kalman Filter which is used to filter calculated values of Speed, Heading, Acceleration and Yaw Rate. I also use the Kalman Filter to predict future values and use those to calculate future geographical positions of an object.</p>
<p>It seems that the Filter is resetting the predicted values to 0. Currently, my next state update is always maintained (nv = v, na = a, etc..), but if I change to <code>nv = v + a * dt</code> I get similar behaviour, values are very close to zero (~ e-14).</p>
<p>Main code:</p>
<pre class="lang-py prettyprint-override"><code># Initialize or retrieve the UKF instance
ukf = get_ukf(station_id)
# Update UKF with current raw measurements
ukf.update([speed, heading, acceleration, yaw_rate])
new_predictions = predict_future_positions(
station_id,
data[station_id].at[curr_index, 'latitude'],
data[station_id].at[curr_index, 'longitude']
)
</code></pre>
<p>Prediction code:</p>
<pre class="lang-py prettyprint-override"><code>def fx(state, dt):
""" Predict next state based on simple motion model assumptions """
v, theta, a, psi_dot = state
nv = v
ntheta = theta # Assuming constant heading for simplicity
na = a # Assuming constant acceleration for simplicity
npsi_dot = psi_dot # Assuming constant yaw rate for simplicity
return np.array([nv, ntheta, na, npsi_dot])
def hx(state):
""" Measurement function returns the state itself, assumes you measure all states directly """
return state
def initialize_ukf():
""" Initialize and return a UKF for tracking speed, heading, acceleration, and yaw rate """
sigmas = MerweScaledSigmaPoints(n=4, alpha=0.1, beta=2., kappa=1.)
ukf = UKF(dim_x=4, dim_z=4, fx=fx, hx=hx, dt=1/30 , points=sigmas)
ukf.x = np.array([0., 0., 0., 0.]) # initial state [speed, heading, acceleration, yaw_rate]
ukf.P *= 10 # initial covariance
ukf.R = np.eye(4) * 0.1 # measurement noise
ukf.Q = np.eye(4) * 0.1 # process noise
return ukf
def get_ukf(station_id):
""" Retrieve or initialize a UKF for a specific station_id """
if station_id not in ukfs:
ukfs[station_id] = initialize_ukf()
return ukfs[station_id]
def calculate_next_position(lat: float, lon: float, speed: float, heading: float, acceleration: float, interval) -> tuple:
# Convert latitude, longitude and heading from degrees to radians
lat_rad, lon_rad, heading_rad = map(math.radians, [lat, lon, heading])
# Distance covered in the interval with the updated speed
distance = speed * interval + 0.5 * acceleration * interval ** 2
# Calculate new latitude and longitude in radians
new_lat_rad = math.asin(math.sin(lat_rad) * math.cos(distance / EARTH_RADIUS) +
math.cos(lat_rad) * math.sin(distance / EARTH_RADIUS) * math.cos(heading_rad))
new_lon_rad = lon_rad + math.atan2(math.sin(heading_rad) * math.sin(distance / EARTH_RADIUS) * math.cos(lat_rad),
math.cos(distance / EARTH_RADIUS) - math.sin(lat_rad) * math.sin(new_lat_rad))
# Convert new latitude and longitude from radians to degrees
new_lat, new_lon = map(math.degrees, [new_lat_rad, new_lon_rad])
return new_lat, new_lon
# def predict_future_positions(lat, lon, speed, heading, acceleration, curve_info, frequency=30, duration=5) -> list:
def predict_future_positions(station_id, lat, lon, frequency=30, duration=5) -> list:
predicted_positions = []
# Calculate the number of points and the duration of each interval
points = frequency * duration
interval_duration = 1 / frequency
ukf = get_ukf(station_id)
ukf.dt = interval_duration # Set UKF's dt to the interval duration
print(f"interval_duration: {ukf.dt}")
for i in range(1, points + 1):
# Predict the next state using the UKF for the current interval
ukf.predict()
new_speed, new_heading, new_acceleration, new_yaw_rate = ukf.x
print(f"Predicted: {new_speed}, {new_heading}, {new_acceleration}, {new_yaw_rate}")
new_lat, new_lon = calculate_next_position(lat, lon, new_speed, new_heading, new_acceleration, interval_duration)
predicted_positions.append({'lat': new_lat, 'lon': new_lon})
lat, lon = new_lat, new_lon
return predicted_positions
</code></pre>
<p>My output:</p>
<pre class="lang-bash prettyprint-override"><code>Speed: 10.254806246670183, Heading: 319.27693339350554, Acceleration: -0.23540827984615223, Yaw rate: -0.005145571837527121
interval_duration: 0.03333333333333333
Predicted: 10.166326468873194, 316.5221712417051, -0.2333771471468742, -0.005145058097190569
Predicted: 10.166326468873166, 316.52217124170784, -0.2333771471468764, -0.005145058097190472
...
Speed: 10.467646761934825, Heading: 319.23780992232264, Acceleration: 0.21254958566790286, Yaw rate: -0.03906999369681518
interval_duration: 0.03333333333333333
Predicted: 10.449913038293573, 319.0779853536578, 0.18630528143125535, -0.03707439752961145
Predicted: 10.449913038293431, 319.0779853536569, 0.1863052814312549, -0.037074397529612
...
Prediction accuracy: 0.10094114807863384 meters
Speed: 10.189528933971618, Heading: 319.25287353184626, Acceleration: -0.2778124154209819, Yaw rate: 0.015047067558968702
Predicted: 10.204898856119058, 319.2425502531232, -0.2504165308446913, 0.011970453237527212
Predicted: 10.204898856119286, 319.2425502531214, -0.25041653084469173, 0.011970453237527268
...
Prediction accuracy: 0.808794667925268 meters
Speed: 10.413539616314386, Heading: 322.54565576546065, Acceleration: 0.22384171917679088, Yaw rate: 3.2902986069174447
Predicted: 10.401223867329037, 322.3506784353949, 0.19584697089942216, 3.0967838480884247
Predicted: 10.401223867329037, 322.3506784353949, 0.19584697089942038, 3.0967838480884033
Predicted: 10.401223867329037, 322.3506784353949, 0.19584697089941927, 3.0967838480884176
...
Prediction accuracy: 0.5443148460430843 meters
Speed: 10.539412327559626, Heading: 323.6073064276114, Acceleration: 0.12570394929129958, Yaw rate: 1.0602272699128528
Predicted: 0.0, 0.0, 0.0, 0.0
Predicted: 0.0, 0.0, 0.0, 0.0
...
Prediction accuracy: 10.36880732693119 meters
Speed: 10.361936129429777, Heading: 335.33964303577073, Acceleration: -0.17724217428198916, Yaw rate: 11.71686610233176
...
</code></pre>
|
<python><prediction><kalman-filter><motion><pykalman>
|
2024-05-05 00:54:51
| 1
| 916
|
AndrΓ© ClΓ©rigo
|
78,430,651
| 3,103,957
|
Setting up path to find packages and modules
|
<p>I have the follwing folder structure of my Python project:
Project is the base directory.</p>
<pre><code>Project
|------package1
| |--------module1.py
| |--------module2.py
|------package2
| |--------module3.py
| |--------module4.py
|------Test
| |-----test.py
</code></pre>
<p>The contents of <code>test.py</code> is:</p>
<pre><code>import package1.module1
</code></pre>
<p>When I run test.py, the below error is thrown:</p>
<pre><code>ModuleNotFoundError: No module named 'package1'
</code></pre>
<p>I am aware that the package/module search would contain the directory where the script is run.
So in this case, package1 directory path is NOT included; hence the error is thrown.
Adding the path of package1 via sys.path.append() is not a nicer way whenever we do imports.</p>
<p>I see that many projects import modules/packages in the above mentioned way only.
I am wondering how they work actually.</p>
<p>can I get some guidance on how to make the above setup work.</p>
<p>Thanks</p>
|
<python><import>
|
2024-05-04 23:36:07
| 0
| 878
|
user3103957
|
78,430,560
| 9,256,321
|
Julia: PCRE.exec error: match limit exceeded when using Regex
|
<p>I'm trying to apply a rather complex regex to a large string in Julia. For reproducibility, the string is:</p>
<pre><code>A = "6666666666666666666666666666611111122222221222222222222222222233361222222222233232336611116111112212211666666666666666666666666666666666111111111121122221222122122222222222222222222222222112222122222222222222222222222222333333332112661222122222222222222222222222222222222222222222222555555555555555555555555555555555555555555555522222222222222222222122222222222333261222222222222222222223333331222222222222222222222222222222222222222222222222222222222222222222222222222222222622222222222222222222222222222233333312222222222612222222222222122255555555555555555555555555555555555555555555555555555555522222222222222222222223332122233222333333333333333333333333333333611112222211222222222222222222222222222222212222222222222212221111225555555555555555555555555555551222222222222222222212221121122212222222222222222222222222221222222222222222555555555555555155555555555155555555555555555555555555555555555555111111222222222212222222222222222222222222222222222122221222222222222222222222221212222222222222225555555555555555555555555511555555555222222222222212222222212222222222222222222222222266"
</code></pre>
<p>The regex in question is <code>pattern_fl = Regex("(?:[234](1*|6*|5*)){$n,}(?:5|6{$m,}|\$)")</code>. This regex is supposed to capture sequences of <code>2</code>,<code>3</code>,<code>4</code> that</p>
<ul>
<li>(1) May contain 1s, 6s or 5s in between</li>
<li>(2) Have a length of <code>>= n</code> where <code>n</code> is a variable set to <code>30</code>, but any 1s, 5s or 6s should not contribue to the count.</li>
<li>(3) End with a single <code>5</code> or with <code>>=m</code> repetitions of 6, where <code>m=10</code> is a variable.</li>
</ul>
<p>Code for reproduction:</p>
<pre><code>A = "6666666666666666666666666666611111122222221222222222222222222233361222222222233232336611116111112212211666666666666666666666666666666666111111111121122221222122122222222222222222222222222112222122222222222222222222222222333333332112661222122222222222222222222222222222222222222222222555555555555555555555555555555555555555555555522222222222222222222122222222222333261222222222222222222223333331222222222222222222222222222222222222222222222222222222222222222222222222222222222622222222222222222222222222222233333312222222222612222222222222122255555555555555555555555555555555555555555555555555555555522222222222222222222223332122233222333333333333333333333333333333611112222211222222222222222222222222222222212222222222222212221111225555555555555555555555555555551222222222222222222212221121122212222222222222222222222222221222222222222222555555555555555155555555555155555555555555555555555555555555555555111111222222222212222222222222222222222222222222222122221222222222222222222222221212222222222222225555555555555555555555555511555555555222222222222212222222212222222222222222222222222266"
n = 30
m = 10
pattern_fl = Regex("(?:[234](1*|6*|5*)){$n,}(?:5|6{$m,}|\$)")
x = eachmatch(pattern_fl, A)
for match in x
print(match.match)
end
</code></pre>
<p>The expected output is to have each regex match printed. The actual output is</p>
<pre><code>PCRE.exec error: match limit exceeded
Stacktrace:
[1] error(s::String)
@ Base ./error.jl:35
[2] exec(re::Ptr{Nothing}, subject::String, offset::Int64, options::UInt32, match_data::Ptr{Nothing})
@ Base.PCRE ./pcre.jl:197
[3] exec_r_data
@ ./pcre.jl:210 [inlined]
[4] match(re::Regex, str::String, idx::Int64, add_opts::UInt32)
@ Base ./regex.jl:385
[5] iterate
@ ./regex.jl:703 [inlined]
[6] iterate(itr::Base.RegexMatchIterator)
@ Base ./regex.jl:701
[7] top-level scope
@ ./In[458]:13
</code></pre>
<p>I gather that my regex expression is too flexible and its search tree produces some kind of overflow? A direct approach would be to find an equivalent, yet more concise regular expression. However, as you can see, I'm looking for a rather flexible set of matches, and I wasn't able to simplify the regex any further.</p>
<p>I have been struggling with producing this regex a lot. At this point I'm open to solutions in other languages, particularly Python.</p>
|
<python><regex><julia>
|
2024-05-04 22:43:42
| 1
| 350
|
lafinur
|
78,430,553
| 8,010,064
|
Get second srcset attribute using Beautiful Soup
|
<p>I'm trying to get the second srcset attribute in beautiful Soup, the original html is as follows:</p>
<pre><code><picture class="card-picture ratio ratio-4x3">
<source srcset="/shop/media/L004D000_picture.PNG?context=bWFzdGVyfGltYWdlc3wzMDE3NTN8aW1hZ2UvcG5nfGgwMS9oMjcvODg0ODIyMDYxODc4Mi9MMDA0RDAwMF9waWN0dXJlLlBOR3wyZjRiZWE1NDU2MWU1MjUzMzU5MjAwNGVlYmIzY2MwNGQzODExMDI3NjNkMDE3YjQ4NGMwNjFlMGVkNTU2OWIy&amp;rmode=pad&amp;width=640&amp;rmode=pad&amp;width=640&amp;format=webp" type="image/webp"/>
<source srcset="/shop/media/L004D000_picture.PNG?context=bWFzdGVyfGltYWdlc3wzMDE3NTN8aW1hZ2UvcG5nfGgwMS9oMjcvODg0ODIyMDYxODc4Mi9MMDA0RDAwMF9waWN0dXJlLlBOR3wyZjRiZWE1NDU2MWU1MjUzMzU5MjAwNGVlYmIzY2MwNGQzODExMDI3NjNkMDE3YjQ4NGMwNjFlMGVkNTU2OWIy&amp;rmode=pad&amp;width=640&amp;rmode=pad&amp;width=640" type="image/jpeg"/>
<img alt="" class="card-img object-fit-contain is-contain" loading="lazy" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
</img>
</picture>
</code></pre>
<p>My code:</p>
<pre><code>for result in results:
imgel = result.find("source", attrs = {'srcset' : True})['srcset']
</code></pre>
<p>This returns the first srcset value _ I want to get the second value the png URL</p>
|
<python><beautifulsoup>
|
2024-05-04 22:40:35
| 1
| 312
|
buzz
|
78,430,525
| 8,484,261
|
Pandas pivot sum using groupy not working due to a datetime column
|
<p>I am trying to sum the values in multiple columns of a pandas dataframe pivot based on the values in the 'Category' columns. However, I am getting an error becasue of a datee column in the pivot table.
How do I sum all the pivoted monthly columns by Category?</p>
<p>Executable code:</p>
<pre><code># test groupbysum
import pandas as pd
import numpy as np
df = pd.DataFrame({
'JDate':["2022-01-31","2022-12-05","2023-11-10","2023-12-03","2024-01-16","2024-01-06","2011-01-04"],
# 'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy','George Lucas'],
'Unit Price':[np.nan,200,None,56,75,65,60],
'Quantity':[1500, 140000, 1400000, 455, 648, 759,1000],
'Amount':[100, 10000, 100000, 5, 48, 59,449],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey','football'],
'energy':[100.,100,100,54,98,3,45],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo','kappa']
})
df["JDate"] = pd.to_datetime(df["JDate"])
df["JYearMonth"] = df['JDate'].dt.to_period('M')
index_to_use = ['Category','Code','Invoice','Unit Price','JDate']
values_to_use = ['Amount']
columns_to_use = ['JYearMonth']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
df2 = df2['Amount'].reset_index()
df2_sum = df2.groupby('Category').sum()
writer= pd.ExcelWriter(
"t2test18.xlsx",
engine='xlsxwriter'
)
df.to_excel(writer,sheet_name="t2",index=True)
df2.to_excel(writer,sheet_name="t2test",index=True)
df2_sum.to_excel(writer,sheet_name="t2testsum",index=True)
workbook = writer.book
worksheet = writer.sheets["t2"]
fmt_header = workbook.add_format({
'bold':True,
'text_wrap':True,
'valign':'top',
'fg_color': '#5DADE2',
'font_color':'#2659D9',
'border':1
})
writer.close()
</code></pre>
|
<python><pandas><dataframe>
|
2024-05-04 22:14:06
| 1
| 3,700
|
Alhpa Delta
|
78,430,389
| 3,048,453
|
Make sense of decompressed xref data from PDF
|
<p>I try to read in a PDF in binary format and parse its information.
I can parse most objects, including using <code>zlib</code> to decompress FlateDecoded data.</p>
<p>But when I try to parse the compressed xref data, I cannot make sense of the decompressed data.</p>
<p>I am using this <a href="https://cran.r-project.org/web/packages/dplyr/dplyr.pdf" rel="nofollow noreferrer">pdf</a> as a test.
The xref starts at 343543, where the PDF object starts with a length of 5906 using /Filter /FlateDecode.
When I decompress the stream, I get the following values (shown are only the first 100, total length is 12625): <code>b'\x00\x00\x00\x00\xff\x02\x00\x00\x02\x00\x01\x00\x00\x0f\x00\x02\x00\x01\x98\x0c\x02\x00\t;\x10\x02\x00\x00\x02\x01\x02\x00\x00\x02\x02\x02\x00\x01\x98-\x02\x00\t;\x0f\x02\x00\x00\x02\x03\x02\x00\x00\x02\x04\x02\x00\x01\x98>\x02\x00\t;\x0e\x02\x00\x00\x02\x05\x02\x00\x00\x02\x06\x02\x00\x01\x98V\x02\x00\t;\r\x02\x00\x00\x02\x07\x02\x00\x00\x02\x08\x02\x00\x01\x98['</code></p>
<p>I have used <a href="https://www.mankier.com/1/mutool" rel="nofollow noreferrer">mutool</a> to clean the pdf, where I see the cleaned and decompressed xref as a benchmark as</p>
<pre><code>xref
0 2525
0000000002 00256 f
0000000016 00000 n
0000000203 00001 f
0000000069 00000 n
0000000134 00000 n
0000000215 00000 n
0000000262 00000 n
0000000321 00000 n
</code></pre>
<h2>MWE</h2>
<p>To replicate the values, I use this python code</p>
<pre><code>import zlib
file = "pdf/dplyr.pdf"
with open(file, "rb") as f:
data = f.read()
xref_text = data[slice(343543, 349686)]
stream = xref_text[slice(220, 6127)]
stream = zlib.decompress(stream)
stream[:100]
</code></pre>
<p>and <code>mutool clean -d dplyr.pdf dplyr_clean.pdf</code> and then in line 37521ff I see the parsed xref data as shown above.</p>
|
<python><pdf>
|
2024-05-04 21:05:12
| 1
| 10,533
|
David
|
78,430,312
| 1,973,920
|
How to get pyparsing to match "1 day" or "2 days" but fail "1 days" and "2 day"?
|
<p>I'm trying to match a sentence fragment of the form "after 3 days" or "after 1 month". I want to be particular with the single and plural forms, so "1 day" is valid but "1 days" is not.</p>
<p>I have the following code which is nearly there but the first two entries in the failure tests don't fail. Any suggestions please that use syntactical notation as I'd like, if possible, to avoid a set_parse_action() that checks the numeric value against the unit's plurality.</p>
<pre><code>from pyparsing import *
units = Keyword('days') ^ Keyword('months')
unit = Keyword('day') ^ Keyword('month')
single = Literal('1') + unit
multi = Word(nums) + units
after = Keyword('after') + ( single ^ multi )
a = after.run_tests('''
after 1 day
after 2 days
after 1 month
after 2 months
''')
print('=============')
b = after.run_tests('''
after 1 days
after 2 day
after 1day
after 2days
''', failure_tests = True)
print('Success tests', 'passed' if a[0] else 'failed')
print('Failure tests', 'passed' if b[0] else 'failed')
</code></pre>
|
<python><pyparsing>
|
2024-05-04 20:31:33
| 1
| 516
|
BruceH
|
78,430,188
| 2,537,486
|
Selecting from DataFrames with mixed dtypes MultiIndex columns returns data with wrong type
|
<p>I have DataFrames organized like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
columns=pd.MultiIndex.from_product([['Time','A','B'],[1,2]]),
index=[0,1,2],
data=[[0,1,2,3,4,5],[10,11,12,13,14,15],[20,21,22,23,24,25]],
dtype=float)
</code></pre>
<p>Now I want to select all of the 'B' columns and their respective level 1 column index for a given row index. One way to to that is</p>
<pre><code>df.loc[2,'B']
</code></pre>
<p>And I get this:</p>
<pre><code>1 24.0
2 25.0
Name: 2, dtype: float64
</code></pre>
<p>So far, so good.</p>
<p>Now let's mix the datatypes in the DataFrame.</p>
<pre><code>import datetime
times = pd.date_range("2018-01-01", periods=3, freq="h").values
df[('Time',1)] = times
df[('Time',2)] = times
df = df.sort_index(level=1,axis=1)
</code></pre>
<p>Now my DataFrame has <code>datetime</code> objects in the 'Time' columns:</p>
<pre><code>df.dtypes
A 1 float64
B 1 float64
Time 1 datetime64[ns]
A 2 float64
B 2 float64
Time 2 datetime64[ns]
dtype: object
</code></pre>
<p>Now let's try the same selection as above:</p>
<pre><code>df.loc[2,'B']
</code></pre>
<p>But this time I get:</p>
<pre><code>1 24.0
2 25.0
Name: 2, dtype: object
</code></pre>
<p>That is, the <code>dtype</code> has been changed to <code>object</code>!
But wait, there's another way to select the data I want:</p>
<pre><code>df.loc[2,('B',slice(None))]
</code></pre>
<p>and this time I get:</p>
<pre><code>B 1 24.0
2 25.0
Name: 2, dtype: float64
</code></pre>
<p>which is the correct answer.
Why this difference? And why does it happen only when dtypes are mixed?</p>
|
<python><pandas>
|
2024-05-04 19:40:28
| 1
| 1,749
|
germ
|
78,430,078
| 8,484,261
|
Formatting excel output from pandas for font size, color etc for all sheets
|
<p>I am writing out multiple dataframes to a excel workbook. I want to change the default font to "century Gothic" and size to 9 and color to blue (font color 2659D9) for all the sheets.
I also want the numbers column to have an accounting format and the date columns to have yyyy-mm-dd format. I tried the code below, but it is not working.</p>
<p>Executable code below:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'JDate':["2022-01-31","2022-12-05","2023-11-10","2023-12-03","2024-01-16","2024-01-06","2011-01-04"],
# 'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy','George Lucas'],
'Unit Price':[np.nan,200,None,56,75,65,60],
'Quantity':[1500, 140000, 1400000, 455, 648, 759,1000],
'Amount':[100, 10000, 100000, 5, 48, 59,449],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey','football'],
'energy':[100.,100,100,54,98,3,45],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo','kappa']
})
df["JDate"] = pd.to_datetime(df["JDate"])
df["JYearMonth"] = df['JDate'].dt.to_period('M')
index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount']
columns_to_use = ['JYearMonth']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
df3 = df2.xs('alpha',level='Category')
df3 = df3.reset_index()
writer= pd.ExcelWriter(
"t2test13.xlsx",
engine='xlsxwriter'
)
df.to_excel(writer,sheet_name="t2",index=True)
df2.to_excel(writer,sheet_name="t2test",index=True)
df3.to_excel(writer,sheet_name="t2filter",index=True)
workbook = writer.book
worksheet = writer.sheets["t2"]
fmt_header = workbook.add_format({
'bold':True,
'text_wrap':True,
'valign':'top',
'fg_color': '#5DADE2',
'font_color':'#2659D9',
'border':1
})
writer.close()
</code></pre>
|
<python><pandas><excel><dataframe>
|
2024-05-04 18:53:33
| 1
| 3,700
|
Alhpa Delta
|
78,430,062
| 14,457,833
|
PyQt5 How to add a pyuic5 generated Python class into QStackedWidget?
|
<p>I've this in my <code>app.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>from PyQt5 import QtWidgets
from screens import Ui_home, Ui_login_page
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.home = Ui_home()
self.home.setupUi(self)
self.login = Ui_login_page()
self.login.setupUi(self)
self.screens = QtWidgets.QStackedWidget()
self.screens.addWidget(self.home)
self.screens.addWidget(self.login)
self.home.pushButton.clicked.connect(
lambda: self.screens.setCurrentWidget(self.login)
)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()
</code></pre>
<p>In above code, <code>Ui_home</code> & <code>Ui_login_page</code> screens are generated from a <code>*.ui</code> file which is generated from PyQt5 Designer. When I run this code, I get this error:</p>
<pre><code>self.screens.addWidget(self.home)
TypeError: addWidget(self, w: Optional[QWidget]): argument 1 has unexpected type 'Ui_home'
</code></pre>
<p>I know that <code>self.setCurrentWidget()</code> requires a <code>QWidget</code>, and the code generated from <code>pyuic5</code> inherits the class from Python <code>object</code>. How can I fix this so that my home and login screens can be added into the stack widget?</p>
|
<python><qt><pyqt><pyqt5><qt5>
|
2024-05-04 18:48:39
| 1
| 4,765
|
Ankit Tiwari
|
78,430,004
| 8,484,261
|
sorting python dataframe by values in a column based on a list
|
<p>I have a pandas dataframe which I am trying to sort on the basis of values in a column, but the sorting is not alphabetical. The sorting is based on a "sorter" list (i.e. a list which gives the order in which values should be sorted).
However, I am getting error when I do this.
executable code below:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'JDate':["2022-01-31","2022-12-05","2023-11-10","2023-12-03","2024-01-16","2024-01-06","2011-01-04"],
# 'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy','George Lucas'],
'Unit Price':[np.nan,200,None,56,75,65,60],
'Quantity':[1500, 140000, 1400000, 455, 648, 759,1000],
'Amount':[100, 10000, 100000, 5, 48, 59,449],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey','football'],
'energy':[100.,100,100,54,98,3,45],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo','kappa']
})
df["JDate"] = pd.to_datetime(df["JDate"])
df["JYearMonth"] = df['JDate'].dt.to_period('M')
index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount']
columns_to_use = ['JYearMonth']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
df4 = df2['Amount'].reset_index()
# setting up the sorter
sorter=['football','ice hockey','basketball','baseball']
#trying the categorical method
df4['Invoice'] = df['Invoice'].astype('Category').cat.set_categories(sorter)
df4.sort_values(['Invoice'],inplace=True)
df3 = df2.xs('alpha',level='Category')
df3 = df3.reset_index() #this prevents merging of rows
writer= pd.ExcelWriter(
"t2test11.xlsx",
engine='xlsxwriter'
)
df.to_excel(writer,sheet_name="t2",index=True)
df2.to_excel(writer,sheet_name="t2test",index=True)
df4.to_excel(writer,sheet_name="t2testFixHeader",index=True)
df3.to_excel(writer,sheet_name="t2filter",index=True)
writer.close()
</code></pre>
|
<python><pandas><dataframe><sorting><categorical-data>
|
2024-05-04 18:26:21
| 3
| 3,700
|
Alhpa Delta
|
78,429,935
| 2,697,895
|
How to get notified when a partition is mounted or unmounted in RPi OS and Python?
|
<p>I tried the following code and I am not getting any notification when mounting and unmounting partitions. Am I missing something ?</p>
<p>I use the library <code>pyinotify</code> to watch the changes in the file <code>/proc/mounts</code>... but it seems that my handler is never called...</p>
<pre><code>import pyinotify, time
# Define a callback function to handle file system events
class EventHandler(pyinotify.ProcessEvent):
def process_IN_MODIFY(self, event):
print(f"Change detected in {event.pathname}!")
# Create an inotify instance
wm = pyinotify.WatchManager()
# Create an event handler instance
handler = EventHandler()
# Create an inotify notifier and pass the function as the event handler
notifier = pyinotify.ThreadedNotifier(wm, handler)
# Watch for changes to /proc/mounts
wm.add_watch("/proc/mounts", pyinotify.IN_MODIFY)
# Start the notifier loop
print("Watching for mount changes...")
notifier.start()
try:
while True:
time.sleep(1)
except: pass
notifier.stop()
print('Done!')
</code></pre>
|
<python><raspberry-pi><pyinotify>
|
2024-05-04 17:59:52
| 1
| 3,182
|
Marus Gradinaru
|
78,429,919
| 51,816
|
How to reverse audio normalization using python?
|
<p>The application I used to export my edited audio was normalizing the audio which I don't want. I have the original audio that doesn't have normalization, and the new audio that has some parts shifted around to match video timing but is normalized by the application.</p>
<p>Is it possible to reverse the normalization using the original audio file? Technically it should be trivial to detect the peaks of each file to calculate the scaling factor, right?</p>
<p>This code should do that:</p>
<pre><code>def adjust_volume(original_path, normalized_path, output_path):
# Load the original and normalized audio
original_audio = AudioSegment.from_file(original_path)
normalized_audio = AudioSegment.from_file(normalized_path)
# Calculate the difference in dBFS
db_difference = original_audio.dBFS - normalized_audio.dBFS
# Adjust normalized audio
adjusted_audio = normalized_audio + db_difference
# Export the adjusted audio
adjusted_audio.export(output_path, format='wav')
</code></pre>
<p><a href="https://i.sstatic.net/WxEZUMHw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WxEZUMHw.png" alt="o = original, s = scaled" /></a></p>
<p>As you can see the top parts are aligned but the bottom parts do not. Is it because I need to scale above the center line using a different factor vs below the center line?</p>
<p><a href="https://i.sstatic.net/XYfdSCcg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XYfdSCcg.png" alt="So the audio looks like this. Top: edited and normalized, Bottom: original" /></a></p>
|
<python><numpy><audio><pydub><audacity>
|
2024-05-04 17:53:51
| 0
| 333,709
|
Joan Venge
|
78,429,819
| 5,896,591
|
python2.7 - How to decode JSON without decoding the UTF-8 inside of it?
|
<p>I need a function to decode UTF-8 encoded JSON. This function should take a UTF-8 encoded JSON string and convert it to UTF-8 encoded objects. The following code works:</p>
<pre><code># helper function
def Obj_To_UTF8(o):
res = {}
for k, v in o.items():
k = k.encode('utf-8')
v = v.encode('utf-8') if isinstance(v, unicode) else v
res[k] = v
return res
# Load UTF-8 encoded JSON to UTF-8 encoded objects
def Load_JSON(s):
return json.loads(s, object_hook = Obj_To_UTF8)
</code></pre>
<p>but is rather ridiculous, as <code>json.loads</code> is decoding the UTF-8 just so we can encode it again. How can I decode JSON without decoding the UTF-8 inside of it?</p>
<p><strong>Background</strong></p>
<p>I emphasize that the JSON is already UTF-8 encoded. This is important because I want to process the decoded JSON in exactly the same character encoding as the encoded JSON, using the same byte-based functions I use to process files, sockets, etc. Therefore, for best modularity, we should not bring <code>unicode</code>s into the program. (If we were changing the encoding or writing a text editor or font renderer, that would be the place to bring in <code>unicode</code>s. If we're not doing those things, then <code>unicode</code>s and the associated encoding/decoding are just a headache. Hopefully the example above illustrates this pretty well.)</p>
<p>For those unfamiliar with UTF-8, it is designed to support matching and tokenization directly on the bytes, specifically so that it is compatible with encoding-agnostic software (some of which is over 50 years old and still kicking). Languages like C and Python2 make it easy to process strings directly in bytes, and therefore avoid constantly encoding and decoding strings.</p>
<p>Unfortunately, <code>json.loads</code> seems to stray from these principles, for no obvious good reason. I can think of only two reasons why a JSON implementation would even care about character encoding:</p>
<ol>
<li>The <code>\u</code> feature, which is <em>optional</em> (and turned off by default in web browsers, so that they tend to emit UTF-8 sequences for non-ASCII characters).</li>
<li>Validating that the received string is proper UTF-8. Hopefully this pedantry would also be <em>optional</em>. (Apart from the UTF-8 fiat, JSON's actual delimiting scheme works perfectly well with binary data.)</li>
</ol>
<p>So <em>maybe</em> the JSON implementation cares about the character encoding, but forcing <em>all</em> JSON applications to deal with character encoding is poor modularity: rather than separating concerns, it unnecessarily ties JSON decoding to UTF-8 decoding. So a decent JSON implementation would at least provide a way to disable the UTF-8 decoding.</p>
|
<python><json><python-2.7><utf-8>
|
2024-05-04 17:15:59
| 1
| 4,630
|
personal_cloud
|
78,429,619
| 5,699,993
|
aws lambda function does not work when importing a function from a different file in a different folder
|
<p>I have the simplest possible Python function and I am able to deploy it as an AWS Lambda function.</p>
<p>The code of the function is this</p>
<p><strong>handler.py</strong></p>
<p>import json</p>
<pre><code>def ask(event, context):
body = {
"message": f"Go Serverless v3.0! Your function executed successfully! Length ",
"input": event,
}
response = {"statusCode": 200, "body": json.dumps(body)}
return response
</code></pre>
<p>The <strong>serverless.yml</strong> is this</p>
<p>service: rag-se-aws-lambda
frameworkVersion: '3'</p>
<pre><code>provider:
name: aws
runtime: python3.11
package:
individually: true
functions:
ask:
handler: handler.ask
events:
- httpApi:
path: /
method: post
</code></pre>
<p>Now I develop a function <code>my_function</code> in the file <strong>src/my_function.py</strong> and I want to use it in <strong>handler.py</strong> like this</p>
<pre><code>import json
from src.my_function import my_function
def ask(event, context):
my_function()
body = {
"message": f"Go Serverless v3.0! Your function executed successfully! Length ",
"input": event,
}
response = {"statusCode": 200, "body": json.dumps(body)}
return response
</code></pre>
<p>When I deploy, with the same <strong>serverless.yml</strong> configuration, the new version of my function I get the following runtime error</p>
<p><em><strong>Unable to import module 'handler': No module named 'my_function'</strong></em></p>
<p>By the way, if the file <strong>my_function.py</strong> is moved to the same root folder where <strong>handler.py</strong> is defined, everything works.</p>
<p>What should I do to be able to import a function from a different folder when using AWS Lambda python functions?</p>
|
<python><amazon-web-services><aws-lambda>
|
2024-05-04 16:09:09
| 1
| 17,802
|
Picci
|
78,429,573
| 2,562,058
|
How to configure debugpy for editable install?
|
<p>I am trying to develop a package that I have installed with <code>pip install -e .</code> .
The project structure is the following:</p>
<pre><code>mypackage
βββ build
βΒ Β βββ mypackage-0.8.83.dist-info
βΒ Β βββ licenses
βββ dist
βββ docs
βββ manual_tests
βΒ Β βββ manual_test.py
βββ src
βΒ Β βββ mypackage
βββ tests
</code></pre>
<p>I want to use the <code>manual_test.py</code> script for debugging <code>mypackage</code>. Among others, in such a file I have <code>import mypackage as mypkg</code> but when I run the debugger I get a <code>module not found error</code> on that line. Other packages are correctly recognized.</p>
<p>The debugpy configuration follows:</p>
<pre><code>{
"request": "launch",
"type": "python",
"cwd": "${fileDirname}",
"program": "${file}",
"stopOnEntry": true,
"console": "integratedTerminal",
"env": {
"PYDEVD_RESOLVE_SYMLINKS": "1",
},
}
</code></pre>
<p>I read somewhere to set <code>PYDEVD_RESOLVE_SYMLINKS=1</code> but it didn't help.</p>
|
<python><debugging><debugpy>
|
2024-05-04 15:54:22
| 0
| 1,866
|
Barzi2001
|
78,429,348
| 2,179,138
|
"Command not found" after installing pip package oemer on macos
|
<p>I installed oemer using the instructions from this page: <a href="https://github.com/BreezeWhite/oemer" rel="nofollow noreferrer">https://github.com/BreezeWhite/oemer</a> .</p>
<pre><code>pip3 install oemer
</code></pre>
<p>(I had to use pip3 on my system.)</p>
<p>Then went to run it, also according to instructions on that page:</p>
<pre><code>oemer ~/Pictures/trumpet.jpg
bash: oemer: command not found
</code></pre>
<p>So I get "command not found".</p>
<p>I thought maybe I needed to add the path to my $PATH, so to find the location of oemer, I ran</p>
<pre><code>pip3 show oemer
Name: oemer
Version: 0.1.5
Summary: End-to-end Optical Music Recognition (OMR) system.
Home-page: https://github.com/BreezeWhite/oemer
Author: BreezeWhite
Author-email: miyasihta2010@tuta.io
License: License :: OSI Approved :: MIT License
Location: /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages
Requires: matplotlib, onnxruntime, opencv-python, pillow, scikit-learn, scipy
Required-by:
</code></pre>
<p>and added /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages to my $PATH. Still didn't work. So I explicitly ran:</p>
<pre><code>/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/oemer ~/Pictures/trumpet.jpg
bash: /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/oemer: is a directory
</code></pre>
<p>Ahh, oemer is a directory, not an executable.</p>
<p>So my question is, how do I run oemer, or any other package installed by pip for that matter?</p>
<p>I tried:</p>
<pre><code>pip3 /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/oemer
ERROR: unknown command "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/oemer"
</code></pre>
<p>...and...</p>
<pre><code>python3 /Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/oemer
/usr/local/bin/python3: can't find '__main__' module in '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/oemer'
</code></pre>
<p>Searches such as "how to run python packages on macos" come up empty, with most results showing how to install python packages, how to install python, or how to install pip.</p>
|
<python><macos><pip>
|
2024-05-04 14:35:05
| 2
| 1,134
|
KevinHJ
|
78,429,162
| 19,003,861
|
Django Form - POST method not recognised as POST in views
|
<p>In my django project, I am trying to create a form which the user will access through a specific url.</p>
<p>By clicking on the url, the user will be automatically redirected to a <code>pager_id</code>.</p>
<p>Inbetween the user click on said url and being redirected to <code>page_id</code>, a form will be passed in the background, without any template.</p>
<p>Slight problem, the form does not pass the <code>if request.method == "POST":</code>.</p>
<p>I know that because the print rendered in the console is <code>this is not a post request</code>.</p>
<p>I think its probably the first time Im not using a template to render the form.</p>
<p>I would normally specify something like:</p>
<pre><code><form "method="POST">
{% csrf_token %}
</form>
</code></pre>
<p>But I am not doing this, this time. Everything is handled in the view.</p>
<p><strong>Question:</strong></p>
<p>Assuming this what is causing problem: Does Django require to use a template to render the form? Or is there a way to specify <code>method="POST"</code> in a different way? Or is there something else I am not seeing?</p>
<p><strong>views.py</strong></p>
<pre><code> def function(request, page_id):
form = myform(request.POST)
if request.method == "POST":
print('this is a post request')
if form.is_valid():
data = form.save(commit=False)
...
data.save()
return redirect('page', page_id=page_id)
else:
form = myform()
print('this is not a post request') #<-- this is what gets printed in the console
else:
print('Come back later!')
return redirect('page', page_id=page_id)
</code></pre>
|
<python><django><django-forms>
|
2024-05-04 13:41:59
| 1
| 415
|
PhilM
|
78,429,087
| 8,484,261
|
Fixing Header rows while writing a pivot dataframe to excel
|
<p>I am pivoting a dataframe and then filtering it. And then I need to write it to excel. But when I write it out,</p>
<ol>
<li>it is inserting a blank row between the header rows and the data rows</li>
<li>I want the header row names in one row not two rows. So, in the example below for the output to excel, I wan thte column names to be "Code", "Invoice" , Unit Price", "2022-12", 2023-12", 2024-01". I do not need the row with "amount" at the top.</li>
</ol>
<p>Executable code is below:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'JDate':["2022-01-31","2022-12-05","2023-11-10","2023-12-03","2024-01-16","2024-01-06"],
# 'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy'],
'Unit Price':[np.nan,200,None,56,75,65],
'Quantity':[1500, 140000, 1400000, 455, 648, 759],
'Amount':[100, 10000, 100000, 5, 48, 59],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey'],
'energy':[100.,100,100,54,98,3],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo']
})
df["JDate"] = pd.to_datetime(df["JDate"])
df["JYearMonth"] = df['JDate'].dt.to_period('M')
index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount']
# columns_to_use = ['Year','Month']
columns_to_use = ['JYearMonth']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
# df3 = df2[df2['Category']=='alpha']
# since this is an index you just filter for it
# df3 = df2.loc[['alpha']]
df3 = df2.xs('alpha',level='Category')
df3 = df3.reset_index() #this prevents merging of rows
writer= pd.ExcelWriter(
"t2test6.xlsx",
engine='xlsxwriter'
)
# df.to_excel(writer,sheet_name="t2",index=True)
# df2.to_excel(writer,sheet_name="t2test",index=True)
df3.to_excel(writer,sheet_name="t2filter",index=True)
writer.close()
</code></pre>
|
<python><pandas><excel><dataframe>
|
2024-05-04 13:08:04
| 1
| 3,700
|
Alhpa Delta
|
78,429,030
| 9,174,271
|
Common wheel zoom in pyecharts grid chart
|
<p>In pyecharts, I create a grid with two graphs having the same x-axis. I'd like to be able to zoom both at the same time using mouse wheel. It works on the single graph using <code>datazoom_opts=[opts.DataZoomOpts(type_="inside")]</code>, but I couldn't find a way to have something similar in <code>Grid</code>.</p>
<p>In javascript <code>echarts</code> library there's <code>echarts.connect</code> method that seems to do this (e.g. <code>echarts.connect([chart1, chart2]);</code>) but it doesn't seem to exist in <code>pyecharts</code>.</p>
<p>Please, see below a minimal functional example:</p>
<pre><code>from pyecharts import options as opts
from pyecharts.charts import Bar, Grid
# if you're using jupyter lab
from pyecharts.globals import CurrentConfig, NotebookType
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB
CurrentConfig.ONLINE_HOST
from random import randrange
x=list(range(0,100))
a = Bar()
a.add_xaxis(x)
a.add_yaxis("ax", [randrange(100) for x in range(0,100)])
a.set_global_opts(
title_opts=opts.TitleOpts(title="Bar-a"),
datazoom_opts=[opts.DataZoomOpts(type_="inside")],)
b = Bar()
b.add_xaxis(x)
b.add_yaxis("bx", [randrange(100) for x in range(0,100)])
b.set_global_opts(
title_opts=opts.TitleOpts(title="Bar-b"),
datazoom_opts=[opts.DataZoomOpts(type_="inside")],)
gr = Grid()
gr.add(a, grid_opts=opts.GridOpts(height="30%"))
gr.add(b, grid_opts=opts.GridOpts(pos_top="50%", height="30%"))
gr.render_notebook()
</code></pre>
<p>I can zoom in and out the first graph (a) using mouse wheel. The second is static. I want to zoom both keeping them aligned.</p>
<p><a href="https://i.sstatic.net/rjzMpHkZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rjzMpHkZ.png" alt="result of above code" /></a></p>
|
<python><echarts>
|
2024-05-04 12:50:16
| 1
| 312
|
GDN
|
78,428,918
| 354,051
|
scipy's find_peaks method produces inconsistent results
|
<pre class="lang-py prettyprint-override"><code>import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import resample
from scipy.signal._peak_finding_utils import _local_maxima_1d
def select_by_peak_distance(peaks, priority, distance):
"""
Evaluate which peaks fulfill the distance condition.
Parameters
----------
peaks : ndarray
Indices of peaks in `vector`.
priority : ndarray
An array matching `peaks` used to determine priority of each peak. A
peak with a higher priority value is kept over one with a lower one.
distance : np.float64
Minimal distance that peaks must be spaced.
Returns
-------
keep : ndarray[bool]
A boolean mask evaluating to true where `peaks` fulfill the distance
condition.
"""
peaks_size = peaks.shape[0]
# Round up because actual peak distance can only be natural number
distance = math.ceil(distance)
keep = np.ones(peaks_size, dtype=np.uint8) # Prepare array of flags
# Create map from `i` (index for `peaks` sorted by `priority`) to `j` (index
# for `peaks` sorted by position). This allows to iterate `peaks` and `keep`
# with `j` by order of `priority` while still maintaining the ability to
# step to neighbouring peaks with (`j` + 1) or (`j` - 1).
priority_to_position = np.argsort(priority)
for i in range(peaks_size - 1, -1, -1):
# "Translate" `i` to `j` which points to current peak whose
# neighbours are to be evaluated
j = priority_to_position[i]
if keep[j] == 0:
# Skip evaluation for peak already marked as "don't keep"
continue
k = j - 1
# Flag "earlier" peaks for removal until minimal distance is exceeded
while 0 <= k and peaks[j] - peaks[k] < distance:
keep[k] = 0
k -= 1
k = j + 1
# Flag "later" peaks for removal until minimal distance is exceeded
while k < peaks_size and peaks[k] - peaks[j] < distance:
keep[k] = 0
k += 1
return keep.astype(np.bool_)
sr, x = wavfile.read("jfk.wav")
x = x.astype(np.float64, order='C') / 32768.0 # Normalize (-1.0, 1.0)
x = resample(x, len(x)//8)
peaks, _, _ = _local_maxima_1d(x)
# Filter peaks all above 0
peaks = np.array([p for p in peaks if x[p] > 0])
keep = select_by_peak_distance(peaks, x[peaks], 20)
peaks = peaks[keep]
valley, _, _ = _local_maxima_1d(-x)
# Filter valley all below 0
valley = np.array([v for v in valley if x[v] < 0])
keep = select_by_peak_distance(valley, -x[valley], 20)
valley = valley[keep]
fig = plt.figure(figsize=(12, 6), dpi=80)
gs = fig.add_gridspec(1, hspace=0)
axs = gs.subplots()
axs.axhline(y = 0.0, color = 'lightgray', ls='-', lw=1.0)
axs.plot(x, lw=1)
axs.plot(peaks, x[peaks], "o", color='green')
axs.plot(valley, x[valley], "o", color='red')
fig.tight_layout()
plt.show()
plt.close()
</code></pre>
<p><a href="https://i.sstatic.net/I3pJNzWk.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/I3pJNzWk.jpg" alt="enter image description here" /></a></p>
<p><a href="https://github.com/scipy/scipy/blob/9c75b1f1bb6f08722af12b37286240aa405981bc/scipy/signal/_peak_finding_utils.pyx#L91" rel="nofollow noreferrer">select_by_peak_distance</a> is the python version of Cython C code.</p>
<ol>
<li>(G1, R1), (G2, R2), (G3, R3) pairs are the correct set of maxima and minima points.</li>
<li>The rest of the maxima points are wrong because they are just one index ahead from the correct position.</li>
<li>Resampling produces blunt or flat peaks, which is obvious and I believe that's the reason that sometimes the peaks are not getting selected. (bottom right of the images) If you increase the number of points by</li>
</ol>
<pre class="lang-py prettyprint-override"><code>x = resample(x, len(x)//4)
</code></pre>
<p>The missing peaks problem is getting resolved but that's not what I'm looking for.</p>
<ol start="4">
<li>In the case of minima the wrong point is one index less from the correct position.</li>
</ol>
<p>If we can solve the problem of maxima, getting the correct minima will be solved by itself. The Left of the maxima (lowest dip) will be the correct minima point.</p>
<p>I have tried a few things with "select_by_peak_distance" method but couldn't able to get the desired result.</p>
|
<python><scipy>
|
2024-05-04 12:06:42
| 0
| 947
|
Prashant
|
78,428,827
| 8,484,261
|
filtering a pivoted dataframe
|
<p>I am trying to filter a pivoted dataframe. But it is giving an error in the pivot part.
How do I fix this?</p>
<p>The executable code is below:</p>
<pre><code>import numpy as np
df = pd.DataFrame({
'Year':[2022,2022,2023,2023,2024,2024],
'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy'],
'Unit Price':[np.nan,200,None,56,75,65],
'Quantity':[1500, 140000, 1400000, 455, 648, 759],
'Amount':[100, 10000, 100000, 5, 48, 59],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey'],
'energy':[100.,100,100,54,98,3],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo']
})
index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount','Quantity']
columns_to_use = ['Year','Month']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
df3 = df2[df2['Category']=='alpha']
writer= pd.ExcelWriter(
"t2test2.xlsx",
engine='xlsxwriter'
)
df.to_excel(writer,sheet_name="t2",index=True)
df2.to_excel(writer,sheet_name="t2test",index=True)
df3.to_excel(writer,sheet_name="t2filter",index=True)
writer.close()
</code></pre>
|
<python><pandas><dataframe>
|
2024-05-04 11:31:02
| 1
| 3,700
|
Alhpa Delta
|
78,428,805
| 21,445,669
|
Cannot install timesynth with Poetry
|
<p>When I run <code>poetry add timesynth</code>, I get the following error:</p>
<pre><code>Backend subprocess exited when trying to invoke build_wheel
error: Multiple top-level packages discovered in a flat-layout: ['cmake', 'symengine'].
To avoid accidental inclusion of unwanted files or directories,
setuptools will not proceed with this build.
If you are trying to create a single distribution with multiple packages
on purpose, you should not rely on automatic discovery.
Instead, consider the following options:
1. set up custom discovery (`find` directive with `include` or `exclude`)
2. use a `src-layout`
3. explicitly set `py_modules` or `packages` with a list of names
To find more information, look for "package discovery" on setuptools docs.
</code></pre>
<p>The problem is with the symengine package (specifically 0.4.0 version). I've tried editing pyproject.toml like so:</p>
<pre><code>[tool.setuptools]
py-modules = []
</code></pre>
<p>As suggested in <a href="https://stackoverflow.com/questions/72294299/multiple-top-level-packages-discovered-in-a-flat-layout">this</a> SO answer, nothing changed. I've also included "timesynth" and "symengine" inside this list, no luck.</p>
<p>I've also tried including this codeblock:</p>
<pre><code>[tool.setuptools.packages.find]
where = ["symengine"]
include = ["pkg*", "symengine"] # alternatively: `exclude = ["additional*"]`
namespaces = false
</code></pre>
<p>But it didn't help.</p>
<p>I'm trying to follow a book about timeseries, but I can't figure out how to install this package. I'm on Windows 11, and Python 3.11 if that matters.</p>
|
<python><python-poetry><symengine>
|
2024-05-04 11:23:56
| 1
| 549
|
mkranj
|
78,428,739
| 16,545,894
|
generate PDF with picture Django rest framework
|
<p>With the code below, I can easily generate a PDF:</p>
<pre><code>import weasyprint
def admin_order_pdf(request, sell_id): # working fine
try:
sell = Sell.objects.get(id=sell_id)
except Sell.DoesNotExist:
return HttpResponse('Sell object does not exist')
html = render_to_string('sell_invoice.html', {'sell': sell})
response = HttpResponse(content_type='application/pdf')
app_static_dir = os.path.join(settings.BASE_DIR, 'pdf', 'static')
css_path = os.path.join(app_static_dir, 'css', 'css.css')
response['Content-Disposition'] = f'filename=sell_{sell.id}.pdf'
weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(css_path)])
return response
</code></pre>
<p>However, even though I can design the PDF with inline CSS and CSS files, I can't figure out how to insert any photos or pictures into it... Is it even possible to add a picture/logo to a PDF? If so, how may I approach it?</p>
|
<python><django><django-rest-framework><weasyprint><django-weasyprint>
|
2024-05-04 11:01:17
| 1
| 1,118
|
Nayem Jaman Tusher
|
78,428,544
| 10,770,967
|
Converting UTC Column into datetime in python pandas
|
<p>I would like to ask for little support. I have here a python frame containing data giving in UTC format. I would like to transform the column into date-format.</p>
<pre><code>Order Date
15-Feb-2024 UTC
17-Feb-2024 UTC
18-Feb-2024 UTC
02-Apr-2024 UTC
05-Mar-2024 UTC
04-Mar-2024 UTC
11-Apr-2024 UTC
12-Apr-2024 UTC
16-Mar-2024 UTC
04-Apr-2024 UTC
05-Feb-2024 UTC
05-Mar-2024 UTC
14-Apr-2024 UTC
df["Order Date"]=pd.to_datetime(df["Order Date"],utc=True,format='%d-%b-%Y')
</code></pre>
<p>Applying the line above gives me the following error</p>
<pre><code>time data "15-Feb-2024 UTC" doesn't match format "%d-%b-%Y", at position 0. You might want to try:
- passing `format` if your strings have a consistent format;
- passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;
- passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.
</code></pre>
<p>I tried all the options, without success.
Can someone tell me where the issue is?
All I need is to transform the column to a date column. I'd be grateful for any support</p>
|
<python><pandas><datetime><utc><python-datetime>
|
2024-05-04 09:57:18
| 1
| 402
|
SMS
|
78,428,505
| 19,375,296
|
scipy.interpolate.LinearNDInterpolator run in a Docker container fills up memory
|
<p>Why does this run in <strong>3 seconds</strong> when I run it directly on my computer and barely uses any RAM, but fills up <strong>30GB of RAM</strong> and <strong>20GB of swap</strong> when I run it in a Python Docker container ?</p>
<h3>test.py</h3>
<pre class="lang-py prettyprint-override"><code>import time
import numpy as np
from scipy.interpolate import LinearNDInterpolator
start_time = time.time()
points = [(0, 1500), (0, 1800), (0, 2000), (0, 2200), (180, 1600), (180, 1900), (180, 2100), (180, 2300)]
values = [5, 20, 25, 40, 2, 10, 15, 20]
points = np.array(points, dtype=np.float64)
values = np.array(values, dtype=np.float64)
interp = LinearNDInterpolator(points, values)
rng = np.random.default_rng()
sampled_angles = 180 * rng.random(size=6000*6000, dtype=np.float64)
sampled_altitude = (2200 - 1600) * rng.random(size=6000*6000, dtype=np.float64) + 1600
interpolated_thicknesses = interp(sampled_angles, sampled_altitude)
print(interpolated_thicknesses[:10])
end_time = time.time()
elapsed_time = end_time - start_time
print(elapsed_time)
</code></pre>
<h3>Dockerfile</h3>
<pre class="lang-bash prettyprint-override"><code>FROM python
WORKDIR /calculator
COPY ./test.py ./test.py
COPY ./requirements.txt ./requirements.txt
RUN apt-get update
RUN apt-get install -y pip
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python3", "test.py"]
</code></pre>
<h3>requirements.txt</h3>
<pre><code>scipy
numpy
</code></pre>
|
<python><docker><numpy><scipy>
|
2024-05-04 09:42:06
| 1
| 348
|
TimothΓ©e Billiet
|
78,428,399
| 694,716
|
How to solve abstract class override maximum recursion depth issue?
|
<p>I am creating a class that has abstract methods and overriding in sub classes.</p>
<p><code>MethodInterceptor</code> class has a method named <code>__getattribute__</code> that call before and after method in executing methods:</p>
<pre><code>from abc import abstractmethod, ABC
class MethodInterceptor(object):
@abstractmethod
def before_execute(self):
pass
@abstractmethod
def after_execute(self):
pass
def __getattribute__(self, name):
attr = object.__getattribute__(self, name)
if hasattr(attr, '__call__'):
def new_func(*args, **kwargs):
self.before_execute()
result = attr(*args, **kwargs)
self.after_execute()
return result
return new_func
else:
return attr
</code></pre>
<p>Creating sub class:</p>
<pre><code>class LoggerInterceptor(MethodInterceptor):
# overriding abstract method
def before_execute(self):
print("before")
def after_execute(self):
print("after")
</code></pre>
<p>Worker class:</p>
<pre><code>class Worker(LoggerInterceptor):
def __init__(self):
self.name = "worker"
def work(self):
print(f"hi I am {self.name}")
c = Worker()
c.work()
</code></pre>
<p>But I am getting an error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/xxx/Projects/Pycharm/method_interceptor.py", line 47, in <module>
c.work()
File "/Users/xxx/Projects/Pycharm/method_interceptor.py", line 18, in new_func
self.before_execute()
File "/Users/xxx/Projects/Pycharm/method_interceptor.py", line 18, in new_func
self.before_execute()
File "/Users/xxx/Projects/Pycharm/method_interceptor.py", line 18, in new_func
self.before_execute()
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
</code></pre>
|
<python>
|
2024-05-04 09:02:15
| 0
| 6,935
|
barteloma
|
78,428,358
| 10,623,444
|
Create MultiPolygon objects from struct type and list[list[list[f64]]] columns using Polars
|
<p>I have downloaded the NYC Taxi Zones <a href="https://data.cityofnewyork.us/Transportation/NYC-Taxi-Zones/d3c5-ddgc" rel="nofollow noreferrer">dataset</a> (downloaded from SODA Api and saved as json file - Not GeoJson or Shapefile). The dataset is rather small, thus I am using the whole information included. For the convenience of the post I am presenting the first 2 rows of the dataset:</p>
<ul>
<li><a href="https://drive.google.com/file/d/1GtdVID2Bp2yFh2atugQBm2kx1Nw7hr6W/view?usp=sharing" rel="nofollow noreferrer">original</a> (with struct type value of <code>the_geom</code>).</li>
<li><a href="https://drive.google.com/file/d/1Y9m9pSrk9LORkANnDyWPOqkixGMvvPIh/view?usp=sharing" rel="nofollow noreferrer">dataset</a> after unpacking the struct type with unnest() command in polars. --updated with <code>write_ndjson()</code> command</li>
</ul>
<p>The original dataset:
<a href="https://i.sstatic.net/gQpgstIz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gQpgstIz.png" alt="enter image description here" /></a></p>
<p>Below the dataset after applying <code>unnest()</code> and selecting some columns and the first 2 rows.</p>
<p><a href="https://i.sstatic.net/XIFDXFAc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XIFDXFAc.png" alt="enter image description here" /></a></p>
<p>You may import the data using polars with the following command</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
poc = pl.read_json("./data.json"))
</code></pre>
<p>I am interested in the multipolygons. I am actually trying to re-calculate the <code>shape_area</code> by using the multipolygon and wkt (Well-Known-Text representation) - method used by <code>shapely</code> module.</p>
<p>What I have done so far is to use the column <code>coordinates</code> and transform it to a MultiPolygon() object - readable by the Shapely module.</p>
<pre class="lang-py prettyprint-override"><code>def flatten_list_of_lists(data):
return [subitem3 for subitem1 in data for subitem2 in subitem1 for subitem3 in subitem2]
</code></pre>
<p>The function takes as input a <code>list[list[list[list[f64]]]]</code> object and transforms to a <code>list[list[f64]]</code> object.</p>
<pre class="lang-py prettyprint-override"><code>flattened_lists = [flatten_list_of_lists(row) for row in poc["coordinates"].to_list()]
print(flattened_lists)
</code></pre>
<blockquote>
<p>[[[-74.18445299999996, 40.694995999999904], [-74.18448899999999, 40.69509499999987], [-74.18449799999996, 40.69518499999987], [-74.18438099999997, 40.69587799999989], [-74.18428199999994, 40.6962109999999], [-74.18402099999997, 40.69707499999989]...</p>
</blockquote>
<p>Then I use the function below that applies string concatenation and basically:</p>
<ul>
<li>Transforms the <code>list[list[f64]]</code> object to String.</li>
<li>Adds the keyword MultiPolygon in front of the string.</li>
<li>Replaces '[' and ']' with '('., ')' respectively.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>def polygon_to_wkt(polygon):
# Convert each coordinate pair to a string formatted as "lon lat"
coordinates_str = ", ".join(f"{lon} {lat}" for lon, lat in polygon)
# Format into a WKT Multipolygon string (each polygon as a single polygon multipolygon)
return f"""MULTIPOLYGON ((({coordinates_str})))"""
formatted_wkt = [polygon_to_wkt(polygon) for polygon in flattened_lists]
poc = poc.with_columns(pl.Series("WKT", formatted_wkt))
</code></pre>
<p><a href="https://i.sstatic.net/oWBFxoA4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oWBFxoA4.png" alt="enter image description here" /></a></p>
<p>Finally, I use the method <code>wkt.loads("MultiPolygon ((()))").area</code> to compute the shape area of the Multipolygon object</p>
<pre class="lang-py prettyprint-override"><code>def convert_to_shapely_area(wkt_str):
try:
return wkt.loads(wkt_str).area
except Exception as e:
print("Error converting to WKT:", e)
return None
poc = poc.with_columns(
pl.col("WKT").map_elements(convert_to_shapely_area).alias("shapely_geometry")
)
print(poc.head())
</code></pre>
<p><a href="https://i.sstatic.net/2A7XJrM6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2A7XJrM6.png" alt="enter image description here" /></a></p>
<p>Even though for the first shape the WKT correctly returns the area of the object, while for the second MultiPolygon the methods returns the following error:</p>
<blockquote>
<p>IllegalArgumentException: Points of LinearRing do not form a closed linestring</p>
</blockquote>
<p>What I have noticed between the two rows, is that the multipolygon of Newark Airport is a continues object of list[list[f64]]] coordinates. Whereas, the Jamaika Bay has multiple sublists [list[list[f64]]] elements (check column coordinates to verify this). Also the screenshot below verify this statement.
<a href="https://i.sstatic.net/OSTtC918.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OSTtC918.png" alt="enter image description here" /></a></p>
<p>Thus, is there any way to unify the multipolygons of Jamaica Bay into one single GEOmetric object before applying WKT?</p>
<p>P.S: Many solutions on GitHub use the shape file, but I would like to regularly re-download the NYC zones automatically with the SODA API.</p>
<p>To download the raw .json file from SODA API (omit <code>logger_object</code> lets pretend it's <code>print()</code>)</p>
<pre class="lang-py prettyprint-override"><code>import requests
params = {
"$limit": geospatial_batch_size, #i.e. 50_000
"$$app_token": config.get("api-settings", "app_token")
}
response = requests.get(api_url, params=params)
if response.status_code == 200:
data = response.json()
if not data:
logger_object.info("No data found, please check the API connection.")
sys.exit()
with open("{0}/nyc_zone_districts_data.json".format(geospatial_data_storage), "w") as f:
json.dump(data, f, indent=4)
else:
logger_object.error("API request failed.")
logger_object.error("Error: {0}".format(response.status_code))
logger_object.error(response.text)
</code></pre>
|
<python><python-polars><shapely><wkt><multipolygons>
|
2024-05-04 08:46:16
| 1
| 1,589
|
NikSp
|
78,428,135
| 4,418,481
|
Edit plotly labels by double click
|
<p>I'm working on a PyQt app that uses Plotly to create some figures. I use QWebEngineView to display the HTML in a Python window by doing something like this:</p>
<pre><code> return f"""
<html>
<head>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body style='margin:0; padding:0; background-color:{self.figure_bg_color};'>
{plot_div}
</body>
</html>
"""
</code></pre>
<p>In my figures, the label, ylabel, and title are set automatically.</p>
<p>I was wondering if there is a way to let the user double-click on them so it will become editable and they could change the text, or if I have to create some widget to do it.</p>
|
<python><plotly>
|
2024-05-04 07:19:16
| 0
| 1,859
|
Ben
|
78,427,983
| 9,586,338
|
Why does `dict(id=1, **{'id': 2})` sometimes raise `KeyError: 'id'` instead of a TypeError?
|
<p>Normally, if you try to pass multiple values for the same keyword argument, you get a TypeError:</p>
<pre><code>In [1]: dict(id=1, **{'id': 2})
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 dict(id=1, **{'id': 2})
TypeError: dict() got multiple values for keyword argument 'id'
</code></pre>
<p>But if you do it <em>while handling another exception</em>, you get a KeyError instead:</p>
<pre><code>In [2]: try:
...: raise ValueError('foo') # no matter what kind of exception
...: except:
...: dict(id=1, **{'id': 2}) # raises: KeyError: 'id'
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [2], in <cell line: 1>()
1 try:
----> 2 raise ValueError('foo') # no matter what kind of exception
3 except:
ValueError: foo
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
Input In [2], in <cell line: 1>()
2 raise ValueError('foo') # no matter what kind of exception
3 except:
----> 4 dict(id=1, **{'id': 2})
KeyError: 'id'
</code></pre>
<p>What's going on here? How could a completely unrelated exception affect what kind of exception <code>dict(id=1, **{'id': 2})</code> throws?</p>
<p>For context, I discovered this behavior while investigating the following bug report: <a href="https://github.com/tortoise/tortoise-orm/issues/1583" rel="noreferrer">https://github.com/tortoise/tortoise-orm/issues/1583</a></p>
<p>This has been reproduced on CPython 3.11.8, 3.10.5, and 3.9.5.</p>
|
<python><cpython>
|
2024-05-04 06:19:19
| 1
| 6,549
|
Waket Zheng
|
78,427,958
| 11,221,706
|
Failing Kubernetes Pod creation from Python script executed in Init Container?
|
<p>Is it possible to fail/terminate pod creation from a Python script executed from an Init container?</p>
<p><strong>Init container</strong>:</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app.kubernetes.io/name: MyApp
spec:
containers:
- name: myapp-container
image: busybox:1.28
command: ['sh', '-c', 'echo The app is running! && sleep 3600']
initContainers:
- name: init-myservice
image: busybox:1.28
command: ["python3", "/scripts/example.py"]
</code></pre>
<p><strong>example.py</strong></p>
<pre><code>What would this Python script contain?
</code></pre>
<p>Thanks!</p>
|
<python><kubernetes>
|
2024-05-04 06:08:07
| 1
| 1,059
|
robtot
|
78,427,707
| 6,546,694
|
How to add range column over groups in polars
|
<p>I have:</p>
<pre><code>df = pl.DataFrame({'key':['a','a','a','b','b','b'],'a':[2,4,6,1,2,3]})
print(df)
shape: (6, 2)
βββββββ¬ββββββ
β key β a β
β --- β --- β
β str β i64 β
βββββββͺββββββ‘
β a β 2 β
β a β 4 β
β a β 6 β
β b β 1 β
β b β 2 β
β b β 3 β
βββββββ΄ββββββ
</code></pre>
<p>I want to add a column with increasing integers within each group defined by key</p>
<pre><code>df = pl.DataFrame({'key':['a','a','a','b','b','b'],'a':[2,4,6,1,2,3], 'r': [1,2,3,1,2,3]})
print(df)
shape: (6, 3)
βββββββ¬ββββββ¬ββββββ
β key β a β r β
β --- β --- β --- β
β str β i64 β i64 β
βββββββͺββββββͺββββββ‘
β a β 2 β 1 β
β a β 4 β 2 β
β a β 6 β 3 β
β b β 1 β 1 β
β b β 2 β 2 β
β b β 3 β 3 β
βββββββ΄ββββββ΄ββββββ
</code></pre>
<p>How do I do it?</p>
|
<python><dataframe><window-functions><python-polars>
|
2024-05-04 03:49:05
| 2
| 5,871
|
figs_and_nuts
|
78,427,685
| 15,474,507
|
non-bidirectional messages between chats
|
<p>I'm trying to achieve bidirectionality of messages, but messages from Chat B are not displayed in Chat A and I don't understand why, if it's a server or client side problem</p>
<pre><code>from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.websockets import WebSocketDisconnect
from starlette.routing import Route, WebSocketRoute, Mount
from starlette.staticfiles import StaticFiles
import base64
connected_websockets = {}
async def websocket_endpoint(websocket):
await websocket.accept()
connected_websockets[id(websocket)] = websocket
try:
while True:
data = await websocket.receive_text()
if data.startswith('ChatA:'):
# Handle message from Chat A
data = data[6:] # Remove the prefix
for ws_id, ws in connected_websockets.items():
if ws_id != id(websocket):
await ws.send_text(f"Received from ChatA: {data}")
elif data.startswith('ChatB:'):
# Handle message from Chat B
data = data[6:] # Remove the prefix
for ws_id, ws in connected_websockets.items():
if ws_id != id(websocket):
await ws.send_text(f"Received from ChatB: {data}")
elif data.startswith('data:'):
# This is a data URL, handle it as a file
await handle_file(data, websocket)
except WebSocketDisconnect:
del connected_websockets[id(websocket)]
async def handle_file(data_url, websocket):
# Extract the file type and data from the URL
file_type, data = data_url.split(';')[0].split('/')[1], data_url.split(',')[1]
# Decode the base64 data
file_data = base64.b64decode(data)
# Now you can save the file data to a file, or do whatever you want with it
with open('received.' + file_type, 'wb') as f:
f.write(file_data)
await websocket.send_text(f"File received: received.{file_type}")
routes = [
WebSocketRoute("/ws", websocket_endpoint),
Mount("/", StaticFiles(directory="static"), name="static") # Aggiungi questa linea
]
app = Starlette(routes=routes)
</code></pre>
<p><strong>client side</strong></p>
<pre><code>var socketA = new WebSocket('ws://localhost:8001/ws');
var socketB = new WebSocket('ws://localhost:8001/ws');
var fileToSend = null;
$('#form-send').submit(function(e){
e.preventDefault();
if (fileToSend) {
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
console.log('Sending file from ChatA: ', fileToSend.name); // Log added
socketA.send(contents);
$('#sent-messages').append($('<li>').text('Sent: ' + fileToSend.name));
fileToSend = null;
};
reader.readAsDataURL(fileToSend);
} else {
var message = 'ChatA:' + $('#input-send').val();
console.log('Sending message from ChatA: ', message); // Log added
socketA.send(message);
$('#sent-messages').append($('<li>').text('Sent: ' + message));
$('#input-send').val('');
}
});
socketA.onmessage = function(event){
var msg = event.data;
console.log('Received message at ChatA: ', msg); // Log added
if (msg.startsWith('File received:')) {
var filename = msg.split(': ')[1];
$('#received-messages').append($('<li>').html('Received: <a href="' + filename + '" download>' + filename + '</a>'));
} else {
$('#received-messages').append($('<li>').text('Received: ' + msg));
}
};
$('#form-receive').submit(function(e){
e.preventDefault();
var message = 'ChatB:' + $('#input-receive').val();
console.log('Sending message from ChatB: ', message); // Log added
socketB.send(message);
$('#received-messages').append($('<li>').text('Sent: ' + message));
$('#input-receive').val('');
});
socketB.onmessage = function(event){
var msg = event.data;
console.log('Received message at ChatB: ', msg); // Log added
if (msg.startsWith('File received:')) {
var filename = msg.split(': ')[1];
$('#received-messages').append($('<li>').html('Received: <a href="' + filename + '" download>' + filename + '</a>'));
} else {
$('#received-messages').append($('<li>').text('Received: ' + msg));
}
};
var dropZone = document.getElementById('sent-messages');
dropZone.addEventListener('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'copy';
});
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
e.stopPropagation();
var files = e.dataTransfer.files;
if (files.length > 0) {
fileToSend = files[0];
$('#input-send').val('File: ' + fileToSend.name);
}
});
</code></pre>
<p>As you can see from the image the messages sent from chat A are displayed in chat B, but the messages sent from chat B are not displayed in chat A, but are displayed in the same chat, which is a problem</p>
<p><a href="https://i.sstatic.net/5MDLY4HO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5MDLY4HO.png" alt="enter image description here" /></a></p>
|
<javascript><python>
|
2024-05-04 03:31:00
| 0
| 307
|
Alex Doc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.