instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings for internal functions
# Copyright 2025 the LlamaFactory team. # # 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -28,6 +28,16 @@ model_name_or_path: str = "./models/Qwen3-32B-AWQ", template: str = "qwen3", ) -> int: + """Calculate the token length of the specified text + + Args: + text: Text to calculate token length for + model_name_or_path: Model path + template: Template name + +...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/utils/length_cdf.py
Add docstrings to improve readability
import re from typing import List, Optional, cast import torch from llamafactory.data import get_template_and_fix_tokenizer from llamafactory.extras.misc import get_device_count from llamafactory.hparams import get_infer_args from llamafactory.model import load_tokenizer from openai.types.chat import ChatCompletion fr...
--- +++ @@ -23,6 +23,7 @@ def extract_json_from_text(text: str) -> str: + """Extract JSON content from text, supporting JSON blocks in markdown format.""" json_pattern = r"```json\s*(.*?)\s*```" match = re.search(json_pattern, text, re.DOTALL) if match: @@ -33,6 +34,16 @@ def parse_guided_decoding...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/core/inference/offline_infer.py
Help me write clear docstrings
import logging from concurrent.futures import Future, ThreadPoolExecutor from typing import Any, Callable, List, Optional, Union from openai import OpenAI from openai.types.chat import ChatCompletion, ChatCompletionMessageParam from pydantic import BaseModel from weclone.core.inference.offline_infer import extract_js...
--- +++ @@ -78,6 +78,7 @@ top_p: float = 0.95, stream: bool = False, ) -> Future: + """Submit a chat request to the thread pool for async processing""" return self.executor.submit(self.chat, prompt_text, temperature, max_tokens, top_p, stream) def chat_batch( @@ -90,6 +91,21...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/core/inference/online_infer.py
Create docstrings for all classes and functions
import json import os import re import subprocess # nosec import sys from typing import List, Union, cast os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn") import pandas as pd from pandas import Timestamp from weclone.core.PII.pii_detector import ChinesePIIDetector, PIIDetector from weclone.data.chat_p...
--- +++ @@ -158,6 +158,7 @@ process_telegram_dataset(self.config) def _execute_length_cdf_script(self): + """Execute the length_cdf.py script to calculate cutoff_len.""" try: python_executable = sys.executable script_path = os.path.join("weclone", "utils", "l...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/data/qa_generator.py
Generate helpful docstrings for debugging
from typing import Dict, List, Optional class MultiLangList: def __init__(self, translations: Dict[str, List[str]], default_lang="en"): self.translations = translations self.current_lang = default_lang self.default_lang = default_lang # Validate that all translation lists have the ...
--- +++ @@ -12,6 +12,7 @@ self._build_reverse_mapping() def _validate_translations(self): + """Validate that all translation lists have the same length""" if not self.translations: raise ValueError("Translations dictionary cannot be empty") @@ -28,6 +29,7 @@ ...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/utils/i18n.py
Add inline docstrings for readability
from dataclasses import dataclass from typing import List, Optional, cast from presidio_analyzer import AnalyzerEngine, BatchAnalyzerEngine, Pattern, PatternRecognizer from presidio_analyzer.nlp_engine import NlpEngineProvider from presidio_anonymizer import AnonymizerEngine from presidio_anonymizer.entities.engine.re...
--- +++ @@ -22,6 +22,7 @@ class PIIDetector: + """PII detector based on presidio library""" def __init__(self, language: str = "en", threshold: float = 0.5): self.language = language @@ -93,6 +94,15 @@ return len(pii_results) > 0 def batch_has_pii(self, texts: List[str]) -> List[bo...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/core/PII/pii_detector.py
Write docstrings for backend logic
import os import sys from typing import Any, Dict, cast import pyjson5 from omegaconf import OmegaConf from pydantic import BaseModel from .config_models import ( WcConfig, WCInferConfig, WCMakeDatasetConfig, WCTrainSftConfig, ) from .log import logger from .tools import dict_to_argv def load_base_c...
--- +++ @@ -17,6 +17,7 @@ def load_base_config() -> WcConfig: + """Load base configuration file and create WcConfig object""" config_path = os.environ.get("WECLONE_CONFIG_PATH", "./settings.jsonc") logger.info(f"Loading configuration from: {config_path}") @@ -47,6 +48,7 @@ def create_config_by_ar...
https://raw.githubusercontent.com/xming521/WeClone/HEAD/weclone/utils/config.py
Document functions with detailed explanations
#!/usr/bin/env python3 import json import sys import os from pathlib import Path from typing import List, Dict, Optional, Tuple from datetime import datetime PLANNING_FILES = ['task_plan.md', 'progress.md', 'findings.md'] def get_project_dir(project_path: str) -> Path: sanitized = project_path.replace('/', '-')...
--- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python3 +""" +Session Catchup Script for planning-with-files + +Analyzes the previous session to find unsynced context after the last +planning file update. Designed to run on SessionStart. + +Usage: python3 session-catchup.py [project-path] +""" import json import sys @@ -11...
https://raw.githubusercontent.com/OthmanAdi/planning-with-files/HEAD/.codebuddy/skills/planning-with-files/scripts/session-catchup.py
Write clean docstrings for readability
#!/usr/bin/env python3 import json import sys import os from pathlib import Path from typing import List, Dict, Optional, Tuple PLANNING_FILES = ['task_plan.md', 'progress.md', 'findings.md'] def detect_ide() -> str: # Check for OpenCode environment if os.environ.get('OPENCODE_DATA_DIR'): return 'op...
--- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3 +""" +Session Catchup Script for planning-with-files + +Session-agnostic scanning: finds the most recent planning file update across +ALL sessions, then collects all conversation from that point forward through +all subsequent sessions until now. + +Supports multiple AI I...
https://raw.githubusercontent.com/OthmanAdi/planning-with-files/HEAD/scripts/session-catchup.py
Add docstrings with type hints explained
#!/usr/bin/env python3 import json import sys import os from pathlib import Path from typing import List, Dict, Optional, Tuple PLANNING_FILES = ['task_plan.md', 'progress.md', 'findings.md'] def get_project_dir(project_path: str) -> Path: # Normalize to an absolute path to ensure a stable representation #...
--- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python3 +""" +Session Catchup Script for planning-with-files + +Analyzes the previous session to find unsynced context after the last +planning file update. Designed to run on SessionStart. + +Usage: python3 session-catchup.py [project-path] +""" import json import sys @@ -11...
https://raw.githubusercontent.com/OthmanAdi/planning-with-files/HEAD/.opencode/skills/planning-with-files/scripts/session-catchup.py
Document functions with detailed explanations
#!/usr/bin/env python3 import argparse import shutil import sys import hashlib from pathlib import Path # ─── Canonical source ────────────────────────────────────────────── CANONICAL = Path("skills/planning-with-files") # ─── Shared source files (relative to CANONICAL) ────────────────── TEMPLATES = [ "template...
--- +++ @@ -1,4 +1,23 @@ #!/usr/bin/env python3 +""" +sync-ide-folders.py — Syncs shared files from the canonical source +(skills/planning-with-files/) to all IDE-specific folders. + +Run this from the repo root before releases: + python scripts/sync-ide-folders.py + +What it syncs: + - Templates (findings.md, pr...
https://raw.githubusercontent.com/OthmanAdi/planning-with-files/HEAD/scripts/sync-ide-folders.py
Generate docstrings for this script
import asyncio import sys from collections.abc import Callable from types import TracebackType from typing import Any, Final, Generic, Literal, overload from ._websocket.reader import WebSocketDataQueue from .client_exceptions import ClientError, ServerTimeoutError, WSMessageTypeError from .client_reqrep import Clien...
--- +++ @@ -1,3 +1,4 @@+"""WebSocket client for asyncio.""" import asyncio import sys @@ -199,6 +200,7 @@ self._ping_task_done(ping_task) def _ping_task_done(self, task: "asyncio.Task[None]") -> None: + """Callback for when the ping task completes.""" if not task.cancelled() and (...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/client_ws.py
Add concise docstrings to each method
import asyncio import socket from contextlib import suppress __all__ = ("tcp_keepalive", "tcp_nodelay") if hasattr(socket, "SO_KEEPALIVE"): def tcp_keepalive(transport: asyncio.Transport) -> None: sock = transport.get_extra_info("socket") if sock is not None: sock.setsockopt(socket....
--- +++ @@ -1,3 +1,4 @@+"""Helper methods to tune a TCP connection""" import asyncio import socket @@ -16,6 +17,7 @@ else: def tcp_keepalive(transport: asyncio.Transport) -> None: + """Noop when keepalive not supported.""" def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None: @@ -31...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/tcp_helpers.py
Create docstrings for all classes and functions
import json from collections.abc import Callable from enum import IntEnum from typing import Any, Final, Literal, NamedTuple, cast WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF]) class WSCloseCode(IntEnum): OK = 1000 GOING_AWAY = 1001 PROTOCOL_ERROR = 1002 UNSUPPORTED_DATA = 1003...
--- +++ @@ -1,3 +1,4 @@+"""Models for WebSocket protocol versions 13 and 8.""" import json from collections.abc import Callable @@ -54,10 +55,12 @@ def json( self, *, loads: Callable[[str | bytes | bytearray], Any] = json.loads ) -> Any: + """Return parsed JSON data.""" return load...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/_websocket/models.py
Provide clean and structured docstrings
import datetime import functools import logging import os import re import time as time_mod from collections import namedtuple from collections.abc import Iterable from typing import Callable, ClassVar from .abc import AbstractAccessLogger from .web_request import BaseRequest from .web_response import StreamResponse ...
--- +++ @@ -16,6 +16,31 @@ class AccessLogger(AbstractAccessLogger): + """Helper object to log access. + + Usage: + log = logging.getLogger("spam") + log_format = "%a %{User-Agent}i" + access_logger = AccessLogger(log, log_format) + access_logger.log(request, response, time) + + ...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_log.py
Write beginner-friendly docstrings
from textwrap import indent from multidict import CIMultiDict __all__ = ("HttpProcessingError",) class HttpProcessingError(Exception): code = 0 message = "" headers = None def __init__( self, *, code: int | None = None, message: str = "", headers: CIMultiDi...
--- +++ @@ -1,3 +1,4 @@+"""Low-level http related exceptions.""" from textwrap import indent @@ -7,6 +8,14 @@ class HttpProcessingError(Exception): + """HTTP error. + + Shortcut for raising HTTP errors with custom code, message and headers. + + code: HTTP Error code. + message: (optional) Error mes...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/http_exceptions.py
Fully document this Python code with docstrings
import asyncio import signal import socket from abc import ABC, abstractmethod from typing import Any, Generic, TypeVar from yarl import URL from .abc import AbstractAccessLogger, AbstractStreamWriter from .http_parser import RawRequestMessage from .streams import StreamReader from .typedefs import PathLike from .web...
--- +++ @@ -64,6 +64,7 @@ @property @abstractmethod def name(self) -> str: + """Return the name of the site (e.g. a URL).""" @abstractmethod async def start(self) -> None: @@ -106,6 +107,14 @@ @property def port(self) -> int: + """The port the server is listening on. +...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_runner.py
Add docstrings to improve code quality
import asyncio import sys import zlib from abc import ABC, abstractmethod from concurrent.futures import Executor from typing import Any, Final, Protocol, TypedDict, cast if sys.version_info >= (3, 12): from collections.abc import Buffer else: from typing import Union Buffer = Union[bytes, bytearray, "mem...
--- +++ @@ -156,6 +156,7 @@ executor: Executor | None = None, max_sync_chunk_size: int | None = MAX_SYNC_CHUNK_SIZE, ): + """Base class for decompression handlers.""" self._executor = executor self._max_sync_chunk_size = max_sync_chunk_size @@ -163,10 +164,12 @@ def ...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/compression_utils.py
Generate missing documentation strings
import asyncio import random import sys from functools import partial from typing import Final from ..base_protocol import BaseProtocol from ..client_exceptions import ClientConnectionResetError from ..compression_utils import ZLibBackend, ZLibCompressor from .helpers import ( MASK_LEN, MSG_SIZE, PACK_CLO...
--- +++ @@ -1,3 +1,4 @@+"""WebSocket protocol versions 13 and 8.""" import asyncio import random @@ -37,6 +38,13 @@ class WebSocketWriter: + """WebSocket writer. + + The writer is responsible for sending messages to the client. It is + created by the protocol when a connection is established. The write...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/_websocket/writer.py
Write clean docstrings for readability
import asyncio import codecs import contextlib import functools import io import re import sys import traceback import warnings from collections.abc import Callable, Iterable, Sequence from hashlib import md5, sha1, sha256 from http.cookies import BaseCookie, SimpleCookie from types import MappingProxyType, TracebackTy...
--- +++ @@ -115,6 +115,10 @@ headers: "CIMultiDictProxy[str]", real_url: URL | _SENTINEL = sentinel, ) -> "RequestInfo": + """Create a new RequestInfo instance. + + For backwards compatibility, the real_url parameter is optional. + """ return tuple.__new__( ...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/client_reqrep.py
Add clean documentation to messy code
import asyncio import base64 import binascii import hashlib import json import sys from collections.abc import Callable, Iterable from typing import Any, Final, Generic, Literal, Union, overload from multidict import CIMultiDict from . import hdrs from ._websocket.reader import WebSocketDataQueue from ._websocket.wri...
--- +++ @@ -224,6 +224,7 @@ self._ping_task_done(ping_task) def _ping_task_done(self, task: "asyncio.Task[None]") -> None: + """Callback for when the ping task completes.""" if not task.cancelled() and (exc := task.exception()): self._handle_ping_pong_exception(exc) ...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_ws.py
Write beginner-friendly docstrings
import functools import re from re import Pattern from struct import Struct from typing import TYPE_CHECKING, Final from ..helpers import NO_EXTENSIONS from .models import WSHandshakeError UNPACK_LEN3 = Struct("!Q").unpack_from UNPACK_CLOSE_CODE = Struct("!H").unpack PACK_LEN1 = Struct("!BB").pack PACK_LEN2 = Struct...
--- +++ @@ -1,3 +1,4 @@+"""Helpers for WebSocket protocol versions 13 and 8.""" import functools import re @@ -28,6 +29,18 @@ def _websocket_mask_python(mask: bytes, data: bytearray) -> None: + """Websocket masking function. + + `mask` is a `bytes` object of length 4; `data` is a `bytearray` + object o...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/_websocket/helpers.py
Add docstrings to my Python code
import asyncio import io import os import pathlib import sys from collections.abc import Awaitable, Callable from contextlib import suppress from enum import Enum, auto from mimetypes import MimeTypes from stat import S_ISREG from types import MappingProxyType from typing import IO, TYPE_CHECKING, Any, Final, Optional ...
--- +++ @@ -59,6 +59,7 @@ class _FileResponseResult(Enum): + """The result of the file response.""" SEND_FILE = auto() # Ie a regular file to send NOT_ACCEPTABLE = auto() # Ie a socket, or non-regular file @@ -76,6 +77,7 @@ class FileResponse(StreamResponse): + """A response object can be us...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_fileresponse.py
Generate docstrings for exported functions
import asyncio import datetime import io import re import socket import string import sys import tempfile import types from collections.abc import Iterator, Mapping, MutableMapping from re import Pattern from types import MappingProxyType from typing import TYPE_CHECKING, Any, Final, Optional, TypeVar, cast, overload f...
--- +++ @@ -184,6 +184,12 @@ remote: str | _SENTINEL = sentinel, client_max_size: int | _SENTINEL = sentinel, ) -> "BaseRequest": + """Clone itself with replacement some attributes. + + Creates and returns a new instance of Request object. If no parameters + are given, an exac...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_request.py
Add docstrings that explain purpose and usage
import abc import asyncio import base64 import functools import hashlib import html import inspect import keyword import os import platform import re import sys from collections.abc import ( Awaitable, Callable, Container, Generator, Iterable, Iterator, Mapping, Sized, ) from pathlib imp...
--- +++ @@ -109,24 +109,40 @@ @property @abc.abstractmethod def canonical(self) -> str: + """Exposes the resource's canonical path. + + For example '/foo/bar/{name}' + + """ @abc.abstractmethod # pragma: no branch def url_for(self, **kwargs: str) -> URL: + """Const...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_urldispatcher.py
Help me write clear docstrings
import base64 import binascii import json import re import sys import uuid import warnings from collections import deque from collections.abc import AsyncIterator, Iterator, Mapping, Sequence from types import TracebackType from typing import TYPE_CHECKING, Any, Union, cast from urllib.parse import parse_qsl, unquote, ...
--- +++ @@ -208,6 +208,11 @@ class MultipartResponseWrapper: + """Wrapper around the MultipartReader. + + It takes care about + underlying connection and close it when it needs in. + """ def __init__( self, @@ -229,21 +234,28 @@ return part def at_eof(self) -> bool: + ...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/multipart.py
Generate docstrings with parameter types
import asyncio import inspect import os import re import signal import sys from types import FrameType from typing import Any, Optional from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat from gunicorn.workers import base from aiohttp import web from .helpers import set_result from .web_app impor...
--- +++ @@ -1,3 +1,4 @@+"""Async gunicorn worker for aiohttp.web""" import asyncio import inspect @@ -198,6 +199,10 @@ @staticmethod def _create_ssl_context(cfg: Any) -> "SSLContext": + """Creates SSLContext instance for usage in asyncio.create_server. + + See ssl.SSLSocket.__init__ for mor...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/worker.py
Add docstrings to clarify complex logic
import re from collections.abc import Sequence from http.cookies import Morsel from typing import cast from .log import internal_logger __all__ = ( "parse_set_cookie_headers", "parse_cookie_header", "preserve_morsel_with_coded_value", ) # Cookie parsing constants # Allow more characters in cookie names ...
--- +++ @@ -1,3 +1,9 @@+""" +Internal cookie handling helpers. + +This module contains internal utilities for cookie parsing and manipulation. +These are not part of the public API and may change without notice. +""" import re from collections.abc import Sequence @@ -77,6 +83,24 @@ def preserve_morsel_with_code...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/_cookie_helpers.py
Auto-generate documentation strings for this file
import abc import asyncio import re import string from contextlib import suppress from enum import IntEnum from re import Pattern from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, TypeVar from multidict import CIMultiDict, CIMultiDictProxy, istr from yarl import URL from . import hdrs from .base_...
--- +++ @@ -201,6 +201,7 @@ def _is_supported_upgrade(headers: CIMultiDictProxy[str]) -> bool: + """Check if the upgrade header is supported.""" u = headers.get(hdrs.UPGRADE, "") # .lower() can transform non-ascii characters. return u.isascii() and u.lower() in {"tcp", "websocket"} @@ -490,6 +491,...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/http_parser.py
Generate NumPy-style docstrings
import logging import socket from abc import ABC, abstractmethod from collections.abc import Awaitable, Callable, Generator, Iterable, Sequence, Sized from http.cookies import BaseCookie, Morsel from typing import TYPE_CHECKING, Any, TypedDict from multidict import CIMultiDict from yarl import URL from ._cookie_helpe...
--- +++ @@ -26,16 +26,24 @@ self._frozen = False def post_init(self, app: Application) -> None: + """Post init stage. + + Not an abstract method for sake of backward compatibility, + but if the router wants to be aware of the application + it can override this. + """ ...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/abc.py
Generate descriptive docstrings automatically
import hashlib import os import re import sys import time from collections.abc import Callable from typing import Final, Literal, TypedDict from yarl import URL from . import hdrs from .client_exceptions import ClientError from .client_middlewares import ClientHandlerType from .client_reqrep import ClientRequest, Cl...
--- +++ @@ -1,3 +1,11 @@+""" +Digest authentication middleware for aiohttp client. + +This middleware implements HTTP Digest Authentication according to RFC 7616, +providing a more secure alternative to Basic Authentication. It supports all +standard hash algorithms including MD5, SHA, SHA-256, SHA-512 and their sessio...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/client_middleware_digest_auth.py
Generate docstrings for each module
import asyncio import functools import random import socket import sys import traceback import warnings from collections import OrderedDict, defaultdict, deque from collections.abc import Awaitable, Callable, Iterator, Sequence from contextlib import suppress from http import HTTPStatus from itertools import chain, cyc...
--- +++ @@ -97,6 +97,7 @@ class Connection: + """Represents a single connection.""" __slots__ = ( "_key", @@ -142,6 +143,7 @@ self._loop.call_exception_handler(context) def __bool__(self) -> Literal[True]: + """Force subclasses to not be falsy, to make checks simpler."""...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/connector.py
Add concise docstrings to each method
import asyncio import enum import io import json import mimetypes import os import sys import warnings from abc import ABC, abstractmethod from collections.abc import AsyncIterable, AsyncIterator, Iterable from itertools import chain from typing import IO, Any, Final, TextIO from multidict import CIMultiDict from . i...
--- +++ @@ -48,6 +48,7 @@ class LookupError(Exception): + """Raised when no payload factory is found for the given data type.""" class Order(str, enum.Enum): @@ -81,6 +82,10 @@ class PayloadRegistry: + """Payload registry. + + note: we need zope.interface for more efficient adapter search + """...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/payload.py
Document helper functions with docstrings
import asyncio import datetime import enum import json import math import time import warnings from collections.abc import Iterator, MutableMapping from concurrent.futures import Executor from http import HTTPStatus from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union, cast, overload from multidict import C...
--- +++ @@ -98,6 +98,13 @@ headers: LooseHeaders | None = None, _real_headers: CIMultiDict[str] | None = None, ) -> None: + """Initialize a new stream response object. + + _real_headers is an internal parameter used to pass a pre-populated + headers object. It is used by the `...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_response.py
Add missing documentation to my Python functions
#!/usr/bin/env python3 import sys import os import argparse from . import run from . import config from . import storage def error(_error, message): print("[-] {}: {}".format(_error, message)) sys.exit(0) def check(args): if args.username is not None or args.userlist or args.members_list: if ar...
--- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3 +''' +Twint.py - Twitter Intelligence Tool (formerly known as Tweep). + +See wiki on Github for in-depth details. +https://github.com/twintproject/twint/wiki + +Licensed under MIT License +Copyright (c) 2018 The Twint Project +''' import sys import os import argparse...
https://raw.githubusercontent.com/twintproject/twint/HEAD/twint/cli.py
Help me comply with documentation standards
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. import json import os import sys import time from pathlib import Path from typing import List, Literal, Optional, Tuple, TypedDict import torch import tor...
--- +++ @@ -477,6 +477,10 @@ suf: str, suffix_first: bool = False, ) -> List[int]: + """ + Format and encode an infilling problem. + If `suffix_first` is set, format in suffix-prefix-middle format. + """ assert tokenizer.prefix_id is not None assert tokenizer.middle_id is not None a...
https://raw.githubusercontent.com/meta-llama/codellama/HEAD/llama/generation.py
Generate docstrings with examples
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. import os from logging import getLogger from typing import List, Optional from sentencepiece import SentencePieceProcessor logger = getLogger() class ...
--- +++ @@ -55,7 +55,9 @@ return self.sp_model.id_to_piece(t) def encode_infilling(self, s: str) -> List[int]: + """Encode a string without an implicit leading space.""" return self.sp_model.encode("☺" + s)[2:] def decode_infilling(self, t: List[int]) -> str: - return self.s...
https://raw.githubusercontent.com/meta-llama/codellama/HEAD/llama/tokenizer.py
Document helper functions with docstrings
import numpy as np ####################################################################### # Training Utils # ####################################################################### def minibatch(X, batchsize=256, shuffle=True): N = X.shape[0] ix = np.aran...
--- +++ @@ -6,6 +6,29 @@ def minibatch(X, batchsize=256, shuffle=True): + """ + Compute the minibatch indices for a training dataset. + + Parameters + ---------- + X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, \*)` + The dataset to divide into minibatches. Assumes the first dimension +...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/utils/utils.py
Create Google-style docstrings for my code
import numpy as np from numpy_ml.utils.misc import logsumexp class MultinomialHMM: def __init__(self, A=None, B=None, pi=None, eps=None): eps = np.finfo(float).eps if eps is None else eps # prior probability of each latent state if pi is not None: pi[pi == 0] = eps #...
--- +++ @@ -1,3 +1,4 @@+"""Hidden Markov model module""" import numpy as np from numpy_ml.utils.misc import logsumexp @@ -5,6 +6,45 @@ class MultinomialHMM: def __init__(self, A=None, B=None, pi=None, eps=None): + r""" + A simple hidden Markov model with multinomial emission distribution. + + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/hmm/hmm.py
Write docstrings for backend logic
import asyncio from typing import TYPE_CHECKING, Union from multidict import MultiMapping from .typedefs import StrOrURL try: import ssl SSLContext = ssl.SSLContext except ImportError: # pragma: no cover ssl = SSLContext = None # type: ignore[assignment] if TYPE_CHECKING: from .client_reqrep imp...
--- +++ @@ -1,3 +1,4 @@+"""HTTP related errors.""" import asyncio from typing import TYPE_CHECKING, Union @@ -52,9 +53,18 @@ class ClientError(Exception): + """Base class for client connection errors.""" class ClientResponseError(ClientError): + """Base class for exceptions that occur after getting a...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/client_exceptions.py
Generate docstrings for exported functions
from abc import ABC, abstractmethod import numpy as np class WrapperBase(ABC): def __init__(self, wrapped_layer): self._base_layer = wrapped_layer if hasattr(wrapped_layer, "_base_layer"): self._base_layer = wrapped_layer._base_layer super().__init__() @abstractmethod ...
--- +++ @@ -1,3 +1,7 @@+""" +A collection of objects thats can wrap / otherwise modify arbitrary neural +network layers. +""" from abc import ABC, abstractmethod @@ -6,6 +10,7 @@ class WrapperBase(ABC): def __init__(self, wrapped_layer): + """An abstract base class for all Wrapper instances""" ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/wrappers/wrappers.py
Create documentation for each function signature
import warnings from itertools import product from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning from numpy_ml.rl_models.tiles.tiles3 import tiles, IHT NO_PD = False try: import pandas as pd except ModuleNotFoundError: NO_PD = True try: import gym...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for training and evaluating RL models on OpenAI gym environments""" import warnings from itertools import product from collections import defaultdict @@ -25,32 +26,71 @@ class EnvModel(object): + """ + A simple tabular environment model that maintains the counts of each...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/rl_models/rl_utils.py
Add concise docstrings to each method
import numpy as np class LinearRegression: def __init__(self, fit_intercept=True): self.beta = None self.sigma_inv = None self.fit_intercept = fit_intercept self._is_fit = False def update(self, X, y, weights=None): if not self._is_fit: raise RuntimeError...
--- +++ @@ -1,9 +1,58 @@+"""Linear regression module.""" import numpy as np class LinearRegression: def __init__(self, fit_intercept=True): + r""" + A weighted linear least-squares regression model. + + Notes + ----- + In weighted linear least-squares regression [1]_, a r...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/linear_models/linear_regression.py
Insert docstrings into my code
from abc import ABC, abstractmethod from collections import defaultdict import numpy as np from .rl_utils import EnvModel, env_stats, tile_state_space from ..utils.data_structures import Dict class AgentBase(ABC): def __init__(self, env): super().__init__() self.env = env self.parameter...
--- +++ @@ -1,3 +1,4 @@+"""Reinforcement learning agents that can be run on OpenAI gym environs""" from abc import ABC, abstractmethod from collections import defaultdict @@ -37,28 +38,123 @@ self._num2obs = {i: act for act, i in self._obs2num.items()} def flush_history(self): + """Clear t...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/rl_models/agents.py
Create docstrings for API functions
import re from functools import partial from ast import literal_eval as _eval import numpy as np from ..optimizers import OptimizerBase, SGD, AdaGrad, RMSProp, Adam from ..activations import ( ELU, GELU, SELU, ReLU, Tanh, Affine, Sigmoid, Identity, SoftPlus, LeakyReLU, Expo...
--- +++ @@ -1,3 +1,4 @@+"""A module containing objects to instantiate various neural network components.""" import re from functools import partial from ast import literal_eval as _eval @@ -39,9 +40,18 @@ class ActivationInitializer(object): def __init__(self, param=None): + """ + A class for in...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/initializers/initializers.py
Write documentation strings for class attributes
import warnings import numpy as np from numpy.linalg import slogdet, inv try: _SCIPY = True from scipy.stats import norm except: _SCIPY = False warnings.warn( "Could not import scipy.stats. Confidence scores " "for GPRegression are restricted to 95% bounds" ) from ..utils.kernels i...
--- +++ @@ -17,11 +17,42 @@ class GPRegression: def __init__(self, kernel="RBFKernel", alpha=1e-10): + """ + A Gaussian Process (GP) regression model. + + .. math:: + + y \mid X, f &\sim \mathcal{N}( [f(x_1), \ldots, f(x_n)], \\alpha I ) \\\\ + f \mid X &\sim \\t...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/nonparametric/gp.py
Add docstrings to improve code quality
from time import time from collections import OrderedDict import numpy as np from ..utils import minibatch from ..layers import FullyConnected from ..losses import WGAN_GPLoss class WGAN_GP(object): def __init__( self, g_hidden=512, init="he_uniform", optimizer="RMSProp(lr=0.000...
--- +++ @@ -9,6 +9,59 @@ class WGAN_GP(object): + """ + A Wasserstein generative adversarial network (WGAN) architecture with + gradient penalty (GP). + + Notes + ----- + In contrast to a regular WGAN, WGAN-GP uses gradient penalty on the + generator rather than weight clipping to encourage the...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/models/wgan_gp.py
Turn comments into proper docstrings
import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): err_msg = "penalty must be 'l1' or 'l2', but got: {}".format(penalty) assert penalty in ["l2", "l1"], err_msg self.beta = None self.gamma = gamma self.penalty = penal...
--- +++ @@ -1,8 +1,85 @@+"""Logistic regression module""" import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): + r""" + A simple binary logistic regression model fit via gradient descent on + the penalized negative log likelihood. + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/linear_models/logistic.py
Write docstrings for algorithm functions
import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np # This list of English stop words is taken from the "Glasgow Information # Retrieval Group". The original list can be found at # http://ir.dcs.gla.ac.uk/resources/linguistic_utils/stop_words _STOP...
--- +++ @@ -1,3 +1,4 @@+"""Common preprocessing utilities for working with text data""" import re import heapq import os.path as op @@ -55,6 +56,7 @@ def ngrams(sequence, N): + """Return all `N`-grams of the elements in `sequence`""" assert N >= 1 return list(zip(*[sequence[i:] for i in range(N)])) ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/preprocessing/nlp.py
Write docstrings for this repository
import numpy as np from numpy_ml.linear_models.linear_regression import LinearRegression eps = np.finfo(float).eps _GLM_LINKS = { "logit": { "link": lambda mu: np.log((mu + eps) / (1 - mu + eps)), "inv_link": lambda eta: 1.0 / (1.0 + np.exp(-eta)), "link_prime": lambda x: (1 / (x + eps)) ...
--- +++ @@ -1,3 +1,4 @@+"""A module for the generalized linear model.""" import numpy as np from numpy_ml.linear_models.linear_regression import LinearRegression @@ -46,6 +47,74 @@ class GeneralizedLinearModel: def __init__(self, link, fit_intercept=True, tol=1e-5, max_iter=100): + r""" + A gen...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/linear_models/glm.py
Add docstrings to clarify complex logic
from abc import ABC, abstractmethod from collections import defaultdict import numpy as np from ..utils.testing import is_number class BanditPolicyBase(ABC): def __init__(self): self.step = 0 self.ev_estimates = {} self.is_initialized = False super().__init__() def __repr__...
--- +++ @@ -1,3 +1,4 @@+"""A module containing exploration policies for various multi-armed bandit problems.""" from abc import ABC, abstractmethod from collections import defaultdict @@ -9,25 +10,48 @@ class BanditPolicyBase(ABC): def __init__(self): + """A simple base class for multi-armed bandit po...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/bandits/policies.py
Fully document this Python code with docstrings
from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): super().__init__() def __call__(self, z): if z.ndim == 1: z = z.reshape(1, -1) return self.fn(z) @abstractmethod def fn(self, z): ...
--- +++ @@ -1,3 +1,4 @@+"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod @@ -6,91 +7,244 @@ class ActivationBase(ABC): def __init__(self, **kwargs): + """Initialize the ActivationBase object""" super().__in...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/activations/activations.py
Fully document this Python code with docstrings
from abc import ABC, abstractmethod import numpy as np from ...utils.testing import is_binary, is_stochastic from ..initializers import ( WeightInitializer, ActivationInitializer, OptimizerInitializer, ) class ObjectiveBase(ABC): def __init__(self): super().__init__() @abstractmethod ...
--- +++ @@ -25,6 +25,18 @@ class SquaredError(ObjectiveBase): def __init__(self): + """ + A squared-error / `L2` loss. + + Notes + ----- + For real-valued target **y** and predictions :math:`\hat{\mathbf{y}}`, the + squared error is + + .. math:: + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/losses/losses.py
Add docstrings that explain inputs and outputs
import numpy as np class Node: def __init__(self, left, right, rule): self.left = left self.right = right self.feature = rule[0] self.threshold = rule[1] class Leaf: def __init__(self, value): self.value = value class DecisionTree: def __init__( self, ...
--- +++ @@ -11,6 +11,10 @@ class Leaf: def __init__(self, value): + """ + `value` is an array of class probabilities if classifier is True, else + the mean of the region + """ self.value = value @@ -23,6 +27,28 @@ criterion="entropy", seed=None, ): +...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/trees/dt.py
Add docstrings to clarify complex logic
from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.policies import ( EpsilonGreedy, UCB1, ThompsonSa...
--- +++ @@ -1,3 +1,4 @@+"""Miscellaneous plots for multi-arm bandit validation""" from collections import namedtuple @@ -20,6 +21,7 @@ def random_multinomial_mab(n_arms=10, n_choices_per_arm=5, reward_range=[0, 1]): + """Generate a random multinomial multi-armed bandit environemt""" payoffs = [] p...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/plots/bandit_plots.py
Document this script properly
import numpy as np from scipy.special import digamma, polygamma, gammaln class LDA(object): def __init__(self, T=10): self.T = T def _maximize_phi(self): D = self.D N = self.N T = self.T phi = self.phi beta = self.beta gamma = self.gamma corpus...
--- +++ @@ -4,9 +4,40 @@ class LDA(object): def __init__(self, T=10): + """ + Vanilla (non-smoothed) LDA model trained using variational EM. + Generates maximum-likelihood estimates for model paramters + `alpha` and `beta`. + + Parameters + ---------- + T : int + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/lda/lda.py
Document all public functions with docstrings
import asyncio import sys from typing import ( # noqa TYPE_CHECKING, Any, Awaitable, Callable, Iterable, List, NamedTuple, Optional, Union, ) from multidict import CIMultiDict from .abc import AbstractStreamWriter from .base_protocol import BaseProtocol from .client_exceptions im...
--- +++ @@ -1,3 +1,4 @@+"""Http related parsers and protocol.""" import asyncio import sys @@ -123,6 +124,7 @@ def _write_chunked_payload( self, chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"] ) -> None: + """Write a chunk with proper chunked encoding.""" chu...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/http_writer.py
Provide docstrings following PEP 257
from time import time import numpy as np from ..layers import Embedding from ..losses import NCELoss from ...preprocessing.nlp import Vocabulary, tokenize_words from ...utils.data_structures import DiscreteSampler class Word2Vec(object): def __init__( self, context_len=5, min_count=None...
--- +++ @@ -23,6 +23,93 @@ num_negative_samples=64, optimizer="SGD(lr=0.1)", ): + """ + A word2vec model supporting both continuous bag of words (CBOW) and + skip-gram architectures, with training via noise contrastive + estimation. + + Parameters + ------...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/models/w2v.py
Add minimal docstrings for each function
import numpy as np import scipy.stats as stats from numpy_ml.utils.testing import is_number, is_symmetric_positive_definite class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): # this is a placeholder until we know the dimensions of X ...
--- +++ @@ -1,3 +1,4 @@+"""A module of Bayesian linear regression models.""" import numpy as np import scipy.stats as stats @@ -6,6 +7,55 @@ class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): + r""" + Bayesian linear regression ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/linear_models/bayesian_regression.py
Add return value explanations in docstrings
import numpy as np from numpy_ml.utils.misc import logsumexp, log_gaussian_pdf class GMM(object): def __init__(self, C=3, seed=None): self.elbo = None self.parameters = {} self.hyperparameters = { "C": C, "seed": seed, } self.is_fit = False ...
--- +++ @@ -1,3 +1,4 @@+"""A Gaussian mixture model class""" import numpy as np from numpy_ml.utils.misc import logsumexp, log_gaussian_pdf @@ -5,6 +6,33 @@ class GMM(object): def __init__(self, C=3, seed=None): + """ + A Gaussian mixture model trained via the expectation maximization + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/gmm/gmm.py
Write documentation strings for class attributes
import numpy as np from numpy.lib.stride_tricks import as_strided from ..utils.windows import WindowInitializer ####################################################################### # Signal Resampling # ##############################################################...
--- +++ @@ -9,6 +9,24 @@ def batch_resample(X, new_dim, mode="bilinear"): + """ + Resample each image (or similar grid-based 2D signal) in a batch to + `new_dim` using the specified resampling strategy. + + Parameters + ---------- + X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_rows,...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/preprocessing/dsp.py
Document this module using docstrings
from abc import ABC, abstractmethod import numpy as np from numpy_ml.utils.testing import random_one_hot_matrix, is_number class Bandit(ABC): def __init__(self, rewards, reward_probs, context=None): assert len(rewards) == len(reward_probs) self.step = 0 self.n_arms = len(rewards) ...
--- +++ @@ -1,3 +1,4 @@+"""A module containing different variations on multi-armed bandit environments.""" from abc import ABC, abstractmethod @@ -15,25 +16,58 @@ super().__init__() def __repr__(self): + """A string representation for the bandit""" HP = self.hyperparameters ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/bandits/bandits.py
Write docstrings for backend logic
import warnings import os.path as op from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning try: import matplotlib.pyplot as plt _PLOTTING = True except ImportError: fstr = "Cannot import matplotlib. Plotting functionality disabled." warnings.war...
--- +++ @@ -1,3 +1,4 @@+"""A trainer/runner object for executing and comparing MAB policies.""" import warnings import os.path as op @@ -18,10 +19,15 @@ def get_scriptdir(): + """Return the directory containing the `trainer.py` script""" return op.dirname(op.realpath(__file__)) def mse(bandit, poli...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/bandits/trainer.py
Create structured documentation for my script
import numpy as np class SmoothedLDA(object): def __init__(self, T, **kwargs): self.T = T self.alpha = (50.0 / self.T) * np.ones(self.T) if "alpha" in kwargs.keys(): self.alpha = (kwargs["alpha"]) * np.ones(self.T) self.beta = 0.01 if "beta" in kwargs.keys(): ...
--- +++ @@ -3,6 +3,32 @@ class SmoothedLDA(object): def __init__(self, T, **kwargs): + """ + A smoothed LDA model trained using collapsed Gibbs sampling. Generates + posterior mean estimates for model parameters `phi` and `theta`. + + Parameters + ---------- + T : int + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/lda/lda_smoothed.py
Write docstrings for data processing functions
import heapq from copy import copy from collections import Hashable import numpy as np from .distance_metrics import euclidean ####################################################################### # Priority Queue # ##############################################...
--- +++ @@ -13,6 +13,7 @@ class PQNode(object): def __init__(self, key, val, priority, entry_id, **kwargs): + """A generic node object for holding entries in :class:`PriorityQueue`""" self.key = key self.val = val self.entry_id = entry_id @@ -23,6 +24,7 @@ return fstr.fo...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/utils/data_structures.py
Add docstrings for utility scripts
from ..utils.kernels import KernelInitializer class KernelRegression: def __init__(self, kernel=None): self.parameters = {"X": None, "y": None} self.hyperparameters = {"kernel": str(kernel)} self.kernel = KernelInitializer(kernel)() def fit(self, X, y): self.parameters = {"X":...
--- +++ @@ -3,15 +3,68 @@ class KernelRegression: def __init__(self, kernel=None): + """ + A Nadaraya-Watson kernel regression model. + + Notes + ----- + The Nadaraya-Watson regression model is + + .. math:: + + f(x) = \sum_i w_i(x) y_i + + where the sa...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/nonparametric/kernel_regression.py
Add docstrings to existing functions
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): from ..initializers import SchedulerInitializer self.cache = {} self.cur_step = 0 self.hyperparameters ...
--- +++ @@ -7,6 +7,11 @@ class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): + """ + An abstract base class for all Optimizer objects. + + This should never be used directly. + """ from ..initializers import SchedulerInitializer self.cache = {} @@ -18...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/optimizers/optimizers.py
Generate docstrings with examples
from abc import ABC, abstractmethod import numpy as np from ..wrappers import init_wrappers, Dropout from ..initializers import ( WeightInitializer, OptimizerInitializer, ActivationInitializer, ) from ..utils import ( pad1D, pad2D, conv1D, conv2D, im2col, col2im, dilate, ...
--- +++ @@ -1,3 +1,4 @@+"""A collection of composable layer objects for building neural networks""" from abc import ABC, abstractmethod import numpy as np @@ -25,6 +26,7 @@ class LayerBase(ABC): def __init__(self, optimizer=None): + """An abstract base class inherited by all neural network layers""" ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/layers/layers.py
Create docstrings for all classes and functions
from time import time from collections import OrderedDict import numpy as np from ..losses import VAELoss from ..utils import minibatch from ..activations import ReLU, Affine, Sigmoid from ..layers import Conv2D, Pool2D, Flatten, FullyConnected class BernoulliVAE(object): def __init__( self, T=5...
--- +++ @@ -29,6 +29,91 @@ optimizer="RMSProp(lr=0.0001)", init="glorot_uniform", ): + """ + A variational autoencoder (VAE) with 2D convolutional encoder and Bernoulli + input and output units. + + Notes + ----- + The VAE architecture is + + .. cod...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/models/vae.py
Generate docstrings for this script
import json import hashlib import warnings import numpy as np try: from scipy.sparse import csr_matrix _SCIPY = True except ImportError: warnings.warn("Scipy not installed. FeatureHasher can only create dense matrices") _SCIPY = False def minibatch(X, batchsize=256, shuffle=True): N = X.shape[0...
--- +++ @@ -14,6 +14,29 @@ def minibatch(X, batchsize=256, shuffle=True): + """ + Compute the minibatch indices for a training dataset. + + Parameters + ---------- + X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, \*)` + The dataset to divide into minibatches. Assumes the first dimension...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/preprocessing/general.py
Add structured docstrings to improve clarity
from collections import Counter import numpy as np from ..utils.data_structures import BallTree class KNN: def __init__( self, k=5, leaf_size=40, classifier=True, metric=None, weights="uniform", ): self._ball_tree = BallTree(leaf_size=leaf_size, metric=metric) self.hyperparameters = ...
--- +++ @@ -1,3 +1,4 @@+"""A k-Nearest Neighbors (KNN) model for both classiciation and regression.""" from collections import Counter import numpy as np @@ -9,6 +10,30 @@ def __init__( self, k=5, leaf_size=40, classifier=True, metric=None, weights="uniform", ): + """ + A `k`-nearest...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/nonparametric/knn.py
Add structured docstrings to improve clarity
import numpy as np from .dt import DecisionTree from .losses import MSELoss, CrossEntropyLoss def to_one_hot(labels, n_classes=None): if labels.ndim > 1: raise ValueError("labels must have dimension 1, but got {}".format(labels.ndim)) N = labels.size n_cols = np.max(labels) + 1 if n_classes is N...
--- +++ @@ -25,6 +25,61 @@ loss="crossentropy", step_size="constant", ): + """ + A gradient boosted ensemble of decision trees. + + Notes + ----- + Gradient boosted machines (GBMs) fit an ensemble of `m` weak learners such that: + + .. math:: + + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/trees/gbdt.py
Create structured documentation for my script
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from math import erf def gaussian_cdf(x, mean, var): eps = np.finfo(float).eps x_scaled = (x - mean) / np.sqrt(var + eps) return (1 + erf(x_scaled / np.sqrt(2))) / 2 class SchedulerBase(ABC): def __init__(self): ...
--- +++ @@ -7,6 +7,10 @@ def gaussian_cdf(x, mean, var): + """ + Compute the probability that a random draw from a 1D Gaussian with mean + `mean` and variance `var` is less than or equal to `x`. + """ eps = np.finfo(float).eps x_scaled = (x - mean) / np.sqrt(var + eps) return (1 + erf(x_s...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/schedulers/schedulers.py
Write Python docstrings for this snippet
from math import floor from itertools import zip_longest basehash = hash class IHT: def __init__(self, sizeval): self.size = sizeval self.overfullCount = 0 self.dictionary = {} def __str__(self): return ( "Collision table:" + " size:" + ...
--- +++ @@ -1,3 +1,30 @@+""" +Tile Coding Software version 3.0beta +by Rich Sutton +based on a program created by Steph Schaeffer and others +External documentation and recommendations on the use of this code is available in the +reinforcement learning textbook by Sutton and Barto, and on the web. +These need to be und...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/rl_models/tiles/tiles3.py
Write proper docstrings for these functions
import numpy as np class GaussianNBClassifier: def __init__(self, eps=1e-6): self.labels = None self.hyperparameters = {"eps": eps} self.parameters = { "mean": None, # shape: (K, M) "sigma": None, # shape: (K, M) "prior": None, # shape: (K,) }...
--- +++ @@ -1,8 +1,73 @@+"""A module for naive Bayes classifiers""" import numpy as np class GaussianNBClassifier: def __init__(self, eps=1e-6): + r""" + A naive Bayes classifier for real-valued data. + + Notes + ----- + The naive Bayes model assumes the features of each tr...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/linear_models/naive_bayes.py
Can you add docstrings to this Python file?
from copy import deepcopy import numpy as np class VanillaALS: def __init__(self, K, alpha=1, max_iter=200, tol=1e-4): self.K = K self.W = None self.H = None self.tol = tol self.alpha = alpha self.max_iter = max_iter @property def parameters(self): ...
--- +++ @@ -1,3 +1,4 @@+"""Algorithms for approximate matrix factorization""" from copy import deepcopy @@ -6,6 +7,52 @@ class VanillaALS: def __init__(self, K, alpha=1, max_iter=200, tol=1e-4): + r""" + Approximately factor a real-valued matrix using regularized alternating + least-squ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/factorization/factors.py
Document my Python code with docstrings
import asyncio import logging import warnings from collections.abc import ( AsyncIterator, Awaitable, Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence, ) from contextlib import AbstractAsyncContextManager, asynccontextmanager from functools import lru_cache, partial, updat...
--- +++ @@ -54,6 +54,7 @@ def _build_middlewares( handler: Handler, apps: tuple["Application", ...] ) -> Callable[[Request], Awaitable[StreamResponse]]: + """Apply middlewares to handler.""" # The slice is to reverse the order of the apps # so they are applied in the order they were added for ap...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_app.py
Generate docstrings with parameter types
import numpy as np class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): self.beta = None self.alpha = alpha self.fit_intercept = fit_intercept def fit(self, X, y): # convert X to a design matrix if we're fitting an intercept if self.fit_intercept: ...
--- +++ @@ -1,14 +1,79 @@+"""Ridge regression module""" import numpy as np class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): + r""" + A ridge regression model with maximum likelihood fit via the normal + equations. + + Notes + ----- + Ridge re...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/linear_models/ridge.py
Generate docstrings with examples
import warnings from collections.abc import Iterable from http import HTTPStatus from typing import Any from multidict import CIMultiDict from yarl import URL from . import hdrs from .helpers import CookieMixin from .typedefs import LooseHeaders, StrOrURL __all__ = ( "HTTPException", "HTTPError", "HTTPRe...
--- +++ @@ -73,6 +73,7 @@ class NotAppKeyWarning(UserWarning): + """Warning when not using AppKey in Application.""" ############################################################ @@ -169,12 +170,15 @@ class HTTPError(HTTPException): + """Base class for exceptions with status codes in the 400s and 500s...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_exceptions.py
Add docstrings for better understanding
from time import time import numpy as np class Trainer(object): def __init__(self, agent, env): self.env = env self.agent = agent self.rewards = {"total": [], "smooth_total": [], "n_steps": [], "duration": []} def _train_episode(self, max_steps, render_every=None): t0 = time()...
--- +++ @@ -4,6 +4,16 @@ class Trainer(object): def __init__(self, agent, env): + """ + An object to facilitate agent training and evaluation. + + Parameters + ---------- + agent : :class:`AgentBase` instance + The agent to train. + env : ``gym.wrappers`` or `...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/rl_models/trainer.py
Provide docstrings following PEP 257
from abc import ABC, abstractmethod import re import numpy as np from ..wrappers import Dropout from ..utils import calc_pad_dims_2D from ..activations import Tanh, Sigmoid, ReLU, LeakyReLU, Affine from ..layers import ( DotProductAttention, FullyConnected, BatchNorm2D, Conv1D, Conv2D, Multipl...
--- +++ @@ -126,6 +126,49 @@ optimizer=None, init="glorot_uniform", ): + """ + A WaveNet-like residual block with causal dilated convolutions. + + .. code-block:: text + + *Skip path in* >-------------------------------------------> + ---> *Skip path out* + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/neural_nets/modules/modules.py
Add docstrings for utility scripts
import textwrap from abc import ABC, abstractmethod from collections import Counter import numpy as np from numpy_ml.linear_models import LinearRegression from numpy_ml.preprocessing.nlp import tokenize_words, ngrams, strip_punctuation class NGramBase(ABC): def __init__(self, N, unk=True, filter_stopwords=True,...
--- +++ @@ -1,3 +1,4 @@+"""A module for different N-gram smoothing models""" import textwrap from abc import ABC, abstractmethod from collections import Counter @@ -10,6 +11,16 @@ class NGramBase(ABC): def __init__(self, N, unk=True, filter_stopwords=True, filter_punctuation=True): + """ + A sim...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/ngram/ngram.py
Add minimal docstrings for each function
import asyncio import builtins from collections import deque from typing import Final from ..base_protocol import BaseProtocol from ..compression_utils import ZLibDecompressor from ..helpers import _EXC_SENTINEL, set_exception from ..streams import EofStream from .helpers import UNPACK_CLOSE_CODE, UNPACK_LEN3, websoc...
--- +++ @@ -1,3 +1,4 @@+"""Reader for WebSocket protocol versions 13 and 8.""" import asyncio import builtins @@ -57,6 +58,10 @@ class WebSocketDataQueue: + """WebSocketDataQueue resumes and pauses an underlying stream. + + It is a destination for WebSocket data. + """ def __init__( sel...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/_websocket/reader_py.py
Add docstrings for internal functions
import asyncio from contextlib import suppress from typing import Callable, Protocol from ._websocket.reader import WebSocketDataQueue from .base_protocol import BaseProtocol from .client_exceptions import ( ClientConnectionError, ClientOSError, ClientPayloadError, ServerDisconnectedError, SocketTi...
--- +++ @@ -29,6 +29,7 @@ class ResponseHandler(BaseProtocol, DataQueue[tuple[RawResponseMessage, StreamReader]]): + """Helper class to adapt between Protocol and StreamReader.""" def __init__(self, loop: asyncio.AbstractEventLoop) -> None: BaseProtocol.__init__(self, loop=loop) @@ -57,6 +58,18 @...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/client_proto.py
Write Python docstrings for this snippet
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): N, M = X.shape idxs = np.random.choice(N, N, replace=True) return X[idxs], Y[idxs] class RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): self.trees =...
--- +++ @@ -12,6 +12,28 @@ def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): + """ + An ensemble (forest) of decision trees where each split is calculated + using a random subset of the features in the input. + + Parameters + --...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/trees/rf.py
Generate docstrings for this script
import numpy as np def logsumexp(log_probs, axis=None): _max = np.max(log_probs) ds = log_probs - _max exp_sum = np.exp(ds).sum(axis=axis) return _max + np.log(exp_sum) def log_gaussian_pdf(x_i, mu, sigma): n = len(mu) a = n * np.log(2 * np.pi) _, b = np.linalg.slogdet(sigma) y = np...
--- +++ @@ -1,7 +1,12 @@+"""Miscellaneous utility functions""" import numpy as np def logsumexp(log_probs, axis=None): + """ + Redefine scipy.special.logsumexp + see: http://bayesjumping.net/log-sum-exp-trick/ + """ _max = np.max(log_probs) ds = log_probs - _max exp_sum = np.exp(ds).sum...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/utils/misc.py
Create documentation strings for testing functions
import re from abc import ABC, abstractmethod import numpy as np class KernelBase(ABC): def __init__(self): super().__init__() self.parameters = {} self.hyperparameters = {} @abstractmethod def _kernel(self, X, Y): raise NotImplementedError def __call__(self, X, Y=No...
--- +++ @@ -15,6 +15,7 @@ raise NotImplementedError def __call__(self, X, Y=None): + """Refer to documentation for the `_kernel` method""" return self._kernel(X, Y) def __str__(self): @@ -23,6 +24,7 @@ return "{}({})".format(H["id"], p_str) def summary(self): + ...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/utils/kernels.py
Add well-formatted docstrings
import numpy as np def euclidean(x, y): return np.sqrt(np.sum((x - y) ** 2)) def manhattan(x, y): return np.sum(np.abs(x - y)) def chebyshev(x, y): return np.max(np.abs(x - y)) def minkowski(x, y, p): return np.sum(np.abs(x - y) ** p) ** (1 / p) def hamming(x, y): return np.sum(x != y) / l...
--- +++ @@ -2,20 +2,131 @@ def euclidean(x, y): + """ + Compute the Euclidean (`L2`) distance between two real vectors + + Notes + ----- + The Euclidean distance between two vectors **x** and **y** is + + .. math:: + + d(\mathbf{x}, \mathbf{y}) = \sqrt{ \sum_i (x_i - y_i)^2 } + + Parame...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/utils/distance_metrics.py
Add docstrings for internal functions
import numpy as np def blackman_harris(window_len, symmetric=False): return generalized_cosine( window_len, [0.35875, 0.48829, 0.14128, 0.01168], symmetric ) def hamming(window_len, symmetric=False): return generalized_cosine(window_len, [0.54, 1 - 0.54], symmetric) def hann(window_len, symmet...
--- +++ @@ -2,20 +2,140 @@ def blackman_harris(window_len, symmetric=False): + """ + The Blackman-Harris window. + + Notes + ----- + The Blackman-Harris window is an instance of the more general class of + cosine-sum windows where `K=3`. Additional coefficients extend the Hamming + window to fu...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/utils/windows.py
Write proper docstrings for these functions
from abc import ABC, abstractmethod from collections import defaultdict from itertools import combinations, permutations import numpy as np ####################################################################### # Graph Components # ##################################...
--- +++ @@ -11,6 +11,21 @@ class Edge(object): def __init__(self, fr, to, w=None): + """ + A generic directed edge object. + + Parameters + ---------- + fr: int + The id of the vertex the edge goes from + to: int + The id of the vertex the edge goes...
https://raw.githubusercontent.com/ddbourgin/numpy-ml/HEAD/numpy_ml/utils/graphs.py
Add docstrings for utility scripts
from types import SimpleNamespace from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, overload from aiosignal import Signal from multidict import CIMultiDict from yarl import URL from .client_reqrep import ClientResponse from .helpers import frozen_dataclass_decorator if TYPE_CHECKING: from .clien...
--- +++ @@ -42,6 +42,7 @@ class TraceConfig(Generic[_T]): + """First-class used to trace requests launched via ClientSession objects.""" @overload def __init__(self: "TraceConfig[SimpleNamespace]") -> None: ... @@ -100,6 +101,7 @@ self._trace_config_ctx_factory: _Factory[_T] = trace_config_ct...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/tracing.py
Help me comply with documentation standards
import asyncio import socket import weakref from typing import Any, Optional from .abc import AbstractResolver, ResolveResult __all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver") try: import aiodns aiodns_default = hasattr(aiodns.DNSResolver, "getaddrinfo") except ImportError: aiodns = No...
--- +++ @@ -25,6 +25,11 @@ class ThreadedResolver(AbstractResolver): + """Threaded resolver. + + Uses an Executor for synchronous getaddrinfo() calls. + concurrent.futures.ThreadPoolExecutor is used by default. + """ def __init__(self) -> None: self._loop = asyncio.get_running_loop() @@ ...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/resolver.py
Annotate my code with docstrings
import io from collections import deque from collections.abc import Iterable from typing import Any from urllib.parse import urlencode from multidict import MultiDict, MultiDictProxy from . import hdrs, multipart, payload from .helpers import guess_filename from .payload import Payload __all__ = ("FormData",) clas...
--- +++ @@ -14,6 +14,10 @@ class FormData: + """Helper class for form body generation. + + Supports multipart/form-data and application/x-www-form-urlencoded. + """ def __init__( self, @@ -122,6 +126,7 @@ ) def _gen_form_data(self) -> multipart.MultipartWriter: + """En...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/formdata.py
Add minimal docstrings for each function
import asyncio import base64 import binascii import contextlib import dataclasses import datetime import enum import functools import inspect import netrc import os import platform import re import sys import time import warnings import weakref from collections import namedtuple from collections.abc import Callable, I...
--- +++ @@ -1,3 +1,4 @@+"""Various helper functions""" import asyncio import base64 @@ -118,6 +119,7 @@ class BasicAuth(namedtuple("BasicAuth", ["login", "password", "encoding"])): + """Http basic authentication helper.""" def __new__( cls, login: str, password: str = "", encoding: str = "lat...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/helpers.py
Generate NumPy-style docstrings
import calendar import contextlib import datetime import heapq import itertools import json import os # noqa import pathlib import pickle import re import time import warnings from collections import defaultdict from collections.abc import Iterable, Iterator, Mapping from http.cookies import BaseCookie, Morsel, Simple...
--- +++ @@ -39,6 +39,14 @@ class _RestrictedCookieUnpickler(pickle.Unpickler): + """A restricted unpickler that only allows cookie-related types. + + This prevents arbitrary code execution when loading pickled cookie data + from untrusted sources. Only types that are expected in a serialized + CookieJar...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/cookiejar.py
Fully document this Python code with docstrings
import asyncio import base64 import dataclasses import hashlib import json import os import sys import traceback import warnings from collections.abc import ( Awaitable, Callable, Collection, Coroutine, Generator, Iterable, Sequence, ) from contextlib import suppress from types import Trace...
--- +++ @@ -1,3 +1,4 @@+"""HTTP Client for asyncio.""" import asyncio import base64 @@ -269,6 +270,7 @@ @final class ClientSession: + """First-class interface for making HTTP requests.""" __slots__ = ( "_base_url", @@ -462,6 +464,7 @@ def request( self, method: str, url: S...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/client.py
Turn comments into proper docstrings
import asyncio import logging import time from collections.abc import AsyncIterator, Sequence from contextlib import asynccontextmanager, suppress from aiohttp import ( ClientError, ClientHandlerType, ClientRequest, ClientResponse, ClientSession, TCPConnector, ) from aiohttp.abc import Resolve...
--- +++ @@ -1,3 +1,4 @@+"""This is a collection of semi-complete examples that get included into the cookbook page.""" import asyncio import logging @@ -18,6 +19,7 @@ class SSRFError(ClientError): + """A request was made to a blacklisted host.""" async def retry_middleware( @@ -138,4 +140,4 @@ #...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/docs/code/client_middleware_cookbook.py
Create structured documentation for my script
# modified from https://tex.stackexchange.com/a/521639 import argparse import re import logging from collections import Counter import time from pix2tex.dataset.extract_latex import remove_labels class DemacroError(Exception): pass def main(): args = parse_command_line() data = read(args.input) dat...
--- +++ @@ -35,6 +35,9 @@ def bracket_replace(string: str) -> str: + ''' + replaces all layered brackets with special symbols + ''' layer = 0 out = list(string) for i, c in enumerate(out): @@ -118,6 +121,15 @@ def pydemacro(t: str) -> str: + r"""Replaces all occurences of newly define...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/dataset/demacro.py
Write docstrings for utility functions
#!/usr/bin/env python3 import argparse import os import sys def _check_file( main_file ): if os.path.exists(main_file): return raise FileNotFoundError( f'Unable to find file {main_file}' ) def _make_desktop_file( desktop_path, desktop_entry ): with open(desktop_path, 'w...
--- +++ @@ -1,5 +1,6 @@ #!/usr/bin/env python3 +'''Simple installer for the graphical user interface of pix2tex''' import argparse import os @@ -28,6 +29,7 @@ gui_file = 'gui.py', icon_file = 'resources/icon.svg', ): + '''Main function for setting up .desktop files (on Linux)''' parser = argpars...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/setup_desktop.py
Generate docstrings for each module
import os import sys import random from tqdm import tqdm import html import requests import re import argparse import logging from typing import Callable, List, Tuple from pix2tex.dataset.extract_latex import find_math htmltags = re.compile(r'<(noscript|script)>.*?<\/\1>', re.S) wikilinks = re.compile(r'href="/wiki/(....
--- +++ @@ -21,6 +21,19 @@ def recursive_search(parser: Callable, seeds: List[str], depth: int = 2, skip: List[str] = [], unit: str = 'links', base_url: str = None, **kwargs) -> Tuple[List[str], List[str]]: + """Find math recursively. Look in `seeds` for math and further sites to look. + + Args: + par...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/dataset/scraping.py