code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _has_seed(self) -> bool:
"""Internal API to check if seed is set."""
return (self.seed is not None and self.seed is not MissingSeed) or (
_random.global_seed is not None and _random.global_seed is not MissingSeed
) | Internal API to check if seed is set. | _has_seed | python | lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py | MIT |
def __init__(
self,
locale: Locale = Locale.DEFAULT,
seed: Seed = MissingSeed,
*args: t.Any,
**kwargs: t.Any,
) -> None:
"""Initialize attributes for data providers.
:param locale: Current locale.
:param seed: Seed to all the random functions.
... | Initialize attributes for data providers.
:param locale: Current locale.
:param seed: Seed to all the random functions.
| __init__ | python | lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py | MIT |
def _setup_locale(self, locale: Locale = Locale.DEFAULT) -> None:
"""Set up locale after pre-check.
:param str locale: Locale
:raises UnsupportedLocale: When locale not supported.
:return: Nothing.
"""
locale_obj = validate_locale(locale)
self.locale = locale_ob... | Set up locale after pre-check.
:param str locale: Locale
:raises UnsupportedLocale: When locale not supported.
:return: Nothing.
| _setup_locale | python | lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py | MIT |
def _extract(self, keys: list[str], default: t.Any = None) -> t.Any:
"""Extracts nested values from JSON file by list of keys.
:param keys: List of keys (order extremely matters).
:param default: Default value.
:return: Data.
"""
if not keys:
raise ValueError... | Extracts nested values from JSON file by list of keys.
:param keys: List of keys (order extremely matters).
:param default: Default value.
:return: Data.
| _extract | python | lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py | MIT |
def _update_dict(self, initial: JSON, other: JSON) -> JSON:
"""Recursively updates a dictionary.
:param initial: Dict to update.
:param other: Dict to update from.
:return: Updated dict.
"""
for k, v in other.items():
if isinstance(v, dict):
i... | Recursively updates a dictionary.
:param initial: Dict to update.
:param other: Dict to update from.
:return: Updated dict.
| _update_dict | python | lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py | MIT |
def _load_dataset(self) -> None:
"""Loads the content from the JSON dataset.
:return: The content of the file.
:raises UnsupportedLocale: Raises if locale is unsupported.
"""
locale = self.locale
datafile = getattr(self.Meta, "datafile", "")
datadir = getattr(sel... | Loads the content from the JSON dataset.
:return: The content of the file.
:raises UnsupportedLocale: Raises if locale is unsupported.
| _load_dataset | python | lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py | MIT |
def update_dataset(self, data: JSON) -> None:
"""Updates dataset merging a given dict into default data.
This method may be useful when you need to override data
for a given key in JSON file.
"""
if not isinstance(data, dict):
raise TypeError("The data must be a dict... | Updates dataset merging a given dict into default data.
This method may be useful when you need to override data
for a given key in JSON file.
| update_dataset | python | lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py | MIT |
def __call__(
self,
items: t.Sequence[t.Any] | None,
length: int = 0,
unique: bool = False,
) -> t.Sequence[t.Any] | t.Any:
"""Generates a randomly chosen sequence or bare element from a sequence.
Provide elements randomly chosen from the elements in a sequence
... | Generates a randomly chosen sequence or bare element from a sequence.
Provide elements randomly chosen from the elements in a sequence
**items**, where when **length** is specified the random choices are
contained in a sequence of the same type of length **length**,
otherwise a single u... | __call__ | python | lk-geimfari/mimesis | mimesis/providers/choice.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/choice.py | MIT |
def isbn(
self, fmt: ISBNFormat | None = None, locale: Locale = Locale.DEFAULT
) -> str:
"""Generates ISBN for current locale.
To change ISBN format, pass parameter ``code`` with needed value of
the enum object :class:`~mimesis.enums.ISBNFormat`
:param fmt: ISBN format.
... | Generates ISBN for current locale.
To change ISBN format, pass parameter ``code`` with needed value of
the enum object :class:`~mimesis.enums.ISBNFormat`
:param fmt: ISBN format.
:param locale: Locale code.
:return: ISBN.
:raises NonEnumerableError: if code is not enum ... | isbn | python | lk-geimfari/mimesis | mimesis/providers/code.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/code.py | MIT |
def ean(self, fmt: EANFormat | None = None) -> str:
"""Generates EAN.
To change an EAN format, pass parameter ``code`` with needed value of
the enum object :class:`~mimesis.enums.EANFormat`.
:param fmt: Format of EAN.
:return: EAN.
:raises NonEnumerableError: if code is... | Generates EAN.
To change an EAN format, pass parameter ``code`` with needed value of
the enum object :class:`~mimesis.enums.EANFormat`.
:param fmt: Format of EAN.
:return: EAN.
:raises NonEnumerableError: if code is not enum EANFormat.
| ean | python | lk-geimfari/mimesis | mimesis/providers/code.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/code.py | MIT |
def hash(self, algorithm: Algorithm | None = None) -> str: # noqa: A003
"""Generates random hash.
To change hashing algorithm, pass parameter ``algorithm``
with needed value of the enum object :class:`~mimesis.enums.Algorithm`
:param algorithm: Enum object :class:`~mimesis.enums.Algor... | Generates random hash.
To change hashing algorithm, pass parameter ``algorithm``
with needed value of the enum object :class:`~mimesis.enums.Algorithm`
:param algorithm: Enum object :class:`~mimesis.enums.Algorithm`.
:return: Hash.
:raises NonEnumerableError: When algorithm is ... | hash | python | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/cryptographic.py | MIT |
def mnemonic_phrase(self) -> str:
"""Generates BIP-39 looking mnemonic phrase.
:return: Mnemonic phrase.
"""
length = self.random.choice([12, 24])
phrases = self.random.choices(WORDLIST, k=length)
return " ".join(phrases) | Generates BIP-39 looking mnemonic phrase.
:return: Mnemonic phrase.
| mnemonic_phrase | python | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/cryptographic.py | MIT |
def bulk_create_datetimes(
date_start: DateTime,
date_end: DateTime,
**kwargs: t.Any,
) -> list[DateTime]:
"""Bulk create datetime objects.
This method creates a list of datetime objects from
``date_start`` to ``date_end``.
You can use the following keyword ... | Bulk create datetime objects.
This method creates a list of datetime objects from
``date_start`` to ``date_end``.
You can use the following keyword arguments:
* ``days``
* ``hours``
* ``minutes``
* ``seconds``
* ``microseconds``
.. warning::
... | bulk_create_datetimes | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def week_date(self, start: int = 2017, end: int = _CURRENT_YEAR) -> str:
"""Generates week number with year.
:param start: Starting year.
:param end: Ending year.
:return: Week number.
"""
year = self.year(start, end)
week = self.random.randint(1, 52)
ret... | Generates week number with year.
:param start: Starting year.
:param end: Ending year.
:return: Week number.
| week_date | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def day_of_week(self, abbr: bool = False) -> str:
"""Generates a random day of the week.
:param abbr: Abbreviated day name.
:return: Day of the week.
"""
key = "abbr" if abbr else "name"
days: list[str] = self._extract(["day", key])
return self.random.choice(days... | Generates a random day of the week.
:param abbr: Abbreviated day name.
:return: Day of the week.
| day_of_week | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def month(self, abbr: bool = False) -> str:
"""Generates a random month of the year.
:param abbr: Abbreviated month name.
:return: Month name.
"""
key = "abbr" if abbr else "name"
months: list[str] = self._extract(["month", key])
return self.random.choice(months) | Generates a random month of the year.
:param abbr: Abbreviated month name.
:return: Month name.
| month | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def date(self, start: int = 2000, end: int = _CURRENT_YEAR) -> Date:
"""Generates a random date object.
:param start: Minimum value of year.
:param end: Maximum value of year.
:return: Formatted date.
"""
year = self.random.randint(start, end)
month = self.random... | Generates a random date object.
:param start: Minimum value of year.
:param end: Maximum value of year.
:return: Formatted date.
| date | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def formatted_date(self, fmt: str = "", **kwargs: t.Any) -> str:
"""Generates random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~.date()`
:return: Formatted date.
... | Generates random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~.date()`
:return: Formatted date.
| formatted_date | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def time(self) -> Time:
"""Generates a random time object.
:return: ``datetime.time`` object.
"""
random_time = time(
self.random.randint(0, 23),
self.random.randint(0, 59),
self.random.randint(0, 59),
self.random.randint(0, 999999),
... | Generates a random time object.
:return: ``datetime.time`` object.
| time | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def formatted_time(self, fmt: str = "") -> str:
"""Generates formatted time as string.
:param fmt: The format of time, if None then use standard
accepted in the current locale.
:return: String formatted time.
"""
time_obj = self.time()
if not fmt:
... | Generates formatted time as string.
:param fmt: The format of time, if None then use standard
accepted in the current locale.
:return: String formatted time.
| formatted_time | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def timezone(self, region: TimezoneRegion | None = None) -> str:
"""Generates a random timezone.
:param region: Timezone region.
:return: Timezone.
"""
region_name = self.validate_enum(region, TimezoneRegion)
return self.random.choice(
[tz for tz in TIMEZONES... | Generates a random timezone.
:param region: Timezone region.
:return: Timezone.
| timezone | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def datetime(
self,
start: int = _CURRENT_YEAR,
end: int = _CURRENT_YEAR,
timezone: str | None = None,
) -> DateTime:
"""Generates random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom tim... | Generates random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return: Datetime
| datetime | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def formatted_datetime(self, fmt: str = "", **kwargs: t.Any) -> str:
"""Generates datetime string in human-readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~.datetime()`
:return: Formatted datetime string.
... | Generates datetime string in human-readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~.datetime()`
:return: Formatted datetime string.
| formatted_datetime | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def timestamp(
self, fmt: TimestampFormat = TimestampFormat.POSIX, **kwargs: t.Any
) -> str | int:
"""Generates a random timestamp in given format.
Supported formats are:
- TimestampFormat.POSIX
- TimestampFormat.RFC_3339
- TimestampFormat.ISO_8601
Example:... | Generates a random timestamp in given format.
Supported formats are:
- TimestampFormat.POSIX
- TimestampFormat.RFC_3339
- TimestampFormat.ISO_8601
Example:
>>> from mimesis import Datetime
>>> from mimesis.enums import TimestampFormat
>>> dt = Datetime... | timestamp | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def duration(
self,
min_duration: int = 1,
max_duration: int = 10,
duration_unit: DurationUnit | None = DurationUnit.MINUTES,
) -> timedelta:
"""Generate a random duration.
The default duration unit is Duration.MINUTES.
When the duration unit is None, then r... | Generate a random duration.
The default duration unit is Duration.MINUTES.
When the duration unit is None, then random
duration from DurationUnit is chosen.
A timedelta object represents a duration, the difference
between two datetime or date instances.
:param min_dur... | duration | python | lk-geimfari/mimesis | mimesis/providers/date.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/date.py | MIT |
def calver(self) -> str:
"""Generates a random calendar versioning string.
:return: Calendar versioning string.
:Example:
2016.11.08
"""
year = self.random.randint(2016, datetime.now().year)
month = self.random.randint(1, 12)
day = self.random.randin... | Generates a random calendar versioning string.
:return: Calendar versioning string.
:Example:
2016.11.08
| calver | python | lk-geimfari/mimesis | mimesis/providers/development.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/development.py | MIT |
def extension(self, file_type: FileType | None = None) -> str:
"""Generates a random file extension.
:param file_type: Enum object FileType.
:return: Extension of the file.
:Example:
.py
"""
key = self.validate_enum(item=file_type, enum=FileType)
ext... | Generates a random file extension.
:param file_type: Enum object FileType.
:return: Extension of the file.
:Example:
.py
| extension | python | lk-geimfari/mimesis | mimesis/providers/file.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/file.py | MIT |
def mime_type(self, type_: MimeType | None = None) -> str:
"""Generates a random mime type.
:param type_: Enum object MimeType.
:return: Mime type.
"""
key = self.validate_enum(item=type_, enum=MimeType)
types = MIME_TYPES[key]
return self.random.choice(types) | Generates a random mime type.
:param type_: Enum object MimeType.
:return: Mime type.
| mime_type | python | lk-geimfari/mimesis | mimesis/providers/file.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/file.py | MIT |
def size(self, minimum: int = 1, maximum: int = 100) -> str:
"""Generates a random file size as string.
:param minimum: Maximum value.
:param maximum: Minimum value.
:return: Size of file.
:Example:
56 kB
"""
num = self.random.randint(minimum, maximu... | Generates a random file size as string.
:param minimum: Maximum value.
:param maximum: Minimum value.
:return: Size of file.
:Example:
56 kB
| size | python | lk-geimfari/mimesis | mimesis/providers/file.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/file.py | MIT |
def file_name(self, file_type: FileType | None = None) -> str:
"""Generates a random file name with an extension.
:param file_type: Enum object FileType
:return: File name.
:Example:
legislative.txt
"""
ext = self.extension(file_type)
name = self.ran... | Generates a random file name with an extension.
:param file_type: Enum object FileType
:return: File name.
:Example:
legislative.txt
| file_name | python | lk-geimfari/mimesis | mimesis/providers/file.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/file.py | MIT |
def company_type(self, abbr: bool = False) -> str:
"""Generates a random type of business entity.
:param abbr: Abbreviated company type.
:return: Types of business entity.
"""
key = "abbr" if abbr else "title"
company_types: list[str] = self._extract(["company", "type",... | Generates a random type of business entity.
:param abbr: Abbreviated company type.
:return: Types of business entity.
| company_type | python | lk-geimfari/mimesis | mimesis/providers/finance.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/finance.py | MIT |
def currency_iso_code(self, allow_random: bool = False) -> str:
"""Returns a currency code for current locale.
:param allow_random: Get a random ISO code.
:return: Currency code.
"""
code: str = self._extract(["currency-code"])
if allow_random:
return self.r... | Returns a currency code for current locale.
:param allow_random: Get a random ISO code.
:return: Currency code.
| currency_iso_code | python | lk-geimfari/mimesis | mimesis/providers/finance.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/finance.py | MIT |
def price(self, minimum: float = 500, maximum: float = 1500) -> float:
"""Generate a random price.
:param minimum: Minimum value of price.
:param maximum: Maximum value of price.
:return: Price.
"""
return self.random.uniform(
minimum,
maximum,
... | Generate a random price.
:param minimum: Minimum value of price.
:param maximum: Maximum value of price.
:return: Price.
| price | python | lk-geimfari/mimesis | mimesis/providers/finance.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/finance.py | MIT |
def price_in_btc(self, minimum: float = 0, maximum: float = 2) -> float:
"""Generates a random price in BTC.
:param minimum: Minimum value of price.
:param maximum: Maximum value of price.
:return: Price in BTC.
"""
return self.random.uniform(
minimum,
... | Generates a random price in BTC.
:param minimum: Minimum value of price.
:param maximum: Maximum value of price.
:return: Price in BTC.
| price_in_btc | python | lk-geimfari/mimesis | mimesis/providers/finance.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/finance.py | MIT |
def __getattr__(self, attrname: str) -> t.Any:
"""Get attribute without an underscore.
:param attrname: Attribute name.
:return: An attribute.
"""
attribute = object.__getattribute__(self, "_" + attrname)
if attribute and callable(attribute):
self.__dict__[at... | Get attribute without an underscore.
:param attrname: Attribute name.
:return: An attribute.
| __getattr__ | python | lk-geimfari/mimesis | mimesis/providers/generic.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/generic.py | MIT |
def __dir__(self) -> list[str]:
"""Available data providers.
:return: List of attributes.
"""
attributes = []
exclude = list(BaseProvider().__dict__.keys())
# Exclude locale explicitly because
# it is not a provider.
exclude.append("locale")
for ... | Available data providers.
:return: List of attributes.
| __dir__ | python | lk-geimfari/mimesis | mimesis/providers/generic.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/generic.py | MIT |
def reseed(self, seed: Seed = MissingSeed) -> None:
"""Reseed the internal random generator.
Overrides method `BaseProvider.reseed()`.
:param seed: Seed for random.
:return: None.
"""
# Make sure to reseed the random generator on Generic itself.
super().reseed(s... | Reseed the internal random generator.
Overrides method `BaseProvider.reseed()`.
:param seed: Seed for random.
:return: None.
| reseed | python | lk-geimfari/mimesis | mimesis/providers/generic.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/generic.py | MIT |
def add_provider(self, cls: t.Type[BaseProvider], **kwargs: t.Any) -> None:
"""Adds a custom provider to a Generic() object.
:param cls: Custom provider.
:param kwargs: Keyword arguments for provider.
:raises TypeError: if cls is Generic, if cls is not
class or is not a subc... | Adds a custom provider to a Generic() object.
:param cls: Custom provider.
:param kwargs: Keyword arguments for provider.
:raises TypeError: if cls is Generic, if cls is not
class or is not a subclass of BaseProvider.
:return: Absolutely none.
| add_provider | python | lk-geimfari/mimesis | mimesis/providers/generic.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/generic.py | MIT |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
"""Initialize attributes.
:param args: Arguments.
:param kwargs: Keyword arguments.
"""
super().__init__(*args, **kwargs)
self._file = File(
seed=self.seed,
random=self.random,
)
... | Initialize attributes.
:param args: Arguments.
:param kwargs: Keyword arguments.
| __init__ | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def dsn(self, dsn_type: DSNType | None = None, **kwargs: t.Any) -> str:
"""Generates a random DSN (Data Source Name).
:param dsn_type: DSN type.
:param kwargs: Additional keyword-arguments for hostname method.
"""
hostname = self.hostname(**kwargs)
scheme, port = self.va... | Generates a random DSN (Data Source Name).
:param dsn_type: DSN type.
:param kwargs: Additional keyword-arguments for hostname method.
| dsn | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def ip_v4_object(self) -> IPv4Address:
"""Generates a random :py:class:`ipaddress.IPv4Address` object.
If you only need special purpose IPv4 addresses,
use :meth:`special_ip_v4_object`.
:return: :py:class:`ipaddress.IPv4Address` object.
"""
return IPv4Address(
... | Generates a random :py:class:`ipaddress.IPv4Address` object.
If you only need special purpose IPv4 addresses,
use :meth:`special_ip_v4_object`.
:return: :py:class:`ipaddress.IPv4Address` object.
| ip_v4_object | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def ip_v4_with_port(self, port_range: PortRange = PortRange.ALL) -> str:
"""Generates a random IPv4 address as string.
:param port_range: PortRange enum object.
:return: IPv4 address as string.
:Example:
19.121.223.58:8000
"""
addr = self.ip_v4()
por... | Generates a random IPv4 address as string.
:param port_range: PortRange enum object.
:return: IPv4 address as string.
:Example:
19.121.223.58:8000
| ip_v4_with_port | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def ip_v6_object(self) -> IPv6Address:
"""Generates random :py:class:`ipaddress.IPv6Address` object.
:return: :py:class:`ipaddress.IPv6Address` object.
"""
return IPv6Address(
self.random.randint(
0,
self._MAX_IPV6,
),
) | Generates random :py:class:`ipaddress.IPv6Address` object.
:return: :py:class:`ipaddress.IPv6Address` object.
| ip_v6_object | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def asn(self) -> str:
"""Generates a random 4-byte ASN.
ASNs reserved for private use are not considered.
:return: ASN number as a string.
:Example:
AS123456
"""
ranges = (1, 4_199_999_999)
number = self.random.randint(*ranges)
return f"AS{n... | Generates a random 4-byte ASN.
ASNs reserved for private use are not considered.
:return: ASN number as a string.
:Example:
AS123456
| asn | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def mac_address(self) -> str:
"""Generates a random MAC address.
:return: Random MAC address.
:Example:
00:16:3e:25:e7:f1
"""
mac_hex = [
0x00,
0x16,
0x3E,
self.random.randint(0x00, 0x7F),
self.random.randi... | Generates a random MAC address.
:return: Random MAC address.
:Example:
00:16:3e:25:e7:f1
| mac_address | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def hostname(
self,
tld_type: TLDType | None = None,
subdomains: list[str] | None = None,
) -> str:
"""Generates a random hostname without a scheme.
:param tld_type: TLDType.
:param subdomains: List of subdomains (make sure they are valid).
:return: Hostname.... | Generates a random hostname without a scheme.
:param tld_type: TLDType.
:param subdomains: List of subdomains (make sure they are valid).
:return: Hostname.
| hostname | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def url(
self,
scheme: URLScheme | None = URLScheme.HTTPS,
port_range: PortRange | None = None,
tld_type: TLDType | None = None,
subdomains: list[str] | None = None,
) -> str:
"""Generates a random URL.
:param scheme: The scheme.
:param port_range: Po... | Generates a random URL.
:param scheme: The scheme.
:param port_range: PortRange enum object.
:param tld_type: TLDType.
:param subdomains: List of subdomains (make sure they are valid).
:return: URL.
| url | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def uri(
self,
scheme: URLScheme | None = URLScheme.HTTPS,
tld_type: TLDType | None = None,
subdomains: list[str] | None = None,
query_params_count: int | None = None,
) -> str:
"""Generates a random URI.
:param scheme: Scheme.
:param tld_type: TLDTyp... | Generates a random URI.
:param scheme: Scheme.
:param tld_type: TLDType.
:param subdomains: List of subdomains (make sure they are valid).
:param query_params_count: Query params.
:return: URI.
| uri | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def query_parameters(self, length: int | None = None) -> dict[str, str]:
"""Generates an arbitrary query parameters as a dict.
:param length: Length of query parameters dictionary (maximum is 32).
:return: Dict of query parameters.
"""
def pick_unique_words(quantity: int = 5) -... | Generates an arbitrary query parameters as a dict.
:param length: Length of query parameters dictionary (maximum is 32).
:return: Dict of query parameters.
| query_parameters | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def slug(self, parts_count: int | None = None) -> str:
"""Generates a random slug of given parts count.
:param parts_count: Slug's parts count.
:return: Slug.
"""
if not parts_count:
parts_count = self.random.randint(2, 12)
if parts_count > 12:
... | Generates a random slug of given parts count.
:param parts_count: Slug's parts count.
:return: Slug.
| slug | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def http_response_headers(self) -> dict[str, t.Any]:
"""Generates a random HTTP response headers.
The following headers are included:
- Allow
- Age
- Server
- Content-Type
- X-Request-ID
- Content-Language
- Content-Location
- Set-Cookie
... | Generates a random HTTP response headers.
The following headers are included:
- Allow
- Age
- Server
- Content-Type
- X-Request-ID
- Content-Language
- Content-Location
- Set-Cookie
- Upgrade-Insecure-Requests
- X-Content-Type-Opt... | http_response_headers | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def http_request_headers(self) -> dict[str, t.Any]:
"""Generates a random HTTP request headers.
The following headers are included:
- Referer
- Authorization
- Cookie
- User-Agent
- X-CSRF-Token
- Content-Type
- Content-Length
- Connectio... | Generates a random HTTP request headers.
The following headers are included:
- Referer
- Authorization
- Cookie
- User-Agent
- X-CSRF-Token
- Content-Type
- Content-Length
- Connection
- Cache-Control
- Accept
- Host
... | http_request_headers | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def special_ip_v4_object(self, purpose: IPv4Purpose | None = None) -> IPv4Address:
"""Generates a special purpose IPv4 address.
:param purpose: Enum object :class:`enums.IPv4Purpose`.
:return: IPv4 address.
:raises NonEnumerableError: if purpose not in :class:`enums.IPv4Purpose`.
... | Generates a special purpose IPv4 address.
:param purpose: Enum object :class:`enums.IPv4Purpose`.
:return: IPv4 address.
:raises NonEnumerableError: if purpose not in :class:`enums.IPv4Purpose`.
| special_ip_v4_object | python | lk-geimfari/mimesis | mimesis/providers/internet.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/internet.py | MIT |
def increment(self, accumulator: str | None = None) -> int:
"""Generates an incrementing number.
Each call of this method returns an incrementing number (with the step of +1).
If **accumulator** passed then increments number associated with it.
Example:
>>> self.increment(... | Generates an incrementing number.
Each call of this method returns an incrementing number (with the step of +1).
If **accumulator** passed then increments number associated with it.
Example:
>>> self.increment()
1
>>> self.increment(accumulator="a")
... | increment | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def float_number(
self, start: float = -1000.0, end: float = 1000.0, precision: int = 15
) -> float:
"""Generates a random float number in range [start, end].
:param start: Start range.
:param end: End range.
:param precision: Round a number to a given
precision... | Generates a random float number in range [start, end].
:param start: Start range.
:param end: End range.
:param precision: Round a number to a given
precision in decimal digits, default is 15.
:return: Float.
| float_number | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def floats(
self, start: float = 0, end: float = 1, n: int = 10, precision: int = 15
) -> list[float]:
"""Generates a list of random float numbers.
:param start: Start range.
:param end: End range.
:param n: Length of the list.
:param precision: Round a number to a g... | Generates a list of random float numbers.
:param start: Start range.
:param end: End range.
:param n: Length of the list.
:param precision: Round a number to a given
precision in decimal digits, default is 15.
:return: The list of floating-point numbers.
| floats | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def complex_number(
self,
start_real: float = 0.0,
end_real: float = 1.0,
start_imag: float = 0.0,
end_imag: float = 1.0,
precision_real: int = 15,
precision_imag: int = 15,
) -> complex:
"""Generates a random complex number.
:param start_real... | Generates a random complex number.
:param start_real: Start real range.
:param end_real: End real range.
:param start_imag: Start imaginary range.
:param end_imag: End imaginary range.
:param precision_real: Round a real part of
number to a given precision.
... | complex_number | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def complexes(
self,
start_real: float = 0,
end_real: float = 1,
start_imag: float = 0,
end_imag: float = 1,
precision_real: int = 15,
precision_imag: int = 15,
n: int = 10,
) -> list[complex]:
"""Generates a list of random complex numbers.
... | Generates a list of random complex numbers.
:param start_real: Start real range.
:param end_real: End real range.
:param start_imag: Start imaginary range.
:param end_imag: End imaginary range.
:param precision_real: Round a real part of
number to a given precision.... | complexes | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def decimals(
self, start: float = 0.0, end: float = 1000.0, n: int = 10
) -> list[Decimal]:
"""Generates a list of decimal numbers.
:param start: Start range.
:param end: End range.
:param n: Length of the list.
:return: A list of :py:class:`decimal.Decimal` objects... | Generates a list of decimal numbers.
:param start: Start range.
:param end: End range.
:param n: Length of the list.
:return: A list of :py:class:`decimal.Decimal` objects.
| decimals | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def matrix(
self,
m: int = 10,
n: int = 10,
num_type: NumType = NumType.FLOAT,
**kwargs: t.Any,
) -> Matrix:
"""Generates m x n matrix with a random numbers.
This method works with a variety of types,
so you can pass method-specific `**kwargs`.
... | Generates m x n matrix with a random numbers.
This method works with a variety of types,
so you can pass method-specific `**kwargs`.
:param m: Number of rows.
:param n: Number of columns.
:param num_type: NumType enum object.
:param kwargs: Other method-specific argumen... | matrix | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def user(self) -> str:
"""Generates a random user.
:return: Path to user.
:Example:
/home/oretha
"""
user = self.random.choice(USERNAMES)
user = user.capitalize() if "win" in self.platform else user.lower()
return str(self._pathlib_home / user) | Generates a random user.
:return: Path to user.
:Example:
/home/oretha
| user | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def users_folder(self) -> str:
"""Generates a random path to user's folders.
:return: Path.
:Example:
/home/taneka/Pictures
"""
user = self.user()
folder = self.random.choice(FOLDERS)
return str(self._pathlib_home / user / folder) | Generates a random path to user's folders.
:return: Path.
:Example:
/home/taneka/Pictures
| users_folder | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def dev_dir(self) -> str:
"""Generates a random path to development directory.
:return: Path.
:Example:
/home/sherrell/Development/Python
"""
user = self.user()
folder = self.random.choice(["Development", "Dev"])
stack = self.random.choice(PROGRAMMIN... | Generates a random path to development directory.
:return: Path.
:Example:
/home/sherrell/Development/Python
| dev_dir | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def project_dir(self) -> str:
"""Generates a random path to project directory.
:return: Path to project.
:Example:
/home/sherika/Development/Falcon/mercenary
"""
dev_dir = self.dev_dir()
project = self.random.choice(PROJECT_NAMES)
return str(self._pa... | Generates a random path to project directory.
:return: Path to project.
:Example:
/home/sherika/Development/Falcon/mercenary
| project_dir | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def bitcoin_address(self) -> str:
"""Generates a random bitcoin address.
Keep in mind that although it generates **valid-looking** addresses,
it does not mean that they are actually valid.
:return: Bitcoin address.
:Example:
3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
... | Generates a random bitcoin address.
Keep in mind that although it generates **valid-looking** addresses,
it does not mean that they are actually valid.
:return: Bitcoin address.
:Example:
3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
| bitcoin_address | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def ethereum_address(self) -> str:
"""Generates a random Ethereum address.
..note: The address will look like Ethereum address,
but keep in mind that it is not the valid address.
:return: Ethereum address.
:Example:
0xe8ece9e6ff7dba52d4c07d37418036a89af9698d
... | Generates a random Ethereum address.
..note: The address will look like Ethereum address,
but keep in mind that it is not the valid address.
:return: Ethereum address.
:Example:
0xe8ece9e6ff7dba52d4c07d37418036a89af9698d
| ethereum_address | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def credit_card_number(self, card_type: CardType | None = None) -> str:
"""Generates a random credit card number.
:param card_type: Issuing Network. Default is Visa.
:return: Credit card number.
:raises NotImplementedError: if card_type not supported.
:Example:
4455... | Generates a random credit card number.
:param card_type: Issuing Network. Default is Visa.
:return: Credit card number.
:raises NotImplementedError: if card_type not supported.
:Example:
4455 5299 1152 2450
| credit_card_number | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def credit_card_expiration_date(self, minimum: int = 16, maximum: int = 25) -> str:
"""Generates a random expiration date for credit card.
:param minimum: Date of issue.
:param maximum: Maximum of expiration_date.
:return: Expiration date of credit card.
:Example:
0... | Generates a random expiration date for credit card.
:param minimum: Date of issue.
:param maximum: Maximum of expiration_date.
:return: Expiration date of credit card.
:Example:
03/19.
| credit_card_expiration_date | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def credit_card_owner(
self,
gender: Gender | None = None,
) -> dict[str, str]:
"""Generates a random credit card owner.
:param gender: Gender of the card owner.
:type gender: Gender enum.
:return:
"""
owner = {
"credit_card": self.credit_... | Generates a random credit card owner.
:param gender: Gender of the card owner.
:type gender: Gender enum.
:return:
| credit_card_owner | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def birthdate(self, min_year: int = 1980, max_year: int = 2023) -> Date:
"""Generates a random birthdate as a :py:class:`datetime.date` object.
:param min_year: Maximum birth year.
:param max_year: Minimum birth year.
:return: Random date object.
"""
self._validate_birth... | Generates a random birthdate as a :py:class:`datetime.date` object.
:param min_year: Maximum birth year.
:param max_year: Minimum birth year.
:return: Random date object.
| birthdate | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def name(self, gender: Gender | None = None) -> str:
"""Generates a random name.
:param gender: Gender's enum object.
:return: Name.
:Example:
John.
"""
key = self.validate_enum(gender, Gender)
names: list[str] = self._extract(["names", key])
... | Generates a random name.
:param gender: Gender's enum object.
:return: Name.
:Example:
John.
| name | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def title(
self,
gender: Gender | None = None,
title_type: TitleType | None = None,
) -> str:
"""Generates a random title for name.
You can generate a random prefix or suffix
for name using this method.
:param gender: The gender.
:param title_type: T... | Generates a random title for name.
You can generate a random prefix or suffix
for name using this method.
:param gender: The gender.
:param title_type: TitleType enum object.
:return: The title.
:raises NonEnumerableError: if gender or title_type in incorrect format.
... | title | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def full_name(
self,
gender: Gender | None = None,
reverse: bool = False,
) -> str:
"""Generates a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolf... | Generates a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolfgang.
| full_name | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def username(
self, mask: str | None = None, drange: tuple[int, int] = (1800, 2100)
) -> str:
"""Generates a username by mask.
Masks allow you to generate a variety of usernames.
- **C** stands for capitalized username.
- **U** stands for uppercase username.
- **l**... | Generates a username by mask.
Masks allow you to generate a variety of usernames.
- **C** stands for capitalized username.
- **U** stands for uppercase username.
- **l** stands for lowercase username.
- **d** stands for digits in the username.
You can also use symbols ... | username | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def password(self, length: int = 8, hashed: bool = False) -> str:
"""Generates a password or hash of password.
:param length: Length of password.
:param hashed: SHA256 hash.
:return: Password or hash of password.
:Example:
k6dv2odff9#4h
"""
character... | Generates a password or hash of password.
:param length: Length of password.
:param hashed: SHA256 hash.
:return: Password or hash of password.
:Example:
k6dv2odff9#4h
| password | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def nationality(self, gender: Gender | None = None) -> str:
"""Generates a random nationality.
:param gender: Gender.
:return: Nationality.
:Example:
Russian
"""
nationalities: list[str] = self._extract(["nationality"])
# Separated by gender
... | Generates a random nationality.
:param gender: Gender.
:return: Nationality.
:Example:
Russian
| nationality | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def phone_number(self, mask: str = "", placeholder: str = "#") -> str:
"""Generates a random phone number.
:param mask: Mask for formatting number.
:param placeholder: A placeholder for a mask (default is #).
:return: Phone number.
:Example:
+7-(963)-409-11-22.
... | Generates a random phone number.
:param mask: Mask for formatting number.
:param placeholder: A placeholder for a mask (default is #).
:return: Phone number.
:Example:
+7-(963)-409-11-22.
| phone_number | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def measure_unit(
self,
name: MeasureUnit | None = None,
symbol: bool = False,
) -> str:
"""Returns unit name from the International System of Units.
:param name: Enum object UnitName.
:param symbol: Return only symbol
:return: Unit.
"""
resul... | Returns unit name from the International System of Units.
:param name: Enum object UnitName.
:param symbol: Return only symbol
:return: Unit.
| measure_unit | python | lk-geimfari/mimesis | mimesis/providers/science.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/science.py | MIT |
def metric_prefix(
self, sign: MetricPrefixSign | None = None, symbol: bool = False
) -> str:
"""Generates a random prefix for the International System of Units.
:param sign: Sing of prefix (positive/negative).
:param symbol: Return the symbol of the prefix.
:return: Metric ... | Generates a random prefix for the International System of Units.
:param sign: Sing of prefix (positive/negative).
:param symbol: Return the symbol of the prefix.
:return: Metric prefix for SI measure units.
:raises NonEnumerableError: if sign is not supported.
:Example:
... | metric_prefix | python | lk-geimfari/mimesis | mimesis/providers/science.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/science.py | MIT |
def alphabet(self, lower_case: bool = False) -> list[str]:
"""Returns an alphabet for current locale.
:param lower_case: Return alphabet in lower case.
:return: Alphabet.
"""
case = "uppercase" if not lower_case else "lowercase"
alpha: list[str] = self._extract(["alphab... | Returns an alphabet for current locale.
:param lower_case: Return alphabet in lower case.
:return: Alphabet.
| alphabet | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def text(self, quantity: int = 5) -> str:
"""Generates the text.
:param quantity: Quantity of sentences.
:return: Text.
"""
text = self._extract(["text"])
return " ".join(self.random.choices(text, k=quantity)) | Generates the text.
:param quantity: Quantity of sentences.
:return: Text.
| text | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def words(self, quantity: int = 5) -> list[str]:
"""Generates a list of random words.
:param quantity: Quantity of words. Default is 5.
:return: Word list.
:Example:
[science, network, god, octopus, love]
"""
words = self._extract(["words"])
return s... | Generates a list of random words.
:param quantity: Quantity of words. Default is 5.
:return: Word list.
:Example:
[science, network, god, octopus, love]
| words | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def _hex_to_rgb(color: str) -> tuple[int, ...]:
"""Converts hex color to RGB format.
:param color: Hex color.
:return: RGB tuple.
"""
color = color.lstrip("#") if color.startswith("#") else color
return tuple(int(color[i : i + 2], 16) for i in (0, 2, 4)) | Converts hex color to RGB format.
:param color: Hex color.
:return: RGB tuple.
| _hex_to_rgb | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def hex_color(self, safe: bool = False) -> str:
"""Generates a random HEX color.
:param safe: Get safe Flat UI hex color.
:return: Hex color code.
:Example:
#d8346b
"""
if safe:
return self.random.choice(SAFE_COLORS)
return f"#{self.rand... | Generates a random HEX color.
:param safe: Get safe Flat UI hex color.
:return: Hex color code.
:Example:
#d8346b
| hex_color | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def vehicle_registration_code(self, locale: Locale | None = None) -> str:
"""Returns vehicle registration code.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
"""
if locale:
return VRC_BY_LOCALES[locale.value]
retu... | Returns vehicle registration code.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
| vehicle_registration_code | python | lk-geimfari/mimesis | mimesis/providers/transport.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/transport.py | MIT |
def __init__(self, *, files: Iterable[Path]) -> None:
"""Find all files of all locales."""
self.files = files
self.before_total = 0
self.after_total = 0 | Find all files of all locales. | __init__ | python | lk-geimfari/mimesis | tasks/minifier.py | https://github.com/lk-geimfari/mimesis/blob/master/tasks/minifier.py | MIT |
def run(self) -> None:
"""Start json minimizer and exit when all json files were minimized."""
for file in self.files:
self.minify(file)
after = human_repr(self.after_total)
before = human_repr(self.before_total)
saved = human_repr(self.before_total - self.after_tota... | Start json minimizer and exit when all json files were minimized. | run | python | lk-geimfari/mimesis | tasks/minifier.py | https://github.com/lk-geimfari/mimesis/blob/master/tasks/minifier.py | MIT |
def validate_nip(nip):
"""Validate NIP.
:param nip: nip to validate
:return: True if nip is valid, False otherwise
"""
nip_digits = list(map(int, nip))
args = (6, 5, 7, 2, 3, 4, 5, 6, 7)
sum_v = sum(map(lambda x: x[0] * x[1], zip(args, nip_digits)))
checksum_digit = sum_v % 11
retur... | Validate NIP.
:param nip: nip to validate
:return: True if nip is valid, False otherwise
| validate_nip | python | lk-geimfari/mimesis | tests/test_builtins/test_poland_spec.py | https://github.com/lk-geimfari/mimesis/blob/master/tests/test_builtins/test_poland_spec.py | MIT |
def validate_pesel(pesel):
"""Validate PESEL.
:param pesel: pesel to validate
:return: True if pesel is valid, False otherwise
"""
pesel_digits = list(map(int, pesel))
args = (9, 7, 3, 1, 9, 7, 3, 1, 9, 7)
sum_v = sum(map(lambda x: x[0] * x[1], zip(args, pesel_digits)))
return pesel_dig... | Validate PESEL.
:param pesel: pesel to validate
:return: True if pesel is valid, False otherwise
| validate_pesel | python | lk-geimfari/mimesis | tests/test_builtins/test_poland_spec.py | https://github.com/lk-geimfari/mimesis/blob/master/tests/test_builtins/test_poland_spec.py | MIT |
def validate_regon(regon):
"""Validate REGON.
:param regon: regon to validate
:return: True if pesel is valid, False otherwise
"""
regon_digits = list(map(int, regon))
args = (8, 9, 2, 3, 4, 5, 6, 7)
sum_v = sum(map(lambda x: x[0] * x[1], zip(args, regon_digits)))
checksum_digit = sum_v... | Validate REGON.
:param regon: regon to validate
:return: True if pesel is valid, False otherwise
| validate_regon | python | lk-geimfari/mimesis | tests/test_builtins/test_poland_spec.py | https://github.com/lk-geimfari/mimesis/blob/master/tests/test_builtins/test_poland_spec.py | MIT |
def _chkpath(method, path):
"""Return an HTTP status for the given filesystem path."""
if method.lower() in ('put', 'delete'):
return 501, "Not Implemented" # TODO
elif method.lower() not in ('get', 'head'):
return 405, "Method Not Allowed"
elif os.path.isdir(pat... | Return an HTTP status for the given filesystem path. | _chkpath | python | renyijiu/douyin_downloader | local_file_adapter.py | https://github.com/renyijiu/douyin_downloader/blob/master/local_file_adapter.py | MIT |
def send(self, req, **kwargs): # pylint: disable=unused-argument
"""Return the file specified by the given request
@type req: C{PreparedRequest}
@todo: Should I bother filling `response.headers` and processing
If-Modified-Since and friends using `os.stat`?
"""
p... | Return the file specified by the given request
@type req: C{PreparedRequest}
@todo: Should I bother filling `response.headers` and processing
If-Modified-Since and friends using `os.stat`?
| send | python | renyijiu/douyin_downloader | local_file_adapter.py | https://github.com/renyijiu/douyin_downloader/blob/master/local_file_adapter.py | MIT |
def resize_image(origin_img, optimize_img, threshold):
"""
shrink image by size
:param origin_img:
:param optimize_img:
:param threshold:
:return:
"""
file_size = os.path.getsize(origin_img)
with Image.open(origin_img) as im:
if file_size > threshold:
width, heigh... |
shrink image by size
:param origin_img:
:param optimize_img:
:param threshold:
:return:
| resize_image | python | renyijiu/douyin_downloader | common/compression.py | https://github.com/renyijiu/douyin_downloader/blob/master/common/compression.py | MIT |
def crop_image(origin_img, optimize_img, x, y, width, height):
"""
crop imgae by size
:param origin image
:param optimize image
:param x , start point
:paran y , start point
:param width, the width of image
:param height, the height of image
"""
file_size = os.path.getsize(origi... |
crop imgae by size
:param origin image
:param optimize image
:param x , start point
:paran y , start point
:param width, the width of image
:param height, the height of image
| crop_image | python | renyijiu/douyin_downloader | common/compression.py | https://github.com/renyijiu/douyin_downloader/blob/master/common/compression.py | MIT |
def compute_reward(seq, actions, ignore_far_sim=True, temp_dist_thre=20, use_gpu=False):
"""
Compute diversity reward and representativeness reward
Args:
seq: sequence of features, shape (1, seq_len, dim)
actions: binary action sequence, shape (1, seq_len, 1)
ignore_far_sim (bool): ... |
Compute diversity reward and representativeness reward
Args:
seq: sequence of features, shape (1, seq_len, dim)
actions: binary action sequence, shape (1, seq_len, 1)
ignore_far_sim (bool): whether to ignore temporally distant similarity (default: True)
temp_dist_thre (int): th... | compute_reward | python | KaiyangZhou/pytorch-vsumm-reinforce | rewards.py | https://github.com/KaiyangZhou/pytorch-vsumm-reinforce/blob/master/rewards.py | MIT |
def generate_summary(ypred, cps, n_frames, nfps, positions, proportion=0.15, method='knapsack'):
"""Generate keyshot-based video summary i.e. a binary vector.
Args:
---------------------------------------------
- ypred: predicted importance scores.
- cps: change points, 2D matrix, each row contains ... | Generate keyshot-based video summary i.e. a binary vector.
Args:
---------------------------------------------
- ypred: predicted importance scores.
- cps: change points, 2D matrix, each row contains a segment.
- n_frames: original number of frames.
- nfps: number of frames per segment.
- po... | generate_summary | python | KaiyangZhou/pytorch-vsumm-reinforce | vsum_tools.py | https://github.com/KaiyangZhou/pytorch-vsumm-reinforce/blob/master/vsum_tools.py | MIT |
def evaluate_summary(machine_summary, user_summary, eval_metric='avg'):
"""Compare machine summary with user summary (keyshot-based).
Args:
--------------------------------
machine_summary and user_summary should be binary vectors of ndarray type.
eval_metric = {'avg', 'max'}
'avg' averages resu... | Compare machine summary with user summary (keyshot-based).
Args:
--------------------------------
machine_summary and user_summary should be binary vectors of ndarray type.
eval_metric = {'avg', 'max'}
'avg' averages results of comparing multiple human summaries.
'max' takes the maximum (best) o... | evaluate_summary | python | KaiyangZhou/pytorch-vsumm-reinforce | vsum_tools.py | https://github.com/KaiyangZhou/pytorch-vsumm-reinforce/blob/master/vsum_tools.py | MIT |
def check_brat_annotation_and_text_compatibility(brat_folder):
'''
Check if brat annotation and text files are compatible.
'''
dataset_type = os.path.basename(brat_folder)
print("Checking the validity of BRAT-formatted {0} set... ".format(dataset_type), end='')
text_filepaths = sorted(glob.glob... |
Check if brat annotation and text files are compatible.
| check_brat_annotation_and_text_compatibility | python | Franck-Dernoncourt/NeuroNER | neuroner/brat_to_conll.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/brat_to_conll.py | MIT |
def brat_to_conll(input_folder, output_filepath, tokenizer, language):
'''
Assumes '.txt' and '.ann' files are in the input_folder.
Checks for the compatibility between .txt and .ann at the same time.
'''
if tokenizer == 'spacy':
spacy_nlp = spacy.load(language)
elif tokenizer == 'stanfo... |
Assumes '.txt' and '.ann' files are in the input_folder.
Checks for the compatibility between .txt and .ann at the same time.
| brat_to_conll | python | Franck-Dernoncourt/NeuroNER | neuroner/brat_to_conll.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/brat_to_conll.py | MIT |
def generate_reference_text_file_for_conll(conll_input_filepath, conll_output_filepath, text_folder):
'''
generates reference text files and adds the corresponding filename and token offsets to conll file.
conll_input_filepath: path to a conll-formatted file without filename and token offsets
text_... |
generates reference text files and adds the corresponding filename and token offsets to conll file.
conll_input_filepath: path to a conll-formatted file without filename and token offsets
text_folder: folder to write the reference text file to
| generate_reference_text_file_for_conll | python | Franck-Dernoncourt/NeuroNER | neuroner/conll_to_brat.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/conll_to_brat.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.