instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write proper docstrings for these functions |
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Literal
import anyio
from mcp.shared.experimental.tasks.resolver import Resolver
from mcp.types import JSONRPCNotification, JSONRPCRequest, Reques... | --- +++ @@ -1,3 +1,15 @@+"""TaskMessageQueue - FIFO queue for task-related messages.
+
+This implements the core message queue pattern from the MCP Tasks spec.
+When a handler needs to send a request (like elicitation) during a task-augmented
+request, the message is enqueued instead of sent directly. Messages are deli... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/message_queue.py |
Write docstrings for data processing functions |
from __future__ import annotations
from typing import Annotated, Any, Literal
from pydantic import BaseModel, Field, TypeAdapter
RequestId = Annotated[int, Field(strict=True)] | str
"""The ID of a JSON-RPC request."""
class JSONRPCRequest(BaseModel):
jsonrpc: Literal["2.0"]
id: RequestId
method: str
... | --- +++ @@ -1,3 +1,4 @@+"""This module follows the JSON-RPC 2.0 specification: https://www.jsonrpc.org/specification."""
from __future__ import annotations
@@ -10,6 +11,7 @@
class JSONRPCRequest(BaseModel):
+ """A JSON-RPC request that expects a response."""
jsonrpc: Literal["2.0"]
id: RequestId... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/types/jsonrpc.py |
Add docstrings that explain purpose and usage | from __future__ import annotations
from datetime import datetime
from typing import Annotated, Any, Final, Generic, Literal, TypeAlias, TypeVar
from pydantic import BaseModel, ConfigDict, Field, FileUrl, TypeAdapter
from pydantic.alias_generators import to_camel
from typing_extensions import NotRequired, TypedDict
f... | --- +++ @@ -37,6 +37,7 @@
class MCPModel(BaseModel):
+ """Base class for all MCP protocol types."""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
@@ -55,6 +56,10 @@
class TaskMetadata(MCPModel):
+ """Metadata for augmenting a request with task execution.
+
+ Includ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/types/_types.py |
Document this script properly | from __future__ import annotations
import logging
from collections.abc import Callable
from contextlib import AsyncExitStack
from types import TracebackType
from typing import Any, Generic, Protocol, TypeVar
import anyio
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from pydantic ... | --- +++ @@ -46,6 +46,7 @@
class ProgressFnT(Protocol):
+ """Protocol for progress notification callbacks."""
async def __call__(
self, progress: float, total: float | None, message: str | None
@@ -53,6 +54,22 @@
class RequestResponder(Generic[ReceiveRequestT, SendResultT]):
+ """Handles re... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/session.py |
Write docstrings including parameters and return values | # core/registration.py
from .execution import FunctionExecutor
import inspect
import ast
from typing import Optional, List, Dict, Any, Union
import logging
import json
logger = logging.getLogger(__name__)
class FunctionRegistrar:
def __init__(self, python_func):
self.python_func = python_func
def re... | --- +++ @@ -18,6 +18,7 @@ dependencies: Optional[List[str]] = None,
triggers: Optional[List[str]] = None,
key_dependencies: Optional[List[str]] = None):
+ """Decorator to register a function."""
def decorator(func):
... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/core/registration.py |
Write docstrings for utility functions | # local_db.py
from sqlalchemy import create_engine, or_
from sqlalchemy.orm import sessionmaker, scoped_session, joinedload
from sqlalchemy.exc import SQLAlchemyError
from contextlib import contextmanager
from .models import Base, Function, FunctionVersion, Import, Log, SecretKey, fernet
import datetime
class Local... | --- +++ @@ -28,6 +28,10 @@ self.Session.remove()
def serialize_for_json(self, obj):
+ """
+ Recursively convert datetime objects to ISO format strings within the given object.
+ Handles dictionaries, lists, and individual datetime objects.
+ """
if isinstance(obj,... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/db/local_db.py |
Write reusable docstrings | from functionz import func
# Initialize the Airtable Table instance
@func.register_function(
metadata={"description": "Initialize Airtable table instance with access token, base ID, and table name."},
key_dependencies=["airtable_access_token"],
imports=["pyairtable"]
)
def init_airtable(base_id, table_name... | --- +++ @@ -7,6 +7,12 @@ imports=["pyairtable"]
)
def init_airtable(base_id, table_name):
+ """
+ Initialize the Airtable Table instance.
+ :param base_id: ID of the Airtable base
+ :param table_name: Name of the table within the base
+ :return: Airtable Table instance
+ """
api_token = glo... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/plugins/airtable.py |
Improve documentation using docstrings | from babyagi.functionz.core.framework import func
@func.register_function(
metadata={"description": "Generate parameters for Augie creation using GPT."},
dependencies=["gpt_call"]
)
def generate_augie_params(user_input, voice_id="29vD33N1CtxCmqQRPOHJ"):
prompt = (
"You are creating parameters for a video g... | --- +++ @@ -5,6 +5,16 @@ dependencies=["gpt_call"]
)
def generate_augie_params(user_input, voice_id="29vD33N1CtxCmqQRPOHJ"):
+ """
+ This function generates JSON parameters for creating an Augie video.
+ It uses GPT to structure the user input into the required format, keeping the default voice_id.
+
+ Paramete... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/plugins/augie.py |
Document my Python code with docstrings | # 1. Crawl a website and initiate a crawl job.
@func.register_function(
metadata={"description": "Submits a crawl job for a website and returns a job ID."},
key_dependencies=["firecrawl_api_key"],
imports={"name":"firecrawl","lib":"firecrawl-py"}
)
def crawl_website(url: str, limit: int = 100, formats: list... | --- +++ @@ -5,6 +5,9 @@ imports={"name":"firecrawl","lib":"firecrawl-py"}
)
def crawl_website(url: str, limit: int = 100, formats: list = ["markdown", "html"], poll_interval: int = 30):
+ """
+ Submits a crawl job for the given URL and returns the crawl job status and job ID.
+ """
from firecrawl im... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/plugins/firecrawl.py |
Write docstrings for algorithm functions | @func.register_function(
metadata={"description": "Get an authentication token using the Wokelo API credentials."},
key_dependencies=["wokelo_username", "wokelo_password"],
imports=[{"name": "requests", "lib": "requests"}]
)
def get_auth_token():
import requests
BASE_URL = 'https://api.wokelo.ai'
url = BASE... | --- +++ @@ -4,6 +4,7 @@ imports=[{"name": "requests", "lib": "requests"}]
)
def get_auth_token():
+ """Obtain an authentication token using Wokelo API credentials stored as secrets."""
import requests
BASE_URL = 'https://api.wokelo.ai'
url = BASE_URL + '/auth/token'
@@ -33,6 +34,7 @@ imports=[{"name": "... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/plugins/wokelo.py |
Add structured docstrings to improve clarity | @func.register_function(
metadata={"description": "Search for a contact by name and domain using VoilaNorbert's API."},
key_dependencies=["voilanorbert_api_key"],
imports=["requests", "time"]
)
def search_contact_by_name_domain(name, domain):
api_key = globals().get('voilanorbert_api_key')
if not api_key:
... | --- +++ @@ -4,6 +4,16 @@ imports=["requests", "time"]
)
def search_contact_by_name_domain(name, domain):
+ """
+ Searches for a contact by name and domain using the VoilaNorbert API.
+
+ Args:
+ name (str): Full name of the person to search.
+ domain (str): Domain of the company the person works for.
+... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/plugins/voilanorbert.py |
Add docstrings to make code maintainable |
from functionz.core.framework import func
# Function 1: Fetch existing functions
@func.register_function(
metadata={"description": "Fetch existing functions using display_functions_wrapper."},
dependencies=["display_functions_wrapper"],
imports=[
{"name": "json", "lib": "json"}
]
)
def fetch_e... | --- +++ @@ -10,6 +10,15 @@ ]
)
def fetch_existing_functions(description: str) -> dict:
+ """
+ Fetches existing functions and returns them along with the initial intermediate_steps.
+
+ Args:
+ description (str): User description of the function to generate.
+
+ Returns:
+ dict: A dictio... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/drafts/generate_function.py |
Document all endpoints with docstrings | # Harmonic API Functions Pack for Functionz Framework
@func.register_function(
metadata={"description": "Fetch a company's enrichment data using its identifier (URL or domain)."},
key_dependencies=["harmonic_api_key"],
imports=[{"name": "requests", "lib": "requests"}]
)
def harmonic_enrich_company(identif... | --- +++ @@ -7,6 +7,10 @@ imports=[{"name": "requests", "lib": "requests"}]
)
def harmonic_enrich_company(identifier):
+ """
+ Enrich a company using its URL, domain, or identifier.
+ Returns the full response from Harmonic API.
+ """
api_key = globals()['harmonic_api_key']
url = "https://api... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/plugins/harmonic.py |
Add docstrings to improve code quality | from __future__ import annotations
import functools
import inspect
from collections.abc import Callable
from functools import cached_property
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel, Field
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.mcpserver.utilities.context_i... | --- +++ @@ -21,6 +21,7 @@
class Tool(BaseModel):
+ """Internal tool registration info."""
fn: Callable[..., Any] = Field(exclude=True)
name: str = Field(description="Name of the tool")
@@ -53,6 +54,7 @@ meta: dict[str, Any] | None = None,
structured_output: bool | None = None,
)... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/tools/base.py |
Add docstrings to improve readability | import babyagi
@babyagi.register_function(
metadata={"description": "Executes AI-generated Python code in a secure E2B sandbox."},
imports=["e2b_code_interpreter"],
key_dependencies=["e2b_api_key"]
)
def execute_code_in_sandbox(code: str):
from e2b_code_interpreter import CodeInterpreter
with Co... | --- +++ @@ -6,6 +6,12 @@ key_dependencies=["e2b_api_key"]
)
def execute_code_in_sandbox(code: str):
+ """
+ This function initializes an E2B sandbox and executes AI-generated Python code within it.
+
+ :param code: Python code to be executed.
+ :return: Results and logs from the code execution.
+ "... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/plugins/e2b.py |
Add docstrings to improve collaboration |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from mcp.server.mcpserver.prompts.base import Message, Prompt
from mcp.server.mcpserver.utilities.logging import get_logger
if TYPE_CHECKING:
from mcp.server.context import LifespanContextT, RequestT
from mcp.server.mcpserver.context i... | --- +++ @@ -1,3 +1,4 @@+"""Prompt management functionality."""
from __future__ import annotations
@@ -14,21 +15,25 @@
class PromptManager:
+ """Manages MCPServer prompts."""
def __init__(self, warn_on_duplicate_prompts: bool = True):
self._prompts: dict[str, Prompt] = {}
self.warn_o... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/prompts/manager.py |
Document this module using docstrings |
from __future__ import annotations
import inspect
from collections.abc import Awaitable, Callable, Sequence
from typing import TYPE_CHECKING, Any, Literal
import pydantic_core
from pydantic import BaseModel, Field, TypeAdapter, validate_call
from mcp.server.mcpserver.utilities.context_injection import find_context_... | --- +++ @@ -1,3 +1,4 @@+"""Base classes for MCPServer prompts."""
from __future__ import annotations
@@ -18,6 +19,7 @@
class Message(BaseModel):
+ """Base class for all prompt messages."""
role: Literal["user", "assistant"]
content: ContentBlock
@@ -29,6 +31,7 @@
class UserMessage(Message):
... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/prompts/base.py |
Generate NumPy-style docstrings |
from mcp.shared.exceptions import MCPError
from mcp.types import INVALID_REQUEST, ClientCapabilities, ClientTasksCapability
def check_tasks_capability(
required: ClientTasksCapability,
client: ClientTasksCapability,
) -> bool:
if required.requests is None:
return True
if client.requests is No... | --- +++ @@ -1,3 +1,11 @@+"""Tasks capability checking utilities.
+
+This module provides functions for checking and requiring task-related
+capabilities. All tasks capability logic is centralized here to keep
+the main session code clean.
+
+WARNING: These APIs are experimental and may change without notice.
+"""
fr... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/capabilities.py |
Add professional docstrings to my codebase |
import time
from urllib.parse import urlparse, urlsplit, urlunsplit
from pydantic import AnyUrl, HttpUrl
def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:
# Convert to string if needed
url_str = str(url)
# Parse the URL and remove fragment, create canonical form
parsed = urlspli... | --- +++ @@ -1,3 +1,4 @@+"""Utilities for OAuth 2.0 Resource Indicators (RFC 8707) and PKCE (RFC 7636)."""
import time
from urllib.parse import urlparse, urlsplit, urlunsplit
@@ -6,6 +7,17 @@
def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:
+ """Convert server URL to canonical resource UR... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/auth_utils.py |
Create documentation strings for testing functions |
from abc import ABC, abstractmethod
from mcp.types import Result, Task, TaskMetadata, TaskStatus
class TaskStore(ABC):
@abstractmethod
async def create_task(
self,
metadata: TaskMetadata,
task_id: str | None = None,
) -> Task:
@abstractmethod
async def get_task(self, ta... | --- +++ @@ -1,3 +1,4 @@+"""TaskStore - Abstract interface for task state storage."""
from abc import ABC, abstractmethod
@@ -5,6 +6,13 @@
class TaskStore(ABC):
+ """Abstract interface for task state storage.
+
+ This is a pure storage interface - it doesn't manage execution.
+ Implementations can use ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/store.py |
Add docstrings that explain logic |
from dataclasses import dataclass
from typing import Any, Generic
from typing_extensions import TypeVar
from mcp.shared.session import BaseSession
from mcp.types import RequestId, RequestParamsMeta
SessionT = TypeVar("SessionT", bound=BaseSession[Any, Any, Any, Any, Any])
@dataclass(kw_only=True)
class RequestCon... | --- +++ @@ -1,3 +1,4 @@+"""Request context for MCP handlers."""
from dataclasses import dataclass
from typing import Any, Generic
@@ -12,7 +13,12 @@
@dataclass(kw_only=True)
class RequestContext(Generic[SessionT]):
+ """Common context for handling incoming requests.
+
+ For request handlers, request_id is ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/_context.py |
Fill in missing docstrings in my code |
from typing import Any, Protocol
import httpx
__all__ = ["create_mcp_http_client", "MCP_DEFAULT_TIMEOUT", "MCP_DEFAULT_SSE_READ_TIMEOUT"]
# Default MCP timeout configuration
MCP_DEFAULT_TIMEOUT = 30.0 # General operations (seconds)
MCP_DEFAULT_SSE_READ_TIMEOUT = 300.0 # SSE streams - 5 minutes (seconds)
class M... | --- +++ @@ -1,3 +1,4 @@+"""Utilities for creating standardized httpx AsyncClient instances."""
from typing import Any, Protocol
@@ -24,6 +25,58 @@ timeout: httpx.Timeout | None = None,
auth: httpx.Auth | None = None,
) -> httpx.AsyncClient:
+ """Create a standardized httpx AsyncClient with MCP default... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/_httpx_utils.py |
Write proper docstrings for these functions |
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any
from mcp.types import JSONRPCMessage, RequestId
ResumptionToken = str
ResumptionTokenUpdateCallback = Callable[[ResumptionToken], Awaitable[None]]
# Callback type for closing SSE streams without terminating
Clo... | --- +++ @@ -1,3 +1,8 @@+"""Message wrapper with metadata support.
+
+This module defines a wrapper type that combines JSONRPCMessage with metadata
+to support transport-specific features like resumability.
+"""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
@@ -15,6 +20,7 @@
@da... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/message.py |
Generate consistent docstrings |
from mcp.shared.exceptions import MCPError
from mcp.types import INVALID_PARAMS, ClientCapabilities, SamplingMessage, Tool, ToolChoice
def check_sampling_tools_capability(client_caps: ClientCapabilities | None) -> bool:
if client_caps is None:
return False
if client_caps.sampling is None:
ret... | --- +++ @@ -1,9 +1,22 @@+"""Shared validation functions for server requests.
+
+This module provides validation logic for sampling and elicitation requests
+that is shared across normal and task-augmented code paths.
+"""
from mcp.shared.exceptions import MCPError
from mcp.types import INVALID_PARAMS, ClientCapabil... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/validation.py |
Document helper functions with docstrings | from typing import Any, Literal
from pydantic import AnyHttpUrl, AnyUrl, BaseModel, Field, field_validator
class OAuthToken(BaseModel):
access_token: str
token_type: Literal["Bearer"] = "Bearer"
expires_in: int | None = None
scope: str | None = None
refresh_token: str | None = None
@field_v... | --- +++ @@ -4,6 +4,7 @@
class OAuthToken(BaseModel):
+ """See https://datatracker.ietf.org/doc/html/rfc6749#section-5.1"""
access_token: str
token_type: Literal["Bearer"] = "Bearer"
@@ -32,6 +33,9 @@
class OAuthClientMetadata(BaseModel):
+ """RFC 7591 OAuth 2.0 Dynamic Client Registration Meta... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/auth.py |
Write docstrings for this repository |
from mcp.types import Implementation, Prompt, Resource, ResourceTemplate, Tool
def get_display_name(obj: Tool | Resource | Prompt | ResourceTemplate | Implementation) -> str:
if isinstance(obj, Tool):
# Tools have special precedence: title > annotations.title > name
if hasattr(obj, "title") and o... | --- +++ @@ -1,8 +1,37 @@+"""Utility functions for working with metadata in MCP types.
+
+These utilities are primarily intended for client-side usage to properly display
+human-readable names in user interfaces in a spec-compliant way.
+"""
from mcp.types import Implementation, Prompt, Resource, ResourceTemplate, To... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/metadata_utils.py |
Create docstrings for reusable components | # self_build.py
from functionz.core.framework import func
import json
@func.register_function(
metadata={"description": "Generates queries based on user description"},
dependencies=["gpt_call"],
imports=["json"]
)
def generate_queries(user_description, X=3, max_retries=3):
prompt = f"""
You are an AI ... | --- +++ @@ -9,6 +9,20 @@ imports=["json"]
)
def generate_queries(user_description, X=3, max_retries=3):
+ """
+ Generates X distinct queries that require action based on the user description using gpt_call.
+
+ Args:
+ user_description (str): Description of the user or their needs.
+ X (in... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/functionz/packs/drafts/self_build.py |
Add docstrings for better understanding | from __future__ import annotations
from typing import Any, cast
from mcp.types import URL_ELICITATION_REQUIRED, ElicitRequestURLParams, ErrorData, JSONRPCError
class MCPError(Exception):
error: ErrorData
def __init__(self, code: int, message: str, data: Any = None):
super().__init__(code, message,... | --- +++ @@ -6,6 +6,7 @@
class MCPError(Exception):
+ """Exception type raised when an error arrives over an MCP connection."""
error: ErrorData
@@ -41,6 +42,12 @@
class StatelessModeNotSupported(RuntimeError):
+ """Raised when attempting to use a method that is not supported in stateless mode.
+
... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/exceptions.py |
Create documentation for each function signature | from __future__ import annotations # Just in case
import json
from typing import Any, Optional, List, Union, Dict
import warnings
import numpy as np
from requests import Session, Response, exceptions
import pandas as pd
from datetime import datetime, date, timedelta
from .const import _QUERY1_URL_
from .utils import l... | --- +++ @@ -15,20 +15,58 @@
class CalendarQuery:
+ """
+ Simple CalendarQuery class for calendar queries, similar to yf.screener.query.QueryBase.
+
+ Simple operand accepted by YF is of the form:
+ `{ "operator": operator, "operands": [field, ...values] }`
+
+ Nested operand accepted by YF:
+ ... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/calendars.py |
Add docstrings to clarify complex logic | import peewee as _peewee
from threading import Lock
import os as _os
import platformdirs as _ad
import atexit as _atexit
import datetime as _dt
import pickle as _pkl
from .utils import get_yf_logger
_cache_init_lock = Lock()
# --------------
# TimeZone cache
# --------------
class _TzCacheException(Exception):
... | --- +++ @@ -21,6 +21,7 @@
class _TzCacheDummy:
+ """Dummy cache to use if tz cache is disabled"""
def lookup(self, tkr):
return None
@@ -215,6 +216,7 @@
class _CookieCacheDummy:
+ """Dummy cache to use if Cookie cache is disabled"""
def lookup(self, tkr):
return None
@@ -42... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/cache.py |
Write docstrings describing each step | import pandas as pd
from typing import Dict, Optional
from yfinance import utils
from yfinance.config import YfConfig
from yfinance.const import _BASE_URL_
from yfinance.data import YfData
from yfinance.exceptions import YFDataException
_QUOTE_SUMMARY_URL_ = f"{_BASE_URL_}/v10/finance/quoteSummary/"
class FundsData:... | --- +++ @@ -10,7 +10,19 @@ _QUOTE_SUMMARY_URL_ = f"{_BASE_URL_}/v10/finance/quoteSummary/"
class FundsData:
+ """
+ ETF and Mutual Funds Data
+ Queried Modules: quoteType, summaryProfile, fundProfile, topHoldings
+
+ Notes:
+ - fundPerformance module is not implemented as better data is queryable usi... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/scrapers/funds.py |
Generate docstrings for this script | import functools
from functools import lru_cache
import socket
import time as _time
from curl_cffi import requests
from urllib.parse import urlsplit, urljoin
from bs4 import BeautifulSoup
import datetime
from frozendict import frozendict
from . import utils, cache
from .config import YfConfig
import threading
from ... | --- +++ @@ -18,6 +18,7 @@
def _is_transient_error(exception):
+ """Check if error is transient (network/timeout) and should be retried."""
if isinstance(exception, (TimeoutError, socket.error, OSError)):
return True
error_type_name = type(exception).__name__
@@ -31,6 +32,10 @@
def lru_cach... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/data.py |
Add docstrings following best practices | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | --- +++ @@ -53,6 +53,18 @@
class TickerBase:
def __init__(self, ticker, session=None):
+ """
+ Initialize a Yahoo Finance Ticker object.
+
+ Args:
+ ticker (str | tuple[str, str]):
+ Yahoo Finance symbol (e.g. "AAPL")
+ or a tuple of (symbol, MIC) e.g... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/base.py |
Help me write clear docstrings | from __future__ import print_function
import pandas as _pd
from typing import Dict, Optional
from .. import utils
from ..config import YfConfig
from ..data import YfData
from .domain import Domain, _QUERY_URL_
class Industry(Domain):
def __init__(self, key, session=None):
YfData(session=session)
... | --- +++ @@ -10,8 +10,16 @@ from .domain import Domain, _QUERY_URL_
class Industry(Domain):
+ """
+ Represents an industry within a sector.
+ """
def __init__(self, key, session=None):
+ """
+ Args:
+ key (str): The key identifier for the industry.
+ session (option... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/domain/industry.py |
Write docstrings for utility functions | from abc import ABC, abstractmethod
import pandas as _pd
from typing import Dict, List, Optional
from ..const import _QUERY1_URL_
from ..data import YfData
from ..ticker import Ticker
_QUERY_URL_ = f'{_QUERY1_URL_}/v1/finance'
class Domain(ABC):
def __init__(self, key: str, session=None):
self._key: str... | --- +++ @@ -9,8 +9,19 @@ _QUERY_URL_ = f'{_QUERY1_URL_}/v1/finance'
class Domain(ABC):
+ """
+ Abstract base class representing a domain entity in financial data, with key attributes
+ and methods for fetching and parsing data. Derived classes must implement the `_fetch_and_parse()` method.
+ """
... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/domain/domain.py |
Create structured documentation for my script | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | --- +++ @@ -255,12 +255,29 @@
def build_template(data):
+ """
+ build_template returns the details required to rebuild any of the yahoo finance financial statements in the same order as the yahoo finance webpage. The function is built to be used on the "FinancialTemplateStore" json which appears in any one of... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/utils.py |
Generate docstrings for each module | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | --- +++ @@ -32,6 +32,15 @@
class Lookup:
+ """
+ Fetches quote (ticker) lookups from Yahoo Finance.
+
+ :param query: The search query for financial data lookup.
+ :type query: str
+ :param session: Custom HTTP session for requests (default None).
+ :param timeout: Request timeout in seconds (defa... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/lookup.py |
Add docstrings for production code | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | --- +++ @@ -32,6 +32,24 @@ def __init__(self, query, max_results=8, news_count=8, lists_count=8, include_cb=True, include_nav_links=False,
include_research=False, include_cultural_assets=False, enable_fuzzy_query=False, recommended=8,
session=None, timeout=30, raise_errors=True):... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/search.py |
Write docstrings for backend logic | from abc import ABC, abstractmethod
import numbers
from typing import List, Union, Dict, TypeVar, Tuple
from yfinance.const import EQUITY_SCREENER_EQ_MAP, EQUITY_SCREENER_FIELDS
from yfinance.const import FUND_SCREENER_EQ_MAP, FUND_SCREENER_FIELDS
from yfinance.exceptions import YFNotImplementedError
from ..utils impo... | --- +++ @@ -136,25 +136,83 @@
class EquityQuery(QueryBase):
+ """
+ The `EquityQuery` class constructs filters for stocks based on specific criteria such as region, sector, exchange, and peer group.
+
+ Start with value operations: `EQ` (equals), `IS-IN` (is in), `BTWN` (between), `GT` (greater than), `LT`... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/screener/query.py |
Include argument descriptions in docstrings | from __future__ import print_function
import pandas as _pd
from typing import Dict, Optional
from ..config import YfConfig
from ..const import SECTOR_INDUSTY_MAPPING_LC
from ..utils import dynamic_docstring, generate_list_table_from_dict, get_yf_logger
from .domain import Domain, _QUERY_URL_
class Sector(Domain):
... | --- +++ @@ -10,8 +10,22 @@ from .domain import Domain, _QUERY_URL_
class Sector(Domain):
+ """
+ Represents a financial market sector and allows retrieval of sector-related data
+ such as top ETFs, top mutual funds, and industry data.
+ """
def __init__(self, key, session=None):
+ """
+ ... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/domain/sector.py |
Add missing documentation to my Python functions | import asyncio
import base64
import json
from typing import List, Optional, Callable, Union
from websockets.sync.client import connect as sync_connect
from websockets.asyncio.client import connect as async_connect
from yfinance import utils
from yfinance.config import YfConfig
from yfinance.pricing_pb2 import Pricing... | --- +++ @@ -40,8 +40,18 @@
class AsyncWebSocket(BaseWebSocket):
+ """
+ Asynchronous WebSocket client for streaming real time pricing data.
+ """
def __init__(self, url: str = "wss://streamer.finance.yahoo.com/?version=2", verbose=True):
+ """
+ Initialize the AsyncWebSocket client.
+
... | https://raw.githubusercontent.com/ranaroussi/yfinance/HEAD/yfinance/live.py |
Improve my code by adding docstrings | import os
import json
import copy
import math
import random
import re
from .utils import *
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
################### check title in page #########################################################
async def check_title_appearance(item, page_list, start... | --- +++ @@ -487,6 +487,10 @@
def remove_first_physical_index_section(text):
+ """
+ Removes the first section between <physical_index_X> and <physical_index_X> tags,
+ and returns the remaining text.
+ """
pattern = r'<physical_index_\d+>.*?<physical_index_\d+>'
match = re.search(pattern, text... | https://raw.githubusercontent.com/VectifyAI/PageIndex/HEAD/pageindex/page_index.py |
Write docstrings for this repository | import tiktoken
import openai
import logging
import os
from datetime import datetime
import time
import json
import PyPDF2
import copy
import asyncio
import pymupdf
from io import BytesIO
from dotenv import load_dotenv
load_dotenv()
import logging
import yaml
from pathlib import Path
from types import SimpleNamespace a... | --- +++ @@ -349,6 +349,7 @@
def list_to_tree(data):
def get_parent_structure(structure):
+ """Helper function to get the parent structure code"""
if not structure:
return None
parts = str(structure).split('.')
@@ -623,6 +624,10 @@
def create_clean_structure_for_descripti... | https://raw.githubusercontent.com/VectifyAI/PageIndex/HEAD/pageindex/utils.py |
Add docstrings for better understanding | from typing import Any, Tuple
import wx # type: ignore
# wx.html and wx.xml imports required here to make packaging with
# pyinstaller on OSX possible without manually specifying `hidden_imports`
# in the build.spec
import wx.html # type: ignore
import wx.lib.inspection # type: ignore
import wx.richtext # type: ig... | --- +++ @@ -1,3 +1,6 @@+'''
+Main runner entry point for Gooey.
+'''
from typing import Any, Tuple
import wx # type: ignore
@@ -27,6 +30,10 @@
def _build_app(build_spec, app) -> Tuple[Any, wx.Frame]:
+ """
+ Note: this method is broken out with app as
+ an argument to facilitate testing.
+ """
... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/bootstrap.py |
Write proper docstrings for these functions | from functools import wraps
import wx # type: ignore
from contextlib import contextmanager
from gooey.gui.three_to_four import Constants
def callafter(f):
@wraps(f)
def inner(*args, **kwargs):
wx.CallAfter(f, *args, **kwargs)
return inner
@contextmanager
def transactUI(obj):
obj.Freeze()
... | --- +++ @@ -1,86 +1,96 @@-from functools import wraps
-
-import wx # type: ignore
-from contextlib import contextmanager
-
-from gooey.gui.three_to_four import Constants
-
-
-def callafter(f):
- @wraps(f)
- def inner(*args, **kwargs):
- wx.CallAfter(f, *args, **kwargs)
- return inner
-
-
-@contextmanag... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/util/wx_util.py |
Write docstrings describing each step | import re
from functools import reduce
from typing import Optional, Callable, Any, Type, Union
import wx # type: ignore
from gooey.gui import formatters, events
from gooey.gui.util import wx_util
from gooey.python_bindings.types import FormField
from gooey.util.functional import getin, ifPresent
from gooey.gui.valid... | --- +++ @@ -1,266 +1,271 @@-import re
-from functools import reduce
-from typing import Optional, Callable, Any, Type, Union
-
-import wx # type: ignore
-
-from gooey.gui import formatters, events
-from gooey.gui.util import wx_util
-from gooey.python_bindings.types import FormField
-from gooey.util.functional import ... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/widgets/bases.py |
Document classes and their methods | import sys
import wx # type: ignore
from gooey.gui import events
from gooey.gui.lang.i18n import _
from gooey.gui.pubsub import pub
from gooey.gui.components.mouse import notifyMouseEvent
class Footer(wx.Panel):
def __init__(self, parent, buildSpec, **kwargs):
wx.Panel.__init__(self, parent, **kwargs)
... | --- +++ @@ -1,150 +1,160 @@-import sys
-import wx # type: ignore
-
-from gooey.gui import events
-from gooey.gui.lang.i18n import _
-from gooey.gui.pubsub import pub
-from gooey.gui.components.mouse import notifyMouseEvent
-
-
-class Footer(wx.Panel):
-
- def __init__(self, parent, buildSpec, **kwargs):
- wx... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/footer.py |
Generate docstrings for script automation | import wx # type: ignore
from gooey.gui.pubsub import pub
from gooey.gui import events
class Timing(object):
def __init__(self, parent):
self.startTime = 0
self.estimatedRemaining = None
self.wxTimer = wx.Timer(parent)
self.parent = parent
parent.Bind(wx.EVT_TIMER, self.pu... | --- +++ @@ -1,3 +1,6 @@+"""
+Module for evaluating time elapsed & time remaining from progress
+"""
import wx # type: ignore
from gooey.gui.pubsub import pub
from gooey.gui import events
@@ -38,6 +41,17 @@ self.wxTimer.Stop()
def format_interval(timeValue):
+ """
+ Formats a number of seconds as a ... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/util/time.py |
Generate docstrings for this script | import wx # type: ignore
from collections import defaultdict
__ALL__ = ['pub']
class PubSub(object):
def __init__(self):
self.registry = defaultdict(list)
def subscribe(self, event, handler):
self.registry[event].append(handler)
def send_message(self, event, **kwargs):
for eve... | --- +++ @@ -1,23 +1,36 @@-import wx # type: ignore
-from collections import defaultdict
-
-__ALL__ = ['pub']
-
-
-class PubSub(object):
-
- def __init__(self):
- self.registry = defaultdict(list)
-
- def subscribe(self, event, handler):
- self.registry[event].append(handler)
-
- def send_message... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/pubsub.py |
Create simple docstrings for beginners | import queue
import sys
import threading
from contextlib import contextmanager
from functools import wraps
from json import JSONDecodeError
from pprint import pprint
from subprocess import CalledProcessError
from threading import Thread, get_ident
from typing import Mapping, Dict, Type, Iterable
import six
import wx ... | --- +++ @@ -1,409 +1,446 @@-import queue
-import sys
-import threading
-from contextlib import contextmanager
-from functools import wraps
-from json import JSONDecodeError
-from pprint import pprint
-from subprocess import CalledProcessError
-from threading import Thread, get_ident
-from typing import Mapping, Dict, T... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/containers/application.py |
Document this module using docstrings | from argparse import ArgumentParser, _SubParsersAction, _MutuallyExclusiveGroup
from functools import wraps
from typing import Union, Any, Mapping, Dict, Callable
from gooey.python_bindings.types import Success, Failure, Try, InvalidChoiceException
from gooey.python_bindings.argparse_to_json import is_subparser
from g... | --- +++ @@ -1,3 +1,27 @@+"""
+All things Dynamic Updates & Validation.
+
+Hear me all ye who enter!
+=========================
+
+This is a module of disgusting hacks and monkey patching. Control flow
+is all over the place and a comprised of hodgepodge of various strategies.
+This is all because Argparse's internal pa... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/dynamics.py |
Fill in missing docstrings in my code | import wx # type: ignore
from wx.lib.wordwrap import wordwrap # type: ignore
class AutoWrappedStaticText(wx.StaticText):
def __init__(self, parent, *args, **kwargs):
self.target = kwargs.pop('target', None)
super(AutoWrappedStaticText, self).__init__(parent, *args, **kwargs)
self.label... | --- +++ @@ -1,43 +1,97 @@-import wx # type: ignore
-from wx.lib.wordwrap import wordwrap # type: ignore
-
-
-
-class AutoWrappedStaticText(wx.StaticText):
-
- def __init__(self, parent, *args, **kwargs):
- self.target = kwargs.pop('target', None)
- super(AutoWrappedStaticText, self).__init__(parent, ... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/util/wrapped_static_text.py |
Fully document this Python code with docstrings | import argparse
import json
import os
import sys
from argparse import (
_CountAction,
_HelpAction,
_StoreConstAction,
_StoreFalseAction,
_StoreTrueAction,
_StoreAction,
_SubParsersAction,
_VersionAction, _MutuallyExclusiveGroup)
from collections import OrderedDict
from functools import p... | --- +++ @@ -1,557 +1,684 @@-import argparse
-import json
-import os
-import sys
-from argparse import (
- _CountAction,
- _HelpAction,
- _StoreConstAction,
- _StoreFalseAction,
- _StoreTrueAction,
- _StoreAction,
- _SubParsersAction,
- _VersionAction, _MutuallyExclusiveGroup)
-from collections i... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/argparse_to_json.py |
Document classes and their methods | import json
from base64 import b64encode
from typing import Optional, List, Dict, Any, Union, Callable
from typing_extensions import TypedDict
import wx
from gooey.gui import events
from gooey.gui.lang.i18n import _
from gooey.python_bindings.types import GooeyParams, Item, Group, TopLevelParser, EnrichedItem, \
... | --- +++ @@ -182,6 +182,11 @@
def combine(state: GooeyState, params: GooeyParams, formState: List[FormField]) -> FullGooeyState:
+ """
+ I'm leaving the refactor of the form elements to another day.
+ For now, we'll just merge in the state of the form fields as tracked
+ in the UI into the main state blo... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/state.py |
Add docstrings to existing functions | import sys
import signal
from textwrap import dedent
def requires_special_handler(platform, requested_signal):
return platform.startswith("win") and requested_signal == signal.CTRL_C_EVENT
def install_handler():
assert sys.platform.startswith("win")
import ctypes
help_msg = dedent('''
Please op... | --- +++ @@ -1,13 +1,65 @@+"""
+Utilities for patching Windows so that CTRL-C signals
+can be received by process groups.
+
+The best resource for understanding why this is required is the Python
+Issue here: https://bugs.python.org/issue13368
+
+**The official docs from both Python and Microsoft cannot be trusted due t... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/signal_support.py |
Replace inline comments with docstrings |
import json
from base64 import b64decode
from typing import Dict, Any
from gooey.python_bindings.schema import validate_public_state
from gooey.python_bindings.types import PublicGooeyState
prefix = 'gooey::'
def serialize_outbound(out: PublicGooeyState):
return prefix + json.dumps(out)
def deserialize_inbou... | --- +++ @@ -1,3 +1,14 @@+"""
+Because Gooey communicates with the host program
+over stdin/out, we have to be able to differentiate what's
+coming from gooey and structured, versus what is arbitrary
+junk coming from the host's own logging.
+
+To do this, we just prefix all written by gooey with the
+literal string 'go... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/coms.py |
Add minimal docstrings for each function | import wx # type: ignore
import wx.richtext # type: ignore
import colored # type: ignore
import re
from gooey.python_bindings import types as t
kColorList = ["#000000", "#800000", "#008000", "#808000", "#000080", "#800080", "#008080", "#c0c0c0",
"#808080", "#ff0000", "#00ff00", "#ffff00", "#0000ff", "#ff00ff",... | --- +++ @@ -36,6 +36,9 @@ "#c6c6c6", "#d0d0d0", "#dadada", "#e4e4e4", "#eeeeee"]
class RichTextConsole(wx.richtext.RichTextCtrl):
+ """
+ An advanced rich test console panel supporting some Xterm control codes.
+ """
def __init__(self, parent):
super(wx.richtext.RichTextCtrl, self)._... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/widgets/richtextconsole.py |
Add clean documentation to messy code | import json
import os
import sys
import traceback
from argparse import ArgumentParser
from copy import deepcopy
from typing import List, Dict
from gooey.python_bindings.dynamics import monkey_patch_for_form_validation
from gooey.python_bindings.dynamics import patch_argument, collect_errors
from gooey.python_bindings.... | --- +++ @@ -1,3 +1,23 @@+"""
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!!!!!!!!!!!DEBUGGING NOTE!!!!!!!!!!!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+PyCharm will inject addition params into stdout when starting
+a new process. This can make debugging VERY VERY CONFUSING as
+the thing being injected starts complaining abou... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/control.py |
Generate consistent documentation across files | from contextlib import contextmanager
import wx # type: ignore
import wx.html # type: ignore
import gooey.gui.events as events
from gooey.gui.components.filtering.prefix_filter import PrefixSearch
from gooey.gui.components.mouse import notifyMouseEvent
from gooey.gui.components.widgets.dropdown import Dropdown
from... | --- +++ @@ -15,6 +15,36 @@
class FilterableDropdown(Dropdown):
+ """
+ TODO: tests for gooey_options
+ TODO: documentation
+ A dropdown with auto-complete / filtering behaviors.
+
+ This is largely a recreation of the `AutoComplete` functionality baked
+ into WX itself.
+
+ Background info:
+ ... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/widgets/dropdown_filterable.py |
Generate documentation strings for clarity | import wx # type: ignore
from typing_extensions import TypedDict
from gooey.gui.components.config import ConfigPage, TabbedConfigPage
from gooey.gui.components.console import Console
from gooey.gui.components.mouse import notifyMouseEvent
from gooey.gui.components.sidebar import Sidebar
from gooey.gui.components.tabb... | --- +++ @@ -1,3 +1,7 @@+"""
+Houses all the supporting rewx components for
+the main application window.
+"""
import wx # type: ignore
from typing_extensions import TypedDict
@@ -18,6 +22,10 @@
def attach_notifier(parent):
+ """
+ Recursively attaches the mouseEvent notifier
+ to all elements in the t... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/application/components.py |
Add detailed documentation for each class | import wx # type: ignore
import wx.lib.agw.multidirdialog as MDD # type: ignore
import os
import re
from gooey.gui.components.widgets.core.text_input import TextInput
from gooey.gui.components.widgets.dialogs.calender_dialog import CalendarDlg
from gooey.gui.components.widgets.dialogs.time_dialog import TimeDlg
from... | --- +++ @@ -1,172 +1,195 @@-import wx # type: ignore
-import wx.lib.agw.multidirdialog as MDD # type: ignore
-import os
-import re
-
-from gooey.gui.components.widgets.core.text_input import TextInput
-from gooey.gui.components.widgets.dialogs.calender_dialog import CalendarDlg
-from gooey.gui.components.widgets.dial... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/widgets/core/chooser.py |
Add docstrings that explain logic | import os
import sys
def is_frozen():
return getattr(sys, 'frozen', False)
def getResourcePath(*args):
if is_frozen():
# MEIPASS explanation:
# https://pythonhosted.org/PyInstaller/#run-time-operation
basedir = getattr(sys, '_MEIPASS', None)
if not basedir:
basedi... | --- +++ @@ -1,3 +1,9 @@+'''
+Utils for retrieving resources when when in a frozen state.
+
+MEIPASS explanation:
+https://pythonhosted.org/PyInstaller/#run-time-operation
+'''
import os
import sys
@@ -29,8 +35,13 @@
def localResourcePath(path):
+ """
+ A packaging aware util for getting the path to the lo... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/util/freeze.py |
Add docstrings that explain logic | from typing import Optional
import wx # type: ignore
from gooey.gui.components.widgets.bases import BaseWidget
from gooey.gui.lang.i18n import _
from gooey.gui.util import wx_util
from gooey.gui.components.widgets import CheckBox
from gooey.util.functional import getin, merge
from gooey.python_bindings import types a... | --- +++ @@ -1,189 +1,203 @@-from typing import Optional
-
-import wx # type: ignore
-from gooey.gui.components.widgets.bases import BaseWidget
-from gooey.gui.lang.i18n import _
-from gooey.gui.util import wx_util
-from gooey.gui.components.widgets import CheckBox
-from gooey.util.functional import getin, merge
-from ... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/widgets/radio_group.py |
Generate consistent documentation across files | import webbrowser
import wx # type: ignore
from gooey.gui.lang.i18n import _
from .widgets.basictextconsole import BasicTextConsole
class Console(wx.Panel):
self_managed = True
def __init__(self, parent, buildSpec, **kwargs):
wx.Panel.__init__(self, parent, name='console', **kwargs)
self.b... | --- +++ @@ -1,85 +1,104 @@-import webbrowser
-
-import wx # type: ignore
-
-from gooey.gui.lang.i18n import _
-from .widgets.basictextconsole import BasicTextConsole
-
-
-class Console(wx.Panel):
- self_managed = True
-
- def __init__(self, parent, buildSpec, **kwargs):
- wx.Panel.__init__(self, parent, n... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/console.py |
Document this code for team use | import wx # type: ignore
from gooey.gui.util import wx_util
class Sidebar(wx.Panel):
def __init__(self, parent, buildSpec, configPanels, *args, **kwargs):
super(Sidebar, self).__init__(parent, *args, **kwargs)
self._parent = parent
self.buildSpec = buildSpec
self.configPanels = c... | --- +++ @@ -1,77 +1,86 @@-import wx # type: ignore
-
-from gooey.gui.util import wx_util
-
-
-class Sidebar(wx.Panel):
- def __init__(self, parent, buildSpec, configPanels, *args, **kwargs):
- super(Sidebar, self).__init__(parent, *args, **kwargs)
- self._parent = parent
- self.buildSpec = buil... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/sidebar.py |
Add inline docstrings for readability | import sys
from json import JSONDecodeError
import six
import wx # type: ignore
from gooey import Events
from gooey.gui import events
from gooey.gui import host
from gooey.gui import state as s
from gooey.gui.application.components import RHeader, ProgressSpinner, ErrorWarning, RTabbedLayout, \
RSidebar, RFooter... | --- +++ @@ -34,6 +34,29 @@
class RGooey(Component):
+ """
+ Main Application container for Gooey.
+
+ State Management
+ ----------------
+
+ Pending further refactor, state is tracked in two places:
+ 1. On this instance (React style)
+ 2. In the WX Form Elements themselves[0]
+
+ As needed... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/application/application.py |
Fill in missing docstrings in my code |
from gooey.gui.pubsub import pub
import gooey.gui.events as events
def notifyMouseEvent(event):
# TODO: is there ever a situation where this wouldn't be skipped..?
event.Skip()
pub.send_message_sync(events.LEFT_DOWN, wxEvent=event) | --- +++ @@ -1,9 +1,28 @@+"""
+WxPython lacks window level event hooks. Meaning, there's no
+general way to subscribe to every mouse event that goes on within
+the application.
+
+To implement features which respond to clicks outside of their
+immediate scope, for instance, dropdowns, a workaround in the form
+of manual... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/mouse.py |
Annotate my code with docstrings | import sys
from argparse import ArgumentParser
from functools import wraps
from gooey.python_bindings.control import choose_hander
from gooey.python_bindings.parameters import gooey_params
from gooey.python_bindings.types import GooeyParams
IGNORE_COMMAND = '--ignore-gooey'
def Gooey(f=None, **gkwargs):
params:... | --- +++ @@ -1,28 +1,51 @@-import sys
-from argparse import ArgumentParser
-from functools import wraps
-
-from gooey.python_bindings.control import choose_hander
-from gooey.python_bindings.parameters import gooey_params
-from gooey.python_bindings.types import GooeyParams
-
-IGNORE_COMMAND = '--ignore-gooey'
-
-
-def ... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/gooey_decorator.py |
Add clean documentation to messy code | import subprocess
from json import JSONDecodeError
from subprocess import CalledProcessError
from gooey.python_bindings.types import Try, Success, Failure
from gooey.python_bindings.coms import deserialize_inbound
def communicate(cmd, encoding) -> Try:
try:
proc = subprocess.Popen(
cmd,
... | --- +++ @@ -1,22 +1,38 @@-import subprocess
-from json import JSONDecodeError
-from subprocess import CalledProcessError
-
-from gooey.python_bindings.types import Try, Success, Failure
-from gooey.python_bindings.coms import deserialize_inbound
-
-
-def communicate(cmd, encoding) -> Try:
- try:
- proc = subp... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/seeder.py |
Write docstrings for this repository | import re
from functools import wraps
from gooey.gui.components.filtering.prefix_filter import OperatorType
class SuperBool(object):
def __init__(self, value, rationale):
self.value = value
self.rationale = rationale
def __bool__(self):
return self.value
__nonzero__ = __bool__
... | --- +++ @@ -5,6 +5,10 @@
class SuperBool(object):
+ """
+ A boolean which keeps with it the rationale
+ for when it is false.
+ """
def __init__(self, value, rationale):
self.value = value
self.rationale = rationale
@@ -19,6 +23,13 @@
def lift(f):
+ """
+ Lifts a basic p... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/options/validators.py |
Write docstrings for this repository | from typing import Mapping, List
import wx # type: ignore
from wx.lib.scrolledpanel import ScrolledPanel # type: ignore
from gooey.gui.components.mouse import notifyMouseEvent
from gooey.gui.components.util.wrapped_static_text import AutoWrappedStaticText
from gooey.gui.lang.i18n import _
from gooey.gui.util import... | --- +++ @@ -1,257 +1,276 @@-from typing import Mapping, List
-
-import wx # type: ignore
-from wx.lib.scrolledpanel import ScrolledPanel # type: ignore
-
-from gooey.gui.components.mouse import notifyMouseEvent
-from gooey.gui.components.util.wrapped_static_text import AutoWrappedStaticText
-from gooey.gui.lang.i18n ... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/config.py |
Add missing documentation to my Python functions | import os
import re
import signal
import subprocess
import sys
from functools import partial
from threading import Thread
import psutil # type: ignore
from gooey.gui import events
from gooey.gui.pubsub import pub
from gooey.gui.util.casting import safe_float
from gooey.util.functional import unit, bind
from gooey.py... | --- +++ @@ -1,138 +1,163 @@-import os
-import re
-import signal
-import subprocess
-import sys
-from functools import partial
-from threading import Thread
-
-import psutil # type: ignore
-
-from gooey.gui import events
-from gooey.gui.pubsub import pub
-from gooey.gui.util.casting import safe_float
-from gooey.util.f... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/processor.py |
Write docstrings for backend logic |
from argparse import _SubParsersAction
def parse_cmd_args(self, args=None):
def prepare_to_read_cmd_args(item):
for action in item._actions:
if isinstance(action, _SubParsersAction):
action.save_dest = action.dest
if not action.dest:
action.dest = '_subparser'
else:
... | --- +++ @@ -1,55 +1,79 @@-
-from argparse import _SubParsersAction
-
-def parse_cmd_args(self, args=None):
-
- def prepare_to_read_cmd_args(item):
- for action in item._actions:
- if isinstance(action, _SubParsersAction):
- action.save_dest = action.dest
- if not action.dest:
- action.de... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/cmd_args.py |
Provide clean and structured docstrings | import re
import pygtrie as trie # type: ignore
from functools import reduce
__ALL__ = ('PrefixTokenizers', 'PrefixSearch')
class PrefixTokenizers:
# This string here is just an arbitrary long string so that
# re.split finds no matches and returns the entire phrase
ENTIRE_PHRASE = '::gooey/tokenizatio... | --- +++ @@ -39,6 +39,10 @@
class PrefixSearch(object):
+ """
+ A trie backed index for quickly finding substrings
+ in a list of options.
+ """
def __init__(self, choices, options={}, *args, **kwargs):
self.choices = sorted(filter(None, choices))
@@ -58,9 +62,24 @@ return sorted(... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/filtering/prefix_filter.py |
Generate helpful docstrings for debugging | import webbrowser
from functools import partial
import wx # type: ignore
from gooey.gui import three_to_four
from gooey.gui.components.dialogs import HtmlDialog
class MenuBar(wx.MenuBar):
def __init__(self, buildSpec, *args, **kwargs):
super(MenuBar,self).__init__(*args, **kwargs)
self.buildSp... | --- +++ @@ -1,67 +1,89 @@-import webbrowser
-from functools import partial
-
-import wx # type: ignore
-
-from gooey.gui import three_to_four
-from gooey.gui.components.dialogs import HtmlDialog
-
-
-class MenuBar(wx.MenuBar):
-
- def __init__(self, buildSpec, *args, **kwargs):
- super(MenuBar,self).__init__... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/menubar.py |
Add docstrings to improve readability |
import wx # type: ignore
from rewx import wsx
import rewx.components as c
from gooey.gui import imageutil, image_repository
from gooey.gui.util import wx_util
from gooey.gui.three_to_four import bitmapFromImage
from gooey.util.functional import getin
from gooey.gui.components.mouse import notifyMouseEvent
PAD_SIZE ... | --- +++ @@ -1,117 +1,126 @@-
-import wx # type: ignore
-from rewx import wsx
-import rewx.components as c
-
-from gooey.gui import imageutil, image_repository
-from gooey.gui.util import wx_util
-from gooey.gui.three_to_four import bitmapFromImage
-from gooey.util.functional import getin
-from gooey.gui.components.mou... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/header.py |
Add detailed documentation for each class | from gooey.gui.components.filtering.prefix_filter import PrefixTokenizers
def _include_layout_docs(f):
f.__doc__ = (f.__doc__ or '') + (LayoutOptions.__doc__ or '')
return f
def _include_global_option_docs(f):
_doc = """:param initial_value: Sets the initial value in the UI.
"""
f.__doc__ = (... | --- +++ @@ -3,17 +3,29 @@
def _include_layout_docs(f):
+ """
+ Combines the layout_options docsstring with the
+ wrapped function's doc string.
+ """
f.__doc__ = (f.__doc__ or '') + (LayoutOptions.__doc__ or '')
return f
def _include_global_option_docs(f):
+ """
+ Combines docstring... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/options/options.py |
Add docstrings for production code |
class ParserError(Exception):
pass
class ArgumentError(Exception):
pass
if __name__ == '__main__':
pass | --- +++ @@ -1,12 +1,19 @@-
-
-class ParserError(Exception):
- pass
-
-
-class ArgumentError(Exception):
- pass
-
-
-if __name__ == '__main__':
+'''
+Created on Feb 10, 2014
+
+@author: Chris
+'''
+
+
+class ParserError(Exception):
+ """Thrown when the parser can't find argparse functions the client code"""
... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/parser_exceptions.py |
Generate descriptive docstrings automatically | from typing import Optional, Tuple, List, Union, Mapping, Any, TypeVar, Generic, Dict
from dataclasses import dataclass
from typing_extensions import TypedDict
class MenuHtmlDialog(TypedDict):
type: str
menuTitle: str
caption: Optional[str]
html: str
class MenuLink(TypedDict):
type: str
menu... | --- +++ @@ -244,6 +244,12 @@
class FieldValue(TypedDict):
+ """
+ The current value of a widget in the UI.
+ TODO: Why are things like cmd and cli type tracked IN the
+ UI and returned as part of the getValue() call?
+ What the hell, young me?
+ """
id: str
cmd: Optional[str]
rawVal... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/python_bindings/types.py |
Add docstrings with type hints explained |
import io
import os
import json
__all__ = ['load', '_']
_DICTIONARY = None
def load(language_dir, filename, encoding):
global _DICTIONARY
try:
json_file = filename + '.json'
with io.open(os.path.join(language_dir, json_file), 'r', encoding=encoding) as f:
_DICTIONARY = json.load(f)
except IOErro... | --- +++ @@ -1,25 +1,34 @@-
-import io
-import os
-import json
-
-__all__ = ['load', '_']
-
-_DICTIONARY = None
-
-def load(language_dir, filename, encoding):
- global _DICTIONARY
- try:
- json_file = filename + '.json'
- with io.open(os.path.join(language_dir, json_file), 'r', encoding=encoding) as f:
- _D... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/lang/i18n.py |
Provide clean and structured docstrings | from gooey.gui.lang.i18n import _
import wx # type: ignore
from gooey.gui.three_to_four import Constants
class BaseDialog(wx.Dialog):
def __init__(self, parent, pickerClass, pickerGetter, localizedPickerLabel):
wx.Dialog.__init__(self, parent, title=localizedPickerLabel)
self.SetBackgroundColour('#fffff... | --- +++ @@ -1,45 +1,53 @@-from gooey.gui.lang.i18n import _
-
-import wx # type: ignore
-
-from gooey.gui.three_to_four import Constants
-
-
-class BaseDialog(wx.Dialog):
- def __init__(self, parent, pickerClass, pickerGetter, localizedPickerLabel):
- wx.Dialog.__init__(self, parent, title=localizedPickerLabel)
-
... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/components/widgets/dialogs/base_dialog.py |
Add docstrings including usage examples |
def merge_dictionaries(x,y):
if x is None:
x = {}
if y is None:
y = {}
try:
return {**x,**y}
except:
z = x.copy()
z.update(y)
return z | --- +++ @@ -1,13 +1,30 @@-
-
-def merge_dictionaries(x,y):
- if x is None:
- x = {}
- if y is None:
- y = {}
- try:
- return {**x,**y}
- except:
- z = x.copy()
- z.update(y)
- return z+'''
+Utils for functional methodologies throughout Gooey
+
+'''
+
+
+def me... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/gui/util/functional.py |
Please document this code using docstrings | from functools import reduce, wraps
from copy import deepcopy
from itertools import chain, dropwhile
from typing import Tuple, Any, List, Union
from gooey.python_bindings.types import Try, Success, Failure
def getin(m, path, default=None):
keynotfound = ':com.gooey-project/not-found'
result = reduce(lambda a... | --- +++ @@ -1,101 +1,120 @@-from functools import reduce, wraps
-from copy import deepcopy
-from itertools import chain, dropwhile
-from typing import Tuple, Any, List, Union
-
-from gooey.python_bindings.types import Try, Success, Failure
-
-
-def getin(m, path, default=None):
- keynotfound = ':com.gooey-project/no... | https://raw.githubusercontent.com/chriskiehl/Gooey/HEAD/gooey/util/functional.py |
Create docstrings for API functions | from __future__ import annotations
import functools
import logging
import os
import os.path
from typing import IO, TYPE_CHECKING, Any
import mergedeep # type: ignore
import yaml
import yaml.constructor
import yaml_env_tag # type: ignore
from mkdocs import exceptions
if TYPE_CHECKING:
from mkdocs.config.defaul... | --- +++ @@ -48,25 +48,46 @@ raise NotImplementedError
def __fspath__(self) -> str:
+ """Can be used as a path."""
return os.path.join(self.value(), self.suffix)
def __str__(self) -> str:
+ """Can be converted to a string to obtain the current class."""
return self._... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/utils/yaml.py |
Document this code for team use |
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, MutableMapping, TypeVar, overload
if sys.version_info >= (3, 10):
from importlib.metadata import EntryPoint, entry_points
else:
from importlib_metadata import EntryPoint, entry_poin... | --- +++ @@ -1,3 +1,4 @@+"""Implements the plugin API for MkDocs."""
from __future__ import annotations
@@ -37,6 +38,7 @@
def get_plugins() -> dict[str, EntryPoint]:
+ """Return a dict of all installed Plugins as {name: EntryPoint}."""
plugins = entry_points(group='mkdocs.plugins')
# Allow third-... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/plugins.py |
Write reusable docstrings | #!/usr/bin/env python
from __future__ import annotations
import logging
import os
import shutil
import sys
import textwrap
import traceback
import warnings
import click
from mkdocs import __version__, config, utils
if sys.platform.startswith("win"):
try:
import colorama
except ImportError:
... | --- +++ @@ -89,6 +89,7 @@
class State:
+ """Maintain logging level."""
def __init__(self, log_name='mkdocs', level=logging.INFO):
self.logger = logging.getLogger(log_name)
@@ -246,6 +247,7 @@ @common_options
@color_option
def cli():
+ """MkDocs - Project documentation with Markdown."""
... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/__main__.py |
Create docstrings for reusable components | from __future__ import annotations
from click import ClickException, echo
class MkDocsException(ClickException):
class Abort(MkDocsException, SystemExit):
code = 1
def show(self, *args, **kwargs) -> None:
echo('\n' + self.format_message())
class ConfigurationError(MkDocsException):
class Buil... | --- +++ @@ -4,9 +4,14 @@
class MkDocsException(ClickException):
+ """
+ The base class which all MkDocs exceptions inherit from. This should
+ not be raised directly. One of the subclasses should be raised instead.
+ """
class Abort(MkDocsException, SystemExit):
+ """Abort the build."""
c... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/exceptions.py |
Add docstrings to make code maintainable | from __future__ import annotations
import functools
import logging
import os
import posixpath
import re
import shutil
import sys
import warnings
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import PurePath
from typing import TYPE_CHECKING, Collection, Iterable, MutableSequen... | --- +++ @@ -1,3 +1,9 @@+"""
+Standalone file utils.
+
+Nothing in this module should have an knowledge of config or the layout
+and structure of the site and pages in the site.
+"""
from __future__ import annotations
import functools
@@ -39,6 +45,11 @@
def get_build_timestamp(*, pages: Collection[Page] | None =... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/utils/__init__.py |
Add detailed documentation for each class | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Iterator, TypeVar
from urllib.parse import urlsplit
from mkdocs.exceptions import BuildError
from mkdocs.structure import StructureItem
from mkdocs.structure.files import file_sort_key
from mkdocs.structure.pages import Page, _Absolut... | --- +++ @@ -64,10 +64,16 @@
@property
def active(self) -> bool:
+ """
+ When `True`, indicates that a child page of this section is the current page and
+ can be used to highlight the section as the currently viewed section. Defaults
+ to `False`.
+ """
return self... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/structure/nav.py |
Add docstrings to clarify complex logic | from __future__ import annotations
import logging
import os
import warnings
from typing import Any, Collection, MutableMapping
import jinja2
import yaml
try:
from yaml import CSafeLoader as SafeLoader
except ImportError: # pragma: no cover
from yaml import SafeLoader # type: ignore
from mkdocs import loca... | --- +++ @@ -21,6 +21,16 @@
class Theme(MutableMapping[str, Any]):
+ """
+ A Theme object.
+
+ Args:
+ name: The name of the theme as defined by its entrypoint.
+ custom_dir: User defined directory for custom templates.
+ static_templates: A list of templates to render as static pages.
... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/theme.py |
Add docstrings for production code | from __future__ import annotations
import functools
import io
import ipaddress
import logging
import mimetypes
import os
import os.path
import pathlib
import posixpath
import re
import socket
import socketserver
import string
import sys
import threading
import time
import traceback
import urllib.parse
import webbrowse... | --- +++ @@ -83,6 +83,7 @@
def _normalize_mount_path(mount_path: str) -> str:
+ """Ensure the mount path starts and ends with a slash."""
return ("/" + mount_path.lstrip("/")).rstrip("/") + "/"
@@ -136,6 +137,7 @@ self._watch_refs: dict[str, Any] = {}
def watch(self, path: str, func: None ... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/livereload/__init__.py |
Generate consistent documentation across files | from __future__ import annotations
import functools
import ipaddress
import logging
import os
import string
import sys
import traceback
import types
import warnings
from collections import Counter, UserString
from types import SimpleNamespace
from typing import (
Any,
Callable,
Collection,
Dict,
Ge... | --- +++ @@ -50,6 +50,18 @@
class SubConfig(Generic[SomeConfig], BaseConfigOption[SomeConfig]):
+ """
+ Subconfig Config Option.
+
+ New: If targeting MkDocs 1.4+, please pass a subclass of Config to the
+ constructor, instead of the old style of a sequence of ConfigOption instances.
+ Validation is t... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/config/config_options.py |
Generate docstrings with parameter types | from __future__ import annotations
import gzip
import logging
import os
import time
from typing import TYPE_CHECKING, Sequence
from urllib.parse import urljoin, urlsplit
import jinja2
from jinja2.exceptions import TemplateNotFound
import mkdocs
from mkdocs import utils
from mkdocs.exceptions import Abort, BuildError... | --- +++ @@ -33,6 +33,7 @@ page: Page | None = None,
base_url: str = '',
) -> templates.TemplateContext:
+ """Return the template context for a given page or template."""
if page is not None:
base_url = utils.get_relative_url('.', page.url)
@@ -60,6 +61,7 @@ def _build_template(
name: s... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/commands/build.py |
Add standardized docstrings across the file | from __future__ import annotations
import enum
import logging
import posixpath
import warnings
from typing import TYPE_CHECKING, Any, Callable, Iterator, MutableMapping, Sequence
from urllib.parse import unquote as urlunquote
from urllib.parse import urljoin, urlsplit, urlunsplit
import markdown
import markdown.exten... | --- +++ @@ -89,6 +89,7 @@
@property
def url(self) -> str:
+ """The URL of the page relative to the MkDocs `site_dir`."""
url = self.file.url
if url in ('.', './'):
return ''
@@ -111,10 +112,12 @@
@property
def active(self) -> bool:
+ """When `True`, ind... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/structure/pages.py |
Provide docstrings following PEP 257 | from __future__ import annotations
from typing import Iterable, Iterator, TypedDict
class _TocToken(TypedDict):
level: int
id: str
name: str
children: list[_TocToken]
def get_toc(toc_tokens: list[_TocToken]) -> TableOfContents:
toc = [_parse_toc_token(i) for i in toc_tokens]
# For the table... | --- +++ @@ -1,3 +1,10 @@+"""
+Deals with generating the per-page table of contents.
+
+For the sake of simplicity we use the Python-Markdown `toc` extension to
+generate a list of dicts for each toc item, and then store it as AnchorLinks to
+maintain compatibility with older versions of MkDocs.
+"""
from __future__ im... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/structure/toc.py |
Add docstrings to my Python code | from __future__ import annotations
import json
import logging
import os
import re
import subprocess
from html.parser import HTMLParser
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from mkdocs.structure.pages import Page
from mkdocs.structure.toc import AnchorLink, TableOfContents
try:
from lunr imp... | --- +++ @@ -23,12 +23,20 @@
class SearchIndex:
+ """
+ Search index is a collection of pages and sections (heading
+ tags and their following content are sections).
+ """
def __init__(self, **config) -> None:
self._entries: list[dict] = []
self.config = config
def _find_t... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/contrib/search/search_index.py |
Write docstrings that follow conventions | from __future__ import annotations
import logging
from typing import IO, Dict, Mapping
from mkdocs.config import base
from mkdocs.config import config_options as c
from mkdocs.structure.pages import Page, _AbsoluteLinksValidationValue
from mkdocs.utils.yaml import get_yaml_loader, yaml_load
class _LogLevel(c.Option... | --- +++ @@ -36,6 +36,7 @@ # depend on others. So, if config option A depends on B, then A should be
# listed higher in the schema.
class MkDocsConfig(base.Config):
+ """The configuration of MkDocs itself (the root object of mkdocs.yml)."""
config_file_path: str = c.Type(str) # type: ignore[assignment]
... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/config/defaults.py |
Write proper docstrings for these functions | from __future__ import annotations
from typing import TYPE_CHECKING, Sequence, TypedDict
if TYPE_CHECKING:
import datetime
from markupsafe import Markup
try:
from jinja2 import pass_context as contextfilter # type: ignore
except ImportError:
from jinja2 import contextfilter # type: ignore
from mkdocs... | --- +++ @@ -36,11 +36,13 @@
@contextfilter
def url_filter(context: TemplateContext, value: str) -> str:
+ """A Template filter to normalize URLs."""
return normalize_url(str(value), page=context['page'], base=context['base_url'])
@contextfilter
def script_tag_filter(context: TemplateContext, extra_scri... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/utils/templates.py |
Generate docstrings with parameter types | from __future__ import annotations
import copy
from typing import TYPE_CHECKING, Callable
import markdown
import markdown.treeprocessors
if TYPE_CHECKING:
from xml.etree import ElementTree as etree
# TODO: This will become unnecessary after min-versions have Markdown >=3.4
_unescape: Callable[[str], str]
try:
... | --- +++ @@ -28,6 +28,7 @@
def _strip_tags(text: str) -> str:
+ """Strip HTML tags and return plain text. Note: HTML entities are unaffected."""
# A comment could contain a tag, so strip comments first
while (start := text.find('<!--')) != -1 and (end := text.find('-->', start)) != -1:
text = t... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/utils/rendering.py |
Generate docstrings for script automation | from __future__ import annotations
import re
from typing import Any
import yaml
try:
from yaml import CSafeLoader as SafeLoader
except ImportError: # pragma: no cover
from yaml import SafeLoader # type: ignore
#####################################################################
# Data Parser ... | --- +++ @@ -1,3 +1,37 @@+"""
+Copyright (c) 2015, Waylan Limberg
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+lis... | https://raw.githubusercontent.com/mkdocs/mkdocs/HEAD/mkdocs/utils/meta.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.