instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add docstrings to improve collaboration | from __future__ import annotations
import json
from datetime import datetime, timezone
from typing import Any, Dict, Optional
from db import Database
class SentinelGovernance:
def __init__(self, db: Optional[Database] = None):
self.db = db or Database()
self.db.init()
def log_action(self, ... | --- +++ @@ -1,3 +1,9 @@+"""
+Auto-governanca do Sentinel.
+
+Registra todas as acoes do sentinel em audit log proprio.
+Padrao leve — sem rate limiting (operacoes locais apenas).
+"""
from __future__ import annotations
import json
@@ -8,12 +14,14 @@
class SentinelGovernance:
+ """Registra acoes do sentinel p... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/skill-sentinel/scripts/governance.py |
Write documentation strings for class attributes | from __future__ import annotations
from typing import Any, Dict, List, Set
from config import CAPABILITY_TAXONOMY
def _map_capabilities(skills: List[Dict[str, Any]]) -> Dict[str, Set[str]]:
capability_keywords = {
"data-extraction": ["scraper", "extract", "crawl", "parse", "scraping"],
"socia... | --- +++ @@ -1,3 +1,9 @@+"""
+Recommender: gap analysis e sugestao de novas skills.
+
+Analisa as capacidades existentes, identifica lacunas no ecossistema
+e gera templates de SKILL.md para skills sugeridas.
+"""
from __future__ import annotations
from typing import Any, Dict, List, Set
@@ -6,6 +12,7 @@
def _ma... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/skill-sentinel/scripts/recommender.py |
Write docstrings for algorithm functions | from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
# ── Paths ────────────────────────────────────────────────────────────────────
ROOT_DIR = Path(__file__).resolve().parent.parent
SCRIPTS_DIR = ROOT_DIR / "scripts"
DATA_DIR = ROOT_DIR / "data"
OUTPUT_DIR ... | --- +++ @@ -1,3 +1,8 @@+"""
+Configuracao central da skill Stability AI.
+
+Gerencia: API keys, modelos, formatos, aspect ratios, limites de seguranca.
+"""
from __future__ import annotations
import json
@@ -134,6 +139,7 @@
def _parse_env_file(env_path: Path) -> dict[str, str]:
+ """Parse arquivo .env e reto... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/stability-ai/scripts/config.py |
Add structured docstrings to improve clarity | from __future__ import annotations
STYLES = {
"photorealistic": {
"name": "Fotorrealismo",
"suffix": (
"photorealistic, hyperrealistic, 8k uhd, high resolution, "
"sharp focus, professional photography, natural lighting, "
"film grain, bokeh, shot on Canon EOS R5... | --- +++ @@ -1,3 +1,9 @@+"""
+Presets de estilo para Stability AI.
+
+Cada estilo adiciona qualificadores ao prompt do usuario para direcionar
+o modelo na direcao visual desejada. Use --style <nome> no CLI.
+"""
from __future__ import annotations
STYLES = {
@@ -141,14 +147,22 @@
def get_style(name: str) -> dict... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/stability-ai/scripts/styles.py |
Create docstrings for API functions | #!/usr/bin/env python3
import argparse
import os
import shutil
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SKILL_DIR = os.path.dirname(SCRIPT_DIR)
BOILERPLATE_DIR = os.path.join(SKILL_DIR, "assets", "boilerplate")
def setup_nodejs(project_path: str, with_webhook: bool = False, with_ai: bool =... | --- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python3
+"""
+Setup a new Telegram Bot project with boilerplate code.
+
+Usage:
+ python setup_project.py --language nodejs --path ./my-telegram-bot
+ python setup_project.py --language python --path ./my-telegram-bot
+ python setup_project.py --language python --path ./... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/telegram/scripts/setup_project.py |
Add return value explanations in docstrings | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent / "data"
MAX_RESULTS = 3
CSV_CONFIG = {
"style": {
"file": "styles.csv",
... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+UI/UX Pro Max Core - BM25 search engine for UI/UX style guides
+"""
import csv
import re
@@ -94,6 +97,7 @@
# ============ BM25 IMPLEMENTATION ============
class BM25:
+ """BM25 ranking algorithm for text search"""
def __init_... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/ui-ux-pro-max/scripts/core.py |
Please document this code using docstrings | from __future__ import annotations
import json
import sqlite3
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional
from config import DB_PATH
DDL = """
-- Execucoes de auditoria
CREATE TABLE IF NOT EXISTS audit_runs (
id INTEGER PRIMARY KEY AU... | --- +++ @@ -1,3 +1,17 @@+"""
+Camada de persistencia SQLite para a skill Sentinel.
+
+Armazena auditorias, findings, snapshots de skills, recomendacoes
+e historico de scores para analise de tendencias.
+
+Uso:
+ from db import Database
+ db = Database()
+ db.init()
+ run_id = db.create_audit_run()
+ db.... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/skill-sentinel/scripts/db.py |
Add missing documentation to my Python functions | #!/usr/bin/env python3
import os
import logging
import asyncio
from dotenv import load_dotenv
from flask import Flask, request, jsonify
from telegram import Update, Bot
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters
load_dotenv()
logging.basicConfig(
format="%(... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Telegram Bot - Webhook Mode with Flask
+
+Usage:
+ python webhook_server.py
+"""
import os
import logging
@@ -46,6 +52,7 @@
@flask_app.route(f"/webhook/{TOKEN}", methods=["POST"])
def webhook():
+ """Handle incoming Telegram updates."""
# Validate ... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/telegram/assets/boilerplate/python/webhook_server.py |
Create structured documentation for my script | from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
# Garantir que o diretorio scripts esta no path
sys.path.insert(0, str(Path(__file__).parent))
from config import DIMENSION_WEIGHTS, get_score_label
from db import Database
... | --- +++ @@ -1,3 +1,14 @@+"""
+CLI principal do Sentinel: orquestra a auditoria completa do ecossistema.
+
+Uso:
+ python run_audit.py # Auditoria completa
+ python run_audit.py --skill instagram # Auditoria de uma skill
+ python run_audit.py --recommend # Apenas gap analysis
+ ... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/skill-sentinel/scripts/run_audit.py |
Add professional docstrings to my codebase | #!/usr/bin/env python3
import subprocess
import sys
import os
import json
from pathlib import Path
def run_cmd(cmd: str) -> str:
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.stdout + result.stderr
except Exception as e:
return str(e)
def ... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+TypeScript Project Diagnostic Script
+Analyzes TypeScript projects for configuration, performance, and common issues.
+"""
import subprocess
import sys
@@ -7,6 +11,7 @@ from pathlib import Path
def run_cmd(cmd: str) -> str:
+ """Run shell command and return... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/typescript-expert/scripts/ts_diagnostic.py |
Add return value explanations in docstrings | from __future__ import annotations
import ast
import re
from pathlib import Path
from typing import Any, Dict, List, Optional
from config import (
IGNORE_DIRS,
SKILL_MAX_DEPTH,
SKILL_SEARCH_PATHS,
SKILLS_ROOT,
)
def _parse_yaml_frontmatter(content: str) -> Dict[str, str]:
if not content.startswi... | --- +++ @@ -1,3 +1,16 @@+"""
+Scanner de skills: descobre e inventaria todas as skills do ecossistema.
+
+Percorre os diretorios conhecidos procurando SKILL.md com frontmatter YAML,
+e coleta metricas de arquivo para cada skill encontrada.
+
+Uso:
+ from scanner import SkillScanner
+ scanner = SkillScanner()
+ ... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/skill-sentinel/scripts/scanner.py |
Add docstrings for production code | from __future__ import annotations
import argparse
import base64
import io
import json
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
sys.path.insert(0, str(Path(__file__).parent))
from c... | --- +++ @@ -1,3 +1,19 @@+"""
+Script principal de geracao de imagens via Stability AI API.
+
+Suporta: text-to-image (SD3.5, Ultra, Core), img2img, upscale, inpaint,
+remove-background, search-and-replace, erase.
+
+Uso:
+ python generate.py --prompt "a mountain sunset" --mode generate
+ python generate.py --prom... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/stability-ai/scripts/generate.py |
Create documentation strings for testing functions | #!/usr/bin/env python3
import argparse
import json
import os
import sys
from urllib.request import urlopen, Request
from urllib.error import HTTPError
def _mask_token(token: str) -> str:
if not token or len(token) < 12:
return "***masked***"
return f"{token[:8]}...masked"
def api_call(token: str, m... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""
+Send a test message via Telegram Bot API.
+
+Usage:
+ python send_message.py --token "TOKEN" --chat-id "CHAT_ID" --text "Hello!"
+ python send_message.py --chat-id "CHAT_ID" --text "Hello!" # Uses env var
+ python send_message.py --chat-id "CHAT_ID" --phot... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/telegram/scripts/send_message.py |
Document this module using docstrings | #!/usr/bin/env python3
import os
import logging
from dotenv import load_dotenv
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Application, CommandHandler, MessageHandler,
CallbackQueryHandler, filters, ContextTypes
)
load_dotenv()
logging.basicConfig(
fo... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Telegram Bot - Long Polling Mode
+
+Usage:
+ python bot.py
+"""
import os
import logging
@@ -20,6 +26,7 @@ # --- Command Handlers ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
+ """Handle /start command."""
user = update.... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/telegram/assets/boilerplate/python/bot.py |
Create docstrings for each class method | #!/usr/bin/env python3
import os
import sys
import json
import signal
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
import videodb
# Retry config
MAX_RETRIES = 10
INITIAL_BACKOFF = 1 # seconds
MAX_BACKOFF = 60 # seconds
# Parse argu... | --- +++ @@ -1,4 +1,30 @@ #!/usr/bin/env python3
+"""
+WebSocket event listener for VideoDB with auto-reconnect and graceful shutdown.
+
+Usage:
+ python scripts/ws_listener.py [OPTIONS] [output_dir]
+
+Arguments:
+ output_dir Directory for output files (default: /tmp or VIDEODB_EVENTS_DIR env var)
+
+Options:
+ --c... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/videodb/scripts/ws_listener.py |
Create docstrings for API functions |
import os
from typing import Any
import httpx
GRAPH_API = "https://graph.facebook.com/v21.0"
class TemplateManager:
def __init__(
self,
token: str | None = None,
waba_id: str | None = None,
):
self.token = token or os.environ["WHATSAPP_TOKEN"]
self.waba_id = waba_id... | --- +++ @@ -1,3 +1,4 @@+"""WhatsApp Template Management - CRUD operations via API."""
import os
from typing import Any
@@ -8,6 +9,7 @@
class TemplateManager:
+ """Manage WhatsApp message templates programmatically."""
def __init__(
self,
@@ -22,6 +24,7 @@ }
async def list_templ... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/whatsapp-cloud-api/assets/boilerplate/python/template_manager.py |
Add docstrings to existing functions |
import asyncio
from typing import Any
import logging
logger = logging.getLogger(__name__)
class BaseWorker:
def __init__(self, input_queue: asyncio.Queue, output_queue: asyncio.Queue):
self.input_queue = input_queue
self.output_queue = output_queue
self.active = False
self._... | --- +++ @@ -1,3 +1,9 @@+"""
+Template: Base Worker Implementation
+
+Use this template as a starting point for creating new workers
+in your voice AI pipeline.
+"""
import asyncio
from typing import Any
@@ -7,19 +13,45 @@
class BaseWorker:
+ """
+ Base class for all workers in the voice AI pipeline
+
... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/voice-ai-engine-development/templates/base_worker_template.py |
Add detailed docstrings explaining each function |
import asyncio
import os
from dotenv import load_dotenv
from flask import Flask, request, jsonify
from whatsapp_client import WhatsAppClient
from webhook_handler import (
validate_hmac_signature,
verify_webhook,
parse_webhook_payload,
extract_message_content,
)
load_dotenv()
app = Flask(__name__)
... | --- +++ @@ -1,3 +1,4 @@+"""WhatsApp Cloud API - Flask Application with Webhook Handler."""
import asyncio
import os
@@ -26,12 +27,14 @@
@app.route("/webhook", methods=["GET"])
def webhook_verify():
+ """Handle webhook verification (GET challenge from Meta)."""
return verify_webhook()
@app.route("/we... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/whatsapp-cloud-api/assets/boilerplate/python/app.py |
Add docstrings to improve readability | #!/usr/bin/env python3
import subprocess
import json
import os
import sys
import re
import argparse
from pathlib import Path
from typing import Dict, List, Any
from datetime import datetime
# Fix Windows console encoding for Unicode output
try:
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.std... | --- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3
+"""
+Skill: vulnerability-scanner
+Script: security_scan.py
+Purpose: Validate that security principles from SKILL.md are applied correctly
+Usage: python security_scan.py <project_path> [--scan-type all|deps|secrets|patterns|config]
+Output: JSON with validation finding... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/vulnerability-scanner/scripts/security_scan.py |
Write reusable docstrings | #!/usr/bin/env python3
import argparse
import os
import sys
try:
import httpx
except ImportError:
print("Error: httpx not installed. Run: pip install httpx")
sys.exit(1)
try:
from dotenv import load_dotenv
except ImportError:
print("Warning: python-dotenv not installed. Using system environment o... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""
+Validate WhatsApp Cloud API configuration.
+
+Checks environment variables and tests API connectivity.
+
+Usage:
+ python validate_config.py
+ python validate_config.py --env-file /path/to/.env
+"""
import argparse
import os
@@ -28,6 +37,7 @@
def check... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/whatsapp-cloud-api/scripts/validate_config.py |
Add docstrings that explain inputs and outputs | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
from design_system import generate_design_system
def format_output(result):
if "error" in result:
return f"Error: {result['error']}"
output = []
if resu... | --- +++ @@ -1,67 +1,76 @@-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-
-import argparse
-from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
-from design_system import generate_design_system
-
-
-def format_output(result):
- if "error" in result:
- return f"Error: {result['er... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/ui-ux-pro-max/scripts/search.py |
Write docstrings for data processing functions |
from typing import Dict, Any
from abc import ABC, abstractmethod
import logging
logger = logging.getLogger(__name__)
# ============================================================================
# Provider Interfaces
# ============================================================================
class TranscriberP... | --- +++ @@ -1,3 +1,9 @@+"""
+Template: Multi-Provider Factory
+
+Use this template to create a factory that supports multiple providers
+for transcription, LLM, and TTS services.
+"""
from typing import Dict, Any
from abc import ABC, abstractmethod
@@ -11,23 +17,29 @@ # =============================================... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/voice-ai-engine-development/templates/multi_provider_factory_template.py |
Provide docstrings following PEP 257 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import json
from pathlib import Path
from core import search, DATA_DIR
# ============ CONFIGURATION ============
REASONING_FILE = "ui-reasoning.csv"
SEARCH_CONFIG = {
"product": {"max_results": 1},
"style": {"max_results": 3},
"color": {"max_resu... | --- +++ @@ -1,5 +1,13 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Design System Generator - Aggregates search results and applies reasoning
+to generate comprehensive design system recommendations.
+
+Usage:
+ from design_system import generate_design_system
+ result = generate_design_system("SaaS da... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/ui-ux-pro-max/scripts/design_system.py |
Add inline docstrings for readability | #!/usr/bin/env python3
import argparse
import os
import shutil
import sys
def get_skill_dir() -> str:
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def setup_project(language: str, path: str, name: str | None = None) -> None:
skill_dir = get_skill_dir()
boilerplate_dir = os.path.jo... | --- +++ @@ -1,4 +1,11 @@ #!/usr/bin/env python3
+"""
+Setup a new WhatsApp Cloud API project with boilerplate code.
+
+Usage:
+ python setup_project.py --language nodejs --path ./my-whatsapp-project
+ python setup_project.py --language python --path ./my-whatsapp-project
+"""
import argparse
import os
@@ -7,1... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/whatsapp-cloud-api/scripts/setup_project.py |
Add docstrings for better understanding | #!/usr/bin/env python3
import re
import json
import sys
import urllib.request
import urllib.error
from pathlib import Path
from typing import List, Dict, Optional
from urllib.parse import urlparse
# VoltAgent repo README URL
VOLTAGENT_README_URL = "https://raw.githubusercontent.com/VoltAgent/awesome-agent-skills/main... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Analyze VoltAgent/awesome-agent-skills repository to extract and normalize skills.
+
+Usage:
+ python3 scripts/analyze_voltagent_repo.py [--output OUTPUT.json]
+"""
import re
import json
@@ -13,6 +19,7 @@ VOLTAGENT_README_URL = "https://raw.githubusercontent.... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/analyze_voltagent_repo.py |
Document this script properly | #!/usr/bin/env python3
import sys
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
def extract_transcript(video_id, language='en'):
try:
# Try to get transcript in specified language with fallback to English
transcript = YouTubeTranscriptApi.get_trans... | --- +++ @@ -1,9 +1,14 @@ #!/usr/bin/env python3
+"""
+Extract YouTube video transcript
+Usage: ./extract-transcript.py VIDEO_ID [LANGUAGE_CODE]
+"""
import sys
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
def extract_transcript(video_id, language='en'):
+ """... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/youtube-summarizer/scripts/extract-transcript.py |
Create structured documentation for my script | #!/usr/bin/env python3
import json
import re
from pathlib import Path
def check_html_content(skill_path: Path) -> dict:
try:
content = skill_path.read_text(encoding='utf-8')
except Exception as e:
return {'error': str(e), 'has_html': False}
# HTML patterns (excluding code blocks)
... | --- +++ @@ -1,10 +1,12 @@ #!/usr/bin/env python3
+"""Check for HTML content in skills and identify which need conversion."""
import json
import re
from pathlib import Path
def check_html_content(skill_path: Path) -> dict:
+ """Check if a skill file contains HTML content."""
try:
content = skill... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/check_html_content.py |
Write docstrings for backend logic | #!/usr/bin/env python3
import re
import shutil
import subprocess
import tempfile
import json
from pathlib import Path
MS_REPO = "https://github.com/microsoft/skills.git"
REPO_ROOT = Path(__file__).parent.parent
TARGET_DIR = REPO_ROOT / "skills"
DOCS_DIR = REPO_ROOT / "docs"
ATTRIBUTION_FILE = DOCS_DIR / "microsoft-sk... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Sync Microsoft Skills Repository - v4 (Flat Structure)
+Reads each SKILL.md frontmatter 'name' field and uses it as a flat directory
+name under skills/ to comply with the repository's indexing conventions.
+"""
import re
import shutil
@@ -15,6 +20,7 @@
def c... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/sync_microsoft_skills.py |
Add docstrings explaining edge cases | #!/usr/bin/env python3
import json
import os
import re
import sys
import urllib.request
import urllib.error
from pathlib import Path
from typing import Dict, Optional
from urllib.parse import urlparse, urljoin
def normalize_skill_name(name: str) -> str:
if '/' in name:
name = name.split('/')[-1]
name ... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Implement validated VoltAgent skills into the local repository.
+
+Downloads and adapts skills from GitHub repositories.
+"""
import json
import os
@@ -11,6 +16,7 @@ from urllib.parse import urlparse, urljoin
def normalize_skill_name(name: str) -> str:
+ ""... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/implement_voltagent_skills.py |
Create docstrings for all classes and functions | #!/usr/bin/env python3
import json
import os
import re
import sys
from _project_paths import find_repo_root
def collect_skill_ids(skills_dir):
ids = set()
for root, dirs, files in os.walk(skills_dir):
dirs[:] = [d for d in dirs if not d.startswith(".")]
if "SKILL.md" in files:
rel ... | --- +++ @@ -1,4 +1,11 @@ #!/usr/bin/env python3
+"""
+Validate cross-references in data/workflows.json and data/bundles.json.
+- Every recommendedSkills slug in workflows must exist under skills/ (with SKILL.md).
+- Every relatedBundles id in workflows must exist in bundles.json.
+- Every skill slug in each bundle's sk... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/validate_references.py |
Create documentation strings for testing functions | #!/usr/bin/env python3
import os
import re
import json
import sys
import argparse
from datetime import datetime
from pathlib import Path
import yaml
from _project_paths import find_repo_root
def get_project_root():
return str(find_repo_root(__file__))
def parse_frontmatter(content):
fm_match = re.search(r'^-... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Generate a report of skills with their date_added metadata in JSON format.
+
+Usage:
+ python generate_skills_report.py [--output report.json] [--sort date|name]
+"""
import os
import re
@@ -11,9 +17,11 @@ from _project_paths import find_repo_root
def get_pr... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/generate_skills_report.py |
Write reusable docstrings | import os
import re
import argparse
import sys
import io
import yaml
from collections.abc import Mapping
from datetime import date, datetime
from _project_paths import find_repo_root
def configure_utf8_output() -> None:
if sys.platform != "win32":
return
for stream_name in ("stdout", "stderr"):
... | --- +++ @@ -10,6 +10,7 @@
def configure_utf8_output() -> None:
+ """Best-effort UTF-8 stdout/stderr on Windows without dropping diagnostics."""
if sys.platform != "win32":
return
@@ -48,6 +49,10 @@ return value
def parse_frontmatter(content, rel_path=None):
+ """
+ Parse frontmatter ... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/validate_skills.py |
Help me document legacy Python code | #!/usr/bin/env python3
import os
import re
import sys
from _project_paths import find_repo_root
# Ensure UTF-8 output for Windows compatibility
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Update all skill dates from 2025 to 2026.
+Fixes the year mismatch issue.
+"""
import os
import re
@@ -12,6 +16,7 @@ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
def update_dates(skills_dir):
+ """Update all dates from 2025 to 2026... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/fix_year_2025_to_2026.py |
Document helper functions with docstrings | #!/usr/bin/env python3
import json
import re
import sys
import urllib.request
import urllib.error
from pathlib import Path
from typing import Dict, Optional, Tuple
from urllib.parse import urlparse, urljoin
def parse_frontmatter(content: str) -> Optional[Dict]:
fm_match = re.search(r'^---\s*\n(.*?)\n---', content... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Convert skills with HTML content to clean markdown.
+
+Attempts to download raw markdown files from GitHub, extracts content from HTML if needed,
+or creates minimal markdown content as fallback.
+"""
import json
import re
@@ -10,6 +16,7 @@ from urllib.parse imp... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/convert_html_to_markdown.py |
Provide clean and structured docstrings | #!/usr/bin/env python3
import os
import re
import sys
import argparse
from datetime import datetime
from pathlib import Path
import yaml
from _project_paths import find_repo_root
# Ensure UTF-8 output for Windows compatibility
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buff... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""
+Manage skill date_added metadata.
+
+Usage:
+ python manage_skill_dates.py list # List all skills with their dates
+ python manage_skill_dates.py add-missing [--date YYYY-MM-DD] # Add dates to skills without them
+ python manage_skill_dates.py... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/manage_skill_dates.py |
Create docstrings for each class method |
import os
import asyncio
from typing import Any
import httpx
GRAPH_API = "https://graph.facebook.com/v21.0"
class WhatsAppClient:
def __init__(
self,
token: str | None = None,
phone_number_id: str | None = None,
waba_id: str | None = None,
):
self.token = token or o... | --- +++ @@ -1,3 +1,4 @@+"""WhatsApp Cloud API Client with async support and retry logic."""
import os
import asyncio
@@ -9,6 +10,7 @@
class WhatsAppClient:
+ """Client for WhatsApp Cloud API with retry and error handling."""
def __init__(
self,
@@ -25,9 +27,11 @@ }
async def se... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/whatsapp-cloud-api/assets/boilerplate/python/whatsapp_client.py |
Add docstrings with type hints explained | #!/usr/bin/env python3
import os
import re
import json
import sys
import argparse
import yaml
from _project_paths import find_repo_root
# Ensure UTF-8 output for Windows compatibility
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.T... | --- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python3
+"""
+Auto-categorize skills based on their names and descriptions.
+Removes "uncategorized" by intelligently assigning categories.
+
+Usage:
+ python auto_categorize_skills.py
+ python auto_categorize_skills.py --dry-run (shows what would change)
+"""
import os
imp... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/auto_categorize_skills.py |
Generate docstrings for script automation | import platform, os
import asyncio
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent, executorResult
from sources.tools.C_Interpreter import CInterpreter
from sources.tools.GoInterpreter import GoInterpreter
from sources.tools.PyInterpreter import PyInterpreter
from sour... | --- +++ @@ -13,6 +13,9 @@ from sources.memory import Memory
class CoderAgent(Agent):
+ """
+ The code agent is an agent that can write and execute code.
+ """
def __init__(self, name, prompt_path, provider, verbose=False):
super().__init__(name, prompt_path, provider, verbose, None)
s... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/agents/code_agent.py |
Improve documentation using docstrings | import re
import time
from datetime import date
from typing import List, Tuple, Type, Dict
from enum import Enum
import asyncio
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent
from sources.tools.searxSearch import searxSearch
from sources.browser import Browser
from so... | --- +++ @@ -21,6 +21,9 @@
class BrowserAgent(Agent):
def __init__(self, name, prompt_path, provider, verbose=False, browser=None):
+ """
+ The Browser agent is an agent that navigate the web autonomously in search of answer
+ """
super().__init__(name, prompt_path, provider, ver... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/agents/browser_agent.py |
Add docstrings that explain purpose and usage |
import hashlib
import hmac
import os
from functools import wraps
from typing import Any
from flask import Request, abort, request
def validate_hmac_signature(app_secret: str | None = None):
secret = app_secret or os.environ["APP_SECRET"]
def decorator(f):
@wraps(f)
def decorated_function(*a... | --- +++ @@ -1,3 +1,4 @@+"""WhatsApp Webhook Handler with HMAC-SHA256 validation."""
import hashlib
import hmac
@@ -9,6 +10,13 @@
def validate_hmac_signature(app_secret: str | None = None):
+ """
+ Flask decorator to validate HMAC-SHA256 signature on webhook requests.
+
+ A Meta assina cada request com ... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/skills/whatsapp-cloud-api/assets/boilerplate/python/webhook_handler.py |
Document functions with clear intent |
from typing import Tuple, Callable
from abc import abstractmethod
import os
import random
import time
import asyncio
from concurrent.futures import ThreadPoolExecutor
from sources.memory import Memory
from sources.utility import pretty_print
from sources.schemas import executorResult
random.seed(time.time())
class... | --- +++ @@ -15,11 +15,23 @@ random.seed(time.time())
class Agent():
+ """
+ An abstract class for all agents.
+ """
def __init__(self, name: str,
prompt_path:str,
provider,
verbose=False,
browser=None) -> No... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/agents/agent.py |
Generate docstrings for this script | import os
import asyncio
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent
from sources.tools.mcpFinder import MCP_finder
from sources.memory import Memory
# NOTE MCP agent is an active work in progress, not functional yet.
class McpAgent(Agent):
def __init__(self... | --- +++ @@ -11,6 +11,10 @@ class McpAgent(Agent):
def __init__(self, name, prompt_path, provider, verbose=False):
+ """
+ The mcp agent is a special agent for using MCPs.
+ MCP agent will be disabled if the user does not explicitly set the MCP_FINDER_API_KEY in environment variable.
+ ... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/agents/mcp_agent.py |
Generate documentation strings for clarity |
from typing import Tuple, Callable
from pydantic import BaseModel
from sources.utility import pretty_print
class QueryRequest(BaseModel):
query: str
tts_enabled: bool = True
def __str__(self):
return f"Query: {self.query}, Language: {self.lang}, TTS: {self.tts_enabled}, STT: {self.stt_enabled}"
... | --- +++ @@ -42,7 +42,19 @@ }
class executorResult:
+ """
+ A class to store the result of a tool execution.
+ """
def __init__(self, block: str, feedback: str, success: bool, tool_type: str):
+ """
+ Initialize an agent with execution results.
+
+ Args:
+ block: ... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/schemas.py |
Generate docstrings for this script | import subprocess
import os, sys
import tempfile
import re
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
class JavaInterpreter(Tools):
def __init__(... | --- +++ @@ -9,6 +9,9 @@ from sources.tools.tools import Tools
class JavaInterpreter(Tools):
+ """
+ This class is a tool to allow execution of Java code.
+ """
def __init__(self):
super().__init__()
self.tag = "java"
@@ -16,6 +19,9 @@ self.description = "This tool allows you t... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/JavaInterpreter.py |
Generate consistent documentation across files |
import sys
import os
import re
from io import StringIO
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
class PyInterpreter(Tools):
def __init__(self)... | --- +++ @@ -10,6 +10,9 @@ from sources.tools.tools import Tools
class PyInterpreter(Tools):
+ """
+ This class is a tool to allow agent for python code execution.
+ """
def __init__(self):
super().__init__()
self.tag = "python"
@@ -17,6 +20,9 @@ self.description = "This tool a... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/PyInterpreter.py |
Insert docstrings into my code | import subprocess
import os, sys
import tempfile
import re
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
class CInterpreter(Tools):
def __init__(sel... | --- +++ @@ -9,6 +9,9 @@ from sources.tools.tools import Tools
class CInterpreter(Tools):
+ """
+ This class is a tool to allow agent for C code execution
+ """
def __init__(self):
super().__init__()
self.tag = "c"
@@ -16,6 +19,9 @@ self.description = "This tool allows the agen... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/C_Interpreter.py |
Write proper docstrings for these functions |
import os, sys
import re
from io import StringIO
import subprocess
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
from sources.tools.safety import is_any... | --- +++ @@ -11,6 +11,9 @@ from sources.tools.safety import is_any_unsafe
class BashInterpreter(Tools):
+ """
+ This class is a tool to allow agent for bash code execution.
+ """
def __init__(self):
super().__init__()
self.tag = "bash"
@@ -18,6 +21,11 @@ self.description = "Thi... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/BashInterpreter.py |
Add docstrings for production code | #!/usr/bin/env python3
import json
import sys
import urllib.request
import urllib.error
from pathlib import Path
from typing import Dict, List, Optional
from urllib.parse import urlparse, urljoin
def check_url_accessible(url: str, timeout: int = 10) -> tuple[bool, Optional[str]]:
try:
req = urllib.request... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""
+Validate GitHub sources for VoltAgent skills.
+
+Checks:
+- URL accessibility
+- Repository existence
+- SKILL.md presence
+- License compatibility
+"""
import json
import sys
@@ -9,6 +18,7 @@ from urllib.parse import urlparse, urljoin
def check_url_accessibl... | https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/HEAD/tools/scripts/validate_voltagent_sources.py |
Auto-generate documentation strings for this file | import os
import json
from pathlib import Path
class Cache:
def __init__(self, cache_dir='.cache', cache_file='messages.json'):
self.cache_dir = Path(cache_dir)
self.cache_file = self.cache_dir / cache_file
self.cache_dir.mkdir(parents=True, exist_ok=True)
if not self.cache_file.exi... | --- +++ @@ -15,14 +15,17 @@ self.cache = set(json.load(f))
def add_message_pair(self, user_message: str, assistant_message: str):
+ """Add a user/assistant pair to the cache if not present."""
if not any(entry["user"] == user_message for entry in self.cache):
self.cache.a... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/llm_server/sources/cache.py |
Add detailed documentation for each class | from colorama import Fore
from typing import List, Tuple, Type, Dict
import queue
import threading
import numpy as np
import time
IMPORT_FOUND = True
try:
import torch
import librosa
import pyaudio
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
except ImportError:
prin... | --- +++ @@ -20,6 +20,9 @@ done = False
class AudioRecorder:
+ """
+ AudioRecorder is a class that records audio from the microphone and adds it to the audio queue.
+ """
def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 4096, chunk: int = 8192, record_seconds: int = 5, ve... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/speech_to_text.py |
Add inline docstrings for readability | import os, sys
import re
import platform
import subprocess
from sys import modules
from typing import List, Tuple, Type, Dict
IMPORT_FOUND = True
try:
from kokoro import KPipeline
from IPython.display import display, Audio
import soundfile as sf
except ImportError:
print("Speech synthesis disabled. To ... | --- +++ @@ -21,6 +21,9 @@ from sources.utility import pretty_print, animate_thinking
class Speech():
+ """
+ Speech is a class for generating speech from text.
+ """
def __init__(self, enable: bool = True, language: str = "en", voice_idx: int = 6) -> None:
self.lang_map = {
"e... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/text_to_speech.py |
Generate documentation strings for clarity | import os
import sys
import torch
import random
from typing import List, Tuple, Type, Dict
from transformers import pipeline
from adaptive_classifier import AdaptiveClassifier
from sources.agents.agent import Agent
from sources.agents.code_agent import CoderAgent
from sources.agents.casual_agent import CasualAgent
fr... | --- +++ @@ -17,6 +17,9 @@ from sources.logger import Logger
class AgentRouter:
+ """
+ AgentRouter is a class that selects the appropriate agent based on the user query.
+ """
def __init__(self, agents: list, supported_language: List[str] = ["en", "fr", "zh"]):
self.agents = agents
se... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/router.py |
Replace inline comments with docstrings | import subprocess
import os, sys
import tempfile
import re
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
class GoInterpreter(Tools):
def __init__(se... | --- +++ @@ -9,6 +9,9 @@ from sources.tools.tools import Tools
class GoInterpreter(Tools):
+ """
+ This class is a tool to allow execution of Go code.
+ """
def __init__(self):
super().__init__()
self.tag = "go"
@@ -16,6 +19,9 @@ self.description = "This tool allows you to exec... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/GoInterpreter.py |
Create documentation strings for testing functions |
from __future__ import annotations
def max_ones_index(array: list[int]) -> int:
length = len(array)
max_count = 0
max_index = 0
prev_zero = -1
prev_prev_zero = -1
for current in range(length):
if array[current] == 0:
if current - prev_prev_zero > max_count:
... | --- +++ @@ -1,8 +1,32 @@+"""
+Max Ones Index
+
+Find the index of the 0 that, when replaced with 1, produces the longest
+continuous sequence of 1s in a binary array. Returns -1 if no 0 exists.
+
+Reference: https://www.geeksforgeeks.org/find-index-0-replaced-1-get-longest-continuous-sequence-1s-binary-array/
+
+Comple... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/max_ones_index.py |
Replace inline comments with docstrings |
from __future__ import annotations
from collections.abc import Generator
from typing import Any
def josephus(items: list[Any], skip: int) -> Generator[Any, None, None]:
skip = skip - 1
index = 0
remaining = len(items)
while remaining > 0:
index = (skip + index) % remaining
yield item... | --- +++ @@ -1,3 +1,15 @@+"""
+Josephus Problem
+
+People sit in a circular fashion; every k-th person is eliminated until
+everyone has been removed. Yield the elimination order.
+
+Reference: https://en.wikipedia.org/wiki/Josephus_problem
+
+Complexity:
+ Time: O(n^2) due to list.pop at arbitrary index
+ Space:... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/josephus.py |
Create docstrings for reusable components |
from __future__ import annotations
def longest_non_repeat_v1(string: str) -> int:
if string is None:
return 0
char_index = {}
max_length = 0
start = 0
for index in range(len(string)):
if string[index] in char_index:
start = max(char_index[string[index]], start)
... | --- +++ @@ -1,8 +1,32 @@+"""
+Longest Substring Without Repeating Characters
+
+Given a string, find the length of the longest substring without repeating
+characters. Multiple algorithm variants are provided.
+
+Reference: https://leetcode.com/problems/longest-substring-without-repeating-characters/
+
+Complexity:
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/longest_non_repeat.py |
Create structured documentation for my script | import os
import platform
import socket
import subprocess
import time
from urllib.parse import urlparse
import httpx
import requests
from dotenv import load_dotenv
from ollama import Client as OllamaClient
from openai import OpenAI
from sources.logger import Logger
from sources.utility import pretty_print, animate_th... | --- +++ @@ -67,6 +67,9 @@ return url, True
def respond(self, history, verbose=True):
+ """
+ Use the choosen provider to generate text.
+ """
llm = self.available_providers[self.provider_name]
self.logger.info(f"Using provider: {self.provider_name} at {self.server_i... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/llm_provider.py |
Generate missing documentation strings | from typing import List, Tuple, Type, Dict
import re
import langid
from transformers import MarianMTModel, MarianTokenizer
from sources.utility import pretty_print, animate_thinking
from sources.logger import Logger
class LanguageUtility:
def __init__(self, supported_language: List[str] = ["en", "fr", "zh"]):
... | --- +++ @@ -7,7 +7,13 @@ from sources.logger import Logger
class LanguageUtility:
+ """LanguageUtility for language, or emotion identification"""
def __init__(self, supported_language: List[str] = ["en", "fr", "zh"]):
+ """
+ Initialize the LanguageUtility class
+ args:
+ supp... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/language.py |
Turn comments into proper docstrings |
from __future__ import annotations
def limit(
array: list[int],
min_lim: int | None = None,
max_lim: int | None = None,
) -> list[int]:
if len(array) == 0:
return array
if min_lim is None:
min_lim = min(array)
if max_lim is None:
max_lim = max(array)
return list(... | --- +++ @@ -1,3 +1,15 @@+"""
+Limit Array Values
+
+Filter an array to include only elements within a specified minimum and
+maximum range (inclusive).
+
+Reference: https://en.wikipedia.org/wiki/Clipping_(signal_processing)
+
+Complexity:
+ Time: O(n)
+ Space: O(n)
+"""
from __future__ import annotations
@... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/limit.py |
Write docstrings for this repository | import requests
from bs4 import BeautifulSoup
import os
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
class searxSearch(Tools):
def __init__(self, b... | --- +++ @@ -9,6 +9,9 @@
class searxSearch(Tools):
def __init__(self, base_url: str = None):
+ """
+ A tool for searching a SearxNG instance and extracting URLs and titles.
+ """
super().__init__()
self.tag = "web_search"
self.name = "searxSearch"
@@ -22,6 +25,7 @@ ... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/searxSearch.py |
Document functions with detailed explanations | import os
import sys
unsafe_commands_unix = [
"rm", # File/directory removal
"dd", # Low-level disk writing
"mkfs", # Filesystem formatting
"chmod", # Permission changes
"chown", # Ownership changes
"shutdown", # System shutdown
"reboot", ... | --- +++ @@ -67,12 +67,18 @@ ]
def is_any_unsafe(cmds):
+ """
+ check if any bash command is unsafe.
+ """
for cmd in cmds:
if is_unsafe(cmd):
return True
return False
def is_unsafe(cmd):
+ """
+ check if a bash command is unsafe.
+ """
if sys.platform.startsw... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/safety.py |
Add docstrings to improve code quality |
from __future__ import annotations
def missing_ranges(array: list[int], low: int, high: int) -> list[tuple[int, int]]:
result = []
start = low
for num in array:
if num == start:
start += 1
elif num > start:
result.append((start, num - 1))
start = num +... | --- +++ @@ -1,8 +1,34 @@+"""
+Missing Ranges
+
+Find the ranges of numbers that are missing between a given low and high
+bound, given a sorted array of integers.
+
+Reference: https://leetcode.com/problems/missing-ranges/
+
+Complexity:
+ Time: O(n)
+ Space: O(n) for the result list
+"""
from __future__ impo... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/missing_ranges.py |
Add docstrings including usage examples |
import sys
import os
import configparser
from abc import abstractmethod
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sources.logger import Logger
class Tools():
def __init__(self):
self.t... | --- +++ @@ -1,4 +1,21 @@
+"""
+define a generic tool class, any tool can be used by the agent.
+
+A tool can be used by a llm like so:
+```<tool name>
+<code or query to execute>
+```
+
+we call these "blocks".
+
+For example:
+```python
+print("Hello world")
+```
+This is then executed by the tool with its own class ... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/tools.py |
Add standardized docstrings across the file |
from __future__ import annotations
import collections
def delete_nth_naive(array: list[int], n: int) -> list[int]:
result = []
for num in array:
if result.count(num) < n:
result.append(num)
return result
def delete_nth(array: list[int], n: int) -> list[int]:
result = []
cou... | --- +++ @@ -1,3 +1,19 @@+"""
+Delete Nth Occurrence
+
+Given a list and a number N, create a new list that contains each element
+of the original list at most N times, without reordering.
+
+Reference: https://www.geeksforgeeks.org/remove-duplicates-from-an-array/
+
+Complexity:
+ delete_nth_naive:
+ Time: O... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/delete_nth.py |
Write docstrings for algorithm functions |
from __future__ import annotations
from typing import Any
def move_zeros(array: list[Any]) -> list[Any]:
result = []
zeros = 0
for element in array:
if element == 0 and type(element) is not bool:
zeros += 1
else:
result.append(element)
result.extend([0] * ze... | --- +++ @@ -1,3 +1,15 @@+"""
+Move Zeros
+
+Move all zeros in an array to the end while preserving the relative order
+of the non-zero (and non-integer-zero) elements.
+
+Reference: https://leetcode.com/problems/move-zeroes/
+
+Complexity:
+ Time: O(n)
+ Space: O(n)
+"""
from __future__ import annotations
@... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/move_zeros.py |
Add docstrings to make code maintainable | import readline
from typing import List, Tuple, Type, Dict
from sources.text_to_speech import Speech
from sources.utility import pretty_print, animate_thinking
from sources.router import AgentRouter
from sources.speech_to_text import AudioTranscriber, AudioRecorder
import threading
class Interaction:
def __init_... | --- +++ @@ -9,6 +9,9 @@
class Interaction:
+ """
+ Interaction is a class that handles the interaction between the user and the agents.
+ """
def __init__(self, agents,
tts_enabled: bool = True,
stt_enabled: bool = True,
@@ -40,21 +43,25 @@ self.emit_status(... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/interaction.py |
Add detailed docstrings explaining each function | from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from sel... | --- +++ @@ -33,6 +33,7 @@
def get_chrome_path() -> str:
+ """Get the path to the Chrome executable."""
if sys.platform.startswith("win"):
paths = [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
@@ -68,6 +69,7 @@ return None
def get_random_user_agent() -> str:
+ ... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/browser.py |
Help me document legacy Python code |
from __future__ import annotations
def garage(initial: list[int], final: list[int]) -> tuple[int, list[list[int]]]:
current = initial[::]
sequence = []
steps = 0
while current != final:
zero_pos = current.index(0)
if zero_pos != final.index(0):
target_car = final[zero_pos... | --- +++ @@ -1,8 +1,35 @@+"""
+Garage Parking Rearrangement
+
+There is a parking lot with only one empty spot (represented by 0). Given the
+initial and final states, find the minimum number of moves to rearrange the lot.
+Each move swaps a car into the empty spot.
+
+Reference: https://en.wikipedia.org/wiki/15_puzzle
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/garage.py |
Improve my code by adding docstrings |
from __future__ import annotations
from collections.abc import Generator, Iterable
from typing import Any
def flatten(input_arr: Iterable[Any], output_arr: list[Any] | None = None) -> list[Any]:
if output_arr is None:
output_arr = []
for element in input_arr:
if not isinstance(element, str) ... | --- +++ @@ -1,3 +1,15 @@+"""
+Flatten Arrays
+
+Given an array that may contain nested arrays, produce a single
+flat resultant array.
+
+Reference: https://en.wikipedia.org/wiki/Flatten_(higher-order_function)
+
+Complexity:
+ Time: O(n) where n is the total number of elements
+ Space: O(n)
+"""
from __futur... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/flatten.py |
Write docstrings for algorithm functions | import json
from typing import List, Tuple, Type, Dict
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent
from sources.agents.code_agent import CoderAgent
from sources.agents.file_agent import FileAgent
from sources.agents.browser_agent import BrowserAgent
from sources.age... | --- +++ @@ -13,6 +13,9 @@
class PlannerAgent(Agent):
def __init__(self, name, prompt_path, provider, verbose=False, browser=None):
+ """
+ The planner agent is a special agent that divides and conquers the task.
+ """
super().__init__(name, prompt_path, provider, verbose, None)
... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/agents/planner_agent.py |
Auto-generate documentation strings for this file |
from __future__ import annotations
class Interval:
def __init__(self, start: int = 0, end: int = 0) -> None:
self.start = start
self.end = end
def __repr__(self) -> str:
return f"Interval ({self.start}, {self.end})"
def __iter__(self):
return iter(range(self.start, self... | --- +++ @@ -1,8 +1,26 @@+"""
+Merge Intervals
+
+Given a collection of intervals, merge all overlapping intervals into a
+consolidated set.
+
+Reference: https://en.wikipedia.org/wiki/Interval_(mathematics)
+
+Complexity:
+ Time: O(n log n) due to sorting
+ Space: O(n)
+"""
from __future__ import annotations
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/merge_intervals.py |
Include argument descriptions in docstrings | import os, sys
import requests
from urllib.parse import urljoin
from typing import Dict, Any, Optional
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
cla... | --- +++ @@ -9,6 +9,9 @@ from sources.tools.tools import Tools
class MCP_finder(Tools):
+ """
+ Tool to find MCPs server
+ """
def __init__(self, api_key: str = None):
super().__init__()
self.tag = "mcp_finder"
@@ -47,6 +50,13 @@ return self._make_request("GET", endpoint)
... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/mcpFinder.py |
Generate docstrings for script automation | import time
import datetime
import uuid
import os
import sys
import json
from typing import List, Tuple, Type, Dict
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import configparser
from sources.utility import timer_decorator, pretty_print, animate_thinking
from sources.logger import Logge... | --- +++ @@ -16,6 +16,10 @@ config.read('config.ini')
class Memory():
+ """
+ Memory is a class for managing the conversation memory
+ It provides a method to compress the memory using summarization model.
+ """
def __init__(self, system_prompt: str,
recover_last_session: bool = Fal... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/memory.py |
Document this code for team use |
from __future__ import annotations
def add_operators(digits: str, target: int) -> list[str]:
result: list[str] = []
if not digits:
return result
_dfs(result, "", digits, target, 0, 0, 0)
return result
def _dfs(
result: list[str],
path: str,
digits: str,
target: int,
posi... | --- +++ @@ -1,8 +1,34 @@+"""
+Expression Add Operators
+
+Given a string of digits and a target value, return all possibilities to
+insert binary operators (+, -, *) between the digits so they evaluate to
+the target value.
+
+Reference: https://leetcode.com/problems/expression-add-operators/
+
+Complexity:
+ Time: ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/add_operators.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
def count_ones_recur(number: int) -> int:
if not number:
return 0
return 1 + count_ones_recur(number & (number - 1))
def count_ones_iter(number: int) -> int:
count = 0
while number:
number &= number - 1
count += 1
return count | --- +++ @@ -1,16 +1,56 @@+"""
+Count Ones (Hamming Weight)
+
+Count the number of 1-bits in the binary representation of an unsigned
+integer using Brian Kernighan's algorithm.
+
+Reference: https://en.wikipedia.org/wiki/Hamming_weight
+
+Complexity:
+ Time: O(k) where k is the number of set bits
+ Space: O(1) i... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/count_ones.py |
Document all public functions with docstrings |
from __future__ import annotations
def find_difference(original: str, shuffled: str) -> str:
xor_result = 0
for character in original + shuffled:
xor_result ^= ord(character)
return chr(xor_result) | --- +++ @@ -1,9 +1,37 @@+"""
+Find the Difference
+
+Given two strings where the second is generated by shuffling the first and
+adding one extra letter, find the added letter using XOR.
+
+Reference: https://en.wikipedia.org/wiki/Exclusive_or
+
+Complexity:
+ Time: O(n) where n is the length of the longer string
+... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/find_difference.py |
Expand my code with proper documentation strings |
from __future__ import annotations
def anagram(first: str, second: str) -> bool:
count_first = [0] * 26
count_second = [0] * 26
for char in first:
index = ord(char) - ord("a")
count_first[index] += 1
for char in second:
index = ord(char) - ord("a")
count_second[index... | --- +++ @@ -1,8 +1,35 @@+"""
+Anagram Checker
+
+Given two strings, determine if they are anagrams of each other (i.e. one
+can be rearranged to form the other).
+
+Reference: https://en.wikipedia.org/wiki/Anagram
+
+Complexity:
+ Time: O(n) where n is the length of the strings
+ Space: O(1) fixed 26-character a... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/anagram.py |
Annotate my code with docstrings |
from __future__ import annotations
def trimmean(array: list[float], percentage: float) -> float:
ratio = percentage / 200
array.sort()
trim_count = int(len(array) * ratio)
trimmed = array[trim_count : len(array) - trim_count]
total = 0
for value in trimmed:
total += value
return t... | --- +++ @@ -1,8 +1,37 @@+"""
+Trimmed Mean
+
+Compute the mean of an array after discarding a given percentage of the
+highest and lowest values. Useful for robust averaging in scoring systems.
+
+Reference: https://en.wikipedia.org/wiki/Truncated_mean
+
+Complexity:
+ Time: O(n log n) due to sorting
+ Space: O(... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/trimmean.py |
Add structured docstrings to improve clarity |
from __future__ import annotations
from collections.abc import Hashable
from typing import Any
def remove_duplicates(array: list[Any]) -> list[Any]:
seen = set()
unique_array = []
for item in array:
if isinstance(item, Hashable):
if item not in seen:
seen.add(item)
... | --- +++ @@ -1,3 +1,15 @@+"""
+Remove Duplicates
+
+Remove duplicate elements from an array while preserving the original order.
+Handles both hashable and unhashable items.
+
+Reference: https://en.wikipedia.org/wiki/Duplicate_code
+
+Complexity:
+ Time: O(n) for hashable items / O(n^2) worst case for unhashable it... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/remove_duplicates.py |
Provide clean and structured docstrings | import os, sys
import stat
import mimetypes
import configparser
if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools
class FileFinder(Tools):
def __init__(... | --- +++ @@ -9,6 +9,9 @@ from sources.tools.tools import Tools
class FileFinder(Tools):
+ """
+ A tool that finds files in the current directory and returns their information.
+ """
def __init__(self):
super().__init__()
self.tag = "file_finder"
@@ -16,6 +19,13 @@ self.descript... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/tools/fileFinder.py |
Add docstrings with type hints explained |
from __future__ import annotations
def two_sum(array: list[int], target: int) -> tuple[int, int] | None:
seen = {}
for index, num in enumerate(array):
if num in seen:
return seen[num], index
else:
seen[target - num] = index
return None | --- +++ @@ -1,12 +1,37 @@+"""
+Two Sum
+
+Given an array of integers and a target sum, return the indices of the two
+numbers that add up to the target.
+
+Reference: https://leetcode.com/problems/two-sum/
+
+Complexity:
+ Time: O(n)
+ Space: O(n)
+"""
from __future__ import annotations
def two_sum(array... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/two_sum.py |
Add professional docstrings to my codebase |
from __future__ import annotations
def combination_sum(candidates: list[int], target: int) -> list[list[int]]:
result: list[list[int]] = []
candidates.sort()
_dfs(candidates, target, 0, [], result)
return result
def _dfs(
nums: list[int],
target: int,
index: int,
path: list[int],
... | --- +++ @@ -1,8 +1,34 @@+"""
+Combination Sum
+
+Given a set of candidate numbers (without duplicates) and a target number,
+find all unique combinations where the candidate numbers sum to the target.
+The same number may be chosen an unlimited number of times.
+
+Reference: https://leetcode.com/problems/combination-su... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/combination_sum.py |
Document functions with clear intent |
from __future__ import annotations
def count_flips_to_convert(first: int, second: int) -> int:
diff = first ^ second
count = 0
while diff:
diff &= diff - 1
count += 1
return count | --- +++ @@ -1,11 +1,39 @@+"""
+Count Flips to Convert
+
+Determine the minimal number of bits you would need to flip to convert
+integer A to integer B. Uses XOR to find differing bits and Brian
+Kernighan's algorithm to count them.
+
+Reference: https://en.wikipedia.org/wiki/Hamming_distance
+
+Complexity:
+ Time: ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/count_flips_to_convert.py |
Write clean docstrings for readability |
from __future__ import annotations
def add_bitwise_operator(first: int, second: int) -> int:
while second:
carry = first & second
first = first ^ second
second = carry << 1
return first | --- +++ @@ -1,10 +1,37 @@+"""
+Add Bitwise Operator
+
+Add two positive integers without using the '+' operator, using only
+bitwise operations (AND, XOR, shift).
+
+Reference: https://en.wikipedia.org/wiki/Adder_(electronics)
+
+Complexity:
+ Time: O(log n) where n is the larger of the two inputs
+ Space: O(1)
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/add_bitwise_operator.py |
Fully document this Python code with docstrings |
from __future__ import annotations
from collections.abc import Generator
def palindromic_substrings(text: str) -> list[list[str]]:
if not text:
return [[]]
results: list[list[str]] = []
for i in range(len(text), 0, -1):
substring = text[:i]
if substring == substring[::-1]:
... | --- +++ @@ -1,3 +1,15 @@+"""
+Palindrome Partitioning
+
+Given a string, find all ways to partition it into palindromic substrings.
+There is always at least one way since single characters are palindromes.
+
+Reference: https://leetcode.com/problems/palindrome-partitioning/
+
+Complexity:
+ Time: O(n * 2^n) where ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/palindrome_partitioning.py |
Provide clean and structured docstrings |
from __future__ import annotations
def binary_gap(number: int) -> int:
last_one_position = None
longest_gap = 0
index = 0
while number != 0:
if number & 1:
if last_one_position is not None:
longest_gap = max(longest_gap, index - last_one_position)
last_... | --- +++ @@ -1,8 +1,36 @@+"""
+Binary Gap
+
+Given a positive integer N, find and return the longest distance between two
+consecutive 1-bits in the binary representation of N. If there are not two
+consecutive 1-bits, return 0.
+
+Reference: https://en.wikipedia.org/wiki/Hamming_distance
+
+Complexity:
+ Time: O(lo... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/binary_gap.py |
Document functions with detailed explanations |
from __future__ import annotations
import math
def minimax(
depth: int,
is_maximizing: bool,
scores: list[int],
alpha: float = -math.inf,
beta: float = math.inf,
) -> float:
if depth == 0:
return scores[0]
mid = len(scores) // 2
if is_maximizing:
value = -math.inf
... | --- +++ @@ -1,3 +1,11 @@+"""Minimax — game-tree search with alpha-beta pruning.
+
+The minimax algorithm finds the optimal move for a two-player zero-sum
+game. Alpha-beta pruning reduces the search space by eliminating branches
+that cannot influence the final decision.
+
+Inspired by PR #860 (DD2480-group16).
+"""
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/minimax.py |
Add well-formatted docstrings |
from __future__ import annotations
def summarize_ranges(array: list[int]) -> list[tuple[int, ...]]:
result = []
if len(array) == 0:
return []
if len(array) == 1:
return [(array[0], array[0])]
iterator = iter(array)
start = end = next(iterator)
for num in iterator:
if n... | --- +++ @@ -1,8 +1,32 @@+"""
+Summarize Ranges
+
+Given a sorted integer array without duplicates, return the summary of its
+ranges as a list of (start, end) tuples.
+
+Reference: https://leetcode.com/problems/summary-ranges/
+
+Complexity:
+ Time: O(n)
+ Space: O(n) for the result list
+"""
from __future__ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/summarize_ranges.py |
Add docstrings to improve code quality |
from colorama import Fore
from termcolor import colored
import platform
import threading
import itertools
import time
thinking_event = threading.Event()
current_animation_thread = None
def get_color_map():
if platform.system().lower() != "windows":
color_map = {
"success": "green",
... | --- +++ @@ -33,6 +33,21 @@ return color_map
def pretty_print(text, color="info", no_newline=False):
+ """
+ Print text with color formatting.
+
+ Args:
+ text (str): The text to print
+ color (str, optional): The color to use. Defaults to "info".
+ Valid colors are:
+ ... | https://raw.githubusercontent.com/Fosowl/agenticSeek/HEAD/sources/utility.py |
Write reusable docstrings |
from __future__ import annotations
def rotate_v1(array: list[int], k: int) -> list[int]:
array = array[:]
length = len(array)
for _ in range(k):
temp = array[length - 1]
for position in range(length - 1, 0, -1):
array[position] = array[position - 1]
array[0] = temp
... | --- +++ @@ -1,8 +1,34 @@+"""
+Rotate Array
+
+Rotate an array of n elements to the right by k steps.
+Three algorithm variants are provided with different time complexities.
+
+Reference: https://leetcode.com/problems/rotate-array/
+
+Complexity:
+ rotate_v1: Time O(n*k), Space O(n)
+ rotate_v2: Time O(n), Spac... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/rotate.py |
Add docstrings for better understanding |
from __future__ import annotations
def subsets(nums: list[int]) -> list[list[int]]:
result: list[list[int]] = []
_backtrack(result, nums, [], 0)
return result
def _backtrack(
result: list[list[int]],
nums: list[int],
stack: list[int],
position: int,
) -> None:
if position == len(num... | --- +++ @@ -1,8 +1,32 @@+"""
+Subsets
+
+Given a set of distinct integers, return all possible subsets (the power
+set). The solution set must not contain duplicate subsets.
+
+Reference: https://en.wikipedia.org/wiki/Power_set
+
+Complexity:
+ Time: O(2^n) where n is the number of elements
+ Space: O(2^n) to st... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/subsets.py |
Add docstrings explaining edge cases |
from __future__ import annotations
def three_sum(array: list[int]) -> set[tuple[int, int, int]]:
result = set()
array.sort()
for i in range(len(array) - 2):
if i > 0 and array[i] == array[i - 1]:
continue
left, right = i + 1, len(array) - 1
while left < right:
... | --- +++ @@ -1,8 +1,32 @@+"""
+Three Sum
+
+Given an array of integers, find all unique triplets that sum to zero
+using the two-pointer technique.
+
+Reference: https://leetcode.com/problems/3sum/
+
+Complexity:
+ Time: O(n^2)
+ Space: O(n) for the result set
+"""
from __future__ import annotations
def t... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/three_sum.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
def get_bit(number: int, position: int) -> int:
return (number & (1 << position)) != 0
def set_bit(number: int, position: int) -> int:
return number | (1 << position)
def clear_bit(number: int, position: int) -> int:
mask = ~(1 << position)
return number & mask
... | --- +++ @@ -1,20 +1,101 @@+"""
+Fundamental Bit Operations
+
+Basic bit manipulation operations: get, set, clear, and update individual
+bits at a specific position in an integer.
+
+Reference: https://en.wikipedia.org/wiki/Bit_manipulation
+
+Complexity:
+ Time: O(1) for all operations
+ Space: O(1)
+"""
fro... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/bit_operation.py |
Add docstrings to meet PEP guidelines |
from __future__ import annotations
def plus_one_v1(digits: list[int]) -> list[int]:
digits[-1] = digits[-1] + 1
result = []
carry = 0
index = len(digits) - 1
while index >= 0 or carry == 1:
digit_sum = 0
if index >= 0:
digit_sum += digits[index]
if carry:
... | --- +++ @@ -1,8 +1,32 @@+"""
+Plus One
+
+Given a non-negative number represented as an array of digits (big-endian),
+add one to the number and return the resulting digit array.
+
+Reference: https://leetcode.com/problems/plus-one/
+
+Complexity:
+ Time: O(n)
+ Space: O(n) for v1, O(1) auxiliary for v2 and v3
+... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/plus_one.py |
Document my Python code with docstrings |
from __future__ import annotations
def subsets_unique(nums: list[int]) -> list[tuple[int, ...]]:
found: set[tuple[int, ...]] = set()
_backtrack(found, nums, [], 0)
return list(found)
def _backtrack(
found: set[tuple[int, ...]],
nums: list[int],
stack: list[int],
position: int,
) -> None... | --- +++ @@ -1,8 +1,32 @@+"""
+Unique Subsets
+
+Given a collection of integers that might contain duplicates, return all
+possible unique subsets (the power set without duplicates).
+
+Reference: https://leetcode.com/problems/subsets-ii/
+
+Complexity:
+ Time: O(2^n) where n is the number of elements
+ Space: O(... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/subsets_unique.py |
Add well-formatted docstrings |
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int = 0
left: TreeNode | None = None
right: TreeNode | None = None | --- +++ @@ -1,3 +1,9 @@+"""Binary tree node shared across all tree algorithms.
+
+This module provides the universal TreeNode used by every tree algorithm
+in this library. Using a single shared type means you can compose
+algorithms freely: build a BST, invert it, then traverse it.
+"""
from __future__ import annot... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/common/tree_node.py |
Provide clean and structured docstrings |
from __future__ import annotations
from collections.abc import Callable
from typing import Any
def n_sum(
n: int,
nums: list[Any],
target: Any,
**kv: Callable[..., Any],
) -> list[list[Any]]:
def _sum_closure_default(a: Any, b: Any) -> Any:
return a + b
def _compare_closure_default... | --- +++ @@ -1,3 +1,16 @@+"""
+N-Sum
+
+Given an array of integers, find all unique n-tuples that sum to a target
+value. Supports custom sum, comparison, and equality closures for advanced
+use cases with non-integer elements.
+
+Reference: https://leetcode.com/problems/4sum/
+
+Complexity:
+ Time: O(n^(k-1)) where... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/n_sum.py |
Add docstrings for utility scripts |
from __future__ import annotations
def pattern_match(pattern: str, string: str) -> bool:
return _backtrack(pattern, string, {})
def _backtrack(
pattern: str,
string: str,
mapping: dict[str, str],
) -> bool:
if len(pattern) == 0 and len(string) > 0:
return False
if len(pattern) == 0... | --- +++ @@ -1,8 +1,36 @@+"""
+Pattern Matching
+
+Given a pattern and a string, determine if the string follows the same
+pattern. A full match means a bijection between each letter in the pattern
+and a non-empty substring in the string.
+
+Reference: https://leetcode.com/problems/word-pattern-ii/
+
+Complexity:
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/pattern_match.py |
Add docstrings to meet PEP guidelines |
from __future__ import annotations
from math import log
def _log2(x: int | float) -> float:
return log(x, 2)
def _binary(x: int, length: int = 1) -> str:
fmt = f"{{0:0{length}b}}"
return fmt.format(x)
def _unary(x: int) -> str:
return (x - 1) * "1" + "0"
def _elias_generic(
length_encoding... | --- +++ @@ -1,3 +1,16 @@+"""
+Elias Gamma and Delta Coding
+
+Universal codes for encoding positive integers. Elias gamma code uses a unary
+prefix followed by a binary suffix. Elias delta code nests gamma coding for
+the length prefix. Both were developed by Peter Elias.
+
+Reference: https://en.wikipedia.org/wiki/Eli... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/compression/elias.py |
Write documentation strings for class attributes |
from __future__ import annotations
def letter_combinations(digits: str) -> list[str]:
if digits == "":
return []
keypad_map = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
c... | --- +++ @@ -1,8 +1,32 @@+"""
+Letter Combinations of a Phone Number
+
+Given a digit string, return all possible letter combinations that the
+number could represent using a telephone keypad mapping.
+
+Reference: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
+
+Complexity:
+ Time: O(4^n) whe... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/letter_combination.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.