analitics

Pages

Tuesday, December 23, 2025

Python Qt6 : testing local web server with PyQt versus Ollama.

This Python program creates a PyQt6 GUI that measures latency for a given URL.
It runs a background thread that repeatedly sends HTTP requests and calculates two values:
The results are sent back to the GUI using Qt signals and displayed live without freezing the interface.
  • HTTP latency (time for the request to complete)
  • Thread latency (total duration of one worker cycle)
See the result in this screenshot:

Wednesday, December 17, 2025

Python Qt6 : Run Visual Studio Code directly from RAM using ImDisk and python.

I built a small tool using Python + PyQt6 that lets me run Visual Studio Code directly from a RAM Disk for maximum speed and minimal SSD wear.
The setup uses ImDisk Toolkit to automatically create a 6 GB RAM Disk (drive O:).
The tool then copies VS Code into RAM and launches it instantly through a simple graphical interface with three buttons:
  • Create RAM Disk
  • Copy VS Code to RAM
  • Launch VS Code from RAM
This method provides much faster startup times and a smoother workflow, making it a great performance boost for Windows users.

News : Reporting a security issue - good practice.

This is how the python solve a security issue:
We take security very seriously and ask that you follow our security policy carefully.
If you've identified a security issue with a project hosted on PyPI.
Login to your PyPI account, then visit the project's page on PyPI. At the bottom of the sidebar, click Report project as malware. Supply the following details in the form:
  • A URL to the project in question
  • An explanation of what makes the project a security issue
  • A link to the problematic lines in the project's distributions via inspector.pypi.io
Important! If you believe you've identified a security issue with PyPI, DO NOT report the issue in any public forum, including (but not limited to):
  • Our GitHub issue tracker
  • Official or unofficial chat channels
  • Official or unofficial mailing lists

Monday, December 15, 2025

Python Qt6 : ... tool for testing fonts.

Today I created a small Python script with PyQt6 using artificial intelligence. It is a tool that takes a folder of fonts, allows to select their size, displays the font size in pixels for Label text from the Godot engine and downloads only the selection of fonts that I like. I have not tested it to see the calculations with Godot, but it seems functional...

Saturday, December 13, 2025

Python Qt6 : ... search custom data in files with python and PyQt6.

The other day I noticed that I can't find what I worked on in the past, some files were blocked... Another task was blocking the artificial intelligence due to the number of uses. I could have used artificial intelligence to open old projects and ask where what I worked on is, but it would be a risk to waste my queries. Since I always use a specific signature when working on separate projects and the backup is distributed on storage that is always filling up, I created a simple script that would search for my custom with custom files, custom content and output a spreader with them. Here is the result of a 310-line source code script, obviously created with artificial intelligence.

Wednesday, December 10, 2025

Python 3.13.0 : ... simple script for copilot history.

NOTES: I have been using artificial intelligence since it appeared, it is obviously faster and more accurate, I recommend using testing on larger projects.
This python script will take the database and use to get copilot history and save to file copilot_conversations.txt :
import os
import sqlite3
import datetime
import requests
from bs4 import BeautifulSoup
import shutil

# Locația tipică pentru istoricul Edge (Windows)
edge_history_path = os.path.expanduser(
    r"~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\History"
)

# Copiem fișierul History în folderul curent
def copy_history_file(src_path, dst_name="edge_history_copy.db"):
    if not os.path.exists(src_path):
        print("Nu am găsit istoricul Edge.")
        return None
    dst_path = os.path.join(os.getcwd(), dst_name)
    try:
        shutil.copy(src_path, dst_path)
        print(f"Am copiat baza de date în {dst_path}")
        return dst_path
    except Exception as e:
        print(f"Eroare la copiere: {e}")
        return None

def extract_copilot_links(db_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    cursor.execute("""
        SELECT url, title, last_visit_time
        FROM urls
        WHERE url LIKE '%copilot%'
    """)

    results = []
    for url, title, last_visit_time in cursor.fetchall():
        ts = datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=last_visit_time)
        results.append({
            "url": url,
            "title": title,
            "last_visit": ts.strftime("%Y-%m-%d %H:%M:%S")
        })

    conn.close()
    return results

def fetch_conversation(url):
    try:
        resp = requests.get(url)
        if resp.status_code == 200:
            soup = BeautifulSoup(resp.text, "html.parser")
            texts = soup.get_text(separator="\n", strip=True)
            return texts
        else:
            return f"Eroare acces {url}: {resp.status_code}"
    except Exception as e:
        return f"Eroare acces {url}: {e}"

if __name__ == "__main__":
    copy_path = copy_history_file(edge_history_path)
    if copy_path:
        chats = extract_copilot_links(copy_path)
        if chats:
            with open("copilot_conversations.txt", "w", encoding="utf-8") as f:
                for chat in chats:
                    content = fetch_conversation(chat["url"])
                    f.write(f"=== Conversație: {chat['title']} ({chat['last_visit']}) ===\n")
                    f.write(content)
                    f.write("\n\n")
            print("Am salvat conversațiile în copilot_conversations.txt")
        else:
            print("Nu am găsit conversații Copilot în istoricul Edge.")

Saturday, December 6, 2025

News : Python 3.14.1 and Python 3.13.10 are now available!

... these are good news from 2 december 2025:
Python 3.14.1 is the first maintenance release of 3.14, containing around 558 bugfixes, build improvements and documentation changes since 3.14.0.
Python 3.13.10 is the tenth maintenance release of 3.13, containing around 300 bugfixes, build improvements and documentation changes since 3.13.9.
Read more on the official blogger.

Friday, December 5, 2025

Python Qt6 : ... data generator tool for a custom format file.

Today I finished a data generator tool for a custom format for a game. The idea is that PyQt6 is versatile and very useful for a developer. This tool generates data in the 2D area of a screen and saves them in a defined format, in this case a position and a size for a text ...
Here is the class for custom range selection sliders.
class RangeSlider(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._min, self._max = 0, 1000
        self._start, self._end = 0, 1000
        self._dragging = None
        self.setMinimumHeight(24)

    def setRange(self, minimum, maximum):
        self._min, self._max = minimum, maximum
        self._start, self._end = minimum, maximum
        self.update()

    def setStart(self, val):
        self._start = max(self._min, min(val, self._end))
        self.update()

    def setEnd(self, val):
        self._end = min(self._max, max(val, self._start))
        self.update()

    def start(self): return self._start
    def end(self): return self._end

    def _pos_to_val(self, x):
        w = self.width()
        ratio = max(0, min(x, w)) / w if w else 0
        return int(self._min + ratio*(self._max-self._min))

    def _val_to_pos(self, val):
        w = self.width()
        return int((val-self._min)/(self._max-self._min)*w) if self._max>self._min else 0

    def mousePressEvent(self, e):
        x = e.position().x()
        sx, ex = self._val_to_pos(self._start), self._val_to_pos(self._end)
        self._dragging = "start" if abs(x-sx)<abs(x-ex) else "end"
        self.mouseMoveEvent(e)

    def mouseMoveEvent(self, e):
        if self._dragging:
            val = self._pos_to_val(int(e.position().x()))
            if self._dragging=="start": self.setStart(val)
            else: self.setEnd(val)

    def mouseReleaseEvent(self,e): self._dragging=None

    def paintEvent(self,e):
        p=QPainter(self); rect=self.rect()
        sx,ex=self._val_to_pos(self._start),self._val_to_pos(self._end)
        p.fillRect(rect,QColor(220,220,220))
        p.fillRect(QRect(QPoint(sx,0),QPoint(ex,rect.height())),QColor(100,200,100,120))
        p.setBrush(QColor(50,120,200)); p.setPen(Qt.PenStyle.NoPen)
        p.drawEllipse(QPoint(sx,rect.center().y()),6,6)
        p.drawEllipse(QPoint(ex,rect.center().y()),6,6)

Thursday, December 4, 2025

News : the pythononline online tool for python users.

Wednesday, December 3, 2025

Python 3.13.0 : ... playwright - part 001.

Playwright for Python is a modern automation library that allows developers to control browsers like Chromium, Firefox, and WebKit. It is widely used for testing, scraping, and simulating real user interactions.
The package provides an asynchronous API, enabling fast and reliable automation. Developers can launch browsers, navigate to pages, fill forms, click buttons, and capture results with minimal code.
In practice, Playwright is useful for tasks such as automated testing, repetitive searches, data collection, and simulating human-like browsing behavior across multiple browsers.
The example script demonstrates how to open Firefox, navigate to Google, perform a series of searches, scroll the page, and pause between actions to mimic natural user activity.
Additionally, the script saves each search query into a text file, creating a simple log of performed searches. This shows how Playwright can combine browser automation with file handling for practical workflows.
I used the pip tool then I install the playwright:
pip install playwright
playwright install
Let's see the script:
import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.firefox.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()

        await page.goto("https://www.google.com")

        queries = [
            "python automation",
            "playwright tutorial",
            "google search automation"
        ]

        with open("results.txt", "w", encoding="utf-8") as f:
            for q in queries:
                # Fill search box
                await page.fill("textarea[name='q']", q)
                await page.press("textarea[name='q']", "Enter")
                await page.wait_for_load_state("domcontentloaded")

                # Scroll + pause
                await page.evaluate("window.scrollBy(0, document.body.scrollHeight)")
                await page.wait_for_timeout(3000)

                # Extract search results (titles + links)
                results = await page.query_selector_all("h3")
                f.write(f"\nResults for: {q}\n")
                for r in results[:5]:  # primele 5 rezultate
                    title = await r.inner_text()
                    link_el = await r.evaluate_handle("node => node.parentElement")
                    link = await link_el.get_attribute("href")
                    f.write(f"- {title} ({link})\n")

                print(f"Saved results for: {q}")

        await browser.close()

asyncio.run(main())
Then I run with this command:
python google_search_test_001.py
Saved results for: python automation
Saved results for: playwright tutorial
Saved results for: google search automation
Need to click to accept on browser ... , and some basic result on results.txt file:

Results for: python automation

Results for: playwright tutorial
- Playwright: Fast and reliable end-to-end testing for modern ... 

Sunday, November 30, 2025

News : the xonsh shell language and command prompt.

Xonsh is a modern, full-featured and cross-platform python shell. The language is a superset of Python 3.6+ with additional shell primitives that you are used to from Bash and IPython. It works on all major systems including Linux, OSX, and Windows. Xonsh is meant for the daily use of experts and novices.
The install is easy with pip tool:
python -m pip install 'xonsh[full]'

Python 3.13.0 : mitmproxy - part 001.

Mitmproxy is an interactive, open‑source proxy tool that lets you intercept, inspect, and modify HTTP and HTTPS traffic in real time. It acts as a "man‑in‑the‑middle" between your computer and the internet, making it possible to debug, test, or analyze how applications communicate online.
Why Python?
  • Mitmproxy is built in Python and exposes a powerful addon API
  • You can write custom scripts to automate tasks and traffic manipulation
  • Block or rewrite requests and responses with flexible logic
  • Inject headers or simulate server responses for testing
  • Integrate with other Python tools for advanced automation
  • Intercept and inspect HTTP and HTTPS traffic in real time
  • Modify requests and responses dynamically with Python scripts
  • Block specific hosts or URLs to prevent unwanted connections
  • Inject custom headers into outgoing requests for debugging or control
  • Rewrite response bodies (HTML, JSON, text) using regex or custom logic
  • Log and save traffic flows for later analysis and replay
  • Simulate server responses to test client behavior offline
  • Automate testing of web applications and APIs with scripted rules
  • Monitor performance metrics such as latency and payload size
  • Integrate with other Python tools for advanced automation and analysis
  • Use a trusted root certificate to decrypt and modify HTTPS traffic securely
Let's install:
pip install mitmproxy
Let's see the python script:
# addon.py
from mitmproxy import http
from mitmproxy import ctx
import re

BLOCKED_HOSTS = {
    "hyte.com",
    "ads.example.org",
}

REWRITE_RULES = [
    # Each rule: (pattern, replacement, content_type_substring)
    (re.compile(rb"Hello World"), b"Salut lume", "text/html"),
    (re.compile(rb"tracking", re.IGNORECASE), b"observare", "text"),
]

ADD_HEADERS = {
    "X-Debug-Proxy": "mitm",
    "X-George-Tool": "true",
}

class GeorgeProxy:
    def __init__(self):
        self.rewrite_count = 0

    def load(self, loader):
        ctx.log.info("GeorgeProxy addon loaded.")

    def request(self, flow: http.HTTPFlow):
        # Block specific hosts early
        host = flow.request.host
        if host in BLOCKED_HOSTS:
            flow.response = http.Response.make(
                403,
                b"Blocked by GeorgeProxy",
                {"Content-Type": "text/plain"}
            )
            ctx.log.warn(f"Blocked request to {host}")
            return

        # Add custom headers to outgoing requests
        for k, v in ADD_HEADERS.items():
            flow.request.headers[k] = v

        ctx.log.info(f"REQ {flow.request.method} {flow.request.url}")

    def response(self, flow: http.HTTPFlow):
        # Only process text-like contents
        ctype = flow.response.headers.get("Content-Type", "").lower()
        raw = flow.response.raw_content

        if raw and any(t in ctype for t in ["text", "html", "json"]):
            new_content = raw
            for pattern, repl, t in REWRITE_RULES:
                if t in ctype:
                    new_content, n = pattern.subn(repl, new_content)
                    self.rewrite_count += n

            if new_content != raw:
                flow.response.raw_content = new_content
                # Update Content-Length only if present
                if "Content-Length" in flow.response.headers:
                    flow.response.headers["Content-Length"] = str(len(new_content))
                ctx.log.info(f"Rewrote content ({ctype}); total matches: {self.rewrite_count}")

        ctx.log.info(f"RESP {flow.response.status_code} {flow.request.url}")

addons = [GeorgeProxy()]
Let's run it:
mitmdump -s addon.py
[21:46:04.435] Loading script addon.py
[21:46:04.504] GeorgeProxy addon loaded.
[21:46:04.506] HTTP(S) proxy listening at *:8080.
[21:46:18.547][127.0.0.1:52128] client connect
[21:46:18.593] REQ GET http://httpbin.org/get
[21:46:18.768][127.0.0.1:52128] server connect httpbin.org:80 (52.44.182.178:80)
[21:46:18.910] RESP 200 http://httpbin.org/get
127.0.0.1:52128: GET http://httpbin.org/get
              << 200 OK 353b
[21:46:19.019][127.0.0.1:52128] client disconnect
[21:46:19.021][127.0.0.1:52128] server disconnect httpbin.org:80 (52.44.182.178:80)
Let's see the result:
curl -x http://127.0.0.1:8080 http://httpbin.org/get
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "Proxy-Connection": "Keep-Alive",
    "User-Agent": "curl/8.13.0",
    "X-Amzn-Trace-Id": "Root=1-692c9f0b-7eaf43e61f276ee62b089933",
    "X-Debug-Proxy": "mitm",
    "X-George-Tool": "true"
  },
  "origin": "84.117.220.94",
  "url": "http://httpbin.org/get"
}
This means
The request successfully went through mitmproxy running on 127.0.0.1:8080. Your addon worked: it injected the custom headers (X-Debug-Proxy, X-George-Tool). The httpbin.org echoed back the request details, showing exactly what the server received.

Python 3.13.0 : Tornado - part 001.

Python Tornado is a high‑performance web framework and asynchronous networking library designed for extreme scalability and real‑time applications. Its standout capability is handling tens of thousands of simultaneous connections efficiently, thanks to non‑blocking I/O.
This is an open source project actively maintained and available on tornadoweb.org.

Python Tornado – Key Capabilities

  • Massive Concurrency: Tornado can scale to tens of thousands of open connections without requiring huge numbers of threads.
  • Non‑blocking I/O: Its asynchronous design makes it ideal for apps that need to stay responsive under heavy load.
  • WebSockets Support: Built‑in support for WebSockets enables real‑time communication between clients and servers.
  • Long‑lived Connections: Perfect for long polling, streaming, or chat applications where connections remain open for extended periods.
  • Coroutines & Async/Await: Tornado integrates tightly with Python’s asyncio, allowing developers to write clean asynchronous code using coroutines.
  • Versatile Use Cases: Beyond web apps, Tornado can act as an HTTP client/server, handle background tasks, or integrate with other services.
Tornado setup: The script creates a web server using the Tornado framework, listening on port 8888.
Route definition: A single route /form is registered, handled by the FormHandler class.
GET request: When you visit http://localhost:8888/form, the server responds with an HTML page (form.html) that contains a simple input form.
POST request: When the form is submitted, the post() method retrieves the value of the name field using self.get_argument("name").
Response: The server then sends back a personalized message
Let's see the script:
import tornado.ioloop
import tornado.web
import os

class FormHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("form.html")  # Render an HTML form

    def post(self):
        name = self.get_argument("name")
        self.write(f"Hello, {name}!")

def make_app():
    return tornado.web.Application([
        (r"/form", FormHandler),
    ],
    template_path=os.path.join(os.path.dirname(__file__), "templates")  # <-- aici
    )

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    print("Server pornit pe http://localhost:8888/form")
    tornado.ioloop.IOLoop.current().start()