_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1300
|
IPv6_Opts._read_opt_mpl
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1301
|
IPv6_Route.read_ipv6_route
|
train
|
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 =
|
python
|
{
"resource": ""
}
|
q1302
|
IPv6_Route._read_data_type_none
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1303
|
IPv6_Route._read_data_type_src
|
train
|
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] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. . .
. . .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
|
python
|
{
"resource": ""
}
|
q1304
|
IPv6_Route._read_data_type_2
|
train
|
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 +
| |
+ +
| |
|
python
|
{
"resource": ""
}
|
q1305
|
IPv6_Route._read_data_type_rpl
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1306
|
write_oggopus_output_gain
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1307
|
_compute_ogg_page_crc
|
train
|
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 + \
|
python
|
{
"resource": ""
}
|
q1308
|
format_ffmpeg_filter
|
train
|
def format_ffmpeg_filter(name, params):
""" Build a string to call a FFMpeg filter. """
return "%s=%s" % (name,
|
python
|
{
"resource": ""
}
|
q1309
|
scan
|
train
|
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() ==
|
python
|
{
"resource": ""
}
|
q1310
|
show_scan_report
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1311
|
get_requirements
|
train
|
def get_requirements(source):
"""Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements
|
python
|
{
"resource": ""
}
|
q1312
|
CloudFlareMiddleware.is_cloudflare_challenge
|
train
|
def is_cloudflare_challenge(response):
"""Test if the given response contains the cloudflare's anti-bot protection"""
return (
response.status == 503
|
python
|
{
"resource": ""
}
|
q1313
|
CloudFlareMiddleware.process_response
|
train
|
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')
|
python
|
{
"resource": ""
}
|
q1314
|
TokenSession.enter_captcha
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1315
|
ImplicitSession._process_auth_form
|
train
|
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',
|
python
|
{
"resource": ""
}
|
q1316
|
ImplicitSession._process_2auth_form
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1317
|
ImplicitSession._process_access_form
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1318
|
BaseLongPoll.wait
|
train
|
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,
|
python
|
{
"resource": ""
}
|
q1319
|
pdf
|
train
|
def pdf(alphas):
'''Returns a Dirichlet PDF function'''
alphap = alphas - 1
c = np.exp(gammaln(alphas.sum()) -
|
python
|
{
"resource": ""
}
|
q1320
|
meanprecision
|
train
|
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.
|
python
|
{
"resource": ""
}
|
q1321
|
_fixedpoint
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1322
|
_meanprecision
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1323
|
_fit_s
|
train
|
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()
|
python
|
{
"resource": ""
}
|
q1324
|
_fit_m
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1325
|
_piecewise
|
train
|
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.
|
python
|
{
"resource": ""
}
|
q1326
|
_init_a
|
train
|
def _init_a(D):
'''Initial guess for Dirichlet alpha parameters given data
|
python
|
{
"resource": ""
}
|
q1327
|
scatter
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1328
|
contour
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1329
|
contourf
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1330
|
_contour
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1331
|
disable_on_env
|
train
|
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]
|
python
|
{
"resource": ""
}
|
q1332
|
disable_checker_on_env
|
train
|
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', '')
|
python
|
{
"resource": ""
}
|
q1333
|
string
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1334
|
iterable
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1335
|
not_empty
|
train
|
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>`
|
python
|
{
"resource": ""
}
|
q1336
|
variable_name
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1337
|
json
|
train
|
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
|
{
"resource": ""
}
|
q1338
|
numeric
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1339
|
_numeric_coercion
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1340
|
path
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1341
|
path_exists
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1342
|
file_exists
|
train
|
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``
|
python
|
{
"resource": ""
}
|
q1343
|
directory_exists
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1344
|
readable
|
train
|
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``
|
python
|
{
"resource": ""
}
|
q1345
|
writeable
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1346
|
executable
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1347
|
url
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1348
|
domain
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1349
|
ip_address
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1350
|
ipv4
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1351
|
ipv6
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1352
|
mac_address
|
train
|
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``
"""
|
python
|
{
"resource": ""
}
|
q1353
|
is_type
|
train
|
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``.
|
python
|
{
"resource": ""
}
|
q1354
|
_check_base_classes
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1355
|
are_equivalent
|
train
|
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):
|
python
|
{
"resource": ""
}
|
q1356
|
is_json
|
train
|
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.
|
python
|
{
"resource": ""
}
|
q1357
|
is_string
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1358
|
is_iterable
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1359
|
is_not_empty
|
train
|
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
"""
|
python
|
{
"resource": ""
}
|
q1360
|
is_variable_name
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1361
|
is_numeric
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1362
|
is_integer
|
train
|
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:
|
python
|
{
"resource": ""
}
|
q1363
|
is_pathlike
|
train
|
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>`
|
python
|
{
"resource": ""
}
|
q1364
|
is_on_filesystem
|
train
|
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.
|
python
|
{
"resource": ""
}
|
q1365
|
is_file
|
train
|
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>`
|
python
|
{
"resource": ""
}
|
q1366
|
is_directory
|
train
|
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>`
|
python
|
{
"resource": ""
}
|
q1367
|
is_readable
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1368
|
is_writeable
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1369
|
is_executable
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1370
|
is_email
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1371
|
is_url
|
train
|
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
|
{
"resource": ""
}
|
q1372
|
is_domain
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1373
|
is_ipv4
|
train
|
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>`
|
python
|
{
"resource": ""
}
|
q1374
|
is_ipv6
|
train
|
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>`
|
python
|
{
"resource": ""
}
|
q1375
|
is_mac_address
|
train
|
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>`
|
python
|
{
"resource": ""
}
|
q1376
|
RailroadLayout.draw_line
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1377
|
get_file_fields
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1378
|
remove_media
|
train
|
def remove_media(files):
"""
Delete file from media dir
"""
for filename in files:
|
python
|
{
"resource": ""
}
|
q1379
|
remove_empty_dirs
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1380
|
get_used_media
|
train
|
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 = {
|
python
|
{
"resource": ""
}
|
q1381
|
get_all_media
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1382
|
get_unused_media
|
train
|
def get_unused_media(exclude=None):
"""
Get media which are not used in models
"""
if not exclude:
exclude = []
|
python
|
{
"resource": ""
}
|
q1383
|
cspace_converter
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1384
|
cspace_convert
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1385
|
as_XYZ100_w
|
train
|
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.
|
python
|
{
"resource": ""
}
|
q1386
|
machado_et_al_2009_matrix
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1387
|
Signature._make_retval_checker
|
train
|
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" %
|
python
|
{
"resource": ""
}
|
q1388
|
Signature._make_args_checker
|
train
|
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)
):
|
python
|
{
"resource": ""
}
|
q1389
|
checker_for_type
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1390
|
_prepare_value
|
train
|
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]
|
python
|
{
"resource": ""
}
|
q1391
|
Trainer.train
|
train
|
def train(self, text, className):
"""
enhances trained data using the given text and class
"""
self.data.increaseClass(className)
|
python
|
{
"resource": ""
}
|
q1392
|
find_all_hid_devices
|
train
|
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.
#
|
python
|
{
"resource": ""
}
|
q1393
|
show_hids
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1394
|
HidDeviceFilter.get_devices_by_parent
|
train
|
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
|
python
|
{
"resource": ""
}
|
q1395
|
HidDeviceFilter.get_devices
|
train
|
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"):
|
python
|
{
"resource": ""
}
|
q1396
|
HidDevice.get_parent_device
|
train
|
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),
|
python
|
{
"resource": ""
}
|
q1397
|
HidDevice.get_physical_descriptor
|
train
|
def get_physical_descriptor(self):
"""Returns physical HID device descriptor
"""
raw_data_type = c_ubyte * 1024
raw_data = raw_data_type()
|
python
|
{
"resource": ""
}
|
q1398
|
HidDevice.close
|
train
|
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)
|
python
|
{
"resource": ""
}
|
q1399
|
HidDevice._process_raw_report
|
train
|
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:
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.