_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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 ...
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 | +-+...
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 | ...
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 | +-+-...
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| +-+-+-+-+-+-+-+-+-...
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 +-+-+-+-+-+-...
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....
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 + \ page[OGG_FIRST_PAGE_HEADER_CRC_OFFSET + OGG_FIRST_PAGE_HEADER_CRC.size:] return ogg_page_crc(page_zero_crc)
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, ":".join("%s=%s" % (k, v) for k, v in params.items()))
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 i...
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 = "%....
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 """ install_reqs = parse_requirements(filename=source, session=PipSession()) return [str(ir.req) for ir in install_reqs]
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 and response.headers.get('Server', '').startswith(b'cloudflare') and 'jschl_vc' in response.text and 'jsc...
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, tryi...
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 id. I do not know why pass here but may be useful :return captcha value """ raise VkCaptchaNeeded(url,...
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.f...
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) ...
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 """ # Parse page p = AccessPageParser() p.feed(html) p.close() form_url ...
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, } ...
python
{ "resource": "" }
q1319
pdf
train
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
{ "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. precision : float Precision or con...
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...
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...
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)).s...
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 if norm(a1 - a0) < tol: return a...
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): ...
python
{ "resource": "" }
q1326
_init_a
train
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
{ "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 =...
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,...
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 ``**kwargs`` are passed on to :func:`plt.tricontourf`.''' return _contour(f, vertexl...
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...
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 ``fu...
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...
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:...
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 ``T...
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:`EmptyValueErro...
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 ...
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...
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 :o...
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....
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:`EmptyValueErro...
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 emp...
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 ``F...
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 ``...
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 ...
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 ...
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 t...
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/ht...
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...
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 IPv...
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....
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:`EmptyValue...
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:...
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:is...
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 break else: return_valu...
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 checke...
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 ...
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 ``Tr...
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 t...
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 duplica...
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 v...
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. ...
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 re...
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>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameter...
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. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if `...
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>` :raises SyntaxError: if ``kwargs`` contains duplica...
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>` :raises SyntaxError: if ``kwargs`` contai...
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 ...
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 man...
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...
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 str...
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>`_, ...
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``...
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>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword par...
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>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword par...
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>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword param...
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,...
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 model._meta.get_fields(): if isinstance(field, models.FileField): ...
python
{ "resource": "" }
q1378
remove_media
train
def remove_media(files): """ Delete file from media dir """ for filename in files: os.remove(os.path.join(settings.MEDIA_ROOT, filename))
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 listdir = [os.path.join(path, filename) for filename in os.listdir(path)]...
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 = { '%s' % field.name: '', } storage = field.storage ...
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)) ...
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 = [] all_media = get_all_media(exclude) used_media = get_used_media() return all_media - used_media
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 ...
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 :ref:`supported-colorspaces` for details. """ converter = cspace_conv...
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 anywhe...
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 ...
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 r...
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) ...
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) i...
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...
python
{ "resource": "" }
q1391
Trainer.train
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 = s...
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-de...
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 ...
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 match...
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): ...
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...
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() if hid_dll.HidD_GetPhysicalDescriptor(self.hid_handle, byref(raw_data), 1024 ): return [x for x in raw_data] ...
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_...
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...
python
{ "resource": "" }