repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
JarryShaw/PyPCAPKit
src/protocols/internet/hopopt.py
HOPOPT._read_opt_ip_dff
def _read_opt_ip_dff(self, code, *, desc): """Read HOPOPT IP_DFF option. Structure of HOPOPT IP_DFF option [RFC 6971]: 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-...
python
def _read_opt_ip_dff(self, code, *, desc): """Read HOPOPT IP_DFF option. Structure of HOPOPT IP_DFF option [RFC 6971]: 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-...
Read HOPOPT IP_DFF option. Structure of HOPOPT IP_DFF option [RFC 6971]: 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hopopt.py#L1016-L1061
JarryShaw/PyPCAPKit
src/const/ipx/socket.py
Socket.get
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Socket(key) if key not in Socket._member_map_: extend_enum(Socket, key, default) return Socket[key]
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Socket(key) if key not in Socket._member_map_: extend_enum(Socket, key, default) return Socket[key]
Backport support for original codes.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipx/socket.py#L28-L34
JarryShaw/PyPCAPKit
src/const/ipx/socket.py
Socket._missing_
def _missing_(cls, value): """Lookup function used when value is not found.""" if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) if 0x0001 <= value <= 0x0BB8: extend_enum(cls, 'Registered by Xer...
python
def _missing_(cls, value): """Lookup function used when value is not found.""" if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) if 0x0001 <= value <= 0x0BB8: extend_enum(cls, 'Registered by Xer...
Lookup function used when value is not found.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipx/socket.py#L37-L56
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_opts.py
IPv6_Opts.read_ipv6_opts
def read_ipv6_opts(self, length, extension): """Read Destination Options for IPv6. Structure of IPv6-Opts header [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | | +-+-+-+-+-...
python
def read_ipv6_opts(self, length, extension): """Read Destination Options for IPv6. Structure of IPv6-Opts header [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | | +-+-+-+-+-...
Read Destination Options for IPv6. Structure of IPv6-Opts header [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + ...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L152-L194
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_opts.py
IPv6_Opts._read_opt_type
def _read_opt_type(self, kind): """Read option type field. Positional arguments: * kind -- int, option kind value Returns: * dict -- extracted IPv6_Opts option Structure of option type field [RFC 791]: Octets Bits Name ...
python
def _read_opt_type(self, kind): """Read option type field. Positional arguments: * kind -- int, option kind value Returns: * dict -- extracted IPv6_Opts option Structure of option type field [RFC 791]: Octets Bits Name ...
Read option type field. Positional arguments: * kind -- int, option kind value Returns: * dict -- extracted IPv6_Opts option Structure of option type field [RFC 791]: Octets Bits Name Descriptions 0 ...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L212-L235
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_opts.py
IPv6_Opts._read_ipv6_opts_options
def _read_ipv6_opts_options(self, length): """Read IPv6_Opts options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted IPv6_Opts options """ counter = 0 # length of read options optkind = list() # ...
python
def _read_ipv6_opts_options(self, length): """Read IPv6_Opts options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted IPv6_Opts options """ counter = 0 # length of read options optkind = list() # ...
Read IPv6_Opts options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted IPv6_Opts options
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L237-L277
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_opts.py
IPv6_Opts._read_opt_none
def _read_opt_none(self, code, *, desc): """Read IPv6_Opts unassigned options. Structure of IPv6_Opts unassigned options [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - | Option Type | Opt Data Len | Option Data +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- -...
python
def _read_opt_none(self, code, *, desc): """Read IPv6_Opts unassigned options. Structure of IPv6_Opts unassigned options [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - | Option Type | Opt Data Len | Option Data +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- -...
Read IPv6_Opts unassigned options. Structure of IPv6_Opts unassigned options [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - | Option Type | Opt Data Len | Option Data +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - Octets Bits ...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L279-L307
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_opts.py
IPv6_Opts._read_opt_mpl
def _read_opt_mpl(self, code, *, desc): """Read IPv6_Opts MPL option. Structure of IPv6_Opts MPL option [RFC 7731]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
python
def _read_opt_mpl(self, code, *, desc): """Read IPv6_Opts MPL option. Structure of IPv6_Opts MPL option [RFC 7731]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
Read IPv6_Opts MPL option. Structure of IPv6_Opts MPL option [RFC 7731]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L797-L869
JarryShaw/PyPCAPKit
src/const/ftp/return_code.py
ReturnCode.get
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ReturnCode(key) if key not in ReturnCode._member_map_: extend_enum(ReturnCode, key, default) return ReturnCode[key]
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ReturnCode(key) if key not in ReturnCode._member_map_: extend_enum(ReturnCode, key, default) return ReturnCode[key]
Backport support for original codes.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ftp/return_code.py#L80-L86
JarryShaw/PyPCAPKit
src/const/ftp/return_code.py
ReturnCode._missing_
def _missing_(cls, value): """Lookup function used when value is not found.""" if not (isinstance(value, int) and 100 <= value <= 659): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) code = str(value) kind = KIND.get(code[0], 'Reserved') info = INFO....
python
def _missing_(cls, value): """Lookup function used when value is not found.""" if not (isinstance(value, int) and 100 <= value <= 659): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) code = str(value) kind = KIND.get(code[0], 'Reserved') info = INFO....
Lookup function used when value is not found.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ftp/return_code.py#L89-L97
JarryShaw/PyPCAPKit
src/const/hip/cipher.py
Cipher.get
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Cipher(key) if key not in Cipher._member_map_: extend_enum(Cipher, key, default) return Cipher[key]
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Cipher(key) if key not in Cipher._member_map_: extend_enum(Cipher, key, default) return Cipher[key]
Backport support for original codes.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/cipher.py#L19-L25
JarryShaw/PyPCAPKit
src/const/mh/packet.py
Packet.get
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Packet(key) if key not in Packet._member_map_: extend_enum(Packet, key, default) return Packet[key]
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Packet(key) if key not in Packet._member_map_: extend_enum(Packet, key, default) return Packet[key]
Backport support for original codes.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/mh/packet.py#L38-L44
JarryShaw/PyPCAPKit
src/const/ipv6/option.py
Option.get
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Option(key) if key not in Option._member_map_: extend_enum(Option, key, default) return Option[key]
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Option(key) if key not in Option._member_map_: extend_enum(Option, key, default) return Option[key]
Backport support for original codes.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv6/option.py#L39-L45
JarryShaw/PyPCAPKit
src/const/ipv6/extension_header.py
ExtensionHeader.get
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ExtensionHeader(key) if key not in ExtensionHeader._member_map_: extend_enum(ExtensionHeader, key, default) return ExtensionHeader[key]
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ExtensionHeader(key) if key not in ExtensionHeader._member_map_: extend_enum(ExtensionHeader, key, default) return ExtensionHeader[key]
Backport support for original codes.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv6/extension_header.py#L25-L31
JarryShaw/PyPCAPKit
src/const/ipv4/option_class.py
OptionClass.get
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return OptionClass(key) if key not in OptionClass._member_map_: extend_enum(OptionClass, key, default) return OptionClass[key]
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return OptionClass(key) if key not in OptionClass._member_map_: extend_enum(OptionClass, key, default) return OptionClass[key]
Backport support for original codes.
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/option_class.py#L18-L24
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_route.py
IPv6_Route.read_ipv6_route
def read_ipv6_route(self, length, extension): """Read Routing Header for IPv6. Structure of IPv6-Route header [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | +-+...
python
def read_ipv6_route(self, length, extension): """Read Routing Header for IPv6. Structure of IPv6-Route header [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | +-+...
Read Routing Header for IPv6. Structure of IPv6-Route header [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L102-L151
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_route.py
IPv6_Route._read_data_type_none
def _read_data_type_none(self, length): """Read IPv6-Route unknown type data. Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | ...
python
def _read_data_type_none(self, length): """Read IPv6-Route unknown type data. Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | ...
Read IPv6-Route unknown type data. Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L169-L197
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_route.py
IPv6_Route._read_data_type_src
def _read_data_type_src(self, length): """Read IPv6-Route Source Route data. Structure of IPv6-Route Source Route data [RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type=0| Segments Left | +-+-...
python
def _read_data_type_src(self, length): """Read IPv6-Route Source Route data. Structure of IPv6-Route Source Route data [RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type=0| Segments Left | +-+-...
Read IPv6-Route Source Route data. Structure of IPv6-Route Source Route data [RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type=0| Segments Left | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L199-L256
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_route.py
IPv6_Route._read_data_type_2
def _read_data_type_2(self, length): """Read IPv6-Route Type 2 data. Structure of IPv6-Route Type 2 data [RFC 6275]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1| +-+-+-+-+-+-+-+-+-...
python
def _read_data_type_2(self, length): """Read IPv6-Route Type 2 data. Structure of IPv6-Route Type 2 data [RFC 6275]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1| +-+-+-+-+-+-+-+-+-...
Read IPv6-Route Type 2 data. Structure of IPv6-Route Type 2 data [RFC 6275]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1| +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L258-L295
JarryShaw/PyPCAPKit
src/protocols/internet/ipv6_route.py
IPv6_Route._read_data_type_rpl
def _read_data_type_rpl(self, length): """Read IPv6-Route RPL Source data. Structure of IPv6-Route RPL Source data [RFC 6554]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-...
python
def _read_data_type_rpl(self, length): """Read IPv6-Route RPL Source data. Structure of IPv6-Route RPL Source data [RFC 6554]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-...
Read IPv6-Route RPL Source data. Structure of IPv6-Route RPL Source data [RFC 6554]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L297-L352
JarryShaw/PyPCAPKit
src/protocols/application/httpv1.py
HTTPv1.read_http
def read_http(self, length): """Read Hypertext Transfer Protocol (HTTP/1.*). Structure of HTTP/1.* packet [RFC 7230]: HTTP-message :==: start-line *( header-field CRLF ) CRLF [ ...
python
def read_http(self, length): """Read Hypertext Transfer Protocol (HTTP/1.*). Structure of HTTP/1.* packet [RFC 7230]: HTTP-message :==: start-line *( header-field CRLF ) CRLF [ ...
Read Hypertext Transfer Protocol (HTTP/1.*). Structure of HTTP/1.* packet [RFC 7230]: HTTP-message :==: start-line *( header-field CRLF ) CRLF [ message-body ]
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/application/httpv1.py#L76-L110
JarryShaw/PyPCAPKit
src/protocols/application/httpv1.py
HTTPv1._read_http_header
def _read_http_header(self, header): """Read HTTP/1.* header. Structure of HTTP/1.* header [RFC 7230]: start-line :==: request-line / status-line request-line :==: method SP request-target SP HTTP-version CRLF status-line :==: HTTP-version SP sta...
python
def _read_http_header(self, header): """Read HTTP/1.* header. Structure of HTTP/1.* header [RFC 7230]: start-line :==: request-line / status-line request-line :==: method SP request-target SP HTTP-version CRLF status-line :==: HTTP-version SP sta...
Read HTTP/1.* header. Structure of HTTP/1.* header [RFC 7230]: start-line :==: request-line / status-line request-line :==: method SP request-target SP HTTP-version CRLF status-line :==: HTTP-version SP status-code SP reason-phrase CRLF heade...
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/application/httpv1.py#L127-L184
Bonsanto/polygon-geohasher
polygon_geohasher/polygon_geohasher.py
geohash_to_polygon
def geohash_to_polygon(geo): """ :param geo: String that represents the geohash. :return: Returns a Shapely's Polygon instance that represents the geohash. """ lat_centroid, lng_centroid, lat_offset, lng_offset = geohash.decode_exactly(geo) corner_1 = (lat_centroid - lat_offset, lng_centroid - ...
python
def geohash_to_polygon(geo): """ :param geo: String that represents the geohash. :return: Returns a Shapely's Polygon instance that represents the geohash. """ lat_centroid, lng_centroid, lat_offset, lng_offset = geohash.decode_exactly(geo) corner_1 = (lat_centroid - lat_offset, lng_centroid - ...
:param geo: String that represents the geohash. :return: Returns a Shapely's Polygon instance that represents the geohash.
https://github.com/Bonsanto/polygon-geohasher/blob/63f27f41ea3e9d8fda7872d86217719286037c11/polygon_geohasher/polygon_geohasher.py#L8-L20
Bonsanto/polygon-geohasher
polygon_geohasher/polygon_geohasher.py
polygon_to_geohashes
def polygon_to_geohashes(polygon, precision, inner=True): """ :param polygon: shapely polygon. :param precision: int. Geohashes' precision that form resulting polygon. :param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored. :return: set. Set ...
python
def polygon_to_geohashes(polygon, precision, inner=True): """ :param polygon: shapely polygon. :param precision: int. Geohashes' precision that form resulting polygon. :param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored. :return: set. Set ...
:param polygon: shapely polygon. :param precision: int. Geohashes' precision that form resulting polygon. :param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored. :return: set. Set of geohashes that form the polygon.
https://github.com/Bonsanto/polygon-geohasher/blob/63f27f41ea3e9d8fda7872d86217719286037c11/polygon_geohasher/polygon_geohasher.py#L23-L62
desbma/r128gain
r128gain/opusgain.py
parse_oggopus_output_gain
def parse_oggopus_output_gain(file): """ Parse an OggOpus file headers, read and return its output gain, and set file seek position to start of Opus header. """ # # Ogg header # # check fields of Ogg page header chunk = file.read(OGG_FIRST_PAGE_HEADER.size) first_ogg_page = bytearray() first_ogg_page.e...
python
def parse_oggopus_output_gain(file): """ Parse an OggOpus file headers, read and return its output gain, and set file seek position to start of Opus header. """ # # Ogg header # # check fields of Ogg page header chunk = file.read(OGG_FIRST_PAGE_HEADER.size) first_ogg_page = bytearray() first_ogg_page.e...
Parse an OggOpus file headers, read and return its output gain, and set file seek position to start of Opus header.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L28-L99
desbma/r128gain
r128gain/opusgain.py
write_oggopus_output_gain
def write_oggopus_output_gain(file, new_output_gain): """ Write output gain Opus header for a file. file must be an object successfully used by parse_oggopus_output_gain. """ opus_header_pos = file.tell() # write Opus header with new gain file.seek(opus_header_pos + OGG_OPUS_ID_HEADER_GAIN_OFFSET) file....
python
def write_oggopus_output_gain(file, new_output_gain): """ Write output gain Opus header for a file. file must be an object successfully used by parse_oggopus_output_gain. """ opus_header_pos = file.tell() # write Opus header with new gain file.seek(opus_header_pos + OGG_OPUS_ID_HEADER_GAIN_OFFSET) file....
Write output gain Opus header for a file. file must be an object successfully used by parse_oggopus_output_gain.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L102-L120
desbma/r128gain
r128gain/opusgain.py
_compute_ogg_page_crc
def _compute_ogg_page_crc(page): """ Compute CRC of an Ogg page. """ page_zero_crc = page[:OGG_FIRST_PAGE_HEADER_CRC_OFFSET] + \ b"\00" * OGG_FIRST_PAGE_HEADER_CRC.size + \ page[OGG_FIRST_PAGE_HEADER_CRC_OFFSET + OGG_FIRST_PAGE_HEADER_CRC.size:] return ogg_page_crc(page_zero_crc)
python
def _compute_ogg_page_crc(page): """ Compute CRC of an Ogg page. """ page_zero_crc = page[:OGG_FIRST_PAGE_HEADER_CRC_OFFSET] + \ b"\00" * OGG_FIRST_PAGE_HEADER_CRC.size + \ page[OGG_FIRST_PAGE_HEADER_CRC_OFFSET + OGG_FIRST_PAGE_HEADER_CRC.size:] return ogg_page_crc(page_zero_crc)
Compute CRC of an Ogg page.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L123-L128
desbma/r128gain
r128gain/__init__.py
get_ffmpeg_lib_versions
def get_ffmpeg_lib_versions(ffmpeg_path=None): """ Get FFmpeg library versions as 32 bit integers, with same format as sys.hexversion. Example: 0x3040100 for FFmpeg 3.4.1 """ r = collections.OrderedDict() cmd = (ffmpeg_path or "ffmpeg", "-version") output = subprocess.run(cmd, che...
python
def get_ffmpeg_lib_versions(ffmpeg_path=None): """ Get FFmpeg library versions as 32 bit integers, with same format as sys.hexversion. Example: 0x3040100 for FFmpeg 3.4.1 """ r = collections.OrderedDict() cmd = (ffmpeg_path or "ffmpeg", "-version") output = subprocess.run(cmd, che...
Get FFmpeg library versions as 32 bit integers, with same format as sys.hexversion. Example: 0x3040100 for FFmpeg 3.4.1
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L47-L68
desbma/r128gain
r128gain/__init__.py
format_ffmpeg_filter
def format_ffmpeg_filter(name, params): """ Build a string to call a FFMpeg filter. """ return "%s=%s" % (name, ":".join("%s=%s" % (k, v) for k, v in params.items()))
python
def format_ffmpeg_filter(name, params): """ Build a string to call a FFMpeg filter. """ return "%s=%s" % (name, ":".join("%s=%s" % (k, v) for k, v in params.items()))
Build a string to call a FFMpeg filter.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L71-L74
desbma/r128gain
r128gain/__init__.py
get_r128_loudness
def get_r128_loudness(audio_filepaths, *, calc_peak=True, enable_ffmpeg_threading=True, ffmpeg_path=None): """ Get R128 loudness loudness level and sample peak. """ logger().info("Analyzing loudness of file%s %s..." % ("s" if (len(audio_filepaths) > 1) else "", ...
python
def get_r128_loudness(audio_filepaths, *, calc_peak=True, enable_ffmpeg_threading=True, ffmpeg_path=None): """ Get R128 loudness loudness level and sample peak. """ logger().info("Analyzing loudness of file%s %s..." % ("s" if (len(audio_filepaths) > 1) else "", ...
Get R128 loudness loudness level and sample peak.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L77-L155
desbma/r128gain
r128gain/__init__.py
scan
def scan(audio_filepaths, *, album_gain=False, skip_tagged=False, thread_count=None, ffmpeg_path=None, executor=None): """ Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. """ r128_data = {} with contextlib.ExitStack() as cm: if executor i...
python
def scan(audio_filepaths, *, album_gain=False, skip_tagged=False, thread_count=None, ffmpeg_path=None, executor=None): """ Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. """ r128_data = {} with contextlib.ExitStack() as cm: if executor i...
Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L158-L236
desbma/r128gain
r128gain/__init__.py
tag
def tag(filepath, loudness, peak, *, album_loudness=None, album_peak=None, opus_output_gain=False, mtime_second_offset=None): """ Tag audio file with loudness metadata. """ assert((loudness is not None) or (album_loudness is not None)) if peak is not None: assert(0 <= peak <= 1.0) if album_peak i...
python
def tag(filepath, loudness, peak, *, album_loudness=None, album_peak=None, opus_output_gain=False, mtime_second_offset=None): """ Tag audio file with loudness metadata. """ assert((loudness is not None) or (album_loudness is not None)) if peak is not None: assert(0 <= peak <= 1.0) if album_peak i...
Tag audio file with loudness metadata.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L257-L352
desbma/r128gain
r128gain/__init__.py
has_loudness_tag
def has_loudness_tag(filepath): """ Return a pair of booleans indicating if filepath has a RG or R128 track/album tag, or None if file is invalid. """ track, album = False, False try: mf = mutagen.File(filepath) except mutagen.MutagenError as e: logger().warning("File '%s' %s: %s" % (filepath, ...
python
def has_loudness_tag(filepath): """ Return a pair of booleans indicating if filepath has a RG or R128 track/album tag, or None if file is invalid. """ track, album = False, False try: mf = mutagen.File(filepath) except mutagen.MutagenError as e: logger().warning("File '%s' %s: %s" % (filepath, ...
Return a pair of booleans indicating if filepath has a RG or R128 track/album tag, or None if file is invalid.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L355-L391
desbma/r128gain
r128gain/__init__.py
show_scan_report
def show_scan_report(audio_filepaths, album_dir, r128_data): """ Display loudness scan results. """ # track loudness/peak for audio_filepath in audio_filepaths: try: loudness, peak = r128_data[audio_filepath] except KeyError: loudness, peak = "SKIPPED", "SKIPPED" else: loudness = "%....
python
def show_scan_report(audio_filepaths, album_dir, r128_data): """ Display loudness scan results. """ # track loudness/peak for audio_filepath in audio_filepaths: try: loudness, peak = r128_data[audio_filepath] except KeyError: loudness, peak = "SKIPPED", "SKIPPED" else: loudness = "%....
Display loudness scan results.
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L394-L422
clemfromspace/scrapy-cloudflare-middleware
setup.py
get_requirements
def get_requirements(source): """Get the requirements from the given ``source`` Parameters ---------- source: str The filename containing the requirements """ install_reqs = parse_requirements(filename=source, session=PipSession()) return [str(ir.req) for ir in install_reqs]
python
def get_requirements(source): """Get the requirements from the given ``source`` Parameters ---------- source: str The filename containing the requirements """ install_reqs = parse_requirements(filename=source, session=PipSession()) return [str(ir.req) for ir in install_reqs]
Get the requirements from the given ``source`` Parameters ---------- source: str The filename containing the requirements
https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/setup.py#L8-L20
clemfromspace/scrapy-cloudflare-middleware
scrapy_cloudflare_middleware/middlewares.py
CloudFlareMiddleware.is_cloudflare_challenge
def is_cloudflare_challenge(response): """Test if the given response contains the cloudflare's anti-bot protection""" return ( response.status == 503 and response.headers.get('Server', '').startswith(b'cloudflare') and 'jschl_vc' in response.text and 'jsc...
python
def is_cloudflare_challenge(response): """Test if the given response contains the cloudflare's anti-bot protection""" return ( response.status == 503 and response.headers.get('Server', '').startswith(b'cloudflare') and 'jschl_vc' in response.text and 'jsc...
Test if the given response contains the cloudflare's anti-bot protection
https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/scrapy_cloudflare_middleware/middlewares.py#L12-L20
clemfromspace/scrapy-cloudflare-middleware
scrapy_cloudflare_middleware/middlewares.py
CloudFlareMiddleware.process_response
def process_response(self, request, response, spider): """Handle the a Scrapy response""" if not self.is_cloudflare_challenge(response): return response logger = logging.getLogger('cloudflaremiddleware') logger.debug( 'Cloudflare protection detected on %s, tryi...
python
def process_response(self, request, response, spider): """Handle the a Scrapy response""" if not self.is_cloudflare_challenge(response): return response logger = logging.getLogger('cloudflaremiddleware') logger.debug( 'Cloudflare protection detected on %s, tryi...
Handle the a Scrapy response
https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/scrapy_cloudflare_middleware/middlewares.py#L22-L48
Fahreeve/aiovk
aiovk/sessions.py
TokenSession.enter_captcha
async def enter_captcha(self, url: str, sid: str) -> str: """ Override this method for processing captcha. :param url: link to captcha image :param sid: captcha id. I do not know why pass here but may be useful :return captcha value """ raise VkCaptchaNeeded(url,...
python
async def enter_captcha(self, url: str, sid: str) -> str: """ Override this method for processing captcha. :param url: link to captcha image :param sid: captcha id. I do not know why pass here but may be useful :return captcha value """ raise VkCaptchaNeeded(url,...
Override this method for processing captcha. :param url: link to captcha image :param sid: captcha id. I do not know why pass here but may be useful :return captcha value
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L104-L112
Fahreeve/aiovk
aiovk/sessions.py
ImplicitSession.authorize
async def authorize(self) -> None: """Getting a new token from server""" html = await self._get_auth_page() url = URL('/authorize?email') for step in range(self.num_of_attempts): if url.path == '/authorize' and 'email' in url.query: # Invalid login or password...
python
async def authorize(self) -> None: """Getting a new token from server""" html = await self._get_auth_page() url = URL('/authorize?email') for step in range(self.num_of_attempts): if url.path == '/authorize' and 'email' in url.query: # Invalid login or password...
Getting a new token from server
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L143-L164
Fahreeve/aiovk
aiovk/sessions.py
ImplicitSession._get_auth_page
async def _get_auth_page(self) -> str: """ Get authorization mobile page without js :return: html page """ # Prepare request params = { 'client_id': self.app_id, 'redirect_uri': 'https://oauth.vk.com/blank.html', 'display': 'mobile', ...
python
async def _get_auth_page(self) -> str: """ Get authorization mobile page without js :return: html page """ # Prepare request params = { 'client_id': self.app_id, 'redirect_uri': 'https://oauth.vk.com/blank.html', 'display': 'mobile', ...
Get authorization mobile page without js :return: html page
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L166-L189
Fahreeve/aiovk
aiovk/sessions.py
ImplicitSession._process_auth_form
async def _process_auth_form(self, html: str) -> (str, str): """ Parsing data from authorization page and filling the form and submitting the form :param html: html page :return: url and html from redirected page """ # Parse page p = AuthPageParser() p.f...
python
async def _process_auth_form(self, html: str) -> (str, str): """ Parsing data from authorization page and filling the form and submitting the form :param html: html page :return: url and html from redirected page """ # Parse page p = AuthPageParser() p.f...
Parsing data from authorization page and filling the form and submitting the form :param html: html page :return: url and html from redirected page
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L191-L220
Fahreeve/aiovk
aiovk/sessions.py
ImplicitSession._process_2auth_form
async def _process_2auth_form(self, html: str) -> (str, str): """ Parsing two-factor authorization page and filling the code :param html: html page :return: url and html from redirected page """ # Parse page p = TwoFactorCodePageParser() p.feed(html) ...
python
async def _process_2auth_form(self, html: str) -> (str, str): """ Parsing two-factor authorization page and filling the code :param html: html page :return: url and html from redirected page """ # Parse page p = TwoFactorCodePageParser() p.feed(html) ...
Parsing two-factor authorization page and filling the code :param html: html page :return: url and html from redirected page
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L222-L244
Fahreeve/aiovk
aiovk/sessions.py
ImplicitSession._process_access_form
async def _process_access_form(self, html: str) -> (str, str): """ Parsing page with access rights :param html: html page :return: url and html from redirected page """ # Parse page p = AccessPageParser() p.feed(html) p.close() form_url ...
python
async def _process_access_form(self, html: str) -> (str, str): """ Parsing page with access rights :param html: html page :return: url and html from redirected page """ # Parse page p = AccessPageParser() p.feed(html) p.close() form_url ...
Parsing page with access rights :param html: html page :return: url and html from redirected page
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L246-L263
Fahreeve/aiovk
aiovk/sessions.py
AuthorizationCodeSession.authorize
async def authorize(self, code: str=None) -> None: """Getting a new token from server""" code = await self.get_code(code) params = { 'client_id': self.app_id, 'client_secret': self.app_secret, 'redirect_uri': self.redirect_uri, 'code': code ...
python
async def authorize(self, code: str=None) -> None: """Getting a new token from server""" code = await self.get_code(code) params = { 'client_id': self.app_id, 'client_secret': self.app_secret, 'redirect_uri': self.redirect_uri, 'code': code ...
Getting a new token from server
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L295-L307
Fahreeve/aiovk
aiovk/longpoll.py
BaseLongPoll.wait
async def wait(self, need_pts=False) -> dict: """Send long poll request :param need_pts: need return the pts field """ if not self.base_url: await self._get_long_poll_server(need_pts) params = { 'ts': self.ts, 'key': self.key, } ...
python
async def wait(self, need_pts=False) -> dict: """Send long poll request :param need_pts: need return the pts field """ if not self.base_url: await self._get_long_poll_server(need_pts) params = { 'ts': self.ts, 'key': self.key, } ...
Send long poll request :param need_pts: need return the pts field
https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/longpoll.py#L48-L89
ericsuh/dirichlet
dirichlet/dirichlet.py
pdf
def pdf(alphas): '''Returns a Dirichlet PDF function''' alphap = alphas - 1 c = np.exp(gammaln(alphas.sum()) - gammaln(alphas).sum()) def dirichlet(xs): '''N x K array''' return c * (xs**alphap).prod(axis=1) return dirichlet
python
def pdf(alphas): '''Returns a Dirichlet PDF function''' alphap = alphas - 1 c = np.exp(gammaln(alphas.sum()) - gammaln(alphas).sum()) def dirichlet(xs): '''N x K array''' return c * (xs**alphap).prod(axis=1) return dirichlet
Returns a Dirichlet PDF function
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L95-L102
ericsuh/dirichlet
dirichlet/dirichlet.py
meanprecision
def meanprecision(a): '''Mean and precision of Dirichlet distribution. Parameters ---------- a : array Parameters of Dirichlet distribution. Returns ------- mean : array Numbers [0,1] of the means of the Dirichlet distribution. precision : float Precision or con...
python
def meanprecision(a): '''Mean and precision of Dirichlet distribution. Parameters ---------- a : array Parameters of Dirichlet distribution. Returns ------- mean : array Numbers [0,1] of the means of the Dirichlet distribution. precision : float Precision or con...
Mean and precision of Dirichlet distribution. Parameters ---------- a : array Parameters of Dirichlet distribution. Returns ------- mean : array Numbers [0,1] of the means of the Dirichlet distribution. precision : float Precision or concentration parameter of the D...
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L104-L121
ericsuh/dirichlet
dirichlet/dirichlet.py
loglikelihood
def loglikelihood(D, a): '''Compute log likelihood of Dirichlet distribution, i.e. log p(D|a). Parameters ---------- D : 2D array where ``N`` is the number of observations, ``K`` is the number of parameters for the Dirichlet distribution. a : array Parameters for the Dirichl...
python
def loglikelihood(D, a): '''Compute log likelihood of Dirichlet distribution, i.e. log p(D|a). Parameters ---------- D : 2D array where ``N`` is the number of observations, ``K`` is the number of parameters for the Dirichlet distribution. a : array Parameters for the Dirichl...
Compute log likelihood of Dirichlet distribution, i.e. log p(D|a). Parameters ---------- D : 2D array where ``N`` is the number of observations, ``K`` is the number of parameters for the Dirichlet distribution. a : array Parameters for the Dirichlet distribution. Returns ...
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L123-L140
ericsuh/dirichlet
dirichlet/dirichlet.py
mle
def mle(D, tol=1e-7, method='meanprecision', maxiter=None): '''Iteratively computes maximum likelihood Dirichlet distribution for an observed data set, i.e. a for which log p(D|a) is maximum. Parameters ---------- D : 2D array ``N x K`` array of numbers from [0,1] where ``N`` is the number ...
python
def mle(D, tol=1e-7, method='meanprecision', maxiter=None): '''Iteratively computes maximum likelihood Dirichlet distribution for an observed data set, i.e. a for which log p(D|a) is maximum. Parameters ---------- D : 2D array ``N x K`` array of numbers from [0,1] where ``N`` is the number ...
Iteratively computes maximum likelihood Dirichlet distribution for an observed data set, i.e. a for which log p(D|a) is maximum. Parameters ---------- D : 2D array ``N x K`` array of numbers from [0,1] where ``N`` is the number of observations, ``K`` is the number of parameters for the ...
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L142-L171
ericsuh/dirichlet
dirichlet/dirichlet.py
_fixedpoint
def _fixedpoint(D, tol=1e-7, maxiter=None): '''Simple fixed point iteration method for MLE of Dirichlet distribution''' N, K = D.shape logp = log(D).mean(axis=0) a0 = _init_a(D) # Start updating if maxiter is None: maxiter = MAXINT for i in xrange(maxiter): a1 = _ipsi(psi(a0...
python
def _fixedpoint(D, tol=1e-7, maxiter=None): '''Simple fixed point iteration method for MLE of Dirichlet distribution''' N, K = D.shape logp = log(D).mean(axis=0) a0 = _init_a(D) # Start updating if maxiter is None: maxiter = MAXINT for i in xrange(maxiter): a1 = _ipsi(psi(a0...
Simple fixed point iteration method for MLE of Dirichlet distribution
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L173-L189
ericsuh/dirichlet
dirichlet/dirichlet.py
_meanprecision
def _meanprecision(D, tol=1e-7, maxiter=None): '''Mean and precision alternating method for MLE of Dirichlet distribution''' N, K = D.shape logp = log(D).mean(axis=0) a0 = _init_a(D) s0 = a0.sum() if s0 < 0: a0 = a0/s0 s0 = 1 elif s0 == 0: a0 = ones(a.shape) / len...
python
def _meanprecision(D, tol=1e-7, maxiter=None): '''Mean and precision alternating method for MLE of Dirichlet distribution''' N, K = D.shape logp = log(D).mean(axis=0) a0 = _init_a(D) s0 = a0.sum() if s0 < 0: a0 = a0/s0 s0 = 1 elif s0 == 0: a0 = ones(a.shape) / len...
Mean and precision alternating method for MLE of Dirichlet distribution
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L191-L219
ericsuh/dirichlet
dirichlet/dirichlet.py
_fit_s
def _fit_s(D, a0, logp, tol=1e-7, maxiter=1000): '''Assuming a fixed mean for Dirichlet distribution, maximize likelihood for preicision a.k.a. s''' N, K = D.shape s1 = a0.sum() m = a0 / s1 mlogp = (m*logp).sum() for i in xrange(maxiter): s0 = s1 g = psi(s1) - (m*psi(s1*m)).s...
python
def _fit_s(D, a0, logp, tol=1e-7, maxiter=1000): '''Assuming a fixed mean for Dirichlet distribution, maximize likelihood for preicision a.k.a. s''' N, K = D.shape s1 = a0.sum() m = a0 / s1 mlogp = (m*logp).sum() for i in xrange(maxiter): s0 = s1 g = psi(s1) - (m*psi(s1*m)).s...
Assuming a fixed mean for Dirichlet distribution, maximize likelihood for preicision a.k.a. s
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L221-L249
ericsuh/dirichlet
dirichlet/dirichlet.py
_fit_m
def _fit_m(D, a0, logp, tol=1e-7, maxiter=1000): '''With fixed precision s, maximize mean m''' N,K = D.shape s = a0.sum() for i in xrange(maxiter): m = a0 / s a1 = _ipsi(logp + (m*(psi(a0) - logp)).sum()) a1 = a1/a1.sum() * s if norm(a1 - a0) < tol: return a...
python
def _fit_m(D, a0, logp, tol=1e-7, maxiter=1000): '''With fixed precision s, maximize mean m''' N,K = D.shape s = a0.sum() for i in xrange(maxiter): m = a0 / s a1 = _ipsi(logp + (m*(psi(a0) - logp)).sum()) a1 = a1/a1.sum() * s if norm(a1 - a0) < tol: return a...
With fixed precision s, maximize mean m
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L251-L266
ericsuh/dirichlet
dirichlet/dirichlet.py
_piecewise
def _piecewise(x, condlist, funclist, *args, **kw): '''Fixed version of numpy.piecewise for 0-d arrays''' x = asanyarray(x) n2 = len(funclist) if isscalar(condlist) or \ (isinstance(condlist, np.ndarray) and condlist.ndim == 0) or \ (x.ndim > 0 and condlist[0].ndim == 0): ...
python
def _piecewise(x, condlist, funclist, *args, **kw): '''Fixed version of numpy.piecewise for 0-d arrays''' x = asanyarray(x) n2 = len(funclist) if isscalar(condlist) or \ (isinstance(condlist, np.ndarray) and condlist.ndim == 0) or \ (x.ndim > 0 and condlist[0].ndim == 0): ...
Fixed version of numpy.piecewise for 0-d arrays
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L268-L316
ericsuh/dirichlet
dirichlet/dirichlet.py
_init_a
def _init_a(D): '''Initial guess for Dirichlet alpha parameters given data D''' E = D.mean(axis=0) E2 = (D**2).mean(axis=0) return ((E[0] - E2[0])/(E2[0]-E[0]**2)) * E
python
def _init_a(D): '''Initial guess for Dirichlet alpha parameters given data D''' E = D.mean(axis=0) E2 = (D**2).mean(axis=0) return ((E[0] - E2[0])/(E2[0]-E[0]**2)) * E
Initial guess for Dirichlet alpha parameters given data D
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L318-L322
ericsuh/dirichlet
dirichlet/dirichlet.py
_ipsi
def _ipsi(y, tol=1.48e-9, maxiter=10): '''Inverse of psi (digamma) using Newton's method. For the purposes of Dirichlet MLE, since the parameters a[i] must always satisfy a > 0, we define ipsi :: R -> (0,inf).''' y = asanyarray(y, dtype='float') x0 = _piecewise(y, [y >= -2.22, y < -2.22], ...
python
def _ipsi(y, tol=1.48e-9, maxiter=10): '''Inverse of psi (digamma) using Newton's method. For the purposes of Dirichlet MLE, since the parameters a[i] must always satisfy a > 0, we define ipsi :: R -> (0,inf).''' y = asanyarray(y, dtype='float') x0 = _piecewise(y, [y >= -2.22, y < -2.22], ...
Inverse of psi (digamma) using Newton's method. For the purposes of Dirichlet MLE, since the parameters a[i] must always satisfy a > 0, we define ipsi :: R -> (0,inf).
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L324-L337
ericsuh/dirichlet
dirichlet/simplex.py
cartesian
def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1]) >>> cartesian((0,0,1)) ...
python
def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1]) >>> cartesian((0,0,1)) ...
Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1]) >>> cartesian((0,0,1)) array([0.5, 0.866025403784438...
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L13-L38
ericsuh/dirichlet
dirichlet/simplex.py
barycentric
def barycentric(points): '''Inverse of :func:`cartesian`.''' points = np.asanyarray(points) ndim = points.ndim if ndim == 1: points = points.reshape((1,points.size)) c = (2/np.sqrt(3.0))*points[:,1] b = (2*points[:,0] - c)/2.0 a = 1.0 - c - b out = np.vstack([a,b,c]).T if ndi...
python
def barycentric(points): '''Inverse of :func:`cartesian`.''' points = np.asanyarray(points) ndim = points.ndim if ndim == 1: points = points.reshape((1,points.size)) c = (2/np.sqrt(3.0))*points[:,1] b = (2*points[:,0] - c)/2.0 a = 1.0 - c - b out = np.vstack([a,b,c]).T if ndi...
Inverse of :func:`cartesian`.
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L40-L52
ericsuh/dirichlet
dirichlet/simplex.py
scatter
def scatter(points, vertexlabels=None, **kwargs): '''Scatter plot of barycentric 2-simplex points on a 2D triangle. :param points: Points on a 2-simplex. :type points: N x 3 list or ndarray. :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b =...
python
def scatter(points, vertexlabels=None, **kwargs): '''Scatter plot of barycentric 2-simplex points on a 2D triangle. :param points: Points on a 2-simplex. :type points: N x 3 list or ndarray. :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b =...
Scatter plot of barycentric 2-simplex points on a 2D triangle. :param points: Points on a 2-simplex. :type points: N x 3 list or ndarray. :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``, ``c == (0,0,1)``. :type vertexla...
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L54-L72
ericsuh/dirichlet
dirichlet/simplex.py
contour
def contour(f, vertexlabels=None, **kwargs): '''Contour line plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. :param f: Function to evaluate on N x 3 ndarray of coordinates :type f: ``ufunc`` :param vertexlabels: Labels for corners of plot in the order ``(a, b,...
python
def contour(f, vertexlabels=None, **kwargs): '''Contour line plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. :param f: Function to evaluate on N x 3 ndarray of coordinates :type f: ``ufunc`` :param vertexlabels: Labels for corners of plot in the order ``(a, b,...
Contour line plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. :param f: Function to evaluate on N x 3 ndarray of coordinates :type f: ``ufunc`` :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``, ...
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L74-L86
ericsuh/dirichlet
dirichlet/simplex.py
contourf
def contourf(f, vertexlabels=None, **kwargs): '''Filled contour plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. Function signature is identical to :func:`contour` with the caveat that ``**kwargs`` are passed on to :func:`plt.tricontourf`.''' return _contour(f, vertexl...
python
def contourf(f, vertexlabels=None, **kwargs): '''Filled contour plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. Function signature is identical to :func:`contour` with the caveat that ``**kwargs`` are passed on to :func:`plt.tricontourf`.''' return _contour(f, vertexl...
Filled contour plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. Function signature is identical to :func:`contour` with the caveat that ``**kwargs`` are passed on to :func:`plt.tricontourf`.
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L88-L94
ericsuh/dirichlet
dirichlet/simplex.py
_contour
def _contour(f, vertexlabels=None, contourfunc=None, **kwargs): '''Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.''' if contourfunc is None: contourfunc = plt.tricontour if vertexlabels is None: vertexlabels = ('1','2...
python
def _contour(f, vertexlabels=None, contourfunc=None, **kwargs): '''Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.''' if contourfunc is None: contourfunc = plt.tricontour if vertexlabels is None: vertexlabels = ('1','2...
Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L96-L114
insightindustry/validator-collection
validator_collection/_decorators.py
disable_on_env
def disable_on_env(func): """Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, the ``value`` (first positional argument) passed to ``func``. If enabled, the result of ``fu...
python
def disable_on_env(func): """Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, the ``value`` (first positional argument) passed to ``func``. If enabled, the result of ``fu...
Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, the ``value`` (first positional argument) passed to ``func``. If enabled, the result of ``func``.
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/_decorators.py#L21-L53
insightindustry/validator-collection
validator_collection/_decorators.py
disable_checker_on_env
def disable_checker_on_env(func): """Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, ``True``. If enabled, the result of ``func``. """ @wraps(func) def func_wrapper...
python
def disable_checker_on_env(func): """Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, ``True``. If enabled, the result of ``func``. """ @wraps(func) def func_wrapper...
Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``. :param func: The function/validator to be disabled. :type func: callable :returns: If disabled, ``True``. If enabled, the result of ``func``.
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/_decorators.py#L56-L79
insightindustry/validator-collection
validator_collection/validators.py
uuid
def uuid(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class...
python
def uuid(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class...
Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L133-L168
insightindustry/validator-collection
validator_collection/validators.py
string
def string(value, allow_empty = False, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Validate that ``value`` is a valid string. :param value: The value to validate. :type value:...
python
def string(value, allow_empty = False, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Validate that ``value`` is a valid string. :param value: The value to validate. :type value:...
Validate that ``value`` is a valid string. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L172-L245
insightindustry/validator-collection
validator_collection/validators.py
iterable
def iterable(value, allow_empty = False, forbid_literals = (str, bytes), minimum_length = None, maximum_length = None, **kwargs): """Validate that ``value`` is a valid iterable. :param value: The value to validate. :param allow_empty: If ``T...
python
def iterable(value, allow_empty = False, forbid_literals = (str, bytes), minimum_length = None, maximum_length = None, **kwargs): """Validate that ``value`` is a valid iterable. :param value: The value to validate. :param allow_empty: If ``T...
Validate that ``value`` is a valid iterable. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Def...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L249-L311
insightindustry/validator-collection
validator_collection/validators.py
none
def none(value, allow_empty = False, **kwargs): """Validate that ``value`` is :obj:`None <python:None>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty but **not** :obj:`None <python:None>`. If ``False`...
python
def none(value, allow_empty = False, **kwargs): """Validate that ``value`` is :obj:`None <python:None>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty but **not** :obj:`None <python:None>`. If ``False`...
Validate that ``value`` is :obj:`None <python:None>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty but **not** :obj:`None <python:None>`. If ``False``, raises a :class:`NotNoneError` if ``value`` is empty but **not**...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L315-L339
insightindustry/validator-collection
validator_collection/validators.py
not_empty
def not_empty(value, allow_empty = False, **kwargs): """Validate that ``value`` is not empty. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueErro...
python
def not_empty(value, allow_empty = False, **kwargs): """Validate that ``value`` is not empty. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueErro...
Validate that ``value`` is not empty. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults t...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L343-L365
insightindustry/validator-collection
validator_collection/validators.py
variable_name
def variable_name(value, allow_empty = False, **kwargs): """Validate that the value is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or ...
python
def variable_name(value, allow_empty = False, **kwargs): """Validate that the value is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or ...
Validate that the value is a valid Python variable name. .. caution:: This function does **NOT** check whether the variable exists. It only checks that the ``value`` would work as a Python variable (or class, or function, etc.) name. :param value: The value to validate. :param allow_em...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L369-L406
insightindustry/validator-collection
validator_collection/validators.py
dict
def dict(value, allow_empty = False, json_serializer = None, **kwargs): """Validate that ``value`` is a :class:`dict <python:dict>`. .. hint:: If ``value`` is a string, this validator will assume it is a JSON object and try to convert it into a :class:`dict <python:dict>...
python
def dict(value, allow_empty = False, json_serializer = None, **kwargs): """Validate that ``value`` is a :class:`dict <python:dict>`. .. hint:: If ``value`` is a string, this validator will assume it is a JSON object and try to convert it into a :class:`dict <python:dict>...
Validate that ``value`` is a :class:`dict <python:dict>`. .. hint:: If ``value`` is a string, this validator will assume it is a JSON object and try to convert it into a :class:`dict <python:dict>` You can override the JSON serializer used by passing it to the ``json_serializer`` property...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L410-L470
insightindustry/validator-collection
validator_collection/validators.py
json
def json(value, schema = None, allow_empty = False, json_serializer = None, **kwargs): """Validate that ``value`` conforms to the supplied JSON Schema. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using...
python
def json(value, schema = None, allow_empty = False, json_serializer = None, **kwargs): """Validate that ``value`` conforms to the supplied JSON Schema. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using...
Validate that ``value`` conforms to the supplied JSON Schema. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. .. hint:: If either ``value`` or ``sc...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L474-L568
insightindustry/validator-collection
validator_collection/validators.py
date
def date(value, allow_empty = False, minimum = None, maximum = None, coerce_value = True, **kwargs): """Validate that ``value`` is a valid date. :param value: The value to validate. :type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datet...
python
def date(value, allow_empty = False, minimum = None, maximum = None, coerce_value = True, **kwargs): """Validate that ``value`` is a valid date. :param value: The value to validate. :type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datet...
Validate that ``value`` is a valid date. :param value: The value to validate. :type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` / :class:`date <python:datetime.date>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L575-L712
insightindustry/validator-collection
validator_collection/validators.py
datetime
def datetime(value, allow_empty = False, minimum = None, maximum = None, coerce_value = True, **kwargs): """Validate that ``value`` is a valid datetime. .. caution:: If supplying a string, the string needs to be in an ISO 8601-format to pa...
python
def datetime(value, allow_empty = False, minimum = None, maximum = None, coerce_value = True, **kwargs): """Validate that ``value`` is a valid datetime. .. caution:: If supplying a string, the string needs to be in an ISO 8601-format to pa...
Validate that ``value`` is a valid datetime. .. caution:: If supplying a string, the string needs to be in an ISO 8601-format to pass validation. If it is not in an ISO 8601-format, validation will fail. :param value: The value to validate. :type value: :class:`str <python:str>` / :class:`dat...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L716-L892
insightindustry/validator-collection
validator_collection/validators.py
time
def time(value, allow_empty = False, minimum = None, maximum = None, coerce_value = True, **kwargs): """Validate that ``value`` is a valid :class:`time <python:datetime.time>`. .. caution:: This validator will **always** return the time as timezone naive (eff...
python
def time(value, allow_empty = False, minimum = None, maximum = None, coerce_value = True, **kwargs): """Validate that ``value`` is a valid :class:`time <python:datetime.time>`. .. caution:: This validator will **always** return the time as timezone naive (eff...
Validate that ``value`` is a valid :class:`time <python:datetime.time>`. .. caution:: This validator will **always** return the time as timezone naive (effectively UTC). If ``value`` has a timezone / UTC offset applied, the validator will coerce the value returned back to UTC. :param value:...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L896-L1078
insightindustry/validator-collection
validator_collection/validators.py
timezone
def timezone(value, allow_empty = False, positive = True, **kwargs): """Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** verify whether the value is a timezone that actually exists, nor can it resolve...
python
def timezone(value, allow_empty = False, positive = True, **kwargs): """Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** verify whether the value is a timezone that actually exists, nor can it resolve...
Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`. .. caution:: This does **not** verify whether the value is a timezone that actually exists, nor can it resolve timezone names (e.g. ``'Eastern'`` or ``'CET'``). For that kind of functionality, we recommend you utilize:...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1082-L1219
insightindustry/validator-collection
validator_collection/validators.py
numeric
def numeric(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a numeric value. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :o...
python
def numeric(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a numeric value. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :o...
Validate that ``value`` is a numeric value. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises an :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``v...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1225-L1295
insightindustry/validator-collection
validator_collection/validators.py
integer
def integer(value, allow_empty = False, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs): """Validate that ``value`` is an :class:`int <python:int>`. :param value: The value to validate. :param allow_empty: I...
python
def integer(value, allow_empty = False, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs): """Validate that ``value`` is an :class:`int <python:int>`. :param value: The value to validate. :param allow_empty: I...
Validate that ``value`` is an :class:`int <python:int>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>`...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1299-L1375
insightindustry/validator-collection
validator_collection/validators.py
float
def float(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a :class:`float <python:float>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``...
python
def float(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a :class:`float <python:float>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``...
Validate that ``value`` is a :class:`float <python:float>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueErro...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1379-L1423
insightindustry/validator-collection
validator_collection/validators.py
fraction
def fraction(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <p...
python
def fraction(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <p...
Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.error...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1427-L1471
insightindustry/validator-collection
validator_collection/validators.py
decimal
def decimal(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:Non...
python
def decimal(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:Non...
Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.Em...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1475-L1540
insightindustry/validator-collection
validator_collection/validators.py
_numeric_coercion
def _numeric_coercion(value, coercion_function = None, allow_empty = False, minimum = None, maximum = None): """Validate that ``value`` is numeric and coerce using ``coercion_function``. :param value: The value to validate....
python
def _numeric_coercion(value, coercion_function = None, allow_empty = False, minimum = None, maximum = None): """Validate that ``value`` is numeric and coerce using ``coercion_function``. :param value: The value to validate....
Validate that ``value`` is numeric and coerce using ``coercion_function``. :param value: The value to validate. :param coercion_function: The function to use to coerce ``value`` to the desired type. :type coercion_function: callable :param allow_empty: If ``True``, returns :obj:`None <python:No...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1543-L1594
insightindustry/validator-collection
validator_collection/validators.py
bytesIO
def bytesIO(value, allow_empty = False, **kwargs): """Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises ...
python
def bytesIO(value, allow_empty = False, **kwargs): """Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises ...
Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` ...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1600-L1629
insightindustry/validator-collection
validator_collection/validators.py
stringIO
def stringIO(value, allow_empty = False, **kwargs): """Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, ra...
python
def stringIO(value, allow_empty = False, **kwargs): """Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, ra...
Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` ...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1633-L1662
insightindustry/validator-collection
validator_collection/validators.py
path
def path(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid path-like object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueErro...
python
def path(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid path-like object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueErro...
Validate that ``value`` is a valid path-like object. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is em...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1666-L1701
insightindustry/validator-collection
validator_collection/validators.py
path_exists
def path_exists(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path-like object that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is emp...
python
def path_exists(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path-like object that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is emp...
Validate that ``value`` is a path-like object that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyVal...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1705-L1738
insightindustry/validator-collection
validator_collection/validators.py
file_exists
def file_exists(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid file that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``F...
python
def file_exists(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid file that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``F...
Validate that ``value`` is a valid file that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` ...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1742-L1775
insightindustry/validator-collection
validator_collection/validators.py
directory_exists
def directory_exists(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid directory that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``...
python
def directory_exists(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid directory that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``...
Validate that ``value`` is a valid directory that exists on the local filesystem. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValu...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1779-L1813
insightindustry/validator-collection
validator_collection/validators.py
readable
def readable(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path to a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it ...
python
def readable(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path to a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it ...
Validate that ``value`` is a path to a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Tim...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1817-L1880
insightindustry/validator-collection
validator_collection/validators.py
writeable
def writeable(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path to a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the ...
python
def writeable(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path to a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the ...
Validate that ``value`` is a path to a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows f...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1883-L1968
insightindustry/validator-collection
validator_collection/validators.py
executable
def executable(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path to an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and t...
python
def executable(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path to an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and t...
Validate that ``value`` is a path to an executable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the various ways in which it can manage file permission. If called on a Windows...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1971-L2049
insightindustry/validator-collection
validator_collection/validators.py
email
def email(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc532...
python
def email(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc532...
Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of string parsing and regular expressions....
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2055-L2212
insightindustry/validator-collection
validator_collection/validators.py
url
def url(value, allow_empty = False, allow_special_ips = False, **kwargs): """Validate that ``value`` is a valid URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/ht...
python
def url(value, allow_empty = False, allow_special_ips = False, **kwargs): """Validate that ``value`` is a valid URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/ht...
Validate that ``value`` is a valid URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_, `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, `RFC 2181 <https://tools.ie...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2216-L2306
insightindustry/validator-collection
validator_collection/validators.py
domain
def domain(value, allow_empty = False, allow_ips = False, **kwargs): """Validate that ``value`` is a valid domain name. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain...
python
def domain(value, allow_empty = False, allow_ips = False, **kwargs): """Validate that ``value`` is a valid domain name. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain...
Validate that ``value`` is a valid domain name. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain. .. note:: This validator checks to validate that ``value`` resembles a valid domain name....
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2310-L2418
insightindustry/validator-collection
validator_collection/validators.py
ip_address
def ip_address(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid IP address. .. note:: First, the validator will check if the address is a valid IPv6 address. If that doesn't work, the validator will check if the address is a valid IPv...
python
def ip_address(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid IP address. .. note:: First, the validator will check if the address is a valid IPv6 address. If that doesn't work, the validator will check if the address is a valid IPv...
Validate that ``value`` is a valid IP address. .. note:: First, the validator will check if the address is a valid IPv6 address. If that doesn't work, the validator will check if the address is a valid IPv4 address. If neither works, the validator will raise an error (as always). :pa...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2422-L2471
insightindustry/validator-collection
validator_collection/validators.py
ipv4
def ipv4(value, allow_empty = False): """Validate that ``value`` is a valid IP version 4 address. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection....
python
def ipv4(value, allow_empty = False): """Validate that ``value`` is a valid IP version 4 address. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection....
Validate that ``value`` is a valid IP version 4 address. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` i...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2475-L2513
insightindustry/validator-collection
validator_collection/validators.py
ipv6
def ipv6(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid IP address version 6. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValue...
python
def ipv6(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid IP address version 6. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValue...
Validate that ``value`` is a valid IP address version 6. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` i...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2517-L2552
insightindustry/validator-collection
validator_collection/validators.py
mac_address
def mac_address(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:...
python
def mac_address(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:...
Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <vali...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2556-L2600
insightindustry/validator-collection
validator_collection/checkers.py
is_type
def is_type(obj, type_, **kwargs): """Indicate if ``obj`` is a type in ``type_``. .. hint:: This checker is particularly useful when you want to evaluate whether ``obj`` is of a particular type, but importing that type directly to use in :func:`isinstance() <python:is...
python
def is_type(obj, type_, **kwargs): """Indicate if ``obj`` is a type in ``type_``. .. hint:: This checker is particularly useful when you want to evaluate whether ``obj`` is of a particular type, but importing that type directly to use in :func:`isinstance() <python:is...
Indicate if ``obj`` is a type in ``type_``. .. hint:: This checker is particularly useful when you want to evaluate whether ``obj`` is of a particular type, but importing that type directly to use in :func:`isinstance() <python:isinstance>` would cause a circular import error. To us...
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L21-L69
insightindustry/validator-collection
validator_collection/checkers.py
_check_base_classes
def _check_base_classes(base_classes, check_for_type): """Indicate whether ``check_for_type`` exists in ``base_classes``. """ return_value = False for base in base_classes: if base.__name__ == check_for_type: return_value = True break else: return_valu...
python
def _check_base_classes(base_classes, check_for_type): """Indicate whether ``check_for_type`` exists in ``base_classes``. """ return_value = False for base in base_classes: if base.__name__ == check_for_type: return_value = True break else: return_valu...
Indicate whether ``check_for_type`` exists in ``base_classes``.
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L72-L85