id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,300 | 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Opt Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| S |M|V| rsv | sequence | seed-id (optional) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ipv6_opts.mpl.type Option Type
0 0 ipv6_opts.mpl.type.value Option Number
0 0 ipv6_opts.mpl.type.action Action (01)
0 2 ipv6_opts.mpl.type.change Change Flag (1)
1 8 ipv6_opts.mpl.length Length of Option Data
2 16 ipv6_opts.mpl.seed_len Seed-ID Length
2 18 ipv6_opts.mpl.flags MPL Option Flags
2 18 ipv6_opts.mpl.max Maximum SEQ Flag
2 19 ipv6_opts.mpl.verification Verification Flag
2 20 - Reserved
3 24 ipv6_opts.mpl.seq Sequence
4 32 ipv6_opts.mpl.seed_id Seed-ID
"""
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
if _size < 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
_smvr = self._read_binary(1)
_seqn = self._read_unpack(1)
opt = dict(
desc=desc,
type=_type,
length=_size + 2,
seed_len=_IPv6_Opts_SEED.get(int(_smvr[:2], base=2)),
flags=dict(
max=True if int(_smvr[2], base=2) else False,
verification=True if int(_smvr[3], base=2) else False,
),
seq=_seqn,
)
_kind = _smvr[:2]
if _kind == '00':
if _size != 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
elif _kind == '01':
if _size != 4:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(2)
elif _kind == '10':
if _size != 10:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(8)
elif _kind == '11':
if _size != 18:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(16)
else:
opt['seed_id'] = self._read_unpack(_size-2)
_plen = _size - opt['seed_len']
if _plen:
self._read_fileng(_plen)
return opt | python | def _read_opt_mpl(self, code, *, desc):
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
if _size < 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
_smvr = self._read_binary(1)
_seqn = self._read_unpack(1)
opt = dict(
desc=desc,
type=_type,
length=_size + 2,
seed_len=_IPv6_Opts_SEED.get(int(_smvr[:2], base=2)),
flags=dict(
max=True if int(_smvr[2], base=2) else False,
verification=True if int(_smvr[3], base=2) else False,
),
seq=_seqn,
)
_kind = _smvr[:2]
if _kind == '00':
if _size != 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
elif _kind == '01':
if _size != 4:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(2)
elif _kind == '10':
if _size != 10:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(8)
elif _kind == '11':
if _size != 18:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(16)
else:
opt['seed_id'] = self._read_unpack(_size-2)
_plen = _size - opt['seed_len']
if _plen:
self._read_fileng(_plen)
return opt | [
"def",
"_read_opt_mpl",
"(",
"self",
",",
"code",
",",
"*",
",",
"desc",
")",
":",
"_type",
"=",
"self",
".",
"_read_opt_type",
"(",
"code",
")",
"_size",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"if",
"_size",
"<",
"2",
":",
"raise",
"ProtocolError",
"(",
"f'{self.alias}: [Optno {code}] invalid format'",
")",
"_type",
"=",
"self",
".",
"_read_opt_type",
"(",
"code",
")",
"_size",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"_smvr",
"=",
"self",
".",
"_read_binary",
"(",
"1",
")",
"_seqn",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"opt",
"=",
"dict",
"(",
"desc",
"=",
"desc",
",",
"type",
"=",
"_type",
",",
"length",
"=",
"_size",
"+",
"2",
",",
"seed_len",
"=",
"_IPv6_Opts_SEED",
".",
"get",
"(",
"int",
"(",
"_smvr",
"[",
":",
"2",
"]",
",",
"base",
"=",
"2",
")",
")",
",",
"flags",
"=",
"dict",
"(",
"max",
"=",
"True",
"if",
"int",
"(",
"_smvr",
"[",
"2",
"]",
",",
"base",
"=",
"2",
")",
"else",
"False",
",",
"verification",
"=",
"True",
"if",
"int",
"(",
"_smvr",
"[",
"3",
"]",
",",
"base",
"=",
"2",
")",
"else",
"False",
",",
")",
",",
"seq",
"=",
"_seqn",
",",
")",
"_kind",
"=",
"_smvr",
"[",
":",
"2",
"]",
"if",
"_kind",
"==",
"'00'",
":",
"if",
"_size",
"!=",
"2",
":",
"raise",
"ProtocolError",
"(",
"f'{self.alias}: [Optno {code}] invalid format'",
")",
"elif",
"_kind",
"==",
"'01'",
":",
"if",
"_size",
"!=",
"4",
":",
"raise",
"ProtocolError",
"(",
"f'{self.alias}: [Optno {code}] invalid format'",
")",
"opt",
"[",
"'seed_id'",
"]",
"=",
"self",
".",
"_read_unpack",
"(",
"2",
")",
"elif",
"_kind",
"==",
"'10'",
":",
"if",
"_size",
"!=",
"10",
":",
"raise",
"ProtocolError",
"(",
"f'{self.alias}: [Optno {code}] invalid format'",
")",
"opt",
"[",
"'seed_id'",
"]",
"=",
"self",
".",
"_read_unpack",
"(",
"8",
")",
"elif",
"_kind",
"==",
"'11'",
":",
"if",
"_size",
"!=",
"18",
":",
"raise",
"ProtocolError",
"(",
"f'{self.alias}: [Optno {code}] invalid format'",
")",
"opt",
"[",
"'seed_id'",
"]",
"=",
"self",
".",
"_read_unpack",
"(",
"16",
")",
"else",
":",
"opt",
"[",
"'seed_id'",
"]",
"=",
"self",
".",
"_read_unpack",
"(",
"_size",
"-",
"2",
")",
"_plen",
"=",
"_size",
"-",
"opt",
"[",
"'seed_len'",
"]",
"if",
"_plen",
":",
"self",
".",
"_read_fileng",
"(",
"_plen",
")",
"return",
"opt"
] | 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Opt Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| S |M|V| rsv | sequence | seed-id (optional) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ipv6_opts.mpl.type Option Type
0 0 ipv6_opts.mpl.type.value Option Number
0 0 ipv6_opts.mpl.type.action Action (01)
0 2 ipv6_opts.mpl.type.change Change Flag (1)
1 8 ipv6_opts.mpl.length Length of Option Data
2 16 ipv6_opts.mpl.seed_len Seed-ID Length
2 18 ipv6_opts.mpl.flags MPL Option Flags
2 18 ipv6_opts.mpl.max Maximum SEQ Flag
2 19 ipv6_opts.mpl.verification Verification Flag
2 20 - Reserved
3 24 ipv6_opts.mpl.seq Sequence
4 32 ipv6_opts.mpl.seed_id Seed-ID | [
"Read",
"IPv6_Opts",
"MPL",
"option",
"."
] | c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L797-L869 |
1,301 | 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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data
"""
if length is None:
length = len(self)
_next = self._read_protos(1)
_hlen = self._read_unpack(1)
_type = self._read_unpack(1)
_left = self._read_unpack(1)
ipv6_route = dict(
next=_next,
length=(_hlen + 1) * 8,
type=_ROUTING_TYPE.get(_type, 'Unassigned'),
seg_left=_left,
)
_dlen = _hlen * 8 - 4
if _dlen:
_func = _ROUTE_PROC.get(_type, 'none')
_data = eval(f'self._read_data_type_{_func}')(_dlen)
ipv6_route.update(_data)
length -= ipv6_route['length']
ipv6_route['packet'] = self._read_packet(header=ipv6_route['length'], payload=length)
if extension:
self._protos = None
return ipv6_route
return self._decode_next_layer(ipv6_route, _next, length) | python | def read_ipv6_route(self, length, extension):
if length is None:
length = len(self)
_next = self._read_protos(1)
_hlen = self._read_unpack(1)
_type = self._read_unpack(1)
_left = self._read_unpack(1)
ipv6_route = dict(
next=_next,
length=(_hlen + 1) * 8,
type=_ROUTING_TYPE.get(_type, 'Unassigned'),
seg_left=_left,
)
_dlen = _hlen * 8 - 4
if _dlen:
_func = _ROUTE_PROC.get(_type, 'none')
_data = eval(f'self._read_data_type_{_func}')(_dlen)
ipv6_route.update(_data)
length -= ipv6_route['length']
ipv6_route['packet'] = self._read_packet(header=ipv6_route['length'], payload=length)
if extension:
self._protos = None
return ipv6_route
return self._decode_next_layer(ipv6_route, _next, length) | [
"def",
"read_ipv6_route",
"(",
"self",
",",
"length",
",",
"extension",
")",
":",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"len",
"(",
"self",
")",
"_next",
"=",
"self",
".",
"_read_protos",
"(",
"1",
")",
"_hlen",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"_type",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"_left",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"ipv6_route",
"=",
"dict",
"(",
"next",
"=",
"_next",
",",
"length",
"=",
"(",
"_hlen",
"+",
"1",
")",
"*",
"8",
",",
"type",
"=",
"_ROUTING_TYPE",
".",
"get",
"(",
"_type",
",",
"'Unassigned'",
")",
",",
"seg_left",
"=",
"_left",
",",
")",
"_dlen",
"=",
"_hlen",
"*",
"8",
"-",
"4",
"if",
"_dlen",
":",
"_func",
"=",
"_ROUTE_PROC",
".",
"get",
"(",
"_type",
",",
"'none'",
")",
"_data",
"=",
"eval",
"(",
"f'self._read_data_type_{_func}'",
")",
"(",
"_dlen",
")",
"ipv6_route",
".",
"update",
"(",
"_data",
")",
"length",
"-=",
"ipv6_route",
"[",
"'length'",
"]",
"ipv6_route",
"[",
"'packet'",
"]",
"=",
"self",
".",
"_read_packet",
"(",
"header",
"=",
"ipv6_route",
"[",
"'length'",
"]",
",",
"payload",
"=",
"length",
")",
"if",
"extension",
":",
"self",
".",
"_protos",
"=",
"None",
"return",
"ipv6_route",
"return",
"self",
".",
"_decode_next_layer",
"(",
"ipv6_route",
",",
"_next",
",",
"length",
")"
] | Read Routing Header for IPv6.
Structure of IPv6-Route header [RFC 8200][RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data | [
"Read",
"Routing",
"Header",
"for",
"IPv6",
"."
] | c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L102-L151 |
1,302 | 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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data
"""
_data = self._read_fileng(length)
data = dict(
data=_data,
)
return data | python | def _read_data_type_none(self, length):
_data = self._read_fileng(length)
data = dict(
data=_data,
)
return data | [
"def",
"_read_data_type_none",
"(",
"self",
",",
"length",
")",
":",
"_data",
"=",
"self",
".",
"_read_fileng",
"(",
"length",
")",
"data",
"=",
"dict",
"(",
"data",
"=",
"_data",
",",
")",
"return",
"data"
] | 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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data | [
"Read",
"IPv6",
"-",
"Route",
"unknown",
"type",
"data",
"."
] | c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L169-L197 |
1,303 | 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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. . .
. . .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[n] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Address
............
"""
_resv = self._read_fileng(4)
_addr = list()
for _ in range((length - 4) // 16):
_addr.append(ipaddress.ip_address(self._read_fileng(16)))
data = dict(
ip=tuple(_addr),
)
return data | python | def _read_data_type_src(self, length):
_resv = self._read_fileng(4)
_addr = list()
for _ in range((length - 4) // 16):
_addr.append(ipaddress.ip_address(self._read_fileng(16)))
data = dict(
ip=tuple(_addr),
)
return data | [
"def",
"_read_data_type_src",
"(",
"self",
",",
"length",
")",
":",
"_resv",
"=",
"self",
".",
"_read_fileng",
"(",
"4",
")",
"_addr",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"(",
"length",
"-",
"4",
")",
"//",
"16",
")",
":",
"_addr",
".",
"append",
"(",
"ipaddress",
".",
"ip_address",
"(",
"self",
".",
"_read_fileng",
"(",
"16",
")",
")",
")",
"data",
"=",
"dict",
"(",
"ip",
"=",
"tuple",
"(",
"_addr",
")",
",",
")",
"return",
"data"
] | 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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. . .
. . .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[n] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Address
............ | [
"Read",
"IPv6",
"-",
"Route",
"Source",
"Route",
"data",
"."
] | c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L199-L256 |
1,304 | 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|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Home Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Home Address
"""
if length != 20:
raise ProtocolError(f'{self.alias}: [Typeno 2] invalid format')
_resv = self._read_fileng(4)
_home = self._read_fileng(16)
data = dict(
ip=ipaddress.ip_address(_home),
)
return data | python | def _read_data_type_2(self, length):
if length != 20:
raise ProtocolError(f'{self.alias}: [Typeno 2] invalid format')
_resv = self._read_fileng(4)
_home = self._read_fileng(16)
data = dict(
ip=ipaddress.ip_address(_home),
)
return data | [
"def",
"_read_data_type_2",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
"!=",
"20",
":",
"raise",
"ProtocolError",
"(",
"f'{self.alias}: [Typeno 2] invalid format'",
")",
"_resv",
"=",
"self",
".",
"_read_fileng",
"(",
"4",
")",
"_home",
"=",
"self",
".",
"_read_fileng",
"(",
"16",
")",
"data",
"=",
"dict",
"(",
"ip",
"=",
"ipaddress",
".",
"ip_address",
"(",
"_home",
")",
",",
")",
"return",
"data"
] | 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|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Home Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Home Address | [
"Read",
"IPv6",
"-",
"Route",
"Type",
"2",
"data",
"."
] | c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L258-L295 |
1,305 | 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| CmprI | CmprE | Pad | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. Addresses[1..n] .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.cmpri CmprI
4 36 route.cpmre CmprE
5 40 route.pad Pad Size
5 44 - Reserved
8 64 route.ip Addresses
"""
_cmpr = self._read_binary(1)
_padr = self._read_binary(1)
_resv = self._read_fileng(2)
_inti = int(_cmpr[:4], base=2)
_inte = int(_cmpr[4:], base=2)
_plen = int(_padr[:4], base=2)
_ilen = 16 - _inti
_elen = 16 - _inte
_addr = list()
for _ in (((length - 4) - _elen - _plen) // _ilen):
_addr.append(ipaddress.ip_address(self._read_fileng(_ilen)))
_addr.append(ipaddress.ip_address(self._read_fileng(_elen)))
_pads = self._read_fileng(_plen)
data = dict(
cmpri=_inti,
cmpre=_inte,
pad=_plen,
ip=tuple(_addr),
)
return data | python | def _read_data_type_rpl(self, length):
_cmpr = self._read_binary(1)
_padr = self._read_binary(1)
_resv = self._read_fileng(2)
_inti = int(_cmpr[:4], base=2)
_inte = int(_cmpr[4:], base=2)
_plen = int(_padr[:4], base=2)
_ilen = 16 - _inti
_elen = 16 - _inte
_addr = list()
for _ in (((length - 4) - _elen - _plen) // _ilen):
_addr.append(ipaddress.ip_address(self._read_fileng(_ilen)))
_addr.append(ipaddress.ip_address(self._read_fileng(_elen)))
_pads = self._read_fileng(_plen)
data = dict(
cmpri=_inti,
cmpre=_inte,
pad=_plen,
ip=tuple(_addr),
)
return data | [
"def",
"_read_data_type_rpl",
"(",
"self",
",",
"length",
")",
":",
"_cmpr",
"=",
"self",
".",
"_read_binary",
"(",
"1",
")",
"_padr",
"=",
"self",
".",
"_read_binary",
"(",
"1",
")",
"_resv",
"=",
"self",
".",
"_read_fileng",
"(",
"2",
")",
"_inti",
"=",
"int",
"(",
"_cmpr",
"[",
":",
"4",
"]",
",",
"base",
"=",
"2",
")",
"_inte",
"=",
"int",
"(",
"_cmpr",
"[",
"4",
":",
"]",
",",
"base",
"=",
"2",
")",
"_plen",
"=",
"int",
"(",
"_padr",
"[",
":",
"4",
"]",
",",
"base",
"=",
"2",
")",
"_ilen",
"=",
"16",
"-",
"_inti",
"_elen",
"=",
"16",
"-",
"_inte",
"_addr",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"(",
"(",
"(",
"length",
"-",
"4",
")",
"-",
"_elen",
"-",
"_plen",
")",
"//",
"_ilen",
")",
":",
"_addr",
".",
"append",
"(",
"ipaddress",
".",
"ip_address",
"(",
"self",
".",
"_read_fileng",
"(",
"_ilen",
")",
")",
")",
"_addr",
".",
"append",
"(",
"ipaddress",
".",
"ip_address",
"(",
"self",
".",
"_read_fileng",
"(",
"_elen",
")",
")",
")",
"_pads",
"=",
"self",
".",
"_read_fileng",
"(",
"_plen",
")",
"data",
"=",
"dict",
"(",
"cmpri",
"=",
"_inti",
",",
"cmpre",
"=",
"_inte",
",",
"pad",
"=",
"_plen",
",",
"ip",
"=",
"tuple",
"(",
"_addr",
")",
",",
")",
"return",
"data"
] | 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| CmprI | CmprE | Pad | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. Addresses[1..n] .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.cmpri CmprI
4 36 route.cpmre CmprE
5 40 route.pad Pad Size
5 44 - Reserved
8 64 route.ip Addresses | [
"Read",
"IPv6",
"-",
"Route",
"RPL",
"Source",
"data",
"."
] | c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L297-L352 |
1,306 | 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.write(OGG_OPUS_ID_HEADER_GAIN.pack(new_output_gain))
# compute page crc
file.seek(0)
page = file.read(opus_header_pos + OGG_OPUS_ID_HEADER.size)
computed_crc = _compute_ogg_page_crc(page)
# write CRC
file.seek(OGG_FIRST_PAGE_HEADER_CRC_OFFSET)
file.write(OGG_FIRST_PAGE_HEADER_CRC.pack(computed_crc)) | python | def write_oggopus_output_gain(file, new_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(OGG_OPUS_ID_HEADER_GAIN.pack(new_output_gain))
# compute page crc
file.seek(0)
page = file.read(opus_header_pos + OGG_OPUS_ID_HEADER.size)
computed_crc = _compute_ogg_page_crc(page)
# write CRC
file.seek(OGG_FIRST_PAGE_HEADER_CRC_OFFSET)
file.write(OGG_FIRST_PAGE_HEADER_CRC.pack(computed_crc)) | [
"def",
"write_oggopus_output_gain",
"(",
"file",
",",
"new_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",
"(",
"OGG_OPUS_ID_HEADER_GAIN",
".",
"pack",
"(",
"new_output_gain",
")",
")",
"# compute page crc",
"file",
".",
"seek",
"(",
"0",
")",
"page",
"=",
"file",
".",
"read",
"(",
"opus_header_pos",
"+",
"OGG_OPUS_ID_HEADER",
".",
"size",
")",
"computed_crc",
"=",
"_compute_ogg_page_crc",
"(",
"page",
")",
"# write CRC",
"file",
".",
"seek",
"(",
"OGG_FIRST_PAGE_HEADER_CRC_OFFSET",
")",
"file",
".",
"write",
"(",
"OGG_FIRST_PAGE_HEADER_CRC",
".",
"pack",
"(",
"computed_crc",
")",
")"
] | Write output gain Opus header for a file.
file must be an object successfully used by parse_oggopus_output_gain. | [
"Write",
"output",
"gain",
"Opus",
"header",
"for",
"a",
"file",
"."
] | 011ee26fe3705a50925571785d206cba2806089a | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L102-L120 |
1,307 | 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):
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) | [
"def",
"_compute_ogg_page_crc",
"(",
"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. | [
"Compute",
"CRC",
"of",
"an",
"Ogg",
"page",
"."
] | 011ee26fe3705a50925571785d206cba2806089a | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L123-L128 |
1,308 | 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):
return "%s=%s" % (name,
":".join("%s=%s" % (k, v) for k, v in params.items())) | [
"def",
"format_ffmpeg_filter",
"(",
"name",
",",
"params",
")",
":",
"return",
"\"%s=%s\"",
"%",
"(",
"name",
",",
"\":\"",
".",
"join",
"(",
"\"%s=%s\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
")",
")"
] | Build a string to call a FFMpeg filter. | [
"Build",
"a",
"string",
"to",
"call",
"a",
"FFMpeg",
"filter",
"."
] | 011ee26fe3705a50925571785d206cba2806089a | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L71-L74 |
1,309 | 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 is None:
if thread_count is None:
try:
thread_count = len(os.sched_getaffinity(0))
except AttributeError:
thread_count = os.cpu_count()
enable_ffmpeg_threading = thread_count > (len(audio_filepaths) + int(album_gain))
executor = cm.enter_context(concurrent.futures.ThreadPoolExecutor(max_workers=thread_count))
asynchronous = False
else:
enable_ffmpeg_threading = False
asynchronous = True
loudness_tags = tuple(map(has_loudness_tag, audio_filepaths))
# remove invalid files
audio_filepaths = tuple(audio_filepath for (audio_filepath,
has_tags) in zip(audio_filepaths,
loudness_tags) if has_tags is not None)
loudness_tags = tuple(filter(None, loudness_tags))
futures = {}
if album_gain:
if skip_tagged and all(map(operator.itemgetter(1), loudness_tags)):
logger().info("All files already have an album gain tag, skipping album gain scan")
elif audio_filepaths:
calc_album_peak = any(map(lambda x: os.path.splitext(x)[-1].lower() != ".opus",
audio_filepaths))
futures[ALBUM_GAIN_KEY] = executor.submit(get_r128_loudness,
audio_filepaths,
calc_peak=calc_album_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
for audio_filepath in audio_filepaths:
if skip_tagged and has_loudness_tag(audio_filepath)[0]:
logger().info("File '%s' already has a track gain tag, skipping track gain scan" % (audio_filepath))
continue
if os.path.splitext(audio_filepath)[-1].lower() == ".opus":
# http://www.rfcreader.com/#rfc7845_line1060
calc_peak = False
else:
calc_peak = True
futures[audio_filepath] = executor.submit(get_r128_loudness,
(audio_filepath,),
calc_peak=calc_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
if asynchronous:
return futures
for audio_filepath in audio_filepaths:
try:
r128_data[audio_filepath] = futures[audio_filepath].result()
except KeyError:
# track gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze file '%s': %s %s" % (audio_filepath,
e.__class__.__qualname__,
e))
if album_gain and audio_filepaths:
try:
r128_data[ALBUM_GAIN_KEY] = futures[ALBUM_GAIN_KEY].result()
except KeyError:
# album gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze files %s: %s %s" % (", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths),
e.__class__.__qualname__,
e))
return r128_data | python | def scan(audio_filepaths, *, album_gain=False, skip_tagged=False, thread_count=None, ffmpeg_path=None, executor=None):
r128_data = {}
with contextlib.ExitStack() as cm:
if executor is None:
if thread_count is None:
try:
thread_count = len(os.sched_getaffinity(0))
except AttributeError:
thread_count = os.cpu_count()
enable_ffmpeg_threading = thread_count > (len(audio_filepaths) + int(album_gain))
executor = cm.enter_context(concurrent.futures.ThreadPoolExecutor(max_workers=thread_count))
asynchronous = False
else:
enable_ffmpeg_threading = False
asynchronous = True
loudness_tags = tuple(map(has_loudness_tag, audio_filepaths))
# remove invalid files
audio_filepaths = tuple(audio_filepath for (audio_filepath,
has_tags) in zip(audio_filepaths,
loudness_tags) if has_tags is not None)
loudness_tags = tuple(filter(None, loudness_tags))
futures = {}
if album_gain:
if skip_tagged and all(map(operator.itemgetter(1), loudness_tags)):
logger().info("All files already have an album gain tag, skipping album gain scan")
elif audio_filepaths:
calc_album_peak = any(map(lambda x: os.path.splitext(x)[-1].lower() != ".opus",
audio_filepaths))
futures[ALBUM_GAIN_KEY] = executor.submit(get_r128_loudness,
audio_filepaths,
calc_peak=calc_album_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
for audio_filepath in audio_filepaths:
if skip_tagged and has_loudness_tag(audio_filepath)[0]:
logger().info("File '%s' already has a track gain tag, skipping track gain scan" % (audio_filepath))
continue
if os.path.splitext(audio_filepath)[-1].lower() == ".opus":
# http://www.rfcreader.com/#rfc7845_line1060
calc_peak = False
else:
calc_peak = True
futures[audio_filepath] = executor.submit(get_r128_loudness,
(audio_filepath,),
calc_peak=calc_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
if asynchronous:
return futures
for audio_filepath in audio_filepaths:
try:
r128_data[audio_filepath] = futures[audio_filepath].result()
except KeyError:
# track gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze file '%s': %s %s" % (audio_filepath,
e.__class__.__qualname__,
e))
if album_gain and audio_filepaths:
try:
r128_data[ALBUM_GAIN_KEY] = futures[ALBUM_GAIN_KEY].result()
except KeyError:
# album gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze files %s: %s %s" % (", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths),
e.__class__.__qualname__,
e))
return r128_data | [
"def",
"scan",
"(",
"audio_filepaths",
",",
"*",
",",
"album_gain",
"=",
"False",
",",
"skip_tagged",
"=",
"False",
",",
"thread_count",
"=",
"None",
",",
"ffmpeg_path",
"=",
"None",
",",
"executor",
"=",
"None",
")",
":",
"r128_data",
"=",
"{",
"}",
"with",
"contextlib",
".",
"ExitStack",
"(",
")",
"as",
"cm",
":",
"if",
"executor",
"is",
"None",
":",
"if",
"thread_count",
"is",
"None",
":",
"try",
":",
"thread_count",
"=",
"len",
"(",
"os",
".",
"sched_getaffinity",
"(",
"0",
")",
")",
"except",
"AttributeError",
":",
"thread_count",
"=",
"os",
".",
"cpu_count",
"(",
")",
"enable_ffmpeg_threading",
"=",
"thread_count",
">",
"(",
"len",
"(",
"audio_filepaths",
")",
"+",
"int",
"(",
"album_gain",
")",
")",
"executor",
"=",
"cm",
".",
"enter_context",
"(",
"concurrent",
".",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"thread_count",
")",
")",
"asynchronous",
"=",
"False",
"else",
":",
"enable_ffmpeg_threading",
"=",
"False",
"asynchronous",
"=",
"True",
"loudness_tags",
"=",
"tuple",
"(",
"map",
"(",
"has_loudness_tag",
",",
"audio_filepaths",
")",
")",
"# remove invalid files",
"audio_filepaths",
"=",
"tuple",
"(",
"audio_filepath",
"for",
"(",
"audio_filepath",
",",
"has_tags",
")",
"in",
"zip",
"(",
"audio_filepaths",
",",
"loudness_tags",
")",
"if",
"has_tags",
"is",
"not",
"None",
")",
"loudness_tags",
"=",
"tuple",
"(",
"filter",
"(",
"None",
",",
"loudness_tags",
")",
")",
"futures",
"=",
"{",
"}",
"if",
"album_gain",
":",
"if",
"skip_tagged",
"and",
"all",
"(",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"loudness_tags",
")",
")",
":",
"logger",
"(",
")",
".",
"info",
"(",
"\"All files already have an album gain tag, skipping album gain scan\"",
")",
"elif",
"audio_filepaths",
":",
"calc_album_peak",
"=",
"any",
"(",
"map",
"(",
"lambda",
"x",
":",
"os",
".",
"path",
".",
"splitext",
"(",
"x",
")",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"!=",
"\".opus\"",
",",
"audio_filepaths",
")",
")",
"futures",
"[",
"ALBUM_GAIN_KEY",
"]",
"=",
"executor",
".",
"submit",
"(",
"get_r128_loudness",
",",
"audio_filepaths",
",",
"calc_peak",
"=",
"calc_album_peak",
",",
"enable_ffmpeg_threading",
"=",
"enable_ffmpeg_threading",
",",
"ffmpeg_path",
"=",
"ffmpeg_path",
")",
"for",
"audio_filepath",
"in",
"audio_filepaths",
":",
"if",
"skip_tagged",
"and",
"has_loudness_tag",
"(",
"audio_filepath",
")",
"[",
"0",
"]",
":",
"logger",
"(",
")",
".",
"info",
"(",
"\"File '%s' already has a track gain tag, skipping track gain scan\"",
"%",
"(",
"audio_filepath",
")",
")",
"continue",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"audio_filepath",
")",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"\".opus\"",
":",
"# http://www.rfcreader.com/#rfc7845_line1060",
"calc_peak",
"=",
"False",
"else",
":",
"calc_peak",
"=",
"True",
"futures",
"[",
"audio_filepath",
"]",
"=",
"executor",
".",
"submit",
"(",
"get_r128_loudness",
",",
"(",
"audio_filepath",
",",
")",
",",
"calc_peak",
"=",
"calc_peak",
",",
"enable_ffmpeg_threading",
"=",
"enable_ffmpeg_threading",
",",
"ffmpeg_path",
"=",
"ffmpeg_path",
")",
"if",
"asynchronous",
":",
"return",
"futures",
"for",
"audio_filepath",
"in",
"audio_filepaths",
":",
"try",
":",
"r128_data",
"[",
"audio_filepath",
"]",
"=",
"futures",
"[",
"audio_filepath",
"]",
".",
"result",
"(",
")",
"except",
"KeyError",
":",
"# track gain was skipped",
"pass",
"except",
"Exception",
"as",
"e",
":",
"# raise",
"logger",
"(",
")",
".",
"warning",
"(",
"\"Failed to analyze file '%s': %s %s\"",
"%",
"(",
"audio_filepath",
",",
"e",
".",
"__class__",
".",
"__qualname__",
",",
"e",
")",
")",
"if",
"album_gain",
"and",
"audio_filepaths",
":",
"try",
":",
"r128_data",
"[",
"ALBUM_GAIN_KEY",
"]",
"=",
"futures",
"[",
"ALBUM_GAIN_KEY",
"]",
".",
"result",
"(",
")",
"except",
"KeyError",
":",
"# album gain was skipped",
"pass",
"except",
"Exception",
"as",
"e",
":",
"# raise",
"logger",
"(",
")",
".",
"warning",
"(",
"\"Failed to analyze files %s: %s %s\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"\"'%s'\"",
"%",
"(",
"audio_filepath",
")",
"for",
"audio_filepath",
"in",
"audio_filepaths",
")",
",",
"e",
".",
"__class__",
".",
"__qualname__",
",",
"e",
")",
")",
"return",
"r128_data"
] | Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. | [
"Analyze",
"files",
"and",
"return",
"a",
"dictionary",
"of",
"filepath",
"to",
"loudness",
"metadata",
"or",
"filepath",
"to",
"future",
"if",
"executor",
"is",
"not",
"None",
"."
] | 011ee26fe3705a50925571785d206cba2806089a | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L158-L236 |
1,310 | 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 = "%.1f LUFS" % (loudness)
if peak is None:
peak = "-"
else:
peak = "%.1f dBFS" % (scale_to_gain(peak))
logger().info("File '%s': loudness = %s, sample peak = %s" % (audio_filepath, loudness, peak))
# album loudness/peak
if album_dir:
try:
album_loudness, album_peak = r128_data[ALBUM_GAIN_KEY]
except KeyError:
album_loudness, album_peak = "SKIPPED", "SKIPPED"
else:
album_loudness = "%.1f LUFS" % (album_loudness)
if album_peak is None:
album_peak = "-"
else:
album_peak = "%.1f dBFS" % (scale_to_gain(album_peak))
logger().info("Album '%s': loudness = %s, sample peak = %s" % (album_dir, album_loudness, album_peak)) | python | def show_scan_report(audio_filepaths, album_dir, r128_data):
# track loudness/peak
for audio_filepath in audio_filepaths:
try:
loudness, peak = r128_data[audio_filepath]
except KeyError:
loudness, peak = "SKIPPED", "SKIPPED"
else:
loudness = "%.1f LUFS" % (loudness)
if peak is None:
peak = "-"
else:
peak = "%.1f dBFS" % (scale_to_gain(peak))
logger().info("File '%s': loudness = %s, sample peak = %s" % (audio_filepath, loudness, peak))
# album loudness/peak
if album_dir:
try:
album_loudness, album_peak = r128_data[ALBUM_GAIN_KEY]
except KeyError:
album_loudness, album_peak = "SKIPPED", "SKIPPED"
else:
album_loudness = "%.1f LUFS" % (album_loudness)
if album_peak is None:
album_peak = "-"
else:
album_peak = "%.1f dBFS" % (scale_to_gain(album_peak))
logger().info("Album '%s': loudness = %s, sample peak = %s" % (album_dir, album_loudness, album_peak)) | [
"def",
"show_scan_report",
"(",
"audio_filepaths",
",",
"album_dir",
",",
"r128_data",
")",
":",
"# track loudness/peak",
"for",
"audio_filepath",
"in",
"audio_filepaths",
":",
"try",
":",
"loudness",
",",
"peak",
"=",
"r128_data",
"[",
"audio_filepath",
"]",
"except",
"KeyError",
":",
"loudness",
",",
"peak",
"=",
"\"SKIPPED\"",
",",
"\"SKIPPED\"",
"else",
":",
"loudness",
"=",
"\"%.1f LUFS\"",
"%",
"(",
"loudness",
")",
"if",
"peak",
"is",
"None",
":",
"peak",
"=",
"\"-\"",
"else",
":",
"peak",
"=",
"\"%.1f dBFS\"",
"%",
"(",
"scale_to_gain",
"(",
"peak",
")",
")",
"logger",
"(",
")",
".",
"info",
"(",
"\"File '%s': loudness = %s, sample peak = %s\"",
"%",
"(",
"audio_filepath",
",",
"loudness",
",",
"peak",
")",
")",
"# album loudness/peak",
"if",
"album_dir",
":",
"try",
":",
"album_loudness",
",",
"album_peak",
"=",
"r128_data",
"[",
"ALBUM_GAIN_KEY",
"]",
"except",
"KeyError",
":",
"album_loudness",
",",
"album_peak",
"=",
"\"SKIPPED\"",
",",
"\"SKIPPED\"",
"else",
":",
"album_loudness",
"=",
"\"%.1f LUFS\"",
"%",
"(",
"album_loudness",
")",
"if",
"album_peak",
"is",
"None",
":",
"album_peak",
"=",
"\"-\"",
"else",
":",
"album_peak",
"=",
"\"%.1f dBFS\"",
"%",
"(",
"scale_to_gain",
"(",
"album_peak",
")",
")",
"logger",
"(",
")",
".",
"info",
"(",
"\"Album '%s': loudness = %s, sample peak = %s\"",
"%",
"(",
"album_dir",
",",
"album_loudness",
",",
"album_peak",
")",
")"
] | Display loudness scan results. | [
"Display",
"loudness",
"scan",
"results",
"."
] | 011ee26fe3705a50925571785d206cba2806089a | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L394-L422 |
1,311 | 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):
install_reqs = parse_requirements(filename=source, session=PipSession())
return [str(ir.req) for ir in install_reqs] | [
"def",
"get_requirements",
"(",
"source",
")",
":",
"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 | [
"Get",
"the",
"requirements",
"from",
"the",
"given",
"source"
] | 03ccea9164418dabe8180053165b0da0bffa0741 | https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/setup.py#L8-L20 |
1,312 | 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 'jschl_answer' in response.text
) | python | def is_cloudflare_challenge(response):
return (
response.status == 503
and response.headers.get('Server', '').startswith(b'cloudflare')
and 'jschl_vc' in response.text
and 'jschl_answer' in response.text
) | [
"def",
"is_cloudflare_challenge",
"(",
"response",
")",
":",
"return",
"(",
"response",
".",
"status",
"==",
"503",
"and",
"response",
".",
"headers",
".",
"get",
"(",
"'Server'",
",",
"''",
")",
".",
"startswith",
"(",
"b'cloudflare'",
")",
"and",
"'jschl_vc'",
"in",
"response",
".",
"text",
"and",
"'jschl_answer'",
"in",
"response",
".",
"text",
")"
] | Test if the given response contains the cloudflare's anti-bot protection | [
"Test",
"if",
"the",
"given",
"response",
"contains",
"the",
"cloudflare",
"s",
"anti",
"-",
"bot",
"protection"
] | 03ccea9164418dabe8180053165b0da0bffa0741 | https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/scrapy_cloudflare_middleware/middlewares.py#L12-L20 |
1,313 | 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, trying to bypass...',
response.url
)
cloudflare_tokens, __ = get_tokens(
request.url,
user_agent=spider.settings.get('USER_AGENT')
)
logger.debug(
'Successfully bypassed the protection for %s, re-scheduling the request',
response.url
)
request.cookies.update(cloudflare_tokens)
request.priority = 99999
return request | python | def process_response(self, request, response, spider):
if not self.is_cloudflare_challenge(response):
return response
logger = logging.getLogger('cloudflaremiddleware')
logger.debug(
'Cloudflare protection detected on %s, trying to bypass...',
response.url
)
cloudflare_tokens, __ = get_tokens(
request.url,
user_agent=spider.settings.get('USER_AGENT')
)
logger.debug(
'Successfully bypassed the protection for %s, re-scheduling the request',
response.url
)
request.cookies.update(cloudflare_tokens)
request.priority = 99999
return request | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"spider",
")",
":",
"if",
"not",
"self",
".",
"is_cloudflare_challenge",
"(",
"response",
")",
":",
"return",
"response",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'cloudflaremiddleware'",
")",
"logger",
".",
"debug",
"(",
"'Cloudflare protection detected on %s, trying to bypass...'",
",",
"response",
".",
"url",
")",
"cloudflare_tokens",
",",
"__",
"=",
"get_tokens",
"(",
"request",
".",
"url",
",",
"user_agent",
"=",
"spider",
".",
"settings",
".",
"get",
"(",
"'USER_AGENT'",
")",
")",
"logger",
".",
"debug",
"(",
"'Successfully bypassed the protection for %s, re-scheduling the request'",
",",
"response",
".",
"url",
")",
"request",
".",
"cookies",
".",
"update",
"(",
"cloudflare_tokens",
")",
"request",
".",
"priority",
"=",
"99999",
"return",
"request"
] | Handle the a Scrapy response | [
"Handle",
"the",
"a",
"Scrapy",
"response"
] | 03ccea9164418dabe8180053165b0da0bffa0741 | https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/scrapy_cloudflare_middleware/middlewares.py#L22-L48 |
1,314 | 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, sid) | python | async def enter_captcha(self, url: str, sid: str) -> str:
raise VkCaptchaNeeded(url, sid) | [
"async",
"def",
"enter_captcha",
"(",
"self",
",",
"url",
":",
"str",
",",
"sid",
":",
"str",
")",
"->",
"str",
":",
"raise",
"VkCaptchaNeeded",
"(",
"url",
",",
"sid",
")"
] | 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 | [
"Override",
"this",
"method",
"for",
"processing",
"captcha",
"."
] | d454649d647d524c6753ba1d6ee16613355ec106 | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L104-L112 |
1,315 | 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.feed(html)
p.close()
# Get data from hidden inputs
form_data = dict(p.inputs)
form_url = p.url
form_data['email'] = self.login
form_data['pass'] = self.password
if p.message:
# Show form errors
raise VkAuthError('invalid_data', p.message, form_url, form_data)
elif p.captcha_url:
form_data['captcha_key'] = await self.enter_captcha(
"https://m.vk.com{}".format(p.captcha_url),
form_data['captcha_sid']
)
form_url = "https://m.vk.com{}".format(form_url)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | python | async def _process_auth_form(self, html: str) -> (str, str):
# Parse page
p = AuthPageParser()
p.feed(html)
p.close()
# Get data from hidden inputs
form_data = dict(p.inputs)
form_url = p.url
form_data['email'] = self.login
form_data['pass'] = self.password
if p.message:
# Show form errors
raise VkAuthError('invalid_data', p.message, form_url, form_data)
elif p.captcha_url:
form_data['captcha_key'] = await self.enter_captcha(
"https://m.vk.com{}".format(p.captcha_url),
form_data['captcha_sid']
)
form_url = "https://m.vk.com{}".format(form_url)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | [
"async",
"def",
"_process_auth_form",
"(",
"self",
",",
"html",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"# Parse page",
"p",
"=",
"AuthPageParser",
"(",
")",
"p",
".",
"feed",
"(",
"html",
")",
"p",
".",
"close",
"(",
")",
"# Get data from hidden inputs",
"form_data",
"=",
"dict",
"(",
"p",
".",
"inputs",
")",
"form_url",
"=",
"p",
".",
"url",
"form_data",
"[",
"'email'",
"]",
"=",
"self",
".",
"login",
"form_data",
"[",
"'pass'",
"]",
"=",
"self",
".",
"password",
"if",
"p",
".",
"message",
":",
"# Show form errors",
"raise",
"VkAuthError",
"(",
"'invalid_data'",
",",
"p",
".",
"message",
",",
"form_url",
",",
"form_data",
")",
"elif",
"p",
".",
"captcha_url",
":",
"form_data",
"[",
"'captcha_key'",
"]",
"=",
"await",
"self",
".",
"enter_captcha",
"(",
"\"https://m.vk.com{}\"",
".",
"format",
"(",
"p",
".",
"captcha_url",
")",
",",
"form_data",
"[",
"'captcha_sid'",
"]",
")",
"form_url",
"=",
"\"https://m.vk.com{}\"",
".",
"format",
"(",
"form_url",
")",
"# Send request",
"url",
",",
"html",
"=",
"await",
"self",
".",
"driver",
".",
"post_text",
"(",
"form_url",
",",
"form_data",
")",
"return",
"url",
",",
"html"
] | Parsing data from authorization page and filling the form and submitting the form
:param html: html page
:return: url and html from redirected page | [
"Parsing",
"data",
"from",
"authorization",
"page",
"and",
"filling",
"the",
"form",
"and",
"submitting",
"the",
"form"
] | d454649d647d524c6753ba1d6ee16613355ec106 | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L191-L220 |
1,316 | 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)
p.close()
# Prepare request data
form_url = p.url
form_data = dict(p.inputs)
form_data['remember'] = 0
if p.message:
raise VkAuthError('invalid_data', p.message, form_url, form_data)
form_data['code'] = await self.enter_confirmation_code()
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | python | async def _process_2auth_form(self, html: str) -> (str, str):
# Parse page
p = TwoFactorCodePageParser()
p.feed(html)
p.close()
# Prepare request data
form_url = p.url
form_data = dict(p.inputs)
form_data['remember'] = 0
if p.message:
raise VkAuthError('invalid_data', p.message, form_url, form_data)
form_data['code'] = await self.enter_confirmation_code()
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | [
"async",
"def",
"_process_2auth_form",
"(",
"self",
",",
"html",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"# Parse page",
"p",
"=",
"TwoFactorCodePageParser",
"(",
")",
"p",
".",
"feed",
"(",
"html",
")",
"p",
".",
"close",
"(",
")",
"# Prepare request data",
"form_url",
"=",
"p",
".",
"url",
"form_data",
"=",
"dict",
"(",
"p",
".",
"inputs",
")",
"form_data",
"[",
"'remember'",
"]",
"=",
"0",
"if",
"p",
".",
"message",
":",
"raise",
"VkAuthError",
"(",
"'invalid_data'",
",",
"p",
".",
"message",
",",
"form_url",
",",
"form_data",
")",
"form_data",
"[",
"'code'",
"]",
"=",
"await",
"self",
".",
"enter_confirmation_code",
"(",
")",
"# Send request",
"url",
",",
"html",
"=",
"await",
"self",
".",
"driver",
".",
"post_text",
"(",
"form_url",
",",
"form_data",
")",
"return",
"url",
",",
"html"
] | Parsing two-factor authorization page and filling the code
:param html: html page
:return: url and html from redirected page | [
"Parsing",
"two",
"-",
"factor",
"authorization",
"page",
"and",
"filling",
"the",
"code"
] | d454649d647d524c6753ba1d6ee16613355ec106 | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L222-L244 |
1,317 | 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 = p.url
form_data = dict(p.inputs)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | python | async def _process_access_form(self, html: str) -> (str, str):
# Parse page
p = AccessPageParser()
p.feed(html)
p.close()
form_url = p.url
form_data = dict(p.inputs)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | [
"async",
"def",
"_process_access_form",
"(",
"self",
",",
"html",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"# Parse page",
"p",
"=",
"AccessPageParser",
"(",
")",
"p",
".",
"feed",
"(",
"html",
")",
"p",
".",
"close",
"(",
")",
"form_url",
"=",
"p",
".",
"url",
"form_data",
"=",
"dict",
"(",
"p",
".",
"inputs",
")",
"# Send request",
"url",
",",
"html",
"=",
"await",
"self",
".",
"driver",
".",
"post_text",
"(",
"form_url",
",",
"form_data",
")",
"return",
"url",
",",
"html"
] | Parsing page with access rights
:param html: html page
:return: url and html from redirected page | [
"Parsing",
"page",
"with",
"access",
"rights"
] | d454649d647d524c6753ba1d6ee16613355ec106 | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L246-L263 |
1,318 | 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,
}
params.update(self.base_params)
# invalid mimetype from server
code, response = await self.api._session.driver.get_text(
self.base_url, params,
timeout=2 * self.base_params['wait']
)
if code == 403:
raise VkLongPollError(403, 'smth weth wrong', self.base_url + '/', params)
response = json.loads(response)
failed = response.get('failed')
if not failed:
self.ts = response['ts']
return response
if failed == 1:
self.ts = response['ts']
elif failed == 4:
raise VkLongPollError(
4,
'An invalid version number was passed in the version parameter',
self.base_url + '/',
params
)
else:
self.base_url = None
return await self.wait() | python | async def wait(self, need_pts=False) -> dict:
if not self.base_url:
await self._get_long_poll_server(need_pts)
params = {
'ts': self.ts,
'key': self.key,
}
params.update(self.base_params)
# invalid mimetype from server
code, response = await self.api._session.driver.get_text(
self.base_url, params,
timeout=2 * self.base_params['wait']
)
if code == 403:
raise VkLongPollError(403, 'smth weth wrong', self.base_url + '/', params)
response = json.loads(response)
failed = response.get('failed')
if not failed:
self.ts = response['ts']
return response
if failed == 1:
self.ts = response['ts']
elif failed == 4:
raise VkLongPollError(
4,
'An invalid version number was passed in the version parameter',
self.base_url + '/',
params
)
else:
self.base_url = None
return await self.wait() | [
"async",
"def",
"wait",
"(",
"self",
",",
"need_pts",
"=",
"False",
")",
"->",
"dict",
":",
"if",
"not",
"self",
".",
"base_url",
":",
"await",
"self",
".",
"_get_long_poll_server",
"(",
"need_pts",
")",
"params",
"=",
"{",
"'ts'",
":",
"self",
".",
"ts",
",",
"'key'",
":",
"self",
".",
"key",
",",
"}",
"params",
".",
"update",
"(",
"self",
".",
"base_params",
")",
"# invalid mimetype from server",
"code",
",",
"response",
"=",
"await",
"self",
".",
"api",
".",
"_session",
".",
"driver",
".",
"get_text",
"(",
"self",
".",
"base_url",
",",
"params",
",",
"timeout",
"=",
"2",
"*",
"self",
".",
"base_params",
"[",
"'wait'",
"]",
")",
"if",
"code",
"==",
"403",
":",
"raise",
"VkLongPollError",
"(",
"403",
",",
"'smth weth wrong'",
",",
"self",
".",
"base_url",
"+",
"'/'",
",",
"params",
")",
"response",
"=",
"json",
".",
"loads",
"(",
"response",
")",
"failed",
"=",
"response",
".",
"get",
"(",
"'failed'",
")",
"if",
"not",
"failed",
":",
"self",
".",
"ts",
"=",
"response",
"[",
"'ts'",
"]",
"return",
"response",
"if",
"failed",
"==",
"1",
":",
"self",
".",
"ts",
"=",
"response",
"[",
"'ts'",
"]",
"elif",
"failed",
"==",
"4",
":",
"raise",
"VkLongPollError",
"(",
"4",
",",
"'An invalid version number was passed in the version parameter'",
",",
"self",
".",
"base_url",
"+",
"'/'",
",",
"params",
")",
"else",
":",
"self",
".",
"base_url",
"=",
"None",
"return",
"await",
"self",
".",
"wait",
"(",
")"
] | Send long poll request
:param need_pts: need return the pts field | [
"Send",
"long",
"poll",
"request"
] | d454649d647d524c6753ba1d6ee16613355ec106 | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/longpoll.py#L48-L89 |
1,319 | 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 | [
"def",
"pdf",
"(",
"alphas",
")",
":",
"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 | [
"Returns",
"a",
"Dirichlet",
"PDF",
"function"
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L95-L102 |
1,320 | 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 concentration parameter of the Dirichlet distribution.'''
s = a.sum()
m = a / s
return (m,s) | 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 concentration parameter of the Dirichlet distribution.'''
s = a.sum()
m = a / s
return (m,s) | [
"def",
"meanprecision",
"(",
"a",
")",
":",
"s",
"=",
"a",
".",
"sum",
"(",
")",
"m",
"=",
"a",
"/",
"s",
"return",
"(",
"m",
",",
"s",
")"
] | 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 Dirichlet distribution. | [
"Mean",
"and",
"precision",
"of",
"Dirichlet",
"distribution",
"."
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L104-L121 |
1,321 | 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.sum()) + logp)
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | 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.sum()) + logp)
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | [
"def",
"_fixedpoint",
"(",
"D",
",",
"tol",
"=",
"1e-7",
",",
"maxiter",
"=",
"None",
")",
":",
"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",
".",
"sum",
"(",
")",
")",
"+",
"logp",
")",
"# if norm(a1-a0) < tol:",
"if",
"abs",
"(",
"loglikelihood",
"(",
"D",
",",
"a1",
")",
"-",
"loglikelihood",
"(",
"D",
",",
"a0",
")",
")",
"<",
"tol",
":",
"# much faster",
"return",
"a1",
"a0",
"=",
"a1",
"raise",
"Exception",
"(",
"'Failed to converge after {} iterations, values are {}.'",
".",
"format",
"(",
"maxiter",
",",
"a1",
")",
")"
] | Simple fixed point iteration method for MLE of Dirichlet distribution | [
"Simple",
"fixed",
"point",
"iteration",
"method",
"for",
"MLE",
"of",
"Dirichlet",
"distribution"
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L173-L189 |
1,322 | 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(a)
s0 = 1
m0 = a0/s0
# Start updating
if maxiter is None:
maxiter = MAXINT
for i in xrange(maxiter):
a1 = _fit_s(D, a0, logp, tol=tol)
s1 = sum(a1)
a1 = _fit_m(D, a1, logp, tol=tol)
m = a1/s1
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | 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(a)
s0 = 1
m0 = a0/s0
# Start updating
if maxiter is None:
maxiter = MAXINT
for i in xrange(maxiter):
a1 = _fit_s(D, a0, logp, tol=tol)
s1 = sum(a1)
a1 = _fit_m(D, a1, logp, tol=tol)
m = a1/s1
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | [
"def",
"_meanprecision",
"(",
"D",
",",
"tol",
"=",
"1e-7",
",",
"maxiter",
"=",
"None",
")",
":",
"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",
"(",
"a",
")",
"s0",
"=",
"1",
"m0",
"=",
"a0",
"/",
"s0",
"# Start updating",
"if",
"maxiter",
"is",
"None",
":",
"maxiter",
"=",
"MAXINT",
"for",
"i",
"in",
"xrange",
"(",
"maxiter",
")",
":",
"a1",
"=",
"_fit_s",
"(",
"D",
",",
"a0",
",",
"logp",
",",
"tol",
"=",
"tol",
")",
"s1",
"=",
"sum",
"(",
"a1",
")",
"a1",
"=",
"_fit_m",
"(",
"D",
",",
"a1",
",",
"logp",
",",
"tol",
"=",
"tol",
")",
"m",
"=",
"a1",
"/",
"s1",
"# if norm(a1-a0) < tol:",
"if",
"abs",
"(",
"loglikelihood",
"(",
"D",
",",
"a1",
")",
"-",
"loglikelihood",
"(",
"D",
",",
"a0",
")",
")",
"<",
"tol",
":",
"# much faster",
"return",
"a1",
"a0",
"=",
"a1",
"raise",
"Exception",
"(",
"'Failed to converge after {} iterations, values are {}.'",
".",
"format",
"(",
"maxiter",
",",
"a1",
")",
")"
] | Mean and precision alternating method for MLE of Dirichlet
distribution | [
"Mean",
"and",
"precision",
"alternating",
"method",
"for",
"MLE",
"of",
"Dirichlet",
"distribution"
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L191-L219 |
1,323 | 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)).sum() + mlogp
h = _trigamma(s1) - ((m**2)*_trigamma(s1*m)).sum()
if g + s1 * h < 0:
s1 = 1/(1/s0 + g/h/(s0**2))
if s1 <= 0:
s1 = s0 * exp(-g/(s0*h + g)) # Newton on log s
if s1 <= 0:
s1 = 1/(1/s0 + g/((s0**2)*h + 2*s0*g)) # Newton on 1/s
if s1 <= 0:
s1 = s0 - g/h # Newton
if s1 <= 0:
raise Exception('Unable to update s from {}'.format(s0))
a = s1 * m
if abs(s1 - s0) < tol:
return a
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s1)) | 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)).sum() + mlogp
h = _trigamma(s1) - ((m**2)*_trigamma(s1*m)).sum()
if g + s1 * h < 0:
s1 = 1/(1/s0 + g/h/(s0**2))
if s1 <= 0:
s1 = s0 * exp(-g/(s0*h + g)) # Newton on log s
if s1 <= 0:
s1 = 1/(1/s0 + g/((s0**2)*h + 2*s0*g)) # Newton on 1/s
if s1 <= 0:
s1 = s0 - g/h # Newton
if s1 <= 0:
raise Exception('Unable to update s from {}'.format(s0))
a = s1 * m
if abs(s1 - s0) < tol:
return a
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s1)) | [
"def",
"_fit_s",
"(",
"D",
",",
"a0",
",",
"logp",
",",
"tol",
"=",
"1e-7",
",",
"maxiter",
"=",
"1000",
")",
":",
"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",
")",
")",
".",
"sum",
"(",
")",
"+",
"mlogp",
"h",
"=",
"_trigamma",
"(",
"s1",
")",
"-",
"(",
"(",
"m",
"**",
"2",
")",
"*",
"_trigamma",
"(",
"s1",
"*",
"m",
")",
")",
".",
"sum",
"(",
")",
"if",
"g",
"+",
"s1",
"*",
"h",
"<",
"0",
":",
"s1",
"=",
"1",
"/",
"(",
"1",
"/",
"s0",
"+",
"g",
"/",
"h",
"/",
"(",
"s0",
"**",
"2",
")",
")",
"if",
"s1",
"<=",
"0",
":",
"s1",
"=",
"s0",
"*",
"exp",
"(",
"-",
"g",
"/",
"(",
"s0",
"*",
"h",
"+",
"g",
")",
")",
"# Newton on log s",
"if",
"s1",
"<=",
"0",
":",
"s1",
"=",
"1",
"/",
"(",
"1",
"/",
"s0",
"+",
"g",
"/",
"(",
"(",
"s0",
"**",
"2",
")",
"*",
"h",
"+",
"2",
"*",
"s0",
"*",
"g",
")",
")",
"# Newton on 1/s",
"if",
"s1",
"<=",
"0",
":",
"s1",
"=",
"s0",
"-",
"g",
"/",
"h",
"# Newton",
"if",
"s1",
"<=",
"0",
":",
"raise",
"Exception",
"(",
"'Unable to update s from {}'",
".",
"format",
"(",
"s0",
")",
")",
"a",
"=",
"s1",
"*",
"m",
"if",
"abs",
"(",
"s1",
"-",
"s0",
")",
"<",
"tol",
":",
"return",
"a",
"raise",
"Exception",
"(",
"'Failed to converge after {} iterations, s is {}'",
".",
"format",
"(",
"maxiter",
",",
"s1",
")",
")"
] | Assuming a fixed mean for Dirichlet distribution, maximize likelihood
for preicision a.k.a. s | [
"Assuming",
"a",
"fixed",
"mean",
"for",
"Dirichlet",
"distribution",
"maximize",
"likelihood",
"for",
"preicision",
"a",
".",
"k",
".",
"a",
".",
"s"
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L221-L249 |
1,324 | 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 a1
a0 = a1
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s)) | 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 a1
a0 = a1
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s)) | [
"def",
"_fit_m",
"(",
"D",
",",
"a0",
",",
"logp",
",",
"tol",
"=",
"1e-7",
",",
"maxiter",
"=",
"1000",
")",
":",
"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",
"a1",
"a0",
"=",
"a1",
"raise",
"Exception",
"(",
"'Failed to converge after {} iterations, s is {}'",
".",
"format",
"(",
"maxiter",
",",
"s",
")",
")"
] | With fixed precision s, maximize mean m | [
"With",
"fixed",
"precision",
"s",
"maximize",
"mean",
"m"
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L251-L266 |
1,325 | 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):
condlist = [condlist]
condlist = [asarray(c, dtype=bool) for c in condlist]
n = len(condlist)
zerod = False
# This is a hack to work around problems with NumPy's
# handling of 0-d arrays and boolean indexing with
# numpy.bool_ scalars
if x.ndim == 0:
x = x[None]
zerod = True
newcondlist = []
for k in range(n):
if condlist[k].ndim == 0:
condition = condlist[k][None]
else:
condition = condlist[k]
newcondlist.append(condition)
condlist = newcondlist
if n == n2-1: # compute the "otherwise" condition.
totlist = condlist[0]
for k in range(1, n):
totlist |= condlist[k]
condlist.append(~totlist)
n += 1
if (n != n2):
raise ValueError(
"function list and condition list must be the same")
y = zeros(x.shape, x.dtype)
for k in range(n):
item = funclist[k]
if not callable(item):
y[condlist[k]] = item
else:
vals = x[condlist[k]]
if vals.size > 0:
y[condlist[k]] = item(vals, *args, **kw)
if zerod:
y = y.squeeze()
return y | 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):
condlist = [condlist]
condlist = [asarray(c, dtype=bool) for c in condlist]
n = len(condlist)
zerod = False
# This is a hack to work around problems with NumPy's
# handling of 0-d arrays and boolean indexing with
# numpy.bool_ scalars
if x.ndim == 0:
x = x[None]
zerod = True
newcondlist = []
for k in range(n):
if condlist[k].ndim == 0:
condition = condlist[k][None]
else:
condition = condlist[k]
newcondlist.append(condition)
condlist = newcondlist
if n == n2-1: # compute the "otherwise" condition.
totlist = condlist[0]
for k in range(1, n):
totlist |= condlist[k]
condlist.append(~totlist)
n += 1
if (n != n2):
raise ValueError(
"function list and condition list must be the same")
y = zeros(x.shape, x.dtype)
for k in range(n):
item = funclist[k]
if not callable(item):
y[condlist[k]] = item
else:
vals = x[condlist[k]]
if vals.size > 0:
y[condlist[k]] = item(vals, *args, **kw)
if zerod:
y = y.squeeze()
return y | [
"def",
"_piecewise",
"(",
"x",
",",
"condlist",
",",
"funclist",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"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",
")",
":",
"condlist",
"=",
"[",
"condlist",
"]",
"condlist",
"=",
"[",
"asarray",
"(",
"c",
",",
"dtype",
"=",
"bool",
")",
"for",
"c",
"in",
"condlist",
"]",
"n",
"=",
"len",
"(",
"condlist",
")",
"zerod",
"=",
"False",
"# This is a hack to work around problems with NumPy's",
"# handling of 0-d arrays and boolean indexing with",
"# numpy.bool_ scalars",
"if",
"x",
".",
"ndim",
"==",
"0",
":",
"x",
"=",
"x",
"[",
"None",
"]",
"zerod",
"=",
"True",
"newcondlist",
"=",
"[",
"]",
"for",
"k",
"in",
"range",
"(",
"n",
")",
":",
"if",
"condlist",
"[",
"k",
"]",
".",
"ndim",
"==",
"0",
":",
"condition",
"=",
"condlist",
"[",
"k",
"]",
"[",
"None",
"]",
"else",
":",
"condition",
"=",
"condlist",
"[",
"k",
"]",
"newcondlist",
".",
"append",
"(",
"condition",
")",
"condlist",
"=",
"newcondlist",
"if",
"n",
"==",
"n2",
"-",
"1",
":",
"# compute the \"otherwise\" condition.",
"totlist",
"=",
"condlist",
"[",
"0",
"]",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"totlist",
"|=",
"condlist",
"[",
"k",
"]",
"condlist",
".",
"append",
"(",
"~",
"totlist",
")",
"n",
"+=",
"1",
"if",
"(",
"n",
"!=",
"n2",
")",
":",
"raise",
"ValueError",
"(",
"\"function list and condition list must be the same\"",
")",
"y",
"=",
"zeros",
"(",
"x",
".",
"shape",
",",
"x",
".",
"dtype",
")",
"for",
"k",
"in",
"range",
"(",
"n",
")",
":",
"item",
"=",
"funclist",
"[",
"k",
"]",
"if",
"not",
"callable",
"(",
"item",
")",
":",
"y",
"[",
"condlist",
"[",
"k",
"]",
"]",
"=",
"item",
"else",
":",
"vals",
"=",
"x",
"[",
"condlist",
"[",
"k",
"]",
"]",
"if",
"vals",
".",
"size",
">",
"0",
":",
"y",
"[",
"condlist",
"[",
"k",
"]",
"]",
"=",
"item",
"(",
"vals",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"if",
"zerod",
":",
"y",
"=",
"y",
".",
"squeeze",
"(",
")",
"return",
"y"
] | Fixed version of numpy.piecewise for 0-d arrays | [
"Fixed",
"version",
"of",
"numpy",
".",
"piecewise",
"for",
"0",
"-",
"d",
"arrays"
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L268-L316 |
1,326 | 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 | [
"def",
"_init_a",
"(",
"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 | [
"Initial",
"guess",
"for",
"Dirichlet",
"alpha",
"parameters",
"given",
"data",
"D"
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L318-L322 |
1,327 | 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 == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.scatter`.
:type **kwargs: keyword arguments.'''
if vertexlabels is None:
vertexlabels = ('1','2','3')
projected = cartesian(points)
plt.scatter(projected[:,0], projected[:,1], **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | 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 == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.scatter`.
:type **kwargs: keyword arguments.'''
if vertexlabels is None:
vertexlabels = ('1','2','3')
projected = cartesian(points)
plt.scatter(projected[:,0], projected[:,1], **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | [
"def",
"scatter",
"(",
"points",
",",
"vertexlabels",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"vertexlabels",
"is",
"None",
":",
"vertexlabels",
"=",
"(",
"'1'",
",",
"'2'",
",",
"'3'",
")",
"projected",
"=",
"cartesian",
"(",
"points",
")",
"plt",
".",
"scatter",
"(",
"projected",
"[",
":",
",",
"0",
"]",
",",
"projected",
"[",
":",
",",
"1",
"]",
",",
"*",
"*",
"kwargs",
")",
"_draw_axes",
"(",
"vertexlabels",
")",
"return",
"plt",
".",
"gcf",
"(",
")"
] | 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 vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.scatter`.
:type **kwargs: keyword arguments. | [
"Scatter",
"plot",
"of",
"barycentric",
"2",
"-",
"simplex",
"points",
"on",
"a",
"2D",
"triangle",
"."
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L54-L72 |
1,328 | 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, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.tricontour`.
:type **kwargs: keyword arguments.'''
return _contour(f, vertexlabels, contourfunc=plt.tricontour, **kwargs) | 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, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.tricontour`.
:type **kwargs: keyword arguments.'''
return _contour(f, vertexlabels, contourfunc=plt.tricontour, **kwargs) | [
"def",
"contour",
"(",
"f",
",",
"vertexlabels",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_contour",
"(",
"f",
",",
"vertexlabels",
",",
"contourfunc",
"=",
"plt",
".",
"tricontour",
",",
"*",
"*",
"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, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.tricontour`.
:type **kwargs: keyword arguments. | [
"Contour",
"line",
"plot",
"on",
"a",
"2D",
"triangle",
"of",
"a",
"function",
"evaluated",
"at",
"barycentric",
"2",
"-",
"simplex",
"points",
"."
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L74-L86 |
1,329 | 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, vertexlabels, contourfunc=plt.tricontourf, **kwargs) | 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, vertexlabels, contourfunc=plt.tricontourf, **kwargs) | [
"def",
"contourf",
"(",
"f",
",",
"vertexlabels",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_contour",
"(",
"f",
",",
"vertexlabels",
",",
"contourfunc",
"=",
"plt",
".",
"tricontourf",
",",
"*",
"*",
"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`. | [
"Filled",
"contour",
"plot",
"on",
"a",
"2D",
"triangle",
"of",
"a",
"function",
"evaluated",
"at",
"barycentric",
"2",
"-",
"simplex",
"points",
"."
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L88-L94 |
1,330 | 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','3')
x = np.linspace(0, 1, 100)
y = np.linspace(0, np.sqrt(3.0)/2.0, 100)
points2d = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
points3d = barycentric(points2d)
valid = (points3d.sum(axis=1) == 1.0) & ((0.0 <= points3d).all(axis=1))
points2d = points2d[np.where(valid),:][0]
points3d = points3d[np.where(valid),:][0]
z = f(points3d)
contourfunc(points2d[:,0], points2d[:,1], z, **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | 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','3')
x = np.linspace(0, 1, 100)
y = np.linspace(0, np.sqrt(3.0)/2.0, 100)
points2d = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
points3d = barycentric(points2d)
valid = (points3d.sum(axis=1) == 1.0) & ((0.0 <= points3d).all(axis=1))
points2d = points2d[np.where(valid),:][0]
points3d = points3d[np.where(valid),:][0]
z = f(points3d)
contourfunc(points2d[:,0], points2d[:,1], z, **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | [
"def",
"_contour",
"(",
"f",
",",
"vertexlabels",
"=",
"None",
",",
"contourfunc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"contourfunc",
"is",
"None",
":",
"contourfunc",
"=",
"plt",
".",
"tricontour",
"if",
"vertexlabels",
"is",
"None",
":",
"vertexlabels",
"=",
"(",
"'1'",
",",
"'2'",
",",
"'3'",
")",
"x",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"100",
")",
"y",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"np",
".",
"sqrt",
"(",
"3.0",
")",
"/",
"2.0",
",",
"100",
")",
"points2d",
"=",
"np",
".",
"transpose",
"(",
"[",
"np",
".",
"tile",
"(",
"x",
",",
"len",
"(",
"y",
")",
")",
",",
"np",
".",
"repeat",
"(",
"y",
",",
"len",
"(",
"x",
")",
")",
"]",
")",
"points3d",
"=",
"barycentric",
"(",
"points2d",
")",
"valid",
"=",
"(",
"points3d",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"==",
"1.0",
")",
"&",
"(",
"(",
"0.0",
"<=",
"points3d",
")",
".",
"all",
"(",
"axis",
"=",
"1",
")",
")",
"points2d",
"=",
"points2d",
"[",
"np",
".",
"where",
"(",
"valid",
")",
",",
":",
"]",
"[",
"0",
"]",
"points3d",
"=",
"points3d",
"[",
"np",
".",
"where",
"(",
"valid",
")",
",",
":",
"]",
"[",
"0",
"]",
"z",
"=",
"f",
"(",
"points3d",
")",
"contourfunc",
"(",
"points2d",
"[",
":",
",",
"0",
"]",
",",
"points2d",
"[",
":",
",",
"1",
"]",
",",
"z",
",",
"*",
"*",
"kwargs",
")",
"_draw_axes",
"(",
"vertexlabels",
")",
"return",
"plt",
".",
"gcf",
"(",
")"
] | Workhorse function for the above, where ``contourfunc`` is the contour
plotting function to use for actual plotting. | [
"Workhorse",
"function",
"for",
"the",
"above",
"where",
"contourfunc",
"is",
"the",
"contour",
"plotting",
"function",
"to",
"use",
"for",
"actual",
"plotting",
"."
] | bf39a6d219348cbb4ed95dc195587a9c55c633b9 | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L96-L114 |
1,331 | 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 ``func``.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
VALIDATORS_DISABLED = os.getenv('VALIDATORS_DISABLED', '')
disabled_functions = [x.strip() for x in VALIDATORS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
try:
value = args[0]
except IndexError:
raise ValidatorUsageError('no value was supplied')
if function_name in disabled_functions and not force_run:
return value
else:
updated_kwargs = {key : kwargs[key]
for key in kwargs
if key != 'force_run'}
return func(*args, **updated_kwargs)
return func_wrapper | python | def disable_on_env(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
VALIDATORS_DISABLED = os.getenv('VALIDATORS_DISABLED', '')
disabled_functions = [x.strip() for x in VALIDATORS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
try:
value = args[0]
except IndexError:
raise ValidatorUsageError('no value was supplied')
if function_name in disabled_functions and not force_run:
return value
else:
updated_kwargs = {key : kwargs[key]
for key in kwargs
if key != 'force_run'}
return func(*args, **updated_kwargs)
return func_wrapper | [
"def",
"disable_on_env",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0111, C0103",
"function_name",
"=",
"func",
".",
"__name__",
"VALIDATORS_DISABLED",
"=",
"os",
".",
"getenv",
"(",
"'VALIDATORS_DISABLED'",
",",
"''",
")",
"disabled_functions",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"VALIDATORS_DISABLED",
".",
"split",
"(",
"','",
")",
"]",
"force_run",
"=",
"kwargs",
".",
"get",
"(",
"'force_run'",
",",
"False",
")",
"try",
":",
"value",
"=",
"args",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"ValidatorUsageError",
"(",
"'no value was supplied'",
")",
"if",
"function_name",
"in",
"disabled_functions",
"and",
"not",
"force_run",
":",
"return",
"value",
"else",
":",
"updated_kwargs",
"=",
"{",
"key",
":",
"kwargs",
"[",
"key",
"]",
"for",
"key",
"in",
"kwargs",
"if",
"key",
"!=",
"'force_run'",
"}",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"updated_kwargs",
")",
"return",
"func_wrapper"
] | 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``. | [
"Disable",
"the",
"func",
"called",
"if",
"its",
"name",
"is",
"present",
"in",
"VALIDATORS_DISABLED",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/_decorators.py#L21-L53 |
1,332 | 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(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
CHECKERS_DISABLED = os.getenv('CHECKERS_DISABLED', '')
disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
if function_name in disabled_functions and not force_run:
return True
else:
return func(*args, **kwargs)
return func_wrapper | python | def disable_checker_on_env(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
CHECKERS_DISABLED = os.getenv('CHECKERS_DISABLED', '')
disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
if function_name in disabled_functions and not force_run:
return True
else:
return func(*args, **kwargs)
return func_wrapper | [
"def",
"disable_checker_on_env",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0111, C0103",
"function_name",
"=",
"func",
".",
"__name__",
"CHECKERS_DISABLED",
"=",
"os",
".",
"getenv",
"(",
"'CHECKERS_DISABLED'",
",",
"''",
")",
"disabled_functions",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"CHECKERS_DISABLED",
".",
"split",
"(",
"','",
")",
"]",
"force_run",
"=",
"kwargs",
".",
"get",
"(",
"'force_run'",
",",
"False",
")",
"if",
"function_name",
"in",
"disabled_functions",
"and",
"not",
"force_run",
":",
"return",
"True",
"else",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"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``. | [
"Disable",
"the",
"func",
"called",
"if",
"its",
"name",
"is",
"present",
"in",
"CHECKERS_DISABLED",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/_decorators.py#L56-L79 |
1,333 | 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: :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_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a string if
it is not already. If ``False``, will raise a :class:`ValueError` if ``value``
is not a string. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid string and ``coerce_value``
is ``False``
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum_length = integer(minimum_length, allow_empty = True)
maximum_length = integer(maximum_length, allow_empty = True)
if coerce_value:
value = str(value)
elif not isinstance(value, basestring):
raise errors.CannotCoerceError('value (%s) was not coerced to a string' % value)
if value and maximum_length and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value (%s) exceeds maximum length %s' % (value, maximum_length)
)
if value and minimum_length and len(value) < minimum_length:
if whitespace_padding:
value = value.ljust(minimum_length, ' ')
else:
raise errors.MinimumLengthError(
'value (%s) is below the minimum length %s' % (value, minimum_length)
)
return value | python | def string(value,
allow_empty = False,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum_length = integer(minimum_length, allow_empty = True)
maximum_length = integer(maximum_length, allow_empty = True)
if coerce_value:
value = str(value)
elif not isinstance(value, basestring):
raise errors.CannotCoerceError('value (%s) was not coerced to a string' % value)
if value and maximum_length and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value (%s) exceeds maximum length %s' % (value, maximum_length)
)
if value and minimum_length and len(value) < minimum_length:
if whitespace_padding:
value = value.ljust(minimum_length, ' ')
else:
raise errors.MinimumLengthError(
'value (%s) is below the minimum length %s' % (value, minimum_length)
)
return value | [
"def",
"string",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"coerce_value",
"=",
"False",
",",
"minimum_length",
"=",
"None",
",",
"maximum_length",
"=",
"None",
",",
"whitespace_padding",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"minimum_length",
"=",
"integer",
"(",
"minimum_length",
",",
"allow_empty",
"=",
"True",
")",
"maximum_length",
"=",
"integer",
"(",
"maximum_length",
",",
"allow_empty",
"=",
"True",
")",
"if",
"coerce_value",
":",
"value",
"=",
"str",
"(",
"value",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'value (%s) was not coerced to a string'",
"%",
"value",
")",
"if",
"value",
"and",
"maximum_length",
"and",
"len",
"(",
"value",
")",
">",
"maximum_length",
":",
"raise",
"errors",
".",
"MaximumLengthError",
"(",
"'value (%s) exceeds maximum length %s'",
"%",
"(",
"value",
",",
"maximum_length",
")",
")",
"if",
"value",
"and",
"minimum_length",
"and",
"len",
"(",
"value",
")",
"<",
"minimum_length",
":",
"if",
"whitespace_padding",
":",
"value",
"=",
"value",
".",
"ljust",
"(",
"minimum_length",
",",
"' '",
")",
"else",
":",
"raise",
"errors",
".",
"MinimumLengthError",
"(",
"'value (%s) is below the minimum length %s'",
"%",
"(",
"value",
",",
"minimum_length",
")",
")",
"return",
"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_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a string if
it is not already. If ``False``, will raise a :class:`ValueError` if ``value``
is not a string. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid string and ``coerce_value``
is ``False``
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length`` | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"string",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L172-L245 |
1,334 | 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 ``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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to :class:`str <python:str>` and
:class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: iterable / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotAnIterableError: if ``value`` is not a valid iterable or
:obj:`None <python:None>`
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is None:
return None
minimum_length = integer(minimum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum_length = integer(maximum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
if isinstance(value, forbid_literals) or not hasattr(value, '__iter__'):
raise errors.NotAnIterableError('value type (%s) not iterable' % type(value))
if value and minimum_length is not None and len(value) < minimum_length:
raise errors.MinimumLengthError(
'value has fewer items than the minimum length %s' % minimum_length
)
if value and maximum_length is not None and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value has more items than the maximum length %s' % maximum_length
)
return value | python | def iterable(value,
allow_empty = False,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is None:
return None
minimum_length = integer(minimum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum_length = integer(maximum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
if isinstance(value, forbid_literals) or not hasattr(value, '__iter__'):
raise errors.NotAnIterableError('value type (%s) not iterable' % type(value))
if value and minimum_length is not None and len(value) < minimum_length:
raise errors.MinimumLengthError(
'value has fewer items than the minimum length %s' % minimum_length
)
if value and maximum_length is not None and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value has more items than the maximum length %s' % maximum_length
)
return value | [
"def",
"iterable",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"forbid_literals",
"=",
"(",
"str",
",",
"bytes",
")",
",",
"minimum_length",
"=",
"None",
",",
"maximum_length",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"value",
"is",
"None",
":",
"return",
"None",
"minimum_length",
"=",
"integer",
"(",
"minimum_length",
",",
"allow_empty",
"=",
"True",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"maximum_length",
"=",
"integer",
"(",
"maximum_length",
",",
"allow_empty",
"=",
"True",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"if",
"isinstance",
"(",
"value",
",",
"forbid_literals",
")",
"or",
"not",
"hasattr",
"(",
"value",
",",
"'__iter__'",
")",
":",
"raise",
"errors",
".",
"NotAnIterableError",
"(",
"'value type (%s) not iterable'",
"%",
"type",
"(",
"value",
")",
")",
"if",
"value",
"and",
"minimum_length",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
"<",
"minimum_length",
":",
"raise",
"errors",
".",
"MinimumLengthError",
"(",
"'value has fewer items than the minimum length %s'",
"%",
"minimum_length",
")",
"if",
"value",
"and",
"maximum_length",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
">",
"maximum_length",
":",
"raise",
"errors",
".",
"MaximumLengthError",
"(",
"'value has more items than the maximum length %s'",
"%",
"maximum_length",
")",
"return",
"value"
] | 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. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to :class:`str <python:str>` and
:class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: iterable / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotAnIterableError: if ``value`` is not a valid iterable or
:obj:`None <python:None>`
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length`` | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"iterable",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L249-L311 |
1,335 | 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:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
"""
if not value and allow_empty:
return None
elif not value:
raise errors.EmptyValueError('value was empty')
return value | python | def not_empty(value,
allow_empty = False,
**kwargs):
if not value and allow_empty:
return None
elif not value:
raise errors.EmptyValueError('value was empty')
return value | [
"def",
"not_empty",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"allow_empty",
":",
"return",
"None",
"elif",
"not",
"value",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value was empty'",
")",
"return",
"value"
] | 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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` | [
"Validate",
"that",
"value",
"is",
"not",
"empty",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L343-L365 |
1,336 | 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 class, or
function, etc.) name.
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
parse('%s = None' % value)
except (SyntaxError, ValueError, TypeError):
raise errors.InvalidVariableNameError(
'value (%s) is not a valid variable name' % value
)
return value | python | def variable_name(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
parse('%s = None' % value)
except (SyntaxError, ValueError, TypeError):
raise errors.InvalidVariableNameError(
'value (%s) is not a valid variable name' % value
)
return value | [
"def",
"variable_name",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"try",
":",
"parse",
"(",
"'%s = None'",
"%",
"value",
")",
"except",
"(",
"SyntaxError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"errors",
".",
"InvalidVariableNameError",
"(",
"'value (%s) is not a valid variable name'",
"%",
"value",
")",
"return",
"value"
] | 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_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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty | [
"Validate",
"that",
"the",
"value",
"is",
"a",
"valid",
"Python",
"variable",
"name",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L369-L406 |
1,337 | 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 a ``$schema`` property, the schema will be assumed to conform to
Draft 7.
.. hint::
If either ``value`` or ``schema`` 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. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param schema: An optional JSON Schema against which ``value`` will be validated.
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :class:`list <python:list>` of
:class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotJSONError: if ``value`` cannot be deserialized from JSON
:raises NotJSONSchemaError: if ``schema`` is not a valid JSON Schema object
:raises JSONValidationError: if ``value`` does not validate against the JSON Schema
"""
original_value = value
original_schema = schema
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not json_serializer:
json_serializer = json_
if isinstance(value, str):
try:
value = json_serializer.loads(value)
except Exception:
raise errors.CannotCoerceError(
'value (%s) cannot be deserialized from JSON' % original_value
)
if isinstance(schema, str):
try:
schema = dict(schema,
allow_empty = allow_empty,
json_serializer = json_serializer,
**kwargs)
except Exception:
raise errors.CannotCoerceError(
'schema (%s) cannot be coerced to a dict' % original_schema
)
if not isinstance(value, (list, dict_)):
raise errors.NotJSONError('value (%s) is not a JSON object' % original_value)
if original_schema and not isinstance(schema, dict_):
raise errors.NotJSONError('schema (%s) is not a JSON object' % original_schema)
if not schema:
return value
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as error:
raise errors.JSONValidationError(error.message)
except jsonschema.exceptions.SchemaError as error:
raise errors.NotJSONSchemaError(error.message)
return value | python | def json(value,
schema = None,
allow_empty = False,
json_serializer = None,
**kwargs):
original_value = value
original_schema = schema
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not json_serializer:
json_serializer = json_
if isinstance(value, str):
try:
value = json_serializer.loads(value)
except Exception:
raise errors.CannotCoerceError(
'value (%s) cannot be deserialized from JSON' % original_value
)
if isinstance(schema, str):
try:
schema = dict(schema,
allow_empty = allow_empty,
json_serializer = json_serializer,
**kwargs)
except Exception:
raise errors.CannotCoerceError(
'schema (%s) cannot be coerced to a dict' % original_schema
)
if not isinstance(value, (list, dict_)):
raise errors.NotJSONError('value (%s) is not a JSON object' % original_value)
if original_schema and not isinstance(schema, dict_):
raise errors.NotJSONError('schema (%s) is not a JSON object' % original_schema)
if not schema:
return value
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as error:
raise errors.JSONValidationError(error.message)
except jsonschema.exceptions.SchemaError as error:
raise errors.NotJSONSchemaError(error.message)
return value | [
"def",
"json",
"(",
"value",
",",
"schema",
"=",
"None",
",",
"allow_empty",
"=",
"False",
",",
"json_serializer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"original_value",
"=",
"value",
"original_schema",
"=",
"schema",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"if",
"not",
"json_serializer",
":",
"json_serializer",
"=",
"json_",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"try",
":",
"value",
"=",
"json_serializer",
".",
"loads",
"(",
"value",
")",
"except",
"Exception",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'value (%s) cannot be deserialized from JSON'",
"%",
"original_value",
")",
"if",
"isinstance",
"(",
"schema",
",",
"str",
")",
":",
"try",
":",
"schema",
"=",
"dict",
"(",
"schema",
",",
"allow_empty",
"=",
"allow_empty",
",",
"json_serializer",
"=",
"json_serializer",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'schema (%s) cannot be coerced to a dict'",
"%",
"original_schema",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"dict_",
")",
")",
":",
"raise",
"errors",
".",
"NotJSONError",
"(",
"'value (%s) is not a JSON object'",
"%",
"original_value",
")",
"if",
"original_schema",
"and",
"not",
"isinstance",
"(",
"schema",
",",
"dict_",
")",
":",
"raise",
"errors",
".",
"NotJSONError",
"(",
"'schema (%s) is not a JSON object'",
"%",
"original_schema",
")",
"if",
"not",
"schema",
":",
"return",
"value",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"value",
",",
"schema",
")",
"except",
"jsonschema",
".",
"exceptions",
".",
"ValidationError",
"as",
"error",
":",
"raise",
"errors",
".",
"JSONValidationError",
"(",
"error",
".",
"message",
")",
"except",
"jsonschema",
".",
"exceptions",
".",
"SchemaError",
"as",
"error",
":",
"raise",
"errors",
".",
"NotJSONSchemaError",
"(",
"error",
".",
"message",
")",
"return",
"value"
] | 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 ``schema`` 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. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param schema: An optional JSON Schema against which ``value`` will be validated.
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :class:`list <python:list>` of
:class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotJSONError: if ``value`` cannot be deserialized from JSON
:raises NotJSONSchemaError: if ``schema`` is not a valid JSON Schema object
:raises JSONValidationError: if ``value`` does not validate against the JSON Schema | [
"Validate",
"that",
"value",
"conforms",
"to",
"the",
"supplied",
"JSON",
"Schema",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L474-L568 |
1,338 | 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 :obj:`None <python:None>`. If ``False``, raises an
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if ``value`` cannot be coerced to a numeric form
"""
if maximum is None:
maximum = POSITIVE_INFINITY
else:
maximum = numeric(maximum)
if minimum is None:
minimum = NEGATIVE_INFINITY
else:
minimum = numeric(minimum)
if value is None and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is not None:
if isinstance(value, str):
try:
value = float_(value)
except (ValueError, TypeError):
raise errors.CannotCoerceError(
'value (%s) cannot be coerced to a numeric form' % value
)
elif not isinstance(value, numeric_types):
raise errors.CannotCoerceError(
'value (%s) is not a numeric type, was %s' % (value,
type(value))
)
if value is not None and value > maximum:
raise errors.MaximumValueError(
'value (%s) exceeds maximum (%s)' % (value, maximum)
)
if value is not None and value < minimum:
raise errors.MinimumValueError(
'value (%s) less than minimum (%s)' % (value, minimum)
)
return value | python | def numeric(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
if maximum is None:
maximum = POSITIVE_INFINITY
else:
maximum = numeric(maximum)
if minimum is None:
minimum = NEGATIVE_INFINITY
else:
minimum = numeric(minimum)
if value is None and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is not None:
if isinstance(value, str):
try:
value = float_(value)
except (ValueError, TypeError):
raise errors.CannotCoerceError(
'value (%s) cannot be coerced to a numeric form' % value
)
elif not isinstance(value, numeric_types):
raise errors.CannotCoerceError(
'value (%s) is not a numeric type, was %s' % (value,
type(value))
)
if value is not None and value > maximum:
raise errors.MaximumValueError(
'value (%s) exceeds maximum (%s)' % (value, maximum)
)
if value is not None and value < minimum:
raise errors.MinimumValueError(
'value (%s) less than minimum (%s)' % (value, minimum)
)
return value | [
"def",
"numeric",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"maximum",
"is",
"None",
":",
"maximum",
"=",
"POSITIVE_INFINITY",
"else",
":",
"maximum",
"=",
"numeric",
"(",
"maximum",
")",
"if",
"minimum",
"is",
"None",
":",
"minimum",
"=",
"NEGATIVE_INFINITY",
"else",
":",
"minimum",
"=",
"numeric",
"(",
"minimum",
")",
"if",
"value",
"is",
"None",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"value",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"try",
":",
"value",
"=",
"float_",
"(",
"value",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'value (%s) cannot be coerced to a numeric form'",
"%",
"value",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"numeric_types",
")",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'value (%s) is not a numeric type, was %s'",
"%",
"(",
"value",
",",
"type",
"(",
"value",
")",
")",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
">",
"maximum",
":",
"raise",
"errors",
".",
"MaximumValueError",
"(",
"'value (%s) exceeds maximum (%s)'",
"%",
"(",
"value",
",",
"maximum",
")",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
"<",
"minimum",
":",
"raise",
"errors",
".",
"MinimumValueError",
"(",
"'value (%s) less than minimum (%s)'",
"%",
"(",
"value",
",",
"minimum",
")",
")",
"return",
"value"
] | 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
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if ``value`` cannot be coerced to a numeric form | [
"Validate",
"that",
"value",
"is",
"a",
"numeric",
"value",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1225-L1295 |
1,339 | 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.
: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:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: the type returned by ``coercion_function``
:raises CoercionFunctionEmptyError: if ``coercion_function`` is empty
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises CannotCoerceError: if ``coercion_function`` raises an
:class:`ValueError <python:ValueError>`, :class:`TypeError <python:TypeError>`,
:class:`AttributeError <python:AttributeError>`,
:class:`IndexError <python:IndexError>, or
:class:`SyntaxError <python:SyntaxError>`
"""
if coercion_function is None:
raise errors.CoercionFunctionEmptyError('coercion_function cannot be empty')
elif not hasattr(coercion_function, '__call__'):
raise errors.NotCallableError('coercion_function must be callable')
value = numeric(value, # pylint: disable=E1123
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum,
force_run = True)
if value is not None:
try:
value = coercion_function(value)
except (ValueError, TypeError, AttributeError, IndexError, SyntaxError):
raise errors.CannotCoerceError(
'cannot coerce value (%s) to desired type' % value
)
return value | python | def _numeric_coercion(value,
coercion_function = None,
allow_empty = False,
minimum = None,
maximum = None):
if coercion_function is None:
raise errors.CoercionFunctionEmptyError('coercion_function cannot be empty')
elif not hasattr(coercion_function, '__call__'):
raise errors.NotCallableError('coercion_function must be callable')
value = numeric(value, # pylint: disable=E1123
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum,
force_run = True)
if value is not None:
try:
value = coercion_function(value)
except (ValueError, TypeError, AttributeError, IndexError, SyntaxError):
raise errors.CannotCoerceError(
'cannot coerce value (%s) to desired type' % value
)
return value | [
"def",
"_numeric_coercion",
"(",
"value",
",",
"coercion_function",
"=",
"None",
",",
"allow_empty",
"=",
"False",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
")",
":",
"if",
"coercion_function",
"is",
"None",
":",
"raise",
"errors",
".",
"CoercionFunctionEmptyError",
"(",
"'coercion_function cannot be empty'",
")",
"elif",
"not",
"hasattr",
"(",
"coercion_function",
",",
"'__call__'",
")",
":",
"raise",
"errors",
".",
"NotCallableError",
"(",
"'coercion_function must be callable'",
")",
"value",
"=",
"numeric",
"(",
"value",
",",
"# pylint: disable=E1123",
"allow_empty",
"=",
"allow_empty",
",",
"minimum",
"=",
"minimum",
",",
"maximum",
"=",
"maximum",
",",
"force_run",
"=",
"True",
")",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"coercion_function",
"(",
"value",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"AttributeError",
",",
"IndexError",
",",
"SyntaxError",
")",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'cannot coerce value (%s) to desired type'",
"%",
"value",
")",
"return",
"value"
] | 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:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: the type returned by ``coercion_function``
:raises CoercionFunctionEmptyError: if ``coercion_function`` is empty
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises CannotCoerceError: if ``coercion_function`` raises an
:class:`ValueError <python:ValueError>`, :class:`TypeError <python:TypeError>`,
:class:`AttributeError <python:AttributeError>`,
:class:`IndexError <python:IndexError>, or
:class:`SyntaxError <python:SyntaxError>` | [
"Validate",
"that",
"value",
"is",
"numeric",
"and",
"coerce",
"using",
"coercion_function",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1543-L1594 |
1,340 | 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:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The path represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty
:raises NotPathlikeError: if ``value`` is not a valid path-like object
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if hasattr(os, 'PathLike'):
if not isinstance(value, (str, bytes, int, os.PathLike)): # pylint: disable=E1101
raise errors.NotPathlikeError('value (%s) is path-like' % value)
else:
if not isinstance(value, int):
try:
os.path.exists(value)
except TypeError:
raise errors.NotPathlikeError('value (%s) is not path-like' % value)
return value | python | def path(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if hasattr(os, 'PathLike'):
if not isinstance(value, (str, bytes, int, os.PathLike)): # pylint: disable=E1101
raise errors.NotPathlikeError('value (%s) is path-like' % value)
else:
if not isinstance(value, int):
try:
os.path.exists(value)
except TypeError:
raise errors.NotPathlikeError('value (%s) is not path-like' % value)
return value | [
"def",
"path",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"if",
"hasattr",
"(",
"os",
",",
"'PathLike'",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"bytes",
",",
"int",
",",
"os",
".",
"PathLike",
")",
")",
":",
"# pylint: disable=E1101",
"raise",
"errors",
".",
"NotPathlikeError",
"(",
"'value (%s) is path-like'",
"%",
"value",
")",
"else",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"try",
":",
"os",
".",
"path",
".",
"exists",
"(",
"value",
")",
"except",
"TypeError",
":",
"raise",
"errors",
".",
"NotPathlikeError",
"(",
"'value (%s) is not path-like'",
"%",
"value",
")",
"return",
"value"
] | 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 empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The path represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty
:raises NotPathlikeError: if ``value`` is not a valid path-like object | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"path",
"-",
"like",
"object",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1666-L1701 |
1,341 | 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 empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True) # pylint: disable=E1123
if not os.path.exists(value):
raise errors.PathExistsError('value (%s) not found' % value)
return value | python | def path_exists(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True) # pylint: disable=E1123
if not os.path.exists(value):
raise errors.PathExistsError('value (%s) not found' % value)
return value | [
"def",
"path_exists",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"value",
"=",
"path",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"value",
")",
":",
"raise",
"errors",
".",
"PathExistsError",
"(",
"'value (%s) not found'",
"%",
"value",
")",
"return",
"value"
] | 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.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist | [
"Validate",
"that",
"value",
"is",
"a",
"path",
"-",
"like",
"object",
"that",
"exists",
"on",
"the",
"local",
"filesystem",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1705-L1738 |
1,342 | 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 ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isfile(value):
raise errors.NotAFileError('value (%s) is not a file')
return value | python | def file_exists(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isfile(value):
raise errors.NotAFileError('value (%s) is not a file')
return value | [
"def",
"file_exists",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"value",
"=",
"path_exists",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"value",
")",
":",
"raise",
"errors",
".",
"NotAFileError",
"(",
"'value (%s) is not a file'",
")",
"return",
"value"
] | 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>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"file",
"that",
"exists",
"on",
"the",
"local",
"filesystem",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1742-L1775 |
1,343 | 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
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotADirectoryError: if ``value`` is not a valid directory
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isdir(value):
raise errors.NotADirectoryError('value (%s) is not a directory' % value)
return value | python | def directory_exists(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isdir(value):
raise errors.NotADirectoryError('value (%s) is not a directory' % value)
return value | [
"def",
"directory_exists",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"value",
"=",
"path_exists",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"value",
")",
":",
"raise",
"errors",
".",
"NotADirectoryError",
"(",
"'value (%s) is not a directory'",
"%",
"value",
")",
"return",
"value"
] | 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.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotADirectoryError: if ``value`` is not a valid directory | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"directory",
"that",
"exists",
"on",
"the",
"local",
"filesystem",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1779-L1813 |
1,344 | 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
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The path to a file on the local filesystem whose readability
is to be validated.
:type value: Path-like object
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated path-like object or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
:raises NotReadableError: if ``value`` cannot be opened for reading
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True) # pylint: disable=E1123
try:
with open(value, mode='r'):
pass
except (OSError, IOError):
raise errors.NotReadableError('file at %s could not be opened for '
'reading' % value)
return value | python | def readable(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True) # pylint: disable=E1123
try:
with open(value, mode='r'):
pass
except (OSError, IOError):
raise errors.NotReadableError('file at %s could not be opened for '
'reading' % value)
return value | [
"def",
"readable",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"value",
"=",
"file_exists",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"try",
":",
"with",
"open",
"(",
"value",
",",
"mode",
"=",
"'r'",
")",
":",
"pass",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"raise",
"errors",
".",
"NotReadableError",
"(",
"'file at %s could not be opened for '",
"'reading'",
"%",
"value",
")",
"return",
"value"
] | 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/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The path to a file on the local filesystem whose readability
is to be validated.
:type value: Path-like object
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated path-like object or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
:raises NotReadableError: if ``value`` cannot be opened for reading | [
"Validate",
"that",
"value",
"is",
"a",
"path",
"to",
"a",
"readable",
"file",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1817-L1880 |
1,345 | 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
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotWriteableError: if ``value`` cannot be opened for writing
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.W_OK)
if not is_valid:
raise errors.NotWriteableError('writing not allowed for file at %s' % value)
return value | python | def writeable(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.W_OK)
if not is_valid:
raise errors.NotWriteableError('writing not allowed for file at %s' % value)
return value | [
"def",
"writeable",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"value",
"=",
"path",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"if",
"sys",
".",
"platform",
"in",
"[",
"'win32'",
",",
"'cygwin'",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'not supported on Windows'",
")",
"is_valid",
"=",
"os",
".",
"access",
"(",
"value",
",",
"mode",
"=",
"os",
".",
"W_OK",
")",
"if",
"not",
"is_valid",
":",
"raise",
"errors",
".",
"NotWriteableError",
"(",
"'writing not allowed for file at %s'",
"%",
"value",
")",
"return",
"value"
] | 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 file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotWriteableError: if ``value`` cannot be opened for writing | [
"Validate",
"that",
"value",
"is",
"a",
"path",
"to",
"a",
"writeable",
"file",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1883-L1968 |
1,346 | 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 the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the executability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is executable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotAFileError: if ``value`` does not exist on the local file system
:raises NotExecutableError: if ``value`` cannot be executed
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.X_OK)
if not is_valid:
raise errors.NotExecutableError('execution not allowed for file at %s' % value)
return value | python | def executable(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.X_OK)
if not is_valid:
raise errors.NotExecutableError('execution not allowed for file at %s' % value)
return value | [
"def",
"executable",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"value",
"=",
"file_exists",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"if",
"sys",
".",
"platform",
"in",
"[",
"'win32'",
",",
"'cygwin'",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'not supported on Windows'",
")",
"is_valid",
"=",
"os",
".",
"access",
"(",
"value",
",",
"mode",
"=",
"os",
".",
"X_OK",
")",
"if",
"not",
"is_valid",
":",
"raise",
"errors",
".",
"NotExecutableError",
"(",
"'execution not allowed for file at %s'",
"%",
"value",
")",
"return",
"value"
] | 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 file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the executability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is executable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotAFileError: if ``value`` does not exist on the local file system
:raises NotExecutableError: if ``value`` cannot be executed | [
"Validate",
"that",
"value",
"is",
"a",
"path",
"to",
"an",
"executable",
"file",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1971-L2049 |
1,347 | 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/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
`RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
: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_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will raise a :class:`InvalidURLError` if ``value`` is a special IP address. Defaults
to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidURLError: if ``value`` is not a valid URL or
empty with ``allow_empty`` set to ``True``
"""
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
value = value.lower()
is_valid = False
stripped_value = None
for protocol in URL_PROTOCOLS:
if protocol in value:
stripped_value = value.replace(protocol, '')
for special_use_domain in SPECIAL_USE_DOMAIN_NAMES:
if special_use_domain in value:
if stripped_value:
try:
domain(stripped_value,
allow_empty = False,
is_recursive = is_recursive)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid and allow_special_ips:
try:
ip_address(stripped_value, allow_empty = False)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid:
is_valid = URL_REGEX.match(value)
if not is_valid and allow_special_ips:
is_valid = URL_SPECIAL_IP_REGEX.match(value)
if not is_valid:
raise errors.InvalidURLError('value (%s) is not a valid URL' % value)
return value | python | def url(value,
allow_empty = False,
allow_special_ips = False,
**kwargs):
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
value = value.lower()
is_valid = False
stripped_value = None
for protocol in URL_PROTOCOLS:
if protocol in value:
stripped_value = value.replace(protocol, '')
for special_use_domain in SPECIAL_USE_DOMAIN_NAMES:
if special_use_domain in value:
if stripped_value:
try:
domain(stripped_value,
allow_empty = False,
is_recursive = is_recursive)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid and allow_special_ips:
try:
ip_address(stripped_value, allow_empty = False)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid:
is_valid = URL_REGEX.match(value)
if not is_valid and allow_special_ips:
is_valid = URL_SPECIAL_IP_REGEX.match(value)
if not is_valid:
raise errors.InvalidURLError('value (%s) is not a valid URL' % value)
return value | [
"def",
"url",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"allow_special_ips",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"is_recursive",
"=",
"kwargs",
".",
"pop",
"(",
"'is_recursive'",
",",
"False",
")",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'value must be a valid string, '",
"'was %s'",
"%",
"type",
"(",
"value",
")",
")",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"is_valid",
"=",
"False",
"stripped_value",
"=",
"None",
"for",
"protocol",
"in",
"URL_PROTOCOLS",
":",
"if",
"protocol",
"in",
"value",
":",
"stripped_value",
"=",
"value",
".",
"replace",
"(",
"protocol",
",",
"''",
")",
"for",
"special_use_domain",
"in",
"SPECIAL_USE_DOMAIN_NAMES",
":",
"if",
"special_use_domain",
"in",
"value",
":",
"if",
"stripped_value",
":",
"try",
":",
"domain",
"(",
"stripped_value",
",",
"allow_empty",
"=",
"False",
",",
"is_recursive",
"=",
"is_recursive",
")",
"is_valid",
"=",
"True",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"if",
"not",
"is_valid",
"and",
"allow_special_ips",
":",
"try",
":",
"ip_address",
"(",
"stripped_value",
",",
"allow_empty",
"=",
"False",
")",
"is_valid",
"=",
"True",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"if",
"not",
"is_valid",
":",
"is_valid",
"=",
"URL_REGEX",
".",
"match",
"(",
"value",
")",
"if",
"not",
"is_valid",
"and",
"allow_special_ips",
":",
"is_valid",
"=",
"URL_SPECIAL_IP_REGEX",
".",
"match",
"(",
"value",
")",
"if",
"not",
"is_valid",
":",
"raise",
"errors",
".",
"InvalidURLError",
"(",
"'value (%s) is not a valid URL'",
"%",
"value",
")",
"return",
"value"
] | 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.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
: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_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will raise a :class:`InvalidURLError` if ``value`` is a special IP address. Defaults
to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidURLError: if ``value`` is not a valid URL or
empty with ``allow_empty`` set to ``True`` | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"URL",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2216-L2306 |
1,348 | 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.
.. note::
This validator checks to validate that ``value`` resembles a valid
domain name. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:[email protected]``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
.. hint::
Leading and trailing whitespace will be automatically stripped.
: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_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will raise a :class:`InvalidDomainError` if ``value`` is an IP
address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidDomainError: if ``value`` is not a valid domain name or
empty with ``allow_empty`` set to ``True``
:raises SlashInDomainError: if ``value`` contains a slash or backslash
:raises AtInDomainError: if ``value`` contains an ``@`` symbol
:raises ColonInDomainError: if ``value`` contains a ``:`` symbol
:raises WhitespaceInDomainError: if ``value`` contains whitespace
"""
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '/' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "/"')
if '\\' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "\\"')
if '@' in value:
raise errors.AtInDomainError('valid domain name cannot contain "@"')
if ':' in value:
raise errors.ColonInDomainError('valid domain name cannot contain ":"')
value = value.strip().lower()
for item in string_.whitespace:
if item in value:
raise errors.WhitespaceInDomainError('valid domain name cannot contain '
'whitespace')
if value in SPECIAL_USE_DOMAIN_NAMES:
return value
if allow_ips:
try:
ip_address(value, allow_empty = allow_empty)
is_valid = True
except (ValueError, TypeError, AttributeError):
is_valid = False
if is_valid:
return value
is_valid = DOMAIN_REGEX.match(value)
if not is_valid and not is_recursive:
with_prefix = 'http://' + value
try:
url(with_prefix, force_run = True, is_recursive = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidDomainError('value (%s) is not a valid domain' % value)
return value | python | def domain(value,
allow_empty = False,
allow_ips = False,
**kwargs):
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '/' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "/"')
if '\\' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "\\"')
if '@' in value:
raise errors.AtInDomainError('valid domain name cannot contain "@"')
if ':' in value:
raise errors.ColonInDomainError('valid domain name cannot contain ":"')
value = value.strip().lower()
for item in string_.whitespace:
if item in value:
raise errors.WhitespaceInDomainError('valid domain name cannot contain '
'whitespace')
if value in SPECIAL_USE_DOMAIN_NAMES:
return value
if allow_ips:
try:
ip_address(value, allow_empty = allow_empty)
is_valid = True
except (ValueError, TypeError, AttributeError):
is_valid = False
if is_valid:
return value
is_valid = DOMAIN_REGEX.match(value)
if not is_valid and not is_recursive:
with_prefix = 'http://' + value
try:
url(with_prefix, force_run = True, is_recursive = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidDomainError('value (%s) is not a valid domain' % value)
return value | [
"def",
"domain",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"allow_ips",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"is_recursive",
"=",
"kwargs",
".",
"pop",
"(",
"'is_recursive'",
",",
"False",
")",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'value must be a valid string, '",
"'was %s'",
"%",
"type",
"(",
"value",
")",
")",
"if",
"'/'",
"in",
"value",
":",
"raise",
"errors",
".",
"SlashInDomainError",
"(",
"'valid domain name cannot contain \"/\"'",
")",
"if",
"'\\\\'",
"in",
"value",
":",
"raise",
"errors",
".",
"SlashInDomainError",
"(",
"'valid domain name cannot contain \"\\\\\"'",
")",
"if",
"'@'",
"in",
"value",
":",
"raise",
"errors",
".",
"AtInDomainError",
"(",
"'valid domain name cannot contain \"@\"'",
")",
"if",
"':'",
"in",
"value",
":",
"raise",
"errors",
".",
"ColonInDomainError",
"(",
"'valid domain name cannot contain \":\"'",
")",
"value",
"=",
"value",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"item",
"in",
"string_",
".",
"whitespace",
":",
"if",
"item",
"in",
"value",
":",
"raise",
"errors",
".",
"WhitespaceInDomainError",
"(",
"'valid domain name cannot contain '",
"'whitespace'",
")",
"if",
"value",
"in",
"SPECIAL_USE_DOMAIN_NAMES",
":",
"return",
"value",
"if",
"allow_ips",
":",
"try",
":",
"ip_address",
"(",
"value",
",",
"allow_empty",
"=",
"allow_empty",
")",
"is_valid",
"=",
"True",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"AttributeError",
")",
":",
"is_valid",
"=",
"False",
"if",
"is_valid",
":",
"return",
"value",
"is_valid",
"=",
"DOMAIN_REGEX",
".",
"match",
"(",
"value",
")",
"if",
"not",
"is_valid",
"and",
"not",
"is_recursive",
":",
"with_prefix",
"=",
"'http://'",
"+",
"value",
"try",
":",
"url",
"(",
"with_prefix",
",",
"force_run",
"=",
"True",
",",
"is_recursive",
"=",
"True",
")",
"# pylint: disable=E1123",
"except",
"ValueError",
":",
"raise",
"errors",
".",
"InvalidDomainError",
"(",
"'value (%s) is not a valid domain'",
"%",
"value",
")",
"return",
"value"
] | 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. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:[email protected]``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
.. hint::
Leading and trailing whitespace will be automatically stripped.
: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_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will raise a :class:`InvalidDomainError` if ``value`` is an IP
address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidDomainError: if ``value`` is not a valid domain name or
empty with ``allow_empty`` set to ``True``
:raises SlashInDomainError: if ``value`` contains a slash or backslash
:raises AtInDomainError: if ``value`` contains an ``@`` symbol
:raises ColonInDomainError: if ``value`` contains a ``:`` symbol
:raises WhitespaceInDomainError: if ``value`` contains whitespace | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"domain",
"name",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2310-L2418 |
1,349 | 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
IPv4 address.
If neither works, the validator will raise an error (as always).
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP address or empty with
``allow_empty`` set to ``True``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if is_py2 and value and isinstance(value, unicode):
value = value.encode('utf-8')
try:
value = ipv6(value, force_run = True) # pylint: disable=E1123
ipv6_failed = False
except ValueError:
ipv6_failed = True
if ipv6_failed:
try:
value = ipv4(value, force_run = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid IPv6 or '
'IPv4 address' % value)
return value | python | def ip_address(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if is_py2 and value and isinstance(value, unicode):
value = value.encode('utf-8')
try:
value = ipv6(value, force_run = True) # pylint: disable=E1123
ipv6_failed = False
except ValueError:
ipv6_failed = True
if ipv6_failed:
try:
value = ipv4(value, force_run = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid IPv6 or '
'IPv4 address' % value)
return value | [
"def",
"ip_address",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"if",
"is_py2",
"and",
"value",
"and",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"try",
":",
"value",
"=",
"ipv6",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"ipv6_failed",
"=",
"False",
"except",
"ValueError",
":",
"ipv6_failed",
"=",
"True",
"if",
"ipv6_failed",
":",
"try",
":",
"value",
"=",
"ipv4",
"(",
"value",
",",
"force_run",
"=",
"True",
")",
"# pylint: disable=E1123",
"except",
"ValueError",
":",
"raise",
"errors",
".",
"InvalidIPAddressError",
"(",
"'value (%s) is not a valid IPv6 or '",
"'IPv4 address'",
"%",
"value",
")",
"return",
"value"
] | 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).
: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 to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP address or empty with
``allow_empty`` set to ``True`` | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"IP",
"address",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2422-L2471 |
1,350 | 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.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or
empty with ``allow_empty`` set to ``True``
"""
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
components = value.split('.')
except AttributeError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
if len(components) != 4 or not all(x.isdigit() for x in components):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
for x in components:
try:
x = integer(x,
minimum = 0,
maximum = 255)
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
return value | python | def ipv4(value, allow_empty = False):
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
components = value.split('.')
except AttributeError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
if len(components) != 4 or not all(x.isdigit() for x in components):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
for x in components:
try:
x = integer(x,
minimum = 0,
maximum = 255)
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
return value | [
"def",
"ipv4",
"(",
"value",
",",
"allow_empty",
"=",
"False",
")",
":",
"if",
"not",
"value",
"and",
"allow_empty",
"is",
"False",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"try",
":",
"components",
"=",
"value",
".",
"split",
"(",
"'.'",
")",
"except",
"AttributeError",
":",
"raise",
"errors",
".",
"InvalidIPAddressError",
"(",
"'value (%s) is not a valid ipv4'",
"%",
"value",
")",
"if",
"len",
"(",
"components",
")",
"!=",
"4",
"or",
"not",
"all",
"(",
"x",
".",
"isdigit",
"(",
")",
"for",
"x",
"in",
"components",
")",
":",
"raise",
"errors",
".",
"InvalidIPAddressError",
"(",
"'value (%s) is not a valid ipv4'",
"%",
"value",
")",
"for",
"x",
"in",
"components",
":",
"try",
":",
"x",
"=",
"integer",
"(",
"x",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"255",
")",
"except",
"ValueError",
":",
"raise",
"errors",
".",
"InvalidIPAddressError",
"(",
"'value (%s) is not a valid ipv4'",
"%",
"value",
")",
"return",
"value"
] | 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`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or
empty with ``allow_empty`` set to ``True`` | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"IP",
"version",
"4",
"address",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2475-L2513 |
1,351 | 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:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 6 address or
empty with ``allow_empty`` is not set to ``True``
"""
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, str):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
value = value.lower().strip()
is_valid = IPV6_REGEX.match(value)
if not is_valid:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
return value | python | def ipv6(value,
allow_empty = False,
**kwargs):
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, str):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
value = value.lower().strip()
is_valid = IPV6_REGEX.match(value)
if not is_valid:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
return value | [
"def",
"ipv6",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"allow_empty",
"is",
"False",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"errors",
".",
"InvalidIPAddressError",
"(",
"'value (%s) is not a valid ipv6'",
"%",
"value",
")",
"value",
"=",
"value",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"is_valid",
"=",
"IPV6_REGEX",
".",
"match",
"(",
"value",
")",
"if",
"not",
"is_valid",
":",
"raise",
"errors",
".",
"InvalidIPAddressError",
"(",
"'value (%s) is not a valid ipv6'",
"%",
"value",
")",
"return",
"value"
] | 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`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 6 address or
empty with ``allow_empty`` is not set to ``True`` | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"IP",
"address",
"version",
"6",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2517-L2552 |
1,352 | 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:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>`
or string-like object
:raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with
``allow_empty`` set to ``True``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '-' in value:
value = value.replace('-', ':')
value = value.lower().strip()
is_valid = MAC_ADDRESS_REGEX.match(value)
if not is_valid:
raise errors.InvalidMACAddressError('value (%s) is not a valid MAC '
'address' % value)
return value | python | def mac_address(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '-' in value:
value = value.replace('-', ':')
value = value.lower().strip()
is_valid = MAC_ADDRESS_REGEX.match(value)
if not is_valid:
raise errors.InvalidMACAddressError('value (%s) is not a valid MAC '
'address' % value)
return value | [
"def",
"mac_address",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"elif",
"not",
"value",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"errors",
".",
"CannotCoerceError",
"(",
"'value must be a valid string, '",
"'was %s'",
"%",
"type",
"(",
"value",
")",
")",
"if",
"'-'",
"in",
"value",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'-'",
",",
"':'",
")",
"value",
"=",
"value",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"is_valid",
"=",
"MAC_ADDRESS_REGEX",
".",
"match",
"(",
"value",
")",
"if",
"not",
"is_valid",
":",
"raise",
"errors",
".",
"InvalidMACAddressError",
"(",
"'value (%s) is not a valid MAC '",
"'address'",
"%",
"value",
")",
"return",
"value"
] | 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 <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>`
or string-like object
:raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with
``allow_empty`` set to ``True`` | [
"Validate",
"that",
"value",
"is",
"a",
"valid",
"MAC",
"address",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2556-L2600 |
1,353 | 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:isinstance>` would cause a circular import
error.
To use this checker in that kind of situation, you can instead pass the
*name* of the type you want to check as a string in ``type_``. The checker
will evaluate it and see whether ``obj`` is of a type or inherits from a
type whose name matches the string you passed.
:param obj: The object whose type should be checked.
:type obj: :class:`object <python:object>`
:param type_: The type(s) to check against.
:type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` /
:class:`str <python:str>` with type name / iterable of :class:`str <python:str>`
with type name
:returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if not is_iterable(type_):
type_ = [type_]
return_value = False
for check_for_type in type_:
if isinstance(check_for_type, type):
return_value = isinstance(obj, check_for_type)
elif obj.__class__.__name__ == check_for_type:
return_value = True
else:
return_value = _check_base_classes(obj.__class__.__bases__,
check_for_type)
if return_value is True:
break
return return_value | python | def is_type(obj,
type_,
**kwargs):
if not is_iterable(type_):
type_ = [type_]
return_value = False
for check_for_type in type_:
if isinstance(check_for_type, type):
return_value = isinstance(obj, check_for_type)
elif obj.__class__.__name__ == check_for_type:
return_value = True
else:
return_value = _check_base_classes(obj.__class__.__bases__,
check_for_type)
if return_value is True:
break
return return_value | [
"def",
"is_type",
"(",
"obj",
",",
"type_",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_iterable",
"(",
"type_",
")",
":",
"type_",
"=",
"[",
"type_",
"]",
"return_value",
"=",
"False",
"for",
"check_for_type",
"in",
"type_",
":",
"if",
"isinstance",
"(",
"check_for_type",
",",
"type",
")",
":",
"return_value",
"=",
"isinstance",
"(",
"obj",
",",
"check_for_type",
")",
"elif",
"obj",
".",
"__class__",
".",
"__name__",
"==",
"check_for_type",
":",
"return_value",
"=",
"True",
"else",
":",
"return_value",
"=",
"_check_base_classes",
"(",
"obj",
".",
"__class__",
".",
"__bases__",
",",
"check_for_type",
")",
"if",
"return_value",
"is",
"True",
":",
"break",
"return",
"return_value"
] | 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 use this checker in that kind of situation, you can instead pass the
*name* of the type you want to check as a string in ``type_``. The checker
will evaluate it and see whether ``obj`` is of a type or inherits from a
type whose name matches the string you passed.
:param obj: The object whose type should be checked.
:type obj: :class:`object <python:object>`
:param type_: The type(s) to check against.
:type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` /
:class:`str <python:str>` with type name / iterable of :class:`str <python:str>`
with type name
:returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"if",
"obj",
"is",
"a",
"type",
"in",
"type_",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L21-L69 |
1,354 | 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_value = _check_base_classes(base.__bases__, check_for_type)
if return_value is True:
break
return return_value | python | def _check_base_classes(base_classes, check_for_type):
return_value = False
for base in base_classes:
if base.__name__ == check_for_type:
return_value = True
break
else:
return_value = _check_base_classes(base.__bases__, check_for_type)
if return_value is True:
break
return return_value | [
"def",
"_check_base_classes",
"(",
"base_classes",
",",
"check_for_type",
")",
":",
"return_value",
"=",
"False",
"for",
"base",
"in",
"base_classes",
":",
"if",
"base",
".",
"__name__",
"==",
"check_for_type",
":",
"return_value",
"=",
"True",
"break",
"else",
":",
"return_value",
"=",
"_check_base_classes",
"(",
"base",
".",
"__bases__",
",",
"check_for_type",
")",
"if",
"return_value",
"is",
"True",
":",
"break",
"return",
"return_value"
] | Indicate whether ``check_for_type`` exists in ``base_classes``. | [
"Indicate",
"whether",
"check_for_type",
"exists",
"in",
"base_classes",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L72-L85 |
1,355 | insightindustry/validator-collection | validator_collection/checkers.py | are_equivalent | def are_equivalent(*args, **kwargs):
"""Indicate if arguments passed to this function are equivalent.
.. hint::
This checker operates recursively on the members contained within iterables
and :class:`dict <python:dict>` objects.
.. caution::
If you only pass one argument to this checker - even if it is an iterable -
the checker will *always* return ``True``.
To evaluate members of an iterable for equivalence, you should instead
unpack the iterable into the function like so:
.. code-block:: python
obj = [1, 1, 1, 2]
result = are_equivalent(*obj)
# Will return ``False`` by unpacking and evaluating the iterable's members
result = are_equivalent(obj)
# Will always return True
:param args: One or more values, passed as positional arguments.
:returns: ``True`` if ``args`` are equivalent, and ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if len(args) == 1:
return True
first_item = args[0]
for item in args[1:]:
if type(item) != type(first_item): # pylint: disable=C0123
return False
if isinstance(item, dict):
if not are_dicts_equivalent(item, first_item):
return False
elif hasattr(item, '__iter__') and not isinstance(item, (str, bytes, dict)):
if len(item) != len(first_item):
return False
for value in item:
if value not in first_item:
return False
for value in first_item:
if value not in item:
return False
else:
if item != first_item:
return False
return True | python | def are_equivalent(*args, **kwargs):
if len(args) == 1:
return True
first_item = args[0]
for item in args[1:]:
if type(item) != type(first_item): # pylint: disable=C0123
return False
if isinstance(item, dict):
if not are_dicts_equivalent(item, first_item):
return False
elif hasattr(item, '__iter__') and not isinstance(item, (str, bytes, dict)):
if len(item) != len(first_item):
return False
for value in item:
if value not in first_item:
return False
for value in first_item:
if value not in item:
return False
else:
if item != first_item:
return False
return True | [
"def",
"are_equivalent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"return",
"True",
"first_item",
"=",
"args",
"[",
"0",
"]",
"for",
"item",
"in",
"args",
"[",
"1",
":",
"]",
":",
"if",
"type",
"(",
"item",
")",
"!=",
"type",
"(",
"first_item",
")",
":",
"# pylint: disable=C0123",
"return",
"False",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"if",
"not",
"are_dicts_equivalent",
"(",
"item",
",",
"first_item",
")",
":",
"return",
"False",
"elif",
"hasattr",
"(",
"item",
",",
"'__iter__'",
")",
"and",
"not",
"isinstance",
"(",
"item",
",",
"(",
"str",
",",
"bytes",
",",
"dict",
")",
")",
":",
"if",
"len",
"(",
"item",
")",
"!=",
"len",
"(",
"first_item",
")",
":",
"return",
"False",
"for",
"value",
"in",
"item",
":",
"if",
"value",
"not",
"in",
"first_item",
":",
"return",
"False",
"for",
"value",
"in",
"first_item",
":",
"if",
"value",
"not",
"in",
"item",
":",
"return",
"False",
"else",
":",
"if",
"item",
"!=",
"first_item",
":",
"return",
"False",
"return",
"True"
] | Indicate if arguments passed to this function are equivalent.
.. hint::
This checker operates recursively on the members contained within iterables
and :class:`dict <python:dict>` objects.
.. caution::
If you only pass one argument to this checker - even if it is an iterable -
the checker will *always* return ``True``.
To evaluate members of an iterable for equivalence, you should instead
unpack the iterable into the function like so:
.. code-block:: python
obj = [1, 1, 1, 2]
result = are_equivalent(*obj)
# Will return ``False`` by unpacking and evaluating the iterable's members
result = are_equivalent(obj)
# Will always return True
:param args: One or more values, passed as positional arguments.
:returns: ``True`` if ``args`` are equivalent, and ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"if",
"arguments",
"passed",
"to",
"this",
"function",
"are",
"equivalent",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L89-L148 |
1,356 | insightindustry/validator-collection | validator_collection/checkers.py | is_json | def is_json(value,
schema = None,
json_serializer = None,
**kwargs):
"""Indicate whether ``value`` is a valid JSON object.
.. 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.
:param value: The value to evaluate.
:param schema: An optional JSON schema against which ``value`` will be validated.
:type schema: :class:`dict <python:dict>` / :class:`str <python:str>` /
:obj:`None <python:None>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.json(value,
schema = schema,
json_serializer = json_serializer,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_json(value,
schema = None,
json_serializer = None,
**kwargs):
try:
value = validators.json(value,
schema = schema,
json_serializer = json_serializer,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_json",
"(",
"value",
",",
"schema",
"=",
"None",
",",
"json_serializer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"json",
"(",
"value",
",",
"schema",
"=",
"schema",
",",
"json_serializer",
"=",
"json_serializer",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a valid JSON object.
.. 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.
:param value: The value to evaluate.
:param schema: An optional JSON schema against which ``value`` will be validated.
:type schema: :class:`dict <python:dict>` / :class:`str <python:str>` /
:obj:`None <python:None>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"valid",
"JSON",
"object",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L340-L375 |
1,357 | insightindustry/validator-collection | validator_collection/checkers.py | is_string | def is_string(value,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
"""Indicate whether ``value`` is a string.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will check whether ``value`` can be coerced
to a string if it is not already. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if value is None:
return False
minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs)
maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs)
if isinstance(value, basestring) and not value:
if minimum_length and minimum_length > 0 and not whitespace_padding:
return False
return True
try:
value = validators.string(value,
coerce_value = coerce_value,
minimum_length = minimum_length,
maximum_length = maximum_length,
whitespace_padding = whitespace_padding,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_string(value,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
if value is None:
return False
minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs)
maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs)
if isinstance(value, basestring) and not value:
if minimum_length and minimum_length > 0 and not whitespace_padding:
return False
return True
try:
value = validators.string(value,
coerce_value = coerce_value,
minimum_length = minimum_length,
maximum_length = maximum_length,
whitespace_padding = whitespace_padding,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_string",
"(",
"value",
",",
"coerce_value",
"=",
"False",
",",
"minimum_length",
"=",
"None",
",",
"maximum_length",
"=",
"None",
",",
"whitespace_padding",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"False",
"minimum_length",
"=",
"validators",
".",
"integer",
"(",
"minimum_length",
",",
"allow_empty",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"maximum_length",
"=",
"validators",
".",
"integer",
"(",
"maximum_length",
",",
"allow_empty",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"and",
"not",
"value",
":",
"if",
"minimum_length",
"and",
"minimum_length",
">",
"0",
"and",
"not",
"whitespace_padding",
":",
"return",
"False",
"return",
"True",
"try",
":",
"value",
"=",
"validators",
".",
"string",
"(",
"value",
",",
"coerce_value",
"=",
"coerce_value",
",",
"minimum_length",
"=",
"minimum_length",
",",
"maximum_length",
"=",
"maximum_length",
",",
"whitespace_padding",
"=",
"whitespace_padding",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a string.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will check whether ``value`` can be coerced
to a string if it is not already. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"string",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L379-L436 |
1,358 | insightindustry/validator-collection | validator_collection/checkers.py | is_iterable | def is_iterable(obj,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
"""Indicate whether ``obj`` is iterable.
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to a :class:`tuple <python:tuple>`
containing :class:`str <python:str>` and :class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``True`` if ``obj`` is a valid iterable, ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if obj is None:
return False
if obj in forbid_literals:
return False
try:
obj = validators.iterable(obj,
allow_empty = True,
forbid_literals = forbid_literals,
minimum_length = minimum_length,
maximum_length = maximum_length,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_iterable(obj,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
if obj is None:
return False
if obj in forbid_literals:
return False
try:
obj = validators.iterable(obj,
allow_empty = True,
forbid_literals = forbid_literals,
minimum_length = minimum_length,
maximum_length = maximum_length,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_iterable",
"(",
"obj",
",",
"forbid_literals",
"=",
"(",
"str",
",",
"bytes",
")",
",",
"minimum_length",
"=",
"None",
",",
"maximum_length",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"False",
"if",
"obj",
"in",
"forbid_literals",
":",
"return",
"False",
"try",
":",
"obj",
"=",
"validators",
".",
"iterable",
"(",
"obj",
",",
"allow_empty",
"=",
"True",
",",
"forbid_literals",
"=",
"forbid_literals",
",",
"minimum_length",
"=",
"minimum_length",
",",
"maximum_length",
"=",
"maximum_length",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``obj`` is iterable.
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to a :class:`tuple <python:tuple>`
containing :class:`str <python:str>` and :class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``True`` if ``obj`` is a valid iterable, ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"obj",
"is",
"iterable",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L440-L485 |
1,359 | insightindustry/validator-collection | validator_collection/checkers.py | is_not_empty | def is_not_empty(value, **kwargs):
"""Indicate whether ``value`` is empty.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is empty, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.not_empty(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_not_empty(value, **kwargs):
try:
value = validators.not_empty(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_not_empty",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"not_empty",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is empty.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is empty, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"empty",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L489-L508 |
1,360 | insightindustry/validator-collection | validator_collection/checkers.py | is_variable_name | def is_variable_name(value, **kwargs):
"""Indicate whether ``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 evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
validators.variable_name(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_variable_name(value, **kwargs):
try:
validators.variable_name(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_variable_name",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"validators",
".",
"variable_name",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``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 evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"valid",
"Python",
"variable",
"name",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L540-L565 |
1,361 | insightindustry/validator-collection | validator_collection/checkers.py | is_numeric | def is_numeric(value,
minimum = None,
maximum = None,
**kwargs):
"""Indicate whether ``value`` is a numeric value.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.numeric(value,
minimum = minimum,
maximum = maximum,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_numeric(value,
minimum = None,
maximum = None,
**kwargs):
try:
value = validators.numeric(value,
minimum = minimum,
maximum = maximum,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_numeric",
"(",
"value",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"numeric",
"(",
"value",
",",
"minimum",
"=",
"minimum",
",",
"maximum",
"=",
"maximum",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a numeric value.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"numeric",
"value",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L799-L832 |
1,362 | insightindustry/validator-collection | validator_collection/checkers.py | is_integer | def is_integer(value,
coerce_value = False,
minimum = None,
maximum = None,
base = 10,
**kwargs):
"""Indicate whether ``value`` contains a whole number.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced
to whole number. If ``False``, will only return ``True`` if ``value`` is already
a whole number (regardless of type). Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:param base: Indicates the base that is used to determine the integer value.
The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be
optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with
integer literals in code. Base 0 means to interpret the string exactly as
an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to
``10``.
:type base: :class:`int <python:int>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.integer(value,
coerce_value = coerce_value,
minimum = minimum,
maximum = maximum,
base = base,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_integer(value,
coerce_value = False,
minimum = None,
maximum = None,
base = 10,
**kwargs):
try:
value = validators.integer(value,
coerce_value = coerce_value,
minimum = minimum,
maximum = maximum,
base = base,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_integer",
"(",
"value",
",",
"coerce_value",
"=",
"False",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"base",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"integer",
"(",
"value",
",",
"coerce_value",
"=",
"coerce_value",
",",
"minimum",
"=",
"minimum",
",",
"maximum",
"=",
"maximum",
",",
"base",
"=",
"base",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` contains a whole number.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced
to whole number. If ``False``, will only return ``True`` if ``value`` is already
a whole number (regardless of type). Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:param base: Indicates the base that is used to determine the integer value.
The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be
optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with
integer literals in code. Base 0 means to interpret the string exactly as
an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to
``10``.
:type base: :class:`int <python:int>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"contains",
"a",
"whole",
"number",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L836-L886 |
1,363 | insightindustry/validator-collection | validator_collection/checkers.py | is_pathlike | def is_pathlike(value, **kwargs):
"""Indicate whether ``value`` is a path-like object.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.path(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_pathlike(value, **kwargs):
try:
value = validators.path(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_pathlike",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"path",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a path-like object.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"path",
"-",
"like",
"object",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1045-L1064 |
1,364 | insightindustry/validator-collection | validator_collection/checkers.py | is_on_filesystem | def is_on_filesystem(value, **kwargs):
"""Indicate whether ``value`` is a file or directory that exists on the local
filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.path_exists(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_on_filesystem(value, **kwargs):
try:
value = validators.path_exists(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_on_filesystem",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"path_exists",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a file or directory that exists on the local
filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"file",
"or",
"directory",
"that",
"exists",
"on",
"the",
"local",
"filesystem",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1068-L1088 |
1,365 | insightindustry/validator-collection | validator_collection/checkers.py | is_file | def is_file(value, **kwargs):
"""Indicate whether ``value`` is a file that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.file_exists(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_file(value, **kwargs):
try:
value = validators.file_exists(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_file",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"file_exists",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a file that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"file",
"that",
"exists",
"on",
"the",
"local",
"filesystem",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1092-L1111 |
1,366 | insightindustry/validator-collection | validator_collection/checkers.py | is_directory | def is_directory(value, **kwargs):
"""Indicate whether ``value`` is a directory that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.directory_exists(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_directory(value, **kwargs):
try:
value = validators.directory_exists(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_directory",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"directory_exists",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a directory that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"directory",
"that",
"exists",
"on",
"the",
"local",
"filesystem",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1115-L1134 |
1,367 | insightindustry/validator-collection | validator_collection/checkers.py | is_readable | def is_readable(value, **kwargs):
"""Indicate whether ``value`` is 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/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
validators.readable(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_readable(value, **kwargs):
try:
validators.readable(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_readable",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"validators",
".",
"readable",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is 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/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"readable",
"file",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1138-L1181 |
1,368 | insightindustry/validator-collection | validator_collection/checkers.py | is_writeable | def is_writeable(value,
**kwargs):
"""Indicate whether ``value`` is 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 file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises NotImplementedError: if called on a Windows system
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
try:
validators.writeable(value,
allow_empty = False,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_writeable(value,
**kwargs):
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
try:
validators.writeable(value,
allow_empty = False,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_writeable",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sys",
".",
"platform",
"in",
"[",
"'win32'",
",",
"'cygwin'",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'not supported on Windows'",
")",
"try",
":",
"validators",
".",
"writeable",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is 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 file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises NotImplementedError: if called on a Windows system
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"writeable",
"file",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1185-L1257 |
1,369 | insightindustry/validator-collection | validator_collection/checkers.py | is_executable | def is_executable(value,
**kwargs):
"""Indicate whether ``value`` is 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 file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises NotImplementedError: if called on a Windows system
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
try:
validators.executable(value,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_executable(value,
**kwargs):
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
try:
validators.executable(value,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_executable",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sys",
".",
"platform",
"in",
"[",
"'win32'",
",",
"'cygwin'",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'not supported on Windows'",
")",
"try",
":",
"validators",
".",
"executable",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is 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 file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises NotImplementedError: if called on a Windows system
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"an",
"executable",
"file",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1260-L1323 |
1,370 | insightindustry/validator-collection | validator_collection/checkers.py | is_email | def is_email(value, **kwargs):
"""Indicate whether ``value`` is an 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.
String parsing in particular is used to validate certain *highly unusual*
but still valid email patterns, including the use of escaped text and
comments within an email address' local address (the user name part).
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.email(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_email(value, **kwargs):
try:
value = validators.email(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_email",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"email",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is an 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.
String parsing in particular is used to validate certain *highly unusual*
but still valid email patterns, including the use of escaped text and
comments within an email address' local address (the user name part).
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"an",
"email",
"address",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1329-L1362 |
1,371 | insightindustry/validator-collection | validator_collection/checkers.py | is_url | def is_url(value, **kwargs):
"""Indicate whether ``value`` is a 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.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to evaluate.
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will fail if ``value`` is a special IP address. Defaults to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.url(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_url(value, **kwargs):
try:
value = validators.url(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_url",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"url",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a 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.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to evaluate.
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will fail if ``value`` is a special IP address. Defaults to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"URL",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1366-L1402 |
1,372 | insightindustry/validator-collection | validator_collection/checkers.py | is_domain | def is_domain(value, **kwargs):
"""Indicate whether ``value`` is a valid domain.
.. 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. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:[email protected]``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
:param value: The value to evaluate.
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will fail if ``value`` is an IP address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.domain(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_domain(value, **kwargs):
try:
value = validators.domain(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_domain",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"domain",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a valid domain.
.. 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. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:[email protected]``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
:param value: The value to evaluate.
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will fail if ``value`` is an IP address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"valid",
"domain",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1406-L1450 |
1,373 | insightindustry/validator-collection | validator_collection/checkers.py | is_ipv4 | def is_ipv4(value, **kwargs):
"""Indicate whether ``value`` is a valid IP version 4 address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.ipv4(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_ipv4(value, **kwargs):
try:
value = validators.ipv4(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_ipv4",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"ipv4",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a valid IP version 4 address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"valid",
"IP",
"version",
"4",
"address",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1477-L1496 |
1,374 | insightindustry/validator-collection | validator_collection/checkers.py | is_ipv6 | def is_ipv6(value, **kwargs):
"""Indicate whether ``value`` is a valid IP version 6 address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.ipv6(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_ipv6(value, **kwargs):
try:
value = validators.ipv6(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_ipv6",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"ipv6",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a valid IP version 6 address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"valid",
"IP",
"version",
"6",
"address",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1500-L1518 |
1,375 | insightindustry/validator-collection | validator_collection/checkers.py | is_mac_address | def is_mac_address(value, **kwargs):
"""Indicate whether ``value`` is a valid MAC address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
try:
value = validators.mac_address(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | python | def is_mac_address(value, **kwargs):
try:
value = validators.mac_address(value, **kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True | [
"def",
"is_mac_address",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"mac_address",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Indicate whether ``value`` is a valid MAC address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | [
"Indicate",
"whether",
"value",
"is",
"a",
"valid",
"MAC",
"address",
"."
] | 8c8047a0fa36cc88a021771279898278c4cc98e3 | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1522-L1540 |
1,376 | kevinpt/syntrax | syntrax.py | RailroadLayout.draw_line | def draw_line(self, lx, ltor):
'''Draw a series of elements from left to right'''
tag = self.get_tag()
c = self.canvas
s = self.style
sep = s.h_sep
exx = 0
exy = 0
terms = lx if ltor else reversed(lx) # Reverse so we can draw left to right
for term in terms:
t, texx, texy = self.draw_diagram(term, ltor) # Draw each element
if exx > 0: # Second element onward
xn = exx + sep # Add space between elements
c.move(t, xn, exy) # Shift last element forward
arr = 'last' if ltor else 'first'
c.create_line(exx-1, exy, xn, exy, tags=(tag,), width=s.line_width, arrow=arr) # Connecting line (NOTE: -1 fudge)
exx = xn + texx # Start at end of this element
else: # First element
exx = texx # Start at end of this element
exy = texy
c.addtag_withtag(tag, t) # Retag this element
c.dtag(t, t) # Drop old tags
if exx == 0: # Nothing drawn, Add a line segment with an arrow in the middle
exx = sep * 2
c.create_line(0,0,sep,0, width=s.line_width, tags=(tag,), arrow='last')
c.create_line(sep, 0,exx,0, width=s.line_width, tags=(tag,))
exx = sep
return [tag, exx, exy] | python | def draw_line(self, lx, ltor):
'''Draw a series of elements from left to right'''
tag = self.get_tag()
c = self.canvas
s = self.style
sep = s.h_sep
exx = 0
exy = 0
terms = lx if ltor else reversed(lx) # Reverse so we can draw left to right
for term in terms:
t, texx, texy = self.draw_diagram(term, ltor) # Draw each element
if exx > 0: # Second element onward
xn = exx + sep # Add space between elements
c.move(t, xn, exy) # Shift last element forward
arr = 'last' if ltor else 'first'
c.create_line(exx-1, exy, xn, exy, tags=(tag,), width=s.line_width, arrow=arr) # Connecting line (NOTE: -1 fudge)
exx = xn + texx # Start at end of this element
else: # First element
exx = texx # Start at end of this element
exy = texy
c.addtag_withtag(tag, t) # Retag this element
c.dtag(t, t) # Drop old tags
if exx == 0: # Nothing drawn, Add a line segment with an arrow in the middle
exx = sep * 2
c.create_line(0,0,sep,0, width=s.line_width, tags=(tag,), arrow='last')
c.create_line(sep, 0,exx,0, width=s.line_width, tags=(tag,))
exx = sep
return [tag, exx, exy] | [
"def",
"draw_line",
"(",
"self",
",",
"lx",
",",
"ltor",
")",
":",
"tag",
"=",
"self",
".",
"get_tag",
"(",
")",
"c",
"=",
"self",
".",
"canvas",
"s",
"=",
"self",
".",
"style",
"sep",
"=",
"s",
".",
"h_sep",
"exx",
"=",
"0",
"exy",
"=",
"0",
"terms",
"=",
"lx",
"if",
"ltor",
"else",
"reversed",
"(",
"lx",
")",
"# Reverse so we can draw left to right",
"for",
"term",
"in",
"terms",
":",
"t",
",",
"texx",
",",
"texy",
"=",
"self",
".",
"draw_diagram",
"(",
"term",
",",
"ltor",
")",
"# Draw each element",
"if",
"exx",
">",
"0",
":",
"# Second element onward",
"xn",
"=",
"exx",
"+",
"sep",
"# Add space between elements",
"c",
".",
"move",
"(",
"t",
",",
"xn",
",",
"exy",
")",
"# Shift last element forward",
"arr",
"=",
"'last'",
"if",
"ltor",
"else",
"'first'",
"c",
".",
"create_line",
"(",
"exx",
"-",
"1",
",",
"exy",
",",
"xn",
",",
"exy",
",",
"tags",
"=",
"(",
"tag",
",",
")",
",",
"width",
"=",
"s",
".",
"line_width",
",",
"arrow",
"=",
"arr",
")",
"# Connecting line (NOTE: -1 fudge)",
"exx",
"=",
"xn",
"+",
"texx",
"# Start at end of this element",
"else",
":",
"# First element",
"exx",
"=",
"texx",
"# Start at end of this element",
"exy",
"=",
"texy",
"c",
".",
"addtag_withtag",
"(",
"tag",
",",
"t",
")",
"# Retag this element",
"c",
".",
"dtag",
"(",
"t",
",",
"t",
")",
"# Drop old tags",
"if",
"exx",
"==",
"0",
":",
"# Nothing drawn, Add a line segment with an arrow in the middle",
"exx",
"=",
"sep",
"*",
"2",
"c",
".",
"create_line",
"(",
"0",
",",
"0",
",",
"sep",
",",
"0",
",",
"width",
"=",
"s",
".",
"line_width",
",",
"tags",
"=",
"(",
"tag",
",",
")",
",",
"arrow",
"=",
"'last'",
")",
"c",
".",
"create_line",
"(",
"sep",
",",
"0",
",",
"exx",
",",
"0",
",",
"width",
"=",
"s",
".",
"line_width",
",",
"tags",
"=",
"(",
"tag",
",",
")",
")",
"exx",
"=",
"sep",
"return",
"[",
"tag",
",",
"exx",
",",
"exy",
"]"
] | Draw a series of elements from left to right | [
"Draw",
"a",
"series",
"of",
"elements",
"from",
"left",
"to",
"right"
] | eecc2714731ec6475d264326441e0f2a47467c28 | https://github.com/kevinpt/syntrax/blob/eecc2714731ec6475d264326441e0f2a47467c28/syntrax.py#L1291-L1325 |
1,377 | akolpakov/django-unused-media | django_unused_media/utils.py | get_file_fields | def get_file_fields():
"""
Get all fields which are inherited from FileField
"""
# get models
all_models = apps.get_models()
# get fields
fields = []
for model in all_models:
for field in model._meta.get_fields():
if isinstance(field, models.FileField):
fields.append(field)
return fields | python | def get_file_fields():
# get models
all_models = apps.get_models()
# get fields
fields = []
for model in all_models:
for field in model._meta.get_fields():
if isinstance(field, models.FileField):
fields.append(field)
return fields | [
"def",
"get_file_fields",
"(",
")",
":",
"# get models",
"all_models",
"=",
"apps",
".",
"get_models",
"(",
")",
"# get fields",
"fields",
"=",
"[",
"]",
"for",
"model",
"in",
"all_models",
":",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"get_fields",
"(",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"models",
".",
"FileField",
")",
":",
"fields",
".",
"append",
"(",
"field",
")",
"return",
"fields"
] | Get all fields which are inherited from FileField | [
"Get",
"all",
"fields",
"which",
"are",
"inherited",
"from",
"FileField"
] | 0a6c38840f4eac49d285c7be5da7330a564cee92 | https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/utils.py#L7-L25 |
1,378 | akolpakov/django-unused-media | django_unused_media/remove.py | remove_media | def remove_media(files):
"""
Delete file from media dir
"""
for filename in files:
os.remove(os.path.join(settings.MEDIA_ROOT, filename)) | python | def remove_media(files):
for filename in files:
os.remove(os.path.join(settings.MEDIA_ROOT, filename)) | [
"def",
"remove_media",
"(",
"files",
")",
":",
"for",
"filename",
"in",
"files",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"MEDIA_ROOT",
",",
"filename",
")",
")"
] | Delete file from media dir | [
"Delete",
"file",
"from",
"media",
"dir"
] | 0a6c38840f4eac49d285c7be5da7330a564cee92 | https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/remove.py#L8-L13 |
1,379 | akolpakov/django-unused-media | django_unused_media/remove.py | remove_empty_dirs | def remove_empty_dirs(path=None):
"""
Recursively delete empty directories; return True if everything was deleted.
"""
if not path:
path = settings.MEDIA_ROOT
if not os.path.isdir(path):
return False
listdir = [os.path.join(path, filename) for filename in os.listdir(path)]
if all(list(map(remove_empty_dirs, listdir))):
os.rmdir(path)
return True
else:
return False | python | def remove_empty_dirs(path=None):
if not path:
path = settings.MEDIA_ROOT
if not os.path.isdir(path):
return False
listdir = [os.path.join(path, filename) for filename in os.listdir(path)]
if all(list(map(remove_empty_dirs, listdir))):
os.rmdir(path)
return True
else:
return False | [
"def",
"remove_empty_dirs",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"settings",
".",
"MEDIA_ROOT",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"False",
"listdir",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"]",
"if",
"all",
"(",
"list",
"(",
"map",
"(",
"remove_empty_dirs",
",",
"listdir",
")",
")",
")",
":",
"os",
".",
"rmdir",
"(",
"path",
")",
"return",
"True",
"else",
":",
"return",
"False"
] | Recursively delete empty directories; return True if everything was deleted. | [
"Recursively",
"delete",
"empty",
"directories",
";",
"return",
"True",
"if",
"everything",
"was",
"deleted",
"."
] | 0a6c38840f4eac49d285c7be5da7330a564cee92 | https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/remove.py#L16-L33 |
1,380 | akolpakov/django-unused-media | django_unused_media/cleanup.py | get_used_media | def get_used_media():
"""
Get media which are still used in models
"""
media = set()
for field in get_file_fields():
is_null = {
'%s__isnull' % field.name: True,
}
is_empty = {
'%s' % field.name: '',
}
storage = field.storage
for value in field.model.objects \
.values_list(field.name, flat=True) \
.exclude(**is_empty).exclude(**is_null):
if value not in EMPTY_VALUES:
media.add(storage.path(value))
return media | python | def get_used_media():
media = set()
for field in get_file_fields():
is_null = {
'%s__isnull' % field.name: True,
}
is_empty = {
'%s' % field.name: '',
}
storage = field.storage
for value in field.model.objects \
.values_list(field.name, flat=True) \
.exclude(**is_empty).exclude(**is_null):
if value not in EMPTY_VALUES:
media.add(storage.path(value))
return media | [
"def",
"get_used_media",
"(",
")",
":",
"media",
"=",
"set",
"(",
")",
"for",
"field",
"in",
"get_file_fields",
"(",
")",
":",
"is_null",
"=",
"{",
"'%s__isnull'",
"%",
"field",
".",
"name",
":",
"True",
",",
"}",
"is_empty",
"=",
"{",
"'%s'",
"%",
"field",
".",
"name",
":",
"''",
",",
"}",
"storage",
"=",
"field",
".",
"storage",
"for",
"value",
"in",
"field",
".",
"model",
".",
"objects",
".",
"values_list",
"(",
"field",
".",
"name",
",",
"flat",
"=",
"True",
")",
".",
"exclude",
"(",
"*",
"*",
"is_empty",
")",
".",
"exclude",
"(",
"*",
"*",
"is_null",
")",
":",
"if",
"value",
"not",
"in",
"EMPTY_VALUES",
":",
"media",
".",
"add",
"(",
"storage",
".",
"path",
"(",
"value",
")",
")",
"return",
"media"
] | Get media which are still used in models | [
"Get",
"media",
"which",
"are",
"still",
"used",
"in",
"models"
] | 0a6c38840f4eac49d285c7be5da7330a564cee92 | https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/cleanup.py#L14-L37 |
1,381 | akolpakov/django-unused-media | django_unused_media/cleanup.py | get_all_media | def get_all_media(exclude=None):
"""
Get all media from MEDIA_ROOT
"""
if not exclude:
exclude = []
media = set()
for root, dirs, files in os.walk(six.text_type(settings.MEDIA_ROOT)):
for name in files:
path = os.path.abspath(os.path.join(root, name))
relpath = os.path.relpath(path, settings.MEDIA_ROOT)
for e in exclude:
if re.match(r'^%s$' % re.escape(e).replace('\\*', '.*'), relpath):
break
else:
media.add(path)
return media | python | def get_all_media(exclude=None):
if not exclude:
exclude = []
media = set()
for root, dirs, files in os.walk(six.text_type(settings.MEDIA_ROOT)):
for name in files:
path = os.path.abspath(os.path.join(root, name))
relpath = os.path.relpath(path, settings.MEDIA_ROOT)
for e in exclude:
if re.match(r'^%s$' % re.escape(e).replace('\\*', '.*'), relpath):
break
else:
media.add(path)
return media | [
"def",
"get_all_media",
"(",
"exclude",
"=",
"None",
")",
":",
"if",
"not",
"exclude",
":",
"exclude",
"=",
"[",
"]",
"media",
"=",
"set",
"(",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"six",
".",
"text_type",
"(",
"settings",
".",
"MEDIA_ROOT",
")",
")",
":",
"for",
"name",
"in",
"files",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"name",
")",
")",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"settings",
".",
"MEDIA_ROOT",
")",
"for",
"e",
"in",
"exclude",
":",
"if",
"re",
".",
"match",
"(",
"r'^%s$'",
"%",
"re",
".",
"escape",
"(",
"e",
")",
".",
"replace",
"(",
"'\\\\*'",
",",
"'.*'",
")",
",",
"relpath",
")",
":",
"break",
"else",
":",
"media",
".",
"add",
"(",
"path",
")",
"return",
"media"
] | Get all media from MEDIA_ROOT | [
"Get",
"all",
"media",
"from",
"MEDIA_ROOT"
] | 0a6c38840f4eac49d285c7be5da7330a564cee92 | https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/cleanup.py#L40-L60 |
1,382 | akolpakov/django-unused-media | django_unused_media/cleanup.py | get_unused_media | def get_unused_media(exclude=None):
"""
Get media which are not used in models
"""
if not exclude:
exclude = []
all_media = get_all_media(exclude)
used_media = get_used_media()
return all_media - used_media | python | def get_unused_media(exclude=None):
if not exclude:
exclude = []
all_media = get_all_media(exclude)
used_media = get_used_media()
return all_media - used_media | [
"def",
"get_unused_media",
"(",
"exclude",
"=",
"None",
")",
":",
"if",
"not",
"exclude",
":",
"exclude",
"=",
"[",
"]",
"all_media",
"=",
"get_all_media",
"(",
"exclude",
")",
"used_media",
"=",
"get_used_media",
"(",
")",
"return",
"all_media",
"-",
"used_media"
] | Get media which are not used in models | [
"Get",
"media",
"which",
"are",
"not",
"used",
"in",
"models"
] | 0a6c38840f4eac49d285c7be5da7330a564cee92 | https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/cleanup.py#L63-L74 |
1,383 | njsmith/colorspacious | colorspacious/conversion.py | cspace_converter | def cspace_converter(start, end):
"""Returns a function for converting from colorspace ``start`` to
colorspace ``end``.
E.g., these are equivalent::
out = cspace_convert(arr, start, end)
::
start_to_end_fn = cspace_converter(start, end)
out = start_to_end_fn(arr)
If you are doing a large number of conversions between the same pair of
spaces, then calling this function once and then using the returned
function repeatedly will be slightly more efficient than calling
:func:`cspace_convert` repeatedly. But I wouldn't bother unless you know
that this is a bottleneck for you, or it simplifies your code.
"""
start = norm_cspace_id(start)
end = norm_cspace_id(end)
return GRAPH.get_transform(start, end) | python | def cspace_converter(start, end):
start = norm_cspace_id(start)
end = norm_cspace_id(end)
return GRAPH.get_transform(start, end) | [
"def",
"cspace_converter",
"(",
"start",
",",
"end",
")",
":",
"start",
"=",
"norm_cspace_id",
"(",
"start",
")",
"end",
"=",
"norm_cspace_id",
"(",
"end",
")",
"return",
"GRAPH",
".",
"get_transform",
"(",
"start",
",",
"end",
")"
] | Returns a function for converting from colorspace ``start`` to
colorspace ``end``.
E.g., these are equivalent::
out = cspace_convert(arr, start, end)
::
start_to_end_fn = cspace_converter(start, end)
out = start_to_end_fn(arr)
If you are doing a large number of conversions between the same pair of
spaces, then calling this function once and then using the returned
function repeatedly will be slightly more efficient than calling
:func:`cspace_convert` repeatedly. But I wouldn't bother unless you know
that this is a bottleneck for you, or it simplifies your code. | [
"Returns",
"a",
"function",
"for",
"converting",
"from",
"colorspace",
"start",
"to",
"colorspace",
"end",
"."
] | 59e0226003fb1b894597c5081e8ca5a3aa4fcefd | https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/conversion.py#L198-L220 |
1,384 | njsmith/colorspacious | colorspacious/conversion.py | cspace_convert | def cspace_convert(arr, start, end):
"""Converts the colors in ``arr`` from colorspace ``start`` to colorspace
``end``.
:param arr: An array-like of colors.
:param start, end: Any supported colorspace specifiers. See
:ref:`supported-colorspaces` for details.
"""
converter = cspace_converter(start, end)
return converter(arr) | python | def cspace_convert(arr, start, end):
converter = cspace_converter(start, end)
return converter(arr) | [
"def",
"cspace_convert",
"(",
"arr",
",",
"start",
",",
"end",
")",
":",
"converter",
"=",
"cspace_converter",
"(",
"start",
",",
"end",
")",
"return",
"converter",
"(",
"arr",
")"
] | Converts the colors in ``arr`` from colorspace ``start`` to colorspace
``end``.
:param arr: An array-like of colors.
:param start, end: Any supported colorspace specifiers. See
:ref:`supported-colorspaces` for details. | [
"Converts",
"the",
"colors",
"in",
"arr",
"from",
"colorspace",
"start",
"to",
"colorspace",
"end",
"."
] | 59e0226003fb1b894597c5081e8ca5a3aa4fcefd | https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/conversion.py#L222-L232 |
1,385 | njsmith/colorspacious | colorspacious/illuminants.py | as_XYZ100_w | def as_XYZ100_w(whitepoint):
"""A convenience function for getting whitepoints.
``whitepoint`` can be either a string naming a standard illuminant (see
:func:`standard_illuminant_XYZ100`), or else a whitepoint given explicitly
as an array-like of XYZ values.
We internally call this function anywhere you have to specify a whitepoint
(e.g. for CIECAM02 or CIELAB conversions).
Always uses the "standard" 2 degree observer.
"""
if isinstance(whitepoint, str):
return standard_illuminant_XYZ100(whitepoint)
else:
whitepoint = np.asarray(whitepoint, dtype=float)
if whitepoint.shape[-1] != 3:
raise ValueError("Bad whitepoint shape")
return whitepoint | python | def as_XYZ100_w(whitepoint):
if isinstance(whitepoint, str):
return standard_illuminant_XYZ100(whitepoint)
else:
whitepoint = np.asarray(whitepoint, dtype=float)
if whitepoint.shape[-1] != 3:
raise ValueError("Bad whitepoint shape")
return whitepoint | [
"def",
"as_XYZ100_w",
"(",
"whitepoint",
")",
":",
"if",
"isinstance",
"(",
"whitepoint",
",",
"str",
")",
":",
"return",
"standard_illuminant_XYZ100",
"(",
"whitepoint",
")",
"else",
":",
"whitepoint",
"=",
"np",
".",
"asarray",
"(",
"whitepoint",
",",
"dtype",
"=",
"float",
")",
"if",
"whitepoint",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"Bad whitepoint shape\"",
")",
"return",
"whitepoint"
] | A convenience function for getting whitepoints.
``whitepoint`` can be either a string naming a standard illuminant (see
:func:`standard_illuminant_XYZ100`), or else a whitepoint given explicitly
as an array-like of XYZ values.
We internally call this function anywhere you have to specify a whitepoint
(e.g. for CIECAM02 or CIELAB conversions).
Always uses the "standard" 2 degree observer. | [
"A",
"convenience",
"function",
"for",
"getting",
"whitepoints",
"."
] | 59e0226003fb1b894597c5081e8ca5a3aa4fcefd | https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/illuminants.py#L97-L116 |
1,386 | njsmith/colorspacious | colorspacious/cvd.py | machado_et_al_2009_matrix | def machado_et_al_2009_matrix(cvd_type, severity):
"""Retrieve a matrix for simulating anomalous color vision.
:param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly".
:param severity: A value between 0 and 100.
:returns: A 3x3 CVD simulation matrix as computed by Machado et al
(2009).
These matrices were downloaded from:
http://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html
which is supplementary data from :cite:`Machado-CVD`.
If severity is a multiple of 10, then simply returns the matrix from that
webpage. For other severities, performs linear interpolation.
"""
assert 0 <= severity <= 100
fraction = severity % 10
low = int(severity - fraction)
high = low + 10
assert low <= severity <= high
low_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][low])
if severity == 100:
# Don't try interpolating between 100 and 110, there is no 110...
return low_matrix
high_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][high])
return ((1 - fraction / 10.0) * low_matrix
+ fraction / 10.0 * high_matrix) | python | def machado_et_al_2009_matrix(cvd_type, severity):
assert 0 <= severity <= 100
fraction = severity % 10
low = int(severity - fraction)
high = low + 10
assert low <= severity <= high
low_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][low])
if severity == 100:
# Don't try interpolating between 100 and 110, there is no 110...
return low_matrix
high_matrix = np.asarray(MACHADO_ET_AL_MATRICES[cvd_type][high])
return ((1 - fraction / 10.0) * low_matrix
+ fraction / 10.0 * high_matrix) | [
"def",
"machado_et_al_2009_matrix",
"(",
"cvd_type",
",",
"severity",
")",
":",
"assert",
"0",
"<=",
"severity",
"<=",
"100",
"fraction",
"=",
"severity",
"%",
"10",
"low",
"=",
"int",
"(",
"severity",
"-",
"fraction",
")",
"high",
"=",
"low",
"+",
"10",
"assert",
"low",
"<=",
"severity",
"<=",
"high",
"low_matrix",
"=",
"np",
".",
"asarray",
"(",
"MACHADO_ET_AL_MATRICES",
"[",
"cvd_type",
"]",
"[",
"low",
"]",
")",
"if",
"severity",
"==",
"100",
":",
"# Don't try interpolating between 100 and 110, there is no 110...",
"return",
"low_matrix",
"high_matrix",
"=",
"np",
".",
"asarray",
"(",
"MACHADO_ET_AL_MATRICES",
"[",
"cvd_type",
"]",
"[",
"high",
"]",
")",
"return",
"(",
"(",
"1",
"-",
"fraction",
"/",
"10.0",
")",
"*",
"low_matrix",
"+",
"fraction",
"/",
"10.0",
"*",
"high_matrix",
")"
] | Retrieve a matrix for simulating anomalous color vision.
:param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly".
:param severity: A value between 0 and 100.
:returns: A 3x3 CVD simulation matrix as computed by Machado et al
(2009).
These matrices were downloaded from:
http://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html
which is supplementary data from :cite:`Machado-CVD`.
If severity is a multiple of 10, then simply returns the matrix from that
webpage. For other severities, performs linear interpolation. | [
"Retrieve",
"a",
"matrix",
"for",
"simulating",
"anomalous",
"color",
"vision",
"."
] | 59e0226003fb1b894597c5081e8ca5a3aa4fcefd | https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/cvd.py#L21-L54 |
1,387 | h2oai/typesentry | typesentry/signature.py | Signature._make_retval_checker | def _make_retval_checker(self):
"""Create a function that checks the return value of the function."""
rvchk = self.retval.checker
if rvchk:
def _checker(value):
if not rvchk.check(value):
raise self._type_error(
"Incorrect return type in %s: expected %s got %s" %
(self.name_bt, rvchk.name(),
checker_for_type(type(value)).name())
)
else:
def _checker(value):
pass
return _checker | python | def _make_retval_checker(self):
rvchk = self.retval.checker
if rvchk:
def _checker(value):
if not rvchk.check(value):
raise self._type_error(
"Incorrect return type in %s: expected %s got %s" %
(self.name_bt, rvchk.name(),
checker_for_type(type(value)).name())
)
else:
def _checker(value):
pass
return _checker | [
"def",
"_make_retval_checker",
"(",
"self",
")",
":",
"rvchk",
"=",
"self",
".",
"retval",
".",
"checker",
"if",
"rvchk",
":",
"def",
"_checker",
"(",
"value",
")",
":",
"if",
"not",
"rvchk",
".",
"check",
"(",
"value",
")",
":",
"raise",
"self",
".",
"_type_error",
"(",
"\"Incorrect return type in %s: expected %s got %s\"",
"%",
"(",
"self",
".",
"name_bt",
",",
"rvchk",
".",
"name",
"(",
")",
",",
"checker_for_type",
"(",
"type",
"(",
"value",
")",
")",
".",
"name",
"(",
")",
")",
")",
"else",
":",
"def",
"_checker",
"(",
"value",
")",
":",
"pass",
"return",
"_checker"
] | Create a function that checks the return value of the function. | [
"Create",
"a",
"function",
"that",
"checks",
"the",
"return",
"value",
"of",
"the",
"function",
"."
] | 0ca8ed0e62d15ffe430545e7648c9a9b2547b49c | https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/signature.py#L172-L186 |
1,388 | h2oai/typesentry | typesentry/signature.py | Signature._make_args_checker | def _make_args_checker(self):
"""
Create a function that checks signature of the source function.
"""
def _checker(*args, **kws):
# Check if too many arguments are provided
nargs = len(args)
nnonvaargs = min(nargs, self._max_positional_args)
if nargs > self._max_positional_args and self._ivararg is None:
raise self._too_many_args_error(nargs)
# Check if there are too few positional arguments (without defaults)
if nargs < self._min_positional_args:
missing = [p.name
for p in self.params[nargs:self._min_positional_args]
if p.name not in kws]
# The "missing" arguments may still be provided as keywords, in
# which case it's not an error at all.
if missing:
raise self._too_few_args_error(missing, "positional")
# Check if there are too few required keyword arguments
if self._required_kwonly_args:
missing = [kw
for kw in self._required_kwonly_args
if kw not in kws]
if missing:
raise self._too_few_args_error(missing, "keyword")
# Check types of positional arguments
for i, argvalue in enumerate(args):
param = self.params[i if i < self._max_positional_args else
self._ivararg]
if param.checker and not (
param.checker.check(argvalue) or
param.has_default and
(argvalue is param.default or argvalue == param.default)
):
raise self._param_type_error(param, param.name, argvalue)
# Check types of keyword arguments
for argname, argvalue in kws.items():
argindex = self._iargs.get(argname)
if argindex is not None and argindex < nnonvaargs:
raise self._repeating_arg_error(argname)
index = self._iargs.get(argname)
if index is None:
index = self._ivarkws
if index is None:
s = "%s got an unexpected keyword argument `%s`" % \
(self.name_bt, argname)
raise self._type_error(s)
param = self.params[index]
if param.checker and not (
param.checker.check(argvalue) or
param.has_default and
(argvalue is param.default or argvalue == param.default)
):
raise self._param_type_error(param, argname, argvalue)
return _checker | python | def _make_args_checker(self):
def _checker(*args, **kws):
# Check if too many arguments are provided
nargs = len(args)
nnonvaargs = min(nargs, self._max_positional_args)
if nargs > self._max_positional_args and self._ivararg is None:
raise self._too_many_args_error(nargs)
# Check if there are too few positional arguments (without defaults)
if nargs < self._min_positional_args:
missing = [p.name
for p in self.params[nargs:self._min_positional_args]
if p.name not in kws]
# The "missing" arguments may still be provided as keywords, in
# which case it's not an error at all.
if missing:
raise self._too_few_args_error(missing, "positional")
# Check if there are too few required keyword arguments
if self._required_kwonly_args:
missing = [kw
for kw in self._required_kwonly_args
if kw not in kws]
if missing:
raise self._too_few_args_error(missing, "keyword")
# Check types of positional arguments
for i, argvalue in enumerate(args):
param = self.params[i if i < self._max_positional_args else
self._ivararg]
if param.checker and not (
param.checker.check(argvalue) or
param.has_default and
(argvalue is param.default or argvalue == param.default)
):
raise self._param_type_error(param, param.name, argvalue)
# Check types of keyword arguments
for argname, argvalue in kws.items():
argindex = self._iargs.get(argname)
if argindex is not None and argindex < nnonvaargs:
raise self._repeating_arg_error(argname)
index = self._iargs.get(argname)
if index is None:
index = self._ivarkws
if index is None:
s = "%s got an unexpected keyword argument `%s`" % \
(self.name_bt, argname)
raise self._type_error(s)
param = self.params[index]
if param.checker and not (
param.checker.check(argvalue) or
param.has_default and
(argvalue is param.default or argvalue == param.default)
):
raise self._param_type_error(param, argname, argvalue)
return _checker | [
"def",
"_make_args_checker",
"(",
"self",
")",
":",
"def",
"_checker",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"# Check if too many arguments are provided",
"nargs",
"=",
"len",
"(",
"args",
")",
"nnonvaargs",
"=",
"min",
"(",
"nargs",
",",
"self",
".",
"_max_positional_args",
")",
"if",
"nargs",
">",
"self",
".",
"_max_positional_args",
"and",
"self",
".",
"_ivararg",
"is",
"None",
":",
"raise",
"self",
".",
"_too_many_args_error",
"(",
"nargs",
")",
"# Check if there are too few positional arguments (without defaults)",
"if",
"nargs",
"<",
"self",
".",
"_min_positional_args",
":",
"missing",
"=",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"self",
".",
"params",
"[",
"nargs",
":",
"self",
".",
"_min_positional_args",
"]",
"if",
"p",
".",
"name",
"not",
"in",
"kws",
"]",
"# The \"missing\" arguments may still be provided as keywords, in",
"# which case it's not an error at all.",
"if",
"missing",
":",
"raise",
"self",
".",
"_too_few_args_error",
"(",
"missing",
",",
"\"positional\"",
")",
"# Check if there are too few required keyword arguments",
"if",
"self",
".",
"_required_kwonly_args",
":",
"missing",
"=",
"[",
"kw",
"for",
"kw",
"in",
"self",
".",
"_required_kwonly_args",
"if",
"kw",
"not",
"in",
"kws",
"]",
"if",
"missing",
":",
"raise",
"self",
".",
"_too_few_args_error",
"(",
"missing",
",",
"\"keyword\"",
")",
"# Check types of positional arguments",
"for",
"i",
",",
"argvalue",
"in",
"enumerate",
"(",
"args",
")",
":",
"param",
"=",
"self",
".",
"params",
"[",
"i",
"if",
"i",
"<",
"self",
".",
"_max_positional_args",
"else",
"self",
".",
"_ivararg",
"]",
"if",
"param",
".",
"checker",
"and",
"not",
"(",
"param",
".",
"checker",
".",
"check",
"(",
"argvalue",
")",
"or",
"param",
".",
"has_default",
"and",
"(",
"argvalue",
"is",
"param",
".",
"default",
"or",
"argvalue",
"==",
"param",
".",
"default",
")",
")",
":",
"raise",
"self",
".",
"_param_type_error",
"(",
"param",
",",
"param",
".",
"name",
",",
"argvalue",
")",
"# Check types of keyword arguments",
"for",
"argname",
",",
"argvalue",
"in",
"kws",
".",
"items",
"(",
")",
":",
"argindex",
"=",
"self",
".",
"_iargs",
".",
"get",
"(",
"argname",
")",
"if",
"argindex",
"is",
"not",
"None",
"and",
"argindex",
"<",
"nnonvaargs",
":",
"raise",
"self",
".",
"_repeating_arg_error",
"(",
"argname",
")",
"index",
"=",
"self",
".",
"_iargs",
".",
"get",
"(",
"argname",
")",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"self",
".",
"_ivarkws",
"if",
"index",
"is",
"None",
":",
"s",
"=",
"\"%s got an unexpected keyword argument `%s`\"",
"%",
"(",
"self",
".",
"name_bt",
",",
"argname",
")",
"raise",
"self",
".",
"_type_error",
"(",
"s",
")",
"param",
"=",
"self",
".",
"params",
"[",
"index",
"]",
"if",
"param",
".",
"checker",
"and",
"not",
"(",
"param",
".",
"checker",
".",
"check",
"(",
"argvalue",
")",
"or",
"param",
".",
"has_default",
"and",
"(",
"argvalue",
"is",
"param",
".",
"default",
"or",
"argvalue",
"==",
"param",
".",
"default",
")",
")",
":",
"raise",
"self",
".",
"_param_type_error",
"(",
"param",
",",
"argname",
",",
"argvalue",
")",
"return",
"_checker"
] | Create a function that checks signature of the source function. | [
"Create",
"a",
"function",
"that",
"checks",
"signature",
"of",
"the",
"source",
"function",
"."
] | 0ca8ed0e62d15ffe430545e7648c9a9b2547b49c | https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/signature.py#L189-L249 |
1,389 | h2oai/typesentry | typesentry/checks.py | checker_for_type | def checker_for_type(t):
"""
Return "checker" function for the given type `t`.
This checker function will accept a single argument (of any type), and
return True if the argument matches type `t`, or False otherwise. For
example:
chkr = checker_for_type(int)
assert chkr.check(123) is True
assert chkr.check("5") is False
"""
try:
if t is True:
return true_checker
if t is False:
return false_checker
checker = memoized_type_checkers.get(t)
if checker is not None:
return checker
hashable = True
except TypeError:
# Exception may be raised if `t` is not hashable (e.g. a dict)
hashable = False
# The type checker needs to be created
checker = _create_checker_for_type(t)
if hashable:
memoized_type_checkers[t] = checker
return checker | python | def checker_for_type(t):
try:
if t is True:
return true_checker
if t is False:
return false_checker
checker = memoized_type_checkers.get(t)
if checker is not None:
return checker
hashable = True
except TypeError:
# Exception may be raised if `t` is not hashable (e.g. a dict)
hashable = False
# The type checker needs to be created
checker = _create_checker_for_type(t)
if hashable:
memoized_type_checkers[t] = checker
return checker | [
"def",
"checker_for_type",
"(",
"t",
")",
":",
"try",
":",
"if",
"t",
"is",
"True",
":",
"return",
"true_checker",
"if",
"t",
"is",
"False",
":",
"return",
"false_checker",
"checker",
"=",
"memoized_type_checkers",
".",
"get",
"(",
"t",
")",
"if",
"checker",
"is",
"not",
"None",
":",
"return",
"checker",
"hashable",
"=",
"True",
"except",
"TypeError",
":",
"# Exception may be raised if `t` is not hashable (e.g. a dict)",
"hashable",
"=",
"False",
"# The type checker needs to be created",
"checker",
"=",
"_create_checker_for_type",
"(",
"t",
")",
"if",
"hashable",
":",
"memoized_type_checkers",
"[",
"t",
"]",
"=",
"checker",
"return",
"checker"
] | Return "checker" function for the given type `t`.
This checker function will accept a single argument (of any type), and
return True if the argument matches type `t`, or False otherwise. For
example:
chkr = checker_for_type(int)
assert chkr.check(123) is True
assert chkr.check("5") is False | [
"Return",
"checker",
"function",
"for",
"the",
"given",
"type",
"t",
"."
] | 0ca8ed0e62d15ffe430545e7648c9a9b2547b49c | https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/checks.py#L32-L61 |
1,390 | h2oai/typesentry | typesentry/checks.py | _prepare_value | def _prepare_value(val, maxlen=50, notype=False):
"""
Stringify value `val`, ensuring that it is not too long.
"""
if val is None or val is True or val is False:
return str(val)
sval = repr(val)
sval = sval.replace("\n", " ").replace("\t", " ").replace("`", "'")
if len(sval) > maxlen:
sval = sval[:maxlen - 4] + "..." + sval[-1]
if notype:
return sval
else:
tval = checker_for_type(type(val)).name()
return "%s of type %s" % (sval, tval) | python | def _prepare_value(val, maxlen=50, notype=False):
if val is None or val is True or val is False:
return str(val)
sval = repr(val)
sval = sval.replace("\n", " ").replace("\t", " ").replace("`", "'")
if len(sval) > maxlen:
sval = sval[:maxlen - 4] + "..." + sval[-1]
if notype:
return sval
else:
tval = checker_for_type(type(val)).name()
return "%s of type %s" % (sval, tval) | [
"def",
"_prepare_value",
"(",
"val",
",",
"maxlen",
"=",
"50",
",",
"notype",
"=",
"False",
")",
":",
"if",
"val",
"is",
"None",
"or",
"val",
"is",
"True",
"or",
"val",
"is",
"False",
":",
"return",
"str",
"(",
"val",
")",
"sval",
"=",
"repr",
"(",
"val",
")",
"sval",
"=",
"sval",
".",
"replace",
"(",
"\"\\n\"",
",",
"\" \"",
")",
".",
"replace",
"(",
"\"\\t\"",
",",
"\" \"",
")",
".",
"replace",
"(",
"\"`\"",
",",
"\"'\"",
")",
"if",
"len",
"(",
"sval",
")",
">",
"maxlen",
":",
"sval",
"=",
"sval",
"[",
":",
"maxlen",
"-",
"4",
"]",
"+",
"\"...\"",
"+",
"sval",
"[",
"-",
"1",
"]",
"if",
"notype",
":",
"return",
"sval",
"else",
":",
"tval",
"=",
"checker_for_type",
"(",
"type",
"(",
"val",
")",
")",
".",
"name",
"(",
")",
"return",
"\"%s of type %s\"",
"%",
"(",
"sval",
",",
"tval",
")"
] | Stringify value `val`, ensuring that it is not too long. | [
"Stringify",
"value",
"val",
"ensuring",
"that",
"it",
"is",
"not",
"too",
"long",
"."
] | 0ca8ed0e62d15ffe430545e7648c9a9b2547b49c | https://github.com/h2oai/typesentry/blob/0ca8ed0e62d15ffe430545e7648c9a9b2547b49c/typesentry/checks.py#L774-L788 |
1,391 | muatik/naive-bayes-classifier | naiveBayesClassifier/trainer.py | Trainer.train | def train(self, text, className):
"""
enhances trained data using the given text and class
"""
self.data.increaseClass(className)
tokens = self.tokenizer.tokenize(text)
for token in tokens:
token = self.tokenizer.remove_stop_words(token)
token = self.tokenizer.remove_punctuation(token)
self.data.increaseToken(token, className) | python | def train(self, text, className):
self.data.increaseClass(className)
tokens = self.tokenizer.tokenize(text)
for token in tokens:
token = self.tokenizer.remove_stop_words(token)
token = self.tokenizer.remove_punctuation(token)
self.data.increaseToken(token, className) | [
"def",
"train",
"(",
"self",
",",
"text",
",",
"className",
")",
":",
"self",
".",
"data",
".",
"increaseClass",
"(",
"className",
")",
"tokens",
"=",
"self",
".",
"tokenizer",
".",
"tokenize",
"(",
"text",
")",
"for",
"token",
"in",
"tokens",
":",
"token",
"=",
"self",
".",
"tokenizer",
".",
"remove_stop_words",
"(",
"token",
")",
"token",
"=",
"self",
".",
"tokenizer",
".",
"remove_punctuation",
"(",
"token",
")",
"self",
".",
"data",
".",
"increaseToken",
"(",
"token",
",",
"className",
")"
] | enhances trained data using the given text and class | [
"enhances",
"trained",
"data",
"using",
"the",
"given",
"text",
"and",
"class"
] | cdc1d8681ef6674e946cff38e87ce3b00c732fbb | https://github.com/muatik/naive-bayes-classifier/blob/cdc1d8681ef6674e946cff38e87ce3b00c732fbb/naiveBayesClassifier/trainer.py#L11-L21 |
1,392 | rene-aguirre/pywinusb | pywinusb/hid/core.py | find_all_hid_devices | def find_all_hid_devices():
"Finds all HID devices connected to the system"
#
# From DDK documentation (finding and Opening HID collection):
# After a user-mode application is loaded, it does the following sequence
# of operations:
#
# * Calls HidD_GetHidGuid to obtain the system-defined GUID for HIDClass
# devices.
#
# * Calls SetupDiGetClassDevs to obtain a handle to an opaque device
# information set that describes the device interfaces supported by all
# the HID collections currently installed in the system. The
# application should specify DIGCF_PRESENT and DIGCF_INTERFACEDEVICE
# in the Flags parameter passed to SetupDiGetClassDevs.
#
# * Calls SetupDiEnumDeviceInterfaces repeatedly to retrieve all the
# available interface information.
#
# * Calls SetupDiGetDeviceInterfaceDetail to format interface information
# for each collection as a SP_INTERFACE_DEVICE_DETAIL_DATA structure.
# The device_path member of this structure contains the user-mode name
# that the application uses with the Win32 function CreateFile to
# obtain a file handle to a HID collection.
#
# get HID device class guid
guid = winapi.GetHidGuid()
# retrieve all the available interface information.
results = []
required_size = DWORD()
info_data = winapi.SP_DEVINFO_DATA()
info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA)
with winapi.DeviceInterfaceSetInfo(guid) as h_info:
for interface_data in winapi.enum_device_interfaces(h_info, guid):
device_path = winapi.get_device_path(h_info,
interface_data,
byref(info_data))
parent_device = c_ulong()
#get parent instance id (so we can discriminate on port)
if setup_api.CM_Get_Parent(byref(parent_device),
info_data.dev_inst, 0) != 0: #CR_SUCCESS = 0
parent_device.value = 0 #null
#get unique instance id string
required_size.value = 0
winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data),
None, 0,
byref(required_size) )
device_instance_id = create_unicode_buffer(required_size.value)
if required_size.value > 0:
winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data),
device_instance_id, required_size,
byref(required_size) )
hid_device = HidDevice(device_path,
parent_device.value, device_instance_id.value )
else:
hid_device = HidDevice(device_path, parent_device.value )
# add device to results, if not protected
if hid_device.vendor_id:
results.append(hid_device)
return results | python | def find_all_hid_devices():
"Finds all HID devices connected to the system"
#
# From DDK documentation (finding and Opening HID collection):
# After a user-mode application is loaded, it does the following sequence
# of operations:
#
# * Calls HidD_GetHidGuid to obtain the system-defined GUID for HIDClass
# devices.
#
# * Calls SetupDiGetClassDevs to obtain a handle to an opaque device
# information set that describes the device interfaces supported by all
# the HID collections currently installed in the system. The
# application should specify DIGCF_PRESENT and DIGCF_INTERFACEDEVICE
# in the Flags parameter passed to SetupDiGetClassDevs.
#
# * Calls SetupDiEnumDeviceInterfaces repeatedly to retrieve all the
# available interface information.
#
# * Calls SetupDiGetDeviceInterfaceDetail to format interface information
# for each collection as a SP_INTERFACE_DEVICE_DETAIL_DATA structure.
# The device_path member of this structure contains the user-mode name
# that the application uses with the Win32 function CreateFile to
# obtain a file handle to a HID collection.
#
# get HID device class guid
guid = winapi.GetHidGuid()
# retrieve all the available interface information.
results = []
required_size = DWORD()
info_data = winapi.SP_DEVINFO_DATA()
info_data.cb_size = sizeof(winapi.SP_DEVINFO_DATA)
with winapi.DeviceInterfaceSetInfo(guid) as h_info:
for interface_data in winapi.enum_device_interfaces(h_info, guid):
device_path = winapi.get_device_path(h_info,
interface_data,
byref(info_data))
parent_device = c_ulong()
#get parent instance id (so we can discriminate on port)
if setup_api.CM_Get_Parent(byref(parent_device),
info_data.dev_inst, 0) != 0: #CR_SUCCESS = 0
parent_device.value = 0 #null
#get unique instance id string
required_size.value = 0
winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data),
None, 0,
byref(required_size) )
device_instance_id = create_unicode_buffer(required_size.value)
if required_size.value > 0:
winapi.SetupDiGetDeviceInstanceId(h_info, byref(info_data),
device_instance_id, required_size,
byref(required_size) )
hid_device = HidDevice(device_path,
parent_device.value, device_instance_id.value )
else:
hid_device = HidDevice(device_path, parent_device.value )
# add device to results, if not protected
if hid_device.vendor_id:
results.append(hid_device)
return results | [
"def",
"find_all_hid_devices",
"(",
")",
":",
"#\r",
"# From DDK documentation (finding and Opening HID collection):\r",
"# After a user-mode application is loaded, it does the following sequence\r",
"# of operations:\r",
"#\r",
"# * Calls HidD_GetHidGuid to obtain the system-defined GUID for HIDClass\r",
"# devices.\r",
"#\r",
"# * Calls SetupDiGetClassDevs to obtain a handle to an opaque device\r",
"# information set that describes the device interfaces supported by all\r",
"# the HID collections currently installed in the system. The\r",
"# application should specify DIGCF_PRESENT and DIGCF_INTERFACEDEVICE\r",
"# in the Flags parameter passed to SetupDiGetClassDevs.\r",
"#\r",
"# * Calls SetupDiEnumDeviceInterfaces repeatedly to retrieve all the\r",
"# available interface information.\r",
"#\r",
"# * Calls SetupDiGetDeviceInterfaceDetail to format interface information\r",
"# for each collection as a SP_INTERFACE_DEVICE_DETAIL_DATA structure.\r",
"# The device_path member of this structure contains the user-mode name\r",
"# that the application uses with the Win32 function CreateFile to\r",
"# obtain a file handle to a HID collection.\r",
"#\r",
"# get HID device class guid\r",
"guid",
"=",
"winapi",
".",
"GetHidGuid",
"(",
")",
"# retrieve all the available interface information.\r",
"results",
"=",
"[",
"]",
"required_size",
"=",
"DWORD",
"(",
")",
"info_data",
"=",
"winapi",
".",
"SP_DEVINFO_DATA",
"(",
")",
"info_data",
".",
"cb_size",
"=",
"sizeof",
"(",
"winapi",
".",
"SP_DEVINFO_DATA",
")",
"with",
"winapi",
".",
"DeviceInterfaceSetInfo",
"(",
"guid",
")",
"as",
"h_info",
":",
"for",
"interface_data",
"in",
"winapi",
".",
"enum_device_interfaces",
"(",
"h_info",
",",
"guid",
")",
":",
"device_path",
"=",
"winapi",
".",
"get_device_path",
"(",
"h_info",
",",
"interface_data",
",",
"byref",
"(",
"info_data",
")",
")",
"parent_device",
"=",
"c_ulong",
"(",
")",
"#get parent instance id (so we can discriminate on port)\r",
"if",
"setup_api",
".",
"CM_Get_Parent",
"(",
"byref",
"(",
"parent_device",
")",
",",
"info_data",
".",
"dev_inst",
",",
"0",
")",
"!=",
"0",
":",
"#CR_SUCCESS = 0\r",
"parent_device",
".",
"value",
"=",
"0",
"#null\r",
"#get unique instance id string\r",
"required_size",
".",
"value",
"=",
"0",
"winapi",
".",
"SetupDiGetDeviceInstanceId",
"(",
"h_info",
",",
"byref",
"(",
"info_data",
")",
",",
"None",
",",
"0",
",",
"byref",
"(",
"required_size",
")",
")",
"device_instance_id",
"=",
"create_unicode_buffer",
"(",
"required_size",
".",
"value",
")",
"if",
"required_size",
".",
"value",
">",
"0",
":",
"winapi",
".",
"SetupDiGetDeviceInstanceId",
"(",
"h_info",
",",
"byref",
"(",
"info_data",
")",
",",
"device_instance_id",
",",
"required_size",
",",
"byref",
"(",
"required_size",
")",
")",
"hid_device",
"=",
"HidDevice",
"(",
"device_path",
",",
"parent_device",
".",
"value",
",",
"device_instance_id",
".",
"value",
")",
"else",
":",
"hid_device",
"=",
"HidDevice",
"(",
"device_path",
",",
"parent_device",
".",
"value",
")",
"# add device to results, if not protected\r",
"if",
"hid_device",
".",
"vendor_id",
":",
"results",
".",
"append",
"(",
"hid_device",
")",
"return",
"results"
] | Finds all HID devices connected to the system | [
"Finds",
"all",
"HID",
"devices",
"connected",
"to",
"the",
"system"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L88-L156 |
1,393 | rene-aguirre/pywinusb | pywinusb/hid/core.py | show_hids | def show_hids(target_vid = 0, target_pid = 0, output = None):
"""Check all HID devices conected to PC hosts."""
# first be kind with local encodings
if not output:
# beware your script should manage encodings
output = sys.stdout
# then the big cheese...
from . import tools
all_hids = None
if target_vid:
if target_pid:
# both vendor and product Id provided
device_filter = HidDeviceFilter(vendor_id = target_vid,
product_id = target_pid)
else:
# only vendor id
device_filter = HidDeviceFilter(vendor_id = target_vid)
all_hids = device_filter.get_devices()
else:
all_hids = find_all_hid_devices()
if all_hids:
print("Found HID class devices!, writting details...")
for dev in all_hids:
device_name = str(dev)
output.write(device_name)
output.write('\n\n Path: %s\n' % dev.device_path)
output.write('\n Instance: %s\n' % dev.instance_id)
output.write('\n Port (ID): %s\n' % dev.get_parent_instance_id())
output.write('\n Port (str):%s\n' % str(dev.get_parent_device()))
#
try:
dev.open()
tools.write_documentation(dev, output)
finally:
dev.close()
print("done!")
else:
print("There's not any non system HID class device available") | python | def show_hids(target_vid = 0, target_pid = 0, output = None):
# first be kind with local encodings
if not output:
# beware your script should manage encodings
output = sys.stdout
# then the big cheese...
from . import tools
all_hids = None
if target_vid:
if target_pid:
# both vendor and product Id provided
device_filter = HidDeviceFilter(vendor_id = target_vid,
product_id = target_pid)
else:
# only vendor id
device_filter = HidDeviceFilter(vendor_id = target_vid)
all_hids = device_filter.get_devices()
else:
all_hids = find_all_hid_devices()
if all_hids:
print("Found HID class devices!, writting details...")
for dev in all_hids:
device_name = str(dev)
output.write(device_name)
output.write('\n\n Path: %s\n' % dev.device_path)
output.write('\n Instance: %s\n' % dev.instance_id)
output.write('\n Port (ID): %s\n' % dev.get_parent_instance_id())
output.write('\n Port (str):%s\n' % str(dev.get_parent_device()))
#
try:
dev.open()
tools.write_documentation(dev, output)
finally:
dev.close()
print("done!")
else:
print("There's not any non system HID class device available") | [
"def",
"show_hids",
"(",
"target_vid",
"=",
"0",
",",
"target_pid",
"=",
"0",
",",
"output",
"=",
"None",
")",
":",
"# first be kind with local encodings\r",
"if",
"not",
"output",
":",
"# beware your script should manage encodings\r",
"output",
"=",
"sys",
".",
"stdout",
"# then the big cheese...\r",
"from",
".",
"import",
"tools",
"all_hids",
"=",
"None",
"if",
"target_vid",
":",
"if",
"target_pid",
":",
"# both vendor and product Id provided\r",
"device_filter",
"=",
"HidDeviceFilter",
"(",
"vendor_id",
"=",
"target_vid",
",",
"product_id",
"=",
"target_pid",
")",
"else",
":",
"# only vendor id\r",
"device_filter",
"=",
"HidDeviceFilter",
"(",
"vendor_id",
"=",
"target_vid",
")",
"all_hids",
"=",
"device_filter",
".",
"get_devices",
"(",
")",
"else",
":",
"all_hids",
"=",
"find_all_hid_devices",
"(",
")",
"if",
"all_hids",
":",
"print",
"(",
"\"Found HID class devices!, writting details...\"",
")",
"for",
"dev",
"in",
"all_hids",
":",
"device_name",
"=",
"str",
"(",
"dev",
")",
"output",
".",
"write",
"(",
"device_name",
")",
"output",
".",
"write",
"(",
"'\\n\\n Path: %s\\n'",
"%",
"dev",
".",
"device_path",
")",
"output",
".",
"write",
"(",
"'\\n Instance: %s\\n'",
"%",
"dev",
".",
"instance_id",
")",
"output",
".",
"write",
"(",
"'\\n Port (ID): %s\\n'",
"%",
"dev",
".",
"get_parent_instance_id",
"(",
")",
")",
"output",
".",
"write",
"(",
"'\\n Port (str):%s\\n'",
"%",
"str",
"(",
"dev",
".",
"get_parent_device",
"(",
")",
")",
")",
"#\r",
"try",
":",
"dev",
".",
"open",
"(",
")",
"tools",
".",
"write_documentation",
"(",
"dev",
",",
"output",
")",
"finally",
":",
"dev",
".",
"close",
"(",
")",
"print",
"(",
"\"done!\"",
")",
"else",
":",
"print",
"(",
"\"There's not any non system HID class device available\"",
")"
] | Check all HID devices conected to PC hosts. | [
"Check",
"all",
"HID",
"devices",
"conected",
"to",
"PC",
"hosts",
"."
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L1571-L1609 |
1,394 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidDeviceFilter.get_devices_by_parent | def get_devices_by_parent(self, hid_filter=None):
"""Group devices returned from filter query in order \
by devcice parent id.
"""
all_devs = self.get_devices(hid_filter)
dev_group = dict()
for hid_device in all_devs:
#keep a list of known devices matching parent device Ids
parent_id = hid_device.get_parent_instance_id()
device_set = dev_group.get(parent_id, [])
device_set.append(hid_device)
if parent_id not in dev_group:
#add new
dev_group[parent_id] = device_set
return dev_group | python | def get_devices_by_parent(self, hid_filter=None):
all_devs = self.get_devices(hid_filter)
dev_group = dict()
for hid_device in all_devs:
#keep a list of known devices matching parent device Ids
parent_id = hid_device.get_parent_instance_id()
device_set = dev_group.get(parent_id, [])
device_set.append(hid_device)
if parent_id not in dev_group:
#add new
dev_group[parent_id] = device_set
return dev_group | [
"def",
"get_devices_by_parent",
"(",
"self",
",",
"hid_filter",
"=",
"None",
")",
":",
"all_devs",
"=",
"self",
".",
"get_devices",
"(",
"hid_filter",
")",
"dev_group",
"=",
"dict",
"(",
")",
"for",
"hid_device",
"in",
"all_devs",
":",
"#keep a list of known devices matching parent device Ids\r",
"parent_id",
"=",
"hid_device",
".",
"get_parent_instance_id",
"(",
")",
"device_set",
"=",
"dev_group",
".",
"get",
"(",
"parent_id",
",",
"[",
"]",
")",
"device_set",
".",
"append",
"(",
"hid_device",
")",
"if",
"parent_id",
"not",
"in",
"dev_group",
":",
"#add new\r",
"dev_group",
"[",
"parent_id",
"]",
"=",
"device_set",
"return",
"dev_group"
] | Group devices returned from filter query in order \
by devcice parent id. | [
"Group",
"devices",
"returned",
"from",
"filter",
"query",
"in",
"order",
"\\",
"by",
"devcice",
"parent",
"id",
"."
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L168-L182 |
1,395 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidDeviceFilter.get_devices | def get_devices(self, hid_filter = None):
"""Filter a HID device list by current object parameters. Devices
must match the all of the filtering parameters
"""
if not hid_filter: #empty list or called without any parameters
if type(hid_filter) == type(None):
#request to query connected devices
hid_filter = find_all_hid_devices()
else:
return hid_filter
#initially all accepted
results = {}.fromkeys(hid_filter)
#the filter parameters
validating_attributes = list(self.filter_params.keys())
#first filter out restricted access devices
if not len(results):
return {}
for device in list(results.keys()):
if not device.is_active():
del results[device]
if not len(results):
return {}
#filter out
for item in validating_attributes:
if item.endswith("_includes"):
item = item[:-len("_includes")]
elif item.endswith("_mask"):
item = item[:-len("_mask")]
elif item +"_mask" in self.filter_params or item + "_includes" \
in self.filter_params:
continue # value mask or string search is being queried
elif item not in HidDevice.filter_attributes:
continue # field does not exist sys.error.write(...)
#start filtering out
for device in list(results.keys()):
if not hasattr(device, item):
del results[device]
elif item + "_mask" in validating_attributes:
#masked value
if getattr(device, item) & self.filter_params[item + \
"_mask"] != self.filter_params[item] \
& self.filter_params[item + "_mask"]:
del results[device]
elif item + "_includes" in validating_attributes:
#subset item
if self.filter_params[item + "_includes"] not in \
getattr(device, item):
del results[device]
else:
#plain comparison
if getattr(device, item) != self.filter_params[item]:
del results[device]
#
return list(results.keys()) | python | def get_devices(self, hid_filter = None):
if not hid_filter: #empty list or called without any parameters
if type(hid_filter) == type(None):
#request to query connected devices
hid_filter = find_all_hid_devices()
else:
return hid_filter
#initially all accepted
results = {}.fromkeys(hid_filter)
#the filter parameters
validating_attributes = list(self.filter_params.keys())
#first filter out restricted access devices
if not len(results):
return {}
for device in list(results.keys()):
if not device.is_active():
del results[device]
if not len(results):
return {}
#filter out
for item in validating_attributes:
if item.endswith("_includes"):
item = item[:-len("_includes")]
elif item.endswith("_mask"):
item = item[:-len("_mask")]
elif item +"_mask" in self.filter_params or item + "_includes" \
in self.filter_params:
continue # value mask or string search is being queried
elif item not in HidDevice.filter_attributes:
continue # field does not exist sys.error.write(...)
#start filtering out
for device in list(results.keys()):
if not hasattr(device, item):
del results[device]
elif item + "_mask" in validating_attributes:
#masked value
if getattr(device, item) & self.filter_params[item + \
"_mask"] != self.filter_params[item] \
& self.filter_params[item + "_mask"]:
del results[device]
elif item + "_includes" in validating_attributes:
#subset item
if self.filter_params[item + "_includes"] not in \
getattr(device, item):
del results[device]
else:
#plain comparison
if getattr(device, item) != self.filter_params[item]:
del results[device]
#
return list(results.keys()) | [
"def",
"get_devices",
"(",
"self",
",",
"hid_filter",
"=",
"None",
")",
":",
"if",
"not",
"hid_filter",
":",
"#empty list or called without any parameters\r",
"if",
"type",
"(",
"hid_filter",
")",
"==",
"type",
"(",
"None",
")",
":",
"#request to query connected devices\r",
"hid_filter",
"=",
"find_all_hid_devices",
"(",
")",
"else",
":",
"return",
"hid_filter",
"#initially all accepted\r",
"results",
"=",
"{",
"}",
".",
"fromkeys",
"(",
"hid_filter",
")",
"#the filter parameters\r",
"validating_attributes",
"=",
"list",
"(",
"self",
".",
"filter_params",
".",
"keys",
"(",
")",
")",
"#first filter out restricted access devices\r",
"if",
"not",
"len",
"(",
"results",
")",
":",
"return",
"{",
"}",
"for",
"device",
"in",
"list",
"(",
"results",
".",
"keys",
"(",
")",
")",
":",
"if",
"not",
"device",
".",
"is_active",
"(",
")",
":",
"del",
"results",
"[",
"device",
"]",
"if",
"not",
"len",
"(",
"results",
")",
":",
"return",
"{",
"}",
"#filter out\r",
"for",
"item",
"in",
"validating_attributes",
":",
"if",
"item",
".",
"endswith",
"(",
"\"_includes\"",
")",
":",
"item",
"=",
"item",
"[",
":",
"-",
"len",
"(",
"\"_includes\"",
")",
"]",
"elif",
"item",
".",
"endswith",
"(",
"\"_mask\"",
")",
":",
"item",
"=",
"item",
"[",
":",
"-",
"len",
"(",
"\"_mask\"",
")",
"]",
"elif",
"item",
"+",
"\"_mask\"",
"in",
"self",
".",
"filter_params",
"or",
"item",
"+",
"\"_includes\"",
"in",
"self",
".",
"filter_params",
":",
"continue",
"# value mask or string search is being queried\r",
"elif",
"item",
"not",
"in",
"HidDevice",
".",
"filter_attributes",
":",
"continue",
"# field does not exist sys.error.write(...)\r",
"#start filtering out\r",
"for",
"device",
"in",
"list",
"(",
"results",
".",
"keys",
"(",
")",
")",
":",
"if",
"not",
"hasattr",
"(",
"device",
",",
"item",
")",
":",
"del",
"results",
"[",
"device",
"]",
"elif",
"item",
"+",
"\"_mask\"",
"in",
"validating_attributes",
":",
"#masked value\r",
"if",
"getattr",
"(",
"device",
",",
"item",
")",
"&",
"self",
".",
"filter_params",
"[",
"item",
"+",
"\"_mask\"",
"]",
"!=",
"self",
".",
"filter_params",
"[",
"item",
"]",
"&",
"self",
".",
"filter_params",
"[",
"item",
"+",
"\"_mask\"",
"]",
":",
"del",
"results",
"[",
"device",
"]",
"elif",
"item",
"+",
"\"_includes\"",
"in",
"validating_attributes",
":",
"#subset item\r",
"if",
"self",
".",
"filter_params",
"[",
"item",
"+",
"\"_includes\"",
"]",
"not",
"in",
"getattr",
"(",
"device",
",",
"item",
")",
":",
"del",
"results",
"[",
"device",
"]",
"else",
":",
"#plain comparison\r",
"if",
"getattr",
"(",
"device",
",",
"item",
")",
"!=",
"self",
".",
"filter_params",
"[",
"item",
"]",
":",
"del",
"results",
"[",
"device",
"]",
"#\r",
"return",
"list",
"(",
"results",
".",
"keys",
"(",
")",
")"
] | Filter a HID device list by current object parameters. Devices
must match the all of the filtering parameters | [
"Filter",
"a",
"HID",
"device",
"list",
"by",
"current",
"object",
"parameters",
".",
"Devices",
"must",
"match",
"the",
"all",
"of",
"the",
"filtering",
"parameters"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L184-L242 |
1,396 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidDevice.get_parent_device | def get_parent_device(self):
"""Retreive parent device string id"""
if not self.parent_instance_id:
return ""
dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN
dev_buffer = dev_buffer_type()
try:
if winapi.CM_Get_Device_ID(self.parent_instance_id, byref(dev_buffer),
MAX_DEVICE_ID_LEN, 0) == 0: #success
return dev_buffer.value
return ""
finally:
del dev_buffer
del dev_buffer_type | python | def get_parent_device(self):
if not self.parent_instance_id:
return ""
dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN
dev_buffer = dev_buffer_type()
try:
if winapi.CM_Get_Device_ID(self.parent_instance_id, byref(dev_buffer),
MAX_DEVICE_ID_LEN, 0) == 0: #success
return dev_buffer.value
return ""
finally:
del dev_buffer
del dev_buffer_type | [
"def",
"get_parent_device",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent_instance_id",
":",
"return",
"\"\"",
"dev_buffer_type",
"=",
"winapi",
".",
"c_tchar",
"*",
"MAX_DEVICE_ID_LEN",
"dev_buffer",
"=",
"dev_buffer_type",
"(",
")",
"try",
":",
"if",
"winapi",
".",
"CM_Get_Device_ID",
"(",
"self",
".",
"parent_instance_id",
",",
"byref",
"(",
"dev_buffer",
")",
",",
"MAX_DEVICE_ID_LEN",
",",
"0",
")",
"==",
"0",
":",
"#success\r",
"return",
"dev_buffer",
".",
"value",
"return",
"\"\"",
"finally",
":",
"del",
"dev_buffer",
"del",
"dev_buffer_type"
] | Retreive parent device string id | [
"Retreive",
"parent",
"device",
"string",
"id"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L266-L279 |
1,397 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidDevice.get_physical_descriptor | def get_physical_descriptor(self):
"""Returns physical HID device descriptor
"""
raw_data_type = c_ubyte * 1024
raw_data = raw_data_type()
if hid_dll.HidD_GetPhysicalDescriptor(self.hid_handle,
byref(raw_data), 1024 ):
return [x for x in raw_data]
return [] | python | def get_physical_descriptor(self):
raw_data_type = c_ubyte * 1024
raw_data = raw_data_type()
if hid_dll.HidD_GetPhysicalDescriptor(self.hid_handle,
byref(raw_data), 1024 ):
return [x for x in raw_data]
return [] | [
"def",
"get_physical_descriptor",
"(",
"self",
")",
":",
"raw_data_type",
"=",
"c_ubyte",
"*",
"1024",
"raw_data",
"=",
"raw_data_type",
"(",
")",
"if",
"hid_dll",
".",
"HidD_GetPhysicalDescriptor",
"(",
"self",
".",
"hid_handle",
",",
"byref",
"(",
"raw_data",
")",
",",
"1024",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"raw_data",
"]",
"return",
"[",
"]"
] | Returns physical HID device descriptor | [
"Returns",
"physical",
"HID",
"device",
"descriptor"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L510-L518 |
1,398 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidDevice.close | def close(self):
"""Release system resources"""
# free parsed data
if not self.is_opened():
return
self.__open_status = False
# abort all running threads first
if self.__reading_thread and self.__reading_thread.is_alive():
self.__reading_thread.abort()
#avoid posting new reports
if self._input_report_queue:
self._input_report_queue.release_events()
if self.__input_processing_thread and \
self.__input_processing_thread.is_alive():
self.__input_processing_thread.abort()
#properly close API handlers and pointers
if self.ptr_preparsed_data:
ptr_preparsed_data = self.ptr_preparsed_data
self.ptr_preparsed_data = None
hid_dll.HidD_FreePreparsedData(ptr_preparsed_data)
# wait for the reading thread to complete before closing device handle
if self.__reading_thread:
self.__reading_thread.join()
if self.hid_handle:
winapi.CloseHandle(self.hid_handle)
# make sure report procesing thread is closed
if self.__input_processing_thread:
self.__input_processing_thread.join()
#reset vars (for GC)
button_caps_storage = self.__button_caps_storage
self.__reset_vars()
while button_caps_storage:
item = button_caps_storage.pop()
del item | python | def close(self):
# free parsed data
if not self.is_opened():
return
self.__open_status = False
# abort all running threads first
if self.__reading_thread and self.__reading_thread.is_alive():
self.__reading_thread.abort()
#avoid posting new reports
if self._input_report_queue:
self._input_report_queue.release_events()
if self.__input_processing_thread and \
self.__input_processing_thread.is_alive():
self.__input_processing_thread.abort()
#properly close API handlers and pointers
if self.ptr_preparsed_data:
ptr_preparsed_data = self.ptr_preparsed_data
self.ptr_preparsed_data = None
hid_dll.HidD_FreePreparsedData(ptr_preparsed_data)
# wait for the reading thread to complete before closing device handle
if self.__reading_thread:
self.__reading_thread.join()
if self.hid_handle:
winapi.CloseHandle(self.hid_handle)
# make sure report procesing thread is closed
if self.__input_processing_thread:
self.__input_processing_thread.join()
#reset vars (for GC)
button_caps_storage = self.__button_caps_storage
self.__reset_vars()
while button_caps_storage:
item = button_caps_storage.pop()
del item | [
"def",
"close",
"(",
"self",
")",
":",
"# free parsed data\r",
"if",
"not",
"self",
".",
"is_opened",
"(",
")",
":",
"return",
"self",
".",
"__open_status",
"=",
"False",
"# abort all running threads first\r",
"if",
"self",
".",
"__reading_thread",
"and",
"self",
".",
"__reading_thread",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"__reading_thread",
".",
"abort",
"(",
")",
"#avoid posting new reports\r",
"if",
"self",
".",
"_input_report_queue",
":",
"self",
".",
"_input_report_queue",
".",
"release_events",
"(",
")",
"if",
"self",
".",
"__input_processing_thread",
"and",
"self",
".",
"__input_processing_thread",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"__input_processing_thread",
".",
"abort",
"(",
")",
"#properly close API handlers and pointers\r",
"if",
"self",
".",
"ptr_preparsed_data",
":",
"ptr_preparsed_data",
"=",
"self",
".",
"ptr_preparsed_data",
"self",
".",
"ptr_preparsed_data",
"=",
"None",
"hid_dll",
".",
"HidD_FreePreparsedData",
"(",
"ptr_preparsed_data",
")",
"# wait for the reading thread to complete before closing device handle\r",
"if",
"self",
".",
"__reading_thread",
":",
"self",
".",
"__reading_thread",
".",
"join",
"(",
")",
"if",
"self",
".",
"hid_handle",
":",
"winapi",
".",
"CloseHandle",
"(",
"self",
".",
"hid_handle",
")",
"# make sure report procesing thread is closed\r",
"if",
"self",
".",
"__input_processing_thread",
":",
"self",
".",
"__input_processing_thread",
".",
"join",
"(",
")",
"#reset vars (for GC)\r",
"button_caps_storage",
"=",
"self",
".",
"__button_caps_storage",
"self",
".",
"__reset_vars",
"(",
")",
"while",
"button_caps_storage",
":",
"item",
"=",
"button_caps_storage",
".",
"pop",
"(",
")",
"del",
"item"
] | Release system resources | [
"Release",
"system",
"resources"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L612-L654 |
1,399 | rene-aguirre/pywinusb | pywinusb/hid/core.py | HidDevice._process_raw_report | def _process_raw_report(self, raw_report):
"Default raw input report data handler"
if not self.is_opened():
return
if not self.__evt_handlers and not self.__raw_handler:
return
if not raw_report[0] and \
(raw_report[0] not in self.__input_report_templates):
# windows sends an empty array when disconnecting
# but, this might have a collision with report_id = 0
if not hid_device_path_exists(self.device_path):
#windows XP sends empty report when disconnecting
self.__reading_thread.abort() #device disconnected
return
if self.__raw_handler:
#this might slow down data throughput, but at the expense of safety
self.__raw_handler(helpers.ReadOnlyList(raw_report))
return
# using pre-parsed report templates, by report id
report_template = self.__input_report_templates[raw_report[0]]
# old condition snapshot
old_values = report_template.get_usages()
# parse incoming data
report_template.set_raw_data(raw_report)
# and compare it
event_applies = self.evt_decision
evt_handlers = self.__evt_handlers
for key in report_template.keys():
if key not in evt_handlers:
continue
#check if event handler exist!
for event_kind, handlers in evt_handlers[key].items():
#key=event_kind, values=handler set
new_value = report_template[key].value
if not event_applies[event_kind](old_values[key], new_value):
continue
#decision applies, call handlers
for function_handler in handlers:
#check if the application wants some particular parameter
if handlers[function_handler]:
function_handler(new_value,
event_kind, handlers[function_handler])
else:
function_handler(new_value, event_kind) | python | def _process_raw_report(self, raw_report):
"Default raw input report data handler"
if not self.is_opened():
return
if not self.__evt_handlers and not self.__raw_handler:
return
if not raw_report[0] and \
(raw_report[0] not in self.__input_report_templates):
# windows sends an empty array when disconnecting
# but, this might have a collision with report_id = 0
if not hid_device_path_exists(self.device_path):
#windows XP sends empty report when disconnecting
self.__reading_thread.abort() #device disconnected
return
if self.__raw_handler:
#this might slow down data throughput, but at the expense of safety
self.__raw_handler(helpers.ReadOnlyList(raw_report))
return
# using pre-parsed report templates, by report id
report_template = self.__input_report_templates[raw_report[0]]
# old condition snapshot
old_values = report_template.get_usages()
# parse incoming data
report_template.set_raw_data(raw_report)
# and compare it
event_applies = self.evt_decision
evt_handlers = self.__evt_handlers
for key in report_template.keys():
if key not in evt_handlers:
continue
#check if event handler exist!
for event_kind, handlers in evt_handlers[key].items():
#key=event_kind, values=handler set
new_value = report_template[key].value
if not event_applies[event_kind](old_values[key], new_value):
continue
#decision applies, call handlers
for function_handler in handlers:
#check if the application wants some particular parameter
if handlers[function_handler]:
function_handler(new_value,
event_kind, handlers[function_handler])
else:
function_handler(new_value, event_kind) | [
"def",
"_process_raw_report",
"(",
"self",
",",
"raw_report",
")",
":",
"if",
"not",
"self",
".",
"is_opened",
"(",
")",
":",
"return",
"if",
"not",
"self",
".",
"__evt_handlers",
"and",
"not",
"self",
".",
"__raw_handler",
":",
"return",
"if",
"not",
"raw_report",
"[",
"0",
"]",
"and",
"(",
"raw_report",
"[",
"0",
"]",
"not",
"in",
"self",
".",
"__input_report_templates",
")",
":",
"# windows sends an empty array when disconnecting\r",
"# but, this might have a collision with report_id = 0\r",
"if",
"not",
"hid_device_path_exists",
"(",
"self",
".",
"device_path",
")",
":",
"#windows XP sends empty report when disconnecting\r",
"self",
".",
"__reading_thread",
".",
"abort",
"(",
")",
"#device disconnected\r",
"return",
"if",
"self",
".",
"__raw_handler",
":",
"#this might slow down data throughput, but at the expense of safety\r",
"self",
".",
"__raw_handler",
"(",
"helpers",
".",
"ReadOnlyList",
"(",
"raw_report",
")",
")",
"return",
"# using pre-parsed report templates, by report id\r",
"report_template",
"=",
"self",
".",
"__input_report_templates",
"[",
"raw_report",
"[",
"0",
"]",
"]",
"# old condition snapshot\r",
"old_values",
"=",
"report_template",
".",
"get_usages",
"(",
")",
"# parse incoming data\r",
"report_template",
".",
"set_raw_data",
"(",
"raw_report",
")",
"# and compare it\r",
"event_applies",
"=",
"self",
".",
"evt_decision",
"evt_handlers",
"=",
"self",
".",
"__evt_handlers",
"for",
"key",
"in",
"report_template",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"evt_handlers",
":",
"continue",
"#check if event handler exist!\r",
"for",
"event_kind",
",",
"handlers",
"in",
"evt_handlers",
"[",
"key",
"]",
".",
"items",
"(",
")",
":",
"#key=event_kind, values=handler set\r",
"new_value",
"=",
"report_template",
"[",
"key",
"]",
".",
"value",
"if",
"not",
"event_applies",
"[",
"event_kind",
"]",
"(",
"old_values",
"[",
"key",
"]",
",",
"new_value",
")",
":",
"continue",
"#decision applies, call handlers\r",
"for",
"function_handler",
"in",
"handlers",
":",
"#check if the application wants some particular parameter\r",
"if",
"handlers",
"[",
"function_handler",
"]",
":",
"function_handler",
"(",
"new_value",
",",
"event_kind",
",",
"handlers",
"[",
"function_handler",
"]",
")",
"else",
":",
"function_handler",
"(",
"new_value",
",",
"event_kind",
")"
] | Default raw input report data handler | [
"Default",
"raw",
"input",
"report",
"data",
"handler"
] | 954c4b2105d9f01cb0c50e24500bb747d4ecdc43 | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L717-L763 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.