instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add docstrings to improve code quality | from collections import OrderedDict
from functools import cached_property
from typing import Dict, Optional, Tuple
from ...typing import HueType
from .. import BaseProvider, ElementsType
from .color import RandomColor
localized = True
class Provider(BaseProvider):
all_colors: Dict[str, str] = OrderedDict(
... | --- +++ @@ -10,6 +10,7 @@
class Provider(BaseProvider):
+ """Implement default color provider for Faker."""
all_colors: Dict[str, str] = OrderedDict(
(
@@ -175,21 +176,51 @@ )
def color_name(self) -> str:
+ """
+ Generate a color name.
+
+ :sample:
+ """
... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/color/__init__.py |
Add well-formatted docstrings | from .. import Provider as BankProvider
class Provider(BankProvider):
country_code = "RU"
region_codes = (
"01",
"03",
"04",
"05",
"07",
"08",
"10",
"11",
"12",
"14",
"15",
"17",
"18",
"19",
... | --- +++ @@ -2,6 +2,14 @@
class Provider(BankProvider):
+ """Implement bank provider for ``ru_RU`` locale.
+
+ Sources for region codes, currency codes, and bank names:
+
+ - https://ru.wikipedia.org/wiki/Коды_субъектов_Российской_Федерации
+ - https://ru.wikipedia.org/wiki/Общероссийский_классификатор_в... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/bank/ru_RU/__init__.py |
Write docstrings for utility functions | from typing import Tuple
from .. import BaseProvider, ElementsType
localized = True
class Provider(BaseProvider):
formats: ElementsType[str] = (
"{{last_name}} {{company_suffix}}",
"{{last_name}}-{{last_name}}",
"{{last_name}}, {{last_name}} and {{last_name}}",
)
company_suffixe... | --- +++ @@ -506,14 +506,26 @@ )
def company(self) -> str:
+ """
+ :example: 'Acme Ltd'
+ """
pattern: str = self.random_element(self.formats)
return self.generator.parse(pattern)
def company_suffix(self) -> str:
+ """
+ :example: 'Ltd'
+ """
... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/company/__init__.py |
Add minimal docstrings for each function |
import colorsys
import math
import random
import sys
from typing import TYPE_CHECKING, Dict, Literal, Optional, Sequence, Tuple
if TYPE_CHECKING:
from ...factory import Generator
from ...typing import HueType, SeedType
ColorFormat = Literal["hex", "hsl", "hsv", "rgb"]
COLOR_MAP: Dict[str, Dict[str, Sequence[... | --- +++ @@ -1,3 +1,15 @@+"""Internal module for human-friendly color generation.
+
+.. important::
+ End users of this library should not use anything in this module.
+
+Code adapted from:
+- https://github.com/davidmerfield/randomColor (CC0)
+- https://github.com/kevinwuhoo/randomcolor-py (MIT License)
+
+Addition... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/color/color.py |
Add docstrings including usage examples | from typing import Optional, Tuple
from faker.utils.checksums import calculate_luhn
from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}}",
"{{la... | --- +++ @@ -295,15 +295,27 @@ # fmt: on
def catch_phrase_noun(self) -> str:
+ """
+ Returns a random catch phrase noun.
+ """
return self.random_element(self.nouns)
def catch_phrase_attribute(self) -> str:
+ """
+ Returns a random catch phrase attribute.
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/company/fr_FR/__init__.py |
Add docstrings to clarify complex logic | from typing import List
from .. import Provider as CompanyProvider
def regon_checksum(digits: List[int]) -> int:
weights_for_check_digit = [8, 9, 2, 3, 4, 5, 6, 7]
check_digit = 0
for i in range(0, 8):
check_digit += weights_for_check_digit[i] * digits[i]
check_digit %= 11
if check_dig... | --- +++ @@ -4,6 +4,9 @@
def regon_checksum(digits: List[int]) -> int:
+ """
+ Calculates and returns a control digit for given list of digits basing on REGON standard.
+ """
weights_for_check_digit = [8, 9, 2, 3, 4, 5, 6, 7]
check_digit = 0
@@ -19,6 +22,9 @@
def local_regon_checksum(digits:... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/company/pl_PL/__init__.py |
Write docstrings for utility functions | from typing import List
from .. import Provider as CompanyProvider
def company_id_checksum(digits: List[int]) -> List[int]:
digits = list(digits)
weights = 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2
dv = sum(w * d for w, d in zip(weights[1:], digits))
dv = (11 - dv) % 11
dv = 0 if dv >= 10 else dv
... | --- +++ @@ -74,15 +74,27 @@ company_suffixes = ("S/A", "S.A.", "Ltda.", "- ME", "- EI", "e Filhos")
def catch_phrase_noun(self) -> str:
+ """
+ Returns a random catch phrase noun.
+ """
return self.random_element(self.nouns)
def catch_phrase_attribute(self) -> str:
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/company/pt_BR/__init__.py |
Fill in missing docstrings in my code | from faker.utils.checksums import calculate_luhn
from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}}-{{last_name}} {{company_suffix}}",
"{{last_name}}, {{last_name}} e {{last_name}} {{company_suffix}}",... | --- +++ @@ -347,6 +347,11 @@ company_suffixes = ("SPA", "e figli", "Group", "s.r.l.")
def _random_vat_office(self) -> int:
+ """
+ Returns a random code identifying the VAT office needed to build a valid VAT with company_vat.
+
+ See https://it.wikipedia.org/wiki/Partita_IVA#Tabella_degl... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/company/it_IT/__init__.py |
Write clean docstrings for readability | from datetime import datetime
from .. import Provider as CompanyProvider
def calculate_checksum(value: str) -> str:
factors = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8][-len(value) :]
check_sum = 0
for number, factor in zip(value, factors):
check_sum += int(number) * factor
return str((check_sum % 1... | --- +++ @@ -1085,6 +1085,9 @@ )
def catch_phrase(self) -> str:
+ """
+ :example: 'Адаптивный и масштабируемый графический интерфейс'
+ """
noun: str = self.random_element(
self.catch_phrase_nouns_masc + self.catch_phrase_nouns_fem + self.catch_phrase_nouns_neu
... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/company/ru_RU/__init__.py |
Document my Python code with docstrings | from collections import OrderedDict
from typing import Optional
from faker.providers.person.uk_UA import translit
from faker.typing import CardType, CreditCard
from .. import Provider as CreditCardProvider
class Provider(CreditCardProvider):
prefix_visa = ["4"]
prefix_mastercard = ["51", "52", "53", "54"]
... | --- +++ @@ -8,6 +8,9 @@
class Provider(CreditCardProvider):
+ """Implement credit card provider for ``uk_UA`` locale.
+ https://blog.ipay.ua/uk/sekrety-bankovskix-kart-kak-identificirovat-bank-po-nomeru-karty/
+ """
prefix_visa = ["4"]
prefix_mastercard = ["51", "52", "53", "54"]
@@ -24,6 +27,1... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/credit_card/uk_UA/__init__.py |
Add docstrings to make code maintainable | from collections import OrderedDict
from typing import Optional
from faker.providers.credit_card import Provider as CreditCardProvider
from faker.typing import CardType, CreditCard
class Provider(CreditCardProvider):
prefix_unionpay = ["62"] # UnionPay cards typically start with 62
prefix_visa = ["4"]
... | --- +++ @@ -6,6 +6,7 @@
class Provider(CreditCardProvider):
+ """Custom credit card provider for the zh_CN locale."""
prefix_unionpay = ["62"] # UnionPay cards typically start with 62
prefix_visa = ["4"]
@@ -20,6 +21,7 @@ )
def credit_card_full(self, card_type: Optional[CardType] = None) ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/credit_card/zh_CN/__init__.py |
Add docstrings for better understanding | from collections import OrderedDict
from typing import Dict, List, Optional
from ...typing import CardType, CreditCard, DateParseType
from .. import BaseProvider
localized = True
class Provider(BaseProvider):
prefix_maestro: List[str] = [
"5018",
"5020",
"5038",
"56##",
... | --- +++ @@ -8,6 +8,20 @@
class Provider(BaseProvider):
+ """Implement default credit card provider for Faker.
+
+ For all methods that take ``card_type`` as an argument, a random card type
+ will be used if the supplied value is ``None``. The list of valid card types
+ includes ``'amex'``, ``'diners'``,... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/credit_card/__init__.py |
Add docstrings for production code | from collections import OrderedDict
from typing import Optional
from faker.providers.person.ru_RU import translit
from faker.typing import CardType, CreditCard
from .. import Provider as CreditCardProvider
class Provider(CreditCardProvider):
prefix_visa = ["4"]
prefix_mastercard = [
"51",
"... | --- +++ @@ -8,6 +8,17 @@
class Provider(CreditCardProvider):
+ """Implement credit card provider for ``ru_RU`` locale.
+
+ For all methods that take ``card_type`` as an argument, a random card type
+ will be used if the supplied value is ``None``. The list of valid card types
+ includes ``'amex'``, ``'m... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/credit_card/ru_RU/__init__.py |
Add docstrings to existing functions | from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}}",
)
company_suffixes = (
"... | --- +++ @@ -20,8 +20,16 @@ )
def company_business_id(self) -> str:
+ """
+ Returns Finnish company Business Identity Code (y-tunnus).
+ Format is 8 digits - e.g. FI99999999,[8] last digit is a check
+ digit utilizing MOD 11-2. The first digit is zero for some old
+ organiza... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/company/fi_FI/__init__.py |
Write reusable docstrings | from faker.providers.person.bn_BD import translate_to_bengali_digits
from .. import Provider as CurrencyProvider
class Provider(CurrencyProvider):
currencies = (
("AED", "সংযুক্ত আরব আমিরাত দিরহাম"),
("AFN", "আফগান আফগানি"),
("সমস্ত", "আলবেনিয়ান লেক"),
("AMD", "আর্মেনিয়ান ড্রাম... | --- +++ @@ -4,6 +4,9 @@
class Provider(CurrencyProvider):
+ """
+ Implement currency provider for ``bn_BD`` locale.
+ """
currencies = (
("AED", "সংযুক্ত আরব আমিরাত দিরহাম"),
@@ -219,6 +222,10 @@ )
def pricetag(self) -> str:
+ """
+ Return price in Bengali digit wit... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/currency/bn_BD/__init__.py |
Document this module using docstrings | import platform
import re
import zoneinfo
from calendar import timegm
from datetime import MAXYEAR
from datetime import date as dtdate
from datetime import datetime
from datetime import time as dttime
from datetime import timedelta
from datetime import timezone as dttimezone
from datetime import tzinfo as TzInfo
from ... | --- +++ @@ -43,6 +43,16 @@
def change_year(current_date: dtdate, year_diff: int) -> dtdate:
+ """
+ Unless the current_date is February 29th, it is fine to just subtract years.
+ If it is a leap day, and we are rolling back to a non-leap year, it will
+ cause a ValueError.
+ Since this is relatively ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/date_time/__init__.py |
Generate docstrings for each module | from .. import Provider as DateTimeProvider
class Provider(DateTimeProvider):
DAY_NAMES = {
"0": "Ravivar",
"1": "Somvar",
"2": "Mangalvar",
"3": "Budhvar",
"4": "Guruvar",
"5": "Shukravar",
"6": "Shanivar",
}
DAY_NAMES_IN_GUJARATI = {
"0":... | --- +++ @@ -62,12 +62,15 @@ return self.MONTH_NAMES[month]
def day_of_week_in_guj(self) -> str:
+ """Returns day of the week in `Gujarati`"""
day = self.date("%w")
return self.DAY_NAMES_IN_GUJARATI[day]
def month_name_in_guj(self) -> str:
+ """Returns month name in ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/date_time/gu_IN/__init__.py |
Add docstrings explaining edge cases | import warnings
from datetime import datetime
from typing import Optional
from ....typing import DateParseType
from .. import Provider as DateParseTypeProvider
# thai_strftime() code adapted from
# https://gist.github.com/bact/b8afe49cb1ae62913e6c1e899dcddbdb
# (Same code base with PyThaiNLP 2.x)
# Public Domain or ... | --- +++ @@ -60,6 +60,9 @@
# Standard conversion support for thai_strftime()
def _std_strftime(dt_obj: datetime, fmt_char: str) -> str:
+ """
+ Standard datetime.strftime() with normalization and exception handling.
+ """
str_ = ""
try:
str_ = dt_obj.strftime(f"%{fmt_char}")
@@ -85,6 +88,1... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/date_time/th_TH/__init__.py |
Add docstrings to existing functions | from decimal import Decimal
from typing import Optional, Tuple, Union
from .. import BaseProvider
localized = True
PlaceType = Tuple[str, str, str, str, str]
class Provider(BaseProvider):
land_coords: Tuple[PlaceType, ...] = (
("42.50729", "1.53414", "les Escaldes", "AD", "Europe/Andorra"),
("... | --- +++ @@ -9,6 +9,12 @@
class Provider(BaseProvider):
+ """
+ land_coords data extracted from geonames.org, under the Creative Commons Attribution 3.0 License.
+ Coordinates are in decimal format for mapping purposes.
+ Country code is in Alpha 2 format (https://www.nationsonline.org/oneworld/country_c... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/geo/__init__.py |
Add docstrings to make code maintainable | import string
from collections import OrderedDict
from typing import Dict, Literal, Optional, Sequence, Union
from .. import BaseProvider, ElementsType
class Provider(BaseProvider):
application_mime_types: ElementsType[str] = (
"application/atom+xml", # Atom feeds
"application/ecmascript",
... | --- +++ @@ -7,6 +7,7 @@
class Provider(BaseProvider):
+ """Implement default file provider for Faker."""
application_mime_types: ElementsType[str] = (
"application/atom+xml", # Atom feeds
@@ -218,16 +219,51 @@ unix_device_prefixes: ElementsType[str] = ("sd", "vd", "xvd")
def mime_type... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/file/__init__.py |
Turn comments into proper docstrings | from faker.providers import BaseProvider
class Provider(BaseProvider):
def doi(self) -> str:
prefix = "10"
registrant = str(self.generator.random.randint(1000, 99999999))
suffix = self.generator.bothify("?#?#?##").lower()
return f"{prefix}.{registrant}/{suffix}" | --- +++ @@ -2,10 +2,21 @@
class Provider(BaseProvider):
+ """
+ Provider for Digital Object Identifier (DOI)
+ Source of info: https://en.wikipedia.org/wiki/Digital_object_identifier (English)
+ """
def doi(self) -> str:
+ """
+ Generate a valid Digital Object Identifier (DOI).
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/doi/__init__.py |
Document all public functions with docstrings | from ipaddress import IPV4LENGTH, IPV6LENGTH, IPv4Network, IPv6Address, IPv6Network
from typing import Dict, List, Optional, Tuple
from ...decode import unidecode
from ...utils.decorators import lowercase, slugify, slugify_unicode
from ...utils.distribution import choices_distribution
from .. import BaseProvider, Elem... | --- +++ @@ -11,6 +11,13 @@
class _IPv4Constants:
+ """
+ IPv4 network constants used to group networks into different categories.
+ Structure derived from `ipaddress._IPv4Constants`.
+
+ Excluded network list is updated to comply with current IANA list of
+ private and reserved networks.
+ """
... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/internet/__init__.py |
Generate missing documentation strings | from typing import Optional, Tuple
from .. import Provider as GeoProvider
class Provider(GeoProvider):
land_coords = (
("42.50729", "1.53414", "লেস এসকালডেস", "AD", "ইউরোপ/অ্যান্ডোরা"),
("36.21544", "65.93249", "সার-ই পুল", "AF", "এশিয়া/কাবুল"),
("40.49748", "44.7662", "হরাজদান", "AM", ... | --- +++ @@ -4,6 +4,9 @@
class Provider(GeoProvider):
+ """
+ Implement GEO provider for ``bn_BD`` locale.
+ """
land_coords = (
("42.50729", "1.53414", "লেস এসকালডেস", "AD", "ইউরোপ/অ্যান্ডোরা"),
@@ -982,4 +985,5 @@ )
def local_latlng(self, country_code: str = "BD", coords_only: b... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/geo/bn_BD/__init__.py |
Improve documentation using docstrings | import re
from faker.utils.decorators import slugify_domain
from .. import Provider as InternetProvider
class Provider(InternetProvider):
free_email_domains = (
"hol.gr",
"gmail.com",
"hotmail.gr",
"yahoo.gr",
"googlemail.gr",
"otenet.gr",
"forthnet.gr",
... | --- +++ @@ -34,6 +34,9 @@
def remove_accents(value: str) -> str:
+ """
+ Remove accents from characters in the given string.
+ """
search = "ΆΈΉΊΌΎΏάέήίόύώΪϊΐϋΰ"
replace = "ΑΕΗΙΟΥΩαεηιουωΙιιυυ"
@@ -47,6 +50,9 @@
def latinize(value: str) -> str:
+ """
+ Converts (transliterates) greek ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/internet/el_GR/__init__.py |
Add missing documentation to my Python functions |
from typing import Any, Optional
MAX_LENGTH = 13
class ISBN:
def __init__(
self,
ean: Optional[str] = None,
group: Optional[str] = None,
registrant: Optional[str] = None,
publication: Optional[str] = None,
) -> None:
self.ean = ean
self.group = group
... | --- +++ @@ -1,3 +1,7 @@+"""
+This module is responsible for generating the check digit and formatting
+ISBN numbers.
+"""
from typing import Any, Optional
@@ -24,6 +28,10 @@ self.check_digit = self._check_digit()
def _check_digit(self) -> str:
+ """Calculate the check digit for ISBN-13.
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/isbn/isbn.py |
Insert docstrings into my code | from typing import Dict, List, Tuple
from .. import BaseProvider
from .isbn import ISBN10, ISBN13, MAX_LENGTH
localized = True
class Provider(BaseProvider):
rules: Dict[str, Dict[str, List[Tuple[str, str, int]]]] = {}
def _body(self) -> List[str]:
ean: str = self.random_element(self.rules.keys())
... | --- +++ @@ -7,10 +7,20 @@
class Provider(BaseProvider):
+ """Generates fake ISBNs.
+
+ See https://www.isbn-international.org/content/what-isbn for the
+ format of ISBNs.
+ See https://www.isbn-international.org/range_file_generation for the
+ list of rules pertaining to each prefix/registration grou... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/isbn/__init__.py |
Add docstrings that explain purpose and usage | from typing import List
from ..en_US import Provider as EnUsProvider
from ..la import Provider as LoremProvider
class Provider(LoremProvider):
english_word_list = EnUsProvider.word_list
def english_word(self) -> str:
return self.word(ext_word_list=self.english_word_list)
def english_words(self... | --- +++ @@ -5,32 +5,81 @@
class Provider(LoremProvider):
+ """Implement lorem provider for ``en_PH`` locale.
+
+ This localized provider generates pseudo-Latin text when using the standard
+ lorem provider methods, and the ``english_*`` methods are also provided for
+ generating text in American English... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/lorem/en_PH/__init__.py |
Create structured documentation for my script | import csv
import hashlib
import io
import json
import os
import re
import string
import tarfile
import uuid
import zipfile
from json import JSONEncoder
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Type, Union, overload
from faker.exceptions import UnsupportedFeature
from ..... | --- +++ @@ -28,9 +28,16 @@
class Provider(BaseProvider):
def boolean(self, chance_of_getting_true: int = 50) -> bool:
+ """Generate a random boolean value based on ``chance_of_getting_true``.
+
+ :sample: chance_of_getting_true=25
+ :sample: chance_of_getting_true=50
+ :sample: chance... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/misc/__init__.py |
Add docstrings to existing functions | from typing import List, Optional, Sequence, cast
from .. import BaseProvider
localized = True
# 'Latin' is the default locale
default_locale = "la"
class Provider(BaseProvider):
word_connector = " "
sentence_punctuation = "."
def get_words_list(
self,
part_of_speech: Optional[str] = ... | --- +++ @@ -9,6 +9,16 @@
class Provider(BaseProvider):
+ """Implement default lorem provider for Faker.
+
+ .. important::
+ The default locale of the lorem provider is ``la``. When using a locale
+ without a localized lorem provider, the ``la`` lorem provider will be
+ used, so generated wo... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/lorem/__init__.py |
Document functions with clear intent | from .. import ElementsType
from .. import Provider as PassportProvider
class Provider(PassportProvider):
electronic_passport_number_formats: ElementsType[str] = (
# standard passaporto elettronico (elettronic passport)
# Format: 2 letters, 7 digits (e.g., YA1234567), used from 2010 on
"?... | --- +++ @@ -3,6 +3,13 @@
class Provider(PassportProvider):
+ """Implement passport provider for ``it_IT``.
+
+ Sources:
+
+ - https://www.poliziadistato.it/articolo/10301
+ - https://www.poliziadistato.it/statics/32/note_tecniche.pdf
+ """
electronic_passport_number_formats: ElementsType[str] ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/passport/it_IT/__init__.py |
Add standardized docstrings across the file | import datetime
import re
from string import ascii_uppercase
from typing import Tuple
from faker.typing import SexLiteral
from .. import BaseProvider, ElementsType
localized = True
class Provider(BaseProvider):
passport_number_formats: ElementsType = ()
def passport_dob(self) -> datetime.date:
b... | --- +++ @@ -12,14 +12,20 @@
class Provider(BaseProvider):
+ """Implement default Passport provider for Faker."""
passport_number_formats: ElementsType = ()
def passport_dob(self) -> datetime.date:
+ """Generate a datetime date of birth."""
birthday = self.generator.date_of_birth()
... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/passport/__init__.py |
Add standardized docstrings across the file |
from collections import OrderedDict
from .. import Provider as PersonProvider
class Provider(PersonProvider):
# Name formats for Kenyan English
formats_female = (
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
... | --- +++ @@ -1,3 +1,13 @@+"""
+Data sources:
+- Forenames: https://forebears.io/kenya/forenames
+- Surnames: https://forebears.io/kenya/surnames
+
+Last updated: 2023 (based on latest available data from Forebears.io)
+
+Note: Name frequencies are based on statistical incidence in the Kenyan population
+and are represen... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/en_KE/__init__.py |
Write docstrings for utility functions |
from collections import Counter, OrderedDict
from .. import Provider as PersonProvider
class Provider(PersonProvider):
# As per https://nl.wikipedia.org/wiki/Familienaam#Belgi%C3%AB, from 1 Jun 2014 a child can get
# the family name of either parent, or both parents' family names separated by a space.
... | --- +++ @@ -1,3 +1,8 @@+"""faker.providers.person.fr_BE - 8-9 Jan 2023.
+
+Last names and male and female first names for locale 'fr_BE' (French-speaking Belgium).
+Source: Statbel (Directorate-general Statistics - Statistics Belgium), https://statbel.fgov.be/en/about-statbel, 2022.
+"""
from collections import Coun... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/fr_BE/__init__.py |
Document functions with clear intent | import random
from datetime import date, timedelta
from typing import Tuple
from faker.typing import SexLiteral
from .. import Provider as PassportProvider
class Provider(PassportProvider):
passport_number_formats = (
# NGP
"?########",
# Pre-NGP
"#########",
)
def pas... | --- +++ @@ -9,6 +9,13 @@
class Provider(PassportProvider):
+ """Implement passport provider for ``en_US`` locale.
+
+ Sources:
+
+ - https://travel.state.gov/content/travel/en/passports/passport-help/next-generation-passport.html
+ - https://www.vitalrecordsonline.com/glossary/passport-book-number
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/passport/en_US/__init__.py |
Add docstrings to meet PEP guidelines | from collections import OrderedDict
from operator import itemgetter
from typing import Tuple
from .. import Provider as PersonProvider
class Provider(PersonProvider):
# link: http://dic.nicovideo.jp/a/日本人の名前一覧
# link: http://www.meijiyasuda.co.jp/enjoy/ranking/
first_name_female_pairs = (
("明美", ... | --- +++ @@ -161,73 +161,139 @@ romanized_formats = romanized_formats_male + romanized_formats_female
def first_name_pair(self) -> Tuple[str, str, str]:
+ """
+ :example: ('明美', 'アケミ', 'Akemi')
+ """
return self.random_element(self.first_name_pairs)
def first_name_male_pai... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/ja_JP/__init__.py |
Add concise docstrings to each method | from .. import Provider as PersonProvider
def translate_to_bengali_digits(en_digit: str = "0") -> str:
english_to_bengali_digits_map = {
"0": "০",
"1": "১",
"2": "২",
"3": "৩",
"4": "৪",
"5": "৫",
"6": "৬",
"7": "৭",
"8": "৮",
"9": "৯... | --- +++ @@ -2,6 +2,10 @@
def translate_to_bengali_digits(en_digit: str = "0") -> str:
+ """
+ Translate any English string containing digits to corresponding Bengali digits.
+ :example: '9786' to '৯৭৮৬'
+ """
english_to_bengali_digits_map = {
"0": "০",
"1": "১",
@@ -21,6 +25,7 @@ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/bn_BD/__init__.py |
Generate missing documentation strings | from datetime import datetime
from typing import List, Optional, Sequence, Tuple, Union
from .. import Provider as PersonProvider
def checksum_identity_card_number(characters: Sequence[Union[str, int]]) -> int:
weights_for_check_digit = [7, 3, 1, 0, 7, 3, 1, 7, 3]
integer_characters = [
(ord(characte... | --- +++ @@ -5,6 +5,9 @@
def checksum_identity_card_number(characters: Sequence[Union[str, int]]) -> int:
+ """
+ Calculates and returns a control digit for given list of characters basing on Identity Card Number standards.
+ """
weights_for_check_digit = [7, 3, 1, 0, 7, 3, 1, 7, 3]
integer_charac... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/pl_PL/__init__.py |
Add verbose docstrings with examples |
from collections import Counter, OrderedDict
from .. import Provider as PersonProvider
class Provider(PersonProvider):
# As per https://nl.wikipedia.org/wiki/Familienaam#Belgi%C3%AB, from 1 Jun 2014 a child can get
# the family name of either parent, or both parents' family names separated by a space.
... | --- +++ @@ -1,3 +1,8 @@+"""faker.providers.person.nl_BE - 8-9 Jan 2023.
+
+Last names and male and female first names for locale 'nl_BE' (Dutch-speaking Belgium).
+Source: Statbel (Directorate-general Statistics - Statistics Belgium), https://statbel.fgov.be/en/about-statbel, 2022.
+"""
from collections import Count... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/nl_BE/__init__.py |
Replace inline comments with docstrings | from collections import OrderedDict
from typing import Dict, Optional
from faker.typing import SexLiteral
from .. import ElementsType
from .. import Provider as PersonProvider
def translit(text: str) -> str:
translit_dict: Dict[str, str] = {
"а": "a",
"б": "b",
"в": "v",
"г": "h"... | --- +++ @@ -1293,15 +1293,40 @@ )
def middle_name(self) -> str:
+ """
+ Generate random middle name.
+ :sample:
+ """
return self.random_element(self.middle_names)
def middle_name_male(self) -> str:
+ """
+ Generate random male middle name.
+ :... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/uk_UA/__init__.py |
Add docstrings to existing functions | from collections import OrderedDict
from itertools import zip_longest
from typing import Dict
from ..es import Provider as PersonProvider
class Provider(PersonProvider):
formats_male = OrderedDict(
[
("{{given_name_male}} {{last_name}} {{last_name}}", 0.55),
("{{first_name_male}} ... | --- +++ @@ -1055,6 +1055,7 @@
@property
def first_names(self): # type: ignore[override]
+ """Returns a list of weighted first names, male and female."""
if not hasattr(self, "_first_names"):
self._first_names = OrderedDict()
for a, b in zip_longest(self.first_names_... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/person/es_CL/__init__.py |
Add docstrings to improve collaboration | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = (
"BG#########",
"BG##########",
)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,6 +2,9 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Bulgarian VAT IDs
+ """
vat_id_formats = (
"BG#########",
@@ -9,5 +12,9 @@ )
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/bg_BG/__init__.py |
Add docstrings with type hints explained | from math import ceil
from typing import List, Tuple
from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats: Tuple[str, ...] = (
"CZ########",
"CZ#########",
"CZ##########",
)
national_id_months: List[str] = ["%.2d" % i for i in range(1, 13)] + ["%.2... | --- +++ @@ -14,9 +14,17 @@ national_id_months: List[str] = ["%.2d" % i for i in range(1, 13)] + ["%.2d" % i for i in range(51, 63)]
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :return: A random Czech VAT ID
+ """
return se... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/cs_CZ/__init__.py |
Generate documentation strings for clarity | from datetime import date
from string import ascii_uppercase
from typing import Optional
from faker.utils.checksums import luhn_checksum
from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("DE#########",)
def __letter_to_digit_string(self, letter: str) -> str:
d... | --- +++ @@ -8,6 +8,14 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the German VAT ID and the pension insurance number
+
+ Sources:
+
+ - http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ - https://de.wikipedia.org/wiki/Versicherungsnummer
+ """
vat_id_formats = (... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/de_DE/__init__.py |
Add return value explanations in docstrings | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("DK########",)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,9 +2,15 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Danish VAT IDs
+ """
vat_id_formats = ("DK########",)
def vat_id(self) -> str:
+ """
+ Returns a random generated Danish Tax ID
+ """
- return self.bothify(self.random_element... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/dk_DK/__init__.py |
Help me comply with documentation standards | from datetime import date
from typing import List, Optional
from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("ATU########",)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats))
def __get_check_digit(self, ssn_without_ch... | --- +++ @@ -5,10 +5,17 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Austrian VAT IDs
+ """
vat_id_formats = ("ATU########",)
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :return: a random Austrian VAT I... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/de_AT/__init__.py |
Expand my code with proper documentation strings | import random
from faker.utils.checksums import calculate_luhn
from .. import Provider as BaseProvider
def tin_checksum(tin: str) -> int:
tin_list = [int(i) for i in list(tin)]
return (
(
(tin_list[0] * 256)
+ (tin_list[1] * 128)
+ (tin_list[2] * 64)
... | --- +++ @@ -6,6 +6,11 @@
def tin_checksum(tin: str) -> int:
+ """
+ Calculates the checksum (last) digit of Greek TINs given the rest
+ :param tin: first 8 digits of a Greek TIN
+ :return: calculated checksum digit
+ """
tin_list = [int(i) for i in list(tin)]
return (
@@ -24,12 +29,20 @@ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/el_GR/__init__.py |
Write beginner-friendly docstrings | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = (
"LT#########",
"LT############",
)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,6 +2,9 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Lithuanian VAT IDs
+ """
vat_id_formats = (
"LT#########",
@@ -9,5 +12,9 @@ )
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/lt_LT/__init__.py |
Create docstrings for reusable components | import math
import string
import sys
import warnings
from decimal import Decimal
from enum import Enum
from typing import Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple, Type, TypeVar, Union, cast, no_type_check
from faker.typing import BasicNumber
from ...exceptions import BaseFakerException
from .. impo... | --- +++ @@ -61,6 +61,13 @@ self,
object_type: Optional[Type[Union[bool, str, float, int, tuple, set, list, Iterable, dict]]] = None,
) -> Optional[Union[bool, str, float, int, tuple, set, list, Iterable, dict]]:
+ """
+ Generates a random object passing the type desired.
+
+ :... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/python/__init__.py |
Add detailed docstrings explaining each function |
import unicodedata
from string import ascii_uppercase, digits
from .. import ElementsType
from .. import Provider as SsnProvider
ALPHABET = ascii_uppercase
ALPHANUMERICS = sorted(digits + ascii_uppercase)
ALPHANUMERICS_DICT = {char: index for index, char in enumerate(ALPHANUMERICS)}
MONTHS_LIST = ("A", "B", "C", "D... | --- +++ @@ -1,3 +1,4 @@+"""it_IT ssn provider (yields italian fiscal codes)"""
import unicodedata
@@ -8001,10 +8002,17 @@
def checksum(value: str) -> str:
+ """
+ Calculates the checksum char used for the 16th char.
+ Author: Vincenzo Palazzo
+ """
return chr(65 + sum(CHECKSUM_TABLE[index % 2]... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/it_IT/__init__.py |
Write docstrings for this repository | from functools import reduce
from math import fmod
from typing import Optional
from ....typing import SexLiteral
from .. import Provider as SsnProvider
def zfix(d: int) -> str:
return "0" + str(d) if d < 10 else str(d)
class Provider(SsnProvider):
def ssn(self, dob: Optional[str] = None, gender: Optional[S... | --- +++ @@ -12,6 +12,17 @@
class Provider(SsnProvider):
def ssn(self, dob: Optional[str] = None, gender: Optional[SexLiteral] = None) -> str:
+ """
+ Generates Hungarian SSN equivalent (személyazonosító szám or, colloquially, személyi szám)
+
+ :param dob: date of birth as a "YYMMDD" string ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/hu_HU/__init__.py |
Add docstrings that explain inputs and outputs |
import random
import string
from typing import Literal, Optional
from .. import Provider as BaseProvider
ALPHABET = string.ascii_uppercase
ALPHANUMERIC = string.digits + ALPHABET
VOWELS = "AEIOU"
CONSONANTS = [letter for letter in ALPHABET if letter not in VOWELS]
# https://es.wikipedia.org/wiki/Plantilla:Abreviac... | --- +++ @@ -1,3 +1,9 @@+"""
+SSN provider for es_MX.
+
+This module adds a provider for mexican SSN, along with Unique Population
+Registry Code (CURP) and Federal Taxpayer Registry ID (RFC).
+"""
import random
import string
@@ -96,6 +102,12 @@
def _reduce_digits(number: int) -> int:
+ """
+ Sum of digits... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/es_MX/__init__.py |
Expand my code with proper documentation strings | from typing import Tuple
from .. import Provider as BaseProvider
def calculate_checksum(ssn_without_checksum: int) -> int:
return 97 - (ssn_without_checksum % 97)
class Provider(BaseProvider):
vat_id_formats = (
"FR?? #########",
"FR## #########",
"FR?# #########",
"FR#? ##... | --- +++ @@ -8,6 +8,9 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the French VAT IDs
+ """
vat_id_formats = (
"FR?? #########",
@@ -123,6 +126,12 @@ )
def ssn(self) -> str:
+ """
+ Creates a French numéro de sécurité sociale
+ https://fr.wiki... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/fr_FR/__init__.py |
Write docstrings including parameters and return values | import operator
from collections import OrderedDict
from .. import Provider as BaseProvider
def nit_check_digit(nit: str) -> str:
reversed_nit = nit[::-1]
digits = (int(digit) for digit in reversed_nit)
multipliers = (3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71)
value = sum(map(operator... | --- +++ @@ -6,6 +6,15 @@
def nit_check_digit(nit: str) -> str:
+ """
+ Calculate the check digit of a NIT.
+
+ The check digit is calculated by multiplying the reversed digits of a NIT
+ by (3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71), respectively,
+ adding the results and applying MOD... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/es_CO/__init__.py |
Add docstrings explaining edge cases | import random
from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = (
"ES?########",
"ES########?",
"ES?#######?",
)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats))
def nie(self) -> str:
... | --- +++ @@ -4,6 +4,9 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Spanish VAT IDs and DOIs
+ """
vat_id_formats = (
"ES?########",
@@ -12,10 +15,22 @@ )
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/es_ES/__init__.py |
Create Google-style docstrings for my code | import datetime
import operator
from typing import List
from .. import Provider as SsnProvider
def checksum(digits: List[int]) -> int:
sum_mod11 = sum(map(operator.mul, digits, Provider.scale1)) % 11
if sum_mod11 < 10:
return sum_mod11
sum_mod11 = sum(map(operator.mul, digits, Provider.scale2)) ... | --- +++ @@ -7,6 +7,20 @@
def checksum(digits: List[int]) -> int:
+ """Calculate checksum of Estonian personal identity code.
+
+ Checksum is calculated with "Modulo 11" method using level I or II scale:
+ Level I scale: 1 2 3 4 5 6 7 8 9 1
+ Level II scale: 3 4 5 6 7 8 9 1 2 3
+
+ The digits of the p... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/et_EE/__init__.py |
Replace inline comments with docstrings | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("CY#########?",)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,9 +2,15 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Cypriot VAT IDs
+ """
vat_id_formats = ("CY#########?",)
def vat_id(self) -> str:
+ """
+ Returns a random generated Cypriot Tax ID
+ """
- return self.bothify(self.random_ele... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/el_CY/__init__.py |
Document functions with detailed explanations | from typing import List, Tuple
from faker.providers.sbn.rules import RegistrantRule
from .. import BaseProvider
from .rules import RULES
from .sbn import SBN, SBN9
class Provider(BaseProvider):
def _body(self) -> List[str]:
reg_pub_len: int = SBN.MAX_LENGTH - 1
# Generate a registrant/publica... | --- +++ @@ -8,8 +8,15 @@
class Provider(BaseProvider):
+ """Generates fake SBNs. These are the precursor to the ISBN and are
+ largely similar to ISBN-10.
+
+ See https://www.isbn-international.org/content/what-isbn for the
+ format of ISBNs. SBNs have no EAN prefix or Registration Group.
+ """
... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/sbn/__init__.py |
Add docstrings to meet PEP guidelines | from itertools import cycle
from .. import Provider as BaseProvider
def rut_check_digit(number: int) -> str:
sum = 0
for factor in cycle(range(2, 8)):
if number == 0:
break
sum += factor * (number % 10)
number //= 10
mod = -sum % 11
if mod == 11:
return "0... | --- +++ @@ -4,6 +4,10 @@
def rut_check_digit(number: int) -> str:
+ """
+ Calculate the last character of a RUT number
+ :return: RUT check digit
+ """
sum = 0
for factor in cycle(range(2, 8)):
@@ -21,6 +25,15 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Chilea... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/es_CL/__init__.py |
Can you add docstrings to this Python file? | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("LU########",)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,9 +2,16 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Luxembourgish VAT IDs
+ """
vat_id_formats = ("LU########",)
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :return: a random Luxembourgi... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/lb_LU/__init__.py |
Add docstrings for internal functions | from typing import List
from .. import Provider as SsnProvider
def checksum(digits: List[int]) -> int:
remainder = 10
for digit in digits:
remainder = (remainder + digit) % 10
if remainder == 0:
remainder = 10
remainder = (remainder * 2) % 11
control_digit = 11 - rema... | --- +++ @@ -4,6 +4,10 @@
def checksum(digits: List[int]) -> int:
+ """
+ Calculate and return control digit for given list of digits based on
+ ISO7064, MOD 11,10 standard.
+ """
remainder = 10
for digit in digits:
remainder = (remainder + digit) % 10
@@ -18,6 +22,15 @@
class Prov... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/hr_HR/__init__.py |
Include argument descriptions in docstrings | import datetime
from .. import Provider as SsnProvider
class Provider(SsnProvider):
def ssn(self, min_age: int = 0, max_age: int = 105, artificial: bool = False) -> str:
def _checksum(hetu):
checksum_characters = "0123456789ABCDEFHJKLMNPRSTUVWXY"
return checksum_characters[int(he... | --- +++ @@ -5,6 +5,22 @@
class Provider(SsnProvider):
def ssn(self, min_age: int = 0, max_age: int = 105, artificial: bool = False) -> str:
+ """
+ Returns 11 character Finnish personal identity code (Henkilötunnus,
+ HETU, Swedish: Personbeteckning). This function assigns random
+ ge... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/fi_FI/__init__.py |
Add structured docstrings to improve clarity | import itertools
from datetime import date
from decimal import Decimal
from typing import Dict, List, Optional, Tuple, Union
from ...typing import SexLiteral
from .. import BaseProvider
class Provider(BaseProvider):
def simple_profile(self, sex: Optional[SexLiteral] = None) -> Dict[str, Union[str, date, SexLit... | --- +++ @@ -9,8 +9,15 @@
class Provider(BaseProvider):
+ """
+ This provider is a collection of functions to generate personal profiles and identities.
+
+ """
def simple_profile(self, sex: Optional[SexLiteral] = None) -> Dict[str, Union[str, date, SexLiteral]]:
+ """
+ Generates a bas... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/profile/__init__.py |
Add docstrings that explain inputs and outputs | import datetime
from .. import Provider as SsnProvider
class Provider(SsnProvider):
def ssn(self, min_age: int = 0, max_age: int = 105) -> str:
def _checksum(ssn_without_checksum):
weights = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
weighted_sum = sum(int(digit) * weight for digit, weight ... | --- +++ @@ -5,6 +5,15 @@
class Provider(SsnProvider):
def ssn(self, min_age: int = 0, max_age: int = 105) -> str:
+ """
+ Returns 11 character Latvian personal identity code (Personas kods).
+ This function assigns random age to person.
+
+ Personal code consists of eleven characters ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/lv_LV/__init__.py |
Add professional docstrings to my codebase |
from typing import Any, Optional
class SBN:
MAX_LENGTH = 9
def __init__(
self,
registrant: Optional[str] = None,
publication: Optional[str] = None,
) -> None:
self.registrant = registrant
self.publication = publication
class SBN9(SBN):
def __init__(self, *ar... | --- +++ @@ -1,3 +1,7 @@+"""
+This module is responsible for generating the check digit and formatting
+SBN numbers.
+"""
from typing import Any, Optional
@@ -20,6 +24,12 @@ self.check_digit = self._check_digit()
def _check_digit(self) -> str:
+ """Calculate the check digit for SBN-9.
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/sbn/sbn.py |
Write proper docstrings for these functions | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = (
"IE#?#####?",
"IE#######?",
"IE#######??",
)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,6 +2,9 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Irish VAT IDs
+ """
vat_id_formats = (
"IE#?#####?",
@@ -10,5 +13,9 @@ )
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :retu... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/en_IE/__init__.py |
Document all public functions with docstrings | from typing import List
from .. import Provider as BaseProvider
class Provider(BaseProvider):
INVALID_SSN_TYPE = "INVALID_SSN"
SSN_TYPE = "SSN"
ITIN_TYPE = "ITIN"
EIN_TYPE = "EIN"
def itin(self) -> str:
area = self.random_int(min=900, max=999)
serial = self.random_int(min=0, max... | --- +++ @@ -10,6 +10,17 @@ EIN_TYPE = "EIN"
def itin(self) -> str:
+ """Generate a random United States Individual Taxpayer Identification Number (ITIN).
+
+ An United States Individual Taxpayer Identification Number
+ (ITIN) is a tax processing number issued by the Internal
+ Rev... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/en_US/__init__.py |
Generate descriptive docstrings automatically | import string
from datetime import datetime, timedelta
from .. import BaseProvider, ElementsType
_DT_ALMOST_MAX = datetime.max - timedelta(1.0)
class Provider(BaseProvider):
user_agents: ElementsType[str] = (
"chrome",
"firefox",
"internet_explorer",
"opera",
"safari",
... | --- +++ @@ -8,6 +8,7 @@
class Provider(BaseProvider):
+ """Implement default user agent provider for Faker."""
user_agents: ElementsType[str] = (
"chrome",
@@ -154,12 +155,15 @@ )
def mac_processor(self) -> str:
+ """Generate a MacOS processor token used in user agent strings.""... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/user_agent/__init__.py |
Write docstrings including parameters and return values | from __future__ import annotations
import copy
import functools
import re
from collections import OrderedDict
from random import Random
from typing import Any, Callable, Pattern, Sequence, TypeVar
from .config import DEFAULT_LOCALE
from .exceptions import UniquenessException
from .factory import Factory
from .genera... | --- +++ @@ -21,6 +21,7 @@
class Faker:
+ """Proxy class capable of supporting multiple locales"""
cache_pattern: Pattern = re.compile(r"^_cached_\w*_mapping$")
generator_attrs = [
@@ -104,6 +105,14 @@ return instance
def __getattribute__(self, attr: str) -> Any:
+ """
+ H... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/proxy.py |
Write documentation strings for class attributes | import datetime
import operator
from typing import List, Optional, Sequence
from ....typing import SexLiteral
from .. import Provider as SsnProvider
def checksum(digits: Sequence[int], scale: List[int]) -> int:
chk_nbr = 11 - (sum(map(operator.mul, digits, scale)) % 11)
if chk_nbr == 11:
return 0
... | --- +++ @@ -8,6 +8,18 @@
def checksum(digits: Sequence[int], scale: List[int]) -> int:
+ """
+ Calculate checksum of Norwegian personal identity code.
+
+ Checksum is calculated with "Module 11" method using a scale.
+ The digits of the personal code are multiplied by the corresponding
+ number in th... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/no_NO/__init__.py |
Write Python docstrings for this snippet | from datetime import datetime
from typing import List
from .. import Provider as SsnProvider
def checksum(digits: List[int]) -> int:
weights_for_check_digit = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7]
check_digit = 0
for i in range(0, 10):
check_digit += weights_for_check_digit[i] * digits[i]
check_di... | --- +++ @@ -5,6 +5,9 @@
def checksum(digits: List[int]) -> int:
+ """
+ Calculates and returns a control digit for given list of digits basing on PESEL standard.
+ """
weights_for_check_digit = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7]
check_digit = 0
@@ -17,6 +20,9 @@
def calculate_month(birth_date: ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/pl_PL/__init__.py |
Add docstrings to improve collaboration | from faker.utils import checksums
from .. import Provider as BaseProvider
class Provider(BaseProvider):
aadhaar_id_formats = ("%##########",)
def aadhaar_id(self) -> str:
aadhaar_digits = self.numerify(self.random_element(self.aadhaar_id_formats))
checksum = checksums.calculate_luhn(int(aa... | --- +++ @@ -4,14 +4,23 @@
class Provider(BaseProvider):
+ """
+ Faker provider for Indian Identifiers
+ """
aadhaar_id_formats = ("%##########",)
def aadhaar_id(self) -> str:
+ """
+ Aadhaar is a 12 digit person identifier generated for residents of
+ India.
+ Deta... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/en_IN/__init__.py |
Document my Python code with docstrings | from .. import Provider as SsnProvider
class Provider(SsnProvider):
def ssn(self) -> str:
# see http://nl.wikipedia.org/wiki/Burgerservicenummer (in Dutch)
def _checksum(digits):
factors = (9, 8, 7, 6, 5, 4, 3, 2, -1)
s = 0
for i in range(len(digits)):
... | --- +++ @@ -3,6 +3,13 @@
class Provider(SsnProvider):
def ssn(self) -> str:
+ """
+ Returns a 9 digits Dutch SSN called "burgerservicenummer (BSN)".
+
+ the Dutch "burgerservicenummer (BSN)" needs to pass the "11-proef",
+ which is a check digit approach; this function essentially rev... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/nl_NL/__init__.py |
Help me comply with documentation standards | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("MT########",)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,9 +2,16 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Maltese VAT IDs
+ """
vat_id_formats = ("MT########",)
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :return: A random Maltese VAT ID
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/mt_MT/__init__.py |
Add standardized docstrings across the file | from math import ceil
from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("SK##########",)
national_id_months = ["%.2d" % i for i in range(1, 13)] + ["%.2d" % i for i in range(51, 63)]
def vat_id(self) -> str:
return self.bothify(self.random_element(self.va... | --- +++ @@ -4,16 +4,27 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Slovakian VAT IDs
+ """
vat_id_formats = ("SK##########",)
national_id_months = ["%.2d" % i for i in range(1, 13)] + ["%.2d" % i for i in range(51, 63)]
def vat_id(self) -> str:
+ """
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/sk_SK/__init__.py |
Write docstrings for algorithm functions | import typer
app = typer.Typer()
@app.command(help="Create a new user with USERNAME.")
def create(username: str):
print(f"Creating user: {username}")
@app.command(help="Delete a user with USERNAME.")
def delete(username: str):
print(f"Deleting user: {username}")
if __name__ == "__main__":
app() | --- +++ @@ -5,13 +5,19 @@
@app.command(help="Create a new user with USERNAME.")
def create(username: str):
+ """
+ Some internal utility function to create.
+ """
print(f"Creating user: {username}")
@app.command(help="Delete a user with USERNAME.")
def delete(username: str):
+ """
+ Some in... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial002_py310.py |
Write reusable docstrings | from typing import Annotated
import typer
app = typer.Typer(rich_markup_mode="rich")
@app.command()
def create(
username: Annotated[str, typer.Argument(help="The username to create")],
lastname: Annotated[
str,
typer.Argument(
help="The last name of the new user", rich_help_panel... | --- +++ @@ -27,13 +27,19 @@ ),
] = None,
):
+ """
+ [green]Create[/green] a new user. :sparkles:
+ """
print(f"Creating user: {username}")
@app.command(rich_help_panel="Utils and Configs")
def config(configuration: str):
+ """
+ [blue]Configure[/blue] the system. :gear:
+ """
... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial007_an_py310.py |
Help me document legacy Python code | from typing import List
from .. import Provider as SsnProvider
def checksum(digits: List[int]) -> int:
s = 0
p = len(digits) + 1
for i in range(0, len(digits)):
s += digits[i] * p
p -= 1
reminder = s % 11
if reminder == 0 or reminder == 1:
return 0
else:
retur... | --- +++ @@ -4,6 +4,12 @@
def checksum(digits: List[int]) -> int:
+ """
+ Returns the checksum of CPF digits.
+ References to the algorithm:
+ https://pt.wikipedia.org/wiki/Cadastro_de_pessoas_f%C3%ADsicas#Algoritmo
+ https://metacpan.org/source/MAMAWE/Algorithm-CheckDigits-v1.3.0/lib/Algorithm/CheckD... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/pt_BR/__init__.py |
Document functions with clear intent | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("PT#########",)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,9 +2,16 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Portuguese VAT IDs
+ """
vat_id_formats = ("PT#########",)
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :return: A random Portuguese VA... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/pt_PT/__init__.py |
Expand my code with proper documentation strings | from .. import Provider as BaseProvider
class Provider(BaseProvider):
vat_id_formats = ("SI########",)
def vat_id(self) -> str:
return self.bothify(self.random_element(self.vat_id_formats)) | --- +++ @@ -2,9 +2,16 @@
class Provider(BaseProvider):
+ """
+ A Faker provider for the Slovenian VAT IDs
+ """
vat_id_formats = ("SI########",)
def vat_id(self) -> str:
+ """
+ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
+ :return: a random Slovenian VAT I... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/sl_SI/__init__.py |
Generate docstrings with examples | import random
from datetime import date, datetime
from typing import Optional
from ....typing import SexLiteral
from .. import Provider as SsnProvider
def select_gender(gender: SexLiteral) -> int:
gender = 0 if gender.lower() == "f" else 1
return random.choice(range(gender, 10, 2))
def calculate_day_count... | --- +++ @@ -8,16 +8,19 @@
def select_gender(gender: SexLiteral) -> int:
+ """Choose an even number for Female and odd number for Male."""
gender = 0 if gender.lower() == "f" else 1
return random.choice(range(gender, 10, 2))
def calculate_day_count(birthday: date) -> int:
+ """Calculate the day ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/uk_UA/__init__.py |
Provide clean and structured docstrings | from typing import Annotated
import typer
app = typer.Typer(help="Awesome CLI user manager.")
@app.command()
def create(username: str):
print(f"Creating user: {username}")
@app.command()
def delete(
username: str,
force: Annotated[
bool,
typer.Option(
prompt="Are you sure y... | --- +++ @@ -7,6 +7,9 @@
@app.command()
def create(username: str):
+ """
+ Create a new user with USERNAME.
+ """
print(f"Creating user: {username}")
@@ -21,6 +24,11 @@ ),
],
):
+ """
+ Delete a user with USERNAME.
+
+ If --force is not used, will ask for confirmation.
+ ""... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial001_an_py310.py |
Add well-formatted docstrings | from typing import Annotated
import typer
app = typer.Typer(rich_markup_mode="markdown")
@app.command()
def create(
username: Annotated[str, typer.Argument(help="The username to be **created**")],
):
print(f"Creating user: {username}")
@app.command(help="**Delete** a user with *USERNAME*.")
def delete(
... | --- +++ @@ -9,6 +9,17 @@ def create(
username: Annotated[str, typer.Argument(help="The username to be **created**")],
):
+ """
+ **Create** a new *shiny* user. :sparkles:
+
+ * Create a username
+
+ * Show that the username is created
+
+ ---
+
+ Learn more at the [Typer docs website](https://ty... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial005_an_py310.py |
Document this script properly | from typing import Annotated
import typer
app = typer.Typer(rich_markup_mode="rich")
@app.command()
def create(
username: Annotated[
str, typer.Argument(help="The username to be [green]created[/green]")
],
):
print(f"Creating user: {username}")
@app.command(help="[bold red]Delete[/bold red] a ... | --- +++ @@ -11,6 +11,11 @@ str, typer.Argument(help="The username to be [green]created[/green]")
],
):
+ """
+ [bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles:
+
+ This requires a [underline]username[/underline].
+ """
print(f"Creating user: {username}")
@... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial004_an_py310.py |
Annotate my code with docstrings | import datetime
import random
from typing import Tuple
from faker.utils.checksums import calculate_luhn
from .. import Provider as SsnProvider
class Provider(SsnProvider):
@staticmethod
def _org_to_vat(org_id: str) -> str:
org_id = org_id.replace("-", "")
if len(org_id) == 10:
o... | --- +++ @@ -23,6 +23,18 @@ long: bool = False,
dash: bool = True,
) -> str:
+ """
+ Returns a 10 or 12 (long=True) digit Swedish SSN, "Personnummer".
+
+ It consists of 10 digits in the form (CC)YYMMDD-SSSQ, where
+ YYMMDD is the date of birth, SSS is a serial number
+ ... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/sv_SE/__init__.py |
Help me write clear docstrings | import typer
app = typer.Typer(help="Awesome CLI user manager.")
@app.command()
def create(username: str):
print(f"Creating user: {username}")
@app.command()
def delete(
username: str,
force: bool = typer.Option(
...,
prompt="Are you sure you want to delete the user?",
help="For... | --- +++ @@ -5,6 +5,9 @@
@app.command()
def create(username: str):
+ """
+ Create a new user with USERNAME.
+ """
print(f"Creating user: {username}")
@@ -17,6 +20,11 @@ help="Force deletion without confirmation.",
),
):
+ """
+ Delete a user with USERNAME.
+
+ If --force is no... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial001_py310.py |
Include argument descriptions in docstrings | from .. import Provider as BaseProvider
def ssn_checksum(number: str) -> int:
weights = (2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9)
check = sum(w * int(n) for w, n in zip(weights, number)) % 11
return 1 if check == 10 else check
def vat_checksum(number: str) -> int:
weights = (7, 5, 3, 2, 1, 7, 5, 3, 2)
... | --- +++ @@ -2,12 +2,18 @@
def ssn_checksum(number: str) -> int:
+ """
+ Calculate the checksum for the romanian SSN (CNP).
+ """
weights = (2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9)
check = sum(w * int(n) for w, n in zip(weights, number)) % 11
return 1 if check == 10 else check
def vat_checks... | https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/ssn/ro_RO/__init__.py |
Please document this code using docstrings | import typer
app = typer.Typer(rich_markup_mode="rich")
@app.command()
def create(
username: str = typer.Argument(
..., help="The username to be [green]created[/green]"
),
):
print(f"Creating user: {username}")
@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic]... | --- +++ @@ -9,6 +9,11 @@ ..., help="The username to be [green]created[/green]"
),
):
+ """
+ [bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles:
+
+ This requires a [underline]username[/underline].
+ """
print(f"Creating user: {username}")
@@ -19,8 +24,11 @@ ... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial004_py310.py |
Add well-formatted docstrings | import typer
app = typer.Typer(rich_markup_mode="rich")
@app.command()
def create(username: str):
print(f"Creating user: {username}")
@app.command()
def delete(username: str):
print(f"Deleting user: {username}")
@app.command(rich_help_panel="Utils and Configs")
def config(configuration: str):
print(f... | --- +++ @@ -5,33 +5,51 @@
@app.command()
def create(username: str):
+ """
+ [green]Create[/green] a new user. :sparkles:
+ """
print(f"Creating user: {username}")
@app.command()
def delete(username: str):
+ """
+ [red]Delete[/red] a user. :x:
+ """
print(f"Deleting user: {username}"... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial006_py310.py |
Insert docstrings into my code | import typer
app = typer.Typer(rich_markup_mode="rich")
@app.command()
def create(
username: str = typer.Argument(..., help="The username to create"),
lastname: str = typer.Argument(
"", help="The last name of the new user", rich_help_panel="Secondary Arguments"
),
force: bool = typer.Option(... | --- +++ @@ -19,13 +19,19 @@ rich_help_panel="Additional Data",
),
):
+ """
+ [green]Create[/green] a new user. :sparkles:
+ """
print(f"Creating user: {username}")
@app.command(rich_help_panel="Utils and Configs")
def config(configuration: str):
+ """
+ [blue]Configure[/blue] the... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial007_py310.py |
Add concise docstrings to each method | import typer
app = typer.Typer(rich_markup_mode="markdown")
@app.command()
def create(username: str = typer.Argument(..., help="The username to be **created**")):
print(f"Creating user: {username}")
@app.command(help="**Delete** a user with *USERNAME*.")
def delete(
username: str = typer.Argument(..., help... | --- +++ @@ -5,6 +5,17 @@
@app.command()
def create(username: str = typer.Argument(..., help="The username to be **created**")):
+ """
+ **Create** a new *shiny* user. :sparkles:
+
+ * Create a username
+
+ * Show that the username is created
+
+ ---
+
+ Learn more at the [Typer docs website](https:... | https://raw.githubusercontent.com/fastapi/typer/HEAD/docs_src/commands/help/tutorial005_py310.py |
Document this code for team use | import inspect
import io
from collections.abc import Callable, Sequence
from typing import (
TYPE_CHECKING,
Any,
Optional,
TypeVar,
)
import click
import click.shell_completion
if TYPE_CHECKING: # pragma: no cover
from .core import TyperCommand, TyperGroup
from .main import Typer
NoneType =... | --- +++ @@ -24,36 +24,151 @@
class Context(click.Context):
+ """
+ The [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) has some additional data about the current execution of your program.
+ When declaring it in a [callback](https://typer.tiangolo.com/tutorial/options/callback-a... | https://raw.githubusercontent.com/fastapi/typer/HEAD/typer/models.py |
Add concise docstrings to each method | import logging
import os
import re
import shutil
import subprocess
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
import typer
from ruff.__main__ import find_ruff_bin
logging.basicConfig(level=logging.INFO)
mkdocs_name = "mkdocs.yml"
docs_path = Path("docs")
en_docs_path = Path... | --- +++ @@ -44,6 +44,9 @@
@app.command()
def generate_readme() -> None:
+ """
+ Generate README.md content from main index.md
+ """
typer.echo("Generating README")
readme_path = Path("README.md")
new_content = generate_readme_content()
@@ -52,6 +55,9 @@
@app.command()
def verify_readme() -... | https://raw.githubusercontent.com/fastapi/typer/HEAD/scripts/docs.py |
Generate consistent documentation across files | import importlib.util
import re
import sys
from pathlib import Path
from typing import Any
import click
import typer
import typer.core
from click import Command, Group, Option
from . import __version__
from .core import HAS_RICH, MARKUP_MODE_KEY
default_app_names = ("app", "cli", "main")
default_func_names = ("main"... | --- +++ @@ -172,6 +172,15 @@ callback=print_version,
),
) -> None:
+ """
+ Run Typer scripts with completion, without having to create a package.
+
+ You probably want to install completion for the typer command:
+
+ $ typer --install-completion
+
+ https://typer.tiangolo.com/
+ """
... | https://raw.githubusercontent.com/fastapi/typer/HEAD/typer/cli.py |
Write docstrings for this repository | #!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. 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/LI... | --- +++ @@ -13,6 +13,12 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+"""
+Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dat... | https://raw.githubusercontent.com/ymcui/Chinese-LLaMA-Alpaca/HEAD/scripts/training/run_clm_pt_with_peft.py |
Write reusable docstrings | import inspect
import os
import platform
import shutil
import subprocess
import sys
import traceback
from collections.abc import Callable, Sequence
from datetime import datetime
from enum import Enum
from functools import update_wrapper
from pathlib import Path
from traceback import FrameSummary, StackSummary
from type... | --- +++ @@ -115,6 +115,20 @@
class Typer:
+ """
+ `Typer` main class, the main entrypoint to use Typer.
+
+ Read more in the
+ [Typer docs for First Steps](https://typer.tiangolo.com/tutorial/typer-app/).
+
+ ## Example
+
+ ```python
+ import typer
+
+ app = typer.Typer()
+ ```
+ """
... | https://raw.githubusercontent.com/fastapi/typer/HEAD/typer/main.py |
Provide clean and structured docstrings | # Extracted and modified from https://github.com/ewels/rich-click
import inspect
import io
from collections import defaultdict
from collections.abc import Iterable
from gettext import gettext as _
from os import getenv
from typing import Any, Literal
import click
from rich import box
from rich.align import Align
from... | --- +++ @@ -104,6 +104,7 @@
# Rich regex highlighter
class OptionHighlighter(RegexHighlighter):
+ """Highlights our special options."""
highlights = [
r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",
@@ -162,6 +163,11 @@ def _make_rich_text(
*, text: str, style: str = "", markup_mode: MarkupModeStr... | https://raw.githubusercontent.com/fastapi/typer/HEAD/typer/rich_utils.py |
Document helper functions with docstrings | from collections.abc import Callable
from typing import TYPE_CHECKING, Annotated, Any, overload
import click
from annotated_doc import Doc
from .models import ArgumentInfo, OptionInfo
if TYPE_CHECKING: # pragma: no cover
import click.shell_completion
# Overload for Option created with custom type 'parser'
@ov... | --- +++ @@ -923,6 +923,26 @@ ),
] = None,
) -> Any:
+ """
+ A [CLI Option](https://typer.tiangolo.com/tutorial/options) is a parameter to your command line application that is called with a single or double dash, something like `--verbose` or `-v`.
+
+ Often, CLI Options are optional, meaning tha... | https://raw.githubusercontent.com/fastapi/typer/HEAD/typer/params.py |
Generate consistent documentation across files | import argparse
import json
import os
import gc
import torch
import peft
from transformers import LlamaTokenizer
from transformers.modeling_utils import dtype_byte_size
from huggingface_hub import snapshot_download
import re
parser = argparse.ArgumentParser()
parser.add_argument('--base_model', default=None, required=... | --- +++ @@ -1,3 +1,11 @@+"""
+Usage:
+python merge_llama_with_chinese_lora_low_mem.py \
+ --base_model path/to/llama/model \
+ --lora_model path/to/first/lora[,path/to/second/lora] \
+ --output_type [pth|huggingface] \
+ --output_dir path/to/output/dir
+"""
import argparse
import json
import os
@@ -117,... | https://raw.githubusercontent.com/ymcui/Chinese-LLaMA-Alpaca/HEAD/scripts/merge_llama_with_chinese_lora_low_mem.py |
Write docstrings for algorithm functions |
from js import console
from pyscript import document, Event # noqa: F401
from pyscript.ffi import create_proxy, is_none
# Utility functions for finding and wrapping DOM elements.
def _wrap_if_not_none(dom_element):
return Element.wrap_dom_element(dom_element) if not is_none(dom_element) else None
def _find_b... | --- +++ @@ -1,3 +1,205 @@+"""
+A lightweight Pythonic interface to the DOM and HTML elements that helps you
+interact with web pages, making it easy to find, create, manipulate, and
+compose HTML elements from Python.
+
+Highlights include:
+
+Use the `page` object to find elements on the current page:
+
+```python
+fr... | https://raw.githubusercontent.com/pyscript/pyscript/HEAD/core/src/stdlib/pyscript/web.py |
Can you add docstrings to this Python file? | #!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. 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/LI... | --- +++ @@ -13,6 +13,12 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+"""
+Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dat... | https://raw.githubusercontent.com/ymcui/Chinese-LLaMA-Alpaca/HEAD/scripts/training/run_clm_sft_with_peft.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.