instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add docstrings to incomplete code | # -*- coding:utf-8 -*-
def ma(data, n=10, val_name="close"):
import numpy as np
'''
移动平均线 Moving Average
Parameters
------
data:pandas.DataFrame
通过 get_h_data 取得的股票数据
n:int
移动平均线时长,时间单位根据data决定
val_name:string
计算哪一列的列名,默认为 c... | --- +++ @@ -1,5 +1,12 @@ # -*- coding:utf-8 -*-
+"""
+股票技术指标接口
+Created on 2018/05/26
+@author: Jackie Liao
+@group : **
+@contact: info@liaocy.net
+"""
def ma(data, n=10, val_name="close"):
@@ -241,6 +248,23 @@
def boll(data, n=10, val_name="close", k=2):
+ '''
+ 布林线指标BOLL
+ Parameters
+ ... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/indictor.py |
Document all endpoints with docstrings | # -*- coding:utf-8 -*-
from __future__ import division
from tushare.stock import cons as ct
from tushare.stock import ref_vars as rv
import pandas as pd
import numpy as np
import time
import lxml.html
from lxml import etree
import re
import json
from pandas.compat import StringIO
from tushare.util import dateu as du
f... | --- +++ @@ -1,694 +1,1092 @@-# -*- coding:utf-8 -*-
-from __future__ import division
-from tushare.stock import cons as ct
-from tushare.stock import ref_vars as rv
-import pandas as pd
-import numpy as np
-import time
-import lxml.html
-from lxml import etree
-import re
-import json
-from pandas.compat import StringI... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/reference.py |
Add docstrings to existing functions | # -*- coding:utf-8 -*-
from tushare.stock import cons as ct
from tushare.stock import news_vars as nv
import pandas as pd
from datetime import datetime
import lxml.html
from lxml import etree
import re
import json
try:
from urllib.request import urlopen, Request
except ImportError:
from urllib2 import urlopen... | --- +++ @@ -1,5 +1,12 @@ # -*- coding:utf-8 -*-
+"""
+新闻事件数据接口
+Created on 2015/02/07
+@author: Jimmy Liu
+@group : waditu
+@contact: jimmysoa@sina.cn
+"""
from tushare.stock import cons as ct
from tushare.stock import news_vars as nv
@@ -17,6 +24,23 @@
def get_latest_news(top=None, show_content=False):
+ ... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/newsevent.py |
Add docstrings following best practices | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import datetime
from bs4 import BeautifulSoup
import pandas as pd
from tushare.futures import domestic_cons as ct
try:
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from urllib.error import HTTPError
from http.cli... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+'''
+Created on 2017年06月04日
+@author: debugo
+@contact: me@debugo.com
+'''
import json
import datetime
@@ -19,6 +24,29 @@
def get_cffex_daily(date = None):
+ """
+ 获取中金所日交易数据
+ Parameters
+ ------
+ date: 日期 format:YY... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/futures/domestic.py |
Add docstrings including usage examples | # -*- coding:utf-8 -*-
import pandas as pd
from tushare.stock import cons as ct
import lxml.html
from lxml import etree
import re
import time
from pandas.compat import StringIO
from tushare.util import dateu as du
try:
from urllib.request import urlopen, Request
except ImportError:
from urllib2 import urlopen,... | --- +++ @@ -1,330 +1,519 @@-# -*- coding:utf-8 -*-
-import pandas as pd
-from tushare.stock import cons as ct
-import lxml.html
-from lxml import etree
-import re
-import time
-from pandas.compat import StringIO
-from tushare.util import dateu as du
-try:
- from urllib.request import urlopen, Request
-except Import... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/fundamental.py |
Generate docstrings for script automation | # -*- coding:utf-8 -*-
from __future__ import division
import time
import json
import lxml.html
from lxml import etree
import pandas as pd
import numpy as np
import datetime
from tushare.stock import cons as ct
import re
from pandas.compat import StringIO
from tushare.util import dateu as du
from tushare.util.formula... | --- +++ @@ -1,971 +1,1281 @@-# -*- coding:utf-8 -*-
-from __future__ import division
-
-import time
-import json
-import lxml.html
-from lxml import etree
-import pandas as pd
-import numpy as np
-import datetime
-from tushare.stock import cons as ct
-import re
-from pandas.compat import StringIO
-from tushare.util im... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/trading.py |
Can you add docstrings to this Python file? | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
from pandas.compat import StringIO
from tushare.stock import cons as ct
import numpy as np
import time
import json
import re
import lxml.html
from lxml import etree
from tushare.util import dateu as du
from tushare.stock import ref_vars as rv
try:
f... | --- +++ @@ -1,5 +1,12 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+"""
+龙虎榜数据
+Created on 2015年6月10日
+@author: Jimmy Liu
+@group : waditu
+@contact: jimmysoa@sina.cn
+"""
import pandas as pd
from pandas.compat import StringIO
@@ -19,6 +26,31 @@
def top_list(date = None, retry_count=3, pause=0.001):
+ "... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/billboard.py |
Please document this code using docstrings | # -*- coding:utf-8 -*-
import pandas as pd
from tushare.stock import cons as ct
from tushare.util import dateu as du
try:
from urllib.request import urlopen, Request
except ImportError:
from urllib2 import urlopen, Request
import time
import json
def realtime_boxoffice(retry_count=3,pause=0.001):
for _ in... | --- +++ @@ -1,4 +1,11 @@ # -*- coding:utf-8 -*-
+"""
+电影票房
+Created on 2015/12/24
+@author: Jimmy Liu
+@group : waditu
+@contact: jimmysoa@sina.cn
+"""
import pandas as pd
from tushare.stock import cons as ct
from tushare.util import dateu as du
@@ -10,6 +17,26 @@ import json
def realtime_boxoffice(retry_count=... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/internet/boxoffice.py |
Provide clean and structured docstrings | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import datetime
CFFEX_DAILY_URL = 'http://www.cffex.com.cn/fzjy/mrhq/%s/%s/%s_1.csv'
SHFE_DAILY_URL = 'http://www.shfe.com.cn/data/dailydata/kx/kx%s.dat'
SHFE_VWAP_URL = 'http://www.shfe.com.cn/data/dailydata/ck/%sdailyTimePrice.dat'
DCE_DAILY_URL = 'http://www.d... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+'''
+Created on 2017年06月04日
+@author: debugo
+@contact: me@debugo.com
+'''
import re
import datetime
@@ -30,6 +35,11 @@ 'postman-token': "153f42ca-148a-8f03-3302-8172cc4a5185"
}
def convert_date(date):
+ """
+ transform a date strin... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/futures/domestic_cons.py |
Add structured docstrings to improve clarity | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import six
import pandas as pd
import requests
import time
from threading import Thread
from tushare.trader import vars as vs
from tushare.trader import utils
from tushare.util import upass as up
from tushare.util.upass import set_broker
class TraderAPI(object):
def _... | --- +++ @@ -1,6 +1,12 @@ #!/usr/bin/env python
# -*- coding:utf-8 -*-
+'''
+Created on 2016年9月25日
+@author: Jimmy Liu
+@group : waditu
+@contact: jimmysoa@sina.cn
+'''
import six
import pandas as pd
import requests
@@ -12,6 +18,12 @@ from tushare.util.upass import set_broker
class TraderAPI(object):
+ """
... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/trader/trader.py |
Write Python docstrings for this snippet | # -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
import re
import json
from tushare.stock import macro_vars as vs
from tushare.stock import cons as ct
try:
from urllib.request import urlopen, Request
except ImportError:
from urllib2 import urlopen, Request
def get_gdp_year():
rdint = vs.ra... | --- +++ @@ -1,5 +1,12 @@ # -*- coding:utf-8 -*-
+"""
+宏观经济数据接口
+Created on 2015/01/24
+@author: Jimmy Liu
+@group : waditu
+@contact: jimmysoa@sina.cn
+"""
import pandas as pd
import numpy as np
@@ -14,6 +21,23 @@
def get_gdp_year():
+ """
+ 获取年度国内生产总值数据
+ Return
+ --------
+ DataFrame
+ ... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/macro.py |
Create docstrings for all classes and functions | # !/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import simplejson as json
from functools import partial
import requests
class DataApi:
__token = ''
__http_url = 'http://api.tushare.pro'
def __init__(self, token, timeout=10):
self.__token = token
self.__timeout = time... | --- +++ @@ -1,6 +1,12 @@ # !/usr/bin/env python
# -*- coding: utf-8 -*-
+"""
+Pro数据接口
+Created on 2017/07/01
+@author: polo,Jimmy
+@group : tushare.pro
+"""
import pandas as pd
import simplejson as json
@@ -14,6 +20,12 @@ __http_url = 'http://api.tushare.pro'
def __init__(self, token, timeout=10):
+ ... | https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/pro/client.py |
Document functions with detailed explanations | #######################################################################
# Copyright (C) #
# 2018 Sergii Bondariev (sergeybondarev@gmail.com) #
# 2018 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the... | --- +++ @@ -13,9 +13,20 @@ from tqdm import tqdm
def true_value(p):
+ """ True value of the first state
+ Args:
+ p (float): probability of the action 'right'.
+ Returns:
+ True value of the first state.
+ The expression is obtained by manually solving the easy linear system
+ of... | https://raw.githubusercontent.com/ShangtongZhang/reinforcement-learning-an-introduction/HEAD/chapter13/short_corridor.py |
Generate docstrings for each module | #######################################################################
# Copyright (C) #
# 2021 Johann Huber (huber.joh@hotmail.fr) #
# Permission given to modify the code as long as you keep this #
# declaration at the top ... | --- +++ @@ -5,6 +5,36 @@ # declaration at the top #
#######################################################################
+"""
+
+Description:
+ This script is meant to reproduce Figure 12.14 of Sutton and Barto's book. This example shows
+ the effect of λ on 4 re... | https://raw.githubusercontent.com/ShangtongZhang/reinforcement-learning-an-introduction/HEAD/chapter12/lambda_effect.py |
Help me comply with documentation standards | #!/usr/bin/env python3
import argparse
import re
import sys
from pathlib import Path
from generate_openai_yaml import write_openai_yaml
MAX_SKILL_NAME_LENGTH = 64
ALLOWED_RESOURCES = {"scripts", "references", "assets"}
SKILL_TEMPLATE = """---
name: {skill_name}
description: [TODO: Complete and informative explanati... | --- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3
+"""
+Skill Initializer - Creates a new skill from template
+
+Usage:
+ init_skill.py <skill-name> --path <path> [--resources scripts,references,assets] [--examples] [--interface key=value]
+
+Examples:
+ init_skill.py my-new-skill --path skills/public
+ init_ski... | https://raw.githubusercontent.com/openai/skills/HEAD/skills/.system/skill-creator/scripts/init_skill.py |
Document all endpoints with docstrings | import argparse
import os
import re
import subprocess
import tempfile
import xml.etree.ElementTree as ET
from os import makedirs, replace
from os.path import abspath, basename, exists, expanduser, join, splitext
from shutil import which
import sys
from typing import Sequence, cast
from zipfile import ZipFile
from pdf2... | --- +++ @@ -29,6 +29,12 @@
def calc_dpi_via_ooxml_docx(input_path: str, max_w_px: int, max_h_px: int) -> int:
+ """Calculate DPI from OOXML `word/document.xml` page size (w:pgSz in twips).
+
+ DOCX stores page dimensions in section properties as twips (1/1440 inch).
+ We read the first encountered section'... | https://raw.githubusercontent.com/openai/skills/HEAD/skills/.curated/doc/scripts/render_docx.py |
Document this module using docstrings | #!/usr/bin/env python3
# Copyright (c) OpenAI. All rights reserved.
import argparse
import re
import sys
import tempfile
from math import ceil
from os import listdir
from os.path import basename, expanduser, isfile, join, splitext
from pathlib import Path
from typing import Literal
SCRIPT_DIR = Path(__file__).resolve(... | --- +++ @@ -19,6 +19,7 @@
def _make_placeholder(w: int, h: int) -> Image.Image:
+ """Create a visible placeholder tile with a light gray fill and a red X cross."""
ph = Image.new("RGBA", (w, h), (220, 220, 220, 255))
ph_draw = ImageDraw.Draw(ph)
line_color = (180, 0, 0, 255)
@@ -55,6 +56,7 @@
... | https://raw.githubusercontent.com/openai/skills/HEAD/skills/.curated/slides/scripts/create_montage.py |
Create docstrings for API functions | #!/usr/bin/env python3
from __future__ import annotations
import json
import subprocess
import sys
from typing import Any
QUERY = """\
query(
$owner: String!,
$repo: String!,
$number: Int!,
$commentsCursor: String,
$reviewsCursor: String,
$threadsCursor: String
) {
repository(owner: $owner, name: $repo... | --- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3
+"""
+Fetch all PR conversation comments + reviews + review threads (inline threads)
+for the PR associated with the current git branch, by shelling out to:
+
+ gh api graphql
+
+Requires:
+ - `gh auth login` already set up
+ - current branch has an associated (open) P... | https://raw.githubusercontent.com/openai/skills/HEAD/skills/.curated/gh-address-comments/scripts/fetch_comments.py |
Create docstrings for API functions | #!/usr/bin/env python3
import argparse
import json
import os
import re
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree as ET
from functools import lru_cache
from os.path import abspath, basename, exists, expanduser, join, splitext
from zipfile import ZipFile
STYLE_TOKENS = [
"regular"... | --- +++ @@ -1,4 +1,70 @@ #!/usr/bin/env python3
+"""Copyright (c) OpenAI. All rights reserved.
+
+Detect missing fonts for PPTX rendering by converting to ODP and inspecting the resolved font
+families per slide.
+
+Overview
+========
+PowerPoint files (PPTX) declare requested font families in runs and theme defaults, ... | https://raw.githubusercontent.com/openai/skills/HEAD/skills/.curated/slides/scripts/detect_font.py |
Add inline docstrings for readability | #!/usr/bin/env python3
# Copyright (c) OpenAI. All rights reserved.
import argparse
import os
import re
import subprocess
import tempfile
import xml.etree.ElementTree as ET
from os import makedirs, replace
from os.path import abspath, basename, exists, expanduser, join, splitext
from typing import Sequence, cast
from z... | --- +++ @@ -17,6 +17,7 @@
def calc_dpi_via_ooxml(input_path: str, max_w_px: int, max_h_px: int) -> int:
+ """Calculate DPI from OOXML `ppt/presentation.xml` slide size (cx/cy in EMUs)."""
with ZipFile(input_path, "r") as zf:
xml = zf.read("ppt/presentation.xml")
root = ET.fromstring(xml)
@@ -3... | https://raw.githubusercontent.com/openai/skills/HEAD/skills/.curated/slides/scripts/render_slides.py |
Add documentation for all methods | #!/usr/bin/env python3
import argparse
import gzip
import shutil
from os import listdir
from os.path import basename, dirname, expanduser, isfile, join, splitext
from subprocess import run
RASTER_EXTS = {
".png",
".jpg",
".jpeg",
".bmp",
".gif",
".tif",
".tiff",
".webp",
}
CONVERTIBLE... | --- +++ @@ -1,4 +1,30 @@ #!/usr/bin/env python3
+"""Copyright (c) OpenAI. All rights reserved.
+
+Ensures input images are rasterized, converting to PNG when needed. Primarily used to
+preview image assets extracted from PowerPoint files.
+
+
+Dependencies used by this tool:
+- Inkscape: SVG/EMF/WMF rasterization
+- Im... | https://raw.githubusercontent.com/openai/skills/HEAD/skills/.curated/slides/scripts/ensure_raster_image.py |
Generate docstrings for exported functions | from dataclasses import dataclass
from typing import List, Tuple
import torch
import torchaudio
from huggingface_hub import hf_hub_download
from models import Model
from moshi.models import loaders
from tokenizers.processors import TemplateProcessing
from transformers import AutoTokenizer
from watermarking import CSM_... | --- +++ @@ -20,6 +20,9 @@
def load_llama3_tokenizer():
+ """
+ https://github.com/huggingface/transformers/issues/22794#issuecomment-2092623992
+ """
tokenizer_name = "meta-llama/Llama-3.2-1B"
tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
bos = tokenizer.bos_token
@@ -93,6 +96,10... | https://raw.githubusercontent.com/SesameAILabs/csm/HEAD/generator.py |
Add docstrings including usage examples | from dataclasses import dataclass
import torch
import torch.nn as nn
import torchtune
from huggingface_hub import PyTorchModelHubMixin
from torchtune.models import llama3_2
def llama3_2_1B() -> torchtune.modules.transformer.TransformerDecoder:
return llama3_2.llama3_2(
vocab_size=128_256,
num_lay... | --- +++ @@ -57,6 +57,14 @@
def _index_causal_mask(mask: torch.Tensor, input_pos: torch.Tensor):
+ """
+ Args:
+ mask: (max_seq_len, max_seq_len)
+ input_pos: (batch_size, seq_len)
+
+ Returns:
+ (batch_size, seq_len, max_seq_len)
+ """
r = mask[input_pos, :]
return r
@@ ... | https://raw.githubusercontent.com/SesameAILabs/csm/HEAD/models.py |
Add docstrings for internal functions |
import wifiphisher.common.constants as constants
class MACMatcher(object):
def __init__(self, mac_vendor_file):
self._mac_to_vendor = {}
self._vendor_file = mac_vendor_file
# get the information in the vendor file
self._get_vendor_information()
def _get_vendor_information(... | --- +++ @@ -1,10 +1,30 @@+"""
+This module was made to match MAC address with vendors
+"""
import wifiphisher.common.constants as constants
class MACMatcher(object):
+ """
+ This class handles Organizationally Unique Identifiers (OUIs).
+ The original data comes from http://standards.ieee.org/regauth/
... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/macmatcher.py |
Help me write clear docstrings |
import time
import wifiphisher.common.constants as constants
from wifiphisher.common.macmatcher import MACMatcher as macmatcher
class Victim(object):
def __init__(self, vmac_address, ip_address):
self.vmac_address = vmac_address
self.ip_address = ip_address
self.os = ""
self.ven... | --- +++ @@ -1,3 +1,4 @@+"""Module to keep track the victims connected to the rogue AP."""
import time
@@ -6,8 +7,10 @@
class Victim(object):
+ """Resembles a Victim (i.e. a connected device to the rogue AP)."""
def __init__(self, vmac_address, ip_address):
+ """Create a Victim object."""
... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/victim.py |
Help me comply with documentation standards |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import subprocess
import time
from subprocess import check_output
import roguehostapd.apctrl as apctrl
import roguehostapd.config.hostapdconfig as hostapdconfig
import wifiphisher.common.constants a... | --- +++ @@ -1,3 +1,4 @@+"""This module was made to fork the rogue access point."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
@@ -14,18 +15,21 @@
class AccessPoint(object):
+ """This class forks the softAP."""
# Instance will be stored ... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/accesspoint.py |
Add docstrings to incomplete code | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: skip-file
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
from shutil import copyfile
from subprocess import PIPE, Popen, check_output... | --- +++ @@ -230,6 +230,9 @@
def setup_logging(args):
+ """
+ Setup the logging configurations
+ """
root_logger = logging.getLogger()
# logging setup
if args.logging:
@@ -245,10 +248,16 @@
def set_ip_fwd():
+ """
+ Set kernel variables.
+ """
Popen(['sysctl', '-w', 'net.ipv... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/pywifiphisher.py |
Document helper functions with docstrings |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from wifiphisher.common.constants import NETWORK_GW_IP, PORT, SSL_PORT
from wifiphisher.common.utilities import execute_commands
class Fw():
@staticmethod
def nat(internal_interface, external_interf... | --- +++ @@ -1,3 +1,4 @@+"""Serves as an abstraction layer in front of iptables."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
@@ -7,10 +8,12 @@
class Fw():
+ """Handles all iptables operations."""
@staticmethod
def nat(internal_int... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/firewall.py |
Add docstrings to my Python code | import datetime
import json
import logging
import os.path
import re
import time
import asyncio
import tornado.ioloop
import tornado.web
import tornado.platform.asyncio
import wifiphisher.common.constants as constants
import wifiphisher.common.extensions as extensions
import wifiphisher.common.uimethods as uimethods
im... | --- +++ @@ -36,12 +36,30 @@
class BackendHandler(tornado.web.RequestHandler):
+ """
+ Validate the POST requests from client by the uimethods
+ """
def initialize(self, em):
+ """
+ :param self: A tornado.web.RequestHandler object
+ :param em: An extension manager object
+ ... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/phishinghttp.py |
Generate docstrings for script automation | #!/usr/bin/env python3
import os
import sys
import shutil
import tempfile
import distutils.sysconfig
import distutils.ccompiler
from distutils.errors import CompileError, LinkError
from setuptools import Command, find_packages, setup
from textwrap import dedent
import wifiphisher.common.constants as constants
try... | --- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3
+r"""
+ _ __ _ _ _ _
+ (_)/ _(_) | | (_) | |
+ ((.)) __ ___| |_ _ _ __ | |__ _ ___| |__ ___ _ __
+ | \ \ /\ / / | _| | '_ \| '_ \| / __| '_ \ / _ \ '__|
+ /_\ \ V V /| | | | | |_) |... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/setup.py |
Generate NumPy-style docstrings |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from logging import getLogger
from subprocess import PIPE, Popen
from wifiphisher.common.constants import DN
# pylint: disable=C0103
logger = getLogger(__name__)
def execute_commands(commands):
for com... | --- +++ @@ -1,3 +1,9 @@+"""Host common and generic functions.
+
+Host all the common and generic functions that are used throughout
+the project.
+
+"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
@@ -12,9 +18,10 @@
def execute_commands(commands):... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/utilities.py |
Add docstrings including usage examples |
import logging
from collections import defaultdict
import scapy.layers.dot11 as dot11
import wifiphisher.common.constants as constants
import wifiphisher.common.globals as universal
logger = logging.getLogger(__name__)
def is_deauth_frame(packet):
if packet.subtype == 10 or packet.subtype == 12:
return ... | --- +++ @@ -1,3 +1,9 @@+"""
+Extension that sends 3 DEAUTH/DISAS Frames:
+ 1 from the AP to the client
+ 1 from the client to the AP
+ 1 to the broadcast address
+"""
import logging
from collections import defaultdict
@@ -9,13 +15,33 @@ logger = logging.getLogger(__name__)
def is_deauth_frame(packet):
+ """
+... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/extensions/deauth.py |
Create docstrings for reusable components | # -*- coding: utf-8 -*-
import logging
import random
from collections import defaultdict
from subprocess import PIPE, Popen, check_output
import pyric
import pyric.pyw as pyw
import wifiphisher.common.constants as constants
logger = logging.getLogger("wifiphisher.interfaces")
class InvalidInterfaceError(Exception... | --- +++ @@ -1,5 +1,9 @@ # -*- coding: utf-8 -*-
+"""
+This module was made to handle all the interface related operations of
+the program
+"""
import logging
import random
@@ -14,8 +18,19 @@
class InvalidInterfaceError(Exception):
+ """ Exception class to raise in case of a invalid interface """
def... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/interfaces.py |
Add docstrings with type hints explained |
import logging
from collections import defaultdict
import scapy.layers.dot11 as dot11
import wifiphisher.common.constants as constants
logger = logging.getLogger(__name__)
class Lure10(object):
def __init__(self, shared_data):
self.first_run = True
self.data = shared_data
# store chan... | --- +++ @@ -1,3 +1,10 @@+"""
+Extension that implements the Lure10 attack.
+
+Exploits the Wi-Fi Sense feature and will result
+to automatic association by fooling the Windows
+Location Service
+"""
import logging
from collections import defaultdict
@@ -9,8 +16,21 @@
class Lure10(object):
+ """
+ Sends a ... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/extensions/lure10.py |
Add docstrings to my Python code |
import curses
import os
import re
import time
from collections import namedtuple
from subprocess import check_output
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.constants as constants
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
imp... | --- +++ @@ -1,3 +1,7 @@+"""
+This module was made to handle the curses sections for the ap selection,
+template selection and the main window
+"""
import curses
import os
@@ -19,8 +23,18 @@
class TuiTemplateSelection(object):
+ """
+ TUI to do Template selection
+ """
def __init__(self):
+ ... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/tui.py |
Document this code for team use |
from collections import defaultdict
import wifiphisher.common.constants as constants
class Roguehostapdinfo(object):
def __init__(self, data):
self._data = data
self._packets_to_send = defaultdict(list)
self._mac2ssid_dict = defaultdict()
self._known_beacon_ssids = self._get_kno... | --- +++ @@ -1,3 +1,7 @@+"""
+Extension that interacts with roguehostapd to print relevant information. For example,
+information regarding automatic association attacks.
+"""
from collections import defaultdict
@@ -5,17 +9,44 @@
class Roguehostapdinfo(object):
+ """
+ Handles for printing KARMA attack in... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/extensions/roguehostapdinfo.py |
Write beginner-friendly docstrings |
from logging import getLogger
from threading import Thread
from time import sleep, strftime
import scapy
import scapy.layers.dot11 as dot11
import wifiphisher.common.globals as universal
from wifiphisher.common.constants import LOCS_DIR, NON_CLIENT_ADDRESSES
from wifiphisher.common.interfaces import NetworkManager
... | --- +++ @@ -1,3 +1,4 @@+"""Handles all reconnaissance operations."""
@@ -15,9 +16,11 @@
class AccessPoint(object):
+ """Represents an access point."""
def __init__(self, ssid, bssid, channel, encryption, capture_file=False):
# type: (str, str, str, str, bool) -> None
+ """Initialize ... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/recon.py |
Help me document legacy Python code | import argparse
import logging
import os
import sys
import pyric
import wifiphisher.common.constants as constants
import wifiphisher.common.interfaces as interfaces
import wifiphisher.extensions.handshakeverify as handshakeverify
logger = logging.getLogger(__name__)
class OpMode(object):
def __init__(self):
... | --- +++ @@ -1,3 +1,9 @@+"""
+All logic regarding the Operation Modes (opmodes).
+
+The opmode is defined based on the user's arguments and the available
+resources of the host system
+"""
import argparse
import logging
import os
@@ -12,8 +18,18 @@
class OpMode(object):
+ """
+ Manager of the operation mode... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/opmode.py |
Help me write clear docstrings |
import collections
import importlib
import logging
import threading
import time
from collections import defaultdict
import scapy.arch.linux as linux
import scapy.layers.dot11 as dot11
import wifiphisher.common.constants as constants
import wifiphisher.common.globals as universal
import wifiphisher.extensions.deauth a... | --- +++ @@ -1,3 +1,6 @@+"""
+All logic regarding extensions management
+"""
import collections
import importlib
@@ -17,14 +20,63 @@
def register_backend_funcs(func):
+ """
+ Register the specific function in extension as backend methods
+ :param func: The instance function needed to register as backend... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/extensions.py |
Fill in missing docstrings in my code |
import logging
import time
from collections import defaultdict
import scapy.layers.dot11 as dot11
import wifiphisher.common.constants as constants
import wifiphisher.common.globals as universal
logger = logging.getLogger(__name__)
class Knownbeacons(object):
def __init__(self, shared_data):
self.data ... | --- +++ @@ -1,3 +1,6 @@+"""
+Extension that sends a number of known beacons to trigger the AUTO-CONNECT flag.
+"""
import logging
import time
@@ -10,8 +13,21 @@ logger = logging.getLogger(__name__)
class Knownbeacons(object):
+ """
+ Sends a number of known beacons to trigger the Auto-Connect flag.
+ ""... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/extensions/knownbeacons.py |
Add detailed docstrings explaining each function |
import logging
import os
import signal
import subprocess
import time
from collections import defaultdict
from threading import Timer
import scapy.layers.dot11 as dot11
import wifiphisher.common.extensions as extensions
logger = logging.getLogger(__name__)
WPS_IDLE, WPS_CONNECTING, WPS_CONNECTED = list(range(3))
# w... | --- +++ @@ -1,3 +1,13 @@+"""
+Extension that sniffs if there is change for WPS PBC exploitation
+
+Define three WPS states
+
+1) WPS_IDLE: Wait for target AP bringing WPSPBC IE in the beacon
+2) WPS_CONNECTING: If users specify the WPS association interface
+ we can start using wpa_supplicant/wpa_cli to connect to th... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/extensions/wpspbc.py |
Auto-generate documentation strings for this file |
import os
from shutil import copyfile
import wifiphisher.common.constants as constants
try:
from configparser import ConfigParser, RawConfigParser
except ImportError:
from configparser import ConfigParser, RawConfigParser
def config_section_map(config_file, section):
config = ConfigParser()
conf... | --- +++ @@ -1,3 +1,7 @@+"""
+This module handles all the phishing related operations for
+Wifiphisher.py
+"""
import os
@@ -13,6 +17,9 @@
def config_section_map(config_file, section):
+ """
+ Map the values of a config file to a dictionary.
+ """
config = ConfigParser()
config.read(config_... | https://raw.githubusercontent.com/wifiphisher/wifiphisher/HEAD/wifiphisher/common/phishingpage.py |
Add standardized docstrings across the file | from datetime import datetime
from chatterbot import languages
from chatterbot.logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot.utils import get_model_for_language
from chatterbot.logic.mcp_tools import MCPToolAdapter
import spacy
class TimeLogicAdapter(LogicAdapter, MCPToolAdap... | --- +++ @@ -8,6 +8,16 @@
class TimeLogicAdapter(LogicAdapter, MCPToolAdapter):
+ """
+ The TimeLogicAdapter returns the current time.
+
+ :kwargs:
+ * *positive* (``list``) --
+ The time-related questions used to identify time questions about the current time.
+ Defaults to a list ... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/logic/time_adapter.py |
Write docstrings including parameters and return values | class Adapter(object):
def __init__(self, chatbot, **kwargs):
self.chatbot = chatbot
class AdapterMethodNotImplementedError(NotImplementedError):
def __init__(self, message='This method must be overridden in a subclass method.'):
super().__init__(message)
class InvalidAdapter... | --- +++ @@ -1,12 +1,29 @@ class Adapter(object):
+ """
+ A superclass for all adapter classes.
+
+ :param chatbot: A ChatBot instance.
+ """
def __init__(self, chatbot, **kwargs):
self.chatbot = chatbot
class AdapterMethodNotImplementedError(NotImplementedError):
+ """
+ ... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/adapters.py |
Add return value explanations in docstrings | from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship, declarative_base
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declared_attr
from chatterbot.conversation import StatementMixin
from chatterbot import constants
class ModelBas... | --- +++ @@ -8,9 +8,15 @@
class ModelBase(object):
+ """
+ An augmented base class for SqlAlchemy models.
+ """
@declared_attr
def __tablename__(cls) -> str:
+ """
+ Return the lowercase class name as the name of the table.
+ """
return cls.__name__.lower()
i... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/ext/sqlalchemy_app/models.py |
Add documentation for all methods | import re
from random import randint
from chatterbot.storage import StorageAdapter
class MongoDatabaseAdapter(StorageAdapter):
def __init__(self, **kwargs):
super().__init__(**kwargs)
from pymongo import MongoClient
from pymongo.errors import OperationFailure
self.database_uri = ... | --- +++ @@ -4,6 +4,31 @@
class MongoDatabaseAdapter(StorageAdapter):
+ """
+ The MongoDatabaseAdapter is an interface that allows
+ ChatterBot to store statements in a MongoDB database.
+
+ :keyword database_uri: The URI of a remote instance of MongoDB.
+ This can be any valid
... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/storage/mongodb.py |
Write docstrings describing each step | class IndexedTextSearch:
name = 'indexed_text_search'
def __init__(self, chatbot, **kwargs):
from chatterbot.comparisons import LevenshteinDistance
self.chatbot = chatbot
statement_comparison_function = kwargs.get(
'statement_comparison_function',
LevenshteinD... | --- +++ @@ -1,4 +1,12 @@ class IndexedTextSearch:
+ """
+ :param statement_comparison_function: A comparison class.
+ Defaults to ``LevenshteinDistance``.
+
+ :param search_page_size:
+ The maximum number of records to load into memory at a time when searching.
+ Defaults to 1000
+ """
... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/search.py |
Can you add docstrings to this Python file? | import string
from spacy.language import Language
from spacy.tokens import Doc
punctuation_table = str.maketrans(dict.fromkeys(string.punctuation))
@Language.component('chatterbot_bigram_indexer')
def chatterbot_bigram_indexer(document):
if not Doc.has_extension('search_index'):
Doc.set_extension('sear... | --- +++ @@ -1,3 +1,7 @@+"""
+Custom components for Spacy processing pipelines.
+https://spacy.io/usage/processing-pipelines#custom-components
+"""
import string
from spacy.language import Language
from spacy.tokens import Doc
@@ -8,6 +12,9 @@
@Language.component('chatterbot_bigram_indexer')
def chatterbot_bigram_... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/components.py |
Add detailed docstrings explaining each function |
def setup_canonical_func(app, pagename, templatename, context, doctree):
conf = app.config
def canonical_func():
# Special case for the root index page
if pagename == 'index':
return conf.html_baseurl
dir_name = pagename.replace('/index', '/')
return f'{conf.html_... | --- +++ @@ -1,5 +1,14 @@+"""
+Add GitHub repository details to the Sphinx context.
+"""
def setup_canonical_func(app, pagename, templatename, context, doctree):
+ """
+ Return the url to the specified page on GitHub.
+
+ (Sphinx 7.4 generates a canonical link with a .html extension even
+ when run in dir... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/docs/_ext/canonical.py |
Document this module using docstrings |
import sys
def get_chatterbot_version():
from chatterbot import __version__
return __version__
if __name__ == '__main__':
if '--version' in sys.argv:
print(get_chatterbot_version())
elif '--help' in sys.argv:
print('usage: chatterbot [--version, --help]')
print(' --version... | --- +++ @@ -1,8 +1,16 @@+"""
+Example usage for ChatterBot command line arguments:
+
+python -m chatterbot --help
+"""
import sys
def get_chatterbot_version():
+ """
+ Return the version of the current package.
+ """
from chatterbot import __version__
return __version__
@@ -16,4 +24,4 @@ ... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/__main__.py |
Document classes and their methods | from chatterbot.conversation import StatementMixin
from chatterbot import constants
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.apps import apps
DJANGO_APP_NAME = constants.DEFAULT_DJANGO_APP_NAME
# Default model paths for swappable models
# These can b... | --- +++ @@ -15,6 +15,10 @@
class AbstractBaseTag(models.Model):
+ """
+ The abstract base tag allows other models to be created
+ using the attributes that exist on the default models.
+ """
name = models.SlugField(
max_length=constants.TAG_NAME_MAX_LENGTH,
@@ -30,6 +34,10 @@
class A... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/ext/django_chatterbot/abstract_models.py |
Document this script properly | import json
from typing import Any, Dict, List, Optional, Union
from chatterbot.logic.logic_adapter import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot.logic.mcp_tools import (
is_tool_adapter,
convert_to_openai_tool_format,
convert_to_ollama_tool_format
)
from chatterbot impo... | --- +++ @@ -1,3 +1,9 @@+"""
+LLM Logic Adapters for ChatterBot.
+
+This module provides logic adapters that integrate Large Language Models.
+LLM adapters can use other logic adapters as tools via MCP (Model Context Protocol).
+"""
import json
from typing import Any, Dict, List, Optional, Union
@@ -12,6 +18,39 @@
... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/logic/llm_adapters.py |
Add missing documentation to my Python functions | import os
import io
import glob
from pathlib import Path
from chatterbot.exceptions import OptionalDependencyImportError
try:
from chatterbot_corpus.corpus import DATA_DIRECTORY
except (ImportError, ModuleNotFoundError):
# Default to the home directory of the current user
DATA_DIRECTORY = os.path.join(
... | --- +++ @@ -19,6 +19,9 @@
def get_file_path(dotted_path, extension='json') -> str:
+ """
+ Reads a dotted file path and returns the file path.
+ """
# If the operating system's file path seperator character is in the string
if os.sep in dotted_path or '/' in dotted_path:
# Assume the pat... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/corpus.py |
Generate descriptive docstrings automatically | import os
import csv
import time
import glob
import json
import tarfile
from typing import List, Union
from tqdm import tqdm
from dateutil import parser as date_parser
from chatterbot.chatterbot import ChatBot
from chatterbot.conversation import Statement
class Trainer(object):
def __init__(self, chatbot: ChatBo... | --- +++ @@ -12,6 +12,14 @@
class Trainer(object):
+ """
+ Base class for all other trainer classes.
+
+ :param boolean show_training_progress: Show progress indicators for the
+ trainer. The environment variable ``CHATTERBOT_SHOW_TRAINING_PROGRESS``
+ can also be set to control this. ``... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/trainers.py |
Create docstrings for all classes and functions | from chatterbot.ext.django_chatterbot.abstract_models import AbstractBaseStatement, AbstractBaseTag
class Statement(AbstractBaseStatement):
class Meta:
swappable = 'CHATTERBOT_STATEMENT_MODEL'
class Tag(AbstractBaseTag):
class Meta:
swappable = 'CHATTERBOT_TAG_MODEL' | --- +++ @@ -2,12 +2,25 @@
class Statement(AbstractBaseStatement):
+ """
+ A statement represents a single spoken entity, sentence or
+ phrase that someone can say.
+
+ This model can be swapped for a custom model by setting
+ CHATTERBOT_STATEMENT_MODEL in your Django settings.
+ """
class M... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/ext/django_chatterbot/models.py |
Generate documentation strings for clarity | from typing import List, Union, Tuple
from chatterbot import languages
from chatterbot.utils import get_model_for_language
import spacy
class NoOpTagger(object):
def __init__(self, language=None):
self.language = language or languages.ENG
def needs_text_indexing(self):
return False
def ... | --- +++ @@ -5,14 +5,27 @@
class NoOpTagger(object):
+ """
+ A no-operation tagger that returns text unchanged.
+ Used by storage adapters that don't rely on indexed search_text fields.
+ """
def __init__(self, language=None):
self.language = language or languages.ENG
def needs_tex... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/tagging.py |
Insert docstrings into my code | from chatterbot.logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot.exceptions import OptionalDependencyImportError
from chatterbot import languages
from chatterbot import parsing
from chatterbot.logic.mcp_tools import MCPToolAdapter
from mathparse import mathparse
import re
class ... | --- +++ @@ -9,6 +9,18 @@
class UnitConversion(LogicAdapter, MCPToolAdapter):
+ """
+ The UnitConversion logic adapter parse inputs to convert values
+ between several metric units.
+
+ For example:
+ User: 'How many meters are in one kilometer?'
+ Bot: '1000.0'
+
+ :kwargs:
+ * *... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/logic/unit_conversion.py |
Create docstrings for reusable components | from chatterbot.conversation import Statement
from unicodedata import normalize
from re import sub as re_sub
from html import unescape
def clean_whitespace(statement: Statement) -> Statement:
# Replace linebreaks and tabs with spaces
# Uses splitlines() which includes a superset of universal newlines:
# h... | --- +++ @@ -1,3 +1,6 @@+"""
+Statement pre-processors.
+"""
from chatterbot.conversation import Statement
from unicodedata import normalize
from re import sub as re_sub
@@ -5,6 +8,9 @@
def clean_whitespace(statement: Statement) -> Statement:
+ """
+ Remove any consecutive whitespace characters from the sta... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/preprocessors.py |
Document this code for team use | from chatterbot.storage import StorageAdapter
from chatterbot import constants
class DjangoStorageAdapter(StorageAdapter):
def __init__(self, **kwargs):
super().__init__(**kwargs)
from django.conf import settings
self.django_app_name = kwargs.get(
'django_app_name',
... | --- +++ @@ -3,6 +3,17 @@
class DjangoStorageAdapter(StorageAdapter):
+ """
+ Storage adapter that allows ChatterBot to interact with
+ Django storage backends.
+
+ :param database: The Django database alias to use (default: 'default')
+ :type database: str
+ :param statement_model: The Statement m... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/storage/django_storage.py |
Improve my code by adding docstrings | from typing import Any, Dict
from abc import ABC, abstractmethod
class MCPToolAdapter(ABC):
@abstractmethod
def get_tool_schema(self) -> Dict[str, Any]:
raise NotImplementedError(
"Logic adapters using MCPToolAdapter must implement get_tool_schema()"
)
@abstractmethod
def... | --- +++ @@ -1,26 +1,112 @@+"""
+MCP (Model Context Protocol) tool adapter for ChatterBot logic adapters.
+
+This module provides a mixin class that allows logic adapters to be exposed
+as MCP-compatible tools to LLMs. Logic adapters that inherit from MCPToolAdapter
+can define tool schemas and be invoked by LLM adapter... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/logic/mcp_tools.py |
Add docstrings to clarify complex logic | import logging
import uuid
from typing import Union
from chatterbot.storage import StorageAdapter
from chatterbot.logic import LogicAdapter
from chatterbot.search import TextSearch, IndexedTextSearch, SemanticVectorSearch
from chatterbot.tagging import PosLemmaTagger
from chatterbot.conversation import Statement
from c... | --- +++ @@ -12,6 +12,45 @@
class ChatBot(object):
+ """
+ A conversational dialog chat bot.
+
+ :param name: A name is the only required parameter for the ChatBot class.
+ :type name: str
+
+ :keyword storage_adapter: The dot-notated import path to a storage adapter class.
+ ... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/chatterbot.py |
Document functions with clear intent | from datetime import datetime
import json
import re
from chatterbot.storage import StorageAdapter
from chatterbot.conversation import Statement as StatementObject
def _escape_redis_special_characters(text):
from redisvl.query.filter import TokenEscaper
# Remove space (last character) and add pipe
escape_... | --- +++ @@ -6,6 +6,14 @@
def _escape_redis_special_characters(text):
+ """
+ Escape special characters in a string that are used in redis queries.
+
+ This function escapes characters that would interfere with the query syntax
+ used in the filter() method, specifically:
+ - Pipe (|) which is used as... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/storage/redis.py |
Write documentation strings for class attributes | import re
from datetime import timedelta, datetime
import calendar
# Variations of dates that the parser can capture
year_variations = ['year', 'years', 'yrs']
day_variations = ['days', 'day']
minute_variations = ['minute', 'minutes', 'mins']
hour_variations = ['hrs', 'hours', 'hour']
week_variations = ['weeks', 'week... | --- +++ @@ -504,6 +504,9 @@
def convert_string_to_number(value: str) -> int:
+ """
+ Convert strings to numbers
+ """
if value is None:
return 1
if isinstance(value, int):
@@ -515,6 +518,9 @@
def convert_time_to_hour_minute(hour: str, minute: str, convention: str) -> dict:
+ """
+... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/parsing.py |
Add docstrings to existing functions | from chatterbot.conversation import Statement
import logging
def get_most_frequent_response(input_statement: Statement, response_list: list[Statement], storage=None) -> Statement:
logger = logging.getLogger(__name__)
logger.info('Selecting response with greatest number of occurrences.')
# Collect all uni... | --- +++ @@ -1,8 +1,23 @@+"""
+Response selection methods determines which response should be used in
+the event that multiple responses are generated within a logic adapter.
+"""
from chatterbot.conversation import Statement
import logging
def get_most_frequent_response(input_statement: Statement, response_list:... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/response_selection.py |
Auto-generate documentation strings for this file | from chatterbot.utils import get_model_for_language
from difflib import SequenceMatcher
import spacy
class Comparator:
def __init__(self, language):
self.language = language
def __call__(self, statement_a, statement_b):
return self.compare(statement_a, statement_b)
def compare_text(sel... | --- +++ @@ -1,9 +1,16 @@+"""
+This module contains various text-comparison algorithms
+designed to compare one statement to another.
+"""
from chatterbot.utils import get_model_for_language
from difflib import SequenceMatcher
import spacy
class Comparator:
+ """
+ Base class establishing the interface tha... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/comparisons.py |
Document this module using docstrings | from typing import Union
import importlib
import time
def import_module(dotted_path: str):
module_parts = dotted_path.split('.')
module_path = '.'.join(module_parts[:-1])
module = importlib.import_module(module_path)
return getattr(module, module_parts[-1])
def initialize_class(data: Union[dict, st... | --- +++ @@ -1,9 +1,16 @@+"""
+ChatterBot utility functions
+"""
from typing import Union
import importlib
import time
def import_module(dotted_path: str):
+ """
+ Imports the specified module based on the
+ dot notated import path for the module.
+ """
module_parts = dotted_path.split('.')
... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/utils.py |
Help me add docstrings to my project | from chatterbot.logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot import languages
from chatterbot.logic.mcp_tools import MCPToolAdapter
class MathematicalEvaluation(LogicAdapter, MCPToolAdapter):
def __init__(self, chatbot, **kwargs):
super().__init__(chatbot, **kwa... | --- +++ @@ -5,6 +5,20 @@
class MathematicalEvaluation(LogicAdapter, MCPToolAdapter):
+ """
+ The MathematicalEvaluation logic adapter parses input to determine
+ whether the user is asking a question that requires math to be done.
+ If so, the equation is extracted from the input and returned with
+ ... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/logic/mathematical_evaluation.py |
Add docstrings for production code | from datetime import datetime, timezone
from dateutil import parser as date_parser
class StatementMixin(object):
statement_field_names = [
'id',
'text',
'search_text',
'conversation',
'persona',
'tags',
'in_response_to',
'search_in_response_to',
... | --- +++ @@ -3,6 +3,10 @@
class StatementMixin(object):
+ """
+ This class has shared methods used to
+ normalize different statement models.
+ """
statement_field_names = [
'id',
@@ -19,15 +23,27 @@ extra_statement_field_names = []
def get_statement_field_names(self) -> list[s... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/conversation.py |
Add docstrings for better understanding | from random import choice
from chatterbot.adapters import Adapter
from chatterbot.storage import StorageAdapter
from chatterbot.search import IndexedTextSearch
from chatterbot.conversation import Statement
from chatterbot import utils
class LogicAdapter(Adapter):
def __init__(self, chatbot, **kwargs):
s... | --- +++ @@ -8,6 +8,31 @@
class LogicAdapter(Adapter):
+ """
+ This is an abstract class that represents the interface
+ that all logic adapters should implement.
+
+ :param search_algorithm_name: The name of the search algorithm that should
+ be used to search for close matches to the provided in... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/logic/logic_adapter.py |
Write docstrings describing each step | import logging
class StorageAdapter(object):
def __init__(self, *args, **kwargs):
self.logger = kwargs.get('logger', logging.getLogger(__name__))
self.raise_on_missing_search_text = kwargs.get(
'raise_on_missing_search_text', True
)
def get_model(self, model_name):
... | --- +++ @@ -2,8 +2,17 @@
class StorageAdapter(object):
+ """
+ This is an abstract class that represents the interface
+ that all storage adapters should implement.
+ """
def __init__(self, *args, **kwargs):
+ """
+ Initialize common attributes shared by all storage adapters.
+
+ ... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/storage/storage_adapter.py |
Document this script properly | from __future__ import annotations
from typing import List
from langchain_core.documents import Document
from redisvl.redis.utils import convert_bytes
from redisvl.query import FilterQuery
from langchain_redis.vectorstores import RedisVectorStore as LangChainRedisVectorStore
class RedisVectorStore(LangChainRedisVe... | --- +++ @@ -1,3 +1,6 @@+"""
+Redis vector store.
+"""
from __future__ import annotations
from typing import List
@@ -10,6 +13,9 @@
class RedisVectorStore(LangChainRedisVectorStore):
+ """
+ Redis vector store integration.
+ """
def query_search(
self,
@@ -17,6 +23,19 @@ filter=N... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/vectorstores.py |
Write beginner-friendly docstrings | import random
from chatterbot.storage import StorageAdapter
class SQLStorageAdapter(StorageAdapter):
def __init__(self, **kwargs):
super().__init__(**kwargs)
from sqlalchemy import create_engine, inspect, event
from sqlalchemy import Index
from sqlalchemy.engine import Engine
... | --- +++ @@ -3,6 +3,19 @@
class SQLStorageAdapter(StorageAdapter):
+ """
+ The SQLStorageAdapter allows ChatterBot to store conversation
+ data in any database supported by the SQL Alchemy ORM.
+
+ All parameters are optional, by default a sqlite database is used.
+
+ It will check if tables are prese... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/chatterbot/storage/sql_storage.py |
Add docstrings for internal functions |
GITHUB_USER = 'gunthercox'
GITHUB_REPO = 'ChatterBot'
def setup_github_func(app, pagename, templatename, context, doctree):
github_version = 'master'
docs_path = 'docs'
def my_func():
return f'https://github.com/{GITHUB_USER}/{GITHUB_REPO}/blob/{github_version}/{docs_path}/{pagename}.rst'
... | --- +++ @@ -1,9 +1,15 @@+"""
+Add GitHub repository details to the Sphinx context.
+"""
GITHUB_USER = 'gunthercox'
GITHUB_REPO = 'ChatterBot'
def setup_github_func(app, pagename, templatename, context, doctree):
+ """
+ Return the url to the specified page on GitHub.
+ """
github_version = 'mas... | https://raw.githubusercontent.com/gunthercox/ChatterBot/HEAD/docs/_ext/github.py |
Add docstrings to existing functions | from lib2to3.pgen2 import token
import os
import torch
import numpy as np
import shutil
import struct
from functools import lru_cache
from itertools import accumulate
def print_rank_0(*message):
if torch.distributed.is_initialized():
if torch.distributed.get_rank() == 0:
print(*message, flush=T... | --- +++ @@ -8,6 +8,7 @@ from itertools import accumulate
def print_rank_0(*message):
+ """If distributed is initialized print only on rank 0."""
if torch.distributed.is_initialized():
if torch.distributed.get_rank() == 0:
print(*message, flush=True)
@@ -176,6 +177,11 @@ retu... | https://raw.githubusercontent.com/BlinkDL/RWKV-LM/HEAD/RWKV-v4/src/binidx.py |
Insert docstrings into my code | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... | --- +++ @@ -5,6 +5,7 @@ # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
+"""Helper wrapper for a Tensorflow optimizer."""
import numpy as np
import tensorflow as tf
@@ -26,6 +27,15 @@ import tensorflow.contrib.nccl as nccl_op... | https://raw.githubusercontent.com/NVlabs/stylegan/HEAD/dnnlib/tflib/optimizer.py |
Write docstrings describing functionality | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... | --- +++ @@ -5,6 +5,7 @@ # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
+"""Submit a function to be run either locally or in a computing cluster."""
import copy
import io
@@ -27,10 +28,20 @@
class SubmitTarget(Enum):
+ """... | https://raw.githubusercontent.com/NVlabs/stylegan/HEAD/dnnlib/submission/submit.py |
Help me add docstrings to my project | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... | --- +++ @@ -5,6 +5,7 @@ # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
+"""Miscellaneous utility classes and functions."""
import ctypes
import fnmatch
@@ -33,6 +34,7 @@
class EasyDict(dict):
+ """Convenience class that b... | https://raw.githubusercontent.com/NVlabs/stylegan/HEAD/dnnlib/util.py |
Generate docstrings with examples | # type: ignore
import _ssl
import os
import sys
import base64
import warnings
from collections import namedtuple
from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag, _simple_enum
from socket import socket, create_connection, _GLOBAL_DEFAULT_TIMEOUT
from _ssl import (
OPENSSL_VERSION_NUMBER,
... | --- +++ @@ -1,4 +1,10 @@ # type: ignore
+"""
+Stub implementation of Python's ssl module for Pyodide.
+
+This module provides stub implementations so that code importing ssl does not fail.
+Actual SSL operations are not supported in Pyodide's browser environment.
+"""
import _ssl
import os
@@ -96,6 +102,7 @@
@_si... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/ssl.py |
Write documentation strings for class attributes | from inspect import (
Parameter,
getattr_static,
isclass,
iscoroutinefunction,
ismethod,
signature,
)
from types import GenericAlias
from typing import ( # type:ignore[attr-defined]
Any,
_AnnotatedAlias,
_GenericAlias,
_UnionGenericAlias,
get_type_hints,
)
from _pyodide_cor... | --- +++ @@ -142,6 +142,9 @@
def get_attr_sig_prop(attr_sig):
+ """Helper for get_attr_sig in case that the attribute we're looking up is a
+ property with annotation.
+ """
# If the attribute is marked with BindClass, then we should attach bind it
# to the resulting proxy.
if isinstance(attr... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/_pyodide/jsbind.py |
Provide docstrings following PEP 257 | #!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
import argparse
import functools
import os
import re
import subprocess
import sys
from collections import namedtuple
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Self
tr... | --- +++ @@ -1,6 +1,19 @@ #!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
+"""
+The main purpose of this script is to automate the changelog transformations
+involved in backports. Many cherry-picks lead to changelog conflicts, and we
+need also to rearrange the changelog on the main branch.
+
+We implement a parser f... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/tools/backport.py |
Document functions with clear intent | import gzip
import io
import mimetypes
import os
import shutil
from pathlib import Path
import boto3
import botocore
import typer
app = typer.Typer()
def check_s3_object_exists(s3_client, bucket: str, object_name: str):
try:
s3_client.head_object(Bucket=bucket, Key=object_name)
return True
e... | --- +++ @@ -24,6 +24,19 @@
def _validate_remote_prefix_to_remove(remote_prefix: Path) -> None:
+ """Check remote prefix to remove
+
+ Examples
+ --------
+ >>> _validate_remote_prefix_to_remove(Path("dev/full/"))
+ >>> _validate_remote_prefix_to_remove(Path("dev/abc2/"))
+ >>> _validate_remote_pre... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/tools/deploy_s3.py |
Help me add docstrings to my project | from collections.abc import Callable
from functools import lru_cache, wraps
from inspect import Parameter, Signature, signature
from typing import Any, ParamSpec, TypeVar
from _pyodide._base import (
CodeRunner,
eval_code,
eval_code_async,
find_imports,
should_quiet,
)
def run_js(code: str, /) ->... | --- +++ @@ -13,6 +13,12 @@
def run_js(code: str, /) -> Any:
+ """
+ A wrapper for the :js:func:`eval` function.
+
+ Runs ``code`` as a Javascript code string and returns the result. Unlike
+ :js:func:`eval`, if ``code`` is not a string we raise a :py:exc:`TypeError`.
+ """
from js import eval as... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/code.py |
Write clean docstrings for readability | import argparse
import subprocess
import sys
import tempfile
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from pyodide_lock import PackageSpec, PyodideLockSpec
def parse_args():
parser = argparse.ArgumentParser(
description="Compare two Pyodide lockfiles and output the... | --- +++ @@ -40,6 +40,15 @@
def get_lockfile_url_from_makefile(branch: str | None = None) -> str:
+ """
+ Get the PYODIDE_PREBUILT_PACKAGES_LOCKFILE URL from the Makefile.
+
+ Args:
+ branch: If provided, get the URL from this git branch. If None, use the current branch.
+
+ Returns:
+ The ... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/tools/create_lockfile_diff.py |
Document functions with detailed explanations | #!/usr/bin/env python3
import re
import shutil
import zipfile
from collections.abc import Callable
from pathlib import Path
from tempfile import TemporaryDirectory
def default_filterfunc(
root: Path, excludes: list[str], stubs: list[str], verbose: bool = False
) -> Callable[[str, list[str]], set[str]]:
def _... | --- +++ @@ -10,8 +10,17 @@ def default_filterfunc(
root: Path, excludes: list[str], stubs: list[str], verbose: bool = False
) -> Callable[[str, list[str]], set[str]]:
+ """
+ The default filter function used by `create_zipfile`.
+
+ This function filters out several modules that are:
+
+ - not support... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/tools/create_zipfile.py |
Document helper functions with docstrings | import asyncio
import contextvars
import inspect
import os
import sys
import time
import traceback
import warnings
import weakref
from asyncio import Future, Task, sleep
from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
from functools import wraps
from typing import Any, TypeVar, overload
from... | --- +++ @@ -22,6 +22,12 @@
class PyodideFuture(Future[T]):
+ """A :py:class:`~asyncio.Future` with extra :js:meth:`~Promise.then`,
+ :js:meth:`~Promise.catch`, and :js:meth:`finally_() <Promise.finally>` methods
+ based on the Javascript promise API. :py:meth:`~asyncio.loop.create_future`
+ returns thes... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/webloop.py |
Create documentation for each function signature | from functools import update_wrapper
from textwrap import dedent
from typing import Any
def delete_attrs(cls):
for name in dir(cls):
if not name.startswith("_"):
try:
delattr(cls, name)
except Exception:
pass
def docs_argspec(argspec: str) -> Any:
... | --- +++ @@ -4,6 +4,11 @@
def delete_attrs(cls):
+ """Prevent attributes of a class or module from being documented.
+
+ The top level documentation comment of the class or module will still be
+ rendered.
+ """
for name in dir(cls):
if not name.startswith("_"):
try:
@@ -13,6 +... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/docs/sphinx_pyodide/sphinx_pyodide/util.py |
Create simple docstrings for beginners | import os
import sys
from abc import ABCMeta
from collections.abc import (
AsyncIterator,
Awaitable,
Callable,
ItemsView,
Iterable,
Iterator,
KeysView,
Mapping,
MutableMapping,
MutableSequence,
Sequence,
ValuesView,
)
from functools import reduce
from types import Traceba... | --- +++ @@ -61,6 +61,7 @@
class _JsProxyMetaClass(type):
def __instancecheck__(cls, instance):
+ """Override for isinstance(instance, cls)."""
# TODO: add support for user-generated subclasses with custom instance
# checks
# e.g., could check for a fetch response with x.construc... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/_pyodide/_core_docs.py |
Document this code for team use | import re
import sys
from collections.abc import Callable, Sequence
from importlib.abc import Loader, MetaPathFinder
from importlib.machinery import ModuleSpec, PathFinder
from importlib.util import spec_from_loader
from types import ModuleType
from typing import Any
from ._core_docs import JsProxy
class JsFinder(Me... | --- +++ @@ -52,6 +52,22 @@ return spec_from_loader(fullname, loader, origin="javascript")
def register_js_module(self, name: str, jsproxy: Any) -> None:
+ """
+ Registers ``jsproxy`` as a JavaScript module named ``name``. The module
+ can then be imported from Python using the standa... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/_pyodide/_importhook.py |
Write beginner-friendly docstrings | #!/usr/bin/env python3
from datetime import date
from sys import version_info
import requests
def latest_version_of_chrome() -> str:
URL = "https://chromedriver.storage.googleapis.com/LATEST_RELEASE"
return requests.get(URL).text.split(".")[0]
def latest_version_of_firefox() -> str:
URL = "https://www... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Get the current versions of Chrome and Firefox to aid in tagging Docker images.
+
+Old Docker image tag: 20230411-chromelatest-firefoxlatest
+New Docker image tag: 20230411-chrome112-firefox112-py311
+"""
from datetime import date
from sys import version_info
@@... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/tools/docker_image_tag.py |
Add clean documentation to messy code | import re
import shutil
import sys
from collections.abc import Iterable
from importlib.machinery import EXTENSION_SUFFIXES
from pathlib import Path
from site import getsitepackages
from tempfile import NamedTemporaryFile
from typing import IO, Any, Literal
from zipfile import ZipFile
try:
from pyodide_js import lo... | --- +++ @@ -82,9 +82,25 @@
# Vendored from pip
class UnsupportedWheel(Exception):
+ """Unsupported wheel."""
def find_wheel_metadata_dir(source: ZipFile, suffix: str) -> str | None:
+ """
+ Returns the name of the contained metadata directory inside the wheel file.
+
+ Parameters
+ ----------
+ ... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/_package_loader.py |
Add docstrings to improve readability | import ast
import asyncio
import rlcompleter
import sys
import traceback
from asyncio import Future, ensure_future
from codeop import ( # type: ignore[attr-defined]
CommandCompiler,
Compile,
PyCF_ALLOW_INCOMPLETE_INPUT,
PyCF_DONT_IMPLY_DEDENT,
_features,
)
from collections.abc import Callable, Gene... | --- +++ @@ -138,6 +138,13 @@
class _Compile(Compile):
+ """Compile code with CodeRunner, and remember future imports
+
+ Instances of this class behave much like the built-in compile function,
+ but if one is used to compile text containing a future statement, it
+ "remembers" and compiles all subsequen... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/console.py |
Help me comply with documentation standards | import gc
import sys
from typing import Any
import __main__
from _pyodide._importhook import jsfinder
from .ffi import JsProxy
def save_state() -> dict[str, Any]:
loaded_js_modules = {}
for [key, value] in sys.modules.items():
if isinstance(value, JsProxy):
loaded_js_modules[key] = value... | --- +++ @@ -9,6 +9,12 @@
def save_state() -> dict[str, Any]:
+ """Record the current global state.
+
+ This includes which JavaScript packages are loaded and the global scope in
+ ``__main__.__dict__``. Many loaded modules might have global state, but
+ there is no general way to track it and we don't t... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/_state.py |
Write clean docstrings for readability |
import builtins
import json
from asyncio import CancelledError
from collections.abc import Awaitable, Callable
from functools import wraps
from typing import IO, TYPE_CHECKING, Any, ParamSpec, TypeVar
from .._package_loader import unpack_buffer
from ..ffi import IN_PYODIDE, JsBuffer, JsException, JsFetchResponse, to_... | --- +++ @@ -1,3 +1,6 @@+"""
+Async fetch API implementation for Pyodide.
+"""
import builtins
import json
@@ -40,6 +43,7 @@
def _construct_abort_reason(reason: Any) -> JsException | None:
+ """Construct an abort reason from a given value."""
if reason is None:
return None
return JsExceptio... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/http/_pyfetch.py |
Add detailed documentation for each class | from collections.abc import Iterator
from sphinx_js import ir
from sphinx_js.ir import Class, TypeXRefInternal
from sphinx_js.typedoc import Analyzer as TsAnalyzer
__all__ = ["ts_xref_formatter", "patch_sphinx_js"]
def patch_sphinx_js():
TsAnalyzer._get_toplevel_objects = _get_toplevel_objects
def ts_xref_for... | --- +++ @@ -12,6 +12,7 @@
def ts_xref_formatter(_config, xref):
+ """Format cross references info sphinx roles"""
from sphinx_pyodide.mdn_xrefs import JSDATA
name = xref.name
@@ -40,6 +41,9 @@
def has_tag(doclet, tag):
+ """Detects whether the doclet comes from a node that has the given modifi... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/docs/sphinx_pyodide/sphinx_pyodide/jsdoc.py |
Insert docstrings into my code | # Configuration file for the Sphinx documentation builder.
# -- Path setup --------------------------------------------------------------
import atexit
import os
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any
from unittest import mock
panels_add_bootstrap_css = False
# --... | --- +++ @@ -25,6 +25,7 @@
def ignore_typevars():
+ """These are all intentionally broken. Disable the warnings about it."""
PY_TYPEVARS_TO_IGNORE = ("T", "T_co", "T_contra", "V_co", "KT", "VT", "VT_co", "P")
JS_TYPEVARS_TO_IGNORE = ("TResult", "TResult1", "TResult2", "U")
@@ -283,6 +284,7 @@
def ... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/docs/conf.py |
Create docstrings for each class method | # setup: N=10
# run: julia(1., 1., N, 1.5, 10., 1e4)
# pythran export julia(float, float, int, float, float, float)
import numpy as np
def kernel(zr, zi, cr, ci, lim, cutoff):
count = 0
while ((zr * zr + zi * zi) < (lim * lim)) and count < cutoff:
zr, zi = zr * zr - zi * zi + cr, 2 * zr * zi + ci
... | --- +++ @@ -6,6 +6,9 @@
def kernel(zr, zi, cr, ci, lim, cutoff):
+ """Computes the number of iterations `n` such that
+ |z_n| > `lim`, where `z_n = z_{n-1}**2 + c`.
+ """
count = 0
while ((zr * zr + zi * zi) < (lim * lim)) and count < cutoff:
zr, zi = zr * zr - zi * zi + cr, 2 * zr * zi ... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/benchmark/benchmarks/numpy_benchmarks/julia.py |
Add structured docstrings to improve clarity | from textwrap import dedent
def dedent_docstring(docstring):
first_newline = docstring.find("\n")
if first_newline == -1:
return docstring
docstring = docstring[:first_newline] + dedent(docstring[first_newline:])
return docstring
def get_cmeth_docstring(func):
from inspect import _empty,... | --- +++ @@ -2,6 +2,17 @@
def dedent_docstring(docstring):
+ """This removes initial spaces from the lines of the docstring.
+
+ After the first line of the docstring, all other lines will include some
+ spaces. This removes them.
+
+ Examples
+ --------
+ >>> from _pyodide.docstring import dedent_... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/_pyodide/docstring.py |
Write docstrings for data processing functions |
import base64
import json
from typing import Any, NotRequired, TypedDict, Unpack
from urllib.parse import urlencode
from ..ffi import IN_PYODIDE
from ._exceptions import HttpStatusError, XHRError, XHRNetworkError
if IN_PYODIDE:
try:
from js import XMLHttpRequest
from pyodide.ffi import JsExceptio... | --- +++ @@ -1,3 +1,21 @@+"""XMLHttpRequest-based HTTP client for Pyodide.
+
+Provides a requests-like synchronous HTTP API using XMLHttpRequest,
+designed specifically for browser environments where traditional HTTP libraries don't work.
+
+Examples
+--------
+>>> from pyodide.http import pyxhr # doctest: +RUN_IN_PYOD... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/http/pyxhr.py |
Create documentation for each function signature | from pathlib import Path
from sphinx.addnodes import desc_signature
from sphinx_js import renderers
from .jsdoc import (
patch_sphinx_js,
ts_xref_formatter,
)
from .lexers import HtmlPyodideLexer, PyodideLexer
from .mdn_xrefs import add_mdn_xrefs
from .packages import get_packages_summary_directive
def fix_... | --- +++ @@ -13,6 +13,16 @@
def fix_pyodide_ffi_path():
+ """
+ The `pyodide.ffi` stuff is defined in `_pyodide._core_docs`. We don't want
+ `_pyodide._core_docs` to appear in the documentation because this isn't
+ where you should import things from so we override the `__name__` of
+ `_pyodide._core_... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/docs/sphinx_pyodide/sphinx_pyodide/__init__.py |
Add docstrings to improve readability | from typing import Any
from ..ffi import JsException
class HttpStatusError(OSError):
status: int
status_text: str
url: str
def __init__(self, status: int, status_text: str, url: str) -> None:
self.status = status
self.status_text = status_text
self.url = url
if 400 <... | --- +++ @@ -4,6 +4,20 @@
class HttpStatusError(OSError):
+ """A subclass of :py:exc:`OSError` raised by :py:meth:`FetchResponse.raise_for_status`
+ if the response status is 4XX or 5XX.
+
+ Parameters
+ ----------
+ status :
+ The http status code of the request
+
+ status_text :
+ The... | https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/http/_exceptions.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.