QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
77,221,779
21,440,451
Azure Function deployment not using VS Code extension
<p>I am trying to deploy Azure Function performing a simple calculation. It is deployed successfully, because I can see <em>Your Functions 4.0 app is up and running</em>. My logic (<a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cfunctionsv2&amp;pivots=programming-language-python" rel="nofollow noreferrer">inspired by this</a>) is set up as follows.</p> <pre><code>import azure.functions as func app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS) @app.route(route=&quot;addition&quot;) def main(req: func.HttpRequest) -&gt; str: a = req.params.get(&quot;a&quot;) b = req.params.get(&quot;b&quot;) return &quot;{}&quot;.format(int(a) * int(b)) </code></pre> <p>When I navigate to <code>/api/addition?a=2&amp;b=3</code> I don't see the expected result. Instead I get 404 Not Found.</p> <p>I have tried deploying using <a href="https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python?pivots=python-mode-decorators" rel="nofollow noreferrer">VS Code Azure Function extension</a>. It was successful and I could confirm the expected result on the screen. However I want to do it without VS Code. What am I missing? Googling it is challenging because everyone asks how to <strong>do it in</strong> VS Code.</p> <p>The buildpipe compiles roughly like so.</p> <pre><code>- task: UsePythonVersion@0 inputs: versionSpec: $(pythonVersion) disableDownloadFromRegistry: true addToPath: true architecture: 'x64' displayName: 'Use python $(pythonVersion)' - script: | python -m venv antenv source antenv/bin/activate pip install -r requirements.txt workingDirectory: $(projectRoot) displayName: 'Install requirements' - task: ArchiveFiles@2 inputs: rootFolderOrFile: '$(projectRoot)' includeRootFolder: false archiveType: 'zip' archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip' replaceExistingArchive: true - publish: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip' artifact: drop </code></pre> <p>Then, it deploys like this.</p> <pre><code>- task: UsePythonVersion@0 inputs: versionSpec: $(pythonVersion) disableDownloadFromRegistry: true addToPath: true architecture: 'x64' displayName: 'Use python $(pythonVersion)' - task: AzureFunctionApp@2 inputs: azureSubscription: $(azureSubscription) appType: 'functionAppLinux' appName: 'func-calculationtest' package: '$(Pipeline.Workspace)/drop/$(Build.BuildId).zip' runtimeStack: 'PYTHON|3.10' deploymentMethod: 'auto' </code></pre>
<python><azure><azure-functions><azure-pipelines>
2023-10-03 11:17:44
1
492
danilo
77,221,619
5,359,846
How can I find pseudo element using Playwright?
<p>In my webpage I have some pseudo elements.</p> <p>For example:</p> <p><a href="https://i.sstatic.net/Crzsr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Crzsr.png" alt="enter image description here" /></a></p> <p>How can I find the ::after element using Playwright?</p>
<python><playwright><playwright-python>
2023-10-03 10:51:10
1
1,838
Tal Angel
77,221,564
4,986,615
Add mypy options --enable-incomplete-feature=Unpack in pyproject.toml
<p>I would like to use the experimental <code>typing.Unpack</code> in my project.</p> <p>In the CLI command, it works when adding <code>--enable-incomplete-feature=Unpack</code>.</p> <p>However, I have mypy issues reported by pyright (in neovim), therefore I would like to add this option in the section <code>mypy</code> of <code>pyproject.toml</code>.</p> <p>How can I achieve it?</p>
<python><mypy><pyproject.toml>
2023-10-03 10:44:31
1
2,916
guhur
77,221,352
3,445,378
How to freeze package version in requirements?
<p>I have installed the a Python Package with <code>pip install pyjwt[crypto]</code> and <code>pip freeze</code> shows me different packages that was installed by that action.</p> <p>What do I need to put in my <code>requirements.txt</code> to correctly freeze the versions I am developing with? I dont want to put to much in the <code>requirements.txt</code>, only what is needed for rebuilding the environment later.</p> <p>Output pip:</p> <pre><code>... pyjwt[crypto] in ..\site-packages (2.8.0) cryptography&gt;=3.4.0 in ..\site-packages (from pyjwt[crypto]) (41.0.4) cffi&gt;=1.12 in ..\site-packages (from cryptography&gt;=3.4.0-&gt;pyjwt[crypto]) (1.16.0) pycparser in ..\site-packages (from cffi&gt;=1.12-&gt;cryptography&gt;=3.4.0-&gt;pyjwt[crypto]) (2.21) ... </code></pre> <p>Output pip freeze:</p> <pre><code> ... cffi==1.16.0 cryptography==41.0.4 pycparser==2.21 PyJWT==2.8.0 ... </code></pre> <p>Is it ok to put only <code>PyJWT[crypto]==2.8.0</code> into <code>requirements.txt</code>?</p> <p>When I put to much into <code>requirements.txt</code> I would make it harder to install additional packages in the future ... I think.</p>
<python><pip><requirements.txt>
2023-10-03 10:11:46
2
1,280
testo
77,221,047
1,818,935
How to replace the Python interpreter of an existing venv virtual environment in VS Code?
<p>A couple days ago I created a <code>venv</code> virtual environment that uses the Python interpreter version 3.11.6. Now that a new Python version, 3.12.0, has been released, how can I replace the interpreter of my existing virtual environment by the new version? Or must I create a whole new virtual environment if I wish to use the newer interpreter version?</p> <p>My IDE is Visual Studio Code 1.82.3. My operating system is Windows 10 Pro v. 22H2.</p>
<python><visual-studio-code><python-venv>
2023-10-03 09:21:20
1
6,053
Evan Aad
77,221,003
7,216,834
For each row in a df, I want to calculate the sum of consecutive four values till last value in python?
<p>I have a df,</p> <pre><code> A B C D E F G 1 2 3 4 4 5 5 100 100 Na 100 100 10 5 </code></pre> <p>I want to create a df, that calculates the consecutive sum,that is 1+2+3+4 = D, 2+3+4+4 = E .... If na is there, the output should be na.</p> <p>Output:</p> <pre><code> D E F G 10 13 16 18 na na na 215 </code></pre> <p>When I tried it takes every 4 values, kindly help</p>
<python>
2023-10-03 09:13:41
1
1,325
Jennifer Therese
77,220,975
1,624,552
Check if http.client.HTTPSConnection instance returns a correct connection without errors
<p>Basically from Python I am creating an instance of http.client.HTTPSConnection from an url address which is the remote server url in order to download a remote file:</p> <pre><code>try: conn = http.client.HTTPSConnection(remoteServerUrl) conn.request(&quot;GET&quot;, remoteFile) # rest of code except Exception as e: print(e.message) finally: conn.close() </code></pre> <p>If I disconnect from internet (no internet connection) and I execute above code, when creating the instance of http.client.HTTPSConnection, it is not throwing any exception saying for example that the connection couldn't be established with the remote server. Also the conn object looks like gets populated correctly. So when executing next line conn.request I get an exception at that moment but not before.</p> <p>I would like to detect the error just when the instance is created and not having to wait until the request (conn.request) is done.</p> <p>When the line of code conn.request is exectued it is throwing the following exception:</p> <pre><code>socket.gaierror: [Errno 11001] getaddrinfo failed </code></pre> <p>So how can I detect if I get a &quot;correct&quot; instance of http.client.HTTPSConnection without errors?</p>
<python><https><httpclient>
2023-10-03 09:10:15
1
10,752
Willy
77,220,871
2,562,058
How to interpolate over a piecewise-constant set of points with scipy or numpy?
<p>I am having troubles in interpolating a set of piecewise-constant points. To better explain, consider the following code:</p> <pre><code>import numpy as np from scipy.interpolate import UnivariateSpline import matplotlib.pyplot as plt N = 30 Ts = 0.2 times = np.arange(0.0, N * Ts, Ts) signal = np.concatenate((1.5 * np.ones(10), -0.5 * np.ones(10), np.ones(10))) interp = UnivariateSpline(times[::3], signal[::3]) signal_interp = interp(times) plt.plot(times, signal) plt.plot(times, signal_interp) plt.show() </code></pre> <p>I expected the plot of <code>signal_interp</code> to overlap the plot of <code>signal</code> but that is not happening.</p> <p>I have found something <a href="https://stackoverflow.com/questions/31084502/piecewise-constant-or-0-degree-spline-interpolation-in-python-scipy">here</a> but the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d" rel="nofollow noreferrer">iterp1d</a> is considered legacy.</p> <p>I also tried to look <a href="https://docs.scipy.org/doc/scipy/reference/interpolate.html" rel="nofollow noreferrer">here</a> but I could not find any guidance for my specific case.</p>
<python><numpy><scipy>
2023-10-03 08:53:24
1
1,866
Barzi2001
77,220,728
5,316,326
Pydantic accept integer as string input
<p>For a FastAPI Pydantic interface I want to be as tolerable as possible, such as receiving an integer for a string parameter and parse that integer to string:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class FooBar(BaseModel): whatever: str FooBar(whatever=12) </code></pre> <p>Gives:</p> <pre><code>ValidationError: 1 validation error for FooBar whatever Input should be a valid string [type=string_type, input_value=12, input_type=int] For further information visit https://errors.pydantic.dev/2.4/v/string_type </code></pre> <p>I think in earlier versions this was possible.</p> <ul> <li>Python 3.10</li> <li>pydantic==2.4.2</li> <li>pydantic_core==2.10.1</li> </ul>
<python><python-3.x><fastapi><pydantic>
2023-10-03 08:30:23
2
4,147
Joost Döbken
77,220,509
14,954,262
Python Merge 2 DICT objects if matching id within a list with separators
<p>In Python I have those 2 dicts objects :</p> <pre><code>dict1 = [{'id_contact': '1', 'name': 'Rick'},{'id_contact': '9', 'name': 'John'}] dict2 = [{'id_company': ';1;3;4;11;', 'company_name': 'Nike'},{'id_company': ';1;2;9;', 'company_name': 'Adidas'}] </code></pre> <p>I would like to merge those 2 dicts to a new one to add the <code>'company_name'</code> if <code>id_contact</code> of dict1 is found in <code>id_company</code> in dict2. If theres is several matches <strong>I would like to use <strong>&quot;;&quot;</strong> as a separator in</strong> <code>'company_name'</code>.</p> <p>The expected result would be :</p> <pre><code>dictmerge = [{'id_contact': '1', 'name': 'Rick', 'company_name': 'Nike;Adidas'},{'id_contact': '9', 'name': 'John', 'company_name': 'Adidas'}] </code></pre> <p>Thanks for your help.</p>
<python><dictionary><merge><match><partial>
2023-10-03 07:48:48
2
399
Nico44044
77,220,394
11,479,825
Llama2 returns multiple [INST] '''json {"action":, "action_input":} answers
<p>I have cloned <a href="https://github.com/PromtEngineer/localGPT" rel="nofollow noreferrer">localGPT</a> and switched to YanaS/llama-2-7b-langchain-chat-GGUF from HuggingFace. The model returns multiple answers instead of just one:</p> <pre><code>Question: {{question}} Answer: ```json {&quot;action&quot;: &quot;Final Answer&quot;, &quot;action_input&quot;: {{answer1}}} ``` [INST] {{somehow rephrased question}} [/INST] ```json {&quot;action&quot;: &quot;Final Answer&quot;, &quot;action_input&quot;: {{answer2}}} ``` [INST] {{somehow rephrased question again}} [/INST] ```json {&quot;action&quot;: &quot;Final Answer&quot;, &quot;action_input&quot;: {{yet another answer}}} and so on. </code></pre> <p>I have no idea why this happens and how to fix it. because in the code the output is presented this way:</p> <pre><code> while True: query = input(&quot;\nEnter a query: &quot;) if query == &quot;exit&quot;: break # Get the answer from the chain res = qa(query) answer, docs = res[&quot;result&quot;], res[&quot;source_documents&quot;] # Print the result print(&quot;\n\n&gt; Question:&quot;) print(query) print(&quot;\n&gt; Answer:&quot;) print(answer) </code></pre> <p>I when I work with the default model I also get multiple answers like this. Any help will be appreciated.</p>
<python><prompt><llama>
2023-10-03 07:26:33
0
985
Yana
77,220,106
1,832,566
Stream from a google storage signed url to another google storage bucket with Python
<p>I get as an input a valid Google Storage signed url for read</p> <p>I am looking for the most elegant way to stream/upload the file from this signed url to another google storage bucket using Python</p> <p>I guess it's more convenient to do so via generating an upload signed url and then streaming to it the file from the read signed url (which I get as an input), but I am open to other solutions too</p> <p>Thanks!</p>
<python><google-cloud-storage><signed-url>
2023-10-03 06:31:17
1
7,884
Alexander
77,220,056
499,721
Programmatically adding commands to `fakeredis` in Python
<p>Is there a way to programmatically add commands to <a href="https://fakeredis.readthedocs.io" rel="nofollow noreferrer"><code>fakeredis</code></a>?</p> <p>Unless I'm missing something, the <a href="https://fakeredis.readthedocs.io/en/latest/guides/implement-command/#implementing-support-for-a-command" rel="nofollow noreferrer">docs</a> suggest directly modifying library code (<code>FakeSocket</code> in <code>_fakesocket.py</code>), which I wish to avoid.</p> <p>Motivation:<br/> I'm writing some unittests for an application which uses <a href="https://github.com/redis/redis-om-python" rel="nofollow noreferrer">Redis-OM</a>. My models are <code>JsonModel</code>s, which cannot be instantiated without an active redis connection (their <code>__init__</code> method checks that the Redis server supports Json).<br/> I'm trying to work around this limitation by using <code>FakeStrictRedis</code>. Unfortunately, it does not support the <em>COMMAND INFO</em> command which is used by <code>JsonModel</code>.</p> <p>Related questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/76578825/how-to-test-a-jsonmodel-in-a-unittest">How to test a JSONModel in a unittest?</a></li> <li><a href="https://stackoverflow.com/questions/55464725/mocking-redis-in-python">Mocking redis in python</a></li> </ul>
<python><redis><mocking><fakeredis>
2023-10-03 06:19:36
1
11,117
bavaza
77,220,025
248,296
Pydantic2 computed field with validate_assignment=True
<p>I have a Pydantic V2 model with a field <code>total_amount</code> which should be automatically computed whenever <code>items</code> field changes:</p> <pre class="lang-py prettyprint-override"><code>from typing import Self import pydantic class Calculation(pydantic.BaseModel): model_config = pydantic.ConfigDict(validate_default=True, validate_assignment=True) items: tuple[int, ...] total_amount: int = 0 @pydantic.model_validator(mode=&quot;after&quot;) def set_amount(self) -&gt; Self: self.total_amount = sum(self.items) return self calc = Calculation(items=(1, 2, 3)) </code></pre> <p>The problem is that because of <code>validate_assignment=True</code>, this code goes into infinite recursion:</p> <pre><code> File &quot;...py&quot;, line 14, in set_amount self.total_amount = sum(self.items) ^^^^^^^^^^^^^^^^^ File &quot;.../python3.11/site-packages/pydantic/main.py&quot;, line 796, in __setattr__ self.__pydantic_validator__.validate_assignment(self, name, value) File &quot;...py&quot;, line 14, in set_amount self.total_amount = sum(self.items) ^^^^^^^^^^^^^^^^^ File &quot;.../python3.11/site-packages/pydantic/main.py&quot;, line 796, in __setattr__ self.__pydantic_validator__.validate_assignment(self, name, value) File &quot;...py&quot;, line 14, in set_amount self.total_amount = sum(self.items) ^^^^^^^^^^^^^^^^^ File &quot;.../python3.11/site-packages/pydantic/main.py&quot;, line 796, in __setattr__ self.__pydantic_validator__.validate_assignment(self, name, value) File &quot;...py&quot;, line 14, in set_amount self.total_amount = sum(self.items) ^^^^^^^^^^^^^^^^^ File &quot;.../python3.11/site-packages/pydantic/main.py&quot;, line 767, in __setattr__ elif not _fields.is_valid_field_name(name): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;.../python3.11/site-packages/pydantic/_internal/_fields.py&quot;, line 277, in is_valid_field_name return not name.startswith('_') ^^^^^^^^^^^^^^^^^^^^ RecursionError: maximum recursion depth exceeded while calling a Python object </code></pre> <p>I want the field to be computed so that when I dump the model instance to the database, it to be up to date with <code>items</code>.</p> <p>Is there a way to work around this? Like excluding a field from assignment validation? Or making it a simple property, but always dump it?</p>
<python><pydantic>
2023-10-03 06:13:11
1
60,030
warvariuc
77,219,992
1,818,935
What methods of its last estimator does a scikit-learn pipeline have?
<p>I'm trying to understand <code>scikit-learn</code> Pipelines.</p> <p><a href="https://scikit-learn.org/stable/modules/compose.html#pipeline-chaining-estimators" rel="nofollow noreferrer">According to a Note in the scikit user guide</a> a Pipeline &quot;has all the methods that the last estimator in the pipeline has&quot;.</p> <p>So I wrote my own estimator class with a method called <code>myfun</code>, used an object of this class as the last step in a new Pipeline instance, and called <code>myfun</code> on it:</p> <pre><code>class MyEstimator: def __init__(self): pass def fit(self, X, y): return self def myfun(self): return None from sklearn.pipeline import make_pipeline pipe = make_pipeline(MyEstimator()) pipe.myfun() </code></pre> <p>This resulted in the following error message:</p> <pre><code> pipe.myfun() ^^^^^^^^^^ AttributeError: 'Pipeline' object has no attribute 'myfun' </code></pre> <p>Evidently contrary to the user guide's claims, a pipeline does not have all the methods that the last estimator in the pipeline has.</p> <p>So I wonder: what methods (more precisely, method signatures) of its last estimator does a pipeline have?</p>
<python><scikit-learn><scikit-learn-pipeline>
2023-10-03 06:05:43
1
6,053
Evan Aad
77,219,925
562,769
Does mypy==x give the same error messages for all Python versions?
<p>I'm the maintainer of pypdf. We use a CI that currently checks mypy for Python 3.6, 3.7, 3.8, 3.9, 3.10, 3.11, 3.12.</p> <p>I am thinking about just running mypy for one Python version.</p> <p>Does mypy in a fixed version x behave the same for all Python versions (we do have pytest covering the code; meaning if we import stuff that is not available in one version pytest will fail).</p>
<python><mypy>
2023-10-03 05:48:48
0
138,373
Martin Thoma
77,219,686
9,668,218
How to use Python library in SQL platform without using Databricks?
<p>I have developed a Python library that is installed on a Databricks cluster and is used to apply a few functions on delta tables:</p> <ul> <li><p>Import library into a notebook</p> </li> <li><p>Read required data from delta tables</p> </li> <li><p>Run python functions on the data and store results in a delta table</p> </li> </ul> <p>I need to run the same python codes in an Azure environment that doesn't have Databricks workspace. The client doesn't use Azure Databricks and all tables are SQL tables stored in Azure SQL database.</p> <p>Is there any way or service that I can use the same python library in a SQL platform without using Databricks (e.g Data Factory, Azure Function)? Especially, any service that supports Spark.</p> <p>It is not possible to write all codes in SQL language so I need to use the python library.</p>
<python><sql><azure><databricks>
2023-10-03 04:33:41
1
1,033
Mohammad
77,219,549
1,049,393
Solving a kinky secondary order ODE via Python Scipy
<p>I have the following second order ODE and I wish to solve it via Python Scipy:</p> <p><a href="https://i.sstatic.net/ymDlV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ymDlV.png" alt="ODE" /></a></p> <p>How can I accomplish this?</p>
<python><math><scipy><numerical-methods><ode>
2023-10-03 03:47:31
0
947
coderodde
77,219,433
20,235,789
Why isn't pydantic v2 finding SettingsSourceCallable?
<p>I'm looking at the migration guide and documentation: <a href="https://docs.pydantic.dev/2.4/migration/#basesettings-has-moved-to-pydantic-settings" rel="noreferrer">https://docs.pydantic.dev/2.4/migration/#basesettings-has-moved-to-pydantic-settings</a></p> <p>I can't seem to find where to locate <code>SettingsSourceCallable</code></p> <p>My pipeline is breaking for this import: <code> from pydantic.env_settings import SettingsSourceCallable</code></p> <p>Error:</p> <pre><code>ImportError: cannot import name 'SettingsSourceCallable' from 'pydantic.env_settings' (/usr/local/lib/python3.9/site-packages/pydantic/env_settings.py) </code></pre> <p>requirements.txt file:</p> <pre><code>fastapi~=0.103.2 pydantic~=2.4.2 uvicorn[standard]~=0.23.2 aiohttp~=3.8.3 PyJWT~=1.7.1 requests~=2.27.1 starlette~=0.27.0 starlette-context~=0.3.6 jose python-jose-cryptodome pytest~=7.1.2 pytest-asyncio~=0.19.0 pytest-cov~=3.0.0 aioresponses~=0.7.3 </code></pre>
<python><pip><pydantic>
2023-10-03 03:01:15
0
441
GustaMan9000
77,219,339
4,451,521
How to set the range in which a density is shown in seaborn
<p>I have the following plots</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd # read some dataframe and sns.histplot(data=df['error'],bins=20, binrange=(0,2),kde=True) </code></pre> <p><a href="https://i.sstatic.net/YdG6s.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YdG6s.png" alt="enter image description here" /></a></p> <p>so you can see I have limited the range for the histogram but not for the curve. Also the curve looks suspiciously low (and wrong)</p> <p>then</p> <pre><code>sns.histplot(data=df['c0_right_error'],bins=40, binrange=(-2,2),kde=True) </code></pre> <p>gives me</p> <p><a href="https://i.sstatic.net/DOCsC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DOCsC.png" alt="enter image description here" /></a></p> <p>I also tried the density plot (which I don't know if it is correct or not)</p> <pre><code>sns.histplot(data=df['c0_right_error'],bins=40, binrange=(-2,2),kde=True, stat='density') </code></pre> <p><a href="https://i.sstatic.net/StQLv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/StQLv.png" alt="enter image description here" /></a></p> <p>How can I limit the range in these plots?</p>
<python><seaborn>
2023-10-03 02:23:17
1
10,576
KansaiRobot
77,219,194
7,147,717
Visual Studio Code python wrong version
<p>I'm using Visual Studio Code to run python. I'm looking at the python version it says: 2.7.16, which I understand is really old.</p> <p><a href="https://i.sstatic.net/TW5aI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TW5aI.png" alt="enter image description here" /></a></p> <p>Now I click on the gear icon &gt; command palette &gt; select interpreter, and click on the one with the star.</p> <p><a href="https://i.sstatic.net/4LbIM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4LbIM.png" alt="enter image description here" /></a></p> <p>But when I run the code again, it always defaults back to the version 2.7.16. How do I get VS Code to recognize the right version of python? What I'm finding online about clicking the right python interpreter isn't working, like the answer has to be something different or more involved than just clicking something in the drop-down menu.</p>
<python><visual-studio-code>
2023-10-03 01:23:24
1
757
hachiko
77,219,154
4,555,765
Adding edge features in heterographs using PyGeometric
<p>For some reason I'm not being able to assign features to edges using <a href="https://pytorch-geometric.readthedocs.io/en/latest/generated/torch_geometric.data.HeteroData.html#torch_geometric.data.HeteroData" rel="nofollow noreferrer"><code>HeteroData</code></a> from PyGeometric package. The version installed are Python 3.11.5, PyTorch 2.0.1+cu117 and TorchGeometric 2.3.1 running over ArchLinux in a virtual environment.</p> <p>Given the following code snippet</p> <pre class="lang-py prettyprint-override"><code>import torch from torch_geometric.data import HeteroData data = HeteroData() # Params num_papers, num_paper_features = 5, 7 num_authors, num_author_features = 4, 10 num_edges = torch.randint(5, num_papers*num_authors, [1]).item() author_writes_paper_num_features = 4 # Adding features to nodes data['paper'].x = torch.randn(num_papers, num_paper_features) data['author'].x = torch.randn(num_authors, num_author_features) # Creating some random edges author_edge_index = torch.randint(0, num_authors, [num_edges]) paper_edge_index = torch.randint(0, num_papers, [num_edges]) edge_index = torch.stack((author_edge_index, paper_edge_index)) data['author', 'writes', 'paper'].edge_index = edge_index data = data.coalesce() # Adding features to edges data['author', 'writes', 'paper'].x = torch.randn(author_writes_paper_num_features, data.num_edges) # Also tried using the transpose edge feature matrix # data['author', 'writes', 'paper'].x = torch.randn(data.num_edges, author_writes_paper_num_features) </code></pre> <p>But, while I can correctly fetch node features</p> <pre><code>data.num_node_features # {'paper': 7, 'author': 10} data.node_stores # [{'x': tensor([[...]])}, # {'x': tensor([[...]])}] data.node_attrs() # ['x'] </code></pre> <p>The same does not happens with edge features</p> <pre><code>data.num_edge_features # {('author', 'writes', 'paper'): 0} </code></pre> <p>Is <em>ZERO</em>. Even with a <code>x</code> entry in edge_stores.</p> <pre><code>data.edge_stores #[{'edge_index': tensor([[0, 0, 0, 1, 1, 2, 2, 3, 3], # [0, 2, 4, 0, 1, 0, 3, 0, 2]]), 'x': tensor([[...]])}] </code></pre> <p>We can see that no feature attribute <code>x</code> is associated with edges</p> <pre class="lang-py prettyprint-override"><code>data.edge_attrs() # ['edge_index'] </code></pre> <p>Any suggestions?</p>
<python><graph><pytorch><pytorch-geometric>
2023-10-03 01:05:52
1
1,211
Lin
77,219,132
3,786,999
Problem with SDV (synthetic data vault): Getting back identical synthetic datasets
<p>I'm using the following code from the SDV library to create a synthetic dataset that's the same shape as my original dataset. While each synthetic dataset is different than the original dataset, all synthetic datasets are identical to each other. I would have thought there would be some randomness built into the synthetic data generation process so that each output would be slightly different. This occurs across sessions even when I set a different random seed. How should I interpret what's happening?</p> <pre><code> metadata.detect_from_dataframe(data=input_data) synthesizer = SingleTablePreset(metadata=metadata,name='FAST_ML') synthesizer.fit(data=input_data) synthetic_data = synthesizer.sample(num_rows=len(input_data))``` </code></pre>
<python><data-generation><synthetic><sdv>
2023-10-03 00:56:24
1
1,139
user3786999
77,219,012
817,630
When including a date column in a multi-index, then calling asfreq, the other columns in the index are removed
<p>I have some code that uses pandas <code>groupby</code> and <code>apply</code> along with <code>asfreq</code> to fill in date gaps for each grouping value.</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime import pandas as pd # Original data df = pd.DataFrame({ &quot;date&quot;: [datetime(2023, 8, 31), datetime(2023, 9, 30), datetime(2023, 8, 31), datetime(2023, 9, 30), datetime(2023, 9, 30)], &quot;name&quot;: [&quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;c&quot;], &quot;constant&quot;: [1, 1, 1, 1, 1], &quot;value&quot;: [100, 101, 200, 201, 301], }) print(df) df = ( df.set_index(&quot;date&quot;) .groupby([ &quot;constant&quot;, &quot;name&quot;, ])[&quot;value&quot;] .apply(lambda x: x.asfreq(&quot;d&quot;, method=&quot;ffill&quot;)) .reset_index() ) print(df) </code></pre> <p>This prints out these two results, which works as expected. For each <code>date</code>, <code>name</code>, and <code>constant</code> value, new rows are added for each day until the next date, and the <code>value</code> amount is filled forward.</p> <pre><code> date name constant value 2023-08-31 a 1 100 2023-09-30 a 1 101 2023-08-31 b 1 200 2023-09-30 b 1 201 2023-09-30 c 1 301 constant name date value 1 a 2023-08-31 100 1 a 2023-09-01 100 1 a 2023-09-02 100 1 a 2023-09-03 100 1 a 2023-09-04 100 ... ... ... ... 1 b 2023-09-27 200 1 b 2023-09-28 200 1 b 2023-09-29 200 1 b 2023-09-30 201 1 c 2023-09-30 301 </code></pre> <p>I'd now like to modify the code to include the original <code>date</code> value for each row. I thought this would be easy and I updated my code to look like this</p> <pre class="lang-py prettyprint-override"><code>df[&quot;original_date&quot;] = df[&quot;date&quot;] df = ( df.set_index(&quot;date&quot;) .groupby([ &quot;original_date&quot;, &quot;constant&quot;, &quot;name&quot;, ])[&quot;value&quot;] .apply(lambda x: x.asfreq(&quot;d&quot;, method=&quot;ffill&quot;)) .reset_index() ) print(df) </code></pre> <p>But the result of this change is</p> <pre><code> date value 2023-08-31 100 2023-08-31 200 2023-09-30 101 2023-09-30 201 2023-09-30 301 </code></pre> <p>Not only are the values not filled forward, but the <code>name</code> and <code>constant</code> columns are removed entirely.</p> <p>Instead I expected this</p> <pre><code>constant name date value original_date 1 a 2023-08-31 100 2023-08-31 1 a 2023-09-01 100 2023-08-31 1 a 2023-09-02 100 2023-08-31 1 a 2023-09-03 100 2023-08-31 1 a 2023-09-04 100 2023-08-31 1 a 2023-09-05 100 2023-08-31 1 a 2023-09-06 100 2023-08-31 1 a 2023-09-07 100 2023-08-31 1 a 2023-09-08 100 2023-08-31 1 a 2023-09-09 100 2023-08-31 1 a 2023-09-10 100 2023-08-31 1 a 2023-09-11 100 2023-08-31 1 a 2023-09-12 100 2023-08-31 1 a 2023-09-13 100 2023-08-31 1 a 2023-09-14 100 2023-08-31 1 a 2023-09-15 100 2023-08-31 1 a 2023-09-16 100 2023-08-31 1 a 2023-09-17 100 2023-08-31 1 a 2023-09-18 100 2023-08-31 1 a 2023-09-19 100 2023-08-31 1 a 2023-09-20 100 2023-08-31 1 a 2023-09-21 100 2023-08-31 1 a 2023-09-22 100 2023-08-31 1 a 2023-09-23 100 2023-08-31 1 a 2023-09-24 100 2023-08-31 1 a 2023-09-25 100 2023-08-31 1 a 2023-09-26 100 2023-08-31 1 a 2023-09-27 100 2023-08-31 1 a 2023-09-28 100 2023-08-31 1 a 2023-09-29 100 2023-08-31 1 a 2023-09-30 101 2023-09-30 1 b 2023-08-31 200 2023-08-31 1 b 2023-09-01 200 2023-08-31 1 b 2023-09-02 200 2023-08-31 1 b 2023-09-03 200 2023-08-31 1 b 2023-09-04 200 2023-08-31 1 b 2023-09-05 200 2023-08-31 1 b 2023-09-06 200 2023-08-31 1 b 2023-09-07 200 2023-08-31 1 b 2023-09-08 200 2023-08-31 1 b 2023-09-09 200 2023-08-31 1 b 2023-09-10 200 2023-08-31 1 b 2023-09-11 200 2023-08-31 1 b 2023-09-12 200 2023-08-31 1 b 2023-09-13 200 2023-08-31 1 b 2023-09-14 200 2023-08-31 1 b 2023-09-15 200 2023-08-31 1 b 2023-09-16 200 2023-08-31 1 b 2023-09-17 200 2023-08-31 1 b 2023-09-18 200 2023-08-31 1 b 2023-09-19 200 2023-08-31 1 b 2023-09-20 200 2023-08-31 1 b 2023-09-21 200 2023-08-31 1 b 2023-09-22 200 2023-08-31 1 b 2023-09-23 200 2023-08-31 1 b 2023-09-24 200 2023-08-31 1 b 2023-09-25 200 2023-08-31 1 b 2023-09-26 200 2023-08-31 1 b 2023-09-27 200 2023-08-31 1 b 2023-09-28 200 2023-08-31 1 b 2023-09-29 200 2023-08-31 1 b 2023-09-30 201 2023-09-30 1 c 2023-09-30 301 2023-09-30 </code></pre> <p>I verified this has to do with the <code>apply(...</code> piece of the code. If I change that to <code>sum</code>, for example, things work as expected.</p> <p>How can I include the original date in for each row in my resulting dataset, and why does including the <code>original_date</code> column remove the other columns in my example here?</p>
<python><pandas><dataframe>
2023-10-02 23:51:46
2
5,912
Kris Harper
77,218,845
14,932,271
How can the right object type be chosen, when using operator overloading in inherited classes?
<p>I am currently writing on a project in Python 3, which is quite huge and will consist of multiple classes. As these files are quite huge I came up with a simpler problem, depicted below.</p> <h1>Base Class</h1> <p>I have a base class called <code>Vector()</code> with multiple methods and performing operator overloading.</p> <pre><code>class Vector(): def __init__(self, vector): self.vector=vector self.length=len(vector) ## general methods def output(self): return (str(self.__class__.__name__)+&quot; &quot;+str(self.vector)+&quot; &quot;+str(self.compute())) ## class specific method def compute(self): return self.vector[0] #returns the length spanned by 1-dimensional vector. ## operator overloading def __add__(self, summand): d=[] for i in range(self.length): d.append(self.vector[i]+summand.vector[i]) return Vector(d) a=Vector([1]) b=Vector([2]) c=a+b print(a.output()) print(b.output()) print(c.output()) </code></pre> <p>The outcome is as expected:</p> <pre><code>Vector [1] 1 Vector [2] 2 Vector [3] 3 </code></pre> <p>We have 3 objects <code>a</code>,<code>b</code> and <code>c</code>, and <code>c</code> is the sum of <code>a</code> and <code>b</code>.</p> <h1>Derived Class</h1> <p>However, the projects needs to have inherited subclasses to deal with different data and datasources, similar to this:</p> <pre><code>class Vector2(Vector): def __init__(self, vector): super().__init__(vector) ## class specific method, all other stuff inherited def compute(self): return self.vector[0]*self.vector[1] #returns the area spanned by 2-dimensional vector. d=Vector2([1,2]) e=Vector2([4,3]) f=e+d print(d.output()) print(e.output()) print(f.output()) </code></pre> <p>The output is the following:</p> <pre><code>Vector2 [1, 2] 2 Vector2 [4, 3] 12 Vector [5, 5] 5 ## &lt;= should be 25 </code></pre> <p>My problem now is, that <code>d</code> and <code>e</code> are correctly instanciated as <code>Vector2()</code> objects and everything works fine with them, but the resulting <code>f</code> is <strong>only</strong> a <code>Vector()</code> object, having the <em>wrong</em> <code>f.compute()</code> result. (In fact it is the right result, but the wrong object type.)</p> <h1>Potential Solutions</h1> <p>I came up with the following solutions:</p> <ol> <li><p>Copy/Pasting all the operator overloading into the derived classes, instanciating the right class each time. This is in my opinion against the rules of code reusability in object oriented programming. And tedious work as already dozens of operator overloading methods exist in each class and a hand full of classes already exist. Code maintenance would be awful. <strong>==&gt; DISCARDED</strong></p> </li> <li><p>Adjust the operator overloading methods similar to that:</p> </li> </ol> <pre><code>class Vector(): # ... ## operator overloading extended version def __add__(self, summand): d=[] for i in range(self.length): d.append(self.vector[i]+summand.vector[i]) if self.__class__.__name__==&quot;Vector2&quot;: return Vector2(d) else: return Vector(d) </code></pre> <p>The result</p> <pre><code>Vector2 [1, 2] 2 Vector2 [4, 3] 12 Vector2 [5, 5] 25 </code></pre> <p>is ok now, but it would require to update all the base class's operator overloading methods, each time a new derived class is added to the project (<code>Vector3()</code>,<code>Vector4()</code>, <code>FancyVector()</code>, ...). Over time this might well be a few dozen. <strong>==&gt; UNHAPPY with that</strong></p> <h1>Final Question</h1> <p>Is there a way to dynamically instanciate objects in the base class, to return the correct object type from operator overloading, when the returned object type is a descendent of that base class?</p> <p>In other words: Can Python detect the object type of inherited operator overloading methods and return the correct derived object type?</p> <p>Thank you in advance.</p>
<python><python-3.x><oop><inheritance>
2023-10-02 22:48:23
3
392
destructioneer
77,218,773
298,622
How can I make mypy work with a custom class decorator similar to dataclass?
<p>I need to generate code for classes in a very similar way <code>dataclasses.dataclass</code> does. In my first version, I wrote something like:</p> <pre class="lang-py prettyprint-override"><code>def typedrow(cls: type[_T]) -&gt; type[_T]: cls_annotations = cls.__dict__.get(&quot;__annotations__&quot;, {}) def __init__(s, *args, **kwargs) -&gt; None: for field_name in cls_annotations.keys(): s.__dict__[field_name] = kwargs.get(field_name) setattr(cls, &quot;__init__&quot;, __init__) return cls </code></pre> <p>Although my code works, <code>mypy</code> is quite unhappy when I write:</p> <pre class="lang-py prettyprint-override"><code>@typedrow class Person: name: Optional[str] = None p = Person(name=&quot;joe&quot;) </code></pre> <p>It complains with <code>error: Unexpected keyword argument &quot;name&quot; for &quot;Person&quot;</code>.</p> <p>I noticed that <code>dataclasses.dataclass</code> does something completely different. Instead, it generates the code in text and calls <code>_create_fn</code>. Given that the generated code has all the type hints, it is kind obvious why <code>mypy</code> gets happy.</p> <p>How does that work <em>exactly</em>?</p> <p>I tried to create a simplified version of <code>_create_fn</code> which seems to be generated exactly the same code as <code>dataclass</code>, however, <code>mypy</code> is still unhappy.</p>
<python><python-decorators><mypy><python-dataclasses>
2023-10-02 22:26:58
1
4,938
Igor Gatis
77,218,738
4,834,431
Azure Pipelines - Variable empty set in python
<p>I have an Azure pipeline defined as:</p> <pre class="lang-yaml prettyprint-override"><code>- task: Bash@3 inputs: targetType: inline script: | python3 script.py echo $(abc) </code></pre> <p>The <code>script.py</code> is loaded and contains the following:</p> <pre class="lang-py prettyprint-override"><code>print('test_print') print('##vso[task.setvariable variable=abc]abc') print('set var') </code></pre> <p>Once I run this, the pipeline logs the print statements, however, the variable <code>abc</code> is empty.<br /> I've played around w e.g. <code>subprocess</code> and using echo in the python script, but without good result.</p> <p>Can anyone point me in the right direction as to why <code>echo $(abc)</code> returns an empty value?<br /> It looks like python didn't set the variable, while it should.</p>
<python><azure-pipelines>
2023-10-02 22:17:47
1
5,906
Kevin C
77,218,730
560,110
How to define a minimum width/height for horizontal and vertical lines when finding the number of rows and columns in a table image with Python OpenCV
<p><a href="https://i.sstatic.net/9EJNX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9EJNX.png" alt="processed image" /></a></p> <p>I'm attempting to take images of 8.5 x 11&quot; petitions and determine which rows contain something that resembles a signature. I'm assuming that I will be able to isolate each row in an inverted image and count the number of white pixels.</p> <p>Using <a href="https://stackoverflow.com/questions/60396925/how-to-find-the-number-of-rows-and-columns-in-a-table-image-with-python-opencv/60423841#60423841">this as a starting point</a>, so far in the process I have been able to isolate the tabular portion of the petition that would house signatures. When I attempt to isolate each row and each column however, I also catch portions of the text. And right now, I'm not entirely sure how to define a minimum width or height for a line segment to eliminate the text portioms.</p> <pre class="lang-py prettyprint-override"><code> # load image, convert to grayscale, otsu's threshold image = cv2.imread(img) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] # find number of rows horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1)) horizontal = cv2.morphologyEx( thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2 ) cnts = cv2.findContours(horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] rows = 0 for c in cnts: cv2.drawContours(image, [c], -1, (36, 255, 12), 2) rows += 1 # find number of columns vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 25)) vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2) cnts = cv2.findContours(vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] columns = 0 for c in cnts: cv2.drawContours(image, [c], -1, (36, 255, 12), 2) columns += 1 logger.info(f&quot;Rows {rows - 1}&quot;) logger.info(f&quot;Columns {columns - 1}&quot;) cv2.imshow(&quot;image&quot;, image) cv2.waitKey() </code></pre> <p>Here is the unprocessed image, per @stateMachine's ask.</p> <p><a href="https://i.sstatic.net/HhHWO.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HhHWO.jpg" alt="unprocessed image" /></a></p>
<python><opencv><image-processing>
2023-10-02 22:15:48
0
345
Chris Keller
77,218,713
9,766,795
binance cancel order request sends back 'unknown unorder received'
<p>I'm using the binance connector API with python <a href="https://binance-connector.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://binance-connector.readthedocs.io/en/latest/</a> with the testnet (<a href="https://testnet.binance.vision/" rel="nofollow noreferrer">https://testnet.binance.vision/</a>) to build a trading bot.</p> <p><strong>The problem that I have is</strong> that I'm sending a request to cancel an order on a certain symbol and I get back 'unknown order received'.</p> <p><em><strong>This is the log:</strong></em></p> <pre><code> 'rateLimits': [ { 'count': 17, 'interval': 'MINUTE', 'intervalNum': 1, 'limit': 6000, 'rateLimitType': 'REQUEST_WEIGHT'}], 'result': { 'clientOrderId': 'ECryC5RymE2cD4u50P11HI', 'cummulativeQuoteQty': '0.00000000', 'executedQty': '0.00000000', 'icebergQty': '0.00000000', 'isWorking': True, 'orderId': 12264945, 'orderListId': -1, 'origQty': '0.00054600', 'origQuoteOrderQty': '0.00000000', 'price': '27449.33000000', 'selfTradePreventionMode': 'NONE', 'side': 'BUY', 'status': 'NEW', 'stopPrice': '0.00000000', 'symbol': 'BTCUSDT', 'time': 1696284008962, 'timeInForce': 'GTC', 'type': 'LIMIT', 'updateTime': 1696284008962, 'workingTime': 1696284008962}, 'status': 200} ---------------------------------------------------------------------------------------------------- 2023-10-02 22:00:11.073 UTC DEBUG binance.websocket.websocket_client: Sending message to Binance WebSocket Server: {&quot;id&quot;: &quot;48b42ef9-6e14-467c-b35c-7f6e52de514c&quot;, &quot;method&quot;: &quot;depth&quot;, &quot;params&quot;: {&quot;symbol&quot;: &quot;BTCUSDT&quot;, &quot;limit&quot;: 1}} ---------------------------------------------------------------------------------------------------- { 'id': '48b42ef9-6e14-467c-b35c-7f6e52de514c', 'rateLimits': [ { 'count': 19, 'interval': 'MINUTE', 'intervalNum': 1, 'limit': 6000, 'rateLimitType': 'REQUEST_WEIGHT'}], 'result': { 'asks': [['27447.71000000', '0.02714400']], 'bids': [['27447.70000000', '0.03461200']], 'lastUpdateId': 20964071}, 'status': 200} ---------------------------------------------------------------------------------------------------- 2023-10-02 22:00:11.307 UTC DEBUG binance.websocket.websocket_client: Sending message to Binance WebSocket Server: {&quot;id&quot;: &quot;f6ab36b1-3618-4061-bedd-d1046a3ee52a&quot;, &quot;method&quot;: &quot;order.cancel&quot;, &quot;params&quot;: {&quot;apiKey&quot;: &quot;5aBdL8xhcEukeAqemVb5H0JSTXpAPYrX07BcHGw0WAjvJS4kClsLvT7rGkgyYsqA&quot;, &quot;orderId&quot;: 12264945, &quot;symbol&quot;: &quot;BTCUSDT&quot;, &quot;timestamp&quot;: 1696284011307, &quot;signature&quot;: &quot;cabf41556cd22cf6af425729a9e77a042d3a77958c5d8118922bc67f1546957c&quot;}} ---------------------------------------------------------------------------------------------------- { 'error': {'code': -2011, 'msg': 'Unknown order sent.'}, 'id': 'f6ab36b1-3618-4061-bedd-d1046a3ee52a', 'rateLimits': [ { 'count': 20, 'interval': 'MINUTE', 'intervalNum': 1, 'limit': 6000, 'rateLimitType': 'REQUEST_WEIGHT'}], 'status': 400} </code></pre> <p>This is the code for the cancel order:</p> <pre class="lang-py prettyprint-override"><code> def cancel_order(self, id: int) -&gt; None: self.currently_cancelling_order = True self.binance_api_client.cancel_order( symbol=self.TRADING_SYMBOL, orderId=id, ) </code></pre> <p>The id for the order I'm trying to cancel is always correct, no matter what, you can check this in the log file as well.</p> <p>This is <strong>the documentation for the request to cancel:</strong> <a href="https://binance-connector.readthedocs.io/en/latest/binance.spot.trade.html?order#binance.spot.trade.cancel_order" rel="nofollow noreferrer">https://binance-connector.readthedocs.io/en/latest/binance.spot.trade.html?order#binance.spot.trade.cancel_order</a>.</p> <p><strong>I think</strong> it's possible that my order might have gotten filled somewhere during the process and when I'm trying to cancel it, I can't cancel it anymore, so I get this answer back.</p> <p><strong>What am I doing wrong?</strong></p>
<python><binance><binance-api-client><python-binance>
2023-10-02 22:10:04
1
632
David
77,218,272
308,827
Lollipop plot for dataframe with two groups
<p>I have the following dataframe:</p> <pre><code> Country variable value 0 Afghanistan Area 38.232510 1 Afghanistan Yield 70.081666 2 Argentina Area 96.776730 3 Argentina Area 60.047651 4 Argentina Yield 66.811117 .. ... ... ... 133 United States Of America Yield 53.536069 134 United States Of America Area 76.975885 135 United States Of America Yield 19.987656 136 Zambia Yield 39.493612 137 Zambia Yield 35.384809 </code></pre> <p>I want to use it to construct a lollipop graphic (e.g. <a href="https://python-graph-gallery.com/184-lollipop-plot-with-2-groups/" rel="nofollow noreferrer">https://python-graph-gallery.com/184-lollipop-plot-with-2-groups/</a>). However, the example dataframe is different from mine in that it has two values for each group while I want to plot the minimum and maximum value for the two groups for each country, with the group being differentiated by hue. How can I do it by modifying the code from that example?</p>
<python><pandas><matplotlib><seaborn><stem-plot>
2023-10-02 20:14:09
1
22,341
user308827
77,218,039
16,363,897
Ways to speed up rolling weighted mean on a pandas dataframe
<p>I have a large <code>DataFrame</code>, on which I need to calculate the rolling row-wise weighted average.</p> <p>I know I can do the following:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(20000, 50)) weights = [1/9, 2/9, 1/3, 2/9, 1/9] rolling_mean = df.rolling(5, axis=1).apply(lambda seq: np.average(seq, weights=weights)) </code></pre> <p>The issue is that this takes around 40 seconds on my PC. Is there any way to speed up this computation?</p>
<python><pandas><numpy>
2023-10-02 19:29:00
4
842
younggotti
77,217,894
3,851,085
Python ckan get packages for organization
<p>Using CKAN in Python, how can I get all packages for a given organization? I am not seeing this functionality here: <a href="https://docs.ckan.org/en/2.9/api/index.html" rel="nofollow noreferrer">https://docs.ckan.org/en/2.9/api/index.html</a></p>
<python><ckan>
2023-10-02 19:03:07
0
1,110
Software Dev
77,217,624
8,380,272
usage of `OR, AND` operators in set union
<p>Bear with me if the question is duplicate. But cant seem to find any related questions/solutions.</p> <p>Suppose I have tow sets:</p> <pre><code>set_one = {10,5,7} set_two = {10,1,3,6, 5, 7} set_one | set_two # union of two sets {1, 3, 5, 6, 7, 10} set_one.union(set_two) # same as above {1, 3, 5, 6, 7, 10} </code></pre> <p>Why does using <code>or</code> result in intersection instead of union? check below</p> <pre><code>set_one or set_two # union of two sets {10, 5, 7} # Shouldn't this be {1, 3, 5, 6, 7, 10}? </code></pre> <p>And using <code>and</code> results in union instead of intersection?</p> <pre><code>set_one &amp; set_two # intersection of two sets {5, 7, 10} set_one.intersection(set_two) # same as above {5, 7, 10} set.intersection(set_one, set_two) # same as above {5, 7, 10} </code></pre> <p>Using <code>and</code></p> <pre><code>set_one and set_two {1, 3, 5, 6, 7, 10} # Should'n this be {5, 7, 10} </code></pre> <p>Run this on python 3.11.5</p>
<python><set>
2023-10-02 18:12:07
2
80,265
Onyambu
77,217,521
116
Is psycopg3 a fork of psycopg2, or a replacement upgrade?
<p>I see references to both psycopg2 and psycopg3, but no clear guidance wrt a roadmap for transitioning between the two. I see that over time there is a large body of SO questions regarding psycopg2.</p> <p>Is psycopg3 intended to be a replacement for psycopg2? Has there been a significant uptake of this version?</p> <p>Will there be a long-lived version of psycopg2? Are there any compelling reasons to choose one version over the other?</p>
<python><psycopg2><psycopg3>
2023-10-02 17:53:10
1
305,996
Mark Harrison
77,217,419
9,983,652
how to group columns efficiently?
<p>I have a dataframe with 10000 columns and the column name is just the numerical data like depth, for each column is for each depth. I'd like to group the columns from 10000 column into 5000 columns by increasing spacing between each column. I am not sure how to do it.</p> <p>Here is a simple example for demonstration:</p> <pre><code>df=pd.DataFrame({'1':[1,2,3,4],'2.1':[2,4,6,8],'3.2':[3,6,9,12],'4.3':[4,8,12,16]}) df 1 2.5 3.2 4.3 0 1 2 3 4 1 2 4 6 8 2 3 6 9 12 3 4 8 12 16 df.columns=df.columns.astype('float') depth_list=df.columns.tolist() import numpy as np spacing_new=2 depth_list_grouped=[ x for x in np.arange(depth_list[0],depth_list[-1],step=spacing_new)] depth_list_grouped [1.0, 3.0] </code></pre> <p>Now I'd like to group column using the above new grouped depth of [1,3], for grouped columns of 1 is equal to mean value of original column of 1,2, grouped column of 3 is equal to mean value of original column of 2,3, 4.</p> <p>Here is my code which is very tedious and take a long time to do for 10000 columns:</p> <pre><code>df_grouped=pd.DataFrame() for col_new in depth_list_grouped: df_grouped[col_new]=[0]*len(df) count=0 for col in df.columns: if (col&gt;=col_new-spacing_new/2)&amp;((col&lt;=col_new+spacing_new/2)): df_grouped[col_new]+=df[col] count+=1 df_grouped[col_new]=df_grouped[col_new]/count df_grouped 1 3 0 1.5 3.0 1 3.0 6.0 2 4.5 9.0 3 6.0 12.0 </code></pre> <p>Any better solution? Thanks</p>
<python><pandas>
2023-10-02 17:32:33
1
4,338
roudan
77,217,381
9,002,634
FastAPI endpoint receiving bytes/file
<p>how can I create a FastAPI endpoint that can receive the following request example.</p> <pre class="lang-py prettyprint-override"><code>import requests # URL of your FastAPI endpoint url = &quot;http://localhost:8000/upload/?param1=temp&amp;param2=temp&quot; # Path to the file you want to upload file_path = &quot;your_file.bin&quot; # Open the file and send it as binary data in the request with open(file_path, &quot;rb&quot;) as file: response = requests.post(url, data=file.read()) # Print the response from the server print(response.status_code) print(response.text) </code></pre> <p>I've already checked <a href="https://fastapi.tiangolo.com/tutorial/request-files/" rel="nofollow noreferrer">Tutorial: Request Files</a>, but this doesn't look to be what I am looking for.</p> <p>If I use <code>File</code> or <code>UploadFile</code>, then the client request would be something like:</p> <pre><code># Files to be uploaded files = { 'data': ('your_file.bin', open('your_file.bin', 'rb')) } # Send the POST request with files response = requests.post(url, params=params, headers=headers, files=files) </code></pre> <p>but that is not the same thing.</p> <p>These are the signatures I've tried so far but none of them works with the way I want the client to upload:</p> <pre class="lang-py prettyprint-override"><code>@router.post( '/upload/', status_code=status.HTTP_201_CREATED, ) def upload_binary(param1: str, param2: str, data: bytes) </code></pre> <p>This one I got 422 Unprocessable Entity</p> <pre class="lang-py prettyprint-override"><code>@router.post( '/upload/', status_code=status.HTTP_201_CREATED, ) def upload_binary(param1: str, param2: str, data: Annotated[bytes, File()]) </code></pre> <p>Also 422 Unprocessable Entity</p> <pre class="lang-py prettyprint-override"><code>@router.post( '/upload/', status_code=status.HTTP_201_CREATED, ) def upload_binary(param1: str, param2: str, data: UploadFile) </code></pre> <p>Also 422, probably because the FastAPI server is expecting form data.</p>
<python><fastapi>
2023-10-02 17:24:11
0
318
Viet Than
77,217,076
9,957,594
Langchain - using filters in a Retriever
<p>Do any of the langchain retrievers provide filter arguments?</p> <p>I'm trying to create an EnsembleFilter using a VectorRetriever (FAISS) and a normal Retriever (BM25), but the filter fails when combining them:</p> <pre><code>documents = [Document(page_content='The Celtics are my favourite team.', metadata={topic=&quot;sport&quot;}), Document(page_content='The Boston Celtics won the game by 20 points', metadata={topic=&quot;sport&quot;}), Document(page_content='This is just a random text.', metadata={topic=&quot;unknown&quot;})] # embeddings is any langchain embeddings db = FAISS.from_documents(documents, embeddings) question = &quot;Who is my favourite team?&quot; retriever = BM25Retriever.from_documents(documents) faiss_retriever = db.as_retriever(search_kwargs={'filter': dict(topic=&quot;sport&quot;), 'k': 4, 'fetch_k': 8}) er = EnsembleRetriever(retrievers=[retriever, faiss_retriever], weights=[0.3, 0.7]) results = er.get_relevant_documents(question) </code></pre> <p>How can I make sure the filter persists in the BM25 retriever?</p>
<python><langchain>
2023-10-02 16:24:06
1
350
tcotts
77,216,874
15,209,311
How to toggle on / off microphone using Python and also get its current state?
<p>I found the following code that toggles off / on the microphone using Python and it works well (only on windows).</p> <pre><code>import win32api import win32gui WM_APPCOMMAND = 0x319 APPCOMMAND_MICROPHONE_VOLUME_MUTE = 0x180000 hwnd_active = win32gui.GetForegroundWindow() win32api.SendMessage(hwnd_active, WM_APPCOMMAND, None, APPCOMMAND_MICROPHONE_VOLUME_MUTE) </code></pre> <p>However, I could not find in any place how to get the state of the microphone (if it's muted or not). How can I do that?</p> <p>And is there a way to achieve toggle on / off microphone + getting its state functionallity in non-windows computers?</p> <p>Thanks</p>
<python><python-3.x><winapi><microphone>
2023-10-02 15:50:38
0
619
Niv
77,216,567
13,142,245
What is the JSON input format for a Lambda function for proxy integration?
<p>I'm using AWS Lambda with an API Gateway proxy integration (<code>AWS_PROXY</code>) such that requests are passed directly without API Gateway imposing any routing.</p> <p>Lambda is hosting a FastAPI application and Mangum is the intermediary that allows Lambda to respond to requests as a uvivorn server would.</p> <p>My question is, how should the request be represented as JSON?</p> <pre class="lang-py prettyprint-override"><code>@app.get(&quot;/get-student/{student_id}&quot;) def get_student(student_id: int): return students[student_id] </code></pre> <p>What should an inbound request look like? This is my naive guess. From Mangum documentation, I'm not yet clear on what is required.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;httpMethod&quot;:&quot;GET&quot;, &quot;path&quot;:&quot;/get-student/1&quot; } </code></pre>
<python><amazon-web-services><aws-lambda><aws-api-gateway><fastapi>
2023-10-02 15:03:35
1
1,238
jbuddy_13
77,216,542
5,567,893
how to merge the multiple dataframes sequentially?
<p>Although I thought this question should be duplicated, I couldn't find the proper answer.</p> <p>I have some problems merging multiple dataframes sequentially.</p> <p>For example, I have four dataframes as below:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({'source': ['A', 'A', 'A', 'B', 'B', 'C', 'C'], 'target': ['1', '2', '3', '4', '5', '6', '7']}) df2 = pd.DataFrame({'source': ['A', 'A'], 'temp': ['a', 'b']}) df3 = pd.DataFrame({'source': ['B', 'B'], 'temp': ['c', 'd']}) df4 = pd.DataFrame({'source': ['C'], 'temp': ['e']}) </code></pre> <p>And I'd like to merge the dataframe as below:</p> <pre class="lang-py prettyprint-override"><code># source target temp #0 A 1 a #1 A 1 b #2 A 2 a #3 A 2 b #4 A 3 a #5 A 3 b #6 B 4 c #7 B 4 d #8 B 5 c #9 B 5 d #10 C 6 e #11 C 7 e </code></pre> <p>To do so, I tried to run the code, but it returned unexpected results.</p> <pre class="lang-py prettyprint-override"><code>#Trial 1 dfs = pd.merge(df1, df2, on='source', how='left') dfs = pd.merge(dfs, df3, on='source', how='left') # new column was created with prefix, but I want to keep the three columns; source, target, temp #Trial 2 dfs = pd.merge(df1, df2, on='source', how='left') dfs['temp']=dfs.set_index('source')['temp'].fillna(df3.set_index('source')['temp'].to_dict()).values # it only fills the fixed number of NaN value, but there are some exception; one NaN in dfs, multiple values in other df3 or df4 #Trial 3 dfs = pd.merge(df1, df2, on='source', how='left') dfs[dfs['source']=='B']['temp']=pd.merge(df1, df3, on='source', how='left')['temp'].dropna() # it didn't change the dfs </code></pre>
<python><pandas><dataframe><merge>
2023-10-02 15:00:01
2
466
Ssong
77,216,430
18,349,319
MinIO docker-compose AccessDenied
<p>My MinIO container When I try to create the MinIO bucket, I have an error:</p> <pre><code>S3 operation failed; code: AccessDenied, message: Access denied </code></pre> <p>I'm creating the bucket with Python minio:</p> <pre class="lang-py prettyprint-override"><code>minio_client = minio.Minio(endpoint=os.getenv(&quot;MINIO_HOST&quot;), secure=False) if not minio_client.bucket_exists(&quot;bucket1&quot;): minio_client.make_bucket(&quot;bucket1&quot;) </code></pre> <pre class="lang-yaml prettyprint-override"><code>minio: image: minio/minio ports: - &quot;9000:9000&quot; - &quot;9001:9001&quot; volumes: - /.minio_storage:/data environment: MINIO_ROOT_USER: admin MINIO_ROOT_PASSWORD: password command: server --address 0.0.0.0:9000 --console-address &quot;:9001&quot; /data restart: unless-stopped </code></pre>
<python><minio>
2023-10-02 14:45:27
0
345
TASK
77,216,279
3,017,906
list.extend method applied while creating the list
<p><code>Python</code> <code>list.extend()</code> method allows to append a list to an existing one, as detailed <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow noreferrer">here</a></p> <p>I can do something like this:</p> <pre><code>import numpy as np a = [1,2,3] a.extend(list(np.arange(4,20,1))) </code></pre> <p>but I <strong>cannot</strong> make this work:</p> <pre><code>a = [1,2,3].extend(list(np.arange(4,20,1))) </code></pre> <p>What am I doing wrong?</p> <p><strong>EDIT</strong></p> <p>It's contained in my selected answer, but I will spell it out for people who, like me, were really missing the point of why this cannot work.</p> <p>The code that does not produce the intended result contains an assigment:</p> <p><code>a = &lt;something&gt;</code></p> <p>This means that on the right-hand side of the <code>=</code> there <strong>must</strong> be a valid expression, otherwise the assignment is void.</p> <p>However, the <code>list.extend()</code> method <strong>does not return anything</strong>, it just modifies the original list.</p> <p>So, the operation:</p> <pre><code>[1,2,3].extend(list(np.arange(4,20,1))) </code></pre> <p>does modify <code>[1,2,3]</code> but there's no reference to this list, so this is an object that there's no way to retrieve. This is why the second code in my question does not work, and the first one does. It's because in the first one I <strong>do</strong> create a reference to the <code>[1,2,3]</code> list, with <code>a = [1,2,3]</code>.</p>
<python><list>
2023-10-02 14:25:08
1
1,343
Michele Ancis
77,216,224
10,410,169
Switch directory in a docker container within Vertex
<p>I have a DBT docker container.</p> <p>The WORKDIR is set to <code>dbt/client/client_name</code>.</p> <p>I am easily able to run commands within the docker container using <code>kfp.components.load_component_from_text()</code></p> <p>However, somewhere along the line I need to switch directories to run other commands, the directory I am attempting to switch to is <code>dbt/client/client_name_raw</code>. What command can I use within my <code>kfp.components.load_component_from_text()</code> in order to switch to that directory?</p> <p>I have already tried the following:</p> <pre class="lang-py prettyprint-override"><code> @staticmethod def run_seed(client_name_raw, dbt_image_uri, target): run_seed = kfp.components.load_component_from_text(f''' name: DBT Client Seed implementation: container: image: {dbt_image_uri} command: [&quot;cd&quot; , &quot;../{client_name_raw}&quot;, &quot;dbt&quot;, &quot;seed&quot;, &quot;--target&quot;, &quot;{target}&quot;] ''')() return run_seed </code></pre> <p>Vertex gives me the following error message</p> <pre><code>&quot;The replica workerpool0-0 exited with a non-zero status of 128. Termination reason: StartError. Termination log message: failed to create containerd task: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: &quot;cd&quot;: executable file not found in $PATH: unknown To find out more about why your job exited please check the logs:&quot; </code></pre> <p>Seems like Vertex/kfp doesn't know how to interpret &quot;cd&quot; in this context. Any advice would be appreciated</p>
<python><docker><google-cloud-vertex-ai><kubeflow-pipelines>
2023-10-02 14:18:19
1
335
Mengezi Dhlomo
77,216,151
583,464
extract words from list after specific character
<p>I have two lists:</p> <pre><code>list_1 = ['08667\nST 403', '08667\nST 403', '08667\nST 403'] list_2 = ['12233\nFION', '12233\nFION', '12233\nFION', '12233\nFION', '31147\nARAB\nP1454'] </code></pre> <p>I want to be able to extract the names after the '\n' keyword.</p> <p>I am using this code:</p> <pre><code>def parse_string(string): string = string.rsplit('\n', 1)[1] return string list_1 = ['08667\nST 403', '08667\nST 403', '08667\nST 403'] list_2 = ['12233\nFION', '12233\nFION', '12233\nFION', '12233\nFION', '31147\nARAB\nP1454'] new_list_1 = [] new_list_2 = [] for i in range(len(list_1)): new_list_1.append(parse_string(list_1[i])) for i in range(len(list_2)): new_list_2.append(parse_string(list_2[i])) </code></pre> <p>For the <code>list_1</code>, it works fine:</p> <pre><code>new_list_1 ['ST 403', 'ST 403', 'ST 403'] </code></pre> <p>but for the <code>list_2</code>:</p> <pre><code>new_list_2 ['FION', 'FION', 'FION', 'FION', 'P1454'] </code></pre> <p>So, the last element is <code>P1454</code> instead of <code>ARAB</code>.</p> <p>How can I automate this to work for all cases?</p>
<python><python-3.x><list>
2023-10-02 14:04:35
3
5,751
George
77,216,117
15,384,651
ANTLR not generating ParserBase
<p>I am new to ANTLR and was looking into the CPP14 grammar <a href="https://github.com/antlr/grammars-v4/tree/master/cpp" rel="nofollow noreferrer">here</a>. I tried using</p> <p><code>antlr4 -Dlanguage=Python3 CPP14Lexer.g4</code></p> <p><code>antlr4 -Dlanguage=Python3 CPP14Parser.g4</code></p> <p>Then use the following driver code:</p> <pre><code>import sys from antlr4 import * from CPP14Lexer import CPP14Lexer from CPP14Parser import CPP14Parser def main(argv): input_stream = FileStream(argv[1]) lexer = CPP14Lexer(input_stream) stream = CommonTokenStream(lexer) parser = CPP14Parser(stream) tree = parser.start_() if __name__ == '__main__': main(sys.argv) </code></pre> <p>And, try running it to parse a Hello World code in cpp, but I get the following error:</p> <pre><code>python Driver.py example.cc Traceback (most recent call last): File &quot;/Users/vedantamohapatra/antlr/Driver.py&quot;, line 4, in &lt;module&gt; from CPP14Parser import CPP14Parser File &quot;/Users/vedantamohapatra/antlr/CPP14Parser.py&quot;, line 14, in &lt;module&gt; from CPP14ParserBase import CPP14ParserBase ModuleNotFoundError: No module named 'CPP14ParserBase' </code></pre> <p>How should I go about correcting this?</p>
<python><parsing><antlr><antlr4>
2023-10-02 13:59:14
1
520
Vedanta Mohapatra
77,216,057
17,884,397
indexing a numpy array by an array of indices in a loop
<p>i have a vector i want to shuffle in batches.<br /> the idea i came up with is to reshape it into 2D array with each row as a batch.<br /> then i shuffle each row on its own.</p> <p>this is toy example of the approach</p> <pre class="lang-py prettyprint-override"><code># shuffle the matrix mat_size = (8, 8) row_size = 4 # generate the row and column indices # shuffle the column col_idx = np.arange(mat_size[0] * mat_size[1], dtype = np.int32) tmp_mat = np.reshape(col_idx, (-1, row_size)) for row in tmp_mat: idx = np.random.choice(row_size, size = row_size, replace = False) row[idx] = row # in place on col_idx tmp_mat </code></pre> <p>the result i get:</p> <pre><code>array([[ 1, 0, 0, 0], [ 4, 5, 6, 4], [ 8, 9, 9, 8], [12, 12, 14, 12], [16, 17, 17, 19], [21, 20, 20, 21], [25, 26, 24, 24], [28, 29, 28, 31], [33, 34, 32, 32], [36, 36, 38, 38], [40, 41, 41, 43], [44, 44, 46, 46], [48, 48, 50, 48], [53, 52, 53, 52], [56, 57, 56, 57], [61, 60, 62, 60]]) </code></pre> <p>the issue is that the rows are not a shuffled version of the input rows.<br /> it can be seen as the original array has unique values per row. i am not sure what happens here.</p> <p>i did found out that if i replace <code>row[idx] = row</code> with <code>row[:] = row[idx]</code> it works.</p> <p>is there an explanation to what is going on?<br /> why is the assignment not working as i expect?</p>
<python><arrays><numpy><for-loop><variable-assignment>
2023-10-02 13:50:56
1
736
Eric Johnson
77,215,858
11,688,559
Google Cloud Function HTTP request connection times out
<p>I am performing an http request to the LibreNMS API via the following Python code:</p> <pre><code>import requests TOKEN = './token.json' def get_request(request_type): url = f'http://192.168.1.141/api/v0/{request_type}' with open(TOKEN,'r') as file: headers = json.load(file) response = requests.get(url,headers=headers) if response.status_code == 200: pass else: print(f&quot;Failed to pull for {request_type}: {response.status_code}&quot;) return response.json() if __name__ == '__main__': dat = get_request('alerts') # pull alerts </code></pre> <p>The script runs perfectly on my local machine and quite fast. However when I try to deploy the scrip as a Google Cloud Function then <code>requests.get(url,headers=headers)</code> seems to time out. In the cloud logs of the function I get:</p> <pre><code>Traceback (most recent call last): File &quot;/layers/google.python.pip/pip/lib/python3.11/site-packages/urllib3/connection.py&quot;, line 203, in _new_conn sock = connection.create_connection( &quot;Traceback (most recent call last): File &quot;/layers/google.python.pip/pip/lib/python3.11/site-packages/urllib3/connectionpool.py&quot;, line 703, in urlopen httplib_response = self._make_request(&quot; &quot;Traceback (most recent call last): File &quot;/layers/google.python.pip/pip/lib/python3.11/site-packages/requests/adapters.py&quot;, line 489, in send resp = conn.urlopen(&quot; Traceback (most recent call last): File &quot;/layers/google.python.pip/pip/lib/python3.11/site-packages/flask/app.py&quot;, line 2529, in wsgi_app response = self.full_dispatch_request()&quot; </code></pre> <p>I have the same versions of <code>requests==2.28.1</code> and <code>urllib3==1.26.14</code> installed on my local machine and in the <code>requirements.txt</code> file of the cloud function. I thought the problem might lie here.</p> <p>I am unsure if a cloud function can perform http requests to non-Google services. Perhaps this is the issue.</p> <p>Please help me understand what is wrong with my function and/or deployment.</p> <h1>Update</h1> <p>It seems that the issue lies within the fact that the address <code>192.168.1.141</code> was local. I have since replaced it with <code>librenms.bctechnologies.co.za:8050</code>. However, it seems like this too is not public as <code>response = requests.get(url,headers=headers)</code> keeps timing out.</p>
<python><http><google-cloud-platform><google-cloud-functions><httprequest>
2023-10-02 13:17:49
1
398
Dylan Solms
77,215,767
13,793,478
How to change app.py variable with HTML button?
<p>How do I add or subtract 1 from the variable num ( in flask route) with an HTML button?</p> <p>So when I click the button it change the var to 1 and refresh the page to show the new value</p> <pre><code>@app.route('/') def note(): num = 1 return render_template('home.html', num=num) </code></pre>
<python><flask><jinja2>
2023-10-02 13:04:02
3
514
Mt Khalifa
77,215,726
15,262,489
The relationship between json pattern in azure python sdk and json view of azure objects
<p>I am writing a python script which will make use of azure python sdk, and inside the script I have some cases of usage of <code>begin_create_or_update</code> function, which is common for most modules in azure python sdk.</p> <p>However, I am having trouble figuring out the proper json pattern for each object to specify in <code>begin_create_or_update</code> function. I am using <a href="https://github.com/Azure-Samples/azure-samples-python-management/blob/main/samples" rel="nofollow noreferrer">the git directory of azure samples</a> as reference to figure out the proper pattern for the json. But I cannot find any official documentation regarding to required and optional argument formats for the json in <code>begin_create_or_update</code> function. For example, I have no clue what kind of arguments I should provide in json if I want to create a virtual machine scale set.</p> <p>I found <a href="https://learn.microsoft.com/en-us/azure/developer/python/sdk/azure-sdk-library-usage-patterns?tabs=pip" rel="nofollow noreferrer">this link</a> which states that the usage of json patterns in the function is possible, but does not provide any link for proper documentation.</p> <p>I have also found some similarities between the json view of objects in portal azure and json pattern which is required in <code>begin_create_or_update</code> function. My question is if there is an official documentation for the json arguments for each type of object which <code>begin_create_or_update</code> function might refer to, and how can I make use of the json view in azure portal in order to figure out the pattern of json in the sdk.</p>
<python><json><azure><azure-python-sdk>
2023-10-02 12:56:13
1
2,306
Karen Baghdasaryan
77,215,634
127,508
How to send a request to AWS Bedrock properly?
<p>I have the following Python code talking to the Bedrock API:</p> <p>Setting up the session:</p> <pre class="lang-py prettyprint-override"><code>import boto3 dev = boto3.session.Session(profile_name=&quot;dev&quot;) bedrock_runtime = dev.client( service_name=&quot;bedrock-runtime&quot;, region_name=&quot;us-east-1&quot;, endpoint_url=&quot;https://bedrock.us-east-1.amazonaws.com&quot;, ) </code></pre> <p>Trying to get a simple answer:</p> <pre class="lang-py prettyprint-override"><code>import json model_id = &quot;anthropic.claude-v2&quot; content_type = &quot;application/json&quot; accept = &quot;*/*&quot; body = {&quot;prompt&quot;:&quot;Human: Who was the 40th president of the united states?&quot;,&quot;max_tokens_to_sample&quot;:42,&quot;temperature&quot;:0.5,&quot;top_k&quot;:250,&quot;top_p&quot;:1,&quot;anthropic_version&quot;:&quot;bedrock-2023-05-31&quot;} resp = bedrock_runtime.invoke_model( modelId=model_id, contentType = content_type, accept = accept, body = json.dumps(body) ) </code></pre> <p>And it throws this:</p> <pre><code>File ~/venv/lib/python3.11/site-packages/botocore/client.py:535, in ClientCreator._create_api_method.&lt;locals&gt;._api_call(self, *args, **kwargs) 531 raise TypeError( 532 f&quot;{py_operation_name}() only accepts keyword arguments.&quot; 533 ) 534 # The &quot;self&quot; in this scope is referring to the BaseClient. --&gt; 535 return self._make_api_call(operation_name, kwargs) File ~/venv/lib/python3.11/site-packages/botocore/client.py:980, in BaseClient._make_api_call(self, operation_name, api_params) 978 error_code = parsed_response.get(&quot;Error&quot;, {}).get(&quot;Code&quot;) 979 error_class = self.exceptions.from_code(error_code) --&gt; 980 raise error_class(parsed_response, operation_name) 981 else: 982 return parsed_response ValidationException: An error occurred (ValidationException) when calling the InvokeModel operation: The requested operation is not recognized by the service. </code></pre> <p>Not sure why.</p>
<python><amazon-web-services><amazon-bedrock>
2023-10-02 12:41:33
1
8,822
Istvan
77,215,614
12,036,506
Python: Returning reference to a class property from another function instead of the actual value
<p>Imagine a basic python class with a property like :</p> <pre class="lang-py prettyprint-override"><code>class Test(Generic[T]): def __init__(self, x: T): self.__x = x @property def x(self): return self.__x def update(self, value: T): self.__x = value # Note that this can be any kindof update depending on the datatype </code></pre> <p>and now I have a factory function that creates multiple of these class objects. I want the factory function to return the class property <code>x</code> instead of the value of <code>x</code> at the given point. For simplicity sake, the factory function here only generates a single class.</p> <pre class="lang-py prettyprint-override"><code>def test_factory(value: T): obj = Test(value) return obj.x, obj.update if __name__ == &quot;__main__&quot;: test_property, test_setter = test_factory(10) print(test_property) test_property = 2 print(test_property) test_setter(12) print(test_property) </code></pre> <p>I would like the output here to be and would expect an error at <code>test_property = 2</code></p> <pre class="lang-bash prettyprint-override"><code>10 10 12 </code></pre> <p>But currently the output is :</p> <pre class="lang-bash prettyprint-override"><code>10 2 2 </code></pre> <p>This is because returning obj.x returns the actual value at that point which is <code>10</code> and then <code>test_property</code> variable is getting set to <code>2</code> Is there a way I can make the test_factory return the actual property that is <code>x</code> so it behaves like I'm using <code>obj.x</code>. I know this can be resolved by returning something like a <code>getX</code> function from <code>Test</code> class but is there any way to do this with this syntax. I want the output of the <code>test_factory</code> to be like a value and not a getter function.</p> <hr /> <p>I also tried returning <code>property(obj.getX())</code> type syntax but this returned a property object and did not have similar behavior to <code>obj.x</code></p>
<python><python-3.x>
2023-10-02 12:36:56
0
368
Gray Hat
77,215,607
4,451,521
How can I create a density plot (using as a reference a histogram)
<p>I have the following script</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig5 = plt.figure() fig5.subplots_adjust(wspace=0.4, hspace=0.6) ax5_2 = fig5.add_subplot(212) std_error = &quot;{:.2f}&quot;.format(np.std(df['error'])) ave_error = &quot;{:.2f}&quot;.format(np.nanmean(df['error'])) ax5_2.set_title(&quot;Error Histogram ave:&quot; + ave_error + &quot; std:&quot; + std_error) ax5_2.hist(df['error'], range=(0, 2), bins=20) </code></pre> <p>with that I get</p> <p><a href="https://i.sstatic.net/LOCX0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LOCX0.png" alt="enter image description here" /></a></p> <p>I want to plot the density here. I tried</p> <pre><code>hist,bin_edges=np.histogram(df['error'], range=(0, 2), bins=20,density=True) bin_widths=np.diff(bin_edges) densities = hist / (np.sum(hist) * bin_widths) plt.bar(bin_edges[:-1], densities, width=bin_widths, align='edge') # Customize your plot as needed plt.xlabel('X-axis Label') plt.ylabel('Density') plt.title('Density Plot') </code></pre> <p>with that I got</p> <p><a href="https://i.sstatic.net/y1WYN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/y1WYN.png" alt="enter image description here" /></a></p> <p>Is this correct? And second, I thought density plots were smooth line-like plots and not bars.</p> <p>How can I create the density plot corresponding to the histogram above?</p> <p>(I tried seaborn completely unrelated histograms and density plots...)</p> <p>EDIT: I tried mcgusty solution</p> <pre><code>errors = np.random.randn(100) df = pd.DataFrame({'errors': errors}) sns.histplot(data=df, x=&quot;errors&quot;, kde=True) </code></pre> <p>and I got</p> <p><a href="https://i.sstatic.net/pOLwV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pOLwV.png" alt="enter image description here" /></a></p> <p>but then I tried the equivalent in matplotlib</p> <pre><code>fig5 = plt.figure() fig5.subplots_adjust(wspace=0.4, hspace=0.6) ax5_2 = fig5.add_subplot(212) ax5_2.hist(errors, range=(-3, 3), bins=9) </code></pre> <p>and I got <a href="https://i.sstatic.net/SuZLv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SuZLv.png" alt="enter image description here" /></a> and</p> <pre><code>hist,bin_edges=np.histogram(errors, range=(-3, 3), bins=9,density=True) bin_widths=np.diff(bin_edges) densities = hist / (np.sum(hist) * bin_widths) plt.bar(bin_edges[:-1], densities, width=bin_widths, align='edge') </code></pre> <p><a href="https://i.sstatic.net/GCy0t.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GCy0t.png" alt="enter image description here" /></a></p> <p>Quite different!</p>
<python><matplotlib>
2023-10-02 12:35:43
1
10,576
KansaiRobot
77,215,365
1,824,285
Problem installing Pytrends on WIndows: Module not found
<p>I have just begun learning Python so I'm not very confident. I have installed Python 3.8.2 and added the location of my installation directory to my PATH in Windows 11. However I cannot get the Pytrends module to work.</p> <p>I can execute Python commands directly in Command Prompt, and also run scripts in Pycharm.</p> <p>I'm trying to install Pytrends, following the guide <a href="https://pypi.org/project/pytrends/" rel="nofollow noreferrer">here</a>. I ran</p> <pre><code>pip install pytrends </code></pre> <p>Which came up with a load of &quot;Requirement already satisfied&quot; reports. I'm not clear on whether it completed installation</p> <pre><code>C:\Users\username&gt;pip install pytrends Requirement already satisfied: pytrends in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (4.9.2) Requirement already satisfied: requests&gt;=2.0 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from pytrends) (2.31.0) Requirement already satisfied: pandas&gt;=0.25 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from pytrends) (2.1.1) Requirement already satisfied: lxml in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from pytrends) (4.9.3) Requirement already satisfied: numpy&gt;=1.23.2 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from pandas&gt;=0.25-&gt;pytrends) (1.26.0) Requirement already satisfied: python-dateutil&gt;=2.8.2 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from pandas&gt;=0.25-&gt;pytrends) (2.8.2) Requirement already satisfied: pytz&gt;=2020.1 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from pandas&gt;=0.25-&gt;pytrends) (2023.3.post1) Requirement already satisfied: tzdata&gt;=2022.1 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from pandas&gt;=0.25-&gt;pytrends) (2023.3) Requirement already satisfied: charset-normalizer&lt;4,&gt;=2 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from requests&gt;=2.0-&gt;pytrends) (3.2.0) Requirement already satisfied: idna&lt;4,&gt;=2.5 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from requests&gt;=2.0-&gt;pytrends) (3.4) Requirement already satisfied: urllib3&lt;3,&gt;=1.21.1 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from requests&gt;=2.0-&gt;pytrends) (2.0.5) Requirement already satisfied: certifi&gt;=2017.4.17 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from requests&gt;=2.0-&gt;pytrends) (2023.7.22) Requirement already satisfied: six&gt;=1.5 in c:\users\username\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from python-dateutil&gt;=2.8.2-&gt;pandas&gt;=0.25-&gt;pytrends) (1.16.0) </code></pre> <p>However, when I run this command from the guide in command line or in my app script:</p> <pre><code>from pytrends.request import TrendReq </code></pre> <p>I receve the error:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'pytrends' </code></pre> <p>I don't really understand this. If I go into my appdata folder, I can see the pytrends folders in there so I think it's installed.</p>
<python>
2023-10-02 11:54:26
2
378
mike_freegan
77,215,333
6,260,154
Get only children folders i.e. exclude current folder using glob.glob * pattern search
<p>This is how my directory structure looks like:</p> <pre><code>&lt;ROOT&gt;/ ├── root.log ├── a/ │ ├── xyz/ │ ├── a_xyz.log ├── b/ │ ├── xyz/ │ └── b_xyz.log ├── c/ │ ├── xyz/ │ └── d/ │ ├── xyz/ │ └── b_xyz.log </code></pre> <p>And this is the piece of code I am using:</p> <pre><code>dirs_where_there_are_logs = { os.path.relpath(os.path.dirname(pth), ROOT) for pth in glob.iglob(f&quot;{ROOT}/**/*.log&quot;, recursive=True) } </code></pre> <p>And this is the output, I am getting:</p> <pre><code>{'.', 'a', 'b', 'c', 'c/d'} </code></pre> <p>But I don't want the <code>glob</code> to include directory in search but only the children directories. This is what the output I need:</p> <pre><code>{'a', 'b', 'c', 'c/d'} </code></pre> <p>Now, now I now I can add <code>if</code> condition to ignore the <code>'.'</code> output, but I want to know is there anything more pythonic which I can use to achieve this.</p> <p>Please let me know if there is any.</p> <p>Edit: Using python 3.8</p>
<python><glob>
2023-10-02 11:47:39
1
1,016
Tony Montana
77,215,313
8,543,025
Count Instances Until Value Repeats
<p>I have a list/array/series of booleans, and I want a list of the same length that contains <code>NaNs</code> wherever there was a <code>False</code> value in the original, and on <code>True</code> indices I want to plug the number of <code>False</code> elements until the next <code>True</code>. If there is no subsequent <code>True</code> than the last &quot;count&quot; should be <code>np.inf</code>.<br /> For example:</p> <pre><code>input: [False, False, True, True, False, False, True, False, True, False , False, False] output: [NaN, NaN, 0, 2, NaN, NaN, 1, NaN, np.inf, NaN, NaN, NaN] </code></pre> <p>Of course, I could iterate over the array/list and count (better to start the iteration from the end in that case). I'm interested in a vectorized implementation.</p>
<python><pandas><numpy><vectorization>
2023-10-02 11:45:01
1
593
Jon Nir
77,215,192
2,756,466
Pydantic datetime is stored as String in MongoDB
<p>I am trying to store some date in Mongo collection but it is stored as String in MongoDB.</p> <p>This is the model:</p> <pre><code>def datetime_now() -&gt; datetime: return datetime.now(timezone.utc) class Project(BaseModel): id: uuid.UUID = Field(default_factory=uuid.uuid4, alias=&quot;_id&quot;) title: str = Field(constr(max_length=30)) description: str = Field(constr(max_length=200)) createdAt: datetime = Field(default_factory=datetime_now) updatedAt: datetime = Field(default_factory=datetime_now) createdBy: Optional[str] = None updatedBy: Optional[str] = None archived: Optional[bool] = False deleted: Optional[bool] = False </code></pre> <p>Here, <code>createdAt</code> field is stored as String in MongoDB. But I want createdAt to be stored as mongo Date field.</p> <p><a href="https://i.sstatic.net/PFfOv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PFfOv.png" alt="enter image description here" /></a></p> <p>For reference, please check this image. Here <strong>createdAt</strong> is manually set as Date, while updatedAt is <code>dateAsString</code>.</p> <p>Code for saving into mongo is:</p> <pre><code>@router.post( &quot;/&quot;, response_description=&quot;Create a new project&quot;, status_code=status.HTTP_201_CREATED, response_model=[], ) def create_project( request: Request, project: Project = Body(...), Authorization: Optional[str] = Header(None), ): print(request.state.jwt_content) project = jsonable_encoder(project) project['createdBy'] = request.state.jwt_content['emp_code'] project['updatedBy'] = request.state.jwt_content['emp_code'] new_project = request.app.database[&quot;projects&quot;].insert_one(project) created_project = request.app.database[&quot;projects&quot;].find_one( {&quot;_id&quot;: new_project.inserted_id} ) return created_project </code></pre>
<python><mongodb><pydantic>
2023-10-02 11:22:39
2
7,004
raju
77,215,191
7,074,716
Jetson TX1: No matching distribution found for cplex
<p>I saw a similar question on <a href="https://stackoverflow.com/questions/62437055/no-matching-distribution-found-for-cplex">stackoverflow</a> before, but I couldn't make it run. I am trying to install cplex on a Jetson TX1 that runs Ubuntu 18.</p> <p>When I run</p> <pre><code>$ pip install cplex Collecting cplex Cache entry deserialization failed, entry ignored Could not find a version that satisfies the requirement cplex (from versions: ) No matching distribution found for cplex </code></pre> <p>Here is what I get when I run the python commands:</p> <pre><code>$ which python /home/ubuntu/c4aarch64_installer/bin/python $ python3 --version (same for python --version) Python 3.7.2 $ python -c &quot;import sys; print(sys.path)&quot; ['', '/opt/ros/melodic/lib/python2.7/dist-packages', '/home/ubuntu/c4aarch64_installer/lib/python37.zip', '/home/ubuntu/c4aarch64_installer/lib/python3.7', '/home/ubuntu/c4aarch64_installer/lib/python3.7/lib-dynload', '/home/ubuntu/c4aarch64_installer/lib/python3.7/site-packages'] $ echo $PYTHONPATH /opt/ros/melodic/lib/python2.7/dist-packages </code></pre> <p>I downloaded the cplex-22.1.1.1-cp311-cp311-manylinux1_x86_64.whl, unpacked it, and then moved cplex folder from cplex-22.1.1.1/cplex-22.1.1.1.data/purelib over to the Jetson TX1 $PYTHONPATH location.</p> <p>Then I ran:</p> <pre><code>$ python3 $ &gt;&gt;&gt; import cplex </code></pre> <p>I got:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/home/ubuntu/cplex-22.1.1.1/cplex-22.1.1.1.data/purelib/cplex/__init__.py&quot;, line 44, in &lt;module&gt; from .aborter import Aborter File &quot;/home/ubuntu/cplex-22.1.1.1/cplex-22.1.1.1.data/purelib/cplex/aborter.py&quot;, line 13, in &lt;module&gt; from ._internal import _procedural as _proc File &quot;/home/ubuntu/cplex-22.1.1.1/cplex-22.1.1.1.data/purelib/cplex/_internal/__init__.py&quot;, line 20, in &lt;module&gt; from . import _list_array_utils File &quot;/home/ubuntu/cplex-22.1.1.1/cplex-22.1.1.1.data/purelib/cplex/_internal/_list_array_utils.py&quot;, line 14, in &lt;module&gt; from . import _pycplex as CPX File &quot;/home/ubuntu/cplex-22.1.1.1/cplex-22.1.1.1.data/purelib/cplex/_internal/_pycplex.py&quot;, line 13, in &lt;module&gt; from . import _pycplex_platform File &quot;/home/ubuntu/cplex-22.1.1.1/cplex-22.1.1.1.data/purelib/cplex/_internal/_pycplex_platform.py&quot;, line 22, in &lt;module&gt; from cplex._internal.py37_cplex2211 import * ModuleNotFoundError: No module named 'cplex._internal.py37_cplex2211' </code></pre> <p>How do I resolve this?</p> <p><strong>EDIT</strong>: I uninstalled ROS and set the python path to /home/ubuntu/c4aarch64_installer/lib/python3.7/site-packages . Not sure if this was a correct move.</p>
<python><installation><cplex>
2023-10-02 11:22:34
0
825
Curious
77,215,176
13,793,478
How to change app.py variable with HTML button?
<p>How do I add or subtract 1 from the variable num ( in flask route) with an HTML button?</p> <pre><code>@app.route('/') def note(): num = 1 return render_template('home.html', num=num) </code></pre>
<python><flask>
2023-10-02 11:19:22
1
514
Mt Khalifa
77,215,129
5,131,139
Python Authentication Issue When Modularizing Tableau API
<p>I have the following Python code that successfully authenticates and retrieves data using the Tableau API:</p> <pre><code># Original Code def get_all_client_users(client): client_users = [] tableau_auth = TSC.TableauAuth( os.getenv('tableau_username'), os.getenv('tableau_pass'), client) server = TSC.Server(os.getenv('tableau_server_url'), use_server_version=True) with server.auth.sign_in(tableau_auth): site_users, pagination_item = server.users.get() for user in site_users: client_users.append(user) return client_users </code></pre> <p>To make the code more modular, I decided to split the authentication process into a separate function as follows:</p> <pre><code>def get_all_client_users(client): client_users = [] server = utils.get_tableau_server_controller(client) site_users, pagination_item = server.users.get() for user in site_users: client_users.append(user) return client_users </code></pre> <p>And in the utils.py module.</p> <pre><code>def get_tableau_server_controller(client): tableau_auth = TSC.TableauAuth(os.getenv('tableau_username'), os.getenv('tableau_pass'), client) server = TSC.Server(os.getenv('tableau_server_url'), use_server_version=True) with server.auth.sign_in(tableau_auth): return server </code></pre> <p>Issue:</p> <p>After modularizing the code, the authentication process no longer works as expected. Getting an exception: <code>Missing site ID. You must sign in first.</code></p> <p>I am not able to understand what can be different for the object when trying to use in the same block and accepting the object from a different function and using the same.</p> <p>Feels like I am missing out on an important Python concept because of which I am not able to understand the issue.</p> <p>Can someone guide me in identifying the issue, please?</p>
<python><tableau-api>
2023-10-02 11:12:12
2
1,429
AnandShiva
77,215,107
22,400,527
ImportError: cannot import name 'url_decode' from 'werkzeug.urls'
<p>I am building a webapp using Flask. I imported the <code>flask-login</code> library to handle user login. But it shows an ImportError.</p> <p>Below is my folder structure:</p> <pre><code>&gt;flask_blog1 &gt;flaskblog &gt;static &gt;templates &gt;__init__.py &gt;forms.py &gt;models.py &gt;routes.py &gt;instance &gt;site.db &gt;venv &gt;requirements.txt &gt;run.py </code></pre> <p>My <code>run.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from flaskblog import app if __name__ == &quot;__main__&quot;: app.run(debug=True) </code></pre> <p>My <code>__init__.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager app = Flask(__name__) app.config[&quot;SECRET_KEY&quot;] = &quot;5791628bb0b13ce0c676dfde280ba245&quot; app.config[&quot;SQLALCHEMY_DATABASE_URI&quot;] = &quot;sqlite:///site.db&quot; db = SQLAlchemy(app) bcrypt = Bcrypt(app) login_manager = LoginManager(app) from flaskblog import routes </code></pre> <p>My <code>models.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime # from .extensions import db from flaskblog import db, login_manager from flask_login import UserMixin @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) image_file = db.Column(db.String(20), nullable=False, default=&quot;default.jpg&quot;) password = db.Column(db.String(60), nullable=False) posts = db.relationship(&quot;Post&quot;, backref=&quot;author&quot;, lazy=True) def __repr__(self): return f&quot;User('{self.username}', '{self.email}', '{self.image_file}')&quot; class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey(&quot;user.id&quot;), nullable=False) def __repr__(self): return f&quot;Post('{self.title}', '{self.date_posted}')&quot; </code></pre> <p>My <code>routes.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from flask import render_template, flash, redirect, url_for from flaskblog import app, db, bcrypt from flaskblog.forms import RegistrationForm, LoginForm from flaskblog.models import User, Post from flask_login import login_user posts = [ { &quot;author&quot;: &quot;Ashutosh Chapagain&quot;, &quot;title&quot;: &quot;Blog Post 1&quot;, &quot;content&quot;: &quot;First Post Content&quot;, &quot;date_posted&quot;: &quot;October 1, 2023&quot;, }, { &quot;author&quot;: &quot;Ash Dhakal&quot;, &quot;title&quot;: &quot;Blog Post 2&quot;, &quot;content&quot;: &quot;Second Post Content&quot;, &quot;date_posted&quot;: &quot;October 2, 2023&quot;, }, ] @app.route(&quot;/&quot;) @app.route(&quot;/home&quot;) def home(): return render_template(&quot;home.html&quot;, posts=posts) @app.route(&quot;/about&quot;) def about(): return render_template(&quot;about.html&quot;, title=&quot;About&quot;) @app.route(&quot;/register&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;]) def register(): form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode( &quot;utf-8&quot; ) user = User( username=form.username.data, email=form.email.data, password=hashed_password ) db.session.add(user) db.session.commit() flash(f&quot;Your account has been created! You are now able to log in!&quot;, &quot;success&quot;) return redirect(url_for(&quot;login&quot;)) return render_template(&quot;register.html&quot;, title=&quot;Register&quot;, form=form) @app.route(&quot;/login&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;]) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) return redirect(url_for(&quot;home&quot;)) else: flash(&quot;Login Unsuccessful. Please check email and password&quot;, &quot;danger&quot;) return render_template(&quot;login.html&quot;, title=&quot;Login&quot;, form=form) </code></pre> <p>My <code>forms.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from flaskblog.models import User class RegistrationForm(FlaskForm): username = StringField( &quot;Username&quot;, validators=[DataRequired(), Length(min=2, max=20)] ) email = StringField(&quot;Email&quot;, validators=[DataRequired(), Email()]) password = PasswordField(&quot;Password&quot;, validators=[DataRequired()]) confirm_password = PasswordField( &quot;Confirm Password&quot;, validators=[DataRequired(), EqualTo(&quot;password&quot;)] ) submit = SubmitField(&quot;Sign Up&quot;) def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if user: raise ValidationError( &quot;That username is taken. Please choose a different one.&quot; ) def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError(&quot;That email is taken. Please choose a different one.&quot;) class LoginForm(FlaskForm): email = StringField(&quot;Email&quot;, validators=[DataRequired(), Email()]) password = PasswordField(&quot;Password&quot;, validators=[DataRequired()]) remember = BooleanField(&quot;Remember Me&quot;) submit = SubmitField(&quot;Login&quot;) </code></pre> <p>The exact error is:</p> <pre class="lang-bash prettyprint-override"><code>(venv) asu@asu-Lenovo-Legion-5-15ARH05:/media/asu/Data/Projects/flask_blog1$ python3 run.py Traceback (most recent call last): File &quot;/media/asu/Data/Projects/flask_blog1/run.py&quot;, line 1, in &lt;module&gt; from flaskblog import app File &quot;/media/asu/Data/Projects/flask_blog1/flaskblog/__init__.py&quot;, line 4, in &lt;module&gt; from flask_login import LoginManager File &quot;/media/asu/Data/Projects/flask_blog1/venv/lib/python3.10/site-packages/flask_login/__init__.py&quot;, line 12, in &lt;module&gt; from .login_manager import LoginManager File &quot;/media/asu/Data/Projects/flask_blog1/venv/lib/python3.10/site-packages/flask_login/login_manager.py&quot;, line 33, in &lt;module&gt; from .utils import _create_identifier File &quot;/media/asu/Data/Projects/flask_blog1/venv/lib/python3.10/site-packages/flask_login/utils.py&quot;, line 14, in &lt;module&gt; from werkzeug.urls import url_decode ImportError: cannot import name 'url_decode' from 'werkzeug.urls' (/media/asu/Data/Projects/flask_blog1/venv/lib/python3.10/site-packages/werkzeug/urls.py) </code></pre>
<python><flask><importerror><flask-login><werkzeug>
2023-10-02 11:07:45
6
329
Ashutosh Chapagain
77,214,878
7,695,845
How to add type hints for a dictionary that maps a class to an instance of that class?
<p>I have a dictionary, <code>foo</code>, that maps a type (class) to an instance of that type:</p> <pre class="lang-py prettyprint-override"><code>class Demo: pass foo = { int: 5, str: &quot;Hi&quot;, Demo: Demo() } </code></pre> <p>How can I add type hints to this variable to allow type checkers such as <code>mypy</code> or <code>pyright</code> to make sure this variable's contents are correct?</p> <p>I tried to use a type variable:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar T = TypeVar(&quot;T&quot;) class Demo: pass foo: dict[type[T], T] = { int: 5, str: &quot;Hi&quot;, Demo: Demo() } </code></pre> <p>But <code>pyright</code> simply complains: <code>Type variable &quot;T&quot; has no meaning in this context</code>. How can I annotate this variable correctly?</p> <p><strong>Edit:</strong></p> <p>Here's my use case, which I find hard to type hint. I have a singleton metaclass similar to the one discussed <a href="https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python">here</a>:</p> <pre class="lang-py prettyprint-override"><code>from typing import ClassVar class Singleton(type): _instances: ClassVar[dict[type[?], ?]] = {} def __call__(cls, *args, **kwargs) -&gt; ?: instance = cls._instances.get(cls) if instance is None: instance = cls._instances[cls] = super().__call__(*args, **kwargs) return instance name = cls.__name__ raise RuntimeError( f&quot;{name} already created. use {name}.get() to get the {name} instance.&quot; ) def get(cls) -&gt; ? | None: return cls._instances.get(cls) </code></pre> <p>I found, in general, that type hinting this metaclass is harder than it should be. I can't understand how to add type hints to the attributes and methods of this metaclass in a way that satisfies the type checker and reflects my intentions.</p>
<python><mypy><python-typing>
2023-10-02 10:27:01
2
1,420
Shai Avr
77,214,861
11,613,489
Cannot export a pandas DataFrame to Excel in Python
<p>I need some help here, please.</p> <p>An excel file needs to be updated, not overwritten. In particular, I need to add data to an Excel file (row by row) from an external data source (data from my own website), which I scraped using a Python script.</p> <p>The following thus represents the excalty I wish to use in my code:</p> <pre><code>import pandas as pd # Initialize an empty DataFrame with column names columns = ['Client', 'Country', 'ID'] data_df = pd.DataFrame(columns=columns) # Simulate data extraction (this represent the data I get from my scrap loop in Python ) data_source = [ {'Client': 'John Doe', 'Country': '@Italy', 'ID': '1234567890'}, {'Client': 'Jane Smith', 'Country': '@San Marino', 'ID': '9876543210'}, ] # Here I loop through my data source/append data to the DataFrame for row_data in data_source: data_df = data_df.append(row_data, ignore_index=True) folder_path = &quot;/foder/user/&quot; file_name = folder_path + &quot;output_file.xlsx&quot; # Pandas Excel excel_writer = pd.ExcelWriter(file_name, engine='xlsxwriter') #DataFrame to Excel data_df.to_excel(excel_writer, sheet_name='Data', index=False) excel_writer.save() </code></pre> <p>When I run the code, I got</p> <blockquote> <p>TypeError: cannot concatenate object of type '&lt;class 'str'&gt;'; only Series and DataFrame objets are valid</p> </blockquote> <p>Root cause:</p> <p>I was investigating more about this error and its suggests that I am trying concatenate a string with an object that is not a string.</p> <p>My question:</p> <p>What coud be the best approach to solve this?</p>
<python><pandas><dataframe>
2023-10-02 10:25:11
0
642
Lorenzo Castagno
77,214,669
458,742
`pip install mysqlclient` fails because `pkg-config --exists mysqlclient` fails
<p>I am trying to <code>pip install mysqlclient</code> on Ubuntu 22.04 but get</p> <pre><code>Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─&gt; [24 lines of output] /bin/sh: 1: pkg-config: not found /bin/sh: 1: pkg-config: not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb </code></pre> <p>As per the comments on <a href="https://stackoverflow.com/questions/76585758/mysqlclient-cannot-install-via-pip-cannot-find-pkg-config-name">this question</a> I did</p> <pre><code>apt-get -y install python3-dev gcc build-essential libmysqlclient-dev </code></pre> <p>note that <code>ls /usr/include/mysql/</code> and <code>ls /usr/lib/x86_64-linux-gnu/libmysqlclient.*</code> show that libmysqlclient is installed and mysql headers are in place.</p> <p>What else is missing?</p>
<python><mysql><ubuntu><pip>
2023-10-02 09:54:10
1
33,709
spraff
77,214,638
1,422,096
Import a RGB array into a PIL image with fromarray
<p>I have a RGB array that I would like to import in <code>PIL</code> with <code>fromarray</code> and save to disk:</p> <pre><code>import numpy as np from PIL import Image from PIL.PngImagePlugin import PngInfo a = np.array([[[255, 0, 0], [0, 255, 0]], # Red Green [[0, 0, 255], [0, 0, 0]]]) # Blue Black img = Image.fromarray(a, mode=&quot;RGB&quot;) metadata = PngInfo() # I need to add metadata, thus the use of Pillow and **not cv2** metadata.add_text(&quot;key&quot;, &quot;value&quot;) img.save(&quot;test.png&quot;, pnginfo=metadata) </code></pre> <p>But the output image is <code>Red Black Black Black</code> instead of <code>Red Green Blue Black</code>.</p> <p>Why?</p> <p><strong>How to properly import a uint8 RGB array in a PIL object and save it to PNG?</strong></p> <p>NB: Not a duplicate of <a href="https://stackoverflow.com/questions/62739851/convert-rgb-arrays-to-pil-image">convert RGB arrays to PIL image</a>.</p> <p>NB2: I also tried with a RGBA array, but the result is similar (the output image is <code>Red Black Black Black</code> instead of <code>Red Green Blue Black</code>) with:</p> <pre><code>a = np.array([[[255, 0, 0, 255], [0, 255, 0, 255]], # Red Green [[0, 0, 255, 255], [0, 0, 0, 255]]]) # Blue Black </code></pre>
<python><numpy><python-imaging-library>
2023-10-02 09:50:33
1
47,388
Basj
77,214,589
1,432,980
ignore security dependency if environment is set to local or dev
<p>I have this dependency in my REST endpoint definition</p> <pre><code>@api_router.post(path=&quot;/request&quot;) def post_request( request_body: RequestBody, access_token: AccessToken = Security(validate_roles, scopes=[&quot;user.access&quot;]) ) </code></pre> <p>This <code>validate_roles</code> function has its own dependency</p> <pre><code>async def validate_roles( security_roles: SecurityScopes, access_token: AccessToken = Depends(decode_token) ) </code></pre> <p>The thing is that I want to skip this validation when the environment is <code>local</code>, so I won't need to decode the token. <code>validate_roles</code> is function, that I cannot change.</p> <p>What can I do?</p> <p>I tried this</p> <pre><code>async def env_aware_validate_roles(): if settings.ENVIRONMENT.lower() != 'prod': return lambda: AccessToken( roles=[&quot;user.access&quot;], iss=&quot;https://login.microsoftonline.com/&lt;tenant_id&gt;/v2.0&quot;, aud=&quot;&lt;app id&gt;&quot; ) else: return validate_roles Security(env_aware_validate_roles, scopes=[&quot;user.access&quot;]) </code></pre> <p>But it did not work. I also tried to call <code>env_aware_validate_roles()</code> but then I get the error</p> <pre><code>&lt;coroutine object env_aware_validate_roles&gt; is not a callable object </code></pre>
<python><fastapi>
2023-10-02 09:41:25
1
13,485
lapots
77,214,515
11,283,324
How to split a numpy array to 2d array based on postive/neagtive changes
<p>I have a numpy 1D array:</p> <pre><code>import numpy as np arr = np.array([1, 1, 3, -2, -1, 2, 0, 2, 1, 1, -3, -1, 2]) </code></pre> <p>I want split it into another two-dimensional array, based on changes in positive and negative values of array's elements(0 is placed in the range of positive values). But the original order of elements should be maintained.</p> <p>The desired result is:</p> <pre><code>new_arr = [[1, 1, 3], [-2, -1], [2, 0, 2, 1, 1], [-3, -1], [2]] </code></pre>
<python><numpy>
2023-10-02 09:30:01
3
351
Sun Jar
77,214,455
13,618,407
Pytorch CustomDataset TypeError: list indices must be integers or slices, not list
<p>I am facing an error using pytorch custom dataset. The problem is really strange to me because it was working, I didn't change anything on the code. Here is the scenario:</p> <ol> <li><p>After building my deep learning model, I test it by training it in 10 then 100 epochs. It was working fine, but I saw that the model need to be trained with more epoch to get better result.</p> </li> <li><p>So, I changed the number of epochs to 500. My GPU crashed, maybe because I printed the result every 10 epochs, and it runs out of memory (I don't know exactly what was the real problem)</p> </li> <li><p>Now after restarting my GPU, jupiter notebook throw me a server error with status code 500</p> </li> <li><p>I search on internet and found a solution for my jupiter notebook by running the following command: <code>pip install --upgrade nbconvert</code></p> </li> <li><p>After that, the code does not work anymore. I tried to debug it and I find something strange:</p> </li> </ol> <ul> <li>The custom dataset class give me an error below if I put the class in a python file and call it from jupiter notebook <strong>(the parameter idx in the function <strong>getitem</strong> is a list)</strong></li> <li>The custom dataset class work if I put the class directly in the jupiter notebook cell and call it from this jupiter notebook <strong>(the parameter idx in the function <strong>getitem</strong> is an integer)</strong></li> </ul> <p>Thank you in advance for your answer.</p> <p><strong>Here is the custom dataset class:</strong></p> <p><em>put this in src/custom_dataset.py for example</em></p> <pre class="lang-py prettyprint-override"><code>import os from natsort import natsorted from PIL import Image # Let's see if we have an available GPU from datasets import Dataset class LoadPairedDataset(Dataset): def __init__(self, root_dir, transform=None): self.root_dir = root_dir self.transform = transform self.images = os.listdir(root_dir) def __len__(self): return len(self.images) def __getitem__(self, idx): print(idx) img_name = os.path.join(self.root_dir, self.images[idx]) image = Image.open(img_name) if self.transform: image = self.transform(image) return image </code></pre> <p><strong>Here is the code I use to call the custom dataset:</strong></p> <p><em>put this in a jupiter notebook cell</em></p> <pre class="lang-py prettyprint-override"><code># Imports import os from PIL import Image import torch from torch.utils.data import Dataset from torchvision import transforms from src.custom_dataset import LoadPairedDataset # Define your own class LoadFromFolder class CustomImageDataset(Dataset): def __init__(self, root_dir, transform=None): self.root_dir = root_dir self.transform = transform self.images = os.listdir(root_dir) def __len__(self): return len(self.images) def __getitem__(self, idx): print(idx) img_name = os.path.join(self.root_dir, self.images[idx]) image = Image.open(img_name) if self.transform: image = self.transform(image) return image base_path = &quot;../lol-custom&quot; # dataloader = {&quot;train_n&quot;: None, &quot;train_p&quot;: None} transform = transforms.Compose([ transforms.ToTensor() ]) train_data = CustomImageDataset(root_dir=base_path + &quot;/train/low&quot;, transform=transform) dataloader = torch.utils.data.DataLoader( train_data, batch_size=5, sampler=None, num_workers=0 ) # The output will be: # 0 1 2 3 4 from the print(idx) in the __getitem__ function in CustomImageDataset class # torch.Size([5, 3, 400, 600]) from the below print print(next(iter(dataloader)).shape) # This will print 0 1 2 3 4 print(&quot;######### The below throw an error ##############&quot;) train_data = LoadPairedDataset(root_dir=base_path + &quot;/train/low&quot;, transform=transform) dataloader = torch.utils.data.DataLoader( train_data, batch_size=5, sampler=None, num_workers=0 ) # The output will be: # [0, 1, 2, 3, 4] from the print(idx) in the __getitem__ function in CustomImageDataset class # THEN ERROR: TypeError: list indices must be integers or slices, not list print(next(iter(dataloader)).shape) </code></pre> <p>I am using torch 2.01 with python 3.9.18</p> <p><strong>And finally, here is the output and the stacktrace of the error</strong></p> <pre class="lang-py prettyprint-override"><code>0 1 2 3 4 torch.Size([5, 3, 400, 600]) ######### The below throw an error ############## [0, 1, 2, 3, 4] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[1], line 61 52 dataloader = torch.utils.data.DataLoader( 53 train_data, 54 batch_size=5, 55 sampler=None, 56 num_workers=0 57 ) 58 # This output will be: 59 # [0, 1, 2, 3, 4] from the print(idx) in the __getitem__ function in CustomImageDataset class 60 # THEN ERROR: TypeError: list indices must be integers or slices, not list ---&gt; 61 print(next(iter(dataloader)).shape) File ~\anaconda3\envs\mmie\lib\site-packages\torch\utils\data\dataloader.py:633, in _BaseDataLoaderIter.__next__(self) 630 if self._sampler_iter is None: 631 # TODO(https://github.com/pytorch/pytorch/issues/76750) 632 self._reset() # type: ignore[call-arg] --&gt; 633 data = self._next_data() 634 self._num_yielded += 1 635 if self._dataset_kind == _DatasetKind.Iterable and \ 636 self._IterableDataset_len_called is not None and \ 637 self._num_yielded &gt; self._IterableDataset_len_called: File ~\anaconda3\envs\mmie\lib\site-packages\torch\utils\data\dataloader.py:677, in _SingleProcessDataLoaderIter._next_data(self) 675 def _next_data(self): 676 index = self._next_index() # may raise StopIteration --&gt; 677 data = self._dataset_fetcher.fetch(index) # may raise StopIteration 678 if self._pin_memory: 679 data = _utils.pin_memory.pin_memory(data, self._pin_memory_device) File ~\anaconda3\envs\mmie\lib\site-packages\torch\utils\data\_utils\fetch.py:49, in _MapDatasetFetcher.fetch(self, possibly_batched_index) 47 if self.auto_collation: 48 if hasattr(self.dataset, &quot;__getitems__&quot;) and self.dataset.__getitems__: ---&gt; 49 data = self.dataset.__getitems__(possibly_batched_index) 50 else: 51 data = [self.dataset[idx] for idx in possibly_batched_index] File ~\anaconda3\envs\mmie\lib\site-packages\datasets\arrow_dataset.py:2807, in Dataset.__getitems__(self, keys) 2805 def __getitems__(self, keys: List) -&gt; List: 2806 &quot;&quot;&quot;Can be used to get a batch using a list of integers indices.&quot;&quot;&quot; -&gt; 2807 batch = self.__getitem__(keys) 2808 n_examples = len(batch[next(iter(batch))]) 2809 return [{col: array[i] for col, array in batch.items()} for i in range(n_examples)] File ~\Projects\mmie\src\custom_dataset.py:21, in LoadPairedDataset.__getitem__(self, idx) 19 def __getitem__(self, idx): 20 print(idx) ---&gt; 21 img_name = os.path.join(self.root_dir, self.images[idx]) 22 image = Image.open(img_name) 24 if self.transform: TypeError: list indices must be integers or slices, not list </code></pre>
<python><jupyter-notebook><pytorch>
2023-10-02 09:22:26
1
561
stic-lab
77,214,384
13,892,783
Python packaging semantic versioning >= vs. ~= in requirements.txt
<p>I have a general question about handling versions in <code>requirements.txt</code> of my package <code>foo</code>. I cannot decide if <code>&gt;=</code> or <code>~=</code> is better.</p> <ul> <li>assume <code>pandas~=1.3.3</code> in <code>requirements.txt</code> of my package <code>foo</code> <ul> <li>in this case, I can guarantee that tests and code of <code>foo</code> works correctly for <code>pandas</code> patches</li> <li><strong>problem</strong>: if there is a minor (or even major) change to <code>1.4.0</code> in <code>pandas</code>, a third package cannot use <code>foo</code> anymore with <code>pandas==1.4.0</code>. So I have to release <code>foo</code> again with <code>pandas~=1.4.0</code>. This means that I have to release constantly ...</li> </ul> </li> <li>assume <code>pandas&gt;=1.3.3</code> in my <code>requirements.txt</code> of my package <code>foo</code> <ul> <li>I thought the <code>&gt;=</code> could solve the problem. With <code>&gt;=</code>, <code>foo</code> can still be used. But ...</li> <li><strong>problem</strong>: this means that <code>foo</code> can even be used with major changes like <code>pandas==2.1.1</code>. I do not know if <code>foo</code> still works correctly. Probably the tests even fail but I won't notice ...</li> </ul> </li> </ul> <p>I am confused and I do not know what to do.</p> <p>What is best practice?</p> <p>Thanks!</p>
<python><package><semantic-versioning><requirements.txt>
2023-10-02 09:11:49
0
317
PanchoVarallo
77,214,285
5,359,846
Finding partial text match using any in Python
<p>I have a list of string that contains values like this:</p> <ul> <li>'abc_def'</li> <li>'{xyz_abc}'</li> <li>'{www-ABC-zzz}'</li> </ul> <p>I wish to find partial text match in my list using the <code>any</code> keyword:</p> <pre><code>result = any('abc' in w for w in list) </code></pre> <p>How can I find all the matching while ignoring upper case of lower case and yet find partial text match?</p>
<python>
2023-10-02 08:51:13
1
1,838
Tal Angel
77,214,118
8,947,333
InvalidRequestError when reading view but not SQL query
<p>I have an SQLAlchemy engine (<code>type(engine)</code> outputs <code>&lt;class 'sqlalchemy.engine.base.Engine'&gt;</code>), when I run this snippet I get an error:</p> <pre><code>with engine.connect() as connexion: pd.read_sql_table(&quot;MY_VIEW&quot;, connexion, schema=&quot;abc&quot;) Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 2, in &lt;module&gt; File &quot;c:\my_project\.venv\lib\site-packages\pandas\io\sql.py&quot;, line 340, in read_sql_table table = pandas_sql.read_table( File &quot;c:\my_project\.venv\lib\site-packages\pandas\io\sql.py&quot;, line 1627, in read_table self.meta.reflect(bind=self.con, only=[table_name]) File &quot;c:\my_project\.venv\lib\site-packages\sqlalchemy\sql\schema.py&quot;, line 5530, in reflect raise exc.InvalidRequestError( sqlalchemy.exc.InvalidRequestError: Could not reflect: requested table(s) not available in Engine(mssql+pyodbc://username:***@myserver.database.windows.net,1433/mydb?driver=ODBC+DRIVER+17+for+SQL+Server) schema 'abc': (MY_VIEW) </code></pre> <p>But when I try to query all lines, this works:</p> <pre><code>pd.read_sql_query(&quot;select * from [abc].[MY_VIEW]&quot;, engine) [...] [4742 rows x 18 columns] </code></pre> <p>As per this answer (<a href="https://stackoverflow.com/a/60906045/8947333">https://stackoverflow.com/a/60906045/8947333</a>) I tried to put the view name in lowercase, but it did not change anything.</p> <p>I can however request any table that is not a view with <code>pd.read_sql_table</code>, but this method fails with any view on any schema.</p> <p>Do you have an idea on how I can solve this?</p>
<python><sqlalchemy>
2023-10-02 08:25:07
0
3,008
Be Chiller Too
77,214,056
9,389,353
Python Requests API 403 Error with same HTTP Request
<p>I am attempting to fetch an API using Python requests.</p> <p>The API is documented here: <a href="https://consumerdatastandardsaustralia.github.io/standards/#get-data-holder-brands" rel="nofollow noreferrer">https://consumerdatastandardsaustralia.github.io/standards/#get-data-holder-brands</a></p> <p>The following request works on reqbin: <a href="https://i.sstatic.net/fZLec.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fZLec.png" alt="screenshot" /></a></p> <p>I have the following Python code</p> <pre class="lang-py prettyprint-override"><code>import requests r = requests.get('https://api.cdr.gov.au/cdr-register/v1/energy/data-holders/brands/summary', headers={&quot;x-v&quot;:&quot;1&quot;}) print(r.content) </code></pre> <p>This returns a 403 error, I'm not sure what other difference there could be between the two requests which could result in such an error.</p> <pre class="lang-html prettyprint-override"><code>b'&lt;html&gt;\r\n&lt;head&gt;&lt;title&gt;403 Forbidden&lt;/title&gt;&lt;/head&gt;\r\n&lt;body&gt;\r\n&lt;center&gt;&lt;h1&gt;403 Forbidden&lt;/h1&gt;&lt;/center&gt;\r\n&lt;hr&gt;&lt;center&gt;Microsoft-Azure-Application-Gateway/v2&lt;/center&gt;\r\n&lt;/body&gt;\r\n&lt;/html&gt;\r\n' </code></pre> <p>I thought it could have to do with the Authorization header for the API which wants a RFC6750 token however that doesn't explain why the reqbin works without one.</p>
<python><python-requests>
2023-10-02 08:12:46
2
987
Luke Prior
77,213,856
1,422,096
How to start the Windows screensaver from Python?
<p><strong>How to launch the Windows screensaver from Python ?</strong></p> <p>I have tried methods like</p> <pre><code>import subprocess subprocess.Popen(&quot;C:\Windows\System32\scrnsave.scr&quot;) </code></pre> <p>it starts a screensaver, but it doesn't start the screensaver that has been configured in the Windows control panel.</p> <p>PS: there are a few questions tagged <code>[screensaver]</code> + <code>[windows]</code> + <code>[python]</code>, but I haven't found a question+answer specific to Windows with Python, so here is Q+A post.</p>
<python><windows><screensaver>
2023-10-02 07:33:07
1
47,388
Basj
77,213,826
458,742
Dockerfile from ubuntu:22.04 apt unable to locate package python3
<p>When I <code>docker build</code> this:</p> <pre><code>FROM ubuntu:22.04 RUN apt-get install -y python3 </code></pre> <p>I get</p> <pre><code>Step 1/2 : FROM ubuntu:22.04 ---&gt; c6b84b685f35 Step 2/2 : RUN apt-get install -y python3 ---&gt; Running in d1f4eff8d024 Reading package lists... Building dependency tree... Reading state information... E: Unable to locate package python3 </code></pre> <p>What's wrong?</p>
<python><docker><ubuntu><apt>
2023-10-02 07:27:04
1
33,709
spraff
77,213,592
2,696,565
Plotly-Dash box plot inside Card component
<p>I have a box plot inside a Plotly-Dash Card component and then when I change the dropdown, I get another card added inside the already existing card. How can I have the existing figure update instead of adding a new card please.</p> <pre><code>from dash import Dash import dash_bootstrap_components as dbc from dash_bootstrap_templates import load_figure_template from dash.dependencies import Input, Output from dash import Dash, html, dcc import numpy as np import plotly.graph_objects as go def render(app: Dash): @app.callback(Output(&quot;box-plot&quot;, &quot;children&quot;),Input(&quot;country-dropdown&quot;, &quot;value&quot;)) def update_boxplot(country: str) -&gt; html.Div: fig = go.Figure(data=[go.Box(y=np.random.randn(50) - 1),go.Box(y=np.random.randn(50) + 1)]) return html.Div(dbc.Card([dbc.CardHeader(&quot;Box plot&quot;), dbc.CardBody(dcc.Graph(figure=fig), id=&quot;box-plot&quot;)])) return html.Div(id=&quot;box-plot&quot;) def getFigureRow(app:Dash): return dbc.Row([dbc.Col([render(app)], width=12)], align='center') def getDropdownRow(app: Dash): return html.Div( children=[dcc.Dropdown(id=&quot;country-dropdown&quot;,options=[&quot;DE&quot;, &quot;FR&quot;, &quot;ES&quot;],value=&quot;DE&quot;,multi=False)] ) def create_layout(app: Dash): print(&quot;create_layout(...) called&quot;) return html.Div([ html.H1(app.title), dbc.Tabs([ dbc.Tab( dbc.Card( dbc.CardBody([ getDropdownRow(app), getFigureRow(app), ]), body=True), label=&quot;Visualize&quot;) ]) ]) if __name__ == &quot;__main__&quot;: app = Dash(external_stylesheets=[dbc.themes.DARKLY]) load_figure_template(&quot;darkly&quot;) app.title = &quot;Dummy&quot; app.layout = create_layout(app) app.run(debug=True) </code></pre>
<python><plotly><plotly-dash>
2023-10-02 06:32:36
0
629
user2696565
77,213,450
6,101,713
Scale vertical (z) axis of 3D surface plot with plot_surface
<p>How can I scale the Z-axis of a surface plot in matplotlib? Take the following example dataset and plot.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linspace(-5, 5, 50) y = np.linspace(-5, 5, 50) x, y = np.meshgrid(x, y) # Generate a 3D surface z = np.exp(-0.1*x**2 - 0.1*y**2) fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111, projection='3d') # Create the surface plot surf = ax.plot_surface(x, y, z, cmap='plasma') plt.show() </code></pre> <p><a href="https://i.sstatic.net/D0cOPl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/D0cOPl.png" alt="3d plot" /></a></p> <p>And I want to scale it so it looks like the below plot (which I have done by adjusting the axis limits) but with with the z-axis limits still between 0 and 1. Is this possible? I couldn't find anything in the docs about how to do this. For illustration the <a href="https://www.rdocumentation.org/packages/graphics/versions/3.6.2/topics/persp" rel="nofollow noreferrer"><code>persp</code></a> function in R has the <code>expand</code> argument that does exactly what I want to do.</p> <pre><code>fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111, projection='3d') # Create the surface plot surf = ax.plot_surface(x, y, z, cmap='plasma') ax.set_zlim([0, 2.5]) plt.show() </code></pre> <p><a href="https://i.sstatic.net/Wpghkl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Wpghkl.png" alt="Scaled 3d plot" /></a></p> <hr /> <h2>Update</h2> <p>For clarification, here's an example of exactly what I'm trying to do using R code. I'm trying to adjust the z-axis aspect ratio. With the <code>persp</code> function in R we can just use the `expand argument to do this. For example:</p> <pre><code># Generate synthetic data for demonstration purposes x &lt;- seq(-5, 5, length.out = 50) y &lt;- seq(-5, 5, length.out = 50) z &lt;- matrix(0, length(x), length(y)) # Generate a Gaussian surface for(i in 1:length(x)) { for(j in 1:length(y)) { z[i, j] &lt;- exp(-0.1 * x[i]^2 - 0.1 * y[j]^2) } } nrz &lt;- nrow(z) ncz &lt;- ncol(z) # Create a function interpolating colors in the range of specified colors jet.colors &lt;- colorRampPalette(c(&quot;#0d0887&quot;, &quot;#cc4678&quot;, &quot;#f0f921&quot;)) # Generate the desired number of colors from this palette nbcol &lt;- 100 color &lt;- jet.colors(nbcol) # Compute the z-value at the facet centres zfacet &lt;- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz] # Recode facet z-values into color indices facetcol &lt;- cut(zfacet, nbcol) </code></pre> <h3>expand = 1.0</h3> <pre><code>persp(x, y, z, theta = 45, phi = 30, expand = 1.0, col = color[facetcol]) </code></pre> <p><a href="https://i.sstatic.net/hIeOFl.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hIeOFl.jpg" alt="expand = 1.0" /></a></p> <h3>expand = 0.3</h3> <pre><code>persp(x, y, z, theta = 45, phi = 30, expand = 0.3, col = color[facetcol]) </code></pre> <p><a href="https://i.sstatic.net/GuPQyl.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GuPQyl.jpg" alt="expand = 0.3" /></a></p>
<python><matplotlib><matplotlib-3d>
2023-10-02 05:53:32
2
1,346
Muon
77,213,190
815,110
Constructing next-occuring python datetime from only month and day
<p>I have a string representing just the month and day (format: <code>&quot;%m/%d&quot;</code>, e.g. &quot;12/25&quot;) and I would like to construct a datetime for the next occurrence of it, relative to today. Ideally a function like:</p> <pre><code>datetime.next_strptime(&quot;12/25&quot;, &quot;%m/%d&quot;) # returns the 2023-12-25 datetime object, since I'm posting this question before 2023-12-25 </code></pre> <p>I know I can write a few lines like:</p> <pre><code># begins as 1900-12-25 since year is absnet date = datetime.strptime(&quot;12/25&quot;, &quot;%m/%d&quot;) # set to 2023-12-25 or current year date.replace(year=date.today().year) # if today is actually past 2023-12-25, we'll increment it by a year if date &lt; date.today(): date = date + relativedelta(years=1) </code></pre> <p>besides being more lines, I worry about having to write in more edge cases (this code doesn't work with <code>&quot;2/29&quot;</code> for instance, as 1900 and date.today().year are possibly not leap years and would raise an exception</p>
<python><datetime>
2023-10-02 04:08:30
0
1,570
Nathan
77,213,101
10,461,632
`open` command not passing `--args`
<p>I'm trying to start a pyinstaller executable with the <code>open</code> command on my Mac, but I need to pass an argument identifying the port to open.</p> <p>When I run <code>./app 5000</code>, the executable opens correctly.</p> <p>When I run <code>open app --args 5000</code>, the executable doesn't recognize the argument and an error is thrown (<code>IndexError: list index out of range</code>).</p> <p>In my executable, I'm trying to access the argument like this: <code>app_config = {&quot;port&quot;: sys.argv[1]}</code>.</p> <p>How can I use the <code>open</code> command and pass an argument to my executable?</p>
<python><macos>
2023-10-02 03:25:03
1
788
Simon1
77,213,099
14,345,989
Given a list of shapely polygons generate a tree of which polygon contains which other polygons with no repeats
<p>I have a list of shapely polygons, none of which overlap. I intend to do certain operations based on their level of nesting within other polygons (union or difference) to generate one final multipolygon that represents the entire set.</p> <p>As a simple example, see the image below in which four polygons labeled A-D are nested. I would want to difference B and D from A, and union C. Note that the level of nesting flip-flops it between adding and removing from the main polygon. <a href="https://i.sstatic.net/BKdyQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BKdyQ.png" alt="enter image description here" /></a></p> <p>The main problem is to generate a tree representing which polygons are nested within which other polygons, without repeats (A contains B, but not C). My current method involves a lot of looping:</p> <ol> <li>Loop through all polygons while checking if the current polygon is contained within any other polygons. If a polygon is not contained, then add it to a list.</li> <li>The &quot;not contained&quot; polygons are the outermost members of the current layer (children of the previous layer). Remove them from the polygon list one at a time and search again (depth-first).</li> <li>Recursively repeat until no polygons remain in the original list</li> </ol> <p>Example of what I've tried, but the recursion is not quite working (contains five polygons in output instead of four):</p> <pre><code>from shapely.geometry import Polygon from shapely import contains import numpy as np class Branch: def __init__(self, root): self.root = root self.children = [] def add_child(self, child): self.children.append(child) def add_children(self, children): for child in children: self.add_child(child) def __repr__(self) -&gt; str: return f&quot;{self.root}:{self.children}&quot; def get_not_contained(polygons): # Find which polygons are not contained within any other polygons not_contained = [] for i in range(len(polygons)): con = False for j in range(len(polygons)): # Don't check against itself if polygons[i] == polygons[j]: continue if contains(polygons[j], polygons[i]): con = True break if not con: not_contained.append(polygons[i]) return not_contained # a box coords = np.array([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]) # several boxes, some of which are nested (nesting labels match the example image) polygons = [ Polygon(coords), # D Polygon(coords * 5 - 1), # A Polygon(coords + 2), # B Polygon(coords * 0.5 + 2.25), # C ] def get_NC_tree(polygons): out = [] NC = get_not_contained(polygons) for poly in NC: brnch = Branch(poly) out.append(brnch) tmp = polygons try: tmp.remove(poly) except ValueError: pass brnch.add_children(get_NC_tree(tmp)) return out print(get_NC_tree(polygons)) </code></pre> <p>I'm new to using shapely, so please let me know if there's an easier way to do this.</p>
<python><recursion><polygon>
2023-10-02 03:23:49
1
886
Mandias
77,213,053
15,233,792
Why did Flask start failing with "ImportError: cannot import name 'url_quote' from 'werkzeug.urls'"?
<p>Environment:</p> <pre class="lang-none prettyprint-override"><code>Python 3.10.11 Flask==2.2.2 </code></pre> <p>I run my Flask backend code in docker container, with BASE Image: <code>FROM pytorch/pytorch:2.0.1-cuda11.7-cudnn8-runtime</code></p> <p>But when I run the pytest with version <code>pytest 7.4.2</code>,</p> <pre class="lang-none prettyprint-override"><code>pip install pytest pytest </code></pre> <p>it raised an Error, with logs:</p> <pre class="lang-none prettyprint-override"><code>==================================== ERRORS ==================================== _____________ ERROR collecting tests/test_fiftyone_utils_utils.py ______________ ImportError while importing test module '/builds/kw/data-auto-analysis-toolkit-backend/tests/test_fiftyone_utils_utils.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/conda/lib/python3.10/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_fiftyone_utils_utils.py:2: in &lt;module&gt; import daat # noqa: F401 /opt/conda/lib/python3.10/site-packages/daat-1.0.0-py3.10.egg/daat/__init__.py:1: in &lt;module&gt; from daat.app import app /opt/conda/lib/python3.10/site-packages/daat-1.0.0-py3.10.egg/daat/app/__init__.py:6: in &lt;module&gt; from flask import Flask, jsonify, request /opt/conda/lib/python3.10/site-packages/flask/__init__.py:5: in &lt;module&gt; from .app import Flask as Flask /opt/conda/lib/python3.10/site-packages/flask/app.py:30: in &lt;module&gt; from werkzeug.urls import url_quote E ImportError: cannot import name 'url_quote' from 'werkzeug.urls' (/opt/conda/lib/python3.10/site-packages/werkzeug/urls.py) </code></pre> <p>My codes works well when I directly run it with <code>python run.py</code></p> <p><code>run.py</code> shown below</p> <pre><code>from daat import app app.run(host='0.0.0.0') </code></pre> <p>I guess it should be the pytest versions issue, because it used to work well without changing any related code, and I use <code>pip install pytest</code> without defined a specific version.</p> <p>And my backend runs well without pytest.</p>
<python><flask><pytest><werkzeug>
2023-10-02 03:02:00
6
2,713
stevezkw
77,213,003
11,737,958
How to filter a numeric value with spaces using regex in python
<p>I am new to python and using version 3.8. I use regex to filter strings, special characters and numbers from a string. There are spaces in between characters and numbers and i try to filter them. I am able to filter the string upto first number. I am unable to filter the string till the last number. Any help would be much appreciated. Thanks in advance!</p> <pre><code>s = 'abc (efg): 2.1 296.2' s1 = re.search(r'abc(\s+)\(efg\):(\s+)(\d+)',s) print(s1.group()) o/p abc (efg): 2 s = 'abc (efg): 2.1 296.2' s1 = re.search(r'abc(\s+)\(efg\):(\s+)(\d+)(\s+)(\d+)',s) print(s1.group()) o/p print(s1.group()) AttributeError: 'NoneType' object has no attribute 'group' </code></pre>
<python><regex>
2023-10-02 02:35:59
4
362
Kishan
77,212,868
11,933,886
Trying to get rid of a circular Python dependency
<p>I have an application (telegram python bot) with a lot of CONSTANTS in it, so I did a bit of a structure here:</p> <pre><code>bot/ api.py bot.py constants.py functions.py keyboards.py </code></pre> <p>Main execution file is: <code>bot.py</code></p> <p>Below is the imports from those files:</p> <pre class="lang-py prettyprint-override"><code># bot.py import os, logging, re import constants as c from telegram import Update from telegram.ext import filters, ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, ConversationHandler, CallbackQueryHandler from keyboards import START_KEYBOARD, INFO_KEYBOARD, SETTINGS_KEYBOARD, PUNCH_KEYBOARD import api as a import functions as f </code></pre> <pre class="lang-py prettyprint-override"><code># api.py import requests, openai import constants as c import functions as f </code></pre> <pre class="lang-py prettyprint-override"><code># constants.py import os import datetime as d import functions as f </code></pre> <pre class="lang-py prettyprint-override"><code># functions.py import api as a import constants as c from typing import Literal from datetime import datetime from telegram import Update </code></pre> <pre class="lang-py prettyprint-override"><code># keyboards.py from telegram import ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton import constants as c </code></pre> <pre><code>bot_1 | Traceback (most recent call last): bot_1 | File &quot;/opt/app/bot.py&quot;, line 2, in &lt;module&gt; bot_1 | import constants as c bot_1 | File &quot;/opt/app/constants.py&quot;, line 3, in &lt;module&gt; bot_1 | import functions as f bot_1 | File &quot;/opt/app/functions.py&quot;, line 1, in &lt;module&gt; bot_1 | import api as a bot_1 | File &quot;/opt/app/api.py&quot;, line 58, in &lt;module&gt; bot_1 | def req_tes_headers(host=c.TES_OAUTH_HOST ,token=''): bot_1 | ^^^^^^^^^^^^^^^^ bot_1 | AttributeError: partially initialized module 'constants' has no attribute 'TES_OAUTH_HOST' (most likely due to a circular import) </code></pre> <p>Why am I getting this error?</p>
<python><python-3.x><circular-dependency>
2023-10-02 01:26:50
2
361
Alex Lebedev
77,212,767
1,056,563
How can the options set on a Spark DataFrameReader be viewed?
<p>The <code>Spark</code> <code>DataFrameReader</code> has an <code>options()</code> method: but it is a <em>setter</em>: ie it is used to impose options on the <em>Reader</em></p> <pre><code> datasource_options = {'driver': 'com.microsoft.sqlserver.jdbc.SQLServerDriver', 'timestampFormat': 'yyyy-MM-dd HH:mm:ss.SSSSSS'} df_reader = ( self.spark.read.option(&quot;kustoCluster&quot;, self.data_source.cluster) .option(&quot;kustoDatabase&quot;, self.data_source.database) .option(&quot;kustoQuery&quot;, resource.query) .options(**datasource_options) ) </code></pre> <p>I would like to confirm the options that have been set into the <code>Reader</code> but have not found a method to do so. Does it exist?</p>
<python><apache-spark><pyspark>
2023-10-02 00:26:08
1
63,891
WestCoastProjects
77,212,657
1,115,716
Writing a SpooledTemporaryFile to disk
<p>I am working on a <code>Strawberry</code> API service that accepts documents. I receive files and process them like so:</p> <pre><code>import typing import strawberry from strawberry.file_uploads import Upload @strawberry.input class FolderInput: files: typing.List[Upload] @strawberry.type class Mutation: @strawberry.mutation async def read_file(self, file: Upload) -&gt; str: return (await file.read()).decode(...) </code></pre> <p>According to the API docs: <a href="https://fastapi.tiangolo.com/tutorial/request-files/#file-parameters-with-uploadfile" rel="nofollow noreferrer">https://fastapi.tiangolo.com/tutorial/request-files/#file-parameters-with-uploadfile</a></p> <p>The <code>file</code> parameter has a member attribute of type <code>SpooledTemporaryFile</code> which looks like a <code>tempfile</code>: <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" rel="nofollow noreferrer">https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile</a></p> <p>How do I write that file to disk?</p>
<python><temporary-files>
2023-10-01 23:27:50
0
1,842
easythrees
77,212,579
3,081,328
Determine different seeds for which random shuffling list generates the same output
<p>It is pretty intuitive that when shuffling a small enough collection, results will repeat themselves, even using different seeds each time, as it is just a matter of exhausting all unique combinations.</p> <p>However, I can't find such information in the Python documentation. I am especially curious if there is any formula or algorithm to determine the different seed values for which the output would be identical. Is it possible to somehow forecast or calculate these seeds?</p> <p>At first sight, I couldn't see any pattern or regular offset, and now it intrigues me if it's possible to find one 😁</p> <p>I'm pasting the snippet of the code that I reproduced several times on my machine and within the online REPL.</p> <pre class="lang-py prettyprint-override"><code>import random a = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;] b = list(a) c = list(a) random.seed(0) random.shuffle(a) random.seed(344) random.shuffle(b) random.seed(496) random.shuffle(c) print(a == b == c == [&quot;c&quot;, &quot;b&quot;, &quot;a&quot;, &quot;e&quot;, &quot;d&quot;]) # True </code></pre>
<python><python-3.x><random>
2023-10-01 22:50:41
0
809
Hunter_71
77,212,471
214,179
Resizing Movie Clip with MoviePy leads to SIGKILL on m1 mac
<p>I'm trying to resize a movie clip using moviepy, but I'm getting a sigkill every time. I've run it on two clips, several times, it seems consistent.</p> <pre><code>Process finished with exit code 137 (interrupted by signal 9: SIGKILL) </code></pre> <p>Reading and writing mp4 files. The source file's info says:</p> <pre><code>Dimensions: 1280 × 720 codecs: Timecode, MPEG-4 AAC, H.264 color profile: HD (1-1-1) </code></pre> <p>It's a canon camcorder for the source, if that adds any information.</p> <p>I was able to resize with ffmpeg directly.</p> <pre><code>ffmpeg -i inputfile.MP4 -ss 00:14:09 -vf &quot;scale=iw*0.5:ih*0.5&quot; -c:v libx264 -c:a aac -strict experimental output_video.mp4 </code></pre> <p>I'm on an an M1 mac, 13.2.1, moviepy 1.03</p> <pre><code> with moviepy.editor.VideoFileClip(abs_path) as video: subclip = video.subclip(args.start, args.end) subclip.resize(640, 480) </code></pre>
<python><macos><apple-m1><moviepy>
2023-10-01 21:59:13
0
1,309
ThoughtfulHacking
77,212,373
6,142,743
Scientific notation in Python - extra digits
<p>I have the following very small floating number in Python:</p> <pre><code>fnum = 0.00012345689000007 </code></pre> <p>When I try to convert to a scientific notation, I am not sure where the extra digits after 7 (the last digit) are coming from:</p> <pre><code>print(&quot;%.40e&quot;%fnum) </code></pre> <p>This is the result: '1.2345689000007001204055334664388965393300e-04'</p> <p>I would be happy if someone could explain.</p>
<python><floating-point><scientific-notation>
2023-10-01 21:20:00
0
379
Danny
77,212,120
6,034,925
Plot Imshow on a Torus (lattice with PBC)
<p>Is there any &quot;simple&quot; solution in <code>matplotlib</code> or another Python package to plot a square lattice on a 2d torus (aka lattice with periodic boundary conditions)?</p> <p>Assume i have a simple 2D array</p> <pre><code># ... a = np.random.random((50, 50)) plt.imshow(a) </code></pre> <p><a href="https://i.sstatic.net/wex56.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wex56.png" alt="enter image description here" /></a></p> <p>I would like to wrap this plane into a torus, which can be achieved e.g. with</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D # Generating Torus Mesh angle = np.linspace(0, 2 * np.pi, 100) theta, phi = np.meshgrid(angle, angle) r, R = .25, 1. X = (R + r * np.cos(phi)) * np.cos(theta) Y = (R + r * np.cos(phi)) * np.sin(theta) Z = r * np.sin(phi) fig = plt.figure() ax = fig.add_subplot(projection = '3d') ax.set_xlim3d(-1, 1) ax.set_ylim3d(-1, 1) ax.set_zlim3d(-1, 1) ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1) plt.show() </code></pre> <p><a href="https://i.sstatic.net/pELch.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pELch.png" alt="enter image description here" /></a></p> <p>I thought about encoding somehow the information on <code>X</code> and <code>Y</code> value in a colormap to pass to <code>plot_surface</code>'s option <code>cmap</code>. The colormap shall have each color of the image according to content of array <code>a</code>.</p> <p>Ideas?</p>
<python><matplotlib><plot><mplot3d>
2023-10-01 20:03:04
2
559
opisthofulax
77,211,990
17,896,651
peewee.OperationalError: database is locked on a single Thread using a locker
<p>I get the issue like 1/10000 times.</p> <p>I have this single code to update the value.</p> <p>I have other places used the database but it seems only this code is crashing with database lock, or it just that this once called most often.</p> <pre><code>class InstaPyLimits(object): @staticmethod def update_daily_activity(time): with ActivityTracker_locker: # ActivityTracker.update(activity_time_curr= ActivityTracker.activity_time_curr + int(time)).where(ActivityTracker.date == _datetime.date.today()).execute() ActivityTracker.update( {ActivityTracker.activity_time_curr: ActivityTracker.activity_time_curr + int(time)}).where( ActivityTracker.date == _datetime.date.today()).execute() models.py: db = SqliteDatabase(Settings.stats_conf_database_location) ActivityTracker_locker = threading.Lock() class ActivityTracker(Model): date = DateField(unique=True) activity_time_curr = IntegerField(default=0) # active seconds today activity_time_max = IntegerField() # max active seconds today class Meta: database = db </code></pre> <p>I spent half a day moving and testing, I think it might be in the way I call the update.</p>
<python><database><peewee>
2023-10-01 19:21:46
1
356
Si si
77,211,976
6,115,999
SAWarning error "SELECT statement has a cartesian product" when trying to append to bridging table in many to many relationship
<p>I want to have two tables. One of ideas and another of tags. This relationship should be many to many.</p> <p>I've created a bridging table:</p> <pre><code>tag_idea = db.Table('tag_idea', db.Column('idea_id', db.Integer, db.ForeignKey('idea.id')), db.Column('ideatag_id', db.Integer, db.ForeignKey('idea_tag.id')) ) </code></pre> <p>These are my two models:</p> <pre><code>class Idea(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) idea_name = db.Column(db.String(40), nullable=False) idea = db.Column(db.String(5000), nullable=False) idea_owner = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) idea_category = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False) tags = db.relationship('IdeaTag', secondary=tag_idea, backref='ideas', primaryjoin=tag_idea.c.idea_id==id, secondaryjoin=tag_idea.c.ideatag_id==id) class IdeaTag(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) tag = db.Column(db.String(25), nullable=False) tag_owner = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) </code></pre> <p>so to test this I loaded a test idea into <code>test</code> and a test tag into <code>testtag</code></p> <p>to add to the bridging table I figured I should be able to use:</p> <p><code>idea.tags.append(testtag)</code></p> <p>But I get the following error:</p> <p><code>SAWarning: SELECT statement has a cartesian product between FROM element(s) &quot;tag_idea&quot;, &quot;idea&quot; and FROM element &quot;idea_tag&quot;. Apply join condition(s) between each element to resolve.</code></p> <p>On the surface, I'm not actually entering a SELECT statement so I don't know how to apply a join in the SELECT statement. How do I resolve this?</p>
<python><flask><flask-sqlalchemy>
2023-10-01 19:19:17
2
877
filifunk
77,211,663
14,255,490
Heatmap with sklearn Confusion Matrix issue
<p>I bumped into the following issue:</p> <pre><code>X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25, random_state=42) y_pred = model.predict(X_test) y_pred = (y_pred &gt; 0.5) from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) sns.heatmap(cm, annot=True) </code></pre> <p>produces the following heatmap:</p> <p><a href="https://i.sstatic.net/b1uhQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/b1uhQ.png" alt="enter image description here" /></a></p> <p>problem is that if we print cm, then it shows:</p> <pre><code>[[87 2] [ 2 52]] </code></pre> <p>What did I do wrong that prevents 2 and 52 from being displayed in the heatmap?</p>
<python><matplotlib><seaborn><heatmap>
2023-10-01 17:53:20
0
351
ArtemNovikov
77,211,591
1,008,933
Django cannot run because GDAL is loading wrong libtiff version
<p>I am unable to run Django on my MacOS Ventura. Looking at the error, I think GDAL is unable to load libtiff library.</p> <p>I did some investigation, I do have libtiff installed.</p> <pre><code>% otool -L /opt/homebrew/lib/libgdal.dylib | grep libtiff /opt/homebrew/opt/libtiff/lib/libtiff.6.dylib (compatibility version 7.0.0, current version 7.1.0) </code></pre> <p>If looking at the error, I think its trying to load libtiff.5.dylib, but I have libtiff.6.dylib. How can I get GDAL to load the installed libtiff ?</p> <pre><code>% python manage.py runserver Watching for file changes with StatReloader 2023-10-01 17:14:00,801 INFO Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File &quot;/opt/homebrew/Cellar/python@3.9/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py&quot;, line 980, in _bootstrap_inner self.run() File &quot;/opt/homebrew/Cellar/python@3.9/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py&quot;, line 917, in run self._target(*self._args, **self._kwargs) File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/utils/autoreload.py&quot;, line 54, in wrapper fn(*args, **kwargs) File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/core/management/commands/runserver.py&quot;, line 109, in inner_run autoreload.raise_last_exception() File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/utils/autoreload.py&quot;, line 77, in raise_last_exception raise _exception[1] File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/core/management/__init__.py&quot;, line 337, in execute autoreload.check_errors(django.setup)() File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/utils/autoreload.py&quot;, line 54, in wrapper fn(*args, **kwargs) File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/__init__.py&quot;, line 24, in setup apps.populate(settings.INSTALLED_APPS) File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/apps/registry.py&quot;, line 91, in populate app_config = AppConfig.create(entry) File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/apps/config.py&quot;, line 90, in create module = import_module(entry) File &quot;/opt/homebrew/Cellar/python@3.9/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py&quot;, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1030, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1007, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 986, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 680, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 850, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 228, in _call_with_frames_removed File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/mapwidgets/__init__.py&quot;, line 4, in &lt;module&gt; from .widgets import GooglePointFieldWidget, GooglePointFieldInlineWidget, \ File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/mapwidgets/widgets.py&quot;, line 5, in &lt;module&gt; from django.contrib.gis.forms import BaseGeometryWidget File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/contrib/gis/forms/__init__.py&quot;, line 3, in &lt;module&gt; from .fields import ( # NOQA File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/contrib/gis/forms/fields.py&quot;, line 2, in &lt;module&gt; from django.contrib.gis.gdal import GDALException File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/contrib/gis/gdal/__init__.py&quot;, line 28, in &lt;module&gt; from django.contrib.gis.gdal.datasource import DataSource File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/contrib/gis/gdal/datasource.py&quot;, line 39, in &lt;module&gt; from django.contrib.gis.gdal.driver import Driver File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/contrib/gis/gdal/driver.py&quot;, line 5, in &lt;module&gt; from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/ds.py&quot;, line 9, in &lt;module&gt; from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal File &quot;/Users/myproj/Documents/project/projectdotcom/env_m1/lib/python3.9/site-packages/django/contrib/gis/gdal/libgdal.py&quot;, line 47, in &lt;module&gt; lgdal = CDLL(lib_path) File &quot;/opt/homebrew/Cellar/python@3.9/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ctypes/__init__.py&quot;, line 374, in __init__ self._handle = _dlopen(self._name, mode) OSError: dlopen(/opt/homebrew/lib/libgdal.dylib, 0x0006): Library not loaded: /opt/homebrew/opt/libtiff/lib/libtiff.5.dylib Referenced from: &lt;3FEB9C56-E432-36C6-A940-FC254CC92FAB&gt; /opt/homebrew/Cellar/libgeotiff/1.7.1_1/lib/libgeotiff.5.dylib Reason: tried: '/opt/homebrew/opt/libtiff/lib/libtiff.5.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/libtiff/lib/libtiff.5.dylib' (no such file), '/opt/homebrew/opt/libtiff/lib/libtiff.5.dylib' (no such file), '/usr/local/lib/libtiff.5.dylib' (no such file), '/usr/lib/libtiff.5.dylib' (no such file, not in dyld cache), '/opt/homebrew/Cellar/libtiff/4.6.0/lib/libtiff.5.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/Cellar/libtiff/4.6.0/lib/libtiff.5.dylib' (no such file), '/opt/homebrew/Cellar/libtiff/4.6.0/lib/libtiff.5.dylib' (no such file), '/usr/local/lib/libtiff.5.dylib' (no such file), '/usr/lib/libtiff.5.dylib' (no such file, not in dyld cache) </code></pre>
<python><django><gdal><libtiff>
2023-10-01 17:35:24
2
3,391
Axil
77,211,419
1,128,648
Upload file to google drive using service account using python
<p>I am using below python script to upload files to Google drive.I am using service account to remove any interactive authentication.</p> <pre><code>from googleapiclient.discovery import build from google.oauth2 import service_account from googleapiclient.http import MediaFileUpload scopes = ['https://www.googleapis.com/auth/drive'] gdrive = 'gdrive_cred.json' folder_id = &quot;1Ixxxxxx6xxxxxa3Ir-xxxxxxxx&quot; save_location = &quot;D:/output&quot; file_name = &quot;sampledata.csv&quot; # Define function to upload the csv files to gdrive def upload_option_strike_data(save_location,file_name): try: creds = service_account.Credentials.from_service_account_file(gdrive, scopes=scopes) service = build('drive', 'v3', credentials=creds) file_metadata = { 'name': file_name, 'parents': [folder_id] } media = MediaFileUpload(f&quot;{save_location}/{file_name}&quot;, mimetype='text/csv') file = service.files().create( body=file_metadata, media_body=media ).execute() except Exception as e: print( f&quot;Failed to upload historical data collected for {index}.Function - save_option_strike_data.Exception: {str(e)}&quot;) </code></pre> <p>upload_option_strike_data(save_location,file_name)</p> <p>This script will upload the file to Grive and always gives e below warning message.</p> <pre><code>--- Logging error --- Traceback (most recent call last): File &quot;C:\Users\xxxxx\AppData\Local\Programs\Python\Python311\Lib\site-packages\googleapiclient\discovery_cache\file_cache.py&quot;, line 32, in &lt;module&gt; from oauth2client.contrib.locked_file import LockedFile ModuleNotFoundError: No module named 'oauth2client.contrib.locked_file' </code></pre> <p>How can I fix this warning.</p>
<python><google-drive-api>
2023-10-01 16:50:12
0
1,746
acr
77,211,360
2,756,466
How to use MongoObjectId in pydantic models
<p>I have created a simple REST API using Python, FastAPI and Pydantic.</p> <p>It is working OK. But the model file creates <code>_id</code> with <code>uuid</code> instead of Mongo's <code>ObjectId</code>.</p> <pre><code>id: uuid.UUID = Field(default_factory=uuid.uuid4, alias=&quot;_id&quot;) </code></pre> <p>How can I use Mongo ObjectId?</p>
<python><fastapi><pydantic>
2023-10-01 16:36:06
1
7,004
raju
77,211,348
2,764,206
Mypy and second-order decorators
<p>I'm trying to implement a second-order decorator that injects a dynamic variable as first argument of the decorated function.</p> <p>Here is what I have so far:</p> <pre><code>from typing import Callable, Concatenate, ParamSpec, TypeVar T = TypeVar('T') U = TypeVar('U') P = ParamSpec('P') def foo(some_arg: U) -&gt; Callable[ [Callable[Concatenate[U, P], T]], Callable[P, T], ]: def decorator(fn: Callable[Concatenate[U, P], T]) -&gt; Callable[P, T]: def wrapper(*args: P.args, **kwargs: P.kwargs) -&gt; T: return fn(some_arg, *args, **kwargs) return wrapper return decorator </code></pre> <p>When running mypy, I got the following error:</p> <pre><code>error: Incompatible return value type ( got &quot;Callable[[Arg(Callable[[U, **P], T], 'fn')], Callable[P, T]]&quot;, expected &quot;Callable[[Callable[[U, **P], T]], Callable[P, T]]&quot;) [return-value] </code></pre> <p>I don't understand what I got wrong. I couldn't found any information about the <code>Arg</code> element that Mypy says it got (couldn't find <code>typing.Arg</code> in mypy documentation).</p> <p>How should I declare the return value of my decorator factory ? How should I interpret this error output from mypy ? Any source from the doc I might have missed ?</p>
<python><mypy><python-typing><python-decorators>
2023-10-01 16:33:35
1
2,341
Nicolas Appriou
77,211,228
414,506
Can a multi-threaded Python app change the CWD?
<p>Would the <code>assert</code> statement in this code raise an error under any Python 3.11+ interpreter?</p> <p>Can the current working directory be changed by another module without this code using any <code>async</code> features?</p> <pre class="lang-py prettyprint-override"><code>import os cwd1 = os.getcwd() # can another module change the CWD here? cwd2 = os.getcwd() assert cwd1 == cwd2 </code></pre> <p>I need to know if the <code>CWD</code> would stay the same in all situations with code like the example, or if I have to check, as rare as it may be, due to a race condition.</p> <p>In other words, is that code thread-safe?</p>
<python><python-3.x><multithreading><thread-safety><race-condition>
2023-10-01 16:02:00
2
615
Carlos Gil
77,211,155
11,426,624
pandas groupby, transform and join
<p>I have a dataframe and I would like to groupby and join the strings of a column together. So something like the below.</p> <pre><code>df = pd.DataFrame({ 'id': [1, 1, 2, 2, 3, 3], 'txt': ['sth', 'sth else', 'sth', 'one more thing', 'sth else', 'sth else'], 'status': ['open', 'open', 'closed', 'open', 'open', 'open']}) df.assign(output= df.where(df.status=='open') .groupby(df.id) .txt.transform(lambda col: ', '.join(col.fillna('')))) </code></pre> <p>which gives me this</p> <pre class="lang-none prettyprint-override"><code> id txt status output 0 1 sth open sth, sth else 1 1 sth else open sth, sth else 2 2 sth closed , one more thing 3 2 one more thing open , one more thing 4 3 sth else open sth else, sth else 5 3 sth else open sth else, sth else </code></pre> <p>is there a way to</p> <ol> <li>not have duplicate values (like in row 4 and 5)</li> <li>not have a leading comma if a status is 'closed' (like in row 2 and 3) so that I would get</li> </ol> <pre class="lang-none prettyprint-override"><code> id txt status output 0 1 sth open sth, sth else 1 1 sth else open sth, sth else 2 2 sth closed one more thing 3 2 one more thing open one more thing 4 3 sth else open sth else 5 3 sth else open sth else </code></pre>
<python><pandas><dataframe><group-by>
2023-10-01 15:42:31
1
734
corianne1234
77,210,960
9,068,493
Can a class in python not use its generic parameter
<p>If I declare a function that is not using a generic parameter more than once:</p> <pre class="lang-py prettyprint-override"><code>import typing as t T = t.TypeVar(&quot;T&quot;) def bad(a: T) -&gt; None: ... </code></pre> <p>a static type-checker marks this as error (or at least as a warning, if using lenient flags). But if I do something similar with <em>a class</em>:</p> <pre class="lang-py prettyprint-override"><code>class ImBad(t.Generic[T]): def not_using_it(i: int) -&gt; str: ... nor_here: int </code></pre> <p>there is no objection from the checker.</p> <p>So my question is: Is it OK not to use a generic parameter in a class? Why anyone would do that?</p>
<python><python-typing>
2023-10-01 14:43:23
1
811
Felix.leg
77,210,935
3,312,274
flask Where to place code to ping elasticsearch
<p>I use elasticsearch in my app. Since I also use blueprints, <code>create_app</code> is defined in the app's <code>__init__.py</code>, which is where <code>app.elasticsearch</code> is initialized.</p> <p>When elasticsearch.ping() fails, I'd like to send an email to an address. I can't send the email in <code>init.py</code> as I need to import email function from another file that is also dependent on <code>app</code>. (cyclic)</p> <p>I'm doing the ping and check at the views, and it feels very wrong as the check has to be performed every visit on the associated page. <strong>Where should I place the elasticsearch.ping and email bit?</strong></p> <pre><code>def ping_elasticsearch(app): with app.app_context(): if not app.elasticsearch.ping(): app.elasticsearch = None send_email('[Microblog] Elasticsearch server cannot be reached', sender=app.config['MAIL_DEFAULT_SENDER'], recipients=[app.config['MAIL_DEFAULT_SENDER']], text_body='Elasticsearch server cannot be reached.', html_body='Elasticsearch server cannot be reached.') @bp.route('/', methods=['GET', 'POST']) @bp.route('/index', methods=['GET', 'POST']) @login_required def index(): if not current_app.elasticsearch_pinged: if current_app.elasticsearch: Thread(target=ping_elasticsearch, args=[current_app._get_current_object()]).start() current_app.elasticsearch_pinged = True ... </code></pre> <p><strong>EDIT:</strong></p> <p>I want app/__init__.py to look like this (note elasticsearch):</p> <pre><code>... def ping_elasticsearch(app): with app.app_context(): if not app.elasticsearch.ping(): app.elasticsearch = None send_email('[Microblog] Elasticsearch server cannot be reached', sender=app.config['MAIL_DEFAULT_SENDER'], recipients=[app.config['MAIL_DEFAULT_SENDER']], text_body='Elasticsearch server cannot be reached.', html_body='Elasticsearch server cannot be reached.') def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) babel.init_app(app) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']], timeout=10) \ if app.config['ELASTICSEARCH_URL'] else None app.elasticsearch_pinged = False if app.elasticsearch: Thread(target=ping_elasticsearch, args=[current_app._get_current_object()]).start() from app.errors import bp as errors_bp app.register_blueprint(errors_bp) ... </code></pre> <p>and the <code>email.py</code> module has the following code:</p> <pre><code>from threading import Thread from flask import current_app from flask_mail import Message from app import mail def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(subject, sender, recipients, text_body, html_body): app = current_app._get_current_object() msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body Thread(target=send_async_email, args=(app, msg)).start() </code></pre>
<python><multithreading><elasticsearch><flask>
2023-10-01 14:36:38
1
565
JeffP
77,210,776
22,466,650
How to plot trips durations while considering their deadlines?
<p>My input is a dataframe :</p> <pre><code>df = pd.DataFrame({'blk1': {'a': '12h45', 'b': None, 'c': None, 'd': None}, 'blk2': {'a': None, 'b': None, 'c': '13h15', 'd': '15h15'}, 'blk3': {'a': None, 'b': '12h10', 'c': None, 'd': None}, 'blk4': {'a': None, 'b': '15h45', 'c': '13h30', 'd': None}, 'blk5': {'a': '13h30', 'b': None, 'c': None, 'd': '16h15'}, 'deadline': {'a': '13h00', 'b': '14h30', 'c': '15h00', 'd': '15h45'}}) </code></pre> <pre><code> blk1 blk2 blk3 blk4 blk5 deadline a 12h45 13h30 13h00 b 12h10 15h45 14h30 c 13h15 13h30 15h00 d 15h15 16h15 15h45 </code></pre> <p>And I'm trying to get the plot below. Basically, I need to compute the duration an element (a, b, c or d) took to go from one block to another. By the way, only two non null values are possible per each row and the direction of a trip is from left columns to right ones.</p> <p><a href="https://i.sstatic.net/aQ8sg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aQ8sg.png" alt="enter image description here" /></a></p> <p>I feel like I'm in the right way but can't figure out how to make the colored (red or green) dashed lines and also how to add the texts (block x to y):</p> <pre><code>df1 = df.drop(columns='deadline').sort_index(ascending=False) df2 = df1.apply(lambda x: pd.to_datetime(x, format='%Hh%M')) df2 = pd.DataFrame([df2.min(axis=1),df2.max(axis=1)]).T df2.columns = ['start', 'end'] df2['duration'] = (df2['end'] - df2['start']) fig, ax = plt.subplots(figsize=(10, 2)) df2 = df2.reset_index() ax.barh(data=df2, width='duration', y='index', left='start', ec='k', color='k,' height=0.2) ax.set_xlim(df2['start'].min(), df2['end'].max()) </code></pre> <p><a href="https://i.sstatic.net/Fc2he.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Fc2he.png" alt="enter image description here" /></a></p>
<python><pandas><matplotlib>
2023-10-01 13:57:18
1
1,085
VERBOSE
77,210,676
4,503,189
Inserting the very special unicode character "Left Half Black Star" (aka U+2BE8) in text
<p>I built an app in Python - though this might be a more general question - writing stars into a text. I can write ☆ and ★ easily but I need the half-star, too. So far all my efforts have been a failure, so I ask.</p> <p>Here is a table of the most important information about these characters.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Black Star ★</th> <th>White Star ☆</th> <th>Left Half Black Star</th> </tr> </thead> <tbody> <tr> <td>Code</td> <td>2605</td> <td>2606</td> <td>2BE8</td> </tr> <tr> <td>utf-8 code</td> <td>E2 98 85</td> <td>E2 98 86</td> <td>E2 AF A8</td> </tr> <tr> <td>Unicode version</td> <td>1.1 (1993)</td> <td>1.1 (1993)</td> <td>11 (2018)</td> </tr> </tbody> </table> </div> <p>This works for simple stars:</p> <pre><code>print((b'black star: \xE2\x98\x85').decode(&quot;utf-8&quot;)) </code></pre> <p>This almost works for simple stars (would be nice if somebody could explain though why the black star text is converted to <code>&quot;汢捡瑳牡›&quot;</code>.)</p> <pre><code>` print((b'black star: \x05\x26').decode(&quot;utf-16&quot;))` </code></pre> <p>This is a total failure resulting in the general character of non-recognized situations: ⯨ instead of my expectation of the half-full star.</p> <pre><code>`print((b'half black star: \xE2\xAF\xA8').decode(&quot;utf-8&quot;))` </code></pre> <p>Same error on the console and writing into the <code>txt</code> file. I think it might be the version of the Unicode, but I am not sure. I guess what is written is the correct character but the display of it fails. Is it? Whatever, the question is how can I actually make it work?</p>
<python><unicode><special-characters>
2023-10-01 13:32:57
0
4,197
BlondCode