QuestionId
int64 74.8M
79.8M
| UserId
int64 56
29.4M
| QuestionTitle
stringlengths 15
150
| QuestionBody
stringlengths 40
40.3k
| Tags
stringlengths 8
101
| CreationDate
stringdate 2022-12-10 09:42:47
2025-11-01 19:08:18
| AnswerCount
int64 0
44
| UserExpertiseLevel
int64 301
888k
| UserDisplayName
stringlengths 3
30
β |
|---|---|---|---|---|---|---|---|---|
78,194,916
| 13,491,504
|
Lambdify order of variables
|
<p>When I use <code>lambdify</code> to turn a sympy function into one that can be used numerically, I need to pass the variables in the function as the first argument. I know that the number of Arguments is important, but is the order also important? How do I know, which letter is assigned to which variable in the original equation. For example:</p>
<pre><code>x, b , c , d , r , z , p = symbols('x b c d r z p')
eq = x*b*c*d
la = lambdify((x, b, c, d), eq)
</code></pre>
<p>I have entered the right order with the variables used prior, but I can also use the following without getting an error:</p>
<pre><code>la = lambdify((r, x, z, p), eq)
</code></pre>
<p>Now I don't know what is assigned to what. And when I try to solve the equation with <code>la(...)</code> I don't know in what order to put the values. Is <code>x</code> now the first or the second value?</p>
|
<python><sympy><lambdify>
|
2024-03-20 16:25:22
| 1
| 637
|
Mo711
|
78,194,891
| 2,612,235
|
Tox doesn't find pyproject.toml?
|
<p>It seems that I cannot manage <code>tox</code> to see my <code>pyproject.toml</code>. I've created a minimal example:</p>
<pre><code>$ mkdir test
$ cd test
$ cat <<EOF > pyproject.toml
[build-system]
requires = ["cython", "setuptools", "wheel"]
build-backend = "setuptools.build_meta"
[tool.tox]
envlist = "py310"
[tool.tox.testenv]
deps = ["pytest"]
commands = ["pytest"]
EOF
$ ls
ls
pyproject.toml
$ tox
ROOT: No tox.ini or setup.cfg or pyproject.toml found, assuming empty tox.ini at /home/user/testtox
...
$ tox --version
ROOT: No tox.ini or setup.cfg or pyproject.toml found, assuming empty tox.ini at /home/ycr/testtox
4.14.1 from /home/user/.local/lib/python3.10/site-packages/tox/__init__.py
</code></pre>
<p>Note that if I <code>touch tox.ini</code> it finds it :(</p>
<p>What's wrong?</p>
|
<python><tox><pyproject.toml>
|
2024-03-20 16:23:11
| 2
| 29,646
|
nowox
|
78,194,843
| 3,442,125
|
How can I get the local curvature of a scipy.CubicSpline?
|
<p>I'm using the scipy.interpolate.CubicSpline to compute a 2d function and want to analyse the curvature of the graph. The CubicSpline can compute a first and second derivative and my approach was to use curvature as
k(t) = |f''(t)| / (1+f'(t)**2)**1.5
(<a href="https://math.stackexchange.com/questions/1155398/difference-between-second-order-derivative-and-curvature">https://math.stackexchange.com/questions/1155398/difference-between-second-order-derivative-and-curvature</a>)</p>
<p>I then visualize the curvature by plotting a circle with r=1/r, which looks reasonable at first sight (larger circle at flatter regions), but is off noticeably.</p>
<p>The plot looks like this:</p>
<p><a href="https://i.sstatic.net/6qlw1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6qlw1.png" alt="enter image description here" /></a></p>
<p>The point density on the spline also depends on the curvature and I suspect that this 'velocity' influences the curvature computation as well.</p>
<p>The plot was generated with this small script:</p>
<pre><code>import numpy as np
from scipy.interpolate import CubicSpline
import matplotlib.pyplot as plt
start = [0, 0]
end = [0.6, 0.2]
d_start = np.array([3.0, 0.0])
d_end = np.array([3.0, 0.0])
cs = CubicSpline([0, 1], [start, end], bc_type=((1, d_start), (1, d_end)))
samples = np.linspace(0, 1, 100)
positions = cs(samples)
plt.plot(positions[:, 0], positions[:, 1], 'bx-')
plt.axis('equal')
t = samples[28]
touch_point = cs(t) # circle should be tangent to the curve at this point
tangent = cs(t, nu=1)
tangent_normed = tangent / np.linalg.norm(tangent)
cs1 = np.linalg.norm(cs(t, nu=1))
cs2 = np.linalg.norm(cs(t, nu=2))
k = abs(cs2) / ((1 + cs1**2)**1.5)
r = 1/k
center = touch_point + r * np.array([-tangent_normed[1], tangent_normed[0]])
plt.plot(touch_point[0], touch_point[1], 'go')
circle = plt.Circle(center, r, color='r', fill=True)
plt.gca().add_artist(circle)
plt.show()
</code></pre>
|
<python><scipy><spline>
|
2024-03-20 16:15:31
| 1
| 867
|
FooTheBar
|
78,194,811
| 4,635,470
|
script not working when arguments used from argparse rather than defaults
|
<p>I have tried to write a python script to extract zip files, copy to a directory and create PR. The default behaviour is to use no arguments and just use the defaults. When I do this it works perfectly. However when I pass the arguments <code>-z</code> or <code>-f</code> I get the following error:</p>
<pre><code>235: An error occurred:
Traceback (most recent call last):
File "/Users/ops.eekfonky/code/dev/server/trunk/deployment/./templatesToPR.py", line 217, in main
template_name, filename = unzip_templates(zip_dir, extraction_dir)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/ops.eekfonky/code/dev/server/trunk/deployment/./templatesToPR.py", line 57, in unzip_templates
filename = next(f for f in os.listdir(zip_dir) if f.endswith('.zip'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
StopIteration
</code></pre>
<p>Here is the full script;</p>
<pre><code>#!/usr/bin/env python3
import argparse
import logging
import os
import shutil
import sys
import subprocess
import importlib
import tempfile
import uuid
import zipfile
import git
import re
from git import Repo, GitCommandError
# Configure logging
logging.basicConfig(level=logging.INFO, format="%(lineno)d: %(message)s")
# Define default values in a dictionary
DEFAULTS = {
"default_branch": "release/17",
"zip_dir": "~/Downloads/templates",
}
def parse_arguments():
"""Parses command-line arguments."""
parser = argparse.ArgumentParser(description='''
This script handles git repositories and templates based on internal defaults or command-line overrides.
Use command-line options to specify custom settings for the script's operation.''')
parser.add_argument('--def-branch', '-d', default=DEFAULTS["default_branch"],
help='Default git branch name. Default is "%(default)s".')
parser.add_argument('--zip-dir', '-z', default=DEFAULTS["zip_dir"],
help='Directory for zipped templates. Default is "%(default)s".')
parser.add_argument('--zip_file', '-f', type=str, default=None, nargs = '?',
help='Specify the .zip filename explicitly. Defaults to the zip_dir if not specified.')
return parser.parse_args()
def install_and_import(package, module_name=None):
"""Installs a package if needed and imports it."""
module_name = module_name if module_name else package
try:
importlib.import_module(module_name)
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
importlib.import_module(module_name)
def ensure_directory_exists(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def unzip_templates(zip_dir, extraction_path):
"""Extracts a template ZIP, handling 'email' and 'sms' directories and preserving nested structures."""
zip_file_path = None
if os.path.isdir(zip_dir):
filename = next(f for f in os.listdir(zip_dir) if f.endswith('.zip'))
zip_file_path = os.path.join(zip_dir, filename)
else:
filename = os.path.basename(zip_dir)
zip_file_path = zip_dir
if not filename:
raise FileNotFoundError("No ZIP file found in the directory or provided file")
template_name = os.path.splitext(filename)[0] # Determine template_name
# Rename template_name if it has spaces (optional)
base_name, ext = os.path.splitext(template_name)
if ' ' in base_name:
new_base_name = base_name.replace(' ', '-')
template_name = new_base_name + ext
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
# Check for files with spaces in the name
for zip_info in zip_ref.infolist():
if ' ' in zip_info.filename:
raise ValueError(f"ZIP file contains a file with a space in the name: {zip_info.filename}")
# Extract directly into the extraction_path
zip_ref.extractall(extraction_path)
# Cleanup __MACOSX Directory
macosx_dir = os.path.join(extraction_path, '__MACOSX')
if os.path.exists(macosx_dir) and os.path.isdir(macosx_dir):
shutil.rmtree(macosx_dir)
logging.info(f"Extracted {filename} to {extraction_path}")
return template_name, filename
def copy_templates_to_destination(extraction_dir, template_dir):
"""Copies extracted templates, overwrites matching files, adds new files, and skips hidden files."""
for subdir in os.listdir(extraction_dir):
source_dir = os.path.join(extraction_dir, subdir)
destination_dir = os.path.join(template_dir, subdir)
# Filter out any hidden files before copying
non_hidden_files = [f for f in os.listdir(source_dir) if not f.startswith('.')]
# Copy with merge
shutil.copytree(source_dir, destination_dir, ignore=shutil.ignore_patterns('.*'), dirs_exist_ok=True)
logging.info(f"Merged {subdir} into {destination_dir}")
def cleanup(extraction_dir, args, filename=None):
"""Clean up temporary files and optionally the original ZIP file(s)."""
shutil.rmtree(extraction_dir)
logging.info(f"Temporary files cleaned up from {extraction_dir}")
zip_dir = DEFAULTS["zip_dir"]
zip_dir = os.path.abspath(os.path.expanduser(zip_dir))
original_zip_file = os.path.join(zip_dir, filename)
if os.path.isfile(original_zip_file):
os.remove(original_zip_file)
logging.debug(f"Original ZIP file removed: {original_zip_file}")
else:
logging.warning(f"No {filename} for ZIP file deletion in default handling.")
class GitRepoManager:
def __init__(self, repo_path):
self.repo = Repo(repo_path)
def prepare_and_create_branch(self, default_branch, template_name, user_initials):
"""Prepares the repository and creates a new branch for template updates."""
original_branch = self.repo.active_branch.name
unique_suffix = str(uuid.uuid4())[:8]
new_branch = f"{user_initials}/{template_name}-{unique_suffix}-no-build"
stashed_changes = False
try:
if self.repo.is_dirty():
logging.info("Changes detected in the working directory. Attempting to stash changes...")
self.repo.git.stash('save', "Stashing changes before template update")
logging.info("All changes stashed.")
stashed_changes = True
self.repo.git.checkout(default_branch)
self.repo.git.pull()
self.repo.git.checkout("HEAD", b=new_branch)
logging.info(f"New branch '{new_branch}' created from '{default_branch}'.")
return True, new_branch, original_branch, stashed_changes
except git.exc.GitCommandError as e:
logging.error(f"Error preparing repository or creating branch: {e}")
return False, None, None, stashed_changes
def handle_updates(self, template_dir, branch_name, original_branch, stashed_changes):
"""Stages, commits, and pushes template changes"""
try:
if branch_name not in self.repo.git.branch().split():
sys.exit(f"Branch '{branch_name}' does not exist locally. Cannot proceed with push.")
self.repo.git.add(template_dir)
self.repo.index.commit("Update templates")
subprocess.run(["git", "push", "origin", branch_name, "--progress"])
self.repo.git.checkout(original_branch)
if stashed_changes:
self.repo.git.stash('pop')
self.repo.git.branch('-D', branch_name)
logging.info(f"Templates pushed and local branch '{branch_name}' removed.")
except git.exc.GitCommandError as e:
logging.error(f"Git operations failed: {e}")
def backup_current_state(self):
# Create a temporary branch to hold the current state
try:
self.repo.git.branch('temp_backup_branch')
except GitCommandError:
# Branch already exists, force update it
self.repo.git.branch('-D', 'temp_backup_branch')
self.repo.git.branch('temp_backup_branch')
def rollback_to_backup(self):
try:
# Reset the current branch to the backup branch
self.repo.git.reset('--hard', 'temp_backup_branch')
print("Rollback successful.")
except GitCommandError as e:
print(f"Rollback failed: {e}")
def main():
args = parse_arguments()
install_and_import('GitPython', 'git')
from git import Repo, GitCommandError
# Script variables with argparse and dynamic paths
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
git_repo_root = os.path.abspath(os.path.join(script_dir, "../../../")) # Example path
template_dir = os.path.join(git_repo_root, "server/trunk/services/src/main/resources/templates")
if args.zip_dir:
zip_dir = os.path.abspath(os.path.expanduser(args.zip_dir)) # Ensure absolute path with ~ expansion
if not os.path.isdir(zip_dir):
raise ValueError("Error: When using the -z flag, you must provide a directory containing ZIP files.")
elif args.zip_file:
zip_dir = os.path.abspath(os.path.expanduser(args.zip_file)) # Ensure absolute path with ~ expansion
if not os.path.isfile(zip_dir):
raise ValueError("Error: When using the -f flag, you must provide a valid file path to a ZIP file.")
else:
zip_dir = DEFAULTS["zip_dir"]
zip_dir = os.path.abspath(os.path.expanduser(zip_dir))
default_branch = args.def_branch
ensure_directory_exists(zip_dir)
extraction_dir = tempfile.mkdtemp(prefix='templates-extraction-', dir='/tmp')
try:
if len(zip_dir) == 0:
print("Empty directory or file not found")
raise Exception('zip template dir is empty')
template_name, filename = unzip_templates(zip_dir, extraction_dir)
print(f"template name: {template_name}, filename: {filename}")
repo_manager = GitRepoManager(git_repo_root)
# Calculate user_initials
whoami_output = subprocess.check_output(['whoami']).decode('utf-8').strip()
parts = whoami_output.split('.')
user_initials = parts[1][0] + parts[-1][0] # Extract initials from first and last name
success, branch_name, original_branch, stashed_changes = repo_manager.prepare_and_create_branch(default_branch, template_name, user_initials)
if not success:
logging.error("Failed to create the new branch. Aborting script.")
sys.exit(1)
copy_templates_to_destination(extraction_dir, template_dir)
repo_manager.handle_updates(template_dir, branch_name, original_branch, stashed_changes)
# removes everything from templates dir
if success:
cleanup(extraction_dir, args, filename)
except Exception as e:
logging.error(f"An error occurred: {e}")
repo_manager.backup_current_state()
repo_manager.rollback_to_backup()
# Call your main function
if __name__ == "__main__":
main()
</code></pre>
<p>Why is this error happening? I am new to Python so am stuck</p>
|
<python>
|
2024-03-20 16:09:55
| 1
| 855
|
eekfonky
|
78,194,660
| 4,865,723
|
Differentiate between optional and mandatory in Python's argparse
|
<p>See this example:</p>
<pre><code>#!/usr/bin/env python3
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input', type=str)
parser.add_argument('-d', '--debug', action='store_true')
parser.add_argument('--version', action='version', version='0.1.2')
return parser.parse_args()
if __name__ == '__main__':
main()
print(f'{sys.argv=}')
</code></pre>
<pre class="lang-bash prettyprint-override"><code>$ ./argpars_debug.py foo --help
usage: argpars_debug.py [-h] [-d] [--version] input
positional arguments:
input
options:
-h, --help show this help message and exit
-d, --debug
--version show program's version number and exit
</code></pre>
<p>The <code>input</code> argument is mandatory. Using <code>--version</code> without <code>input</code> is possible:</p>
<pre class="lang-bash prettyprint-override"><code>$ ./argpars_debug.py --version
0.1.2
</code></pre>
<p>but using <code>--debug</code> without <code>input</code> is not possible:</p>
<pre class="lang-bash prettyprint-override"><code>$ ./argpars_debug.py --debug
usage: argpars_debug.py [-h] [-d] [--version] input
argpars_debug.py: error: the following arguments are required: input
</code></pre>
<p>However, I would like to use <code>--debug</code> with <em>and without</em> <code>input</code>:</p>
<pre class="lang-bash prettyprint-override"><code>$ ./argpars_debug.py --debug
$ ./argpars_debug.py foo --debug
</code></pre>
<p>How can I modify this behavior?</p>
|
<python><argparse>
|
2024-03-20 15:46:11
| 0
| 12,450
|
buhtz
|
78,194,648
| 9,930,052
|
How to start a function in a python/propy script via c#?
|
<p>My python script (c:\Temp\StartPython\test.py) looks like this:</p>
<pre><code>import arcpy
import string, sys, os
import ctypes
logfile ="C:\\Temp\\StartPython\\Logfile.log"
def Main(dataset):
print ("Started with argument " + dataset)
datei = open(logfile,'a')
datei.write("Started with argument " + dataset)
</code></pre>
<p>I want to start the function "main" from the script via C#. For this I have to use the propy.bat which is used by ArcGis Pro to establish a CONDA-Enviroment for phython.</p>
<pre><code>@echo off
@CALL :normalizepath scripts_path "%~dp0"
:: get the active environment from PythonEnvUtils.exe
FOR /F "delims=" %%i IN ('"%scripts_path%..\..\PythonEnvUtils.exe"') DO set CONDA_NEW_ENV=%%i
@set CONDA_SKIPCHECK=1
@set "CONDA_PREFIX=%CONDA_NEW_ENV%"
@set "CONDA_BACKUP_PATH=%PATH%"
@SET "activate_path="%scripts_path%activate.bat" "%CONDA_NEW_ENV%"
@set "deactivate_path="%scripts_path%deactivate.bat""
@call %activate_path%
python.exe %*
@set PY_ERRORLEVEL=%ERRORLEVEL%
@call %deactivate_path%
@set "PATH=%CONDA_BACKUP_PATH%"
@set "CONDA_BACKUP_PATH="
@exit /b %PY_ERRORLEVEL%
:normalizepath
@set "%1=%~dpfn2"
@exit /b
</code></pre>
<p>I was able to create a class for starting the script, which looks like this:</p>
<pre><code>internal class RunProcess
{
private Process _process;
private StringBuilder _sbOut = new StringBuilder();
private StringBuilder _sbError = new StringBuilder();
public (string Output, string Error, int ErrCode) RunProcessGrabOutput(string Executable, string Arguments, string WorkingDirectory)
{
int exitCode = -1;
try
{
_sbOut.Clear();
_sbError.Clear();
_process = new Process();
_process.StartInfo.FileName = Executable;
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.WorkingDirectory = WorkingDirectory;
_process.StartInfo.RedirectStandardInput = true;
_process.StartInfo.RedirectStandardOutput = true;
_process.StartInfo.RedirectStandardError = true;
_process.StartInfo.StandardErrorEncoding = Encoding.UTF8;
_process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
_process.StartInfo.CreateNoWindow = true;
_process.StartInfo.EnvironmentVariables.Add("PYTHONUNBUFFERED", "TRUE");
if (!string.IsNullOrEmpty(Arguments))
_process.StartInfo.Arguments = Arguments;
_process.EnableRaisingEvents = true;
_process.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
_process.ErrorDataReceived += new DataReceivedEventHandler(ProcessErrorHandler);
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
// You can set the priority only AFTER the you started the process.
_process.PriorityClass = ProcessPriorityClass.BelowNormal;
_process.WaitForExit();
exitCode = _process.ExitCode;
}
catch
{
// This is how we indicate that something went wrong.
throw;
}
return (_sbOut.ToString(), _sbError.ToString(), exitCode);
}
private void ProcessOutputHandler(object SendingProcess, DataReceivedEventArgs OutLine)
{
_sbOut.AppendLine(OutLine.Data);
}
private void ProcessErrorHandler(object SendingProcess, DataReceivedEventArgs OutLine)
{
_sbError.AppendLine(OutLine.Data);
}
}
</code></pre>
<p>This is how I try to start the script:</p>
<pre><code>var executable = "C:\\Program Files\\ArcGIS\\Pro\\bin\\Python\\Scripts\\propy.bat";
var workingDir = "C:\\Program Files\\ArcGIS\\Pro\\bin";
var myArguments = "\"C:\\Temp\\StartPython\\test.py\" \"C:\\somePath\" ";
var process = new RunProcess();
var processOutcome = process.RunProcessGrabOutput(executable,
myArguments, workingDir);
</code></pre>
<p>RunProcessGrabOutput will last ~ 1 second and afterwards no Logfile is written and the processOutcome is kinda empty:</p>
<pre><code>processOutcome ("\r\n", "\r\n", 0) (string Output, string Error, int ErrCode)
</code></pre>
|
<python><c#><conda><arcgis>
|
2024-03-20 15:43:52
| 1
| 403
|
Gener4tor
|
78,194,480
| 4,380,772
|
Convert Python Flask Webservice to Windows Service
|
<p>I am very new to Python. I have a flask API written and I am facing some issues with that. I want to run this API in a server and initially I planned to create a bat file and run the service in the task scheduler. However I ran into some file permissions issues. I have a code snippet which generates the log file in the directory and when I run the python code directly, it generates the log file but when ran in task scheduler it doesn't.</p>
<p>Hence I though I can go with a Windows Service which gives more flexibility. Below is my code for the windows service and my sample API python code as I wont able to provide my full code. What I am doing here is I query a table get few values, use a document template and populate the values in placeholders and finally, I save the document as a PDF in a folder. I have a Web UI from where I invoke a call to this API to generate the document based on values provided from UI.</p>
<p>--- API Python Code ---</p>
<pre><code> import ast
import logging
import os
import traceback
import pandas as pd
import win32com.client
import pythoncom
from docx.shared import Mm
from docxtpl import DocxTemplate, RichText, InlineImage
from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from flask import Flask, request, jsonify
from waitress import serve
app = Flask(__name__)
wdFormatPDF = 17
logging.basicConfig(filename='Logfile.log', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
# path setting
base_dir = os.path.dirname(os.path.abspath(__file__))
ET_doc = DocxTemplate(template_Path + "Generated.docx")
def narrative_settings(structure_No, cla_engine):
# ticket 4912 - Active column included
ns_select_query = "SELECT * FROM Settings where structureNo = '{structure_number}' and Active = 1".format(structure_number=structure_No)
settings_df = pd.read_sql_query(ns_select_query, cla_engine)
image_path_var = settings_df['logoFile'].iloc[0]
ns_report_location = settings_df['FolderPath'].iloc[0]
eot_logo = InlineImage(ET_doc, image_descriptor=image_path_var, width=Mm(15), height=Mm(15))
ds_logo = InlineImage(DS_doc, image_descriptor=image_path_var,
width=Mm(15), height=Mm(15))
return eot_logo, ds_logo, ns_report_location
@app.route("/generation/", methods=['GET'])
def base():
report_date_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
eot_logo_var, ds_logo_var, report_location = narrative_settings(structure_no, cla_engine)
context = {'structure_no': structure_no, 'Logo': eot_logo_var,
'report_time': report_date_time}
ET_doc.render(context)
ET_doc.save(report_location + doc_file_name)
pdf_file_name = f'Narrative_{subj_id}_{report_date}.pdf'
word = win32com.client.Dispatch("Word.Application", pythoncom.CoInitialize())
doc = word.Documents.Open(report_location + doc_file_name)
doc.SaveAs(report_location + pdf_file_name, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
os.remove(report_location + doc_file_name)
report_status = "Generated"
if __name__ == "__main__":
serve(app, host="", port=7105)
app.run(debug=True)
</code></pre>
<p>---- Service.Py ----</p>
<pre><code>import servicemanager
import sys
import win32serviceutil
import threading
import concurrent.futures
import time
from na_webservice import app
class workingthread(threading.Thread):
def __init__(self, quitEvent):
self.quitEvent = quitEvent
self.waitTime = 1
threading.Thread.__init__(self)
def run(self):
try:
# Running start_flask() function on different thread, so that it doesn't blocks the code
executor = concurrent.futures.ThreadPoolExecutor(max_workers=10)
executor.submit(self.start_flask)
except:
pass
# Following Lines are written so that, the program doesn't get quit
# Will Run a Endless While Loop till Stop signal is not received from Windows Service API
while not self.quitEvent.isSet(): # If stop signal is triggered, exit
time.sleep(1)
def start_flask(self):
# This Function contains the actual logic, of windows service
# This is case, we are running our flaskserver
test = FlaskServer()
test.start()
class FlaskService(win32serviceutil.ServiceFramework):
_svc_name_ = "Service"
_svc_display_name_ = "Narrative Service"
_svc_description_ = "Web Service for executing python code"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = threading.Event()
self.thread = workingthread(self.hWaitStop)
def SvcStop(self):
self.hWaitStop.set()
def SvcDoRun(self):
thread = Thread(target=app.run())
thread.daemon = True
thread.start()
while (1):
rc = win32event.WaitForSingleObject(self.hWaitStop, 1000)
if rc == win32event.WAIT_OBJECT_0:
# Stop event
break
self.thread.start()
self.hWaitStop.wait()
self.thread.join()
self.start(app);
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(FlaskService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(FlaskService)
</code></pre>
<p>I followed the steps provided in this post <a href="https://stackoverflow.com/questions/55677165/python-flask-as-windows-service">Stackover flow question </a> however I dont know how to call my flask API into the windows service code. I have just imported the flask API in my service.py but didnt understand how I can call it in this. Can someone guide me on how to do this.</p>
|
<python><flask>
|
2024-03-20 15:19:55
| 0
| 1,667
|
Karthik Venkatraman
|
78,194,368
| 301,774
|
roc_auc_score differs between RandomForestClassifier GridSearchCV and explicitly coded RandomForestCLassifier
|
<p>Why doesn't a trained <code>RandomForestClassifier</code> with specific parameters match the performance of varying those parameters with a <code>GridSearchCV</code>?</p>
<pre><code>def random_forest(X_train, y_train):
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import roc_auc_score, make_scorer
from sklearn.model_selection import train_test_split
X_train, X_validate, y_train, y_validate = train_test_split(X_train, y_train, random_state=0)
# various combinations of max depth and max features
max_depth_vals = [1,2,3]
max_features_vals = [2,3,4]
grid_values = {'max_depth': max_depth_vals, 'max_features': max_features_vals}
# build GridSearch
clf = RandomForestClassifier(n_estimators=10)
grid = GridSearchCV(clf, param_grid=grid_values, cv=3, scoring='roc_auc')
grid.fit(X_train, y_train)
y_hat_proba = grid.predict_proba(X_validate)
print('Train Grid best parameter (max. AUC): ', grid.best_params_)
print('Train Grid best score (AUC): ', grid.best_score_)
print('Validation set AUC: ', roc_auc_score(y_validate, y_hat_proba[:,1]))
# build RandomForest with hard coded values. AUC should be ballpark to grid search
clf = RandomForestClassifier(max_depth=3, max_features=4, n_estimators=10)
clf.fit(X_train, y_train)
y_hat = clf.predict(X_validate)
y_hat_prob = clf.predict_proba(X_validate)[:, 1]
auc = roc_auc_score(y_hat, y_hat_prob)
print("\nMax Depth: 3 Max Features: 4\n---------------------------------------------")
print("auc: {}".format(auc))
return
</code></pre>
<p>Results - the grid search identifies the best parameters of <code>max_depth=3</code> and <code>max_features=4</code> and calculates a <code>roc_auc_score</code> of <code>0.85</code>; when I put that through the code with the reserved validation set i get an <code>roc_auc_score</code> of <code>0.84</code>. However when I code the classifier directly with those parameters it calculates an <code>roc_auc_score</code> of <code>1.0</code>. My understanding is that it should be in the same ballpark ~0.85 but this feels way off.</p>
<pre><code>Validation set AUC: 0.8490471073563559
Grid best parameter (max. AUC): {'max_depth': 3, 'max_features': 4}
Grid best score (AUC): 0.8599727094965482
Max Depth: 3 Max Features: 4
---------------------------------------------
auc: 1.0
</code></pre>
<p>I could be misunderstanding concepts, not apply techniques correctly, or even have coding issues. Thanks.</p>
|
<python><scikit-learn><random-forest><gridsearchcv><auc>
|
2024-03-20 15:02:53
| 0
| 6,896
|
akaphenom
|
78,194,254
| 3,194,618
|
Using pyarrow.DictionaryArray instead of Categorical in pandas DataFrame
|
<p>I'm evaluating the possibility of using arrow-based data types in our data flows.</p>
<p>Our flows are based on pandas and using <code>dtype_backend='pyarrow'</code> seems working pretty well (basically this options prioritize the arrow type in constructors).
I'm finding some problems using <code>pyarrow.DictionaryArray</code> instead of <code>Categorical</code>.</p>
<p>Here an example:</p>
<pre><code>import pyarrow as pa
import pandas as pd
def pyarrow_cat_dtype(vals):
as_dict_vals = pa.array(vals).dictionary_encode()
return pd.ArrowDtype(as_dict_vals.type)
vals = ['A', 'B', 'C']
ser = pd.Series(vals*2, dtype=pyarrow_cat_dtype(vals))
</code></pre>
<p>The series is of type:</p>
<pre><code>dictionary<values=string, indices=int32, ordered=0>[pyarrow]
</code></pre>
<p>During the ETL process, the series is then changed and is not
clear to me how to reflect these changes also in the categories</p>
<p>Suppose we need to delete most of the values or merge categorical from multiple sources.</p>
<p>Using categorical this can be done by accessing to <code>.categories</code> attribute
or using <code>observed=True</code> in a groupby as described in <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html" rel="nofollow noreferrer">the documentation</a>
but I cannot find something similar for <a href="https://arrow.apache.org/docs/python/generated/pyarrow.DictionaryArray.html#pyarrow-dictionaryarray" rel="nofollow noreferrer">DictionaryArray</a> to manage it.</p>
<p><strong>How and where are stored these values in pandas? Is there a way to do an introspection of the dtype and read or manage the underlying values and indices?</strong></p>
<p>It's not clear to me, why, for example, adding a new value to a pd.Categorical Series it raises a TypeError, while this doesn't happen using DictionaryArrays.</p>
|
<python><pandas><pyarrow>
|
2024-03-20 14:47:03
| 0
| 1,479
|
Glauco
|
78,194,178
| 8,618,380
|
GCP function to function HTTP call
|
<p>I am trying to call a GCP function (B) from another GCP function (A).</p>
<p>So far, I have:</p>
<ul>
<li>Created a service account and granted function invoker role</li>
<li>Added to function B the service account as Function Admin</li>
<li>Downloaded a json key for the created service account</li>
<li>Tried to run the code locally</li>
</ul>
<p>from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession</p>
<pre><code>function_url = 'https://europe-west6-xxx.cloudfunctions.net/yyy'
json_path = "/Users/xxx44b1.json"
credentials = service_account.IDTokenCredentials.from_service_account_file(
json_path,
target_audience=function_url,
)
authed_session = AuthorizedSession(credentials)
response = authed_session.post(function_url)
response.text
</code></pre>
<p>However, it does not work, and returns:</p>
<pre><code><html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>404 Page not found</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Page not found</h1>
<h2>The requested URL was not found on this server.</h2>
<h2></h2>
</body></html>
</code></pre>
<p>How can I solve that?</p>
|
<python><google-cloud-platform><google-cloud-functions>
|
2024-03-20 14:36:39
| 1
| 1,975
|
Alessandro Ceccarelli
|
78,194,173
| 10,764,260
|
2D PointCloud Visualization in Python
|
<p>I have some 3D objects from ikea furniture and I would like to sample point clouds and display them as 2D image. In the PointNet Paper (<a href="https://arxiv.org/abs/1612.00593" rel="nofollow noreferrer">https://arxiv.org/abs/1612.00593</a>) they used a very nice visualization:</p>
<p><a href="https://i.sstatic.net/TIsfN.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TIsfN.jpg" alt="enter image description here" /></a></p>
<p>But I can't quite figure out how they did it (images top row). Mostly, because I cannot describe the visualization either. It looks like they do some sort of depth coloring, but I wonder multiple things:</p>
<ol>
<li>How do they deal with perspective? Is there some automated way how they display the point clouds, so the object is good visible (e.g. no degree of freedom loose I suppose?)?</li>
<li>What is the strategy for the colors?</li>
<li>What do they color exactly? It looks like they use bigger squares</li>
</ol>
<p>I started with something like this:</p>
<pre class="lang-py prettyprint-override"><code>point_clouds_per_part = assembly_step.sample_point_cloud(2500)[0]
all_points = point_clouds_per_part.reshape(-1, 3)
df = pd.DataFrame(all_points.numpy(), columns=['x', 'y', 'z'])
z_normalized = (df['z'] - df['z'].min()) / (df['z'].max() - df['z'].min())
plt.figure(figsize=(100, 100))
scatter = plt.scatter(df['x'], df['y'], c=z_normalized, cmap='cool', s=50, marker='s')
plt.colorbar(scatter, label='X coordinate')
plt.xlabel('X')
plt.ylabel('Y')
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
</code></pre>
<p>And well, I don't recognize much:
<a href="https://i.sstatic.net/rdQC5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rdQC5.png" alt="enter image description here" /></a></p>
<p>I tried something like:</p>
<pre class="lang-py prettyprint-override"><code>cloud = pyntcloud.PyntCloud(df)
cloud.plot(background="black", use_as_color="y", cmap="cool", elev=20, azim=67, initial_point_size=10)
</code></pre>
<p><a href="https://i.sstatic.net/8iJYE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8iJYE.png" alt="enter image description here" /></a></p>
<p>Which does look a lot better (in case you wonder: It's the part on the side of the applaro ikea bench). But well, now it is 3D, I set arbitrary values for rotation and not sure if I color the pixels after the same logic as the authors did.</p>
<p>I would appreciate some help on how to reproduce the plots of PointNet!</p>
<p>I added a csv with the point clouds here <a href="https://pastebin.com/PNUMaAys" rel="nofollow noreferrer">https://pastebin.com/PNUMaAys</a> for testing. In case it is relevant, this is my code for sampling the point clouds in the first place:</p>
<pre class="lang-py prettyprint-override"><code>torch.tensor(trimesh.sample.sample_surface(trimesh.load(path, force='mesh'), number_of_points)[0])
</code></pre>
|
<python><matplotlib><point-clouds>
|
2024-03-20 14:35:47
| 0
| 308
|
Leon0402
|
78,193,859
| 1,668,622
|
What's a straightforward way to split a string on 'top level' only, regarding quotes and parentheses?
|
<p>I want to provide a function which takes a comma-separated string and splits it on separators, similar to <code>str.split()</code> but keeping (potentially nested) quoted and parenthesized parts.
Examples include comma-separated key-value pairs (<code>a=b,c=d</code>) but also comma-separated shell commands which might include the separator or even quote characters you could use to write a simple regex.</p>
<p>To avoid writing a fully-fledged parser my first idea was to use the <code>csv</code> module (see <a href="https://stackoverflow.com/questions/28725898/how-to-handle-double-quotes-inside-field-values-with-csv-module">How to handle double quotes inside field values with csv module?</a>) but I failed using it even for simple cases e.g.:</p>
<pre><code>>>> s = "a='[1,2,3]',c=d"
>>> list(csv.reader([s], delimiter=',', quotechar="'")) # expected: ["a='[1,2,3]'", "c=d"]
[["a='[1", '2', "3]'", 'c=d']]
</code></pre>
<p>and I didn't try with more complex stuff like <code>a='[1,"3,14",3]',c="[4,5,6]"</code>.</p>
<p>Is there an easy way to either tame <code>csv.reader</code> to split the above string into <code>['a=..', 'c=..']</code> or even better to use some built-in string processing capability?</p>
|
<python><csv><parsing><split>
|
2024-03-20 13:48:38
| 2
| 9,958
|
frans
|
78,193,854
| 6,714,667
|
Cannot find package "tests"
|
<p>i imported following:</p>
<pre><code>from office365.sharepoint.client_context import ClientContext
from tests import test_user_credentials, test_team_site_url
</code></pre>
<p>however "tests" is not recognized (Import tests could not be resolved) it's not clear what package needs to be installed. i pip installed:</p>
<pre><code>pip install Office365-REST-Python-Client
</code></pre>
<p>and i thought tests would be installed too. I cannot find a package called tests so nervous to pip install tests if it causes conflict. Does anyone know what i need to do?</p>
|
<python><sharepoint>
|
2024-03-20 13:48:02
| 1
| 999
|
Maths12
|
78,193,760
| 5,539,674
|
Understanding JSONDecodeError when using JsonOutputParser
|
<p>I am just getting started with output-parsers and I'm impressed with their usefulness when they work properly. I have, however, run into a case where every now and then, a chain returns an error that seems to be related to the JsonOutputParser that I use, as indicated by the following (condensed) error message:</p>
<pre><code>JSONDecodeError
JsonOutputParser.parse_result(self, result, partial)
156 # Parse the JSON string into a Python dictionary
--> 157 parsed = parser(json_str)
159 return parsed
122 # If we got here, we ran out of characters to remove
123 # and still couldn't parse the string as JSON, so return the parse error
124 # for the original string.
--> 125 return json.loads(s, strict=strict)
</code></pre>
<p>According to <a href="https://www.reddit.com/r/LangChain/comments/17hep0o/comment/k6na6nd/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button" rel="nofollow noreferrer">this post here</a> this could be related to there not being "enough tokens left to fully generate my output", which seems to be in line with the error message above:</p>
<pre><code>122 # If we got here, we ran out of characters to remove
</code></pre>
<p>although I am not fully sure what that means or how it can be fixed.</p>
<p>Has anybody encountered this problem before and could offer some guidance? I must admit that I'm feeling kind of stumped, especially since the error can't be reproduced reliably and only occurs every other time I run my script.</p>
|
<python><langchain>
|
2024-03-20 13:35:56
| 1
| 315
|
O RenΓ©
|
78,193,630
| 1,552,080
|
Python Pandas grouping DataFrame by blocks of sequential values
|
<p>I have a large pandas DataFrame having a timestamp column, a value column, a "key" column and a column with a flag indicating end of a block (and some more actually)</p>
<pre><code>timestamp, value, key, last_in_block
12345, 1.0, 2, False <-- start of block 1
12346, 0.5, 4, False
12347, 1.2, 1, False
12348, 2.2, 6, False
12349, 1.5, 3, False
12350, 1.2, 3, False
12351, 2.3, 3, False
12352, 0.4, 5, True
12371, 1.3, 2, False <-- start of block 2
12372, 0.9, 4, False
12373, 1.7, 1, False
12374, 2.0, 6, False
12375, 1.2, 3, False
12376, 1.4, 3, False
12377, 2.7, 3, False
12378, 0.8, 5, True
...
</code></pre>
<p>In the "key" column a characteristic sequence of values (in this example 2 4 5 6 3 3 3 5) appears identifying a data block. I would like to apply a "groupBy" statement to break the Frame into groups by blocks. Is this / how is this possible?</p>
<pre><code>df = pd.DataFrame(data =
{"timestamp": list(range(12345,12353)) + list(range(12371,12379)),
"value": [1.0,0.5,1.2,2.2,1.5,1.2,2.3,0.4,1.3,0.9,1.7,2.0,1.2,1.4,2.7,0.8],
"key": [2,4,1,6,3,3,3,5]*2,
"last_in_block" : [False]*7+[True]+[False]*7+[True]})
</code></pre>
<p>Update, answers to questions:</p>
<ul>
<li>I known the sequence in advance</li>
<li>The sequences are complete besides very rare exceptions</li>
</ul>
|
<python><pandas><group-by>
|
2024-03-20 13:17:31
| 2
| 1,193
|
WolfiG
|
78,193,572
| 3,907,561
|
Why so many python built-in functions has no in-code docs?
|
<p><code>train_kwargs</code> is a standard python <code>dict</code>, I don't know what does <code>update(...)</code> do, is it merge the new kwargs into itself or replace all key-values?</p>
<p>So much so that I had to open the browser to check the official online documentation, which seriously affected my efficiency.</p>
<p>There are so many examples of no in-code docs built-in types and built-in functions that I wonβt list them all.</p>
<p><a href="https://i.sstatic.net/tYK1L.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tYK1L.png" alt="enter image description here" /></a></p>
<hr />
<p>Some classes and functions have well in-code docs.</p>
<p><a href="https://i.sstatic.net/x73qK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/x73qK.png" alt="enter image description here" /></a></p>
|
<python>
|
2024-03-20 13:09:17
| 1
| 1,167
|
huang
|
78,193,562
| 1,498,389
|
setuptools.package-data has no effect within a docker container
|
<p>So, I have this little pyproject.toml-based project (named <code>RecordEcos</code>) to do multi-camera recording with a minimalist interface (using PySimpleGUI). The interface make use of a placeholder image when the camera are not connected.</p>
<p>I've added the following section to my pyproject.toml to ensure the image is well embedded into the wheel.</p>
<pre class="lang-ini prettyprint-override"><code>[tool.setuptools.package-data]
RecordEcos = ["*.png"]
</code></pre>
<p>And indeed, everything works perfectly on my laptop:</p>
<pre class="lang-bash prettyprint-override"><code>$ python -m build | grep Placeholder
copying RecordEcos/gui/img/Placeholder.png -> RecordEcos-0.4.5/RecordEcos/gui/img
copying RecordEcos/gui/img/Placeholder.png -> build/lib/RecordEcos/gui/img
copying build/lib/RecordEcos/gui/img/Placeholder.png -> build/bdist.linux-x86_64/wheel/RecordEcos/gui/img
adding 'RecordEcos/gui/img/Placeholder.png'
</code></pre>
<p>Actually, it's working on my laptop even if I don't add the setuptools <code>package-data</code> option. Which seems to be quite consonant with setuptools <a href="https://setuptools.pypa.io/en/latest/userguide/datafiles.html#package-data" rel="nofollow noreferrer">documentation</a>.</p>
<p>So I've pushed it to gitlab, the CI has been triggered... And the resulting wheel does not contains the image.<br />
So to be sure, I've try it within a docker image:</p>
<pre class="lang-bash prettyprint-override"><code>laptop $ docker run -it python:3.11 /bin/bash
python-container $ pip install build
python-container $ git clone <repository>
python-container $ cd <repository>
python-container & python -m build |Β grep Placeholder
</code></pre>
<p>The image is not copied !</p>
<p>Does someone have any clue what's happening there ?</p>
<p>I've tried it with the alpine, slim and bookworm variants of <code>python:3.11</code></p>
<h4>Misc informations</h4>
<p>laptop under ArchLinux</p>
<p><strong>Python & packages</strong><br />
Python: 3.11.8<br />
build: 1.1.1<br />
setuptools: 65.6.0</p>
<p><strong>gitlab-ci.yml</strong></p>
<pre class="lang-yaml prettyprint-override"><code>build:
stage: build
image: python:3.11-alpine
script:
- pip install build
- python -m build
artifacts:
untracked: false
when: on_success
expire_in: "30 days"
paths:
- dist/
</code></pre>
|
<python><setuptools><pyproject.toml>
|
2024-03-20 13:07:39
| 1
| 5,140
|
NiziL
|
78,193,430
| 3,917,215
|
Generating graph like structure based on multiple columns using Python
|
<p>I have a dataframe with the following columns: Node1, Node2, Node1_REV, and Node2_REV. In this structure, Node1 serves as a parent node, while Node2 functions as a child node. Both Node1_REV and Node2_REV capture different revisions of their respective nodes. ChildNode values may possess their own child values, indicated in columns ChildNode and ChildNode_Rev.</p>
<p>For instance, B1/1, B2/1, and B2/2 have their own child values in the ChildNode/ChildNode_Rev columns. Additionally, values such as B1/1 may appear in different ParentNodes like A1/1 and A2/1, while values like B2/1 may appear in A1/2, with different revisions like B2/2 potentially appearing in another ParentNode like A2/2.</p>
<p>This hierarchical chain continues until a path is established where a parentNode doesn't appear as a childNode to any other values.</p>
<p>To generate the desired output, it's necessary to traverse through all the values, identifying all possible levels and combinations until the top node is reached. When checking for possible links, the combination of Node+Rev should be considered unique, rather than just the Node value alone.</p>
<ul>
<li><strong>Sample Input Dataframe:</strong></li>
</ul>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th>Node1</th>
<th>Node1_Rev</th>
<th>Node2</th>
<th>Node2_REV</th>
<th>REF</th>
<th>DES</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>1</td>
<td>B1</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>A1</td>
<td>2</td>
<td>B2</td>
<td>1</td>
<td>12</td>
<td>SG</td>
</tr>
<tr>
<td>A2</td>
<td>1</td>
<td>B1</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>A2</td>
<td>2</td>
<td>B2</td>
<td>2</td>
<td>12</td>
<td>SG</td>
</tr>
<tr>
<td>B1</td>
<td>1</td>
<td>K5</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>B1</td>
<td>1</td>
<td>K1</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>B2</td>
<td>2</td>
<td>T1</td>
<td>1</td>
<td>12</td>
<td>S1</td>
</tr>
<tr>
<td>A3</td>
<td>2</td>
<td>G7</td>
<td>2</td>
<td>12</td>
<td>G2A3</td>
</tr>
<tr>
<td>A3</td>
<td>3</td>
<td>H9</td>
<td>1</td>
<td>23</td>
<td>...</td>
</tr>
<tr>
<td>B2</td>
<td>1</td>
<td>J1</td>
<td>3</td>
<td>22</td>
<td>SSD</td>
</tr>
</tbody>
</table></div>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'Node1': ['A1','A1','A2','A2','B1','B2','A3','A3','B2'],
'Node1_Rev': ['1','2','1','2','1','2','2','3','1'],
'Node2': ['B1','B2','B1','B2','K5','T1','G7','H9','J1'],
'Node2_Rev': ['1','1', '1','2','1','1','2','1','3'],
'REF' : ['11','12','11','12','11','12','12','23','22'],
'DES' : ['QR','SG','QW','SG','QR','S1','G2A3','...','SSD']
}
)
</code></pre>
<ul>
<li><strong>Sample Output Dataframe:</strong></li>
</ul>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th>Node0</th>
<th>Node0_Rev</th>
<th>Node1</th>
<th>Node1_REV</th>
<th>Node2</th>
<th>Node2_REV</th>
<th>REF</th>
<th>DES</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>1</td>
<td>A1</td>
<td>1</td>
<td>B1</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>A1</td>
<td>2</td>
<td>A1</td>
<td>2</td>
<td>B2</td>
<td>1</td>
<td>12</td>
<td>SG</td>
</tr>
<tr>
<td>A2</td>
<td>1</td>
<td>A2</td>
<td>1</td>
<td>B1</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>A2</td>
<td>2</td>
<td>A2</td>
<td>2</td>
<td>B2</td>
<td>2</td>
<td>12</td>
<td>SG</td>
</tr>
<tr>
<td>A1</td>
<td>1</td>
<td>B1</td>
<td>1</td>
<td>K5</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>A2</td>
<td>1</td>
<td>B1</td>
<td>1</td>
<td>K1</td>
<td>1</td>
<td>11</td>
<td>QR</td>
</tr>
<tr>
<td>A2</td>
<td>2</td>
<td>B2</td>
<td>2</td>
<td>T1</td>
<td>1</td>
<td>12</td>
<td>S1</td>
</tr>
<tr>
<td>A3</td>
<td>2</td>
<td>A3</td>
<td>2</td>
<td>G7</td>
<td>2</td>
<td>12</td>
<td>G2A3</td>
</tr>
<tr>
<td>A3</td>
<td>3</td>
<td>A3</td>
<td>3</td>
<td>H9</td>
<td>1</td>
<td>23</td>
<td>...</td>
</tr>
<tr>
<td>A1</td>
<td>2</td>
<td>B2</td>
<td>1</td>
<td>J1</td>
<td>3</td>
<td>22</td>
<td>SSD</td>
</tr>
</tbody>
</table></div>
<p><a href="https://i.sstatic.net/2KWTa.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2KWTa.png" alt="enter image description here" /></a></p>
<p>What are the efficient ways to generate the output for a bigger dataset?</p>
<p><a href="https://stackoverflow.com/users/16343464/mozway">https://stackoverflow.com/users/16343464/mozway</a> Opened this new question to enhance the <a href="https://stackoverflow.com/questions/75315046/how-to-make-a-hierarchical-structure-based-on-multi-level-data/75315212?noredirect=1#comment137850403_75315212">How to make a hierarchical structure based on multi level data</a></p>
|
<python><pandas><dataframe>
|
2024-03-20 12:47:28
| 2
| 353
|
Osceria
|
78,193,207
| 9,251,158
|
How to add a specific number of silent samples to an audio file
|
<p>I am manipulating audio with pydub for use with video. I want to pad the end of an audio segment with silent frames so it fills a frame of video. At an audio sampling rate of 48kHz and a video sampling rate of 25 fps, I need each audio segment to have a multiple of 1920 samples (= 48 000 / 25).</p>
<p>I followed <a href="https://stackoverflow.com/questions/51408458/pydub-slice-audio-segment-by-sample">this thread</a> to add silent samples at the end of a segment:</p>
<pre class="lang-py prettyprint-override"><code>import pydub
segment = pydub.AudioSegment.from_wav("jingle.wav")
sampling_rate = segment.frame_rate
assert 48000 == sampling_rate
num_samples = len(segment.get_array_of_samples())
num_samples_to_add = 1920 - num_samples % 1920
silence = pydub.AudioSegment.silent(duration=1000, frame_rate=sampling_rate)
silence_samples = silence.get_array_of_samples()
silence_padding = silence._spawn(silence_samples[:num_samples_to_add])
padded = segment + silence_padding
print("Segment: %d samples, %dms" % (len(segment.get_array_of_samples()), len(segment)))
print("Silence: %d samples, %dms" % (len(silence_padding.get_array_of_samples()), len(silence_padding)))
print("Padded: %d samples, %dms" % (len(padded.get_array_of_samples()), len(padded)))
print("Padded should have %d frames instead of %d" % (num_samples + num_samples_to_add, len(padded.get_array_of_samples())))
</code></pre>
<p>The result is:</p>
<pre><code>Segment: 230544 samples, 2402ms
Silence: 1776 samples, 37ms
Padded: 234096 samples, 2438ms
Padded should have 232320 frames instead of 234096
</code></pre>
<p>The number of milliseconds in the result is right, but the number of samples is not. The code worked on one WAV file but doesn't on <a href="https://www.dropbox.com/scl/fi/hfxqry0kfwbehrad5sd08/jingle.wav?rlkey=idngfwaqi6cw0liy45wfwz1jf&dl=0" rel="nofollow noreferrer">this one</a>. I suspect it's because of improper use of <code>._spawn</code>, but I could not find documentation and I cannot figure out why the discrepancy between duration in seconds and in samples.</p>
<p>How can I add a specific number of silent samples at the end of an audio file?</p>
|
<python><audio><pydub>
|
2024-03-20 12:12:32
| 0
| 4,642
|
ginjaemocoes
|
78,193,123
| 16,525,263
|
How to use window function in pyspark dataframe
|
<p>I have a pyspark dataframe as below:</p>
<pre><code>Mail sno mail_date date1 present
abc@abc.com 790 2024-01-01 2024-02-06 yes
abc@abc.com 790 2023-12-23 2023-01-01
nis@abc.com 101 2022-02-23
nis@abc.com 101 2021-01-20 2022-07-09 yes
</code></pre>
<p>In the final dataframe, I need one record of <code>sno</code> with all the max date values and corresponding max date in mail_date column for <code>present</code>
So the final dataframe should be like:</p>
<pre><code>Mail sno mail_date date1 present
abc@abc.com 790 2024-01-01 2024-02-06 yes
nis@abc.com 101 2022-02-23 2022-07-09
</code></pre>
<p>I have the following code,</p>
<pre><code>windowSpec=Window.partitionBy('Mail','sno')
df= df.withColumn('max_mail_date', F.max('mail_date').over(windowSpec))\
.withColumn('max_date1', F.max('date1').over(windowSpec))
df1 = df.withColumn('mail_date', F.when(F.col('mail_date').isNotNull(), F.col('max_mail_date')).otherwise(F.col('mail_date')))\
.drop('max_mail_date').dropDuplicates()
</code></pre>
<p>Here, Im not getting the expected values in the present column.
Please suggest any changes</p>
|
<python><apache-spark><join><pyspark>
|
2024-03-20 11:59:47
| 2
| 434
|
user175025
|
78,192,929
| 3,433,875
|
ax.get_position wont give me position of all plots on multiple subplots
|
<p>I am trying to overlap a matrix of subplots.</p>
<p>The code I am using is:</p>
<pre><code>fig, axes = plt.subplots(ncols =2, nrows = 2, figsize=(8,8), sharey=True, facecolor = "#FFFFFF", subplot_kw=dict(polar=True) ,constrained_layout=True)
fig.tight_layout(h_pad=-5)
directions = [1,-1]
for ax,direction in zip(axes.ravel(), directions):
shift_axes = 0.2 if direction == 1 else -0.2
box = ax.get_position()
print(box)
box.x0 = box.x0 + shift_axes #x0 first coordinate of the box
box.x1 = box.x1 + shift_axes #x1 last coordinate of the box
ax.set_position(box)
</code></pre>
<p>Which returns:</p>
<p><a href="https://i.sstatic.net/LLE6V.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LLE6V.png" alt="enter image description here" /></a></p>
<p>If I print the results of box, I get only the first two. What am I doing wrong?
<a href="https://i.sstatic.net/TNNnD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TNNnD.png" alt="enter image description here" /></a></p>
|
<python><matplotlib>
|
2024-03-20 11:31:46
| 0
| 363
|
ruthpozuelo
|
78,192,905
| 1,194,864
|
Unexpected printouts interfere with tqdm progress bar in PyTorch training run
|
<p>I am trying to understand how the progress bar using <code>tqdm</code> works exactly. I have some code that looks as follows:</p>
<pre><code>import torch
import torchvision
print(f"torch version: {torch.__version__}")
print(f"torchvision version: {torchvision.__version__}")
load_data()
manual_transforms = transforms.Compose([])
train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders()
# them within the main function I have placed the train function that exists in the `engine.py` file
def main():
results = engine.train(model=model,
train_dataloader=train_dataloader,
test_dataloader=test_dataloader,
optimizer=optimizer,
loss_fn=loss_fn,
epochs=5,
device=device)
</code></pre>
<p>and the <code>engine.train()</code> function includes the following code <code>for epoch in tqdm(range(epochs)):</code> then, the training for each batch takes place to visualize the progress of the training. Each time the tqdm runs for each step it prints also the following statements:</p>
<pre><code>print(f"torch version: {torch.__version__}")
print(f"torchvision version: {torchvision.__version__}")
</code></pre>
<p>So finally, my question is why this is happening. How does the main function have access to these global statements and how can avoid printing everything in each loop?</p>
|
<python><pytorch><tqdm>
|
2024-03-20 11:27:57
| 1
| 5,452
|
Jose Ramon
|
78,192,787
| 1,439,597
|
Celery worker container never restarts after getting MemoryError
|
<p>I am getting this annoying issue on my production machine, where I have a docker container for my celery container, configured like this:</p>
<pre><code>worker:
build: .
env_file:
- .env
command: celery -A my_app worker --loglevel=info --concurrency 1 -E
deploy:
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 120s
depends_on:
- api
</code></pre>
<p>My issue is that sadly, this worker often goes out of memory (despite setting <code>worker_max_tasks_per_child = 1000</code>), throwing this error:</p>
<pre><code>[2024-03-19 17:23:24,533: CRITICAL/MainProcess] Unrecoverable error: MemoryError()
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/celery/worker/worker.py", line 203, in start
File "/usr/local/lib/python3.10/site-packages/celery/bootsteps.py", line 116, in start
File "/usr/local/lib/python3.10/site-packages/celery/bootsteps.py", line 365, in start
File "/usr/local/lib/python3.10/site-packages/celery/worker/consumer/consumer.py", line 332, in start
File "/usr/local/lib/python3.10/site-packages/celery/bootsteps.py", line 116, in start
step.start(parent)
File "/usr/local/lib/python3.10/site-packages/celery/worker/consumer/consumer.py", line 628, in start
c.loop(*c.loop_args())
File "/usr/local/lib/python3.10/site-packages/celery/worker/loops.py", line 97, in asynloop
next(loop)
File "/usr/local/lib/python3.10/site-packages/kombu/asynchronous/hub.py", line 362, in create_loop
File "/usr/local/lib/python3.10/site-packages/kombu/transport/redis.py", line 1326, in on_readable
File "/usr/local/lib/python3.10/site-packages/kombu/transport/redis.py", line 562, in on_readable
File "/usr/local/lib/python3.10/site-packages/kombu/transport/redis.py", line 955, in _brpop_read
File "/usr/local/lib/python3.10/site-packages/redis/client.py", line 1275, in parse_response
File "/usr/local/lib/python3.10/site-packages/redis/connection.py", line 865, in read_response
File "/usr/local/lib/python3.10/site-packages/redis/connection.py", line 346, in read_response
File "/usr/local/lib/python3.10/site-packages/redis/connection.py", line 356, in _read_response
File "/usr/local/lib/python3.10/site-packages/redis/connection.py", line 259, in readline
File "/usr/local/lib/python3.10/site-packages/redis/connection.py", line 209, in _read_from_socket
MemoryError
</code></pre>
<p>And the REAL BIG issue for me right now, is that the docker container never restarts after hitting this crash, and I have no idea why! My django container also gets memory errors and seems to restart fine (with the exact same <code>restart_policy</code>), but not this one...</p>
<p>I tried setting the container's <code>mem_limit</code> to some arbitrary value (1/4 of the host's RAM), as I read that maybe the MemoryError could be stopping the container without any error... (but as I said, I already received MemoryErrors on my django container and it restarted fine), to no avail.</p>
|
<python><docker><docker-compose><celery><out-of-memory>
|
2024-03-20 11:07:03
| 1
| 4,850
|
SylvainB
|
78,192,584
| 3,212,623
|
Running AWS SAM locally throws aws_lambda_powertools not found
|
<p>I am trying to setup AWS SAM python project with <code>aws-lambda-powertools</code>. I have added the <code>aws-lambda-powertools</code> to requirements as well. When I deploy it to AWS, the import of <code>aws-lambda-powertools</code> works fine.
However, when running locally <code>sam local start-api -t template.yaml</code> throws</p>
<pre><code>{
"errorMessage": "Unable to import module 'app' No module named 'aws_lambda_powertools'",
"errorType": "Runtime.ImportModuleError",
"requestId": "996dae2b-7708-4693-9657-6e3aaef4fc2d",
"stackTrace": []
}
</code></pre>
<p>The python aws lambda code is:</p>
<pre class="lang-py prettyprint-override"><code>from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools import Logger
from aws_lambda_powertools import Tracer
from aws_lambda_powertools import Metrics
from aws_lambda_powertools.metrics import MetricUnit
app = APIGatewayRestResolver()
tracer = Tracer()
logger = Logger()
metrics = Metrics(namespace="Powertools")
@app.get("/hello")
@tracer.capture_method
def hello():
# adding custom metrics
# See: https://awslabs.github.io/aws-lambda-powertools-python/latest/core/metrics/
metrics.add_metric(name="HelloWorldInvocations", unit=MetricUnit.Count, value=1)
# structured log
# See: https://awslabs.github.io/aws-lambda-powertools-python/latest/core/logger/
logger.info("Hello world API - HTTP 200")
return {"message": "hello world"}
# Enrich logging with contextual information from Lambda
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
# Adding tracer
# See: https://awslabs.github.io/aws-lambda-powertools-python/latest/core/tracer/
@tracer.capture_lambda_handler
# ensures metrics are flushed upon request completion/failure and capturing ColdStart metric
@metrics.log_metrics(capture_cold_start_metric=True)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context)
</code></pre>
<p>My SAM template has,</p>
<pre><code>Globals: # https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-template-anatomy-globals.html
Function:
Timeout: 5
MemorySize: 128
Runtime: python3.12
Tracing: Active
# You can add LoggingConfig parameters such as the Logformat, Log Group, and SystemLogLevel or ApplicationLogLevel. Learn more here https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-loggingconfig.
LoggingConfig:
LogFormat: JSON
Api:
TracingEnabled: true
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html
Properties:
Handler: app.lambda_handler
CodeUri: hello_world
Description: Hello World function
Architectures:
- x86_64
Tracing: Active
Events:
HelloPath:
Type: Api # More info about API Event Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-api.html
Properties:
Path: /hello
Method: GET
</code></pre>
<p>Is there some extra config that I need to follow?</p>
|
<python><amazon-web-services><aws-lambda><aws-sam><aws-sam-cli>
|
2024-03-20 10:36:41
| 1
| 3,165
|
pnv
|
78,192,496
| 2,102,290
|
cdktf lifecycle ignore_changes doesn't seem to work for tags
|
<p>I have a terraform stack that is managed using the python version of <code>cdktf</code> where each instance has some tags associated with it, something like:</p>
<pre class="lang-py prettyprint-override"><code>start_time = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
self.instance = Instance(
self,
f"some-instance",
ami=ami,
instance_type=instance_type,
...
tags=dict(
start_time=start_time,
...
)
)
</code></pre>
<p>When I do a <code>cdktf deploy</code> with this, I always get a change to the "starting" tag. I would like to avoid this being marked as a diff so going by <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/resource-tagging#ignoring-changes-in-individual-resources" rel="nofollow noreferrer">this</a> post it seems it should be possible to add a <code>lifecycle</code> entry and it will be ignored:</p>
<pre class="lang-py prettyprint-override"><code>self.instance = Instance(
...
lifecycle=dict(ignore_changes=["tags.start_time"]),
)
</code></pre>
<p>However, this doesn't seem to work. It doesn't seem to have much documentation in this area so I suspect I'm doing something wrong with the format.</p>
<p>Does anyone know what the correct format is? Or if this should even work?</p>
<hr />
<p>[1] <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/resource-tagging#ignoring-changes-in-individual-resources" rel="nofollow noreferrer">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/resource-tagging#ignoring-changes-in-individual-resources</a></p>
|
<python><terraform><terraform-cdk>
|
2024-03-20 10:23:04
| 0
| 582
|
Michael
|
78,192,477
| 13,954,738
|
Unexpected keyword argument 'as_tuple' error in Flask even after upgrading werkzeug version to 2.0.3
|
<p>While I am testing my API I recently started to get the error below.</p>
<pre><code> if request is None:
> builder = EnvironBuilder(*args, **kwargs)
E TypeError: EnvironBuilder.__init__() got an unexpected keyword argument 'as_tuple'
</code></pre>
<p>Code:</p>
<pre><code>@pytest.fixture(autouse=True)
def client():
app = my_app()
with app.test_client() as client:
yield client
def test_new_func(client, monkeypatch):
monkeypatch.setattr(UnitPricing, 'find_unit_price', find_unit_pricing)
monkeypatch.setattr(FullPricing, 'find_full_price', find_full_pricing)
response = client.post("/price/calc", json=input_payload)
assert response.status_code == 200
assert json.loads(response.data) == output_data
</code></pre>
<p>In one of the solutions, it was suggested to pin <code>werkzeug</code> version to <code>2.0.3</code> and my requirement.txt file is meeting this condition but I'm still getting the error.</p>
<p><a href="https://stackoverflow.com/questions/71661851/typeerror-init-got-an-unexpected-keyword-argument-as-tuple">TypeError: __init__() got an unexpected keyword argument 'as_tuple'</a></p>
<pre><code>> pip show Flask werkzeug
Name: Flask
Version: 2.0.2
Summary: A simple framework for building complex web applications.
Home-page: https://palletsprojects.com/p/flask
Author: Armin Ronacher
Author-email: armin.ronacher@active-4.com
License: BSD-3-Clause
Location: c:\users\xyz\venv\lib\site-packages
Requires: click, itsdangerous, Jinja2, Werkzeug
Required-by: Flask-Session, Flask-SQLAlchemy
---
Name: Werkzeug
Version: 2.0.3
Summary: The comprehensive WSGI web application library.
Home-page: https://palletsprojects.com/p/werkzeug/
Author: Armin Ronacher
Author-email: armin.ronacher@active-4.com
License: BSD-3-Clause
Location: c:\users\xyz\venv\lib\site-packages
Requires:
Required-by: Flask
</code></pre>
<p>Any help would be appreciated.</p>
|
<python><flask>
|
2024-03-20 10:20:47
| 0
| 336
|
ninjacode
|
78,192,426
| 6,649,591
|
How to use Solr as retriever in RAG
|
<p>I want to build a RAG (Retrieval Augmented Generation) service with LangChain and for the retriever I want to use Solr.
There is already a python package <code>eurelis-langchain-solr-vectorstore</code> where you can use Solr in combination with LangChain but how do I define server credentials? And my embedding model is already running on a server. I thought something like this but I don't know</p>
<pre class="lang-py prettyprint-override"><code>import requests
from eurelis_langchain_solr_vectorstore import Solr
embeddings_model = requests.post("http://server-insight/embeddings/")
solr = Solr(embeddings_model, core_kwargs={
'page_content_field': 'text_t', # field containing the text content
'vector_field': 'vector', # field containing the embeddings of the text content
'core_name': 'langchain', # core name
'url_base': 'http://localhost:8983/solr' # base url to access solr
}) # with custom default core configuration
retriever = solr.as_retriever()
</code></pre>
|
<python><solr><fastapi><langchain>
|
2024-03-20 10:12:33
| 1
| 487
|
Christian
|
78,192,256
| 9,472,819
|
Decorated function call now showing warning for incorrect arguments in PyCharm
|
<p>I'm having some problems when static type checking decorated functions. For instance, when I use an incorrect function argument name or type, I don't get any warning or error hints in the IDE, only at runtime.</p>
<p><strong>What steps will reproduce the problem?</strong></p>
<ul>
<li><p>Add a decorator to a function</p>
</li>
<li><p>Use a incorrect argument name or type</p>
</li>
</ul>
<p><strong>What is the expected result?</strong></p>
<ul>
<li>PyCharm should highlight the wrong argument name or wrong type.</li>
</ul>
<p><strong>What happens instead?</strong></p>
<ul>
<li>The attribute name is not highlighted.</li>
</ul>
<p><strong>Additional Info</strong></p>
<ul>
<li>This is with Python 3.10 and PyCharm 2023.3.4</li>
</ul>
<p>Code sample follows:</p>
<pre><code>def myDecorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@myDecorator
def myFunc(x: int, y: int):
print(x+y)
myFunc(z=4, x="something") # Expecting "z=4" and x="something" to be highlighted
</code></pre>
<h2>Edit</h2>
<p>It's now working with regular functions. However, I'm encountering the same problem if these functions are defined inside of a Class, as seen below:</p>
<pre><code>from typing import ParamSpec
from typing import TypeVar
from typing import Callable
P = ParamSpec("P")
T = TypeVar("T")
def myDecorator(func: Callable[P, T]) -> Callable[P, T]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
return func(*args, **kwargs)
return wrapper
class myClass:
@myDecorator
def myFunc2(self, x: int, y: int) -> None:
print(x + y)
@myDecorator
def another_function(self):
self.myFunc2(x=3) # showing type hinting: P and highlighting "x=3" as a wrong argument.
</code></pre>
|
<python><pycharm><decorator><python-typing>
|
2024-03-20 09:43:57
| 1
| 749
|
tomas-silveira
|
78,191,944
| 13,086,128
|
What is the difference between read, scan, and sink in polars?
|
<p>In polars I see methods are <code>read</code>, <code>scan</code> and <code>sink</code> for the input.</p>
<p>For the output, we have <code>write</code>.</p>
<p>What is the difference between <code>read</code>, <code>scan</code>, and <code>sink</code> ?</p>
<p><a href="https://docs.pola.rs/py-polars/html/reference/io.html" rel="nofollow noreferrer">https://docs.pola.rs/py-polars/html/reference/io.html</a></p>
<p><a href="https://i.sstatic.net/KTPQF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KTPQF.png" alt="enter image description here" /></a></p>
|
<python><python-3.x><python-polars>
|
2024-03-20 08:52:46
| 1
| 30,560
|
Talha Tayyab
|
78,191,890
| 2,625,540
|
Relative Import: No Known Parent Package
|
<p>I'm trying to do a relative import. From my understanding, I should have an <code>__init__.py</code> file to suggest this is a module.</p>
<p>Let's say I have:</p>
<pre><code>$ ls
__init__.py foo.py bar.py
</code></pre>
<p><code>__init__.py</code> is an empty file. Additionally:</p>
<pre><code>$ cat foo.py
from .bar import MyExampleClass
thing = MyExampleClass()
</code></pre>
<p>and</p>
<pre><code>$ cat bar.py
class MyExampleClass():
pass
</code></pre>
<p>So, why do I get?</p>
<pre><code>ImportError: attempted relative import with no known parent package
</code></pre>
|
<python><python-import><importerror>
|
2024-03-20 08:43:12
| 1
| 744
|
pgierz
|
78,191,884
| 1,537,366
|
DuckDB pandas pass DataFrame by name easily with IntelliSense support
|
<p>In DuckDB, we have to directly use the DataFrame variable name as a string in the SQL syntax (as shown <a href="https://duckdb.org/2021/05/14/sql-on-pandas.html" rel="nofollow noreferrer">here</a>):</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import duckdb
mydf = pd.DataFrame({'a' : [1, 2, 3]})
print(duckdb.query("SELECT SUM(a) FROM mydf").to_df())
</code></pre>
<p>But in VS Code the IntelliSense will not recognise the reference to <code>mydf</code> in the second statement, and it will mark <code>mydf</code> as unreferenced. And if <code>mydf</code> is renamed with IntelliSense, of course the second statement will break. Is there any way to make IntelliSense work?</p>
|
<python><pandas><visual-studio-code><duckdb>
|
2024-03-20 08:41:50
| 1
| 1,217
|
user1537366
|
78,191,881
| 12,415,855
|
Accessing with python and sshtunnel not possible on Mac?
|
<p>i try to access my mysql-database using a sshtunnel in python with the following code -</p>
<pre><code>import mysql.connector
import sshtunnel
if __name__ == '__main__':
with sshtunnel.SSHTunnelForwarder(
("xyz.a2hosting.com", 7822),
ssh_username="myName",
ssh_password="myPW",
remote_bind_address=("0.0.0.0", 3306),
local_bind_address=("127.0.0.1", 3306),
allow_agent=False
) as tunnel:
mydb = mysql.connector.connect(
user="myUser",
password="myPW",
host="127.0.0.1",
database="myDB",
port="3306")
c = mydb.cursor()
print(f"Access is working fine!")
</code></pre>
<p>This works fine on my windows computer without problems.</p>
<p>But on my Mac i get the following error:</p>
<pre><code>(openai) PolziMacs-Mini:colli239 polzimac$ python test1.py
2024-03-20 09:35:50,928| ERROR | Password is required for key /Users/polzimac/.ssh/id_ed25519
2024-03-20 09:35:53,579| ERROR | Problem setting SSH Forwarder up: Couldn't open tunnel 0.0.0.0:3306 <> 127.0.0.1:3306 might be in use or destination not reachable
Traceback (most recent call last):
File "/Users/polzimac/Documents/DEV/Fiverr/TRY/colli239/test1.py", line 5, in <module>
with sshtunnel.SSHTunnelForwarder(
File "/Users/polzimac/Documents/DEV/venv/openai/lib/python3.9/site-packages/sshtunnel.py", line 1608, in __enter__
self.start()
File "/Users/polzimac/Documents/DEV/venv/openai/lib/python3.9/site-packages/sshtunnel.py", line 1344, in start
self._raise(HandlerSSHTunnelForwarderError,
File "/Users/polzimac/Documents/DEV/venv/openai/lib/python3.9/site-packages/sshtunnel.py", line 1174, in _raise
raise exception(reason)
sshtunnel.HandlerSSHTunnelForwarderError: An error occurred while opening tunnels.
</code></pre>
<p>How can i run this also on my Mac-Computer?</p>
|
<python><macos><mysql-connector><ssh-tunnel>
|
2024-03-20 08:41:22
| 0
| 1,515
|
Rapid1898
|
78,191,857
| 6,930,340
|
pandas.to_parquet pyarrow.lib.ArrowInvalid: Could not convert Timedelta
|
<p>I have a huge multiindex dataframe in long format. There's only one "value" column. Some entries in "value" are of type <code>pd.Timedelta</code>.</p>
<p>I got an error when trying to save that dataframe as <code>parquet</code> file using <code>pd.to_parquet</code>:</p>
<p><code>pyarrow.lib.ArrowInvalid: ("Could not convert Timedelta('2903 days 00:00:00') with type Timedelta: tried to convert to double", 'Conversion failed for column value with type object')</code></p>
<p>If I convert the particular value from the error message to <code>numpy</code>, I get the following:</p>
<p><code>array([Timedelta('2903 days 00:00:00')], dtype=object)</code></p>
<p>I set up a toy example to check if it is possible at all to convert <code>pd.Timedelta</code> to <code>parquet</code>. The following code works just fine:</p>
<pre><code>import pandas as pd
idx = pd.MultiIndex.from_tuples(
[("A", "x"), ("A", "y"), ("B", "x"), ("B", "y")],
names=["idx1", "idx2"])
data = {"value": [
pd.Timedelta(days=10),
2.5,
pd.Timedelta(days=20),
5
]}
df = pd.DataFrame(data=data, index=idx)
df.to_parquet("test.parquet")
x = pd.read_parquet("test.parquet")
</code></pre>
<p>A simple <code>df.iloc[0, :].to_numpy()</code> delivers the exact same type as in my real dataframe: <code>array([Timedelta('10 days 00:00:00')], dtype=object)</code>.</p>
<p>I am wondering what might be the difference of my original dataframe compared to my toy example?</p>
|
<python><pandas><parquet><pyarrow>
|
2024-03-20 08:37:23
| 2
| 5,167
|
Andi
|
78,191,580
| 1,866,775
|
How to catch potentially undefined variables with pylint or mypy?
|
<pre class="lang-py prettyprint-override"><code>import time
if time.time() > 42:
x = 1
print(x)
</code></pre>
<p>My IDE (PyCharm) warns me about <code>x</code> potentially being undefined:</p>
<p><a href="https://i.sstatic.net/cSFrR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cSFrR.png" alt="enter image description here" /></a></p>
<p>But <code>pylint</code> and <code>mypy</code> do not say anything. Is there a way to make one of them complain about this situation too?</p>
|
<python><python-3.x><mypy><lint><pylint>
|
2024-03-20 07:47:11
| 3
| 11,227
|
Tobias Hermann
|
78,191,505
| 4,427,777
|
`pandas` datetime - correct way to do linear interpolation
|
<p>FYI: <code>pandas</code> version is 1.3.4 for now</p>
<p>I have currently working code to interpolate non-monotonous timestamps (along with various other data not sampled monotonously) into a dataframe <code>out</code> with a monotonous (float-type) time <code>index</code>. The important part is here:</p>
<pre><code>out = out.join(dateTime_df.astype('int64'),
how = 'outer',
).interpolate(method = 'linear',
limit_area = 'inside',
).loc[index] #`index` is the monotonous time index
out["DateTime_col"] = out["DateTime_col"].astype('<M8[ns]')
</code></pre>
<p>This currently works, but throws a <code>FutureWarning</code>:</p>
<pre><code>FutureWarning: casting datetime64[ns] values to int64 with .astype(...) is deprecated and will raise in a future version. Use .view(...) instead.
</code></pre>
<p>I'm wondering what the "right" way to do this would be, using <code>.view()</code>, as it doesn't seem like <code>DataFrame</code> has a <code>view</code> method (at least in my ancient <code>pandas</code> version 1.3.4 I'm stuck with for now). I'm somewhat afraid to update my <code>pandas</code> version until I have a fix.</p>
<p>Edit: adding test data:</p>
<pre><code>out = pd.DataFrame(np.random.rand(10, 3),
columns = ['previously', 'imported', 'data'])
dateTime_df = pd.DataFrame([datetime.datetime.now() - datetime.timedelta(days = 1),
datetime.datetime.now()],
index = [3, 7],
columns = ["DateTime_col"])
index = np.arange(10)
</code></pre>
|
<python><pandas><datetime><type-conversion><interpolation>
|
2024-03-20 07:32:51
| 0
| 14,469
|
Daniel F
|
78,191,480
| 231,934
|
Register jupyter variable from an another module
|
<p>I created simple cell magic function for calling AWS Athena</p>
<pre><code>import awswrangler as wr
import inspect
import pandas as pd
from IPython.core.magic import (register_line_magic, register_cell_magic,
register_line_cell_magic)
@register_cell_magic
def athena(line, cell):
"""
Execute athena query and return the result as a pandas dataframe
Usage:
>>> %%athena <database> [<destination_var>]
:param line:
:param cell:
:return:
"""
args = []
if line:
args = line.split()
df = wr.athena.read_sql_query(cell, database=args[0])
if len(args) > 1:
globals()[args[1]] = df
else:
return df
</code></pre>
<p>and put it into separate module that's imported from the Jupyter notebook.</p>
<p>The problem is that the resulting dataframe is not registered into the global variables of the jupyter notebook, but to the globals of that module.</p>
<p>When I inline this stanza in the notebook and execute it within it then the variable is properly registered and accessible.</p>
<p>What's the correct way of registering that dataframe into the Jupyter's globals?</p>
<p>I tried several hacks using inspect library to get the importer module but it didn't work for me and I fell like this is an invalid solution.</p>
<p>Isn't there any way to get the notebooks globals properly or even some special context that allows me to register variables properly?</p>
|
<python><jupyter-notebook>
|
2024-03-20 07:27:35
| 1
| 3,842
|
Martin Macak
|
78,191,390
| 7,217,896
|
GPT python SDK introduces massive overhead / incorrect timeout
|
<p>I've been using openai python packge v0.28.1 with the <code>requests_timeout</code> param which worked OK.
I then updated to the ^1. version only to find out that the timeout no longer works as expected (they have changed the param name from <code>requests_timeout</code> to <code>timeout</code>.</p>
<p>Here is an odd behavior with the current newest version (1.14.1):</p>
<pre><code>from openai import OpenAI, APITimeoutError
import os
client = OpenAI(
api_key=os.environ['OPENAI_API_KEY'],
)
for timeout in [0.001, 0.1, 1, 2]:
with log_duration('openai query') as duration_context:
try:
response = client.chat.completions.create( # type: ignore[call-overload]
model="gpt-4-0125-preview",
messages=[{'content': 'describe the universe in 10000 characters', 'role': 'system'}],
temperature=0.0,
max_tokens=450,
top_p=1,
timeout=timeout
)
except APITimeoutError as e:
continue
</code></pre>
<p>log_duration just measure the time it takes. the result are :</p>
<pre><code>2024-03-20 14:59:19 [info ] openai query duration=2.805093 duration=2.8050930500030518 name=openai query
2024-03-20 14:59:22 [info ] openai query duration=2.844164 duration=2.8441641330718994 name=openai query
2024-03-20 14:59:29 [info ] openai query duration=6.396946 duration=6.396945953369141 name=openai query
2024-03-20 14:59:38 [info ] openai query duration=9.387082 duration=9.387081861495972 name=openai query
</code></pre>
<p>which is way more then the timeouts. We have been getting a bunch of timeouts on our lambdas without understanding why as the timeout on openai is supposed to be so much lower.</p>
<p>what am I missing? is there such a big overhead in OpenAI's >1 python SDK?</p>
|
<python><openai-api><chatgpt-api><gpt-4>
|
2024-03-20 07:04:28
| 1
| 3,778
|
NotSoShabby
|
78,191,273
| 1,581,090
|
How to create and use a virtual environment with PyCharm on windows?
|
<p>I am new to PyCharm and need to run pytests within a virtual environment using PyCharm 2023.3.4 (Community Edition) on Windows 10. I am following the documentation <a href="https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html#python_create_virtual_env" rel="nofollow noreferrer">HERE</a> which seems to describe how to create and use a virtual environment with PyCharm. But either the documentation is outdated, or I am doing something wrong...</p>
<p>In the section <code>Create a virtual environment using the project requirements</code> it says to open the project folder containing the file <code>requirements.txt</code> will prompt a popup to create a virtual environment for that project - that is not true. I do not see such a popup.</p>
<p>Addendum: You have to create a new existing project with the <code>requirements.txt</code> file DIRECTLY in that folder. Not a project where it is in a subfolder!</p>
<p>Before that in the section <code>Create a virtualenv environment</code> it explains to add a Python Interpreter. I followed these somewhat complicated instructions and ended up with a <code>venv</code> folder which did not contain a <code>python</code> executable. So I am a bit lost. Should I first create the virtual environment inside a PowerShell and then "add" that to the project? Or is there some way that PyCharm creates it and installs all requirements?</p>
<p>I created a virtual environment locally and tried to add this as an "Python Interpreter". That did not work as I get the error "Environment location directory is not empty"...</p>
|
<python><windows><pycharm>
|
2024-03-20 06:40:27
| 1
| 45,023
|
Alex
|
78,191,214
| 1,202,995
|
python to_bytes() to return an even number of digits
|
<p>I'm trying to convert an int (i.e. 3490) into 2 bytes via the <code>to_bytes()</code> function and instead of returning <strong>b'\x0d\xa2'</strong>, I'm getting <strong>b'\r\xa2'</strong>. What am I missing here and how can I get the former to return?</p>
|
<python><hex><byte>
|
2024-03-20 06:24:39
| 2
| 308
|
tehawtness
|
78,191,158
| 894,126
|
Selenium fetches first 4 elements while scraping
|
<p>Scraping code below only fetches 4 elements of "price", however once page is fully loaded there are 71 price related elements on the page.</p>
<p>Scraping code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
import pickle
import pandas as pd
import time
# Initializing a list with two Useragents
useragentarray = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
]
options = Options()
options.add_argument("start-maximized")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.headless = True
web = "https://www.urbanoutfitters.com/womens-clothing"
driver = webdriver.Chrome(options=options)
driver.execute_cdp_cmd("Network.setUserAgentOverride", {"userAgent": useragentarray[0]})
driver.get(web)
user_agent = driver.execute_script("return navigator.userAgent;")
try:
product_container = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, 'c-pwa-tile-tiles')))
except NoSuchElementException:
print('Main container does not exist!')
prices = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.XPATH, './/div[@class="c-pwa-tile-grid s-pwa-tile-grid"]//span[contains(@class, "c-pwa-product-price__current s-pwa-product-price__current")]')))
print("Prices Length: ",len(prices))
product_name = []
product_price = []
book_length = []
for price in prices:
product_price.append(price.text)
print("product_price => ", product_price)
driver.quit()
</code></pre>
<p>Output:</p>
<p>product_price => ['$130.00', '$42.00 β $52.00', '$19.00', '$69.00']</p>
<p>If I use XPATH in chrome like below, also again get 4 elements, however once I start iterating over it, it loads more elements related to "price"</p>
<p><a href="https://i.sstatic.net/DHdMz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DHdMz.png" alt="enter image description here" /></a></p>
<p>Can you please guide as to how I can fetch all prices on the page, these should be ~71 as there are 71 products listed on the page, probably there is better implementing approach to this problem? perhaps scrolling over the page automatically?</p>
<p>Thanks for your expert input!</p>
|
<python><python-3.x><selenium-webdriver>
|
2024-03-20 06:13:34
| 1
| 510
|
Ayub
|
78,190,677
| 9,855,588
|
building python package with parent folder in structure
|
<p>I'm building a python package that contains the following structure:</p>
<pre><code>foo/
__init__.py
bar_module_one/
__init__.py
do_something_cool.py
buzz_module_two/
__init__.py
youre_lazy.py
</code></pre>
<p>In <code>setup.py</code> I have the following:</p>
<pre><code>from setuptools import find_packages, setup
setup(
version="0.1.0",
name="foo",
packages=find_packages(),
package_dir={"foo": "foo"},
)
</code></pre>
<p>I can't figure out how to make it so the package installs as the same structure. It currently just installs <code>bar_module_one/</code> and <code>buz_module_two/</code>, but I want the modules to be installed as part of foo. I want to be able to do <code>from foo.bar_module_one.do_something_cool import yo</code>.</p>
|
<python><python-3.x>
|
2024-03-20 03:06:24
| 1
| 3,221
|
dataviews
|
78,190,543
| 1,089,957
|
Can Cython be used to define C-callable variadic functions?
|
<p>I'm writing <a href="https://github.com/JesseTG/libretro.py" rel="nofollow noreferrer">a Python library</a> for testing DLLs that implement a particular C API. This library also exposes functionality to the native DLLs through callback functions fetched at runtime. There's a specific function I'd like to implement, and it's declared like so:</p>
<pre class="lang-c prettyprint-override"><code>enum retro_log_level; // definition omitted for brevity
// typedef for a printf-like function
typedef void (RETRO_CALLCONV *retro_log_printf_t)(enum retro_log_level level, const char *fmt, ...);
struct retro_log_callback
{
// defined in Python, called by C
retro_log_printf_t log;
};
</code></pre>
<p>The problem is that <code>retro_log_printf_t</code> is variadic, <a href="https://stackoverflow.com/questions/13867473/can-i-create-a-prototype-for-a-variadic-python-function-using-ctypes-so-that-a-d">and therefore cannot be implemented with <code>ctypes</code></a>. I didn't design or implement this API, so I can't change it.</p>
<p>One idea I had was to implement <code>retro_log_printf_t</code> in C (or similar) so that I can bypass the linked <code>ctypes</code> limit. I'm considering Cython for this, but I don't know if that's possible.</p>
<p>So my question is this: <strong>How can I use Cython to declare and implement a variadic function that can be called from C and is compatible with the aforementioned <code>retro_log_printf_t</code>?</strong></p>
|
<python><c><cython><ctypes><variadic-functions>
|
2024-03-20 02:16:25
| 0
| 2,195
|
JesseTG
|
78,190,525
| 5,087,283
|
Reparameterizing a model in PyTorch
|
<p>I am trying to optimize the parameters of a simple model which is implemented using the PyTorch library. For the purpose of optimization, I would like to use a different representation of the parameters than that which is specified by the model class. I would like, in particular, to represent my parameters as a single vector (rather than two vectors as in this example).</p>
<p>I can convert from <code>model.parameters()</code> (which is an <code>Iterable</code>) to the desired vector representation using <code>parameters_to_vector</code> from <code>torch.nn.utils.convert_parameters</code>. However, when I try to label this vector as a leaf (with <code>detach</code> and <code>requires_grad_</code>), and use it to populate the original parameters of the model object with <code>vector_to_parameters</code>, then it appears that the computation graph is not made aware of what is happening.</p>
<pre><code>#!/usr/bin/python3
import torch
import torch.nn as nn
from torch.nn.utils.convert_parameters import *
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.linear = nn.Linear(10, 1)
def forward(self, x):
return self.linear(x)
model = SimpleModel()
for name, param in model.named_parameters():
print(name, param.size())
# this prints:
## linear.weight torch.Size([1, 10])
## linear.bias torch.Size([1])
loss_function = nn.MSELoss()
vparams = parameters_to_vector(model.parameters()).detach().clone().requires_grad_(True)
# populate model.parameters() from vparams
vector_to_parameters(vparams, model.parameters())
input_data = torch.randn(1, 10)
output = model(input_data)
target = torch.randn(1, 1)
loss = loss_function(output, target)
# loss.backward() ## if we do this, then vparams.grad is None
## this one works, but we wanted to use vparams:
# vgrads = torch.autograd.grad(loss, model.linear.weight)[0]
## this gives an error:
vgrads = torch.autograd.grad(loss, vparams)[0]
## "One of the differentiated Tensors appears to not have been used in the graph."
</code></pre>
<p>I also tried performing the vector slices manually, but this doesn't fix the error. E.g.:</p>
<pre><code>model.linear.weight.data.copy_(vparams[0:10].view_as(model.linear.weight.data))
</code></pre>
<p>or</p>
<pre><code>model.linear.weight = nn.Parameter(vparams[0:10].view_as(model.linear.weight.data))
</code></pre>
<p>I'm somewhat new to PyTorch, but I've read that it is possible with PyTorch to compute gradients through slices, so it seems that what I'm attempting should be possible.</p>
<p>Am I missing something about the <code>torch.nn.Parameter</code> class which is used by PyTorch models? Are members of this class required to be "leaves" in the computation graph? Here is a smaller example that omits the <code>nn.Module</code> subclass and just tries to create a <code>nn.Parameter</code> object from a "slice":</p>
<pre><code>import torch
import torch.nn as nn
a = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
#b = nn.Parameter(a[1]) # "RuntimeError: One of the differentiated Tensors appears to not have been used in the graph."
#b = torch.Tensor(a[1]) # "IndexError: slice() cannot be applied to a 0-dim tensor."
b = a[1] # works
g = torch.autograd.grad(b, a)[0]
</code></pre>
<p>From the error message, it seems that PyTorch is not able to differentiate through an <code>nn.Parameter</code> initialization. Is there a way to fix this?</p>
|
<python><tensorflow><deep-learning><pytorch>
|
2024-03-20 02:12:02
| 1
| 811
|
Metamorphic
|
78,190,411
| 10,146,441
|
How to preserve newline characters in CSH when storing in a variable or echo
|
<p>I have a <code>python</code> script which is getting called from a <code>csh</code> script ( I can not use <code>bash</code>). The python script prints out string with the newline characters and I am storing the output in a csh variable. However, as soon I store it in a variable, I am losing all the newline characters. Below are the scripts:</p>
<p>python script (pcmd.py)</p>
<pre><code>def main(op):
if op == "h": # print help
# below newline character is getting lost
print ("Help first line\n second line.")
else: # print and later execute csh commands
print ("setenv SOME_ENV_VAR 123; setenv ANOTHER asd")
if __name__ == "__main__":
import sys
main(sys.argv[1])
</code></pre>
<p>csh script (pcmd.csh)</p>
<pre><code># store the py script in a variable
set pcmd="./pcmd.py $*"
# store the output of the first eval command
set output=`eval "$pcmd"`
# if output contains setenv, eval the output (csh commands)
if ( "$output" =~ *setenv* ) then
eval "${output}"
else # otherwise, print the output
echo "${output}" # Issue : losing newline chars, tried echo -e too but of no avail
</code></pre>
<p>execution</p>
<pre><code>pcmd.csh h
expects: Help first line
second line.
actual: Help first line second line. # missing newline character
</code></pre>
<p>Can someone point out the missing bit in the scripts?</p>
|
<python><echo><csh>
|
2024-03-20 01:28:23
| 1
| 684
|
DDStackoverflow
|
78,190,205
| 1,447,953
|
pandas: how to aggregate records into rolling time windows at a given frequency?
|
<p>Here is my data:</p>
<pre><code>times = pd.date_range(start=pd.Timestamp.now(), end=pd.Timestamp.now() + pd.Timedelta(minutes=1),
periods=61)
data = np.arange(61)
df = pd.DataFrame({'times': times, 'data': data})
</code></pre>
<p>output:</p>
<pre><code> times data
0 2024-03-20 10:38:44.100877000 0
1 2024-03-20 10:38:45.100877416 1
2 2024-03-20 10:38:46.100877833 2
3 2024-03-20 10:38:47.100878250 3
4 2024-03-20 10:38:48.100878666 4
.. ... ...
56 2024-03-20 10:39:40.100900333 56
57 2024-03-20 10:39:41.100900750 57
58 2024-03-20 10:39:42.100901166 58
59 2024-03-20 10:39:43.100901583 59
60 2024-03-20 10:39:44.100902000 60
</code></pre>
<p>If I want to group this with a rolling window of say 2 seconds I can do this:</p>
<pre><code>df_windows = df.rolling(on='times', window=pd.Timedelta(seconds=2))
for window in df_windows:
print(window)
</code></pre>
<p>Then I get this:</p>
<pre><code>times
2024-03-20 10:48:09.273265 0
data
times
2024-03-20 10:48:09.273265000 0
2024-03-20 10:48:10.273265333 1
data
times
2024-03-20 10:48:10.273265333 1
2024-03-20 10:48:11.273265666 2
data
times
2024-03-20 10:48:11.273265666 2
2024-03-20 10:48:12.273266000 3
data
</code></pre>
<p>Cool. But if I don't want a window computed relative to every single row then pandas seems to be lacking features to do that? E.g. a step parameter was added to <code>rolling</code> (<a href="https://github.com/pandas-dev/pandas/issues/15354" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/15354</a>) but it doesn't work for this case:</p>
<pre><code>df_windows = df.rolling(on='times', window=pd.Timedelta(seconds=2), step=2)
NotImplementedError: step is not supported with frequency windows
</code></pre>
<p>It also doesn't make much sense because <code>2</code> is not a meaningful step, it should be a
<code>pd.Timedelta</code> object, but the step argument has to be an integer.</p>
<p>So, it seems like the rolling function cannot achieve what I want. So, what workaround is there in pandas? I would like one that works with irregular data, i.e. does not rely on my
timestamps being at some regular frequency. I can do something with <code>groupby</code> to get time groups, but I don't see a way to get overlapping windows using groupby...</p>
|
<python><pandas><group-by><pandas-rolling>
|
2024-03-19 23:57:19
| 0
| 2,974
|
Ben Farmer
|
78,190,193
| 901,426
|
best method to improve awk speed in writing to sqlite3 db
|
<p>I have a device that runs BusyBox, has ONE processor available for client use, and needs to run as a flow pulse counter (among other things), catching zero or many pulses of 20ms in width at random intervals within each second.</p>
<p>The device has a second processor walled off from the client dedicated to creating a muxed datapool of its I/O port signals. The muxed signal is available via a manufacturer-provided Awk script, which i have modified to provide a TICKCOUNT that increments when the demuxed signal reports '1'. I can't share the manufacturer's code, obviously, but I can share mine.</p>
<p>Alongside of this runs a Python application that collects signal data from the mux stream and reports it via MQTT to an Ignition dashboard for client consumption / management / whatever. The MQTT reporting interval is 5sec. The pulse count check against the store value (text file/sqlite db) is every 2sec, enabling plenty of time to perform a flow rate calculation and report it back via MQTT to the consuming dashboard.</p>
<p>In order to be able to capture the pulse signal, I had to get the sampling rate below 15ms. Running the Awk script balls out in an eternal <code>while</code> loop did the trick; I'm able to consistently get ~7-11ms read intervals. And I <em>was</em> just outputting to a text file so Python could read from THAT and do what it wanted with it, using the MQTT timestamp to calculate flow rates.</p>
<p>Enter management. Flow rate calculations must now be done on the device, not on the dashboard server. WTH.</p>
<p>So now Read/Write times matter a hell of a lot more and I've switched the script to writing to an SQLite database to get a rolling timestamp on the writes that Python can then access and pass on via MQTT.</p>
<p>My issue is, the count appears to no longer be accurate because the read from the database in Python's subshell PLUS the subshell required to execute the sqlite3 query in Awk are interrupting the sampling speed. If this had another core to dump the sampling to, this would be a non-issue.</p>
<p>So. How can I best optimize this Awk code for as much speed as possible to claw back as many cycles as possible to retain coherence with actual pulse counts? And I'm fully willing to accept that this might no longer be doable.</p>
<p>The Awk code (from memory because I'm not currently sitting at the device):</p>
<pre><code>#!/bin/awk -f
# proprietary code that sets the mux config
BEGIN {
TICKCOUNT = 0
db = "path/to/pulseCount.db"
commandSQL = "sqlite3 -noheader " db " \"%s\";"
while(1) {
# more proprietary code that reads the mux and dumps value to DIN variable
if (DIN == '1') {
TICKCOUNT++
querySQL = "update pulseCount set pulses=" TICKCOUNT ";"
system(sprintf(commandSQL, querySQL))
}
}
}
END {
}
</code></pre>
<p>This works; dumping a crapton of return values into <code>stdout</code> from the <code>sqlite3</code> call, but I'm told this isn't a performance concern. (Plus, as I think about it, when running in production, <code>nohup</code> will dump it to <code>/dev/null</code> anyway). HOWEVER, I'm told the overhead of opening <code>system()</code> is killing speed faster than PolPot 'cleansing' West Timor in the 90's. That's bad.</p>
<p>I'm not sure where to optimize from here. I am historically an infosec / network guy coming out of WebDev. I'm not hardware experienced. So, go gently. I am open to any advice on how to beat this thing and, if it can't be done, I am open to that option as well; in which case I'll find some other way to get done what needs doing.</p>
|
<python><bash><awk>
|
2024-03-19 23:54:19
| 0
| 867
|
WhiteRau
|
78,190,160
| 6,329,217
|
Local vs NonLocal Scope Python
|
<p>I am trying to understand scopes in Python and am confused in the examples below (I am using Python 3.12.2) -</p>
<p>1.</p>
<pre><code>a = 10
def myfunc():
a = 2
print(a)
print(a)
myfunc()
</code></pre>
<p>This gives the output -</p>
<pre><code>10
2
</code></pre>
<ol start="2">
<li></li>
</ol>
<pre><code>a = 10
def myfunc():
print(a)
print(a)
myfunc()
</code></pre>
<p>This gives the output -</p>
<pre><code>10
10
</code></pre>
<ol start="3">
<li>However, when I do this -</li>
</ol>
<pre><code>a = 10
def myfunc():
print(a)
a = 2
print(a)
myfunc()
</code></pre>
<pre><code>UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
</code></pre>
<p>I am not sure how this is different from code example 1. Why is my output not-</p>
<pre><code>10
10
</code></pre>
|
<python><scope>
|
2024-03-19 23:41:53
| 0
| 362
|
Aditi Garg
|
78,190,082
| 12,309,386
|
Polars list of values based on intersection of different column list with another dataset
|
<p>I have a dataframe with <code>people</code> and the <code>food</code> they like:</p>
<pre class="lang-py prettyprint-override"><code>df_class = pl.DataFrame(
{
'people': ['alan', 'bob', 'charlie'],
'food': [['orange', 'apple'], ['banana', 'cherry'], ['banana', 'grape']]
}
)
print(df_class)
shape: (3, 2)
βββββββββββ¬βββββββββββββββββββββββ
β people β food β
β --- β --- β
β str β list[str] β
βββββββββββͺβββββββββββββββββββββββ‘
β alan β ["orange", "apple"] β
β bob β ["banana", "cherry"] β
β charlie β ["banana", "grape"] β
βββββββββββ΄βββββββββββββββββββββββ
</code></pre>
<p>And, I have a data structure with <code>animals</code> and the things they like to eat:</p>
<pre class="lang-py prettyprint-override"><code>animals = [
('squirrel', ('acorn', 'almond')),
('parrot', ('cracker', 'grape', 'guava')),
('dog', ('chicken', 'bone')),
('monkey', ('banana', 'plants'))
]
</code></pre>
<p>I want to add a new column <code>pets</code> in <code>df_class</code>, such that <code>pets</code> is a list of the animals that have at least one food in common with the corresponding person:</p>
<pre class="lang-py prettyprint-override"><code>df_class.with_columns(pets=???) # <-- not sure what to do here
shape: (3, 3)
βββββββββββ¬βββββββββββββββββββββββ¬βββββββββββββββββββββββ
β people β food β pets β
β --- β --- β --- β
β str β list[str] β list[str] β
βββββββββββͺβββββββββββββββββββββββͺβββββββββββββββββββββββ‘
β alan β ["orange", "apple"] β [] β
β bob β ["banana", "cherry"] β ["monkey"] β
β charlie β ["banana", "grape"] β ["monkey", "parrot"] β
βββββββββββ΄βββββββββββββββββββββββ΄βββββββββββββββββββββββ
</code></pre>
<ul>
<li>I have some flexibility in the data structure for <code>animals</code>, in case for e.g. this is easier to do with some sort of set intersection</li>
<li>the order of pets is unimportant</li>
<li>pets should contain unique values</li>
<li>I'm looking for a single expression that would achieve the desired result, so as to fit within a larger framework of a list of expressions that perform transformations on other columns of my actual dataset</li>
</ul>
<p>Side note: my title seems kind of clunky and I'm open to suggestions to reword so that it's easier to find by others that might be trying to solve a similar problem.</p>
|
<python><dataframe><python-polars>
|
2024-03-19 23:11:21
| 2
| 927
|
teejay
|
78,190,020
| 543,572
|
How to reset a group of comboboxes back to no selection tkinter?
|
<p>I'm using ttkbootstrap with tkinter and I have 15 ttkbootstrap comboboxes that I want to reset to no selection if a button is pressed. I tried this code I found somewhere, but it does nothing. I did verify I'm hitting the function with a print statement though:</p>
<pre><code>import tkinter
from tkinterr import *
import ttkbootstrap as ttk
def clear():
print("In the clear function!)
if isinstance(Widget, ttk.combobox):
Widget.delete(0,end)
</code></pre>
<p>I'm assuming Widget isn't defined properly and that is the issue? I tried using Combobox and ComboBoxWidget, then tried to <a href="https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/naming-widgets.html" rel="nofollow noreferrer">name a widget instance</a> ,but nothing seems to work.</p>
<p>I put all of the comboboxes in a class so I can pass self to other methods.</p>
<pre><code>The button code is:
self.clear_button = ttk.Button(button_frame),
command = lambda: clear(),
etc...
</code></pre>
<p>I know I can reset an individual combobox using:</p>
<pre><code> def clear_combo():
combobox.delete(0, "end")
</code></pre>
<p>I can loop through each combobox by unique name, but I was looking to find a better solution as that seemed clunky. Is there a way to generically select a specific type of ttk widget for this?</p>
|
<python><tkinter><combobox><ttkbootstrap>
|
2024-03-19 22:48:54
| 1
| 15,801
|
James-Jesse Drinkard
|
78,190,016
| 4,302,855
|
MessageBox with Timer buttons that looks like messagebox.showwarn()
|
<p>I used the top answer at <a href="https://stackoverflow.com/questions/61841410/messagebox-pause-python">MessageBox pause - Python</a> to make a dialog box that has a timed 'OK' button on it. However, the box is pretty sad looking and I'd like it to look like a standard messagebox.showwarn() message box even taking advantage of the 'detail' parameter.</p>
<p>My problem is that messageboxes don't look like they are meant to be refactored and customized or sub-classed. I also tried using ttkbootstrap to put the Icon.warn inside a label, but all it did was turn all my buttons a blue color and never displayed the icon. Plus, I'd prefer not to use another library just to display a warning icon as my script is already pretty bloated.</p>
<p>Is there a practical way to either:</p>
<ol>
<li><p>Subclass the messagebox.Message object to have an OK button that has a pause time before it can be pressed and also make it look like a warning messagebox; or</p>
</li>
<li><p>Keep my current solution using Saad's answer of subclassing a simpledialog but make it look more like a warning messagebox including the warning icon and detail lines.</p>
</li>
</ol>
|
<python><tkinter>
|
2024-03-19 22:47:14
| 1
| 845
|
boymeetscode
|
78,189,710
| 2,599,861
|
How to read a parquet file with arrays by ROW instead of array elements?
|
<p>I am using tensorflow-io to read a parquet file. This parquet file contains columns with lists or maps. Following is an example of my dataset in duck db, as you can see, there is a timestamp column and two array columns.</p>
<p><a href="https://i.sstatic.net/zfnl5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zfnl5.png" alt="enter image description here" /></a></p>
<p>I am using the following function to load the file. I uses tensorflow-io (version 0.36, compatible with tensorflow 2.15).</p>
<pre><code>import tensorflow as tf
import tensorflow_io as tfio
def load_single_parquet_file(source_file_path: str, relevant_features_list: Optional[List[str]]) -> tf.data.Dataset:
single_file_dataset = tfio.IODataset.from_parquet(source_file_path, columns=relevant_features_list)
return single_file_dataset
</code></pre>
<p>I need the rows as is, that means, a timestamp (may be in any other tensorflow-compatible format) and two 1-dimensional tensors of type string. But the function is retuning me a dataset where each row a cartesian product of the elements of the array, that means, it is reading at array element level instead of row level, what makes no sense to my problem and make the data unusable.</p>
<p>Here is a piece of the output:</p>
<pre><code>OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691007000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'91.25'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691080000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'85.62'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691293000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'80.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691670000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'70.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691881000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'60.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700856196000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'60.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700858022000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'85.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700859164000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'85.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700861186000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'80.00'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700862391000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'75.00'>)])
</code></pre>
<p>As you can see, it's repeating the <code>previous_scores.list.element</code> for the same values of <code>timestamp</code> and <code>device_type.list.element</code>, instead of just returning the lists.</p>
<p>How can I read a parquet file with nested structures by-row, not by row element?</p>
<p>I am using tensorflow-io to read a parquet file. This parquet file contains columns with lists or maps. Following is an example of my dataset in duck db, as you can see, there is a timestamp column and two array columns.</p>
<p><a href="https://i.sstatic.net/zfnl5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zfnl5.png" alt="enter image description here" /></a></p>
<p>I am using the following function to load the file. I uses tensorflow-io (version 0.36, compatible with tensorflow 2.15).</p>
<pre><code>import tensorflow as tf
import tensorflow_io as tfio
def load_single_parquet_file(source_file_path: str, relevant_features_list: Optional[List[str]]) -> tf.data.Dataset:
single_file_dataset = tfio.IODataset.from_parquet(source_file_path, columns=relevant_features_list)
return single_file_dataset
</code></pre>
<p>I need the rows as is, that means, a timestamp (may be in any other tensorflow-compatible format) and two 1-dimensional tensors of type string. But the function is retuning me a dataset where each row a cartesian product of the elements of the array, that means, it is reading at array element level instead of row level, what makes no sense to my problem and make the data unusable.</p>
<p>Here is a piece of the output:</p>
<pre><code>OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691007000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'91.25'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691080000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'85.62'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691293000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'80.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691670000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'70.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700691881000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'60.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700856196000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'60.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700858022000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'85.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700859164000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'85.12'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700861186000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'80.00'>)])
OrderedDict([(b'timestamp', <tf.Tensor: shape=(), dtype=int64, numpy=1700862391000000>), (b'device_type.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'desktop'>), (b'previous_scores.list.element', <tf.Tensor: shape=(), dtype=string, numpy=b'75.00'>)])
</code></pre>
<p>As you can see, it's repeating the <code>previous_scores.list.element</code> for the same values of <code>timestamp</code> and <code>device_type.list.element</code>, instead of just returning the lists.</p>
<p>How can I read a parquet file with nested structures by-row, not by row element?</p>
|
<python><tensorflow><machine-learning><tensorflow-io>
|
2024-03-19 21:21:26
| 0
| 588
|
AndrΓ© Claudino
|
78,189,699
| 9,415,280
|
how to get continuous date index base on the first index values on Pandas
|
<p>I got an df with this index, at some point the date change from 2024-03-03 to 2023-02-25.
I want to replace the wrong part (2023...) by the logical extend of the correct one</p>
<p>sample:</p>
<pre><code>2024-02-23 -5.60000
2024-02-24 -13.00000
2024-02-25 -27.20000
2024-02-26 -4.20000
2024-02-27 -11.20000
2024-02-28 -14.73625
2024-02-29 -19.37000
2024-03-01 -16.89000
2024-03-02 -5.97000
2024-03-03 -1.30000
2023-02-25 -35.40000
2023-02-26 -28.70000
2023-02-27 -26.40000
2023-02-28 -15.40000
2023-03-01 -14.10000
2023-03-02 -11.20000
2023-03-03 -21.00000
2023-03-04 -17.00000
2023-03-05 -17.60000
2023-03-06 -6.70000
</code></pre>
<p>How to make it clean and pythonic?</p>
|
<python><pandas><datetime>
|
2024-03-19 21:19:17
| 1
| 451
|
Jonathan Roy
|
78,189,344
| 5,619,073
|
Short of modifying Python's source C, is there any way to add a new format character to the struct module's format specification mini-language?
|
<p>I'm reading data from machines using the Modbus protocol. If you're not familiar with Modbus, I envy you. More seriously though, Modbus is a low-level protocol that allows you to read "registers" from a machine by specifying a start address and a number of registers to read. A "register" is just a two-byte word. Machines implementing Modbus generally only natively understand how to encode whole-number types (int, short, etc), and floats in their registers. So, if you need to represent another datatype, you have to find a way to represent it as a series of integers and floats on the Modbus-implementing machine's end, and devise some way to reconstruct those individual integer+float values into the actual datatype you need on your end.</p>
<p>This wouldn't be an issue, but the machines I'm communicating with use an unholy combination of little-endian and big-endian. Specifically, ints, shorts, etc are all encoded in big-endian, but floats are encoded in a format that is neither big-endian nor little-endian. For example, if we have a floating-point value <em>x</em> that would be represented as <code>01 02 03 04</code> in big-endian, and <code>04 03 02 01</code> in little-endian, these machines would represent <em>x</em> as <code>03 04 01 02</code>. I don't know any name for this format, so I've just been calling it "regswapped big-endian", as it <em>would</em> be big-endian if you just swapped the contents of the first and second registers.</p>
<p>Until now, I've been decoding regswapped floats by just swapping the positions of bytes 1+2 with bytes 3+4 whenever I read a float, before passing it to <code>struct.unpack(">f")</code>. That has worked just fine because the actual data I'm reading has just been integers and floats.</p>
<p>However, the requirements of the data-collection software I wrote were recently expanded. It is no longer sufficient to assume that a float is just a float, and an integer is just an integer, as I now need to support more complex types that are composed of multiple integers and/or floats. For example, a series of six unsigned shorts and a float which together represent a timestamp with offset. If the floats were in big-endian format like every other value the machines record, I would just pass the data to <code>struct.unpack(">HHHHHHf")</code>, and then pass the output from that to <code>datetime.datetime()</code>, but they <strong>aren't</strong> encoded in big-endian format - I still need to swap bytes 1+2 with bytes 3+4 of any float I read before I can actually decode it. But since I'm reading data that is composed of multiple individual values now, I can't just blindly swap bytes 1+2 with bytes 3+4 - I need to know exactly where any floats are located within the bytes I've read.</p>
<p>The most straightforward way I can think of to handle this would be to just add my own custom format code to the <code>struct</code> module's format specification mini-language to represent a "regswapped float", maybe using the character <code>"r"</code>. That way, I could just do <code>struct.unpack(">HHHHHHr")</code> or <code>struct.unpack(">rr")</code>, or whatever else I need, and be done with it. However, it seems that the <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow noreferrer"><code>struct</code> module's format specification mini-language</a> comes directly from <a href="https://github.com/python/cpython/blob/v3.12.2/Modules/_struct.c#L808" rel="nofollow noreferrer">Python's underlying C implementation.</a></p>
<p>So instead, I thought I could create a subclass of <code>struct.Struct</code> that checks for <code>"r"</code> in the format string that it's passed, perform any byte-swapping on <code>"r"</code>-type floats as necessary, construct a new format string replacing all <code>"r"</code>s with <code>"f"</code>s, and <code>unpack()</code> the data using that new format string. But to be able to do that correctly with any arbitrary format string, I would effectively need to re-implement all the parsing rules for the struct format-specification mini-language, which would be a terrible idea.</p>
<p>So, is there any way for me to add a custom format code, or achieve something like it in Python, without modifying the underlying C?</p>
|
<python><struct><modbus>
|
2024-03-19 19:58:47
| 1
| 437
|
Nick Muise
|
78,189,208
| 14,619,971
|
How to get the result of an excel formula in Python?
|
<p>I need to execute the following excel formula in Python:</p>
<pre><code>STDEV.S(A1:A3)
</code></pre>
<p>Tried this code:</p>
<pre><code>from openpyxl import Workbook
from openpyxl.formula import Tokenizer
wb = Workbook()
ws = wb.active
ws['A1'] = 10
ws['A2'] = 20
ws['A3'] = 30
ws['B1'] = "=STDEV.S(A1:A3)"
# Calculate the formula
result = ws['B1'].calculate()
print("STDEV.S Result:", result)
</code></pre>
<p>got the error:</p>
<pre><code>'Cell' object has no attribute 'calculate'
</code></pre>
<p>in this line:</p>
<pre><code>result = ws['B1'].calculate()
</code></pre>
<p>How can I get the result of STDEV.S(A1:A3) then?</p>
|
<python><excel>
|
2024-03-19 19:32:31
| 2
| 829
|
jkfe
|
78,188,979
| 820,013
|
Define a protocol that mimics QFileSystemModel.index() and its overloads
|
<p>I'm trying to implement a protocol that mimics QFileSystemModel so that I can use that protocol to define a new custom class. The protocol definition is generating a mypy error when trying to make sure that protocol is satisfied by current QFileSystemModel derived class. Here is what I've tried...</p>
<pre><code>import typing
from PyQt6 import QtCore, QtGui
class FileSystemModelProtocol(typing.Protocol):
"""Define the subset of QFileSystemModel methods used...for defining a class with the same behavior"""
@typing.overload
def index(self, row: int, column: int, parent: QtCore.QModelIndex = ...) -> QtCore.QModelIndex: ...
@typing.overload
# def index(self, path: typing.Optional[str], column: int = ...) -> QtCore.QModelIndex: ... path vs row causes an error
def index(self, row: typing.Optional[str], column: int = ...) -> QtCore.QModelIndex: ...
def index(self, row: typing.Optional[int | str] = ..., column: int = ..., parent: QtCore.QModelIndex = ...) -> QtCore.QModelIndex: ...
class CustomFileSystemModel(QtGui.QFileSystemModel, FileSystemModelProtocol): # error: Definition of "index" in base class "QAbstractItemModel" is incompatible with definition in base class "FileSystemModelProtocol"
pass
class TableModel(QtCore.QAbstractTableModel, FileSystemModelProtocol):
def index_from_str(self, path: str) -> QtCore.QModelIndex:
return QtCore.QModelIndex() # TODO: lookup with path
def index(self, row_path: typing.Optional[int | str] = None, column: int = 0, parent: QtCore.QModelIndex = QtCore.QModelIndex()) -> QtCore.QModelIndex:
if isinstance(row_path, str):
return self.index_from_str(row_path)
if isinstance(row_path, int):
return super().index(row_path, column, parent)
return QtCore.QModelIndex()
c = CustomFileSystemModel()
t = TableModel()
</code></pre>
<p>*** Edited down to a more minimal example. The previous edit showed some previous attempts as well as the relevant prototypes from the qt sources. This should be just the relevant code. Mypy execution and results follow</p>
<p>*** Edit 2
Renaming path in the second overload to row made this error go away ...# error: Overloaded function implementation does not accept all possible arguments of signature 2</p>
<pre><code>mypy file_system_protocol_test_so1.py
file_system_protocol_test_so1.py:26: error: Definition of "index" in base class "QAbstractItemModel" is incompatible with definition in base class "FileSystemModelProtocol" [misc]
Found 1 error in 1 file (checked 1 source file)
</code></pre>
|
<python><mypy><pyqt6>
|
2024-03-19 18:46:21
| 0
| 4,674
|
shao.lo
|
78,188,957
| 613,913
|
Decode binary file in AWS environment using PySpark
|
<p>Is it possible to consume a Netezza backup file in AWS environment and load it to Redshift.
File is a compressed binary file created using the below query. This file can also be produced using NZ_BACKUP utility in Netezza for a full database.</p>
<pre><code>CREATE EXTERNAL TABLE 'C:\filename.bak' USING (remotesource 'ODBC' FORMAT 'internal'
COMPRESS true) AS SELECT * FROM schema.tablename;
or
nzbackup -dir /home/user/backups -u user -pw password -db db1
</code></pre>
<p>I want this file to be decoded and load to a data frame in AWS environment utilizing Python or PySpark (glue). Following are the steps I am planning to do in AWS. I need some guidance in the first step. How to decode a compressed binary from Netezza.</p>
<ol>
<li>Decode the file to ASCII (How?)</li>
<li>Load to DF and generate parquet</li>
<li>Copy to Redshift</li>
</ol>
|
<python><pyspark><aws-glue><binaryfiles><netezza>
|
2024-03-19 18:41:47
| 1
| 373
|
need_the_buzz
|
78,188,898
| 114,265
|
Is it possible to create a Python application that subscribes to parts of a firebase project
|
<p>I have a scenario where there is a firebase project, and I would like to monitor certain events that they make public.</p>
<p>An event happens, and I would like to subscribe to that, and send out a notification. From what I can see with python there is the firebase_admin library, and I can call initialize. The issue is that I don't have a login. In talking with the developer of the project their belief is that since they are publishing that data publicly, I should not need to authenticate.</p>
<p>But when I read this documentation, it want me to have a json credential file, or authenticate with gcloud</p>
<p><a href="https://firebase.google.com/docs/firestore/quickstart#python_1" rel="nofollow noreferrer">https://firebase.google.com/docs/firestore/quickstart#python_1</a></p>
<pre><code>import firebase_admin
from firebase_admin import firestore
# Application Default credentials are automatically created.
app = firebase_admin.initialize_app()
db = firestore.client()
</code></pre>
<p>Is there any way to get around this and subscribe without providing credentials?</p>
<p>I just want to get to where I can make these types of calls assuming the results are public and not behind authentication.
<a href="https://firebase.google.com/docs/firestore/query-data/listen" rel="nofollow noreferrer">https://firebase.google.com/docs/firestore/query-data/listen</a></p>
|
<python><firebase>
|
2024-03-19 18:27:15
| 1
| 3,290
|
Brian S
|
78,188,760
| 3,305,998
|
How to separate rust library and exported python extensions which wrap it
|
<p>I have a rust library which provides useful functionality for use in other rust programs. Additionally I would like to provide this functionality as a python extension (using <a href="https://github.com/PyO3/pyo3" rel="nofollow noreferrer">pyo3</a> and <a href="https://setuptools-rust.readthedocs.io/" rel="nofollow noreferrer">setuptools-rust</a>, although expect most practices to be tool agnostic)</p>
<ol>
<li>What best practices are there for separating and packaging this? The documentation examples all show a single library. This means that anyone building the rust library and using it in the rust ecosystem needs the python headers and gets the exported python module as well, which isn't great.</li>
<li>Is there any guidance on testing the exported python extensions within rust rather than only from python? (so I don't need to manually <code>pip install -e .</code> in order to build the extension before running the tests)</li>
</ol>
<p>I'm guessing the "right" approach to (1) uses workspaces?</p>
<p>My current setup is:</p>
<pre><code>FizzBuzz
- src
- lib.rs
- tests
- test_fizzbuzz.rs
- test_fizzbuzz.py
- Cargo.toml
- pyproject.toml
</code></pre>
<p>Cargo.toml:</p>
<pre class="lang-ini prettyprint-override"><code>[package]
name = "fizzbuzz"
...
[lib]
name = "fizzbuzzo3"
path = "src/lib.rs"
crate-type = ["cdylib", "rlib"]
[dependencies]
pyo3 = "0.20.3"
</code></pre>
<p>pyproject.toml</p>
<pre class="lang-ini prettyprint-override"><code>[build-system]
requires = ["setuptools", "setuptools-rust"]
build-backend = "setuptools.build_meta"
[project]
name = "fizzbuzz"
...
[[tool.setuptools-rust.ext-modules]]
target = "fizzbuzzo3"
...
</code></pre>
<p>I'd like to split this into two rust libraries:</p>
<ul>
<li>one tested by test_fizzbuzz.rs only containing the rust implementation of the functionality</li>
<li>and a separate one test by both test_fizzbuzzo3.rs and test_fizzbuzz.py covering the python binding</li>
</ul>
<p>I should be able to edit the code in the rust library and see the change when running all three test suites, then later publish the rust crate and python package to crates.io and pypi.org</p>
|
<python><rust><pyo3>
|
2024-03-19 18:01:57
| 0
| 318
|
MusicalNinja
|
78,188,758
| 1,439,748
|
Subtracting polygons and converting them to not have holes in python
|
<p>I have several blue and red polygons. I would like the red ones subtracted from the blue ones.</p>
<p>After this is done, some remaining polygons may have holes. I'd like those polygons with holes converted to polygons without holes.</p>
<h1>What I've tried so far</h1>
<pre class="lang-py prettyprint-override"><code>from typing import TypedDict
from shapely.geometry import MultiPolygon, Polygon
class Coords(TypedDict):
x: list[float]
y: list[float]
def subtract_polygons(group_a: list[Coords], group_b: list[Coords]):
# Convert polygons to Shapely Polygon objects
polygons_a = [Polygon(zip(group["x"], group["y"])) for group in group_a]
polygons_b = [Polygon(zip(group["x"], group["y"])) for group in group_b]
# Create a "negative" polygon for the hole in group B
negative_polygons_b = [polygon.exterior for polygon in polygons_b]
# Subtract each polygon in polygons_b from each polygon in polygons_a
result_polygons = []
for polygon_a in polygons_a:
for negative_polygon_b in negative_polygons_b:
result_polygon = polygon_a.difference(negative_polygon_b)
result_polygons.append(result_polygon)
# Convert the resulting geometry to MultiPolygon
result_multipolygon = MultiPolygon(result_polygons)
print("polygons_a", polygons_a)
print("polygons_b", polygons_b)
print("negative_polygons_b", negative_polygons_b)
print("result_multipolygon", result_multipolygon)
group_a: list[Coords] = [
{"x": [100, 200, 200, 100, 100], "y": [100, 100, 200, 200, 100]},
{"x": [130, 230, 230, 130, 130], "y": [130, 130, 230, 230, 130]},
{"x": [180, 280, 280, 180, 180], "y": [180, 180, 280, 280, 180]},
]
group_b: list[Coords] = [
{"x": [150, 175, 175, 150, 150], "y": [150, 150, 175, 175, 150]},
{"x": [150, 250, 250, 150, 150], "y": [220, 220, 320, 320, 220]},
]
subtract_polygons(group_a, group_b)
</code></pre>
<h1>Desired result:</h1>
<p>Note that the little line is arbitrary. I just wanted to show that it's a single polygon, concave in this case, without a hole</p>
<p><a href="https://i.sstatic.net/HXprJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HXprJ.png" alt="enter image description here" /></a></p>
<h1>Input and Actual Result:</h1>
<p><a href="https://i.sstatic.net/DzlOL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DzlOL.png" alt="enter image description here" /></a></p>
<h1>The console output:</h1>
<pre><code>polygons_a [
<POLYGON ((100 100, 200 100, 200 200, 100 200, 100 100))>,
<POLYGON ((130 130, 230 130, 230 230, 130 230, 130 130))>,
<POLYGON ((180 180, 280 180, 280 280, 180 280, 180 180))>
]
polygons_b [
<POLYGON ((150 150, 175 150, 175 175, 150 175, 150 150))>,
<POLYGON ((150 220, 250 220, 250 320, 150 320, 150 220))>
]
negative_polygons_b [
<LINEARRING (150 150, 175 150, 175 175, 150 175, 150 150)>,
<LINEARRING (150 220, 250 220, 250 320, 150 320, 150 220)>
]
result_multipolygon MULTIPOLYGON (
((100 200, 200 200, 200 100, 100 100, 100 200)),
((100 200, 200 200, 200 100, 100 100, 100 200)),
((130 230, 230 230, 230 130, 130 130, 130 230)),
((230 130, 130 130, 130 230, 150 230, 230 230, 230 220, 230 130)),
((180 280, 280 280, 280 180, 180 180, 180 280)),
((280 280, 280 180, 180 180, 180 220, 180 280, 250 280, 280 280))
)
</code></pre>
|
<python><polygon><shapely>
|
2024-03-19 18:01:40
| 1
| 3,804
|
LCIII
|
78,188,638
| 6,195,489
|
Fast way to convert 2d string numpy array to a 3d int array
|
<p>I have a very large numpy array with entries like:</p>
<pre><code>[['0/1' '2/0']
['3/0' '1/4']]
</code></pre>
<p>I want to convert it/ get an array with the 3d array like</p>
<pre><code>[[[0 1] [2 0]]
[[3 0] [1 4]]]
</code></pre>
<p>The array is very wide, so a lot of columns, but not many rows. And there are around 100 or so possibilities for the string. This isnt actually a fraction, just a demonstration of what is in the file (its genomics data, given to me in this format).</p>
<p>I don't want to run in parallel, as I will be running this on a single CPU before moving to a single GPU, so the extra CPUs would be idle while the GPU kernel is running.
I have tried numba:</p>
<pre><code>import numpy as np
import itertools
from numba import njit
import time
@njit(nopython=True)
def index_with_numba(data,int_data,indices):
for pos in indices:
str_match = str(pos[0])+'/'+str(pos[1])
for i in range(data.shape[0]):
for j in range(data.shape[1]):
if data[i, j] == str_match:
int_data[i,j] = pos
return int_data
def generate_masks():
masks=[]
def _2d_array(i,j):
return np.asarray([i,j],dtype=np.int32)
for i in range(10):
for j in range(10):
masks.append(_2d_array(i,j))
return masks
rows = 100000
cols = 200
numerators = np.random.randint(0, 10, size=(rows,cols))
denominators = np.random.randint(0, 10, size=(rows,cols))
samples = np.array([f"{numerator}/{denominator}" for numerator, denominator in zip(numerators.flatten(), denominators.flatten())],dtype=str).reshape(rows, cols)
samples_int = np.empty((samples.shape[0],samples.shape[1],2),dtype=np.int32)
# Generate all possible masks
masks = generate_masks()
t0=time.time()
samples_int = index_with_numba(samples,samples_int, masks)
t1=time.time()
print(f"Time to index {t1-t0}")
</code></pre>
<p>But it is too slow to be feasible.</p>
<pre><code>Time to index 182.0304057598114
</code></pre>
<p>The reason I want this is I want to write a cuda kernel to perform an operation based on the original values - so for '0/1' i need 0 and 1 etc, but I cannot handle the strings. I had thought perhaps masks could be used, but they dont seem to be suitable.</p>
<p>Any suggestions appreciated.</p>
|
<python><numpy><numba>
|
2024-03-19 17:38:20
| 4
| 849
|
abinitio
|
78,188,519
| 991,703
|
how do I recover an old python environment?
|
<p>I am in a bit of a problem, as a server was upgraded, and some old python environments are no longer working. I cannot just activate the environment, but I would like to create a new environment which is a replica of the old environment to the extent possible.</p>
<p>This means installing on the new environment the same version of packages from the old environment.</p>
<p>Is there a way to extract this information from the old environment, for example, into a requirements.txt file? There doesn't seem to be anywhere a requirements.txt file in the old environment I can use.</p>
<p>EDIT: Thank you for the discussion. Yes, it was my mistake for not doing pip freeze before the upgrade, but I wasn't aware things are that flimsy.</p>
<p>Some of the code is old (and I know I will get comments about python 2.7 being used in some of the cases), but for example, when I run pip freeze from one of the activated packages I get:</p>
<pre><code># pip freeze
/.../venv/bin/python: error while loading shared libraries: libpython2.7.so.1.0: cannot open shared object file: No such file or directory
</code></pre>
<p>I know python 2.7 is installed on the machine, but I looked through all files in the whole server for this object file, and couldn't find it.</p>
|
<python><virtualenv><python-venv>
|
2024-03-19 17:15:23
| 1
| 4,761
|
kloop
|
78,188,399
| 5,266,998
|
is there parallelism inside Ollama?
|
<p>Below Python program is intended to translate large English texts into French. I use a for loop to feed a series of reports into Ollama.</p>
<pre><code>from functools import cached_property
from ollama import Client
class TestOllama:
@cached_property
def ollama_client(self) -> Client:
return Client(host=f"http://127.0.0.1:11434")
def translate(self, text_to_translate: str):
ollama_response = self.ollama_client.generate(
model="mistral",
prompt=f"translate this French text into English: {text_to_translate}"
)
return ollama_response['response'].lstrip(), ollama_response['total_duration']
def run(self):
reports = ["reports_text_1", "reports_text_2"....] # avearge text size per report is between 750-1000 tokens.
for each_report in reports:
try:
translated_report, total_duration = self.translate(
text_to_translate=each_report
)
print(f"Translated text:{translated_report}, Time taken:{total_duration}")
except Exception as e:
pass
if __name__ == '__main__':
job = TestOllama()
job.run()
</code></pre>
<p>docker command to run ollama:</p>
<pre><code>docker run -d --gpus=all --network=host --security-opt seccomp=unconfined -v report_translation_ollama:/root/.ollama --name ollama ollama/ollama
</code></pre>
<p>My question is: When I run this script on V100 and H100, I don't see a significant difference in execution time. I've avoided parallelism, thinking that Ollama might internally use parallelism to process. However, when I check with the htop command, I see only one core being used. Am I correct in my understanding?</p>
<p>I am a beginner in NLP, so any help or guidance on how to organize my code (e.g., using multithreading to send Ollama requests) would be appreciated.</p>
|
<python><docker><mistral-7b><ollama>
|
2024-03-19 16:55:42
| 2
| 2,607
|
Januka samaranyake
|
78,188,264
| 6,197,439
|
Adding breakpoint in pdb results with "End of file"?
|
<p>I'm so tired of this ...</p>
<p>Well, <a href="https://stackoverflow.com/questions/46317180/pdb-set-a-breakpoint-on-file-which-isnt-in-sys-path">pdb: set a breakpoint on file which isn't in sys.path</a> says:</p>
<blockquote>
<p>According to <a href="https://stackoverflow.com/questions/23071175/how-to-set-breakpoints-in-a-library-module-pdb">this answer</a> you can also set a break point by writing the full path to filename</p>
</blockquote>
<p>And I've even tried it once before, and it worked.</p>
<p>And now I'm trying to debug another script:</p>
<pre class="lang-none prettyprint-override"><code>$ python3 -m pdb freeze.py
> c:/tmp/mytest/freeze.py(9)<module>()
-> import py2exe
(Pdb) n
> c:/tmp/mytest/freeze.py(10)<module>()
-> from py2exe import freeze
(Pdb) b /mingw64/lib/python3.11/site-packages/py2exe/runtime.py:166
End of file
(Pdb) b
(Pdb)
</code></pre>
<p>And just to show that file, and line 166, exists:</p>
<pre class="lang-none prettyprint-override"><code>$ awk 'NR >= 165 && NR <= 167 {printf "%d\t%s\n", NR, $0}' /mingw64/lib/python3.11/site-packages/py2exe/runtime.py
165 def analyze(self):
166 logger.info("Analyzing the code")
167
</code></pre>
<p>What is the problem? Why cannot I set a breakpoint and I get "End of file" instead? How do I set the breakpoint properly so it works?</p>
|
<python><breakpoints><pdb>
|
2024-03-19 16:31:31
| 1
| 5,938
|
sdbbs
|
78,188,105
| 827,927
|
Python type hints: what should I use for a variable that can be any iterable?
|
<p>Consider the function:</p>
<pre><code>def mysum(x)->int:
s = 0
for i in x:
s += i
return s
</code></pre>
<p>The argument <code>x</code> can be <code>list[int]</code> or <code>set[int]</code>, it can also be <code>d.keys()</code> where d is a dict, it can be <code>range(10)</code>, as well as any other iterable, where the item is of type int. What is the correct type-hint for <code>x</code>?</p>
<p>My python is 3.10+.</p>
|
<python><python-typing>
|
2024-03-19 16:07:51
| 1
| 37,410
|
Erel Segal-Halevi
|
78,188,083
| 20,920,790
|
Why doesn't sns.barplot legend show all values?
|
<p>I have the following graph. Why does the last graph legend not contain all labels? It should contain these values:</p>
<pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 20, 21]
</code></pre>
<p><a href="https://i.sstatic.net/x8rSt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/x8rSt.png" alt="enter image description here" /></a></p>
<p>Code:</p>
<pre><code># select only this year
year = 2022
quarter = [1, 2, 3, 4]
# check dataframe (there's no 4 quarter in 2022 year)
def is_df_empty(df):
return len(df) != 0
# filter by 2022 year
df_year = df4_1_grouped[(df4_1_grouped['date'].dt.year == year)]
# count number of quarters in year
number_of_plots = len(df_year['date'].dt.quarter.unique())
# subplots
figure, axs = plt.subplots(number_of_plots, 1, figsize=(10, 6*number_of_plots))
axes = axs.ravel()
# loop for iter quarters
for q, ax in zip(quarter, axes):
# filter by quarter
df_filtered = df_year[
df_year['date'].dt.quarter.isin(list([q]))
]
# check df.empty
if is_df_empty(df_filtered):
# plot
ax = sns.barplot(
data=df_filtered,
x='month_dt',
y='mentor_cnt',
hue='sessions',
ax=ax,
palette="BrBG",
linewidth=0
)
# add values
for container in ax.containers:
ax.bar_label(container, size=11)
ax.grid(False)
ax.tick_params(axis='both', labelsize=12)
ax.set_xlabel('')
ax.set_ylabel('Mentors', fontsize=14)
ax.set_ylim(0, max(df_filtered['mentor_cnt'])*1.2)
# add legend
ax.legend(loc='upper right', fontsize=11)
ax.set_title(f'Session finished per month for mentors {year} year - {q} quarter', fontsize=15)
else:
continue
plt.tight_layout()
plt.show()
</code></pre>
<p>Table:</p>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th style="text-align: right;"></th>
<th style="text-align: left;">month_dt</th>
<th style="text-align: right;">sessions</th>
<th style="text-align: right;">mentor_cnt</th>
<th style="text-align: left;">date</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">37</td>
<td style="text-align: left;">2022-01-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">133</td>
<td style="text-align: left;">2022-01-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">38</td>
<td style="text-align: left;">2022-01-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">53</td>
<td style="text-align: left;">2022-01-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">39</td>
<td style="text-align: left;">2022-01-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">18</td>
<td style="text-align: left;">2022-01-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">40</td>
<td style="text-align: left;">2022-02-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">142</td>
<td style="text-align: left;">2022-02-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">41</td>
<td style="text-align: left;">2022-02-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">52</td>
<td style="text-align: left;">2022-02-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">42</td>
<td style="text-align: left;">2022-02-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">18</td>
<td style="text-align: left;">2022-02-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">43</td>
<td style="text-align: left;">2022-02-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-02-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">44</td>
<td style="text-align: left;">2022-02-01</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-02-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">45</td>
<td style="text-align: left;">2022-03-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">164</td>
<td style="text-align: left;">2022-03-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">46</td>
<td style="text-align: left;">2022-03-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">73</td>
<td style="text-align: left;">2022-03-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">47</td>
<td style="text-align: left;">2022-03-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">36</td>
<td style="text-align: left;">2022-03-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">48</td>
<td style="text-align: left;">2022-03-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">7</td>
<td style="text-align: left;">2022-03-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">49</td>
<td style="text-align: left;">2022-04-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">175</td>
<td style="text-align: left;">2022-04-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">50</td>
<td style="text-align: left;">2022-04-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">102</td>
<td style="text-align: left;">2022-04-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">51</td>
<td style="text-align: left;">2022-04-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">39</td>
<td style="text-align: left;">2022-04-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">52</td>
<td style="text-align: left;">2022-04-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">16</td>
<td style="text-align: left;">2022-04-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">53</td>
<td style="text-align: left;">2022-04-01</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">4</td>
<td style="text-align: left;">2022-04-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">54</td>
<td style="text-align: left;">2022-04-01</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">2</td>
<td style="text-align: left;">2022-04-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">55</td>
<td style="text-align: left;">2022-05-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">168</td>
<td style="text-align: left;">2022-05-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">56</td>
<td style="text-align: left;">2022-05-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">118</td>
<td style="text-align: left;">2022-05-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">57</td>
<td style="text-align: left;">2022-05-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">45</td>
<td style="text-align: left;">2022-05-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">58</td>
<td style="text-align: left;">2022-05-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">21</td>
<td style="text-align: left;">2022-05-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">59</td>
<td style="text-align: left;">2022-05-01</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">13</td>
<td style="text-align: left;">2022-05-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">60</td>
<td style="text-align: left;">2022-05-01</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">2</td>
<td style="text-align: left;">2022-05-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">61</td>
<td style="text-align: left;">2022-06-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">179</td>
<td style="text-align: left;">2022-06-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">62</td>
<td style="text-align: left;">2022-06-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">111</td>
<td style="text-align: left;">2022-06-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">63</td>
<td style="text-align: left;">2022-06-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">52</td>
<td style="text-align: left;">2022-06-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">64</td>
<td style="text-align: left;">2022-06-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">24</td>
<td style="text-align: left;">2022-06-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">65</td>
<td style="text-align: left;">2022-06-01</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">6</td>
<td style="text-align: left;">2022-06-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">66</td>
<td style="text-align: left;">2022-06-01</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">9</td>
<td style="text-align: left;">2022-06-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">67</td>
<td style="text-align: left;">2022-06-01</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">3</td>
<td style="text-align: left;">2022-06-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">68</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">167</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">69</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">129</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">70</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">85</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">71</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">38</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">72</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">16</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">73</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">11</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">74</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">8</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">75</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">8</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">76</td>
<td style="text-align: left;">2022-07-01</td>
<td style="text-align: right;">9</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-07-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">77</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">155</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">78</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">123</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">79</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">91</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">80</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">50</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">81</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">34</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">82</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">26</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">83</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">16</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">84</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">8</td>
<td style="text-align: right;">8</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">85</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">9</td>
<td style="text-align: right;">5</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">86</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">10</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">87</td>
<td style="text-align: left;">2022-08-01</td>
<td style="text-align: right;">12</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-08-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">88</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">1</td>
<td style="text-align: right;">183</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">89</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">105</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">90</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">65</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">91</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">32</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">92</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">13</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">93</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">12</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">94</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">7</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">95</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">8</td>
<td style="text-align: right;">6</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">96</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">9</td>
<td style="text-align: right;">2</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">97</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">10</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">98</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">11</td>
<td style="text-align: right;">2</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">99</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">13</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">100</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">20</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
<tr>
<td style="text-align: right;">101</td>
<td style="text-align: left;">2022-09-01</td>
<td style="text-align: right;">21</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">2022-09-01 00:00:00</td>
</tr>
</tbody>
</table></div>
|
<python><matplotlib><seaborn><legend>
|
2024-03-19 16:04:49
| 1
| 402
|
John Doe
|
78,188,054
| 7,949,129
|
Selenium with Python does not print console.log messages
|
<p>My problem is, I can not see any of <em><strong>console.log, console.error, console.warning</strong></em> messages in my logs when I run this Python script:</p>
<pre><code>import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
class ChromeDriver():
def __init__(login_url, user, passwd):
self.login_url = login_url
self.user = user
self.passwd = passwd
def __enter__(self):
options = Options()
options.set_capability('goog:loggingPrefs', {'browser': 'ALL'})
self.driver = webdriver.Chrome(options=options)
self.driver.maximize_window()
self._login()
return self.driver
def _login():
pass # implement login
def __exit__(self, exc_type, exc_val, exc_tb):
self.driver.quit()
def check_console_logs(driver, url):
try:
driver.get(url)
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'title'))
)
if '404' in driver.title:
print(f'failed to open {url}: 404 Not found')
return
logs = driver.get_log('browser')
if logs:
print(f"Console logs found in {url}:")
for log_entry in logs:
print(log_entry['level'], log_entry['message'])
print()
time.sleep(5)
except Exception as ex:
print(f"Error occurred while accessing {url}: {ex}")
test_urls = [''] # add urls to test
with ChromeDriver(username, password) as driver:
for url in test_urls:
check_console_logs(driver, url)
</code></pre>
<p>However, if I pause it in the debugger and open the devtools in the browser which was spawned by Python, I am able to see all the logs. I tried quite a lot but I still can not log any of the Javascript messages in Python.</p>
<p>I see only some other logs, which I am not interested in, because what I want to do is to call the different urls of my project in order to see if some unexpected warnings or errors are printed from my program flow.</p>
<p>The driver.capabilities shows browserVersion 122.06261.129 and chromedriverVersion is 122.0.6261.128 and I use selenium 4.18.1 and Python 3.10.</p>
|
<python><google-chrome><selenium-webdriver><logging><selenium-chromedriver>
|
2024-03-19 16:01:10
| 1
| 359
|
A. L
|
78,188,005
| 2,578,846
|
MLFlow search for a registered model is not working in R
|
<p>I would like to query registered models in mlflow using R api: <code>mlflow::mlflow_search_registered_models(filter="name='model_xyz'")</code>. But, it is throwing following error:</p>
<pre><code>Error : API request to endpoint 'registered-models/search' failed with error code 404. Reponse body: 'ENDPOINT_NOT_FOUND; No API found for 'POST /mlflow/registered-models/search''
</code></pre>
<p>I believe this is a <strong>GET</strong> request. But, why it is saying No API found for <strong>POST</strong> request ? Any hints will be appreciated.</p>
<p>For your information, I have mlflow version (R): <code>mlflow_2.11.1</code> installed in my system.</p>
|
<python><r><mlflow>
|
2024-03-19 15:53:22
| 0
| 3,071
|
Sijan Bhandari
|
78,187,861
| 12,320,370
|
Appending tuples returned by for loop
|
<p>I am running some SQL queries using sqlalchemy. I have a for loop that runs queries against Snowflake tables.</p>
<p>Current Code:</p>
<pre><code>for x in list:
results = cursor.execute(f"SELECT TABLE_NAME as TABLE_NAME, 'TABLE_SCHEMA as TABLE_SCHEMA, MAX(DATE) as DATE FROM {database}.{schema}.{table}")
for result in results:
print(result)
</code></pre>
<p>This for loop returns a tuple with each iteration, like below:</p>
<pre><code>('SCHEMA_1','TABLE_1','DATE_1')
('SCHEMA_2','TABLE_2','DATE_2')
('SCHEMA_3','TABLE_3','DATE_3')
</code></pre>
<p>etc.</p>
<p>How can I create a tuple of tuples from this from loop? So I can then later pass it into a DataFrame.</p>
<p>All I want to do is create a dataframe from the loop that will append the results each time, so I can then write the complete df back to Snowflake.</p>
<p><strong>I cannot use the snowflake-connector-python[pandas] module and need to do it with sqlalchemy + pandas.</strong></p>
|
<python><list><sqlalchemy><tuples><snowflake-cloud-data-platform>
|
2024-03-19 15:32:38
| 1
| 333
|
Nairda123
|
78,187,747
| 12,107,239
|
How to Replace Pydantic's constr for use outside of BaseModel in FastAPI?
|
<p>I'm working with FastAPI and Pydantic for a project where I've used <code>constr</code> for string validation. This has been particularly useful for ensuring that string inputs adhere to specific constraints, like length and format, directly in the route function signatures.</p>
<p><a href="https://i.sstatic.net/aPOwM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aPOwM.png" alt="enter image description here" /></a></p>
<p>Here's an example of how I've been using it:</p>
<pre class="lang-py prettyprint-override"><code>from pydantic import constr
from fastapi import FastAPI, HTTPException
SiteCode = constr(strict=True, to_upper=True, max_length=4)
app = FastAPI()
@app.get("/{site_code}", summary="Read a site")
async def get_site(site_code: SiteCode) -> str:
return "..."
</code></pre>
<p>However, I've learned that constr is <a href="https://docs.pydantic.dev/latest/api/types/#pydantic.types.constr" rel="nofollow noreferrer">deprecated</a>, and I'm looking for a modern replacement that aligns with current best practices in Pydantic and FastAPI. My goal is to maintain the same level of validation (e.g., strict, to_upper, max_length) for parameters passed directly to route functions, not just within Pydantic models.</p>
|
<python><fastapi><pydantic>
|
2024-03-19 15:15:57
| 1
| 323
|
rcepre
|
78,187,625
| 3,651,529
|
See if pandas character column is in the string column
|
<p>I want to see, by row, if values of a char column are present in a string column.</p>
<p>For example, in</p>
<pre><code>df = pd.DataFrame({
'char': ['A', 'B', 'A', 'C', 'D'],
'str': ['WCCC', 'BFC', 'GFA', 'E', <NA>]
})
</code></pre>
<p>I want to see if the 'char' column is in the 'str' column.</p>
<p>expected output is
<code>[False, True, True, False, False]</code>.</p>
<p>I am working with a large dataset.</p>
|
<python><pandas><string>
|
2024-03-19 14:58:40
| 3
| 6,252
|
kangaroo_cliff
|
78,187,376
| 22,466,650
|
How to make a regex orderless when validating a list of texts?
|
<p>My input is this dataframe (but it could be a simple list) :</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'description': ['ij edf m-nop ij abc', 'abc ij mnop yz', 'yz yz mnop aa abc', 'i j y y abc xxx mnop y z', 'yz mnop ij kl abc uvwxyz', 'aaabc ijij uuu yz mnop']})
</code></pre>
<p>I also have a list of keywords (between 3 and 7 items) that I need to valid. We should only validate an exact combination of the whole keywords and ignore characters in between. The problem is that those keywords don't respect the order I put them in my list (here <code>keywords</code>).</p>
<p>I searched in google and here too but couldn't find any post that talks about a similar topic. So I made the code below which is making a permuation of the keywords and put them in a regex string.</p>
<pre><code>import re
import itertools
keywords = ['abc', 'ij', 'mnop', 'yz']
regex = ''
for perm in list(itertools.permutations(keywords)):
perm = [fr'\b{key}\b' for key in perm]
regex += f'(?:{".*".join(perm)})|'
regex = regex.rstrip('|')
</code></pre>
<p>Here is a snippet of my regex :</p>
<pre><code># (?:\babc\b.*\bij\b.*\bmnop\b.*\byz\b)|(?:\babc\b.*\bij\b.*\byz\b.*\bmnop\b)|(?:\
# babc\b.*\bmnop\b.*\bij\b.*\byz\b)|(?:\babc\b.*\bmnop\b.*\byz\b.*\bij\b)|(?:\babc
# \b.*\byz\b.*\bij\b.*\bmnop\b)|(?:\babc\b.*\byz\b.*\bmnop\b.*\bij\b)|(?:\bij\b.*\
# babc\b.*\bmnop\b.*\byz\b)|(?:\bij\b.*\babc\b.*\byz\b.*\bmnop\b)|(?:\bij\b.*\bmno
# p\b.*\babc\b.*\byz\b)|(?:\bij\b.*\bmnop\b.*\byz\b.*\babc\b)|(?:\bij\b.*\byz\b.*\
# babc\b.*\bmnop\b)|(?:\bij\b.*\byz\b.*\bmnop\b.*\babc\b)|(?:\bmnop\b.*\babc\b.*\b
# ij\b.*\byz\b)|(?:\bmnop\b.*\babc\b.*\byz\b.*\bij\b)|(?:\bmnop\b.*\bij\b.*\babc\b
# .*\byz\b)|(?:\bmnop\b.*\bij\b.*\byz\b.*\babc\b)|(?:\bmnop\b.*\byz\b.*\babc\b.*\b
# ij\b)|(?:\bmnop\b.*\byz\b.*\bij\b.*\babc\b)|(?:\byz\b.*\babc\b.*\bij\b.*\bmnop\b
# )|(?:\byz\b.*\babc\b.*\bmnop\b.*\bij\b)|(?:\byz\b.*\bij\b.*\babc\b.*\bmnop\b)|(?
# :\byz\b.*\bij\b.*\bmnop\b.*\babc\b)|(?:\byz\b.*\bmnop\b.*\babc\b.*\bij\b)|(?:\by
# z\b.*\bmnop\b.*\bij\b.*\babc\b)
</code></pre>
<p>While it works on the example I gave, it takes 5-15 minutes on my real dataset (50k rows and very long descriptions with breaklines) and I'm not sure if my approach handles correctly all the rows. And there is also a problem, sometimes I had to validate a list of 6 keywords, which gives 720 permuation !</p>
<p>Can you guys help me solve this ? Is regex the right way to approach my problem ?</p>
<p>My expected ouptut is this :</p>
<pre><code> description valid
0 ij edf m-nop ij abc
1 abc ij mnop yz True
2 yz yz mnop aa abc
3 i j y y abc xxx mnop y z
4 yz mnop ij kl abc uvwxyz True
5 aaabc ijij uuu yz mnop
</code></pre>
|
<python><pandas>
|
2024-03-19 14:21:18
| 1
| 1,085
|
VERBOSE
|
78,187,218
| 3,079,439
|
Converting Pandas DataFrame structure into Pytorch Dataset
|
<p>Have a question regarding Pytorch framework that I started to use recently (while always used keras/tf in the past).</p>
<p>So I would like to convert simple pandas <code>DataFrame</code> to the pytorch <code>Dataset</code>.</p>
<pre><code>import pandas as pd
df = pd.DataFrame(np.array([[1, 2], [4, 5], [7, 8]]), columns=['A', 'B'])
</code></pre>
<p>For applying desirable transformation, I create custom Dataset class and inherit from the pytorch Dataset in the following way:</p>
<pre><code>from datasets import Dataset
class CustomDataset(Dataset):
def __init__(self, src_file):
df = pd.read_csv(src_file)
self.A = df['A']
self.B = df['B']
def __len__(self):
return len(self.A)
def __getitem__(self, idx):
A_py = self.A.iloc[idx]
B_py = self.B.iloc[idx]
return A_py, B_py
</code></pre>
<p>When I try to execute the code doing:</p>
<pre><code>data = CustomDataset('src_file')
data
</code></pre>
<p>receiving an error of the following kind:</p>
<pre><code>AttributeError: 'CustomDataset' object has no attribute '_info'
</code></pre>
<p>What is wrong here and how should I change my approach?</p>
|
<python><pandas><pytorch>
|
2024-03-19 14:00:13
| 1
| 3,158
|
Keithx
|
78,187,120
| 13,086,128
|
Drop all the columns after a particular column
|
<p>Suppose, I am reading a csv with hundreds of columns.</p>
<p>Now, I know that after a particular column say <code>'XYZ'</code> all the columns are junk.</p>
<p>I want to keep all the columns from the beginning till column <code>'XYZ'</code> and drop all the columns after column <code>'XYZ'</code>.</p>
<p>In pandas, I may do something like:</p>
<pre><code>df.iloc[:, :df.columns.get_loc('XYZ') + 1]
</code></pre>
<p>What could be an efficient way in polars?</p>
|
<python><python-3.x><python-polars>
|
2024-03-19 13:43:56
| 2
| 30,560
|
Talha Tayyab
|
78,187,045
| 4,537,160
|
Trying to install Python3.11 in Docker image based on nvidia/cuda:11.3.1-cudnn8-runtime-ubuntu20.04, getting html5lib error
|
<p>I'm using this Dockerfile:</p>
<pre><code>FROM nvidia/cuda:11.3.1-cudnn8-runtime-ubuntu20.04
ENV DEBIAN_FRONTEND=noninteractive
# the following line is needed in order for the build to succeed due to some outdated stuff in the docker image
RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub
# Update package lists and install necessary tools
RUN apt-get update && \
apt-get install -y software-properties-common
# Add deadsnakes PPA to get Python 3.11
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt update --fix-missing && \
apt install python3.11 python3.11-distutils -y && \
apt install python3-pip -y && \
ln -sf /usr/bin/python3.11 /usr/bin/python && \
ln -sf /usr/bin/pip3 /usr/bin/pip
# install latest pip
RUN curl -sS https://bootstrap.pypa.io/get-pip.py | python3.11
RUN apt-get update -y && apt-get install -y --no-install-recommends build-essential gcc \
libsndfile1
ARG UNAME=user
ARG UID=1000
ARG GID=1000
RUN groupadd -g $GID -o $UNAME
RUN useradd -m -u $UID -g $GID -o -s /bin/bash $UNAME
USER $UNAME
COPY requirements.txt /tmp/requirements.txt
RUN python -m pip install --user setuptools wheel
RUN python -m pip install --user --no-cache-dir -r /tmp/requirements.txt -f https://download.pytorch.org/whl/cu113/torch_stable.html
</code></pre>
<p>As mentioned in the comment, I added the deadsnakes PPA to get Python 3.11.
I keep getting the error:</p>
<pre><code>File "/usr/lib/python3/dist-packages/pip/_internal/index/collector.py", line 12, in <module>
0.929 from pip._vendor import html5lib, requests
0.929 ImportError: cannot import name 'html5lib' from 'pip._vendor' (/usr/lib/python3/dist-packages/pip/_vendor/__init__.py)
</code></pre>
<p>I'm installing pip using the <code>get-pip.py</code> as suggested in <a href="https://stackoverflow.com/questions/70431655/importerror-cannot-import-name-html5lib-from-pip-vendor-usr-lib-python3">this answer</a>, but still no success.</p>
|
<python><docker><pip>
|
2024-03-19 13:35:21
| 1
| 1,630
|
Carlo
|
78,186,958
| 1,422,096
|
How to monkey-patch np.savez_compressed to add compression level, without editing numpy's source files?
|
<p>I need to modify the ZIP <code>compressionlevel</code> internally used in <a href="https://numpy.org/doc/stable/reference/generated/numpy.savez_compressed.html" rel="nofollow noreferrer"><code>np.savez_compressed</code></a>. There is a <a href="https://github.com/numpy/numpy/issues/20995" rel="nofollow noreferrer">feature proposal</a> on Numpy Github, but it is not implemented yet.</p>
<p>I see two options:</p>
<ul>
<li><p>modify the source file <code>/numpy/lib/npyio.py</code> and replace <code>zipf = zipfile_factory(file, mode="w", compression=compression)</code> by <code><idem>..., compresslevel=compresslevel)</code>, but this creates the burden, that on each re-install or upgrade, after <code>pip install numpy</code>, I have to do this modification: this is a suboptimal solution.</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/5626193/what-is-monkey-patching">monkey-patching</a> the <a href="https://github.com/numpy/numpy/blob/v1.26.0/numpy/lib/npyio.py#L713" rel="nofollow noreferrer"><code>_savez</code> function</a></p>
</li>
</ul>
<p>How to do this?</p>
<p>Here I tried the second option, but it fails with <code>ValueError: seek of closed file</code>, but I don't see why:</p>
<pre><code>import numpy as np
def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None):
import zipfile
if not hasattr(file, 'write'):
file = os_fspath(file)
if not file.endswith('.npz'):
file = file + '.npz'
namedict = kwds
for i, val in enumerate(args):
key = 'arr_%d' % i
if key in namedict.keys():
raise ValueError("Cannot use un-named variables and keyword %s" % key)
namedict[key] = val
if compress:
compression = zipfile.ZIP_DEFLATED
else:
compression = zipfile.ZIP_STORED
zipf = np.lib.npyio.zipfile_factory(file, mode="w", compression=compression, compresslevel=2) # !! the only modified line !!
for key, val in namedict.items():
fname = key + '.npy'
val = np.asanyarray(val)
# always force zip64, gh-10776
with zipf.open(fname, 'w', force_zip64=True) as fid:
format.write_array(fid, val, allow_pickle=allow_pickle, pickle_kwargs=pickle_kwargs)
zipf.close()
np.lib.npyio._savez = _savez
x = np.array([1, 2, 3, 4])
with open("test.npz", "wb") as f:
np.savez_compressed(f, x=x)
</code></pre>
|
<python><arrays><numpy><compression><monkeypatching>
|
2024-03-19 13:21:12
| 1
| 47,388
|
Basj
|
78,186,669
| 12,415,855
|
Pytesseract / Recoginizing chars + digits + spaces
|
<p>i would like to recognize some text (with digits and spaces) from a image using the following code:</p>
<pre><code>erg = pytesseract.image_to_string(img)
</code></pre>
<p>Generally this works fine with that but i also get character i donΒ΄t want like Γ</p>
<pre><code>ΓAU OPTRONICS CORPORATION
() Preliminary Specification
(V) Final Specification
Module 18.5" Color TFT-LCD
Model Name (G18SHANOT.O
Customer Date ΓApproved by Date
Crystal Hsieh 2016/06/29
Approved by Propared by
</code></pre>
<p>So i tried to whitelist tesseract using the following code instead:</p>
<pre><code>workString =f'-c tessedit\_char\_whitelist={string.digits}(){string.ascii\_letters}'
erg = pytesseract.image\_to\_string(img, config=workString)
</code></pre>
<p>With that i get the following text - so it seems that Γ is not outputted - but unfortunately have no spaces anymore -</p>
<p>AUOPTRONICSCORPORATION</p>
<pre><code>()ProliminarySpecification
(V)FinalSpecification
Module 185ColorTFTLCD
ModelName (G18SHANOTO
Customer Date Approvedby Date
CrstalHsieh 2016(06)29
Approvedby Proparedby
</code></pre>
<p>Is there any way to whitelist the characters and digits but also still output the spaces / blanks?</p>
|
<python><python-tesseract>
|
2024-03-19 12:37:39
| 1
| 1,515
|
Rapid1898
|
78,186,564
| 9,754,418
|
"ModuleNotFoundError: No module named 'sagemaker.huggingface' despite installing sagemaker package"
|
<p>I am trying to use the <code>sagemaker.huggingface</code> module to run a hugging face estimator as described in <a href="https://huggingface.co/blog/sagemaker-distributed-training-seq2seq#create-a-huggingface-estimator-and-start-training" rel="nofollow noreferrer">this blog</a>, but I encounter the following error:</p>
<pre><code>ModuleNotFoundError: No module named 'sagemaker.huggingface'; 'sagemaker' is not a package
</code></pre>
<p>This is the line of code it gets that error on, in the first line of my python file:</p>
<pre><code>from sagemaker.huggingface import HuggingFace
</code></pre>
<p>I have installed the <code>sagemaker</code> package (version <code>2.213.0</code> when I run <code>conda list</code>) using <code>conda install sagemaker</code> without any errors on my system. If I do <code>import sagemaker</code>, I don't get the error. However, when I check if the <code>huggingface</code> submodule is included in the <code>sagemaker</code> package using the following code:</p>
<pre class="lang-py prettyprint-override"><code>if 'huggingface' in dir(sagemaker):
print('The huggingface submodule is included in this version of sagemaker.')
else:
print('The huggingface submodule is not included in this version of sagemaker.')
</code></pre>
<p>I get the output:</p>
<pre><code>The huggingface submodule is not included in this version of sagemaker.
</code></pre>
<p>I am using Python 3.10.13 (when I check <code>python --version</code>) and have created a new conda environment named "distill" with the following packages installed:</p>
<pre><code>conda create --name distill python=3.10.6 -y
conda activate distill
conda install -y pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 cudatoolkit=11.3 -c pytorch
pip install git+https://github.com/huggingface/transformers@v4.24.0 datasets sentencepiece protobuf==3.20.* tensorboardX
</code></pre>
<p>I am running SageMaker Distribution 1.4 on SageMaker Studio.</p>
<p>What could be causing this issue, and how can I resolve it to use the <code>sagemaker.huggingface</code> module?</p>
|
<python><conda><amazon-sagemaker><large-language-model><huggingface>
|
2024-03-19 12:20:47
| 0
| 1,238
|
Yann Stoneman
|
78,186,481
| 539,251
|
Polars DataFrames Python do replacement by using mask which itself is another Polars DataFrame
|
<p>How to change variables (or recreate) dataframe, with another boolean mask Polars DataFrame?
So not just single column vectors (Series), but both a DataFrame.</p>
<p>So set the following to 1000, where amount > 270, value at the bottom would become 1000</p>
<p>Input:</p>
<pre><code> apples[0].amount apples[1].amount... apples[3].amount apples[4].amount
0 NaN 321.68012 ... NaN NaN
1 NaN NaN ... NaN 259.70487
2 NaN NaN ... NaN 259.70487
3 NaN NaN ... NaN 259.70487
4 NaN NaN ... NaN 259.70487
... ... ... ... ... ...
440582 79.57273 NaN ... NaN NaN
440583 NaN NaN ... NaN NaN
440584 NaN NaN ... NaN NaN
440585 NaN NaN ... NaN NaN
440586 NaN NaN ... 299.91544 NaN
[440587 rows x 5 columns]
</code></pre>
<p>Expected Output:</p>
<pre><code> apples[0].amount apples[1].amount... apples[3].amount apples[4].amount
0 NaN 1000.00000 ... NaN NaN
1 NaN NaN ... NaN 259.70487
2 NaN NaN ... NaN 259.70487
3 NaN NaN ... NaN 259.70487
4 NaN NaN ... NaN 259.70487
... ... ... ... ... ...
440582 79.57273 NaN ... NaN NaN
440583 NaN NaN ... NaN NaN
440584 NaN NaN ... NaN NaN
440585 NaN NaN ... NaN NaN
440586 NaN NaN ... 1000.00000 NaN
[440587 rows x 5 columns]
</code></pre>
<p><strong>Another example</strong>:
cum_sum_volume_apples input:</p>
<pre><code> apples[0].amount apples[1].amount ... apples[3].amount apples[4].amount
0 321.66164 1322.18012 ... 1581.98712 1683.34388
1 321.66164 574.39164 ... 849.15207 1260.20487
2 321.66164 574.39164 ... 849.15207 1260.20487
3 321.66164 574.39164 ... 849.15207 1260.20487
4 321.66164 574.39164 ... 849.15207 1260.20487
... ... ... ... ... ...
440582 1080.07273 1089.38273 ... 3248.32543 3266.94847
440583 9.06278 26.69990 ... 1107.99783 1117.30783
440584 346.34516 363.98228 ... 1445.28021 1454.59021
440585 346.34516 363.98228 ... 882.09418 891.40418
440586 426.89556 773.24072 ... 1300.41544 1308.98974
[440587 rows x 5 columns]
</code></pre>
<p>at_or_above_threshold_mask ~1000</p>
<pre><code> apples[0].amount apples[1].amount ... apples[3].amount apples[4].amount
0 False True ... False False
1 False False ... False True
2 False False ... False True
3 False False ... False True
4 False False ... False True
... ... ... ... ... ...
440582 True False ... False False
440583 False False ... False False
440584 False False ... False False
440585 False False ... False False
440586 False False ... True False
[440587 rows x 5 columns]
</code></pre>
<p>How to filter on just the true values, with the at_threshold_mask, on another dataframe with the same x/y length? (a sample could include a mask on the already existing cum_sum_volume_apples above)</p>
<pre><code>cum_sum_all = pl.cum_sum_horizontal("*")
at_or_above_threshold_boolean_cum_sum = (
(cum_sum_volume_apples >= volume_threshold).select(cum_sum_all).unnest("cum_sum")
)
at_or_above_threshold_mask = at_or_above_threshold_boolean_cum_sum >= 1
at_threshold_mask = at_or_above_threshold_boolean_cum_sum == 1
</code></pre>
|
<python><python-polars>
|
2024-03-19 12:07:55
| 2
| 1,545
|
BigChief
|
78,186,362
| 1,288,071
|
How to apply `numpy.vectorize` on a subset of arguments?
|
<p>I have searched a lot but couldn't find a solution to this particular problem. I have a function with the following signature:</p>
<pre><code>def my_function(self, number: float, lookup: list[str]) -> float:
# perform some operation
return some_float_based_on_operation
</code></pre>
<p>I am trying to vectorize it as follows:</p>
<pre><code>my_ndarray = np.vectorize(self.my_function)(my_ndarray, ["a", "b", "c"])
</code></pre>
<p>where <code>my_ndarray</code> is one dimensional array of 18 floats.</p>
<p>But I get the following error when I try to run the code above:</p>
<pre><code>ValueError: operands could not be broadcast together with shapes (18,) (3,)
</code></pre>
<p>My use case does not need to have both arguments of same length because the second argument is an unrelated list of strings. How can I vectorize such a function?</p>
|
<python><numpy>
|
2024-03-19 11:49:43
| 1
| 1,735
|
Cashif Ilyas
|
78,186,300
| 18,519,921
|
Differrent behavior between numpy arrays and array scalars
|
<p>This is a follow-up on <a href="https://stackoverflow.com/questions/78180968/can-i-force-array-numpy-to-keep-its-uint32-type">this</a> question.</p>
<p>When we use a numpy <strong>array</strong> with a specific type, it preserves its type following numeric operations.<br />
For example adding 1 to a <code>uint32</code> array will wrap up the value to 0 if needed (when the array contained the max <code>uint32</code> value) and keep the array of type <code>uint32</code>:</p>
<pre><code>import numpy
a = numpy.array([4294967295], dtype='uint32')
a += 1 # will wrap to 0
print(a)
print(a.dtype)
</code></pre>
<p>Output:</p>
<pre><code>uint32
[0]
uint32
</code></pre>
<p>This behavior does not hold for an array <strong>scalar</strong> with the same type:</p>
<pre><code>import numpy
a = numpy.uint32(4294967295)
print(a.dtype)
a += 1 # will NOT wrap to 0, and change the scalar type
print(a)
print(a.dtype)
</code></pre>
<p>Output:</p>
<pre><code>uint32
4294967296
int64
</code></pre>
<p>But according to the <a href="https://numpy.org/doc/stable/user/basics.types.html#array-scalars" rel="nofollow noreferrer">array scalars documentation</a>:</p>
<blockquote>
<p>The primary advantage of using array scalars is that they preserve the array type</p>
<p>...</p>
<p>Therefore, the use of array scalars ensures <strong>identical behaviour between arrays and scalars</strong>, irrespective of whether the value is inside an array or not.</p>
</blockquote>
<p><em>(emphasys is mine)</em></p>
<p><strong>My question:</strong><br />
Why do I observe the above different behavior between arrays and scalars despite the explicit documentation that states they should behave identically ?</p>
|
<python><numpy><numpy-ndarray><numpy-scalar>
|
2024-03-19 11:40:19
| 1
| 35,449
|
wohlstad
|
78,186,148
| 12,780,274
|
Received duplicate pseudo-header field b':path' error when I send http2 requests in python
|
<p>I have a url that only responds to http2 requests.</p>
<p>When I want send http/2 request with python to the URL, I get bellow <code>ERROR</code>:</p>
<blockquote>
<p><code>h2.exceptions.ProtocolError: Received duplicate pseudo-header field b':path'</code></p>
</blockquote>
<p>My <code>Code</code>:</p>
<pre><code>from hyper.contrib import HTTP20Adapter
import requests
MyHeader={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
adapter = HTTP20Adapter(headers=MyHeader)
sessions=requests.session()
sessions.mount(prefix='https://myurl.com', adapter=adapter)
r=sessions.get('Continue_My_Url_response')
print(r)
</code></pre>
<p>I use too many <code>requests</code> library for <code>HTTP/1</code> and this is first time I want work with <code>HTTP/2</code>.</p>
<p>Any body have idea and example for send this request over <code>HTTP/2</code>?</p>
|
<python><python-3.x><http2>
|
2024-03-19 11:14:08
| 2
| 643
|
henrry
|
78,185,983
| 108,390
|
What is the equivalent to df.to_markdown() for a Polars Dataframe?
|
<p>In Pandas, it is super easy to just do</p>
<pre><code>from IPython.display import display, Markdown
display(Markdown(my_df.to_markdown()))
</code></pre>
<p>In a Notebook to get nice-looking tables printed out.</p>
<p>if you have a Polars dataframe, you (obviously) get</p>
<blockquote>
<p>AttributeError: 'DataFrame' object has no attribute 'to_markdown'</p>
</blockquote>
<p>My current workaround is to</p>
<pre><code>to_display = my_df.to_pandas()
display(Markdown(to_display.to_markdown()))
</code></pre>
<p>Is there a better way?</p>
|
<python><python-polars>
|
2024-03-19 10:48:32
| 1
| 1,393
|
Fontanka16
|
78,185,715
| 860,848
|
Passing and Returning Java Map to GraalVM python
|
<p>I want to pass java map to python code and access the map values in python, and then store the results in a map, then access the results in Java. I'm stuck with the first step to pass java map to python.</p>
<p>I have tried with the following code, but didn't work</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;
public class PythonJavaMap {
public static void main(String[] args) {
Map<String, String> javaMap = new HashMap<>();
javaMap.put("key1", "value1");
javaMap.put("key2", "value2");
try (Context context = Context.create()) {
context.getBindings("python").putMember("java_map", javaMap);
Value result = context.eval("python", "for key, value in java_map.items(): print(value)");
}
}
}
</code></pre>
<p>I got the following error</p>
<pre><code>Exception in thread "main" AttributeError: foreign object has no attribute 'items'
at <python> <module>(Unknown)
at org.graalvm.polyglot.Context.eval(Context.java:428)
at com.mindSynth.PythonJavaMap.main(PythonJavaMap.java:18)
</code></pre>
|
<python><java><graalvm><graalpython>
|
2024-03-19 10:07:28
| 1
| 607
|
Jay
|
78,185,606
| 726,730
|
multiproccessing broken pipe error when i am trying to send plot data from process
|
<p>I have made a pyqt5 app to test the microphones. I used pydub and pyaudio modules for this scope. I also plot the microphone data with matplotlib. I have a QDialog, which run an emitter to communicate with the qdialog and multiproccessing to read from pyaudio input stream. When from my ui i choose to normalize the microphone sound then there is noise when i don't speak. Also in this case after some minutes the application crash with this error:</p>
<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
File "C:\Users\chris\Documents\My Projects\papinhio-player\src\python+\main-window\../..\python+\menu-1\manage-input-and-output-sound-devices\microphone-input-device-settings\microphone-input-device-setting.py", line 866, in run
self.to_emitter.send({"type":"plot_data","plot_data":[self.x_vals,self.y_vals],"normalized_value":normalized_value})
File "C:\Python\Lib\multiprocessing\connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "C:\Python\Lib\multiprocessing\connection.py", line 301, in _send_bytes
nwritten, err = ov.GetOverlappedResult(True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
BrokenPipeError: [WinError 109] ΠδιοΟΞΟΞ΅Ο
ΟΞ· ΞΟΡι ΟΞ΅ΟΞΌΞ±ΟΞΉΟΟΡί
Process Manage_Input_Device_Child_Proc-1:
Traceback (most recent call last):
File "C:\Users\chris\Documents\My Projects\papinhio-player\src\python+\main-window\../..\python+\menu-1\manage-input-and-output-sound-devices\microphone-input-device-settings\microphone-input-device-setting.py", line 866, in run
self.to_emitter.send({"type":"plot_data","plot_data":[self.x_vals,self.y_vals],"normalized_value":normalized_value})
File "C:\Python\Lib\multiprocessing\connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "C:\Python\Lib\multiprocessing\connection.py", line 301, in _send_bytes
nwritten, err = ov.GetOverlappedResult(True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
BrokenPipeError: [WinError 109] ΠδιοΟΞΟΞ΅Ο
ΟΞ· ΞΟΡι ΟΞ΅ΟΞΌΞ±ΟΞΉΟΟΡί
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\Lib\multiprocessing\process.py", line 314, in _bootstrap
self.run()
File "C:\Users\chris\Documents\My Projects\papinhio-player\src\python+\main-window\../..\python+\menu-1\manage-input-and-output-sound-devices\microphone-input-device-settings\microphone-input-device-setting.py", line 875, in run
self.to_emitter.send({"type":"error","error_message":error_message})
File "C:\Python\Lib\multiprocessing\connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "C:\Python\Lib\multiprocessing\connection.py", line 289, in _send_bytes
ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
BrokenPipeError: [WinError 232] ΠδιοΟΞΟΞ΅Ο
ΟΞ· κλΡίνΡι
Process finished with exit code -1073741571 (0xC00000FD)
</code></pre>
<p>The error has something to do with plot data. If i comment this line: <code>self.to_emitter.send({"type":"plot_data","plot_data":[self.x_vals,self.y_vals],"normalized_value":normalized_value})</code> then there is no application crash.</p>
<p>Relative code:</p>
<pre class="lang-py prettyprint-override"><code>class Manage_Input_Device_Emitter(QThread):
try:
plot_data_signal = pyqtSignal(list,float)
save_finished = pyqtSignal()
devices_settings = pyqtSignal(list,int,float,float,float,float,float)
error_signal = pyqtSignal(str)
except:
pass
def __init__(self, from_process: Pipe):
try:
super().__init__()
self.data_from_process = from_process
except:
pass
def run(self):
try:
while True:
data = self.data_from_process.recv()
if data["type"]=="plot_data":
self.plot_data_signal.emit(data["plot_data"],data["normalized_value"])
elif data["type"]=="save_finished":
self.save_finished.emit()
elif data["type"]=="available_devices":
self.devices_settings.emit(data["devices"],data["device_index"],data["volume"],data["is_normalized"],data["pan"],data["low frequency"],data["high frequency"])
elif data["type"] == "error":
self.error_signal.emit(data["error_message"])
except:
error_message = traceback.format_exc()
self.error_signal.emit(error_message)
class Manage_Input_Device_Child_Proc(Process):
def __init__(self, to_emitter, from_mother):
try:
super().__init__()
self.daemon = False
self.to_emitter = to_emitter
self.data_from_mother = from_mother
#local argument(s) save
except:
try:
error_message = str(traceback.format_exc())
to_emitter.send({"type":"error","error_message":error_message})
except:
pass
def run(self):
try:
self.fetch_input_settings()
self.bit_rate = 128*1024 #128 kb/sec
self.packet_time = 125 #125 msec
#self.packet_time = 125*44100/32768
self.packet_size = int(16384/4)
#self.new_sample_rate = 32768
self.new_sample_rate = 44100
self.TIME_WINDOW = 3000
self.format = pyaudio.paInt16
self.channels = 2
self.input_stream = None
self.output_stream = None
self.play_status = "stopped"
self.process_terminated = False
while(self.process_terminated == False):
if self.play_status == "stopped":
data = self.data_from_mother.get()
else:
q_size = self.data_from_mother.qsize()
if q_size>0:
data = self.data_from_mother.get()
else:
data = None
if data is not None:
if data["type"] == "stop-process":
self.process_terminated = True
return 1
if data["type"] == "save":
device_name = data["device_name"]
volume = data["volume"]
is_normalized = data["is_normalized"]
pan = data["pan"]
low_frequency = data["low_frequency"]
high_frequency = data["high_frequency"]
self.save(device_name,volume,is_normalized,pan,low_frequency,high_frequency)
break
elif data["type"] == "test":
self.output_stream = self.p.open(format=pyaudio.paInt16,channels=self.channels,rate=self.new_sample_rate,output=True,output_device_index=self.output_device_index,frames_per_buffer=self.packet_size)
#self.output_stream = self.p.open(format=pyaudio.paInt16,channels=self.channels,rate=self.new_sample_rate,output=True,frames_per_buffer=self.packet_size)
self.output_stream.start_stream()
self.input_device_name = data["content"]
for input_device in self.input_devices:
if(data["content"]==input_device[2]):
self.input_device_index = input_device[1]
self.input_stream = self.p.open(format=pyaudio.paInt16,channels=1,rate=self.new_sample_rate,input=True,input_device_index=self.input_device_index,frames_per_buffer=self.packet_size)
self.input_stream.start_stream()
self.input_channels = 1
'''
try:
self.input_stream = self.p.open(format=pyaudio.paInt16,channels=self.channels,rate=self.new_sample_rate,input=True,input_device_index=self.input_device_index,frames_per_buffer=self.packet_size)
self.input_stream.start_stream()
self.input_channels = self.channels
except Exception as e:
#self.input_stream = self.p.open(format=pyaudio.paInt16,channels=1,rate=self.new_sample_rate,input=True,input_device_index=self.input_device_index,frames_per_buffer=self.packet_size)
self.input_stream = self.p.open(format=pyaudio.paInt16,channels=1,rate=self.new_sample_rate,input=True,input_device_index=self.input_device_index,frames_per_buffer=self.packet_size)
self.input_stream.start_stream()
self.input_channels = 1
'''
self.play_status = "playing"
self.chunk_number = 0
self.current_duration_milliseconds = 0
self.now = datetime.now()
self.x_vals = np.array([])
self.y_vals = np.array([])
elif data["type"] == "stop":
self.play_status = "stopped"
self.chunk_number = 0
self.current_duration_milliseconds = 0
try:
self.output_stream.stop_stream()
self.output_stream.close()
self.input_stream.stop_stream()
self.input_stream.close()
except:
pass
self.now = datetime.now()
self.x_vals = np.array([])
self.y_vals = np.array([])
elif data["type"] == "volume":
self.volume = data["value_base_100"]
elif data["type"] == "is_normalized":
self.is_normalized = data["boolean_value"]
elif data["type"] == "pan":
self.pan = data["pan_value"]
elif data["type"] == "low_frequency":
self.low_frequency = data["low_frequency_value"]
elif data["type"] == "high frequency":
self.high_frequency = data["high_frequency_value"]
if self.play_status=="playing":
in_data = self.input_stream.read(self.packet_size,exception_on_overflow = False)
if self.input_channels == 2:
slice = AudioSegment(in_data, sample_width=2, frame_rate=self.new_sample_rate, channels=2)
else:
slice = AudioSegment(in_data, sample_width=2, frame_rate=self.new_sample_rate, channels=1)
slice = AudioSegment.from_mono_audiosegments(slice, slice)
if self.pan!=0:
slice = slice.pan(self.pan/100)
if self.low_frequency>20:
slice = effects.high_pass_filter(slice, self.low_frequency)
if self.high_frequency>20000:
slice = effects.low_pass_filter(slice, self.high_frequency)
if(self.volume==0):
db_volume = -200
else:
db_volume = 20*math.log10(self.volume/100)
slice = slice+db_volume
if self.is_normalized:
slice = self.normalize_method(slice,0.1)
self.output_stream.write(slice.raw_data)
free = self.output_stream.get_write_available()
if free > self.packet_size: # Is there a lot of space in the buffer?
tofill = free - self.packet_size
silence = chr(0)*tofill*self.channels*2
self.output_stream.write(silence) # Fill it with silence
#free = self.output_stream.get_write_available()
#print(free)
chunk_time = len(slice)
samples = slice.get_array_of_samples()
left_samples = samples[::2]
right_samples = samples[1::2]
left_audio_data = np.frombuffer(left_samples, np.int16)[::16] #down sampling
right_audio_data = np.frombuffer(right_samples, np.int16)[::16] #down sampling
audio_data = np.vstack((left_audio_data,right_audio_data)).ravel('F')
time_data = np.array([])
for i in range(0,len(audio_data)):
time_data = np.append(time_data, self.now)
self.now = self.now+timedelta(milliseconds=chunk_time/len(audio_data))
self.x_vals = np.concatenate((self.x_vals, time_data))
self.y_vals = np.concatenate((self.y_vals, audio_data))
if(self.x_vals.size>audio_data.size*(self.TIME_WINDOW/chunk_time)):
self.x_vals = self.x_vals[audio_data.size:]
self.y_vals = self.y_vals[audio_data.size:]
average_data_value = slice.max
normalized_value = abs(average_data_value)/slice.max_possible_amplitude
if normalized_value>1:
normalized_value = 1
if self.play_status == "stopped":
normalized_value = 0
self.to_emitter.send({"type":"plot_data","plot_data":[self.x_vals,self.y_vals],"normalized_value":normalized_value})
self.now = datetime.now()
self.chunk_number += 1
self.current_duration_milliseconds += chunk_time
except:
error_message = str(traceback.format_exc())
print(error_message)
self.to_emitter.send({"type":"error","error_message":error_message})
def normalize_method(self,seg, headroom):
try:
peak_sample_val = seg.max
# if the max is 0, this audio segment is silent, and can't be normalized
if peak_sample_val == 0:
return seg
target_peak = seg.max_possible_amplitude * utils.db_to_float(-headroom)
#target_peak = seg.max_possible_amplitude * (percent_headroom)
needed_boost = utils.ratio_to_db(target_peak / peak_sample_val)
return seg.apply_gain(needed_boost)
except:
error_message = traceback.format_exc()
self.to_emitter.send({"type":"error","error_message":error_message})
return seg
</code></pre>
|
<python><pyqt5><multiprocessing><pipe>
|
2024-03-19 09:52:26
| 1
| 2,427
|
Chris P
|
78,185,518
| 2,729,831
|
Gcloud functions deploy crash
|
<p>Everytime I try to deploy a function I get an error:</p>
<pre><code>ERROR: gcloud crashed (TypeError): expected string or bytes-like object
</code></pre>
<p>I uploaded the same code manually in a zip file and there were no problems.</p>
<p>This is the command:</p>
<pre><code>gcloud functions deploy myfunction \
--runtime python39 \
--trigger-http \
--entry-point main \
--source . \
--region europe-west1 \
--project myproject \
--env-vars-file env.json
</code></pre>
<p>With debug anbled:</p>
<pre><code>DEBUG: expected string or bytes-like object
Traceback (most recent call last):
File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 987, in Execute
resources = calliope_command.Run(cli=self, args=args)
File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 807, in Run
resources = command_instance.Run(args)
File "/usr/lib/google-cloud-sdk/lib/surface/functions/deploy.py", line 104, in Run
return command_v2.Run(args, self.ReleaseTrack())
File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/functions/v2/deploy/command.py", line 1065, in Run
_SetInvokerPermissions(args, function, is_new_function)
File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/functions/v2/deploy/command.py", line 866, in _SetInvokerPermissions
service_ref_one_platform = resources.REGISTRY.ParseRelativeName(
File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/core/resources.py", line 1082, in ParseRelativeName
return parser.ParseRelativeName(
File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/core/resources.py", line 203, in ParseRelativeName
match = re.match(path_template, relative_name)
File "/usr/lib/google-cloud-sdk/platform/bundledpythonunix/lib/python3.9/re.py", line 191, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object
ERROR: gcloud crashed (TypeError): expected string or bytes-like object
</code></pre>
|
<python><google-cloud-functions><gcloud>
|
2024-03-19 09:38:40
| 1
| 473
|
blob
|
78,184,921
| 5,049,813
|
How can just using the += "syntactic sugar" cause an infinite loop?
|
<p>Let <code>a = [-1, -2, -3]</code>. I want to modify the list <code>a</code> so that <code>a == [-1, -2, -3, 1, 2, 3]</code>, and I want to use <code>map</code> to achieve that.</p>
<p>I have the following different pieces of code I've written to do this:</p>
<ol>
<li><code>a = a + map(abs, a)</code></li>
<li><code>a = a + list(map(abs, a))</code></li>
<li><code>a += map(abs, a)</code></li>
<li><code>a += list(map(abs, a))</code></li>
</ol>
<p>Here's the results:</p>
<ol>
<li><strong><code>TypeError: can only concatenate list (not "map") to list</code></strong></li>
<li>Works as expected: <code>a = [-1, -2, -3, 1, 2, 3]</code></li>
<li><strong>Hangs indefinitely</strong> before getting terminated with no error message (potentially ran out of memory?)</li>
<li>Works as expected: <code>a = [-1, -2, -3, 1, 2, 3]</code></li>
</ol>
<p>I thought that <code>a += b</code> was just syntactic sugar for <code>a = a + b</code>, but, given how (1) and (3) behave, that's clearly that's not the case.</p>
<p>Why does (1) give an error, while (3) seems to go into an infinite loop, despite one generally just being a syntactic sugar version of the other?</p>
|
<python><addition><syntactic-sugar>
|
2024-03-19 07:46:23
| 1
| 5,220
|
Pro Q
|
78,184,551
| 5,884,886
|
Need help learning Python with non thread safe code
|
<p>I'm trying to work through a tutorial for Python 3.12.2. I'm at the section where it tries to demonstrate non-thread safe code. The tutorial said the following code would produce unpredictable results. Well, for me it produced very predictable results. The code is:</p>
<pre><code># when no thread synchronization used
from threading import Thread as Thread
def inc():
global x
for _ in range(1000000):
x+=1
#global variable
x = 0
counter = 0
while counter < 10:
# creating threads
threads = [Thread(target=inc) for _ in range(10)]
# start the threads
for thread in threads:
thread.start()
#wait for the threads
for thread in threads:
thread. Join()
print("Pass ", counter, "final value of x:", f"{x:,}")
x = 0
counter += 1
</code></pre>
<p>It produced the following output;</p>
<pre><code>PS D:\PythonDev> python .\thread3a.py
Pass 0 final value of x: 10,000,000
Pass 1 final value of x: 10,000,000
Pass 2 final value of x: 10,000,000
Pass 3 final value of x: 10,000,000
Pass 4 final value of x: 10,000,000
Pass 5 final value of x: 10,000,000
Pass 6 final value of x: 10,000,000
Pass 7 final value of x: 10,000,000
Pass 8 final value of x: 10,000,000
Pass 9 final value of x: 10,000,000
PS D:\PythonDev>
</code></pre>
<p>I modified it to add the outer while loop so I would not have to run it from the command line over and over again. According to the tutorial the expected result of each pass is supposed to be 10,000,000. However, in reality the result should be unpredictable and less than 10,000,000. It's neither. What am I doing wrong?</p>
<p>My environment is;</p>
<pre><code>O/S: MS Windows 10 Home 22H2
RAM: 16 GB
CPU: Intel Core I7-2860QM
Terminal Session: PowerShell 7.4.1
Python version: 3.12.2
</code></pre>
|
<python><multithreading>
|
2024-03-19 06:17:56
| 2
| 329
|
Barry S. Rayfield
|
78,184,545
| 9,749,972
|
Can we make parent class initialization less often than child class'?
|
<p>I tried to plot sine waves with different frequencies (<code>f</code>) and amplitudes (<code>a</code>) using class inheritance. But it doesn't seem to me it runs efficiently.
Here is my code where I put common attributes f and a in the parent class and the variable t in the child class.</p>
<pre><code>import math
from matplotlib import pyplot as plt
class Parent:
def __init__(self, f, a):
self.freq = f
self.ampl = a
self.color = (f/a/3, (f/a)/2, (f/a)) # some random RGB numbers
class Child(Parent):
def __init__(self, t, f, a):
super(Child, self).__init__(f, a)
self.time = t
def volt(self):
omega = 2*math.pi*self.freq
return self.ampl * math.sin(omega*self.time)
if __name__ == '__main__':
for (f,a) in [(0.05,1.5), (0.1,1)]:
color = Parent(f, a).color
time = [i for i in range(50)]
cl = [Child(x, f, a).volt() for x in time]
plt.plot(time, cl, color=color)
plt.xlabel("time")
plt.ylabel("amplitude")
plt.title(f"Voltage waveform for different frequencies")
plt.show()
</code></pre>
<p>It works. But for every instantiation of <code>Child(x, f, a)</code>, it runs <code>super().__init__</code> as well, which doesn't change for every variable <code>x</code>. I wonder if there is a way to run <code>Parent</code> in the outer loop for variable <code>f, a</code> and run <code>Child</code> in the inner loop for variable <code>x</code>.</p>
|
<python><class><inheritance>
|
2024-03-19 06:15:44
| 3
| 691
|
Leon Chang
|
78,184,542
| 14,367,125
|
How to scan Bluetooth BR/EDR (Classic) with Python on macOS?
|
<p>I'm developing a remote sensor using ESP32 to collect data and send it to my macOS via Bluetooth, and use Python to receive it from the macOS side. I hope I can build a small Python tool to:</p>
<ol>
<li>Scan surrounding Bluetooth devices.</li>
<li>User selects the specific one they want (in this way, my ESP32 Bluetooth device).</li>
<li>Create communication between them.</li>
</ol>
<p>I know the vanilla Python can communicate with MAC address of a connected Bluetooth device (STEP 3), according to <a href="https://www.youtube.com/watch?v=8pMaR-WUc6U" rel="nofollow noreferrer">this tutorial</a>. But the problem is how can I find the MAC address programmatically (STEP 1).</p>
<ol>
<li>Since <code>PyBluez</code> is not under development anymore, it's not considered.</li>
<li><code>bleak</code> can only discover BLE devices, according to <a href="https://bleak.readthedocs.io/en/latest/api/scanner.html" rel="nofollow noreferrer">its documentation</a>. Also, I tried to scan with it, but the output only shows the name as <code>None</code> for BR/EDR (Classic) devices. (I replace the real address with x for privacy reason):</li>
</ol>
<pre><code>xxxxxxxx-2C6A-65F5-9450-xxxxxxxxxxxx: None
xxxxxxxx-D159-3E92-85BF-xxxxxxxxxxxx: None
xxxxxxxx-1206-C3AF-4A51-xxxxxxxxxxxx: Yimingβs iPhone
</code></pre>
|
<python><macos><bluetooth>
|
2024-03-19 06:13:51
| 0
| 726
|
Yiming Designer
|
78,184,522
| 11,748,924
|
Count num of occurences of every 26 characters for every word in numpy
|
<p>I have this numpy array that stored on <code>wordlist_arr</code>:</p>
<pre><code>[b'aabi\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abcdefghijklmnopqrstuvwxyz'
b'aabinomin\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abcdefghijklmnopqrstuvwxyz'
b'aaji\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abcdefghijklmnopqrstuvwxyz'
...
b'zus\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abcdefghijklmnopqrstuvwxyz'
b'zuzumo\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abcdefghijklmnopqrstuvwxyz'
b'zuzuni\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abcdefghijklmnopqrstuvwxyz']
(71729,)
|S64
</code></pre>
<p>I expect I could count 26 characters for every wordlist, so the output shape will be <code>(71729, 26)</code>:</p>
<pre><code>[[3,2,1,1,1,1,1,1,2,1,...,1],
...
]
'''
In [3,2,1,1,1,1,1,1,2,1,...,1]
index 0 represent num "a" counted, index 1 represent num "b" counted, and so on...
'''
</code></pre>
<p>I change POV and reshape so that it will be viewed as per characters</p>
<pre><code>wordlist.view('S1').reshape((wordlist.size, -1))
'''
[[b'a' b'a' b'b' ... b'x' b'y' b'z']
[b'a' b'a' b'b' ... b'x' b'y' b'z']
[b'a' b'a' b'j' ... b'x' b'y' b'z']
...
[b'z' b'u' b's' ... b'x' b'y' b'z']
[b'z' b'u' b'z' ... b'x' b'y' b'z']
[b'z' b'u' b'z' ... b'x' b'y' b'z']]
(71729, 64)
|S1
'''
</code></pre>
<p>As you see I put <code>abcdefghijklmnopqrstuvwxyz</code> at the end of index so that I could use method <code>np.unique</code> so that at least there is 1 counted of every alphabetic. But it seems it doesn't work, instead it returned every possible characters used.</p>
<pre><code>[b'' b'a' b'b' b'c' b'd' b'e' b'f' b'g' b'h' b'i' b'j' b'k' b'l' b'm' b'n'
b'o' b'p' b'q' b'r' b's' b't' b'u' b'v' b'w' b'x' b'y' b'z']
(27,)
|S1
</code></pre>
<p>I tried another approach using numpy char count but it seems doesn't work too:</p>
<pre><code>np.char.count(wordlist.view('S1').reshape(wordlist.size, -1), alphabet, axis=1)
# ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (71729, 64) and arg 1 with shape (26,).
</code></pre>
<p>Actually I can use native way, but for now I'm looking for numpythonic way so that I can utilize numpy performance that written in <code>C lang</code></p>
|
<python><arrays><numpy><count><character>
|
2024-03-19 06:04:38
| 1
| 1,252
|
Muhammad Ikhwan Perwira
|
78,184,361
| 726,730
|
PyQt5: How to center QDialog inside centralwidget of QMainWindow
|
<p>I have a QMainWindow like this:<a href="https://i.sstatic.net/tDtKJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tDtKJ.png" alt="enter image description here" /></a></p>
<p>In the top of the window there is title bar (default windows behavior) with the title the program icon and the minimize, maximize and close buttons.
After there is a menubar, and under it there is a toolbar.
Then there is the main centralwidget (which has only a stackedwidget as child widget).
And in the bottom of the page there is the statusbar.</p>
<p>When i open a new QDialog using .exec() method i want:</p>
<ol>
<li>QDialog size to be 0.98*centralwidget_size</li>
<li>QDialog to be centered so the center of QDialog to be the center a centralwidget.</li>
<li>Make 2. responsive if it's possible (I mean the QDialog's rect() to be changed on QMainWindow rect() change).</li>
</ol>
<p>I tried many methods with no luck.</p>
<pre class="lang-py prettyprint-override"><code> title_bar_height = QtWidgets.QApplication.style().pixelMetric(QtWidgets.QStyle.PM_TitleBarHeight)
central_widget_width = int(self.main_self.ui.centralwidget.frameSize().width())
central_widget_height = int(self.main_self.ui.centralwidget.frameSize().height())
self.setFixedSize(int(0.95*central_widget_width),int(1.0*(central_widget_height-title_bar_height)))
central_widget_top_x = int(self.main_self.ui.centralwidget.frameGeometry().x())
central_widget_top_y = int(self.main_self.ui.centralwidget.frameGeometry().y())
central_widget_width = int(self.main_self.ui.centralwidget.frameGeometry().width())
central_widget_height = int(self.main_self.ui.centralwidget.frameGeometry().height())
qdialog_width = self.frameGeometry().width()
qdialog_height = self.frameGeometry().height()
print(central_widget_top_y)#->75
qdialog_new_x = central_widget_top_x + (central_widget_width-qdialog_width)/2
qdialog_new_y = central_widget_top_y + (central_widget_height-qdialog_height)/2
self.move(int(qdialog_new_x),int(qdialog_new_y))
print(self.frameGeometry().y()) #->75
</code></pre>
<p><a href="https://i.sstatic.net/MQ9AW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MQ9AW.png" alt="enter image description here" /></a></p>
<p>The size is correct, but the x,y aren't.</p>
|
<python><user-interface><pyqt5>
|
2024-03-19 05:19:26
| 1
| 2,427
|
Chris P
|
78,184,320
| 1,333,133
|
A conda activated virtual enviroment is not running the Python file when called from a flask webservice
|
<p>I have created a virutal environment using conda, and am trying to run a python script in it using a flask end point call. The code is not executing , whereas if I run the file from terminal by getting inside the virtual environment it runs in less than a minute. Any idea what am I missing?</p>
<p>My venv name: py311</p>
<p>My calls are:</p>
<pre><code>import flask
import requests
import json
import urllib3
import urllib.parse
from flask import request, jsonify,make_response
import subprocess
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/vl/<startdate>/<enddate>', methods=['GET'])
def gen2(startdate, enddate):
result_err={}
k=subprocess.getoutput(' /home/azureuser/anaconda3/bin/conda run -n py311 && python Ekal_Visit_Listing_Between_Dates_A.py ' + startdate +" " +enddate)
result_err['fname']=k
return make_response(jsonify(result_err),200)
if __name__ == "__main__":
app.run(host='0.0.0.0')
</code></pre>
<p>Error in browser is :</p>
<pre><code>{
"fname": "\n# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<\n\n Traceback (most recent call last):\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/exception_handler.py\", line 17, in __call__\n return func(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/cli/main.py\", line 83, in main_subshell\n exit_code = do_call(args, parser)\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/cli/conda_argparse.py\", line 196, in do_call\n result = getattr(module, func_name)(args, parser)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/cli/main_run.py\", line 96, in execute\n script, command = wrap_subprocess_call(\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/utils.py\", line 448, in wrap_subprocess_call\n raise Exception(\"No compatible shell found!\")\n Exception: No compatible shell found!\n\n`$ /home/azureuser/anaconda3/bin/conda run -n py311`\n\n environment variables:\n CIO_TEST=<not set>\n CONDA_ROOT=/home/azureuser/anaconda3\n CURL_CA_BUNDLE=<not set>\n LD_PRELOAD=<not set>\n PATH=/home/azureuser/anaconda3/envs/py311/bin\n REQUESTS_CA_BUNDLE=<not set>\n SSL_CERT_FILE=<not set>\n\n active environment : None\n user config file : /var/www/.condarc\n populated config files : \n conda version : 24.1.2\n conda-build version : 24.1.2\n python version : 3.11.7.final.0\n solver : libmamba (default)\n virtual packages : __archspec=1=broadwell\n __conda=24.1.2=0\n __glibc=2.27=0\n __linux=5.4.0=0\n __unix=0=0\n base environment : /home/azureuser/anaconda3 (read only)\n conda av data dir : /home/azureuser/anaconda3/etc/conda\n conda av metadata url : None\n channel URLs : https://repo.anaconda.com/pkgs/main/linux-64\n https://repo.anaconda.com/pkgs/main/noarch\n https://repo.anaconda.com/pkgs/r/linux-64\n https://repo.anaconda.com/pkgs/r/noarch\n package cache : /home/azureuser/anaconda3/pkgs\n /var/www/.conda/pkgs\n envs directories : /var/www/.conda/envs\n /home/azureuser/anaconda3/envs\n platform : linux-64\n user-agent : conda/24.1.2 requests/2.31.0 CPython/3.11.7 Linux/5.4.0-1109-azure ubuntu/18.04.5 glibc/2.27 solver/libmamba conda-libmamba-solver/24.1.0 libmambapy/1.5.6\n UID:GID : 33:33\n netrc file : None\n offline mode : False\n\n\nAn unexpected error has occurred. Conda has prepared the above report.\nIf you suspect this error is being caused by a malfunctioning plugin,\nconsider using the --no-plugins option to turn off plugins.\n\nExample: conda --no-plugins install <package>\n\nAlternatively, you can set the CONDA_NO_PLUGINS environment variable on\nthe command line to run the command without plugins enabled.\n\nExample: CONDA_NO_PLUGINS=true conda install <package>\n"
</code></pre>
<p>Curl call to this is also failing:</p>
<pre><code>curl 'https://afitraining.ekalarogya.org/vl/2024-01-01/2024-03-01'
{
"fname": "\n# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<\n\n Traceback (most recent call last):\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/exception_handler.py\", line 17, in __call__\n return func(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/cli/main.py\", line 83, in main_subshell\n exit_code = do_call(args, parser)\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/cli/conda_argparse.py\", line 196, in do_call\n result = getattr(module, func_name)(args, parser)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/cli/main_run.py\", line 96, in execute\n script, command = wrap_subprocess_call(\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/home/azureuser/anaconda3/lib/python3.11/site-packages/conda/utils.py\", line 448, in wrap_subprocess_call\n raise Exception(\"No compatible shell found!\")\n Exception: No compatible shell found!\n\n`$ /home/azureuser/anaconda3/bin/conda run -n py311`\n\n environment variables:\n CIO_TEST=<not set>\n CONDA_ROOT=/home/azureuser/anaconda3\n CURL_CA_BUNDLE=<not set>\n LD_PRELOAD=<not set>\n PATH=/home/azureuser/anaconda3/envs/py311/bin\n REQUESTS_CA_BUNDLE=<not set>\n SSL_CERT_FILE=<not set>\n\n active environment : None\n user config file : /var/www/.condarc\n populated config files : \n conda version : 24.1.2\n conda-build version : 24.1.2\n python version : 3.11.7.final.0\n solver : libmamba (default)\n virtual packages : __archspec=1=broadwell\n __conda=24.1.2=0\n __glibc=2.27=0\n __linux=5.4.0=0\n __unix=0=0\n base environment : /home/azureuser/anaconda3 (read only)\n conda av data dir : /home/azureuser/anaconda3/etc/conda\n conda av metadata url : None\n channel URLs : https://repo.anaconda.com/pkgs/main/linux-64\n https://repo.anaconda.com/pkgs/main/noarch\n https://repo.anaconda.com/pkgs/r/linux-64\n https://repo.anaconda.com/pkgs/r/noarch\n package cache : /home/azureuser/anaconda3/pkgs\n /var/www/.conda/pkgs\n envs directories : /var/www/.conda/envs\n /home/azureuser/anaconda3/envs\n platform : linux-64\n user-agent : conda/24.1.2 requests/2.31.0 CPython/3.11.7 Linux/5.4.0-1109-azure ubuntu/18.04.5 glibc/2.27 solver/libmamba conda-libmamba-solver/24.1.0 libmambapy/1.5.6\n UID:GID : 33:33\n netrc file : None\n offline mode : False\n\n\nAn unexpected error has occurred. Conda has prepared the above report.\nIf you suspect this error is being caused by a malfunctioning plugin,\nconsider using the --no-plugins option to turn off plugins.\n\nExample: conda --no-plugins install <package>\n\nAlternatively, you can set the CONDA_NO_PLUGINS environment variable on\nthe command line to run the command without plugins enabled.\n\nExample: CONDA_NO_PLUGINS=true conda install <package>\n"
</code></pre>
<p>whereas if I run this from inside venv this runs in less than a min:</p>
<pre><code>(base) myhost:~$ source activate py311
(py311) myhost:~$ python script.py '2024-01-01' '2024-03-01'
myurl/reports/19_03_2024_10_27_56_product_listing.xlsx
</code></pre>
|
<python><anaconda3>
|
2024-03-19 05:05:05
| 1
| 8,901
|
Satya
|
78,183,969
| 1,942,868
|
Python requires libmysqlclient.22.dylib but libmysqlclient.23.dylib exist
|
<p>I bumped into this error.
when running django script using mysql</p>
<pre><code>ImportError: dlopen(/Users/whitebear/.local/share/virtualenvs/cinnamon-admin-mg9y4sUV/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.22.dylib
</code></pre>
<p>There is no <code>/opt/homebrew/opt/mysql/lib/libmysqlclient.22.dylib</code>, but</p>
<p>there is /opt/homebrew/opt/mysql/lib/libmysqlclient.23.dylib instead.</p>
<blockquote>
<p>mysql --version
mysql Ver 8.3.0 for macos14.2 on arm64 (Homebrew)</p>
</blockquote>
<blockquote>
<p>python --version
Python 3.9.18</p>
</blockquote>
<p>So I guess I should update <code>python</code> to another version, or downgrade <code>mysql</code></p>
<p>Am I correct?</p>
<p>If so which version should I update to?</p>
|
<python><mysql>
|
2024-03-19 02:37:26
| 0
| 12,599
|
whitebear
|
78,183,857
| 3,055,616
|
Could not find a version that satisfies the requirement torch when compiling
|
<p>I have a code running on a Mac mini M2 that requires torch and torch audio, and that works as expected when testing it in VSCode but when compiling into Docker I get this error, any idea how to fix it? I've found some other posts online regarding the python versions, I did try changing versions (3.10, 3.11) and even using a lower version of torch (1.8.0) but none of that made any difference.</p>
<p>Thank you.</p>
<p>Dockerfile</p>
<pre><code>FROM --platform=linux/arm64 python:3.9-alpine3.15
# Upgrade pip
RUN python -m pip install --upgrade pip
# Install system dependencies
RUN apk add --no-cache build-base \
&& apk add --no-cache ffmpeg-dev ffmpeg \
&& apk add --no-cache pkgconfig
# Copy the project code
ADD . /code
WORKDIR /code
# Install Python dependencies from requirements.txt
RUN pip install -r requirements.txt
# Expose the necessary port
EXPOSE 80
# Define the command to run the application
CMD python app.py
</code></pre>
<p>requirements.txt</p>
<pre><code>flask
requests
torch==2.0.0
torchaudio==2.0.1
</code></pre>
<p>Error:</p>
<pre><code>Building 25.2s (11/11) FINISHED docker:desktop-linux
=> [web internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 559B 0.0s
=> [web internal] load metadata for docker.io/library/python:3.9-alpine3.15 0.7s
=> [web auth] library/python:pull token for registry-1.docker.io 0.0s
=> [web internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [web 1/6] FROM docker.io/library/python:3.9-alpine3.15@sha256:86d5546236a8f8dd6505a92c40db8a01f8c22b7425f32396b6bfe6ef4bd18230 0.0s
=> [web internal] load build context 3.5s
=> => transferring context: 8.42MB 3.2s
=> CACHED [web 2/6] RUN python -m pip install --upgrade pip 0.0s
=> CACHED [web 3/6] RUN apk add --no-cache build-base && apk add --no-cache ffmpeg-dev ffmpeg && apk add --no-cache pkgconfig 0.0s
=> [web 4/6] ADD . /code 19.1s
=> [web 5/6] WORKDIR /code 0.1s
=> ERROR [web 6/6] RUN pip install -r requirements.txt 1.7s
------
> [web 6/6] RUN pip install -r requirements.txt:
1.239 Collecting flask (from -r requirements.txt (line 1))
1.416 Downloading flask-3.0.2-py3-none-any.whl.metadata (3.6 kB)
1.461 Collecting requests (from -r requirements.txt (line 4))
1.490 Downloading requests-2.31.0-py3-none-any.whl.metadata (4.6 kB)
1.610 ERROR: Could not find a version that satisfies the requirement torch==2.0.0 (from versions: none)
1.610 ERROR: No matching distribution found for torch==2.0.0
</code></pre>
|
<python><docker><pytorch>
|
2024-03-19 01:50:32
| 1
| 685
|
AJ152
|
78,183,758
| 9,067,589
|
Python PyQt5 Add Remote Debugging To Compiled Application
|
<p>In my project I create an application which I then compile with pyinstaller.</p>
<p>The application allows the end-user to add HTML5 files into a folder which the python script then runs as a web app using PyQt5. As described in the documentation <a href="https://doc.qt.io/qt-6/qtwebengine-debugging.html" rel="nofollow noreferrer">here</a> to get remote debugging running I start the app by executing the following command line:</p>
<pre><code>python main.py --remote-debugging-port=8080
</code></pre>
<p>Since this is a command line parameter, once I've compiled the project using pyinstaller this option is gone and the remote debugging tools are no longer available for the end-user.</p>
<p>What I need is to add the parameters inside the code like this:</p>
<pre><code>if __name__ == "__main__":
# Example Sudo Code:
# startAppWithArguments("--remote-debugging-port=8080")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
</code></pre>
<p>I've looked into <a href="https://docs.python.org/3/howto/argparse.html" rel="nofollow noreferrer">Argparse</a> but this does not seem to be what I'm looking for. Also I've sort of read that I could maybe pass the parameter into <code>sys.argv</code> but I failed make sense of it.</p>
<p>How can I add the remote debuigging parameter <code>--remote-debugging-port=8080</code> to my application inside the code without needing the CLI to run it?</p>
|
<python><pyqt5><pyinstaller><remote-debugging>
|
2024-03-19 01:08:17
| 1
| 1,247
|
Miger
|
78,183,666
| 2,340,002
|
How to bind implicit constructor/conversion in Python with pybind11?
|
<p>I'm trying to mimic implicit conversion/construction of a simple struct in Python using <code>pybind11</code>:</p>
<pre><code>struct MyType {
double a;
double b;
};
void func(size_t foo, const MyType& bar) {
// ...
}
// ...
PYBIND11_MODULE(pymylib, module) {
// ...
py::class_< MyType >(module, "MyType")
.def(py::init< double, double >(), "a"_a, "b"_a)
.def(py::init([](const std::array< double, 2 >& ab){ return MyType({ab[0], ab[1]}); }), "ab"_a = std::array< double, 2>{ 1.0, 0.25 }) // not implicit
.def_readwrite("a", &MyType::a)
.def_readwrite("b", &MyType::b);
py::implicitly_convertible< std::array< double, 2 >, MyType >(); // conversion is not implicit
module.def("func", &func, "foo"_a, "bar"_a);
}
</code></pre>
<p>While in C++ one can use brace initialization <code>{}</code> without having to implicitly call <code>MyType</code> constructor (simplifying the syntax), I am still unable to have an implicit conversion from a list object when passing MyType as argument to <code>func</code>:</p>
<pre><code>obj = module.MyType(8.7, 5.6)
module.func(47, obj) # works
module.func(47, module.MyType([4.1, 7.8])) # works
module.func(47, [4.1, 7.8]) # does not work ('incompatible function arguments')
</code></pre>
<p>From what I understand from <a href="https://pybind11.readthedocs.io/en/stable/advanced/classes.html#brace-initialization" rel="nofollow noreferrer"><code>pybind11</code> documentation</a>, the constructor declaration <code>py::init< double, double >()</code> should bind brace-initialization implicitly, but it's not working as I expected:</p>
<pre><code>TypeError: func(): incompatible function arguments. The following argument types are supported:
1. module.func(a: float, b: module.MyType)
</code></pre>
<p>I tried adding a custom constructor accepting a list/array, but it is still not called implicitly.</p>
<p>Due to the simplicity of the struct, having to explicitly call the constructor seems unnecessary, particularly if defined in a Python submodule or nested on another class;
How - if possible - do I achieve this behavior in Python?</p>
|
<python><c++><implicit-conversion><pybind11>
|
2024-03-19 00:25:47
| 1
| 1,767
|
joaocandre
|
78,183,619
| 1,390,639
|
too many ticks on log colorscale
|
<p>I am working in a <code>Jupyter</code> notebook with <code>Python 3.9.12</code> and <code>matplotlib 3.5.2</code>. I am trying to plot a contour plot using <code>contourf</code> with a logarithmic "z" or "colorscale."</p>
<p>The code that I'm using is here:</p>
<pre><code>#set up a 1d plot
fig,axes = plt.subplots(1,1,figsize=(9.0,8.0),sharex=True)
ax1 = axes
from matplotlib import cm, ticker
ymin=1.0
ymax=15
xmin=4.0
xmax=45
zzN = np.nan_to_num(zzN)
z = ma.masked_where((zzN<=1e-3)|(zzN>0.2), zzN)
nrcont=ax1.contourf(p1,q1,z,locator=ticker.LogLocator(), cmap='coolwarm',alpha=0.3)
cbar = fig.colorbar(nrcont)
cbar.ax.set_ylabel('joint PDF',labelpad=15)
ax1.set_xlim(xmin, xmax) #in pairs
ax1.set_ylim(ymin,ymax)
ax1.set_xlabel('phonon energy [keV]')
ax1.set_ylabel('charge energy [keV]')
ax1.grid(True)
ax1.yaxis.grid(True,which='minor',linestyle='--')
#ax1.legend(loc=2,prop={'size':22})
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
plt.tight_layout()
plt.show()
</code></pre>
<p>The object <code>zzN</code> are the contour values that I am plotting and they range from something like <code>10^-320</code> to about <code>0.13</code>. Because of that huge range I masked it down in the variable <code>z</code> to go over just 2 decades instead. I would like to go to 4 decades for this plot.</p>
<p>The result is the following plot:</p>
<p><a href="https://i.sstatic.net/Id5iu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Id5iu.png" alt="contour plot" /></a></p>
<p>It's obvious that the colorscale is log but it is for some reason trying to give me ticks that are spaced 0.0025 apart. This is fine for the first decade of the scale, but for the last decade it results in a huge amount of ticks.</p>
<p>How can I get the normal "log" ticks back where each decade has 10 ticks logarithmically spaced?</p>
<p>Also: when I don't severely limit my z range (like if I try to start at 1e-4 instead of 1e-3) there are so many ticks that I get:</p>
<pre><code>Locator attempting to generate 4444 ticks ([0.000325, ..., 1.0]), which exceeds Locator.MAXTICKS (1000).
</code></pre>
|
<python><matplotlib><jupyter-notebook>
|
2024-03-19 00:06:34
| 0
| 1,259
|
villaa
|
78,183,300
| 169,083
|
How to return the full hierarchy of an XML node?
|
<p>Given the following XML snippet:</p>
<pre><code><Profile>
<Settings>
<PresentationParameters>
<Annualize>True</Annualize>
<LoadExAnteRiskForPresentation>False</LoadExAnteRiskForPresentation>
<MultiLegDisplayMode>Legs</MultiLegDisplayMode>
<Parameters>
<InitialDisplayMode>CollapseToPositions</InitialDisplayMode>
<InitialExpandCollapseLevel>-1</InitialExpandCollapseLevel>
</Parameters>
<PivotExpandCollapseStrategy>ExpandAllStrategy</PivotExpandCollapseStrategy>
<RollupExternallyManagedSleeves>False</RollupExternallyManagedSleeves>
<SharedParameters>
<AssetBasisInEffect>
<CalculationType>Invalid</CalculationType>
<IsColumnBasisInvested>False</IsColumnBasisInvested>
<Type>Standard</Type>
<Value>MWB_SESSION</Value>
</AssetBasisInEffect>
<AssetBasisSaveable>
<CalculationType>Invalid</CalculationType>
<IsColumnBasisInvested>False</IsColumnBasisInvested>
<Type>Standard</Type>
<Value>MWB_SESSION</Value>
</AssetBasisSaveable>
<CurrencySaveable>
<Mode>GROUP</Mode>
</CurrencySaveable>
<IsSessionBasisInEffect>True</IsSessionBasisInEffect>
</SharedParameters>
<ShowPositionsGrandTotal>True</ShowPositionsGrandTotal>
<TargetingCurrency>
<Mode>GROUP</Mode>
</TargetingCurrency>
<TransposeColumns>False</TransposeColumns>
<UnitBasisMeasureOption>PercentagePoints</UnitBasisMeasureOption>
<UnitTrustConstituentMode>DoNotDisplay</UnitTrustConstituentMode>
<WeightProrationOption>Default</WeightProrationOption>
</PresentationParameters>
</Settings>
</Profile>
</code></pre>
<p>I want to return a result that shows the full path of each leaf node, along with its value - as such:</p>
<pre><code>Settings.PresentationParameters.Annualize TRUE
Settings.PresentationParameters.LoadExAnteRiskForPresentation FALSE
Settings.PresentationParameters.MultiLegDisplayMode Legs
Settings.PresentationParameters.Parameters.InitialDisplayMode CollapseToPositions
...
</code></pre>
<p>Looking for advice on how to retrieve the entire path of the node.</p>
|
<python><xml><xpath>
|
2024-03-18 22:21:32
| 3
| 620
|
NoazDad
|
78,183,274
| 4,967,582
|
If I used recursion to solve Subset Product, would it "know" not to use combinations with a product > N to avoid redundancy?
|
<p>I'm solving Subset Product for positive integers, I'm given a list <strong>S</strong> of divisors and an integer <strong>N</strong>.
I must decide if a combination exists that equals to target.</p>
<p>I will remove non-divisors from <strong>S</strong>, remove duplicates of 1 as any combination equals 1 and this does not affect the correctness. I sort from smallest to largest as that's a requirement for my code to work as intended.</p>
<p>I find the max combination size by iterating and multiplying through the integers in <strong>S</strong> until we <strong><= N</strong>. I then cap the combinations to that size.</p>
<p><strong>I handle special cases that are efficiently solvable.</strong></p>
<ul>
<li>If the product of all elements in S equals <strong>N</strong>, return True.</li>
<li>If the product of all elements in S is less than <strong>N</strong>, return False.</li>
</ul>
<p>The code then does all combinations up to <strong>max_comb_size</strong> and either outputs True or False.</p>
<p>I would like to use a more efficient method to avoid even more redundant combinations, but I need to make sure recursion is actually working and "knows" that there's a <strong>max_comb_size</strong>. What would a recursive method look like for this variant Subset Product?</p>
<h2>Part One</h2>
<pre><code>from itertools import combinations
from itertools import product
import sys
from collections import deque
def check_divisors(N, S):
# Multiset Subset Product General Case for positive integers only
# Initialize the maximum combination size
max_comb_size = 0
# Calculate the product of divisors and find the maximum combination size
# without exceeding N
# The variable max_comb_size effectively bounds the size of combinations
divisor_product = 1
for divisor in S:
if divisor_product * divisor <= N:
max_comb_size += 1
divisor_product *= divisor
else:
break
# Case where all elements of S have a total product equal to N
product = 1
for num in S:
product *= num
if product == N:
return True
# Case where all elements of S have a product less than N
if product < N:
return False
# Try combinations of divisors starting from the smallest ones
for comb_size in range(1, max_comb_size + 1):
for combo in combinations(S, comb_size):
# Calculate the product of the current combination
current_product = 1 # Renamed the variable to avoid shadowing
for divisor in combo:
current_product *= divisor
# If the product equals N, return True
if current_product == N:
return True
# If no combination has a product equal to N, return False
return False
</code></pre>
<p>Part Two</p>
<pre><code>N = 320
S = [1,1,1,2,2,4,4,4,4,5,6]
# Remove non_divisors so that max_combo_size doesn't get confused.
# Also, 1's should only appear once, otherwise max_combo_size
# gets confused.
new_S = deque([])
flag = 0
for i in S:
if i != 1:
if N % i == 0:
new_S.append(i)
if i == 1:
flag = 1
# O(1) insertion, only one 1 is allowed
# as it confuses max_combination_size. Doesn't
# affect correctness as any combination of 1 has
# a product of 1*n
if flag == 1:
new_S.appendleft(1)
# Sorting is required for max_comb_size to work.
S = sorted(new_S)
print(check_divisors(N, S))
</code></pre>
|
<python><recursion><combinations>
|
2024-03-18 22:14:25
| 3
| 347
|
The T
|
78,183,246
| 15,412,256
|
Complex Polars Operation Using Subqueries and Threshold first hits
|
<p><code>df_original</code> represents the ice-cream inspector on station <code>A</code> and <code>B</code>:</p>
<pre class="lang-py prettyprint-override"><code>df_original = pl.DataFrame(
{
"station": ["A", "A", "A", "A", "B", "B", "B", "B"],
"ice_cream_date": [1, 2, 3, 4, 1, 2, 3, 4],
"customers": [10, 20, 30, 5, 5, 7, 4, 10],
"event": [0, 1, 0, 1, 1, 0, 1, 0],
}
)
</code></pre>
<ul>
<li><code>ice_cream_date</code> is the date encoded.</li>
<li><code>customers</code> represents the number of customers</li>
<li><code>event</code> represents the binary encoding where an inspector</li>
</ul>
<p><code>df_evnets</code> is where <code>event == 1</code> in <code>df_original</code>:</p>
<pre class="lang-py prettyprint-override"><code>df_events = pl.DataFrame(
{
"events": [1, 1, 1, 1],
"ice_cream_date": [2, 4, 1, 3],
"station": ["A", "A", "B", "B"],
"customers": [20, 5, 5, 4],
"evaluation_span": [10, 2, 2, 2],
"evaluation_end_date": [4, 4, 3, 4],
"evaluation_end_date_customer": [5, 5, 4, 10],
"good_customer": [30, 10, 8, 12],
"bad_customer": [5, 0, 4, 3],
}
)
</code></pre>
<ul>
<li><code>evaluation_span</code> is the number of days after the inspection date</li>
<li><code>evaluation_end_date</code> is the latest day for the inspection. (if the date+evaluation_span > max available date, the evaluation_end_date is the max available date.)</li>
<li><code>evaluation_end_date_customer</code> is the number of customers at the <code>evaluation_end_date</code> in <code>df_original</code></li>
<li><code>good_customer</code> is the good threshold for an inspector to give the station "good" rating on a particular <code>ice_cream_date</code></li>
<li><code>bad_customer</code>: the bad threshold</li>
</ul>
<p><strong>Struggling with:</strong>
I want to label whether a station has being given <code>good</code> or <code>bad</code> rating for every non-zero event.</p>
<p><strong>If an inspector sees the number of customers exceeds(dips below) the good(bad) threshold first, the station will be given good(bad) rating no matter of the length of the event span</strong></p>
<p>Expected output:</p>
<pre class="lang-py prettyprint-override"><code>shape: (4, 7)
ββββββββββββββββββ¬ββββββββββ¬βββββββββββββββββββββ¬βββββββ¬ββββββ¬βββββββββββββββββ¬βββββββββββββββββββββ
β ice_cream_date β station β evaluation_custome β good β bad β evaluation_end β actual_evaluation_ β
β --- β --- β rs β --- β --- β --- β end_date β
β i64 β str β --- β i64 β i64 β i64 β --- β
β β β i64 β β β β i64 β
ββββββββββββββββββͺββββββββββͺβββββββββββββββββββββͺβββββββͺββββββͺβββββββββββββββββͺβββββββββββββββββββββ‘
β 2 β A β 30 β 1 β 0 β 0 β 3 β
β 4 β A β 5 β 0 β 0 β 1 β 4 β
β 1 β B β 4 β 0 β 1 β 1 β 3 β
β 3 β B β 10 β 0 β 0 β 1 β 4 β
ββββββββββββββββββ΄ββββββββββ΄βββββββββββββββββββββ΄βββββββ΄ββββββ΄βββββββββββββββββ΄βββββββββββββββββββββ
</code></pre>
<ul>
<li><code>evaluation_customers</code> is the number of customers used for the evaluation</li>
<li><code>good</code> is the good binary label, indicating that during the <code>(event_date, event_date+evaluation_span]</code>, whether an inspector gives good rating to a station for a particular inspection event.</li>
<li><code>bad</code> is the bad binary label.</li>
<li><code>evaluation_end</code> is the evaluation end label, indicating that the number of customers did not exceeds(dips below) the good(bad) threshold during <code>(event_date, event_date+span)</code></li>
<li><code>actual_evaluation_end_date</code> is the date where the evaluation ends (good or bad threshold reached)</li>
</ul>
<p><a href="https://i.sstatic.net/kmSAK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kmSAK.png" alt="enter image description here" /></a></p>
|
<python><algorithm><python-polars>
|
2024-03-18 22:04:58
| 0
| 649
|
Kevin Li
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.