You can find the Intel's NPU Acceleration Library on this GitHub repo with Python code samples.
Is a blog about python programming language. You can see my work with python programming language, tutorials and news.
Showing posts with label 2024 news. Show all posts
Showing posts with label 2024 news. Show all posts
Saturday, September 7, 2024
News : Python in Visual Studio Code – September 2024 Release
We’re excited to announce the September 2024 release of the Python and Jupyter extensions for Visual Studio Code!
This release includes the following announcements:
Django unit test support
Go to definition from inlay hints with Pylance
If you’re interested, you can check the full list of improvements in our changelogs for the Python, Jupyter and Pylance extensions.
Read more on the offcial website.
Thursday, August 29, 2024
News : ... august 2024
... news for Python users and developers.
Python 3.12.5 released, see the official webpage.
... new Python 3.13.0 release candidate 1 released, you can read on this webpage.
the last one: Announcing Python Software Foundation Fellow Members for Q1 2024! from this webpage.
About the releases, I can say that all kinds of improvements are coming, I liked that they made the shell more interactive.
Sunday, April 28, 2024
News : New Django Builder online tool.
Django builder is free to use, and a personal project worked on in my spare time.
Any donations are very much appreciated.
If you want to, feel free to donate using the BitCoin address or PayPal link below.
Here is a new online tool that allows you to create projects with the Django framework and manage them more easily. It comes with different versions of Django, you can include channels and HTMX.
I don't see a command line to manage the project...
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
django,
news,
online tool,
web,
web development
Friday, April 19, 2024
Python 3.10.12 : Colab quantum circuits with qiskit - part 046.
I've added another introductory example to my GitHub repository with Google Colab notebooks on how to use quantum circuits with the Python package called qiskit and the IBM Quantum Platform.
I used the IBM Quantum Platform and it provides an A.P.I symbol so that it can be used with the source code.
You can find this notebook at this catafest_061.ipynb repo file.
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
Colab,
cuda,
module,
modules,
news,
packages,
python,
python 3,
python modules,
python packages,
qiskit,
qiskit_ibm_runtime,
runtime,
tutorial,
tutorials
Thursday, April 4, 2024
News : SciPy 1.13.0 new release.
SciPy 1.13.0 is the culmination of 3 months of hard work. This
out-of-band release aims to support NumPy 2.0.0, and is backwards
compatible to NumPy 1.22.4. The version of OpenBLAS used to build
the PyPI wheels has been increased to 0.3.26.dev.
This release requires Python 3.9+ and NumPy 1.22.4 or greater.
For running on PyPy, PyPy3 6.0+ is required.
This release can be found on the official GitHub repo.
python -m pip install --upgrade pip
Requirement already satisfied: pip in c:\python312\lib\site-packages (24.0)
...
python -m pip install --upgrade matplotlib
Collecting matplotlib
Downloading matplotlib-3.8.4-cp312-cp312-win_amd64.whl.metadata (5.9 kB)
...
Successfully installed contourpy-1.2.1 cycler-0.12.1 fonttools-4.50.0 kiwisolver-1.4.5 matplotlib-3.8.4
...
python -m pip install --upgrade scipy
Collecting scipy
Downloading scipy-1.13.0-cp312-cp312-win_amd64.whl.metadata (60 kB)
...
Successfully installed scipy-1.13.0
I tested the interpolate.Akima1DInterpolator changes with the default python script and works well:
import numpy as np
from scipy.interpolate import Akima1DInterpolator
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.linspace(1, 7, 7)
y = np.array([-1, -1, -1, 0, 1, 1, 1])
xs = np.linspace(min(x), max(x), num=100)
y_akima = Akima1DInterpolator(x, y, method="akima")(xs)
y_makima = Akima1DInterpolator(x, y, method="makima")(xs)
ax.plot(x, y, "o", label="data")
ax.plot(xs, y_akima, label="akima")
ax.plot(xs, y_makima, label="makima")
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
plt.show()
about Akima piecewise cubic Hermite interpolation.
Akima interpolator Fit piecewise cubic polynomials, given vectors x and y. The interpolation method by Akima uses a continuously differentiable sub-spline built from piecewise cubic polynomials. The resultant curve passes through the given data points and will appear smooth and natural.
The result of this source code is this:
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
matplotlib,
module,
modules,
news,
numpy,
packages,
python modules,
python packages,
scipy,
tutorial,
tutorials
Sunday, March 31, 2024
Python 3.12.1 : About multiprocessing performance.
Today I test a simple python script for Pool and ThreadPool python classes from multiprocessing python module.
The main goal was to test Python’s multiprocessing performance with my computer.
NumPy releases the GIL for many of its operations, which means you can use multiple CPU cores even with threads.
Processing large amounts of data with Pandas can be difficult, and with Polars dataframe library is a potential solution.
Sciagraph gives you both performance profiling and peak memory profiling information.
Let's teste only these class:
The multiprocessing.pool.Pool class provides a process pool in Python.
The multiprocessing.pool.ThreadPool class in Python provides a pool of reusable threads for executing spontaneous tasks.
This is the python script:
from time import time
import multiprocessing as mp
from multiprocessing.pool import ThreadPool
import numpy as np
import pickle
def main():
arr = np.ones((1024, 1024, 1024), dtype=np.uint8)
expected_sum = np.sum(arr)
with ThreadPool(1) as threadpool:
start = time()
assert (
threadpool.apply(np.sum, (arr,)) == expected_sum
)
print("Thread pool:", time() - start)
with mp.get_context("spawn").Pool(1) as process_pool:
start = time()
assert (
process_pool.apply(np.sum, (arr,))
== expected_sum
)
print("Process pool:", time() - start)
if __name__ == "__main__":
main()
This is the result:
python thread_process_pool_001.py
Thread pool: 1.6689703464508057
Process pool: 11.644825458526611
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
GIL,
module,
modules,
multiprocessing,
news,
numpy,
packages,
pandas,
Polars,
Pool,
python,
python 3,
python modules,
python packages,
Sciagraph,
ThreadPool
Sunday, March 10, 2024
Python 3.12.1 : From script to executable with pyinstaller.
Using scripts in or out of the environment is useful and accessible. Another version is to create an executable, but it will no longer allow the same access to the source code resource and the executable will not be very buildable.
It is debatable, especially for those who do not trust the compiled language.
Today, I use a Python packet called aaa that allows, through other options, the creation of an executable.
I installed this Python packet with the pip utility.
pip install PyInstaller
The source code I used is a simple example that displays some text.
import time
print("Welcome catafest !")
time.sleep(100)
To convert the Python program file into a single standalone executable, I used this command:
pyinstaller --onefile --console exec_001.py
9538 INFO: PyInstaller: 6.5.0, contrib hooks: 2024.3
9539 INFO: Python: 3.12.1
9636 INFO: Platform: Windows-10-10.0.19045-SP0
9638 INFO: wrote C:\PythonProjects\executable_001\exec_001.spec
9711 INFO: Extending PYTHONPATH with paths
['C:\\PythonProjects\\executable_001']
18951 INFO: checking Analysis
18999 INFO: Building because C:\PythonProjects\executable_001\exec_001.py changed
18999 INFO: Initializing module dependency graph...
19031 INFO: Caching module graph hooks...
19392 INFO: Analyzing base_library.zip ...
26750 INFO: Loading module hook 'hook-encodings.py' from 'C:\\Python312\\Lib\\site-packages\\PyInstaller\\hooks'...
35164 INFO: Loading module hook 'hook-pickle.py' from 'C:\\Python312\\Lib\\site-packages\\PyInstaller\\hooks'...
40857 INFO: Loading module hook 'hook-heapq.py' from 'C:\\Python312\\Lib\\site-packages\\PyInstaller\\hooks'...
44873 INFO: Caching module dependency graph...
45194 INFO: Running Analysis Analysis-00.toc
45194 INFO: Looking for Python shared library...
45217 INFO: Using Python shared library: C:\Python312\python312.dll
45217 INFO: Analyzing C:\PythonProjects\executable_001\exec_001.py
45223 INFO: Processing module hooks...
45240 INFO: Performing binary vs. data reclassification (2 entries)
45243 INFO: Looking for ctypes DLLs
45259 INFO: Analyzing run-time hooks ...
45264 INFO: Including run-time hook 'C:\\Python312\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_inspect.py'
45326 INFO: Looking for dynamic libraries
45708 INFO: Extra DLL search directories (AddDllDirectory): []
45709 INFO: Extra DLL search directories (PATH): []
46487 INFO: Warnings written to C:\PythonProjects\executable_001\build\exec_001\warn-exec_001.txt
46534 INFO: Graph cross-reference written to C:\PythonProjects\executable_001\build\exec_001\xref-exec_001.html
46696 INFO: checking PYZ
46797 INFO: checking PKG
46962 INFO: Building because C:\PythonProjects\executable_001\exec_001.py changed
46962 INFO: Building PKG (CArchive) exec_001.pkg
52220 INFO: Building PKG (CArchive) exec_001.pkg completed successfully.
52222 INFO: Bootloader C:\Python312\Lib\site-packages\PyInstaller\bootloader\Windows-64bit-intel\run.exe
52222 INFO: checking EXE
52225 INFO: Building EXE because EXE-00.toc is non existent
52225 INFO: Building EXE from EXE-00.toc
52251 INFO: Copying bootloader EXE to C:\PythonProjects\executable_001\dist\exec_001.exe
52334 INFO: Copying icon to EXE
52383 INFO: Copying 0 resources to EXE
52383 INFO: Embedding manifest in EXE
52416 INFO: Appending PKG archive to EXE
52457 INFO: Fixing EXE headers
52738 INFO: Building EXE from EXE-00.toc completed successfully.
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
module,
modules,
news,
packages,
pyinstaller,
python,
python 3,
python modules,
python packages,
tutorial,
tutorials
Saturday, March 9, 2024
News : All Books Bundle from Michael Driscoll
For $60 you can buy a lot of all the card decks from Michael Driscoll.
- Get a copy of all my self-published Python eBooks :
- Python 101 - 2nd Edition
- Python 201: Intermediate Python
- ReportLab: PDF Processing with Python
- Jupyter Notebook 101
- Creating GUI Applications with Python
- Pillow: Image Processing with Python
- Automating Excel with Python
- The Python Quiz Book
News : Website for Python users.
Here is a site called clcoding.com for those who use the python language with many simple examples and even a test fairy: python coding challenge day.
Thursday, March 7, 2024
Python 3.12.1 : flaskcode - an web based code editor.
This is an web based code editor on python flask framework.
Let's install with pip tool:
pip install flaskcode
Collecting flaskcode
Downloading flaskcode-0.0.8.tar.gz (14.5 MB)
...
Installing collected packages: flaskcode
Successfully installed flaskcode-0.0.8
The flaskcode can be integrated in to your own Flask app by configuring and registering flaskcode.blueprint with your app:
from flask import Flask
import flaskcode
app = Flask(__name__)
app.config.from_object(flaskcode.default_config)
app.config['FLASKCODE_RESOURCE_BASEPATH'] = '/path/to/resource/folder'
app.register_blueprint(flaskcode.blueprint, url_prefix='/flaskcode')
@app.route('/')
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run()
You can run easy this online tool on web browser with this command:
flaskcode
FlaskCode CLI: C:\PythonProjects
* Serving Flask app 'flaskcode.cli'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5001
Press CTRL+C to quit
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
flaskcode,
module,
modules,
news,
packages,
python,
python 3,
python modules,
python packages,
tutorial,
tutorials
Tuesday, March 5, 2024
Python 3.12.1 : Bandit tool for security issues in Python code.
Bandit is a tool designed to find common security issues in Python code. To do this Bandit processes each file, builds an AST from it, and runs appropriate plugins against the AST nodes. Once Bandit has finished scanning all the files it generates a report.
Bandit was originally developed within the OpenStack Security Project and later rehomed to PyCQA
Installation is simple with the pip tool:.
pip install bandit
Collecting bandit
Downloading bandit-1.7.7-py3-none-any.whl.metadata (5.9 kB)
...
Installing collected packages: PyYAML, pygments, pbr, mdurl, stevedore, markdown-it-py, rich, bandit
Successfully installed PyYAML-6.0.1 bandit-1.7.7 markdown-it-py-3.0.0 mdurl-0.1.2 pbr-6.0.0 pygments-2.17.2
rich-13.7.1 stevedore-5.2.0
You can see all features with this command:
bandit -h
I test on the script from the last tutorial with pypdf python module and the result is great:
bandit test_001.py
[main] INFO profile include tests: None
[main] INFO profile exclude tests: None
[main] INFO cli include tests: None
[main] INFO cli exclude tests: None
[main] INFO running on Python 3.12.1
Run started:2024-03-05 19:53:56.858212
Test results:
No issues identified.
Code scanned:
Total lines of code: 24
Total lines skipped (#nosec): 0
Run metrics:
Total issues (by severity):
Undefined: 0
Low: 0
Medium: 0
High: 0
Total issues (by confidence):
Undefined: 0
Low: 0
Medium: 0
High: 0
Files skipped (0):
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
bandit,
module,
modules,
news,
packages,
python,
python 3,
python modules,
python packages,
tutorial,
tutorials
Monday, March 4, 2024
Python 3.12.1 : Testing pypdf - version 4.1.0 .
I tried to find a solution for processing PDF files.
The newer Python package called "unstructured" I tested was a disaster and a waste of time and resources.
Today I will show you tests with the Python package called pypdf with version: 4.1.0.
You can find it on the official page.
Installation is simple with the pip tool and you can also add options offered by crypto.
pip install pypdf[crypto]
Collecting pypdf[crypto]
Downloading pypdf-4.1.0-py3-none-any.whl.metadata (7.4 kB)
...
Installing collected packages: pypdf
Successfully installed pypdf-4.1.0
Here is some information displayed with the show option.
python -m pip show pypdf
Name: pypdf
Version: 4.1.0
Summary: A pure-python PDF library capable of splitting, merging, cropping, and transforming PDF files
Home-page:
Author:
Author-email: Mathieu Fenniak <biziqe@mathieu.fenniak.net>
License:
Location: C:\Python312\Lib\site-packages
Requires:
Required-by:
I create a little script for testing:
import os
from pypdf import PdfReader
from pypdf import PdfWriter
#PdfMerger is deprecated and will be removed in pypdf 5.0.0. Use PdfWriter instead.
#from pypdf import PdfMerger
pdf_file = PdfReader("invoice-001.pdf")
print("Size in pages : ",len(pdf_file.pages))
print("========")
page = pdf_file .pages[0]
print("Page : ", page)
print("========")
text = page.extract_text()
print("Page text : ", text)
print("========")
print("PDF Metadata : ", pdf_file.metadata)
print("PDF Metadata - Title: ", pdf_file.metadata.title)
print("========")
pdf_writer = PdfWriter("invoice-002.pdf")
page = pdf_writer.add_blank_page(width=8.27 * 72, height=11.7 * 72)
pdf_writer.write("invoice-002.pdf")
from pypdf import PdfWriter
merger = PdfWriter()
for pdf in ["invoice-001.pdf", "invoice-002.pdf"]:
merger.append(pdf)
merger.write("invoice-003.pdf")
merger.close()
The result is this:
python test_001.py
Size in pages : 1
========
Page : {'/Type': '/Page', '/Resources': {'/ProcSet': ['/PDF', '/Text', '/ImageB', '/ImageC', '/ImageI'], '/ExtGState':
{'/G3': IndirectObject(3, 0, 2484091272080)}, '/XObject': {'/X4': IndirectObject(4, 0, 2484091272080)}, '/Font': {'/F7':
IndirectObject(7, 0, 2484091272080), '/F8': IndirectObject(8, 0, 2484091272080)}}, '/MediaBox': [0, 0, 612, 792],
'/Contents': IndirectObject(9, 0, 2484091272080), '/StructParents': 0, '/Parent': IndirectObject(10, 0, 2484091272080)}
========
Page text : Dino Store
227 Cobblestone Road
30000 Bedrock, Cobblestone County
+555 7 789-1234
https://dinostore.bed | hello@dinostore.bedPayment details:
ACC:123006705
IBAN:US100000060345
SWIFT:BOA447
Bill to:
Slate Rock and Gravel Company
222 Rocky Way
30000 Bedrock, Cobblestone County
+555 7 123-5555
fred@slaterockgravel.bedInvoice No. 1
Invoice Date: 03.03.2024
Issue Date: 03.03.2024
Due Date: 02.04.2024
INVOICE
Item Quantity Price Discount Tax Linetotal
1 Test 001 1 50,00 € 1% 19% 49,50 €
2 Test 002 2 40,00 € 2% 19% 78,40 €
3 Frozen Brontosaurus Ribs 1 100,00 € 0% 19% 100,00 €
Subtotal: 227,90 €
Tax 19%: 43,30 €
Total: 271,20 €
Terms & Notes
Fred, thank you very much. We really appreciate your business.
Please send payments before the due date.
========
PDF Metadata : {'/Creator': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0', '/Producer': 'Skia/PDF m122', '/CreationDate':
"D:20240304221509+00'00'", '/ModDate': "D:20240304221509+00'00'"}
PDF Metadata - Title: None
========
The run of the script will create a second blend PDF named invoice-002 then will merge with the first one will result a PDF named : invoice-003.pdf .
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
crypto,
module,
modules,
news,
packages,
pypdf,
python,
python 3,
python modules,
python packages,
tutorial,
tutorials
Saturday, February 24, 2024
Python 3.12.1 : pipx tool .
The pip is a general-purpose package installer for both libraries and apps with no environment isolation. pipx is made specifically for application installation, as it adds isolation yet still makes the apps available in your shell: pipx creates an isolated environment for each application and its associated packages.
Install the pipx tool :
python -m pip install --user pipx
Collecting pipx
Downloading pipx-1.4.3-py3-none-any.whl.metadata (17 kB)
...
Upgrade the pipx tool:
python -m pip install --user --upgrade pipx
Using pipx to install an application by running :
python -m pipx install pyos
⡿ installing pyos installed package pyos 0.8.0, installed using Python 3.12.1
These apps are now globally available
- psh.exe
- pyos.exe
done! ✨ 🌟 ✨
Show the Python packages on the environment:
python -m pipx list
venvs are in C:\Users\catafest\AppData\Local\pipx\pipx\venvs
apps are exposed on your $PATH at C:\Users\catafest\.local\bin
manual pages are exposed at C:\Users\catafest\.local\share\man
package pyos 0.8.0, installed using Python 3.12.1
- psh.exe
- pyos.exe
If an application installed by pipx requires additional packages, you can add them with pipx inject, and this can be seen with the list argument.
python -m pipx inject pyos matplotlib
injected package matplotlib into venv pyos
done! ✨ 🌟 ✨
...
python -m pipx list
venvs are in C:\Users\catafest\AppData\Local\pipx\pipx\venvs
apps are exposed on your $PATH at C:\Users\catafest\.local\bin
manual pages are exposed at C:\Users\catafest\.local\share\man
package pyos 0.8.0, installed using Python 3.12.1
- psh.exe
- pyos.exe
...
python -m pipx list --include-injected
venvs are in C:\Users\catafest\AppData\Local\pipx\pipx\venvs
apps are exposed on your $PATH at C:\Users\catafest\.local\bin
manual pages are exposed at C:\Users\catafest\.local\share\man
package pyos 0.8.0, installed using Python 3.12.1
- psh.exe
- pyos.exe
Injected Packages:
- matplotlib 3.8.3
- test-py 0.3
This adds the matplotlib package to pyosenvironment.
If I try to inject into another environment name, then I will get an error:
python -m pipx inject catafest matplotlib
Can't inject 'matplotlib' into nonexistent Virtual Environment 'catafest'. Be sure to install the package first
with 'pipx install catafest' before injecting into it.
Create a Python file named test.py with this source code:
# test.py
# Requirements:
# requests
#
# The list of requirements is terminated by a blank line or an empty comment line.
import sys
import requests
project = sys.argv[1]
pipx_data = requests.get(f"https://pypi.org/pypi/{project}/json").json()
print(pipx_data["info"]["version"])
You can run it with:
python -m pipx run test.py pipx
1.4.3
I don't know how advanced the environment is built and I tested some simple scenarios but I found some inconsistencies in the scripts created by the user that can be run other than with a simple run and on several environments in the same folder. Theoretically, there should be such functionality.
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
matplotlib,
module,
modules,
news,
packages,
pipx,
python,
python 3,
python modules,
python packages,
tutorial,
tutorials
Saturday, February 17, 2024
Python 3.10.12 : Few example for CUDA and NVCC - part 044.
NVCC use CUDA C/C++ source code and allows developers to write high-performance GPU-accelerated applications by leveraging the power of NVIDIA GPUs for parallel processing tasks.
Today I test some simple examples with this tool on Google Colab using the nvcc4jupyter python package.
You need to install it with the pip and know how to use the CUDA C/C++ source code, or use the basic example from documentation.
pip install nvcc4jupyter
I change some source code because is need to install this library and I don't have time to learn and test.
But this will allow me to test better, because on my desktop I don't have a good hardware.
This is the source I change and I cut the source code linked on error_handling.h.
This is the changed source code , you can see more on my GitHub repo for Google Colab ! !
#include
//#include "error_handling.h"
const int DSIZE = 4096;
const int block_size = 256;
// vector add kernel: C = A + B
__global__ void vadd(const float *A, const float *B, float *C, int ds){
int idx = threadIdx.x + blockIdx.x * blockDim.x;
if (idx < ds) {
C[idx] = A[idx] + B[idx];
}
}
int main(){
float *h_A, *h_B, *h_C, *d_A, *d_B, *d_C;
// allocate space for vectors in host memory
h_A = new float[DSIZE];
h_B = new float[DSIZE];
h_C = new float[DSIZE];
// initialize vectors in host memory to random values (except for the
// result vector whose values do not matter as they will be overwritten)
for (int i = 0; i < DSIZE; i++) {
h_A[i] = rand()/(float)RAND_MAX;
h_B[i] = rand()/(float)RAND_MAX;
}
// allocate space for vectors in device memory
cudaMalloc(&d_A, DSIZE*sizeof(float));
cudaMalloc(&d_B, DSIZE*sizeof(float));
cudaMalloc(&d_C, DSIZE*sizeof(float));
//cudaCheckErrors("cudaMalloc failure"); // error checking
// copy vectors A and B from host to device:
cudaMemcpy(d_A, h_A, DSIZE*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, h_B, DSIZE*sizeof(float), cudaMemcpyHostToDevice);
//cudaCheckErrors("cudaMemcpy H2D failure");
// launch the vector adding kernel
vadd<<<(DSIZE+block_size-1)/block_size, block_size>>>(d_A, d_B, d_C, DSIZE);
//cudaCheckErrors("kernel launch failure");
// wait for the kernel to finish execution
cudaDeviceSynchronize();
//cudaCheckErrors("kernel execution failure");
cudaMemcpy(h_C, d_C, DSIZE*sizeof(float), cudaMemcpyDeviceToHost);
//cudaCheckErrors("cudaMemcpy D2H failure");
printf("A[0] = %f\n", h_A[0]);
printf("B[0] = %f\n", h_B[0]);
printf("C[0] = %f\n", h_C[0]);
return 0;
}
This is result ...
A[0] = 0.840188
B[0] = 0.394383
C[0] = 0.000000
Posted by
Cătălin George Feștilă
Labels:
2024,
2024 news,
Colab,
cuda,
module,
modules,
news,
nvcc,
nvcc4jupyter,
nvidia-smi,
packages,
python,
python 3,
python modules,
python packages,
runtime,
tutorial,
tutorials
Tuesday, January 16, 2024
News : How to use ShellExecuteA with Python programming language.
I just discovery this option to use ShellExecuteA in Python.
Let's see some example:
import ctypes
import sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if not is_admin():
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
... and another example:
import sys
import ctypes
#fix unicode access
import sys
if sys.version_info[0] >= 3:
unicode = str
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print('Command line: ', executable, argument_line)
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print ('I have admin privilege.')
input('Press ENTER to exit.')
elif ret is None:
print('I am elevating to admin privilege.')
input('Press ENTER to exit.')
else:
print('Error(ret=%d): cannot elevate privilege.' % (ret, ))
Thursday, January 11, 2024
News : NVIDIA Kaolin library provides a PyTorch API.
NVIDIA Kaolin library provides a PyTorch API for working with a variety of 3D representations and includes a growing collection of GPU-optimized operations such as modular differentiable rendering, fast conversions between representations, data loading, 3D checkpoints, differentiable camera API, differentiable lighting with spherical harmonics and spherical gaussians, powerful quadtree acceleration structure called Structured Point Clouds, interactive 3D visualizer for jupyter notebooks, convenient batched mesh container and more ... from GitHub repo - kaolin.
See this example from NVIDIA:
NVIDIA Kaolin library has introduced the SurfaceMesh class to make it easier to track attributes such as faces, vertices, normals, face_normals, and others associated with surface meshes.
Friday, January 5, 2024
Python 3.12.1 : How to read all CLSID with winreg.
The winreg python module can be found default into python instalation.
This is the source code I used to list all of CLSID:
import winreg
# Open the CLSID key under HKEY_CLASSES_ROOT
clsid_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID")
# Iterate through all the subkeys
for i in range(winreg.QueryInfoKey(clsid_key)[0]):
# Get the name of the subkey
subkey_name = winreg.EnumKey(clsid_key, i)
# Open the subkey
subkey = winreg.OpenKey(clsid_key, subkey_name, 0, winreg.KEY_READ)
try:
# Read the default value of the subkey
value, type = winreg.QueryValueEx(subkey, "")
# Print the subkey name and the value
print(subkey_name, value)
except:
# Skip the subkeys that cannot be read
pass
# Close the subkey
winreg.CloseKey(subkey)
# Close the CLSID key
winreg.CloseKey(clsid_key)
... and this source code comes with an text file output:
import winreg
# Open the CLSID key under HKEY_CLASSES_ROOT
clsid_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID")
# Open the file for writing
with open("clsid_info.txt", "w") as f:
# Iterate through all the subkeys
for i in range(winreg.QueryInfoKey(clsid_key)[0]):
# Get the name of the subkey
subkey_name = winreg.EnumKey(clsid_key, i)
# Open the subkey
subkey = winreg.OpenKey(clsid_key, subkey_name, 0, winreg.KEY_READ)
try:
# Read the default value of the subkey
value, type = winreg.QueryValueEx(subkey, "")
# Write the subkey name and the value to the file
f.write(subkey_name + " " + value + "\n")
except:
# Skip the subkeys that cannot be read
pass
# Close the subkey
winreg.CloseKey(subkey)
# Close the CLSID key
winreg.CloseKey(clsid_key)
Subscribe to:
Posts (Atom)