instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Create docstrings for all classes and functions
import collections import copy import hashlib import itertools import os import re import shutil import string import struct import sys import tempfile from pwnlib import abi from pwnlib import constants from pwnlib.context import LocalContext from pwnlib.context import context from pwnlib.elf import ELF from pwnlib.l...
--- +++ @@ -1,3 +1,362 @@+r""" +Return Oriented Programming + +Manual ROP +------------------- + +The ROP tool can be used to build stacks pretty trivially. +Let's create a fake binary which has some symbols which might +have been useful. + + >>> context.clear(arch='i386') + >>> binary = ELF.from_assembly('add es...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/rop/rop.py
Write documentation strings for class attributes
import socket import socks from pwnlib.log import getLogger from pwnlib.timeout import Timeout from pwnlib.tubes.sock import sock log = getLogger(__name__) class remote(sock): def __init__(self, host, port, fam = "any", typ = "tcp", sock=None, ssl=False, ssl_context=None, ssl_a...
--- +++ @@ -8,6 +8,56 @@ log = getLogger(__name__) class remote(sock): + r"""Creates a TCP or UDP-connection to a remote host. It supports + both IPv4 and IPv6. + + The returned object supports all the methods from + :class:`pwnlib.tubes.sock` and :class:`pwnlib.tubes.tube`. + + Arguments: + ho...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/tubes/remote.py
Add docstrings that explain logic
import time import pwnlib class _DummyContextClass(object): def __enter__(self): pass def __exit__(self,*a): pass _DummyContext = _DummyContextClass() class _countdown_handler(object): def __init__(self, obj, timeout): self.obj = obj self.timeout = timeout def __enter__(self)...
--- +++ @@ -1,3 +1,6 @@+""" +Timeout encapsulation, complete with countdowns and scope managers. +""" import time import pwnlib @@ -57,6 +60,53 @@ maximum = Maximum(2**20) class Timeout(object): + """ + Implements a basic class which has a timeout, and support for + scoped timeout countdowns. + + Val...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/timeout.py
Generate documentation strings for clarity
import time as __time def sleep(n): end = __time.time() + n while True: left = end - __time.time() if left <= 0: break __time.sleep(left)
--- +++ @@ -1,11 +1,20 @@+"""Improved replacements for standard functions +""" import time as __time def sleep(n): + """sleep(n) + + Replacement for :func:`time.sleep()`, which does not return if a signal is received. + + Arguments: + n (int): Number of seconds to sleep. + """ end = __tim...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/replacements.py
Fully document this Python code with docstrings
from pwnlib.abi import ABI from pwnlib.context import context from pwnlib.util import packing from pwnlib.util.misc import align class Unresolved(object): pass class CurrentStackPointer(Unresolved): pass class NextGadgetAddress(Unresolved): pass class StackAdjustment(Unresolved): pass class A...
--- +++ @@ -1,3 +1,5 @@+"""Abstracting ROP calls +""" from pwnlib.abi import ABI from pwnlib.context import context from pwnlib.util import packing @@ -6,22 +8,80 @@ class Unresolved(object): + """ + Encapsulates logic for deferring evaluation of a value used + in a ROP chain which is in some way self-r...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/rop/call.py
Add docstrings to clarify complex logic
import logging import re from operator import itemgetter from sortedcontainers import SortedList from pwnlib.log import getLogger from pwnlib.memleak import MemLeak from pwnlib.util.cyclic import * from pwnlib.util.fiddling import randoms from pwnlib.util.misc import align from pwnlib.util.packing import * log = getL...
--- +++ @@ -1,3 +1,98 @@+r""" +Provide some tools to exploit format string bug + +Let's use this program as an example: + +:: + + #include <stdio.h> + #include <stdlib.h> + #include <unistd.h> + #include <sys/mman.h> + #define MEMORY_ADDRESS ((void*)0x11111000) + #define MEMORY_SIZE 1024 + #define ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/fmtstr.py
Document functions with clear intent
from copy import deepcopy from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util.packing import * from pwnlib.util.packing import _need_bytes from pwnlib.util.misc import align log = getLogger(__name__) ELF32_R_SYM_SHIFT = 8 ELF64_R_SYM_SHIFT = 32 class Elf32_Rel(object): """ ...
--- +++ @@ -1,3 +1,69 @@+r""" +Provides automatic payload generation for exploiting buffer overflows +using ret2dlresolve. + +We use the following example program: + +:: + + #include <unistd.h> + void vuln(void){ + char buf[64]; + read(STDIN_FILENO, buf, 200); + } + int main(int argc, char** a...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/rop/ret2dlresolve.py
Replace inline comments with docstrings
import ctypes import functools import string from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util.packing import pack, _p8lu from pwnlib.util.packing import unpack log = getLogger(__name__) __all__ = ['MemLeak', 'RelativeMemLeak'] class MemLeak(object): def __init__(self, f, sear...
--- +++ @@ -12,6 +12,71 @@ __all__ = ['MemLeak', 'RelativeMemLeak'] class MemLeak(object): + """MemLeak is a caching and heuristic tool for exploiting memory leaks. + + It can be used as a decorator, around functions of the form: + + def some_leaker(addr): + ... + return data_as_st...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/memleak.py
Add structured docstrings to improve clarity
import os import sys import tempfile from pwnlib.context import LocalContext, context from pwnlib.elf import ELF from pwnlib.tubes.process import process __all__ = ['run_assembly', 'run_shellcode', 'run_assembly_exitcode', 'run_shellcode_exitcode'] @LocalContext def run_assembly(assembly): if context.os == 'darw...
--- +++ @@ -10,6 +10,25 @@ @LocalContext def run_assembly(assembly): + """ + Given an assembly listing, assemble and execute it. + + Returns: + + A :class:`pwnlib.tubes.process.process` tube to interact with the process. + + Example: + + >>> p = run_assembly('mov ebx, 3; mov eax, SYS_exit; ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/runner.py
Write docstrings describing functionality
from pwnlib.context import context class Buffer(object): def __init__(self, buffer_fill_size = None): self.data = [] # Buffer self.size = 0 # Length self.buffer_fill_size = buffer_fill_size def __len__(self): return self.size def __nonzero__(self): return len(sel...
--- +++ @@ -2,24 +2,76 @@ class Buffer(object): + """ + List of strings with some helper routines. + + Example: + + >>> b = Buffer() + >>> b.add(b"A" * 10) + >>> b.add(b"B" * 10) + >>> len(b) + 20 + >>> b.get(1) + b'A' + >>> len(b) + 19 + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/tubes/buffer.py
Write documentation strings for class attributes
import logging import os import random import re import string import sys import threading import time from pwnlib import term from pwnlib.config import register_config from pwnlib.context import Thread from pwnlib.context import context from pwnlib.exception import PwnlibException from pwnlib.term import spinners fro...
--- +++ @@ -1,3 +1,96 @@+""" +Logging module for printing status during an exploit, and internally +within ``pwntools``. + +Exploit Developers +------------------ +By using the standard ``from pwn import *``, an object named ``log`` will +be inserted into the global namespace. You can use this to print out +status mes...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/log.py
Document all endpoints with docstrings
from collections import namedtuple from pwnlib.abi import ABI from pwnlib.context import LocalContext from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util.packing import flat from pwnlib.util.packing import pack from pwnlib.util.packing import unpack_many log = getLogger(__name__) reg...
--- +++ @@ -1,3 +1,163 @@+r""" +Sigreturn ROP (SROP) + +Sigreturn is a syscall used to restore the entire register context +from memory pointed at by ESP. + +We can leverage this during ROP to gain control of registers for which +there are not convenient gadgets. The main caveat is that *all* registers +are set, inclu...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/rop/srop.py
Document functions with clear intent
import os import sys import tempfile import time from pwnlib.context import context from pwnlib.util.misc import read, write from pwnlib.util.packing import _encode, _decode from pathlib import * class SSHPath(PosixPath): sep = '/' def __init__(self, path, ssh=None): self.path = self._s(path) ...
--- +++ @@ -1,3 +1,8 @@+""" +Handles file abstraction for remote SSH files + +Emulates pathlib as much as possible, but does so through duck typing. +""" import os import sys import tempfile @@ -10,6 +15,52 @@ from pathlib import * class SSHPath(PosixPath): + r"""Represents a file that exists on a remote files...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/filesystem/ssh.py
Auto-generate documentation strings for this file
import os import time import tempfile import struct from pwnlib.context import context from pwnlib.elf import ELF from pwnlib.filesystem.path import Path from pwnlib.log import getLogger from pwnlib.tubes.process import process from pwnlib.util.fiddling import enhex, unhex from pwnlib.util.hashes import sha1filehex, s...
--- +++ @@ -1,3 +1,6 @@+""" +Fetch a LIBC binary based on some heuristics. +""" import os import time import tempfile @@ -19,6 +22,21 @@ def _turbofast_extract_build_id(path): + """ + Elf_External_Note: + + 0x00 +--------+ + | namesz | <- Size of entry's owner string + 0x04 +--------+ + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/libcdb.py
Add docstrings that explain inputs and outputs
import io import sys import os from pwnlib.term import keyconsts as kc from pwnlib.term import keymap as km from pwnlib.term import term from pwnlib.term import text cursor = text.reverse buffer_left, buffer_right = '', '' saved_buffer = None history = [] history_idx = None prompt_handle = None buffer_handle = None...
--- +++ @@ -422,12 +422,54 @@ shutdown_hook() def raw_input(prompt='', float=True): + r"""raw_input(prompt='', float=True) + + Replacement for the built-in ``raw_input`` using ``pwnlib`` readline + implementation. + + Arguments: + prompt(str): The prompt to show to the user. + f...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/term/readline.py
Add docstrings following best practices
import ctypes import errno import logging import os import select import signal import stat import subprocess import sys import time from collections import namedtuple IS_WINDOWS = sys.platform.startswith('win') if IS_WINDOWS: import queue import threading else: import fcntl import pty import reso...
--- +++ @@ -42,6 +42,185 @@ signal_names = {-v:k for k,v in signal.__dict__.items() if k.startswith('SIG')} class process(tube): + r""" + Spawns a new process, and wraps it with a tube for communication. + + Arguments: + + argv(list): + List of arguments to pass to the spawned process. + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/tubes/process.py
Create Google-style docstrings for my code
import ctypes from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util.packing import pack, unpack log = getLogger(__name__) length=0 size='size' name='name' variables={ 0:{name:'flags',size:length}, 1:{name:'_IO_read_ptr',size:length}, 2:{name:'_IO_read_end',size:length}, ...
--- +++ @@ -1,3 +1,24 @@+r""" +File Structure Exploitation + +struct FILE (_IO_FILE) is the structure for File Streams. +This offers various targets for exploitation on an existing bug in the code. +Examples - ``_IO_buf_base`` and ``_IO_buf_end`` for reading data to arbitrary location. + +Remembering the offsets of var...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/filepointer.py
Add minimal docstrings for each function
_const_codes = [ 'POP_TOP','ROT_TWO','ROT_THREE','ROT_FOUR','DUP_TOP', 'BUILD_LIST','BUILD_MAP', 'MAP_ADD', 'BUILD_TUPLE','BUILD_SET', 'BUILD_CONST_KEY_MAP', 'BUILD_STRING', 'LOAD_CONST','LOAD_SMALL_INT','RETURN_VALUE','STORE_SUBSCR', 'STORE_MAP', 'LIST_TO_TUPLE', 'LIST_EXTEND', 'SET_UPDATE', 'DICT_...
--- +++ @@ -20,10 +20,24 @@ _values_codes = _expr_codes + ['LOAD_NAME'] def _get_opcodes(codeobj): + """_get_opcodes(codeobj) -> [opcodes] + + Extract the actual opcodes as a list from a code object + + >>> c = compile("[1 + 2, (1,2)]", "", "eval") + >>> _get_opcodes(c) # doctest: +SKIP + [...100, 10...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/safeeval.py
Please document this code using docstrings
import abc import logging import os import re import string import subprocess import sys import threading import time from pwnlib import atexit from pwnlib import term from pwnlib.context import context from pwnlib.log import Logger from pwnlib.timeout import Timeout from pwnlib.tubes.buffer import Buffer from pwnlib....
--- +++ @@ -21,6 +21,9 @@ class tube(Timeout, Logger): + """ + Container of all the tube functions common to sockets, TTYs and SSH connetions. + """ default = Timeout.default forever = Timeout.forever @@ -37,6 +40,33 @@ atexit.register(self.close) def _normalize_keepends_drop(sel...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/tubes/tube.py
Add return value explanations in docstrings
import threading import time from pwnlib import term from pwnlib.term import text _banner = r''' .:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:. ) _____ _ _ ) ( | _ |___ _ _ _ ___ ___ ___ _| | | |_ _ _ ...
--- +++ @@ -1,3 +1,4 @@+"""Silly module mostly meant as an easter-egg.""" import threading import time @@ -23,6 +24,8 @@ ''' def splash(): + """Put this at the beginning of your exploit to create the illusion that + your sploit is enterprisey and top notch quality""" def updater(): @@ -63,4 +66,4 ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/splash.py
Add docstrings for better understanding
import string from pwnlib.context import context, LocalNoarchContext from pwnlib.log import getLogger from pwnlib.util import packing, iters log = getLogger(__name__) # Taken from https://en.wikipedia.org/wiki/De_Bruijn_sequence but changed to a generator def de_bruijn(alphabet = None, n = None): if alphabet is ...
--- +++ @@ -8,6 +8,17 @@ # Taken from https://en.wikipedia.org/wiki/De_Bruijn_sequence but changed to a generator def de_bruijn(alphabet = None, n = None): + """de_bruijn(alphabet = None, n = None) -> generator + + Generator for a sequence of unique substrings of length `n`. This is implemented using a + De...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/cyclic.py
Add docstrings to existing functions
import ctypes import ctypes.util import socket from pwnlib.util.packing import p16 from pwnlib.util.packing import p32 from pwnlib.util.packing import pack __all__ = ['getifaddrs', 'interfaces', 'interfaces4', 'interfaces6', 'sockaddr'] # /usr/src/linux-headers-3.12-1-common/include/uapi/linux/socket.h sa_family_t =...
--- +++ @@ -74,6 +74,21 @@ return family, addr def getifaddrs(): + """getifaddrs() -> dict list + + A wrapper for libc's ``getifaddrs``. + + Arguments: + None + + Returns: + list of dictionaries each representing a `struct ifaddrs`. The + dictionaries have the fields `name`, `flags`, `...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/net.py
Please document this code using docstrings
import string import subprocess from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.tubes.process import process from pwnlib.util import fiddling from pwnlib.util.misc import which, normalize_argv_env log = getLogger(__name__) def test_all(): test('a') ## test('ab') ## test('a...
--- +++ @@ -1,3 +1,242 @@+r""" +Routines here are for getting any NULL-terminated sequence of bytes evaluated +intact by any shell. This includes all variants of quotes, whitespace, and +non-printable characters. + +Supported Shells +---------------- + +The following shells have been evaluated: + +- Ubuntu (dash/sh) +...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/sh_string.py
Write docstrings for utility functions
__all__ = ['getall', 'random'] import os import random as randommod _cache = None def _load(): global _cache if _cache is None: _cache = set() with open(os.path.join(os.path.dirname(__file__), 'data/useragents/useragents.txt' ), 'r...
--- +++ @@ -1,3 +1,6 @@+""" +Database of >22,000 user agent strings +""" __all__ = ['getall', 'random'] import os @@ -18,7 +21,39 @@ return _cache def getall(): + """getall() -> str set + + Get all the user agents that we know about. + + Arguments: + None + + Returns: + A set of use...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/useragents.py
Generate consistent documentation across files
import base64 import binascii import random import re import os import string from io import BytesIO from pwnlib.context import LocalNoarchContext from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.term import text from pwnlib.util import iters from pwnlib.util import lists from pwnlib.ut...
--- +++ @@ -21,6 +21,19 @@ log = getLogger(__name__) def unhex(s): + r"""unhex(s) -> str + + Hex-decodes a string. + + Example: + + >>> unhex("74657374") + b'test' + >>> unhex("F\n") + b'\x0f' + >>> unhex(bytearray(b" F ")) + b'\x0f' + """ s = s.strip() ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/fiddling.py
Help me comply with documentation standards
import atexit import os import signal import subprocess from pwnlib import tubes from pwnlib.context import LocalContext from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util import misc from pwnlib.util import proc log = getLogger(__name__) CREATE_SUSPENDED = 0x00000004 @LocalContex...
--- +++ @@ -1,103 +1,236 @@-import atexit -import os -import signal - -import subprocess - -from pwnlib import tubes -from pwnlib.context import LocalContext -from pwnlib.context import context -from pwnlib.log import getLogger -from pwnlib.util import misc -from pwnlib.util import proc - -log = getLogger(__name__) - -...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/windbg.py
Create docstrings for each class method
import logging import os import re import shutil import string import sys import tarfile import tempfile import threading import time from pwnlib import term from pwnlib.context import context, LocalContext from pwnlib.exception import PwnlibException from pwnlib.log import Logger from pwnlib.log import getLogger from...
--- +++ @@ -136,6 +136,10 @@ h.success() def kill(self): + """kill() + + Kills the process. + """ self.close() @@ -167,6 +171,11 @@ return self.poll(block=True) def poll(self, block=False): + """poll() -> int + + Poll the exit code of the...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/tubes/ssh.py
Add missing documentation to my Python functions
from pwnlib.context import context from pwnlib.util.packing import unpack from pwnlib.log import getLogger from enum import IntEnum log = getLogger(__name__) class Dtype(IntEnum): DT_UNK = 0 DT_FIFO = 1 DT_CHR = 2 DT_DIR = 4 DT_BLK = 6 DT_REG = 8 DT_LNK = 10 DT_SOCK = 12 DT_WHT = 1...
--- +++ @@ -18,6 +18,46 @@ DT_SUBVOL = 16 class linux_dirent: + """ + Represent struct linux_dirent + + .. code-block:: c + + struct linux_dirent + { + unsigned long d_ino; + unsigned long d_off; + unsigned short d_reclen; + char d_name[]; + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/getdents.py
Add docstrings following best practices
import errno import select import socket from pwnlib.log import getLogger from pwnlib.tubes.tube import tube log = getLogger(__name__) class sock(tube): def __init__(self, *args, **kwargs): super(sock, self).__init__(*args, **kwargs) self.closed = {"recv": False, "send": False} # Overwritte...
--- +++ @@ -8,6 +8,7 @@ log = getLogger(__name__) class sock(tube): + """Base type used for :class:`.tubes.remote` and :class:`.tubes.listen` classes""" def __init__(self, *args, **kwargs): super(sock, self).__init__(*args, **kwargs) @@ -15,6 +16,10 @@ # Overwritten for better usability ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/tubes/sock.py
Add docstrings to improve readability
import os import signal import string import struct import subprocess import sys import time from pwnlib import term from pwnlib.log import getLogger from pwnlib.term.readline import raw_input from pwnlib.tubes.process import process log = getLogger(__name__) def testpwnproc(cmd): import fcntl import termios...
--- +++ @@ -45,6 +45,44 @@ return p def yesno(prompt, default=None): + r"""Presents the user with prompt (typically in the form of question) + which the user must answer yes or no. + + Arguments: + prompt (str): The prompt to show + default: The default option; `True` means "yes" + + Retur...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/ui.py
Add docstrings to improve code quality
import datetime import json import os import time import packaging.version from pwnlib.args import args from pwnlib.config import register_config from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util.misc import read from pwnlib.util.misc import write from pwnlib.util.web import wget fr...
--- +++ @@ -1,3 +1,24 @@+""" +# Pwntools Update + +In order to ensure that Pwntools users always have the latest and +greatest version, Pwntools automatically checks for updates. + +Since this update check takes a moment, it is only performed once +every week. It can be permanently disabled via: + +:: + + $ echo ne...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/update.py
Add docstrings to clarify complex logic
import json import base64 import errno import os import re import signal import socket import stat import string import subprocess import sys import tempfile import inspect import time import types from pwnlib import atexit from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.timeout import ...
--- +++ @@ -25,18 +25,73 @@ log = getLogger(__name__) def align(alignment, x): + """align(alignment, x) -> int + + Rounds `x` up to nearest multiple of the `alignment`. + + Example: + + >>> [align(5, n) for n in range(15)] + [0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15] + """ retu...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/misc.py
Add well-formatted docstrings
import sys import types from pwnlib.util import fiddling from pwnlib.util import packing from pwnlib.util import safeeval from pwnlib.util.crc import known class BitPolynom(object): def __init__(self, n): if isinstance(n, (bytes, bytearray, str)): from pwnlib.util.packing import _need_text ...
--- +++ @@ -1,3 +1,22 @@+"""Module for calculating CRC-sums. + +Contains all crc implementations know on the interwebz. For most implementations +it contains only the core crc algorithm and not e.g. padding schemes. + +It is horribly slow, as implements a naive algorithm working direclty on +bit polynomials. This class...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/crc/__init__.py
Create documentation strings for testing functions
import collections import copy import marshal import multiprocessing import operator import random import time import types from itertools import * from pwnlib.context import context from pwnlib.log import getLogger __all__ = [ 'bruteforce' , 'mbruteforce' ...
--- +++ @@ -1,3 +1,6 @@+""" +This module includes and extends the standard module :mod:`itertools`. +""" import collections import copy import marshal @@ -61,12 +64,83 @@ log = getLogger(__name__) def take(n, iterable): + """take(n, iterable) -> list + + Returns first `n` elements of `iterable`. If `iterab...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/iters.py
Can you add docstrings to this Python file?
import errno import socket import sys import time import psutil from pwnlib import tubes from pwnlib.log import getLogger from .net import sock_match from pwnlib.timeout import Timeout log = getLogger(__name__) all_pids = psutil.pids def pidof(target): if isinstance(target, tubes.ssh.ssh_channel): retu...
--- +++ @@ -15,6 +15,34 @@ all_pids = psutil.pids def pidof(target): + """pidof(target) -> int list + + Get PID(s) of `target`. The returned PID(s) depends on the type of `target`: + + - :class:`str`: PIDs of all processes with a name matching `target`. + - :class:`pwnlib.tubes.process.process`: singlet...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/proc.py
Create simple docstrings for beginners
import collections def partition(lst, f, save_keys = False): d = collections.OrderedDict() for l in lst: c = f(l) s = d.setdefault(c, []) s.append(l) if save_keys: return d else: return list(d.values()) def group(n, lst, underfull_action = 'ignore', fill_value...
--- +++ @@ -2,6 +2,27 @@ def partition(lst, f, save_keys = False): + """partition(lst, f, save_keys = False) -> list + + Partitions an iterable into sublists using a function to specify which + group they belong to. + + It works by calling `f` on every element and saving the results into + an :class:...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/lists.py
Add docstrings with type hints explained
import argparse import importlib.metadata import json import logging import multiprocessing import os import pprint import sys import time import traceback from collections.abc import Iterable # Combines all paths to `pelican` package accessible from `sys.path` # Makes it possible to install `pelican` and namespace pl...
--- +++ @@ -46,6 +46,10 @@ class Pelican: def __init__(self, settings): + """Pelican initialization + + Performs some checks on the environment before doing anything else. + """ # define the default settings self.settings = settings @@ -86,6 +90,7 @@ self.settings...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/__init__.py
Expand my code with proper documentation strings
import calendar import errno import fnmatch import logging import os from collections import defaultdict from functools import partial from itertools import chain, groupby from operator import attrgetter from jinja2 import ( BaseLoader, ChoiceLoader, Environment, FileSystemLoader, PrefixLoader, ...
--- +++ @@ -39,6 +39,7 @@ class Generator: + """Baseclass generator""" def __init__( self, @@ -110,6 +111,10 @@ signals.generator_init.send(self) def get_template(self, name): + """Return the template by name. + Use self.theme to get the templates to use, and return a...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/generators.py
Fill in missing docstrings in my code
#!/usr/bin/env python import argparse import os import shutil import sys def err(msg, die=None): sys.stderr.write(msg + "\n") if die: sys.exit(die if isinstance(die, int) else 1) try: import pelican except ImportError: err( "Cannot import pelican.\nYou must install Pelican in order ...
--- +++ @@ -7,6 +7,7 @@ def err(msg, die=None): + """Print an error message and exits if an exit code is given""" sys.stderr.write(msg + "\n") if die: sys.exit(die if isinstance(die, int) else 1) @@ -30,6 +31,7 @@ def main(): + """Main function""" parser = argparse.ArgumentParser...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/tools/pelican_themes.py
Auto-generate documentation strings for this file
import copy import datetime import locale import logging import os import re from html import unescape from typing import Any from urllib.parse import ParseResult, unquote, urljoin, urlparse, urlunparse try: from zoneinfo import ZoneInfo except ModuleNotFoundError: from backports.zoneinfo import ZoneInfo fro...
--- +++ @@ -35,6 +35,15 @@ class Content: + """Represents a content. + + :param content: the string to parse, containing the original content. + :param metadata: the metadata associated to this page (optional). + :param settings: the settings dictionary (optional). + :param source_path: The location ...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/contents.py
Generate consistent docstrings
from __future__ import annotations import datetime import fnmatch import locale import logging import os import pathlib import re import shutil import traceback import unicodedata import urllib from collections.abc import ( Callable, Collection, Generator, Hashable, Iterable, Sequence, ) from c...
--- +++ @@ -58,6 +58,13 @@ def strftime(date: datetime.datetime, date_format: str) -> str: + """ + Enhanced replacement for built-in strftime with zero stripping + + This works by 'grabbing' possible format strings (those starting with %), + formatting them with the date, stripping any leading zeros if ...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/utils.py
Write Python docstrings for this snippet
import gzip import hashlib import logging import os import pickle from pelican.utils import mkdir_p logger = logging.getLogger(__name__) class FileDataCacher: def __init__(self, settings, cache_name, caching_policy, load_policy): self.settings = settings self._cache_path = os.path.join(self.set...
--- +++ @@ -10,8 +10,15 @@ class FileDataCacher: + """Class that can cache data contained in files""" def __init__(self, settings, cache_name, caching_policy, load_policy): + """Load the specified cache within CACHE_PATH in settings + + only if *load_policy* is True, + May use gzip if...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/cache.py
Add docstrings to make code maintainable
import functools import logging import os from collections import namedtuple from math import ceil logger = logging.getLogger(__name__) PaginationRule = namedtuple( # noqa: PYI024 "PaginationRule", "min_page URL SAVE_AS", ) class Paginator: def __init__(self, name, url, object_list, settings, per_page=N...
--- +++ @@ -27,6 +27,7 @@ self._num_pages = self._count = None def page(self, number): + "Returns a Page object for the given 1-based page number." bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: @@ -41,6 +42,7 @@ ...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/paginator.py
Provide clean and structured docstrings
#!/usr/bin/env python import argparse import datetime import json import logging import os import re import subprocess import sys import tempfile import time import urllib.request as urllib_request from collections import defaultdict from html import unescape from urllib.error import URLError from urllib.parse import ...
--- +++ @@ -119,6 +119,7 @@ def _import_bs4(): + """Import and return bs4, otherwise sys.exit.""" try: import bs4 # noqa: PLC0415 except ImportError: @@ -131,6 +132,7 @@ def file_to_soup(xml, features="xml"): + """Reads a file, returns soup.""" bs4 = _import_bs4() with open(x...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/tools/pelican_import.py
Write docstrings describing functionality
import os from pathlib import Path from shutil import which from invoke import task from livereload import Server PKG_NAME = "pelican" PKG_PATH = Path(PKG_NAME) DOCS_PORT = int(os.environ.get("DOCS_PORT", "8000")) BIN_DIR = "bin" if os.name != "nt" else "Scripts" PTY = os.name != "nt" ACTIVE_VENV = os.environ.get("VI...
--- +++ @@ -23,11 +23,13 @@ @task def docbuild(c): + """Build documentation""" c.run(f"{VENV_BIN}/sphinx-build -W docs docs/_build", pty=PTY) @task(docbuild) def docserve(c): + """Serve docs at http://localhost:$DOCS_PORT/ (default port is 8000)""" server = Server() server.watch("docs/conf...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/tasks.py
Generate missing documentation strings
import datetime import logging import os import re from collections import OrderedDict from html import escape from html.parser import HTMLParser from io import StringIO import docutils import docutils.core import docutils.io from docutils.parsers.rst.languages import get_language as get_docutils_lang from docutils.wr...
--- +++ @@ -60,6 +60,17 @@ def ensure_metadata_list(text): + """Canonicalize the format of a list of authors or tags. This works + the same way as Docutils' "authors" field: if it's already a list, + those boundaries are preserved; otherwise, it must be a string; + if the string contains semicolons, it...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/readers.py
Generate docstrings for this script
import collections import struct import sys import warnings from pwnlib.context import LocalNoarchContext from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util import iters mod = sys.modules[__name__] log = getLogger(__name__) def pack(number, word_size = None, endianness = None, sign...
--- +++ @@ -1,3 +1,34 @@+r""" +Module for packing and unpacking integers. + +Simplifies access to the standard ``struct.pack`` and ``struct.unpack`` +functions, and also adds support for packing/unpacking arbitrary-width +integers. + +The packers are all context-aware for ``endian`` and ``signed`` arguments, +though th...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/util/packing.py
Add docstrings for internal functions
import copy import importlib.util import inspect import locale import logging import os import re import sys from os.path import isabs from pathlib import Path from types import ModuleType from typing import Any from pelican.log import LimitFilter from pelican.paginator import PaginationRule def load_source(name: st...
--- +++ @@ -231,6 +231,7 @@ def get_settings_from_module(module: ModuleType | None = None) -> Settings: + """Loads settings from a module, returns a dictionary.""" context = {} if module is not None: @@ -239,6 +240,7 @@ def get_settings_from_file(path: str) -> Settings: + """Loads settings fro...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/settings.py
Add docstrings to improve readability
import logging import warnings from collections import defaultdict from rich.console import Console from rich.logging import RichHandler __all__ = ["init"] console = Console() class LimitFilter(logging.Filter): LOGS_DEDUP_MIN_LEVEL = logging.WARNING _ignore = set() _raised_messages = set() _thres...
--- +++ @@ -11,6 +11,14 @@ class LimitFilter(logging.Filter): + """ + Remove duplicates records, and limit the number of records in the same + group. + + Groups are specified by the message to use when the number of records in + the same group hit the limit. + E.g.: log.warning(('43 is not the ans...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/log.py
Add docstrings that explain inputs and outputs
import logging import os from posixpath import join as posix_join from urllib.parse import urljoin from feedgenerator import Atom1Feed, Rss201rev2Feed, get_tag_uri from markupsafe import Markup from pelican.paginator import Paginator from pelican.plugins import signals from pelican.utils import ( get_relative_pat...
--- +++ @@ -100,6 +100,11 @@ ) def _open_w(self, filename, encoding, override=False): + """Open a file to write some content to it. + + Exit if we have already written to that file, unless one (and no more + than one) of the writes has the override parameter set to True. + """...
https://raw.githubusercontent.com/getpelican/pelican/HEAD/pelican/writers.py
Include argument descriptions in docstrings
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. from copy import deepcopy from dataclasses import dataclass, field from pathlib import Path from typing import Any, List, Literal, Optional, Type, Union import yaml from typing_extensions import Self def find_multiple(n: int, k: int)...
--- +++ @@ -10,6 +10,12 @@ def find_multiple(n: int, k: int) -> int: + """Utility function for finding the nearest value to n which is a multiple of k. + + NOTE: We define this function in this module rather than `litgpt.utils` so that users can import + this file to do configuration manipulations in Pytho...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/config.py
Document classes and their methods
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import math from functools import partial from typing import Any, List, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from typing_extensions import Self from litgpt.config import Config fro...
--- +++ @@ -1,5 +1,10 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Full definition of a decoder-only transformer-based language model, all of it in this single file. + +Based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT and +https://github.com/Eleuthe...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/model.py
Write clean docstrings for readability
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # 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...
--- +++ @@ -33,6 +33,26 @@ VOCAB_SIZE: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): + """ + Cross Entropy Loss = 1/n sum [ -yi log(Pi) ] + Pi = exp(xi) / sum(exp(xi)) + CE_i = -y log(p) = -y log[ exp(x) / sum(exp(x)) ] + = -y [ x - log[sum(exp(x))] ] + = y * (log[sum(exp(x))] - x) + ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/extensions/thunder/unsloth/kernels/cross_entropy_loss.py
Generate missing documentation strings
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import sys import time from pathlib import Path from typing import Optional import lightning as L import torch import torch_xla.core.xla_model as xm from lightning.fabric.accelerators import XLAAccelerator from lightning.fabric.strateg...
--- +++ @@ -33,6 +33,18 @@ top_k: Optional[int] = None, eos_id: Optional[int] = None, ) -> torch.Tensor: + """Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested. + + The implementation of this function is modified from A. Karpathy's nanoGPT. + + Args...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/extensions/xla/generate/base.py
Fully document this Python code with docstrings
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import math import warnings from dataclasses import dataclass from typing import Dict, Optional, Union @dataclass class TrainArgs: save_interval: Optional[int] = 1000 """Number of optimizer steps between saving checkpoints""" ...
--- +++ @@ -7,6 +7,7 @@ @dataclass class TrainArgs: + """Training-related arguments""" save_interval: Optional[int] = 1000 """Number of optimizer steps between saving checkpoints""" @@ -54,16 +55,19 @@ ) def gradient_accumulation_iters(self, devices: int, num_nodes: int = 1) -> int:...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/args.py
Improve documentation using docstrings
from contextlib import nullcontext from datetime import timedelta from typing import TYPE_CHECKING, Any, ContextManager, Dict, List, Optional, Tuple, Union import torch import torch.distributed from lightning.fabric.accelerators.accelerator import Accelerator from lightning.fabric.plugins.collectives.torch_collective...
--- +++ @@ -1,3 +1,4 @@+"""Fabric Strategy to support Thunder DDP: To be upstreamed into Fabric eventually.""" from contextlib import nullcontext from datetime import timedelta @@ -46,6 +47,20 @@ timeout: Optional[timedelta] = default_pg_timeout, **kwargs: Any, ): + r"""Strategy for Rep...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/extensions/thunder/strategies/thunder_ddp.py
Write docstrings describing each step
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import math import pprint import time import warnings from dataclasses import asdict from datetime import timedelta from functools import partial from pathlib import Path from typing import Dict, Optional, Tuple, Union import lightning...
--- +++ @@ -74,6 +74,32 @@ logger_name: LoggerChoice = "tensorboard", seed: int = 42, ): + """Pretrain a model. + + Arguments: + model_name: The name of the model to pretrain. Choose from names in ``litgpt.config``. Use "list" to list the supported models. + model_config: A ``litgpt.Config...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/pretrain.py
Add missing documentation to my Python functions
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import math import os import pprint import sys import time from dataclasses import asdict from datetime import timedelta from functools import partial from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tupl...
--- +++ @@ -83,6 +83,34 @@ executors: Optional[List[str]] = ("sdpa", "torchcompile", "nvfuser", "torch"), strategy: Literal["auto", "ddp", "fsdp"] = "fsdp", ): + """Pretrain a model. + + Arguments: + model_name: The name of the model to pretrain. Choose from names in ``litgpt.config``. Mutually e...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/extensions/thunder/pretrain.py
Add docstrings to make code maintainable
import shutil from contextlib import ExitStack, nullcontext from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, ContextManager, Dict, List, Literal, Optional, Tuple, Union import torch from lightning.fabric.accelerators.accelerator import Accelerator from lightning.fabric.plugins.environments.cl...
--- +++ @@ -1,3 +1,4 @@+"""Fabric Strategy to support Thunder FSDP: To be upstreamed into Fabric eventually.""" import shutil from contextlib import ExitStack, nullcontext @@ -57,6 +58,47 @@ state_dict_type: Literal["full", "sharded"] = "sharded", **kwargs: Any, ): + r"""Strategy for Fu...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/extensions/thunder/strategies/thunder_fsdp.py
Improve documentation using docstrings
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. from pathlib import Path from pprint import pprint from typing import Any, Dict, Optional, Tuple import lightning as L import torch import yaml from litgpt.lora import GPT, Config, lora_filter, merge_lora_weights from litgpt.utils im...
--- +++ @@ -1,5 +1,6 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""This script merges the LoRA weights with the base model""" from pathlib import Path from pprint import pprint @@ -16,6 +17,23 @@ def merge_lora( checkpoint_dir: Path, pretrained_checkpoint_dir: Opti...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/scripts/merge_lora.py
Write Python docstrings for this snippet
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. from dataclasses import dataclass, field from pathlib import Path from typing import List, Optional, Union import torch from torch.utils.data import DataLoader from litgpt.data import DataModule, SFTDataset, get_sft_collate_fn from li...
--- +++ @@ -1,4 +1,5 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Implementation derived from https://github.com/tloen/alpaca-lora""" from dataclasses import dataclass, field from pathlib import Path @@ -14,6 +15,7 @@ @dataclass class Deita(DataModule): + """Deita ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/data/deita.py
Help me comply with documentation standards
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import gc from collections import defaultdict from functools import partial from pathlib import Path from pprint import pprint from typing import Dict, Optional, Union import torch from lightning.fabric.utilities.load import _NotYetLoa...
--- +++ @@ -518,6 +518,9 @@ def qkv_reassemble(param: Union[torch.Tensor, NotYetLoadedTensor], config: Config) -> torch.Tensor: + """Reassemble from a normal to an interleaved placement in a QKV matrix. + [Q, Q, ..., K, K, ..., V, V, ...] --> [Q, K, V, Q, K, V, ...] + """ q, k, v = param.split( ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/scripts/convert_lit_checkpoint.py
Document this code for team use
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import sys import time import warnings from pathlib import Path from pprint import pprint from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple import lightning as L import torch import torch._dynamo.config import torc...
--- +++ @@ -66,6 +66,33 @@ speculative_k: int, **sample_kwargs: Dict[str, Any], ) -> torch.Tensor: + """Performs speculative decoding using a draft and a target model. + + This implements the speculative decoding algorithm from "Fast Inference from Transformers via Speculative Decoding" + (https://ar...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/generate/speculative_decoding.py
Generate documentation strings for clarity
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import itertools import logging import re import sys import time import warnings from collections import OrderedDict from functools import partial from pathlib import Path from pprint import pprint from typing import List, Literal, Opti...
--- +++ @@ -104,6 +104,7 @@ chunk_on: Type[torch.nn.Module], chunk_sizes: List[int], ) -> "OrderedDict[str, int]": + """Create a mapping from layer (block) to device.""" # this assumes that the definition order is the same as the execution order hits = [name for name, submodule in module.named_mo...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/generate/sequentially.py
Add detailed documentation for each class
import logging import sys import time import warnings from functools import partial from pathlib import Path from pprint import pprint from typing import Literal, Optional, Union import lightning as L import torch import torch._dynamo.config import torch._inductor.config from lightning.fabric.plugins import Bitsandby...
--- +++ @@ -1,3 +1,4 @@+"""Tensor-parallel implementation adapted from https://github.com/pytorch-labs/gpt-fast/blob/14df27/tp.py""" import logging import sys @@ -113,6 +114,39 @@ precision: Optional[str] = None, compile: bool = False, ) -> None: + """Generation script that uses tensor parallelism to r...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/generate/tp.py
Generate missing documentation strings
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import sys import time import warnings from pathlib import Path from pprint import pprint from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union import lightning as L import torch import torch._dynamo.config impo...
--- +++ @@ -139,6 +139,20 @@ include_prompt: bool, include_eos: bool, ) -> Iterator[torch.Tensor]: + """ + Generates tokens for a single prompt. + + Args: + model: The model to use. + prompt: The tokenized prompt to generate from. + max_returned_tokens: The maximum number of new ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/generate/base.py
Add docstrings to existing functions
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. # Derived from https://github.com/microsoft/LoRA # ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT Licens...
--- +++ @@ -6,6 +6,42 @@ # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ------------------------------------------------------------------------------------------ +r""" + Low Ranking Adaptation for LLMs scheme. + + ┌───────────────────┐ + ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/lora.py
Document classes and their methods
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. # # This file implements the LitGPT Python API import sys import time from pathlib import Path from typing import Any, Callable, List, Literal, Optional, Tuple, Union import lightning as L import numpy as np import torch from lightning....
--- +++ @@ -98,6 +98,7 @@ return logits def trainer_setup(self, trainer_ckpt: Optional[Path] = None) -> None: + """Initializes the model checkpoint for PyTorch Lightning Trainer contexts""" self.model = GPT(self.config) if trainer_ckpt is not None: @@ -152,6 +153,22 @@ ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/api.py
Generate documentation strings for clarity
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import os from dataclasses import dataclass, field from typing import List, Optional, Union import torch from torch.utils.data import DataLoader, random_split from litgpt.data import DataModule, SFTDataset, get_sft_collate_fn from lit...
--- +++ @@ -1,4 +1,5 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Implementation derived from https://github.com/tloen/alpaca-lora""" import os from dataclasses import dataclass, field @@ -14,6 +15,7 @@ @dataclass class LIMA(DataModule): + """LIMA data module for s...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/data/lima.py
Add detailed docstrings explaining each function
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import json from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union import torch from torch.utils.data import DataLoader, random_split from litgpt.constants import _REQUESTS_AVAILABLE from ...
--- +++ @@ -1,4 +1,5 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Implementation derived from https://github.com/tloen/alpaca-lora""" import json from dataclasses import dataclass, field @@ -18,6 +19,7 @@ @dataclass class Alpaca(DataModule): + """Alpaca data module...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/data/alpaca.py
Create documentation for each function signature
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. from abc import abstractmethod from functools import partial from typing import Any, Callable, Dict, List, Optional, Union import torch from lightning import LightningDataModule from torch import Tensor from torch.utils.data import Data...
--- +++ @@ -13,6 +13,7 @@ class DataModule(LightningDataModule): + """Base class for all data modules in LitGPT.""" @abstractmethod def connect( @@ -22,6 +23,9 @@ max_seq_length: Optional[int] = None, **kwargs, ) -> None: + """All settings that can't be determined at the ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/data/base.py
Add docstrings to incomplete code
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import json from pathlib import Path from typing import Optional import torch import yaml from lightning_utilities.core.imports import RequirementCache from torch.utils.data import random_split from tqdm import tqdm from litgpt.token...
--- +++ @@ -1,5 +1,6 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Implementation derived from https://github.com/tloen/alpaca-lora""" import json from pathlib import Path @@ -26,6 +27,11 @@ ignore_index: int = -100, max_seq_length: Optional[int] = None, ) -> ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/extensions/xla/scripts/prepare_alpaca.py
Write docstrings describing functionality
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. from dataclasses import dataclass from typing import Any, Dict, Optional, Tuple import torch import torch.nn as nn from typing_extensions import Self from litgpt.config import Config as BaseConfig from litgpt.model import GPT as Base...
--- +++ @@ -1,5 +1,12 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Implementation of the paper: + +LLaMA-Adapter: Efficient Fine-tuning of Language Models with Zero-init Attention +https://arxiv.org/abs/2303.16199 + +Port for LitGPT +""" from dataclasses import dataclas...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/adapter.py
Create docstrings for each class method
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import sys import time from pathlib import Path from pprint import pprint from typing import Iterator, List, Literal, Optional, Tuple import lightning as L import torch from lightning.fabric.plugins import BitsandbytesPrecision from l...
--- +++ @@ -35,6 +35,30 @@ top_p: float = 1.0, stop_tokens: Tuple[List[int], ...] = (), ) -> Iterator[torch.Tensor]: + """Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as possible. + + Arguments: + model: The model to use. + prompt: Tensor of shap...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/chat/base.py
Create docstrings for reusable components
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import gc import json import os import re import warnings from collections import defaultdict from functools import partial from pathlib import Path from pprint import pprint from typing import Dict, List, Optional, Tuple, Union import...
--- +++ @@ -727,6 +727,9 @@ def qkv_reassemble( param: Union[torch.Tensor, NotYetLoadedTensor], config: Config ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Reassemble from a normal to an interleaved placement in a QKV matrix. + [Q, K, V, Q, K, V, ...] --> [Q, Q, ..., K, K, ..., V, V, ...] + ...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/scripts/convert_hf_checkpoint.py
Add return value explanations in docstrings
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. import inspect import json import math import os import pickle import random import re import shutil import subprocess import sys import warnings from dataclasses import asdict, is_dataclass from io import BytesIO from pathlib import P...
--- +++ @@ -1,5 +1,6 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Utility functions for training and inference.""" import inspect import json @@ -78,6 +79,7 @@ def reset_parameters(module: nn.Module) -> None: + """Calls `reset_parameters` on the module and all i...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/utils.py
Generate consistent docstrings
# Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. from dataclasses import dataclass from typing import Any, Dict, Optional, Type import torch import torch.nn as nn from typing_extensions import Self import litgpt from litgpt.adapter import GPT as BaseModel from litgpt.adapter import...
--- +++ @@ -1,5 +1,12 @@ # Copyright Lightning AI. Licensed under the Apache License 2.0, see LICENSE file. +"""Implementation of the paper: + +LLaMA-Adapter V2: Parameter-Efficient Visual Instruction Model +https://arxiv.org/abs/2304.15010 + +Port for LitGPT +""" from dataclasses import dataclass from typing imp...
https://raw.githubusercontent.com/Lightning-AI/litgpt/HEAD/litgpt/adapter_v2.py
Write beginner-friendly docstrings
import sys import socket import errno import os import threading import subprocess import traceback import re if sys.platform != "win32": import fcntl logprefix = '' verbose = 0 def b(s): return s.encode("ASCII") def get_verbose_level(): return verbose def log(s): try: sys.stdout.flush()...
--- +++ @@ -64,6 +64,18 @@ def resolvconf_nameservers(systemd_resolved): + """Retrieves a list of tuples (address type, address as a string) of + the DNS servers used by the system to resolve hostnames. + + If parameter is False, DNS servers are retrieved from only + /etc/resolv.conf. This behavior make...
https://raw.githubusercontent.com/sshuttle/sshuttle/HEAD/sshuttle/helpers.py
Improve documentation using docstrings
import os import sys from ipaddress import ip_address, ip_network import threading from collections import namedtuple import socket import subprocess import re from multiprocessing import shared_memory from struct import Struct from functools import wraps from enum import IntEnum import time import traceback from ssh...
--- +++ @@ -402,6 +402,7 @@ return False def _egress_divert(self, ready_cb): + """divert outgoing packets to proxy""" proto = IPProtocol.TCP filter = f"outbound and {proto.filter}" af_filters = [] @@ -482,6 +483,7 @@ w.send(pkt, recalculate_checksum=True)...
https://raw.githubusercontent.com/sshuttle/sshuttle/HEAD/sshuttle/methods/windivert.py
Help me write clear docstrings
import time import socket import re import select import errno import os import sys import platform import subprocess as ssubprocess import sshuttle.helpers as helpers from sshuttle.helpers import log, debug1, debug2, debug3, get_env POLL_TIME = 60 * 15 NETSTAT_POLL_TIME = 30 CACHEFILE = os.path.expanduser('~/.sshutt...
--- +++ @@ -35,6 +35,8 @@ def write_host_cache(): + """If possible, write our hosts file to disk so future connections + can reuse the hosts that we already found.""" tmpname = '%s.%d.tmp' % (CACHEFILE, os.getpid()) global CACHE_WRITE_FAILED try: @@ -60,6 +62,8 @@ def read_host_cache(): ...
https://raw.githubusercontent.com/sshuttle/sshuttle/HEAD/sshuttle/hostwatch.py
Insert docstrings into my code
import socket import os from sshuttle.helpers import debug1 def _notify(message): addr = os.environ.get("NOTIFY_SOCKET", None) if not addr or len(addr) == 1 or addr[0] not in ('/', '@'): return False addr = '\0' + addr[1:] if addr[0] == '@' else addr try: sock = socket.socket(sock...
--- +++ @@ -1,3 +1,12 @@+"""When sshuttle is run via a systemd service file, we can communicate +to systemd about the status of the sshuttle process. In particular, we +can send READY status to tell systemd that sshuttle has completed +startup and send STOPPING to indicate that sshuttle is beginning +shutdown. + +For d...
https://raw.githubusercontent.com/sshuttle/sshuttle/HEAD/sshuttle/sdnotify.py
Fully document this Python code with docstrings
# structure.py from validate import Validator, validated from collections import ChainMap class StructureMeta(type): @classmethod def __prepare__(meta, clsname, bases): return ChainMap({}, Validator.validators) @staticmethod def __new__(meta, name, bases, methods): methods = m...
--- +++ @@ -35,6 +35,9 @@ @classmethod def create_init(cls): + ''' + Create an __init__ method from _fields + ''' args = ','.join(cls._fields) code = f'def __init__(self, {args}):\n' for name in cls._fields: @@ -49,6 +52,10 @@ validate_attributes(cls) ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/7_6/structure.py
Write docstrings including parameters and return values
# structure.py from validate import Validator, validated class Structure: _fields = () _types = () def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: raise AttributeError('No attribute %s' % n...
--- +++ @@ -23,6 +23,9 @@ @classmethod def create_init(cls): + ''' + Create an __init__ method from _fields + ''' args = ','.join(cls._fields) code = f'def __init__(self, {args}):\n' for name in cls._fields: @@ -37,6 +40,10 @@ validate_attributes(cls) ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/7_3/structure.py
Add inline docstrings for readability
# readrides.py import csv import collections.abc def read_rides_as_tuples(filename): records = [] with open(filename) as f: rows = csv.reader(f) headings = next(rows) # Skip headers for row in rows: route = row[0] date = row[1] daytype = row[2] ...
--- +++ @@ -4,6 +4,9 @@ import collections.abc def read_rides_as_tuples(filename): + ''' + Read the bus ride data as a list of tuples + ''' records = [] with open(filename) as f: rows = csv.reader(f) @@ -18,6 +21,9 @@ return records def read_rides_as_dicts(filename): + ''' + ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/2_5/readrides.py
Add docstrings including usage examples
# reader.py import csv def read_csv_as_dicts(filename, types): records = [] with open(filename) as f: rows = csv.reader(f) headers = next(rows) for row in rows: record = { name: func(val) for name, func, val in zip(headers, types, row) } records.append(record) ...
--- +++ @@ -3,6 +3,9 @@ import csv def read_csv_as_dicts(filename, types): + ''' + Read a CSV file into a list of dicts with column type conversion + ''' records = [] with open(filename) as f: rows = csv.reader(f) @@ -13,10 +16,13 @@ return records def read_csv_as_instances(filenam...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/3_3/reader.py
Write docstrings for algorithm functions
# reader.py import csv import logging log = logging.getLogger(__name__) def convert_csv(lines, converter, *, headers=None): rows = csv.reader(lines) if headers is None: headers = next(rows) records = [] for rowno, row in enumerate(rows, start=1): try: records.append(conve...
--- +++ @@ -28,9 +28,16 @@ lambda headers, row: cls.from_row(row)) def read_csv_as_dicts(filename, types, *, headers=None): + ''' + Read CSV data into a list of dictionaries with optional type conversion + ''' with open(filename) as file: return csv_as_dicts(file, types,...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/5_5/reader.py
Add docstrings for internal functions
# structure.py from validate import Validator, validated from collections import ChainMap class StructureMeta(type): @classmethod def __prepare__(meta, clsname, bases): return ChainMap({}, Validator.validators) @staticmethod def __new__(meta, name, bases, methods): methods = m...
--- +++ @@ -41,6 +41,9 @@ @classmethod def create_init(cls): + ''' + Create an __init__ method from _fields + ''' args = ','.join(cls._fields) code = f'def __init__(self, {args}):\n' for name in cls._fields: @@ -55,6 +58,10 @@ validate_attributes(cls) ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/8_6/structure.py
Create simple docstrings for beginners
# structure.py from validate import Validator, validated class Structure: _fields = () _types = () def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: raise AttributeError('No attribute %s' % n...
--- +++ @@ -23,6 +23,9 @@ @classmethod def create_init(cls): + ''' + Create an __init__ method from _fields + ''' args = ','.join(cls._fields) code = f'def __init__(self, {args}):\n' for name in cls._fields: @@ -37,6 +40,10 @@ validate_attributes(cls) ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/7_4/structure.py
Add docstrings including usage examples
# stock.py class Stock: def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price def cost(self): return self.shares * self.price def sell(self, nshares): self.shares -= nshares def read_portfolio(filename): import csv ...
--- +++ @@ -13,6 +13,9 @@ self.shares -= nshares def read_portfolio(filename): + ''' + Read a CSV file of stock data into a list of Stocks + ''' import csv portfolio = [] with open(filename) as f: @@ -24,6 +27,9 @@ return portfolio def print_portfolio(portfolio): + ''' + ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/3_1/stock.py
Generate NumPy-style docstrings
# structure.py from validate import Validator, validated from collections import ChainMap class StructureMeta(type): @classmethod def __prepare__(meta, clsname, bases): return ChainMap({}, Validator.validators) @staticmethod def __new__(meta, name, bases, methods): methods = m...
--- +++ @@ -42,6 +42,9 @@ @classmethod def create_init(cls): + ''' + Create an __init__ method from _fields + ''' args = ','.join(cls._fields) code = f'def __init__(self, {args}):\n' for name in cls._fields: @@ -56,6 +59,10 @@ validate_attributes(cls) ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/8_1/structure.py
Expand my code with proper documentation strings
# reader.py import csv def convert_csv(lines, converter, *, headers=None): rows = csv.reader(lines) if headers is None: headers = next(rows) return list(map(lambda row: converter(headers, row), rows)) def csv_as_dicts(lines, types, *, headers=None): return convert_csv(lines, ...
--- +++ @@ -20,9 +20,16 @@ headers=headers) def read_csv_as_dicts(filename, types, *, headers=None): + ''' + Read CSV data into a list of dictionaries with optional type conversion + ''' with open(filename) as file: return csv_as_dicts(file, types, headers=headers) de...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/5_3/reader.py
Document my Python code with docstrings
# readrides.py import csv def read_rides_as_tuples(filename): records = [] with open(filename) as f: rows = csv.reader(f) headings = next(rows) # Skip headers for row in rows: route = row[0] date = row[1] daytype = row[2] rides = int(...
--- +++ @@ -3,6 +3,9 @@ import csv def read_rides_as_tuples(filename): + ''' + Read the bus ride data as a list of tuples + ''' records = [] with open(filename) as f: rows = csv.reader(f) @@ -17,6 +20,9 @@ return records def read_rides_as_dicts(filename): + ''' + Read the bus...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/2_2/readrides.py
Create docstrings for each class method
# structure.py from .validate import Validator, validated from collections import ChainMap class StructureMeta(type): @classmethod def __prepare__(meta, clsname, bases): return ChainMap({}, Validator.validators) @staticmethod def __new__(meta, name, bases, methods): methods = ...
--- +++ @@ -41,6 +41,9 @@ @classmethod def create_init(cls): + ''' + Create an __init__ method from _fields + ''' args = ','.join(cls._fields) code = f'def __init__(self, {args}):\n' for name in cls._fields: @@ -55,6 +58,10 @@ validate_attributes(cls) ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/9_2/structly/structure.py
Add docstrings explaining edge cases
# structure.py __all__ = [ 'Structure' ] from .validate import Validator, validated from collections import ChainMap class StructureMeta(type): @classmethod def __prepare__(meta, clsname, bases): return ChainMap({}, Validator.validators) @staticmethod def __new__(meta, name, bases, m...
--- +++ @@ -43,6 +43,9 @@ @classmethod def create_init(cls): + ''' + Create an __init__ method from _fields + ''' args = ','.join(cls._fields) code = f'def __init__(self, {args}):\n' for name in cls._fields: @@ -57,6 +60,10 @@ validate_attributes(cls) ...
https://raw.githubusercontent.com/dabeaz-course/python-mastery/HEAD/Solutions/9_3/structly/structure.py
Generate consistent documentation across files
#!/usr/bin/env python3 # this module is part of undetected_chromedriver import json import os from selenium.webdriver.chromium.options import ChromiumOptions as _ChromiumOptions class ChromeOptions(_ChromiumOptions): _session = None _user_data_dir = None @property def user_data_dir(self): ...
--- +++ @@ -18,11 +18,22 @@ @user_data_dir.setter def user_data_dir(self, path: str): + """ + Sets the browser profile folder to use, or creates a new profile + at given <path>. + + Parameters + ---------- + path: str + the path to a chrome profile folder ...
https://raw.githubusercontent.com/FlareSolverr/FlareSolverr/HEAD/src/undetected_chromedriver/options.py
Insert docstrings into my code
from typing import List from selenium.webdriver.common.by import By import selenium.webdriver.remote.webelement class WebElement(selenium.webdriver.remote.webelement.WebElement): def click_safe(self): super().click() self._parent.reconnect(0.1) def children( self, tag=None, recursive...
--- +++ @@ -12,6 +12,10 @@ def children( self, tag=None, recursive=False ) -> List[selenium.webdriver.remote.webelement.WebElement]: + """ + returns direct child elements of current element + :param tag: str, if supplied, returns <tag> nodes only + """ script = "r...
https://raw.githubusercontent.com/FlareSolverr/FlareSolverr/HEAD/src/undetected_chromedriver/webelement.py
Generate docstrings with parameter types
import logging from dataclasses import dataclass from datetime import datetime, timedelta from typing import Optional, Tuple from uuid import uuid1 from selenium.webdriver.chrome.webdriver import WebDriver import utils @dataclass class Session: session_id: str driver: WebDriver created_at: datetime ...
--- +++ @@ -20,12 +20,23 @@ class SessionsStorage: + """SessionsStorage creates, stores and process all the sessions""" def __init__(self): self.sessions = {} def create(self, session_id: Optional[str] = None, proxy: Optional[dict] = None, force_new: Optional[bool] = False)...
https://raw.githubusercontent.com/FlareSolverr/FlareSolverr/HEAD/src/sessions.py
Generate docstrings for each module
#!/usr/bin/env python3 from __future__ import annotations __version__ = "3.5.5" import json import logging import os import pathlib import re import shutil import subprocess import sys import tempfile import time from weakref import finalize import selenium.webdriver.chrome.service import selenium.webdriver.chrome...
--- +++ @@ -1,5 +1,19 @@ #!/usr/bin/env python3 +""" + + 888 888 d8b + 888 888 Y8P + 888 888 + .d8888b 88888b. 888d888 .d88b. 888...
https://raw.githubusercontent.com/FlareSolverr/FlareSolverr/HEAD/src/undetected_chromedriver/__init__.py
Document all endpoints with docstrings
import asyncio from collections.abc import Mapping from collections.abc import Sequence from functools import wraps import os import logging import threading import time import traceback from typing import Any from typing import Awaitable from typing import Callable from typing import List from typing import Optional ...
--- +++ @@ -15,10 +15,22 @@ class Structure(dict): + """ + This is a dict-like object structure, which you should subclass + Only properties defined in the class context are used on initialization. + + See example + """ _store = {} def __init__(self, *a, **kw): + """ + Ins...
https://raw.githubusercontent.com/FlareSolverr/FlareSolverr/HEAD/src/undetected_chromedriver/devtool.py
Provide docstrings following PEP 257
#!/usr/bin/env python3 # this module is part of undetected_chromedriver from packaging.version import Version as LooseVersion import io import json import logging import os import pathlib import platform import random import re import shutil import string import subprocess import sys import time from urllib.request im...
--- +++ @@ -49,6 +49,15 @@ version_main: int = 0, user_multi_procs=False, ): + """ + Args: + executable_path: None = automatic + a full file path to the chromedriver executable + force: False + terminate processes w...
https://raw.githubusercontent.com/FlareSolverr/FlareSolverr/HEAD/src/undetected_chromedriver/patcher.py