repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
box/genty | genty/genty.py | _build_final_method_name | python | def _build_final_method_name(
method_name,
dataset_name,
dataprovider_name,
repeat_suffix,
):
# For tests using a dataprovider, append "_<dataprovider_name>" to
# the test method name
suffix = ''
if dataprovider_name:
suffix = '_{0}'.format(dataprovider_name)
... | Return a nice human friendly name, that almost looks like code.
Example: a test called 'test_something' with a dataset of (5, 'hello')
Return: "test_something(5, 'hello')"
Example: a test called 'test_other_stuff' with dataset of (9) and repeats
Return: "test_other_stuff(9) iteration_<X>"
... | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L270-L335 | null | # coding: utf-8
from __future__ import absolute_import, unicode_literals
import functools
from itertools import chain
import math
import re
import sys
import types
import six
from .genty_args import GentyArgs
from .private import encode_non_ascii_string
REPLACE_FOR_PERIOD_CHAR = '\xb7'
def genty(target_cls):
... |
box/genty | genty/genty.py | _build_dataset_method | python | def _build_dataset_method(method, dataset):
if isinstance(dataset, GentyArgs):
test_method = lambda my_self: method(
my_self,
*dataset.args,
**dataset.kwargs
)
else:
test_method = lambda my_self: method(
my_self,
*dataset
... | Return a fabricated method that marshals the dataset into parameters
for given 'method'
:param method:
The underlying test method.
:type method:
`callable`
:param dataset:
Tuple or GentyArgs instance containing the args of the dataset.
:type dataset:
`tuple` or :class... | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L338-L366 | null | # coding: utf-8
from __future__ import absolute_import, unicode_literals
import functools
from itertools import chain
import math
import re
import sys
import types
import six
from .genty_args import GentyArgs
from .private import encode_non_ascii_string
REPLACE_FOR_PERIOD_CHAR = '\xb7'
def genty(target_cls):
... |
box/genty | genty/genty.py | _build_dataprovider_method | python | def _build_dataprovider_method(method, dataset, dataprovider):
if isinstance(dataset, GentyArgs):
final_args = dataset.args
final_kwargs = dataset.kwargs
else:
final_args = dataset
final_kwargs = {}
def test_method_wrapper(my_self):
args = dataprovider(
m... | Return a fabricated method that calls the dataprovider with the given
dataset, and marshals the return value from that into params to the
underlying test 'method'.
:param method:
The underlying test method.
:type method:
`callable`
:param dataset:
Tuple or GentyArgs instance ... | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L369-L416 | null | # coding: utf-8
from __future__ import absolute_import, unicode_literals
import functools
from itertools import chain
import math
import re
import sys
import types
import six
from .genty_args import GentyArgs
from .private import encode_non_ascii_string
REPLACE_FOR_PERIOD_CHAR = '\xb7'
def genty(target_cls):
... |
box/genty | genty/genty.py | _add_method_to_class | python | def _add_method_to_class(
target_cls,
method_name,
func,
dataset_name,
dataset,
dataprovider,
repeat_suffix,
):
# pylint: disable=too-many-arguments
test_method_name_for_dataset = _build_final_method_name(
method_name,
dataset_name,
... | Add the described method to the given class.
:param target_cls:
Test class to which to add a method.
:type target_cls:
`class`
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:param func:
The underlying test function to call.
... | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L450-L514 | null | # coding: utf-8
from __future__ import absolute_import, unicode_literals
import functools
from itertools import chain
import math
import re
import sys
import types
import six
from .genty_args import GentyArgs
from .private import encode_non_ascii_string
REPLACE_FOR_PERIOD_CHAR = '\xb7'
def genty(target_cls):
... |
box/genty | genty/private/__init__.py | format_kwarg | python | def format_kwarg(key, value):
translator = repr if isinstance(value, six.string_types) else six.text_type
arg_value = translator(value)
return '{0}={1}'.format(key, arg_value) | Return a string of form: "key=<value>"
If 'value' is a string, we want it quoted. The goal is to make
the string a named parameter in a method call. | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/private/__init__.py#L7-L17 | null | # coding: utf-8
from __future__ import unicode_literals
import six
def format_arg(value):
"""
:param value:
Some value in a dataset.
:type value:
varies
:return:
unicode representation of that value
:rtype:
`unicode`
"""
translator = repr if isinstance(val... |
box/genty | genty/private/__init__.py | format_arg | python | def format_arg(value):
translator = repr if isinstance(value, six.string_types) else six.text_type
return translator(value) | :param value:
Some value in a dataset.
:type value:
varies
:return:
unicode representation of that value
:rtype:
`unicode` | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/private/__init__.py#L20-L32 | null | # coding: utf-8
from __future__ import unicode_literals
import six
def format_kwarg(key, value):
"""
Return a string of form: "key=<value>"
If 'value' is a string, we want it quoted. The goal is to make
the string a named parameter in a method call.
"""
translator = repr if isinstance(value... |
box/genty | genty/private/__init__.py | encode_non_ascii_string | python | def encode_non_ascii_string(string):
encoded_string = string.encode('utf-8', 'replace')
if six.PY3:
encoded_string = encoded_string.decode()
return encoded_string | :param string:
The string to be encoded
:type string:
unicode or str
:return:
The encoded string
:rtype:
str | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/private/__init__.py#L35-L50 | null | # coding: utf-8
from __future__ import unicode_literals
import six
def format_kwarg(key, value):
"""
Return a string of form: "key=<value>"
If 'value' is a string, we want it quoted. The goal is to make
the string a named parameter in a method call.
"""
translator = repr if isinstance(value... |
box/genty | genty/genty_dataset.py | genty_dataprovider | python | def genty_dataprovider(builder_function):
datasets = getattr(builder_function, 'genty_datasets', {None: ()})
def wrap(test_method):
# Save the data providers in the test method. This data will be
# consumed by the @genty decorator.
if not hasattr(test_method, 'genty_dataproviders'):
... | Decorator defining that this test gets parameters from the given
build_function.
:param builder_function:
A callable that returns parameters that will be passed to the method
decorated by this decorator.
If the builder_function returns a tuple or list, then that will be
passed ... | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L15-L47 | null | # coding: utf-8
from __future__ import unicode_literals
try:
from collections import OrderedDict
except ImportError:
# pylint:disable=import-error
from ordereddict import OrderedDict
# pylint:enable=import-error
import six
from .genty_args import GentyArgs
from .private import format_arg
def genty_d... |
box/genty | genty/genty_dataset.py | genty_dataset | python | def genty_dataset(*args, **kwargs):
datasets = _build_datasets(*args, **kwargs)
def wrap(test_method):
# Save the datasets in the test method. This data will be consumed
# by the @genty decorator.
if not hasattr(test_method, 'genty_datasets'):
test_method.genty_datasets = Or... | Decorator defining data sets to provide to a test.
Inspired by http://sebastian-bergmann.de/archives/
702-Data-Providers-in-PHPUnit-3.2.html
The canonical way to call @genty_dataset, with each argument each
representing a data set to be injected in the test method call:
@genty_dataset(
... | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L50-L148 | [
"def _build_datasets(*args, **kwargs):\n \"\"\"Build the datasets into a dict, where the keys are the name of the\n data set and the values are the data sets themselves.\n\n :param args:\n Tuple of unnamed data sets.\n :type args:\n `tuple` of varies\n :param kwargs:\n Dict of pr... | # coding: utf-8
from __future__ import unicode_literals
try:
from collections import OrderedDict
except ImportError:
# pylint:disable=import-error
from ordereddict import OrderedDict
# pylint:enable=import-error
import six
from .genty_args import GentyArgs
from .private import format_arg
def genty_da... |
box/genty | genty/genty_dataset.py | _build_datasets | python | def _build_datasets(*args, **kwargs):
datasets = OrderedDict()
_add_arg_datasets(datasets, args)
_add_kwarg_datasets(datasets, kwargs)
return datasets | Build the datasets into a dict, where the keys are the name of the
data set and the values are the data sets themselves.
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicod... | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L151-L171 | [
"def _add_arg_datasets(datasets, args):\n \"\"\"Add data sets of the given args.\n\n :param datasets:\n The dict where to accumulate data sets.\n :type datasets:\n `dict`\n :param args:\n Tuple of unnamed data sets.\n :type args:\n `tuple` of varies\n \"\"\"\n for da... | # coding: utf-8
from __future__ import unicode_literals
try:
from collections import OrderedDict
except ImportError:
# pylint:disable=import-error
from ordereddict import OrderedDict
# pylint:enable=import-error
import six
from .genty_args import GentyArgs
from .private import format_arg
def genty_da... |
box/genty | genty/genty_dataset.py | _add_arg_datasets | python | def _add_arg_datasets(datasets, args):
for dataset in args:
# turn a value into a 1-tuple.
if not isinstance(dataset, (tuple, GentyArgs)):
dataset = (dataset,)
# Create a test_name_suffix - basically the parameter list
if isinstance(dataset, GentyArgs):
datas... | Add data sets of the given args.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L174-L198 | null | # coding: utf-8
from __future__ import unicode_literals
try:
from collections import OrderedDict
except ImportError:
# pylint:disable=import-error
from ordereddict import OrderedDict
# pylint:enable=import-error
import six
from .genty_args import GentyArgs
from .private import format_arg
def genty_da... |
box/genty | genty/genty_dataset.py | _add_kwarg_datasets | python | def _add_kwarg_datasets(datasets, kwargs):
for test_method_suffix, dataset in six.iteritems(kwargs):
datasets[test_method_suffix] = dataset | Add data sets of the given kwargs.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies | train | https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L201-L214 | null | # coding: utf-8
from __future__ import unicode_literals
try:
from collections import OrderedDict
except ImportError:
# pylint:disable=import-error
from ordereddict import OrderedDict
# pylint:enable=import-error
import six
from .genty_args import GentyArgs
from .private import format_arg
def genty_da... |
vpelletier/python-functionfs | functionfs/__init__.py | getInterfaceInAllSpeeds | python | def getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()):
interface = getDescriptor(
USBInterfaceDescriptor,
bNumEndpoints=len(endpoint_list),
**interface
)
class_descriptor_list = list(class_descriptor_list)
fs_list = [interface] + class_descriptor_list
... | Produce similar fs, hs and ss interface and endpoints descriptors.
Should be useful for devices desiring to work in all 3 speeds with maximum
endpoint wMaxPacketSize. Reduces data duplication from descriptor
declarations.
Not intended to cover fancy combinations.
interface (dict):
Keyword arg... | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L120-L260 | [
"def getDescriptor(klass, **kw):\n \"\"\"\n Automatically fills bLength and bDescriptorType.\n \"\"\"\n # XXX: ctypes Structure.__init__ ignores arguments which do not exist\n # as structure fields. So check it.\n # This is annoying, but not doing it is a huge waste of time for the\n # develope... | # This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... |
vpelletier/python-functionfs | functionfs/__init__.py | getDescriptor | python | def getDescriptor(klass, **kw):
# XXX: ctypes Structure.__init__ ignores arguments which do not exist
# as structure fields. So check it.
# This is annoying, but not doing it is a huge waste of time for the
# developer.
empty = klass()
assert hasattr(empty, 'bLength')
assert hasattr(empty, '... | Automatically fills bLength and bDescriptorType. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L262-L283 | null | # This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... |
vpelletier/python-functionfs | functionfs/__init__.py | getOSDesc | python | def getOSDesc(interface, ext_list):
try:
ext_type, = {type(x) for x in ext_list}
except ValueError:
raise TypeError('Extensions of a single type are required.')
if issubclass(ext_type, OSExtCompatDesc):
wIndex = 4
kw = {
'b': OSDescHeaderBCount(
bC... | Return an OS description header.
interface (int)
Related interface number.
ext_list (list of OSExtCompatDesc or OSExtPropDesc)
List of instances of extended descriptors. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L285-L329 | null | # This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... |
vpelletier/python-functionfs | functionfs/__init__.py | getOSExtPropDesc | python | def getOSExtPropDesc(data_type, name, value):
klass = type(
'OSExtPropDesc',
(OSExtPropDescHead, ),
{
'_fields_': [
('bPropertyName', ctypes.c_char * len(name)),
('dwPropertyDataLength', le32),
('bProperty', ctypes.c_char * len(valu... | Returns an OS extension property descriptor.
data_type (int)
See wPropertyDataType documentation.
name (string)
See PropertyName documentation.
value (string)
See PropertyData documentation.
NULL chars must be explicitely included in the value when needed,
this functi... | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L331-L361 | null | # This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... |
vpelletier/python-functionfs | functionfs/__init__.py | getDescsV2 | python | def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=()):
count_field_list = []
descr_field_list = []
kw = {}
for descriptor_list, flag, prefix, allowed_descriptor_klass in (
(fs_list, HAS_FS_DESC, 'fs', USBDescriptorHeader),
(hs_list, HAS_HS_DESC, 'hs', USBDescriptorHeader)... | Return a FunctionFS descriptor suitable for serialisation.
flags (int)
Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP,
CONFIG0_SETUP.
{fs,hs,ss,os}_list (list of descriptors)
Instances of the following classes:
{fs,hs,ss}_list:
USBInterfaceDescriptor
... | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L389-L480 | [
"def get(self, value, default=None):\n return self.reverse_dict.get(value, default)\n"
] | # This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... |
vpelletier/python-functionfs | functionfs/__init__.py | getStrings | python | def getStrings(lang_dict):
field_list = []
kw = {}
try:
str_count = len(next(iter(lang_dict.values())))
except StopIteration:
str_count = 0
else:
for lang, string_list in lang_dict.items():
if len(string_list) != str_count:
raise ValueError('All va... | Return a FunctionFS descriptor suitable for serialisation.
lang_dict (dict)
Key: language ID (ex: 0x0409 for en-us)
Value: list of unicode objects
All values must have the same number of items. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L482-L530 | null | # This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... |
vpelletier/python-functionfs | functionfs/__init__.py | serialise | python | def serialise(structure):
return ctypes.cast(
ctypes.pointer(structure),
ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)),
).contents | structure (ctypes.Structure)
The structure to serialise.
Returns a ctypes.c_char array.
Does not copy memory. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L532-L543 | null | # This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... |
vpelletier/python-functionfs | functionfs/__init__.py | Endpoint0File.halt | python | def halt(self, request_type):
try:
if request_type & ch9.USB_DIR_IN:
self.read(0)
else:
self.write(b'')
except IOError as exc:
if exc.errno != errno.EL2HLT:
raise
else:
raise ValueError('halt did not ... | Halt current endpoint. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L559-L572 | null | class Endpoint0File(EndpointFileBase):
"""
File object exposing ioctls available on endpoint zero.
"""
def getRealInterfaceNumber(self, interface):
"""
Returns the host-visible interface number, or None if there is no such
interface.
"""
try:
return ... |
vpelletier/python-functionfs | functionfs/__init__.py | Endpoint0File.getRealInterfaceNumber | python | def getRealInterfaceNumber(self, interface):
try:
return self._ioctl(INTERFACE_REVMAP, interface)
except IOError as exc:
if exc.errno == errno.EDOM:
return None
raise | Returns the host-visible interface number, or None if there is no such
interface. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L574-L584 | [
"def _ioctl(self, func, *args, **kw):\n result = fcntl.ioctl(self, func, *args, **kw)\n if result < 0:\n raise IOError(result)\n return result\n"
] | class Endpoint0File(EndpointFileBase):
"""
File object exposing ioctls available on endpoint zero.
"""
def halt(self, request_type):
"""
Halt current endpoint.
"""
try:
if request_type & ch9.USB_DIR_IN:
self.read(0)
else:
... |
vpelletier/python-functionfs | functionfs/__init__.py | EndpointFile.getDescriptor | python | def getDescriptor(self):
result = USBEndpointDescriptor()
self._ioctl(ENDPOINT_DESC, result, True)
return result | Returns the currently active endpoint descriptor
(depending on current USB speed). | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L621-L628 | [
"def _ioctl(self, func, *args, **kw):\n result = fcntl.ioctl(self, func, *args, **kw)\n if result < 0:\n raise IOError(result)\n return result\n"
] | class EndpointFile(EndpointFileBase):
"""
File object exposing ioctls available on non-zero endpoints.
"""
_halted = False
def getRealEndpointNumber(self):
"""
Returns the host-visible endpoint number.
"""
return self._ioctl(ENDPOINT_REVMAP)
def clearHalt(self):... |
vpelletier/python-functionfs | functionfs/__init__.py | EndpointFile.halt | python | def halt(self):
try:
self._halt()
except IOError as exc:
if exc.errno != errno.EBADMSG:
raise
else:
raise ValueError('halt did not return EBADMSG ?')
self._halted = True | Halt current endpoint. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L633-L644 | [
"def _halt(self):\n raise NotImplementedError\n"
] | class EndpointFile(EndpointFileBase):
"""
File object exposing ioctls available on non-zero endpoints.
"""
_halted = False
def getRealEndpointNumber(self):
"""
Returns the host-visible endpoint number.
"""
return self._ioctl(ENDPOINT_REVMAP)
def clearHalt(self):... |
vpelletier/python-functionfs | functionfs/__init__.py | Function.close | python | def close(self):
ep_list = self._ep_list
while ep_list:
ep_list.pop().close()
self._closed = True | Close all endpoint file descriptors. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L800-L807 | null | class Function(object):
"""
Pythonic class for interfacing with FunctionFS.
Properties available:
function_remote_wakeup_capable (bool)
Whether the function wishes to be allowed to wake host.
function_remote_wakeup (bool)
Whether host has allowed the function to wake... |
vpelletier/python-functionfs | functionfs/__init__.py | Function.onSetup | python | def onSetup(self, request_type, request, value, index, length):
if (request_type & ch9.USB_TYPE_MASK) == ch9.USB_TYPE_STANDARD:
recipient = request_type & ch9.USB_RECIP_MASK
is_in = (request_type & ch9.USB_DIR_IN) == ch9.USB_DIR_IN
if request == ch9.USB_REQ_GET_STATUS:
... | Called when a setup USB transaction was received.
Default implementation:
- handles USB_REQ_GET_STATUS on interface and endpoints
- handles USB_REQ_CLEAR_FEATURE(USB_ENDPOINT_HALT) on endpoints
- handles USB_REQ_SET_FEATURE(USB_ENDPOINT_HALT) on endpoints
- halts on everything e... | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L956-L1036 | [
"def getEndpoint(self, index):\n \"\"\"\n Return a file object corresponding to given endpoint index,\n in descriptor list order.\n \"\"\"\n return self._ep_list[index]\n",
"def disableRemoteWakeup(self):\n \"\"\"\n Called when host issues a clearFeature request of the \"suspend\" flag\n o... | class Function(object):
"""
Pythonic class for interfacing with FunctionFS.
Properties available:
function_remote_wakeup_capable (bool)
Whether the function wishes to be allowed to wake host.
function_remote_wakeup (bool)
Whether host has allowed the function to wake... |
vpelletier/python-functionfs | examples/usbcat/slowprinter.py | main | python | def main():
now = datetime.datetime.now
try:
while True:
sys.stdout.write(str(now()) + ' ')
time.sleep(1)
except KeyboardInterrupt:
pass
except IOError as exc:
if exc.errno != errno.EPIPE:
raise | Slowly writes to stdout, without emitting a newline so any output
buffering (or input for next pipeline command) can be detected. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/slowprinter.py#L22-L36 | null | #!/usr/bin/env python -u
# This file is part of python-functionfs
# Copyright (C) 2016-2018 Vincent Pelletier <plr.vincent@gmail.com>
#
# python-functionfs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat.onEnable | python | def onEnable(self):
trace('onEnable')
self._disable()
self._aio_context.submit(self._aio_recv_block_list)
self._real_onCanSend()
self._enabled = True | The configuration containing this function has been enabled by host.
Endpoints become working files, so submit some read operations. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L121-L130 | [
"def _disable(self):\n \"\"\"\n The configuration containing this function has been disabled by host.\n Endpoint do not work anymore, so cancel AIO operation blocks.\n \"\"\"\n if self._enabled:\n self._real_onCannotSend()\n has_cancelled = 0\n for block in self._aio_recv_block_l... | class USBCat(functionfs.Function):
_enabled = False
def __init__(self, path, writer, onCanSend, onCannotSend):
self._aio_context = libaio.AIOContext(
PENDING_READ_COUNT + MAX_PENDING_WRITE_COUNT,
)
self.eventfd = eventfd = libaio.EventFD()
self._writer = writer
... |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat._disable | python | def _disable(self):
if self._enabled:
self._real_onCannotSend()
has_cancelled = 0
for block in self._aio_recv_block_list + self._aio_send_block_list:
try:
self._aio_context.cancel(block)
except OSError as exc:
... | The configuration containing this function has been disabled by host.
Endpoint do not work anymore, so cancel AIO operation blocks. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L136-L155 | [
"def noIntr(func):\n while True:\n try:\n return func()\n except (IOError, OSError) as exc:\n if exc.errno != errno.EINTR:\n raise\n"
] | class USBCat(functionfs.Function):
_enabled = False
def __init__(self, path, writer, onCanSend, onCannotSend):
self._aio_context = libaio.AIOContext(
PENDING_READ_COUNT + MAX_PENDING_WRITE_COUNT,
)
self.eventfd = eventfd = libaio.EventFD()
self._writer = writer
... |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat.onAIOCompletion | python | def onAIOCompletion(self):
event_count = self.eventfd.read()
trace('eventfd reports %i events' % event_count)
# Even though eventfd signaled activity, even though it may give us
# some number of pending events, some events seem to have been already
# processed (maybe during io_ca... | Call when eventfd notified events are available. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L157-L168 | null | class USBCat(functionfs.Function):
_enabled = False
def __init__(self, path, writer, onCanSend, onCannotSend):
self._aio_context = libaio.AIOContext(
PENDING_READ_COUNT + MAX_PENDING_WRITE_COUNT,
)
self.eventfd = eventfd = libaio.EventFD()
self._writer = writer
... |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat.write | python | def write(self, value):
aio_block = libaio.AIOBlock(
mode=libaio.AIOBLOCK_MODE_WRITE,
target_file=self.getEndpoint(1),
buffer_list=[bytearray(value)],
offset=0,
eventfd=self.eventfd,
onCompletion=self._onCanSend,
)
self._aio... | Queue write in kernel.
value (bytes)
Value to send. | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L196-L213 | [
"def getEndpoint(self, index):\n \"\"\"\n Return a file object corresponding to given endpoint index,\n in descriptor list order.\n \"\"\"\n return self._ep_list[index]\n",
"def _onCannotSend(self):\n trace('send queue full, pause sending')\n self._real_onCannotSend()\n self._need_resume =... | class USBCat(functionfs.Function):
_enabled = False
def __init__(self, path, writer, onCanSend, onCannotSend):
self._aio_context = libaio.AIOContext(
PENDING_READ_COUNT + MAX_PENDING_WRITE_COUNT,
)
self.eventfd = eventfd = libaio.EventFD()
self._writer = writer
... |
tuxu/python-samplerate | examples/play_modulation.py | get_input_callback | python | def get_input_callback(samplerate, params, num_samples=256):
amplitude = params['mod_amplitude']
frequency = params['mod_frequency']
def producer():
"""Generate samples.
Yields
------
samples : ndarray
A number of samples (`num_samples`) of the sine.
"""... | Return a function that produces samples of a sine.
Parameters
----------
samplerate : float
The sample rate.
params : dict
Parameters for FM generation.
num_samples : int, optional
Number of samples to be generated on each call. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/examples/play_modulation.py#L27-L57 | [
"def producer():\n \"\"\"Generate samples.\n\n Yields\n ------\n samples : ndarray\n A number of samples (`num_samples`) of the sine.\n \"\"\"\n start_time = 0\n while True:\n time = start_time + np.arange(num_samples) / samplerate\n start_time += num_samples / samplerate\n... | #!/usr/bin/env python
"""Demonstrate realtime audio resampling and playback using the callback API.
A carrier frequency is modulated by a sine wave, and the resulting signal is
played back on the default sound output. During playback, the modulation signal
is generated at source samplerate, then resampled to target sa... |
tuxu/python-samplerate | examples/play_modulation.py | get_playback_callback | python | def get_playback_callback(resampler, samplerate, params):
def callback(outdata, frames, time, _):
"""Playback callback.
Read samples from the resampler and modulate them onto a carrier
frequency.
"""
last_fmphase = getattr(callback, 'last_fmphase', 0)
df = params['f... | Return a sound playback callback.
Parameters
----------
resampler
The resampler from which samples are read.
samplerate : float
The sample rate.
params : dict
Parameters for FM generation. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/examples/play_modulation.py#L60-L88 | null | #!/usr/bin/env python
"""Demonstrate realtime audio resampling and playback using the callback API.
A carrier frequency is modulated by a sine wave, and the resulting signal is
played back on the default sound output. During playback, the modulation signal
is generated at source samplerate, then resampled to target sa... |
tuxu/python-samplerate | examples/play_modulation.py | main | python | def main(source_samplerate, target_samplerate, params, converter_type):
from time import sleep
ratio = target_samplerate / source_samplerate
with sr.CallbackResampler(get_input_callback(source_samplerate, params),
ratio, converter_type) as resampler, \
sd.OutputSt... | Setup the resampling and audio output callbacks and start playback. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/examples/play_modulation.py#L91-L107 | [
"def get_input_callback(samplerate, params, num_samples=256):\n \"\"\"Return a function that produces samples of a sine.\n\n Parameters\n ----------\n samplerate : float\n The sample rate.\n params : dict\n Parameters for FM generation.\n num_samples : int, optional\n Number o... | #!/usr/bin/env python
"""Demonstrate realtime audio resampling and playback using the callback API.
A carrier frequency is modulated by a sine wave, and the resulting signal is
played back on the default sound output. During playback, the modulation signal
is generated at source samplerate, then resampled to target sa... |
tuxu/python-samplerate | samplerate/converters.py | _get_converter_type | python | def _get_converter_type(identifier):
if isinstance(identifier, str):
return ConverterType[identifier]
if isinstance(identifier, ConverterType):
return identifier
return ConverterType(identifier) | Return the converter type for `identifier`. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L22-L28 | null | """Converters
"""
from __future__ import print_function, division
from enum import Enum
import numpy as np
class ConverterType(Enum):
"""Enum of samplerate converter types.
Pass any of the members, or their string or value representation, as
``converter_type`` in the resamplers.
"""
sinc_best = ... |
tuxu/python-samplerate | samplerate/converters.py | resample | python | def resample(input_data, ratio, converter_type='sinc_best', verbose=False):
from samplerate.lowlevel import src_simple
from samplerate.exceptions import ResamplingError
input_data = np.require(input_data, requirements='C', dtype=np.float32)
if input_data.ndim == 2:
num_frames, channels = input_... | Resample the signal in `input_data` at once.
Parameters
----------
input_data : ndarray
Input data. A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is represented as a 2D array of shape
(`num_frames`, `num_channels`). For use with ... | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L31-L90 | [
"def _get_converter_type(identifier):\n \"\"\"Return the converter type for `identifier`.\"\"\"\n if isinstance(identifier, str):\n return ConverterType[identifier]\n if isinstance(identifier, ConverterType):\n return identifier\n return ConverterType(identifier)\n",
"def src_simple(inpu... | """Converters
"""
from __future__ import print_function, division
from enum import Enum
import numpy as np
class ConverterType(Enum):
"""Enum of samplerate converter types.
Pass any of the members, or their string or value representation, as
``converter_type`` in the resamplers.
"""
sinc_best = ... |
tuxu/python-samplerate | samplerate/converters.py | Resampler.set_ratio | python | def set_ratio(self, new_ratio):
from samplerate.lowlevel import src_set_ratio
return src_set_ratio(self._state, new_ratio) | Set a new conversion ratio immediately. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L130-L133 | [
"def src_set_ratio(state, new_ratio):\n \"\"\"Set a new SRC ratio.\n\n This allows step responses in the conversion ratio.\n Returns non zero on error.\n \"\"\"\n return _lib.src_set_ratio(state, new_ratio) if state else None\n"
] | class Resampler(object):
"""Resampler.
Parameters
----------
converter_type : ConverterType, str, or int
Sample rate converter.
num_channels : int
Number of channels.
"""
def __init__(self, converter_type='sinc_fastest', channels=1):
from samplerate.lowlevel import f... |
tuxu/python-samplerate | samplerate/converters.py | Resampler.process | python | def process(self, input_data, ratio, end_of_input=False, verbose=False):
from samplerate.lowlevel import src_process
from samplerate.exceptions import ResamplingError
input_data = np.require(input_data, requirements='C', dtype=np.float32)
if input_data.ndim == 2:
num_frames,... | Resample the signal in `input_data`.
Parameters
----------
input_data : ndarray
Input data. A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is represented as a 2D array of shape
(`num_frames`, `num_channels`... | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L135-L189 | [
"def src_process(state, input_data, output_data, ratio, end_of_input=0):\n \"\"\"Standard processing function.\n\n Returns non zero on error.\n \"\"\"\n input_frames, _ = _check_data(input_data)\n output_frames, _ = _check_data(output_data)\n data = ffi.new('SRC_DATA*')\n data.input_frames = in... | class Resampler(object):
"""Resampler.
Parameters
----------
converter_type : ConverterType, str, or int
Sample rate converter.
num_channels : int
Number of channels.
"""
def __init__(self, converter_type='sinc_fastest', channels=1):
from samplerate.lowlevel import f... |
tuxu/python-samplerate | samplerate/converters.py | CallbackResampler._create | python | def _create(self):
from samplerate.lowlevel import ffi, src_callback_new, src_delete
from samplerate.exceptions import ResamplingError
state, handle, error = src_callback_new(
self._callback, self._converter_type.value, self._channels)
if error != 0:
raise Resamp... | Create new callback resampler. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L222-L232 | [
"def src_callback_new(callback, converter_type, channels):\n \"\"\"Initialisation for the callback based API.\n\n Parameters\n ----------\n callback : function\n Called whenever new frames are to be read. Must return a NumPy array\n of shape (num_frames, channels).\n converter_type : in... | class CallbackResampler(object):
"""CallbackResampler.
Parameters
----------
callback : function
Function that returns new frames on each call, or `None` otherwise.
A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is represented... |
tuxu/python-samplerate | samplerate/converters.py | CallbackResampler.set_starting_ratio | python | def set_starting_ratio(self, ratio):
from samplerate.lowlevel import src_set_ratio
if self._state is None:
self._create()
src_set_ratio(self._state, ratio)
self.ratio = ratio | Set the starting conversion ratio for the next `read` call. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L246-L252 | [
"def src_set_ratio(state, new_ratio):\n \"\"\"Set a new SRC ratio.\n\n This allows step responses in the conversion ratio.\n Returns non zero on error.\n \"\"\"\n return _lib.src_set_ratio(state, new_ratio) if state else None\n",
"def _create(self):\n \"\"\"Create new callback resampler.\"\"\"\n... | class CallbackResampler(object):
"""CallbackResampler.
Parameters
----------
callback : function
Function that returns new frames on each call, or `None` otherwise.
A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is represented... |
tuxu/python-samplerate | samplerate/converters.py | CallbackResampler.reset | python | def reset(self):
from samplerate.lowlevel import src_reset
if self._state is None:
self._create()
src_reset(self._state) | Reset state. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L254-L259 | [
"def src_reset(state):\n \"\"\"Reset the internal SRC state.\n\n Does not modify the quality settings.\n Does not free any memory allocations.\n Returns non zero on error.\n \"\"\"\n return _lib.src_reset(state) if state else None\n",
"def _create(self):\n \"\"\"Create new callback resampler.... | class CallbackResampler(object):
"""CallbackResampler.
Parameters
----------
callback : function
Function that returns new frames on each call, or `None` otherwise.
A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is represented... |
tuxu/python-samplerate | samplerate/converters.py | CallbackResampler.read | python | def read(self, num_frames):
from samplerate.lowlevel import src_callback_read, src_error
from samplerate.exceptions import ResamplingError
if self._state is None:
self._create()
if self._channels > 1:
output_shape = (num_frames, self._channels)
elif self.... | Read a number of frames from the resampler.
Parameters
----------
num_frames : int
Number of frames to read.
Returns
-------
output_data : ndarray
Resampled frames as a (`num_output_frames`, `num_channels`) or
(`num_output_frames`,) a... | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L270-L304 | [
"def src_callback_read(state, ratio, frames, data):\n \"\"\"Read up to `frames` worth of data using the callback API.\n\n Returns\n -------\n frames : int\n Number of frames read or -1 on error.\n \"\"\"\n data_ptr = ffi.cast('float*f', ffi.from_buffer(data))\n return _lib.src_callback_r... | class CallbackResampler(object):
"""CallbackResampler.
Parameters
----------
callback : function
Function that returns new frames on each call, or `None` otherwise.
A single channel is provided as a 1D array of `num_frames` length.
Input data with several channels is represented... |
tuxu/python-samplerate | samplerate/lowlevel.py | _check_data | python | def _check_data(data):
if not (data.dtype == _np.float32 and data.flags.c_contiguous):
raise ValueError('supplied data must be float32 and C contiguous')
if data.ndim == 2:
num_frames, channels = data.shape
elif data.ndim == 1:
num_frames, channels = data.size, 1
else:
ra... | Check whether `data` is a valid input/output for libsamplerate.
Returns
-------
num_frames
Number of frames in `data`.
channels
Number of channels in `data`.
Raises
------
ValueError: If invalid data is supplied. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L41-L63 | null | """Lowlevel wrappers around libsamplerate.
The docstrings of the `src_*` functions are adapted from the libsamplerate
header file.
"""
import os as _os
import sys as _sys
from ctypes.util import find_library as _find_library
import numpy as _np
# Locate and load libsamplerate
from samplerate._src import ffi
lib_base... |
tuxu/python-samplerate | samplerate/lowlevel.py | src_simple | python | def src_simple(input_data, output_data, ratio, converter_type, channels):
input_frames, _ = _check_data(input_data)
output_frames, _ = _check_data(output_data)
data = ffi.new('SRC_DATA*')
data.input_frames = input_frames
data.output_frames = output_frames
data.src_ratio = ratio
data.data_in ... | Perform a single conversion from an input buffer to an output buffer.
Simple interface for performing a single conversion from input buffer to
output buffer at a fixed conversion ratio. Simple interface does not require
initialisation as it can only operate on a single buffer worth of audio. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L86-L102 | [
"def _check_data(data):\n \"\"\"Check whether `data` is a valid input/output for libsamplerate.\n\n Returns\n -------\n num_frames\n Number of frames in `data`.\n channels\n Number of channels in `data`.\n\n Raises\n ------\n ValueError: If invalid data is supplied.\n \"... | """Lowlevel wrappers around libsamplerate.
The docstrings of the `src_*` functions are adapted from the libsamplerate
header file.
"""
import os as _os
import sys as _sys
from ctypes.util import find_library as _find_library
import numpy as _np
# Locate and load libsamplerate
from samplerate._src import ffi
lib_base... |
tuxu/python-samplerate | samplerate/lowlevel.py | src_new | python | def src_new(converter_type, channels):
error = ffi.new('int*')
state = _lib.src_new(converter_type, channels, error)
return state, error[0] | Initialise a new sample rate converter.
Parameters
----------
converter_type : int
Converter to be used.
channels : int
Number of channels.
Returns
-------
state
An anonymous pointer to the internal state of the converter.
error : int
Error code. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L105-L124 | null | """Lowlevel wrappers around libsamplerate.
The docstrings of the `src_*` functions are adapted from the libsamplerate
header file.
"""
import os as _os
import sys as _sys
from ctypes.util import find_library as _find_library
import numpy as _np
# Locate and load libsamplerate
from samplerate._src import ffi
lib_base... |
tuxu/python-samplerate | samplerate/lowlevel.py | src_process | python | def src_process(state, input_data, output_data, ratio, end_of_input=0):
input_frames, _ = _check_data(input_data)
output_frames, _ = _check_data(output_data)
data = ffi.new('SRC_DATA*')
data.input_frames = input_frames
data.output_frames = output_frames
data.src_ratio = ratio
data.data_in = ... | Standard processing function.
Returns non zero on error. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L135-L150 | [
"def _check_data(data):\n \"\"\"Check whether `data` is a valid input/output for libsamplerate.\n\n Returns\n -------\n num_frames\n Number of frames in `data`.\n channels\n Number of channels in `data`.\n\n Raises\n ------\n ValueError: If invalid data is supplied.\n \"... | """Lowlevel wrappers around libsamplerate.
The docstrings of the `src_*` functions are adapted from the libsamplerate
header file.
"""
import os as _os
import sys as _sys
from ctypes.util import find_library as _find_library
import numpy as _np
# Locate and load libsamplerate
from samplerate._src import ffi
lib_base... |
tuxu/python-samplerate | samplerate/lowlevel.py | _src_input_callback | python | def _src_input_callback(cb_data, data):
cb_data = ffi.from_handle(cb_data)
ret = cb_data['callback']()
if ret is None:
cb_data['last_input'] = None
return 0 # No frames supplied
input_data = _np.require(ret, requirements='C', dtype=_np.float32)
input_frames, channels = _check_data(i... | Internal callback function to be used with the callback API.
Pulls the Python callback function from the handle contained in `cb_data`
and calls it to fetch frames. Frames are converted to the format required by
the API (float, interleaved channels). A reference to these data is kept
internally.
R... | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L184-L214 | null | """Lowlevel wrappers around libsamplerate.
The docstrings of the `src_*` functions are adapted from the libsamplerate
header file.
"""
import os as _os
import sys as _sys
from ctypes.util import find_library as _find_library
import numpy as _np
# Locate and load libsamplerate
from samplerate._src import ffi
lib_base... |
tuxu/python-samplerate | samplerate/lowlevel.py | src_callback_new | python | def src_callback_new(callback, converter_type, channels):
cb_data = {'callback': callback, 'channels': channels}
handle = ffi.new_handle(cb_data)
error = ffi.new('int*')
state = _lib.src_callback_new(_src_input_callback, converter_type,
channels, error, handle)
if s... | Initialisation for the callback based API.
Parameters
----------
callback : function
Called whenever new frames are to be read. Must return a NumPy array
of shape (num_frames, channels).
converter_type : int
Converter to be used.
channels : int
Number of channels.
... | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L217-L247 | null | """Lowlevel wrappers around libsamplerate.
The docstrings of the `src_*` functions are adapted from the libsamplerate
header file.
"""
import os as _os
import sys as _sys
from ctypes.util import find_library as _find_library
import numpy as _np
# Locate and load libsamplerate
from samplerate._src import ffi
lib_base... |
tuxu/python-samplerate | samplerate/lowlevel.py | src_callback_read | python | def src_callback_read(state, ratio, frames, data):
data_ptr = ffi.cast('float*f', ffi.from_buffer(data))
return _lib.src_callback_read(state, ratio, frames, data_ptr) | Read up to `frames` worth of data using the callback API.
Returns
-------
frames : int
Number of frames read or -1 on error. | train | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L250-L259 | null | """Lowlevel wrappers around libsamplerate.
The docstrings of the `src_*` functions are adapted from the libsamplerate
header file.
"""
import os as _os
import sys as _sys
from ctypes.util import find_library as _find_library
import numpy as _np
# Locate and load libsamplerate
from samplerate._src import ffi
lib_base... |
bd808/python-iptools | iptools/ipv6.py | validate_ip | python | def validate_ip(s):
if _HEX_RE.match(s):
return len(s.split('::')) <= 2
if _DOTTED_QUAD_RE.match(s):
halves = s.split('::')
if len(halves) > 2:
return False
hextets = s.split(':')
quads = hextets[-1].split('.')
for q in quads:
if int(q) > 2... | Validate a hexidecimal IPv6 ip address.
>>> validate_ip('::')
True
>>> validate_ip('::1')
True
>>> validate_ip('2001:db8:85a3::8a2e:370:7334')
True
>>> validate_ip('2001:db8:85a3:0:0:8a2e:370:7334')
True
>>> validate_ip('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
True
>>> va... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv6.py#L157-L209 | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv6.py | ip2long | python | def ip2long(ip):
if not validate_ip(ip):
return None
if '.' in ip:
# convert IPv4 suffix to hex
chunks = ip.split(':')
v4_int = ipv4.ip2long(chunks.pop())
if v4_int is None:
return None
chunks.append('%x' % ((v4_int >> 16) & 0xffff))
chunks.ap... | Convert a hexidecimal IPv6 address to a network byte order 128-bit
integer.
>>> ip2long('::') == 0
True
>>> ip2long('::1') == 1
True
>>> expect = 0x20010db885a3000000008a2e03707334
>>> ip2long('2001:db8:85a3::8a2e:370:7334') == expect
True
>>> ip2long('2001:db8:85a3:0:0:8a2e:370:73... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv6.py#L213-L277 | [
"def ip2long(ip):\n \"\"\"Convert a dotted-quad ip address to a network byte order 32-bit\n integer.\n\n\n >>> ip2long('127.0.0.1')\n 2130706433\n >>> ip2long('127.1')\n 2130706433\n >>> ip2long('127')\n 2130706432\n >>> ip2long('127.0.0.256') is None\n True\n\n\n :param ip: Dotted-... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv6.py | long2ip | python | def long2ip(l, rfc1924=False):
if MAX_IP < l or l < MIN_IP:
raise TypeError(
"expected int between %d and %d inclusive" % (MIN_IP, MAX_IP))
if rfc1924:
return long2rfc1924(l)
# format as one big hex value
hex_str = '%032x' % l
# split into double octet chunks without pa... | Convert a network byte order 128-bit integer to a canonical IPv6
address.
>>> long2ip(2130706433)
'::7f00:1'
>>> long2ip(42540766411282592856904266426630537217)
'2001:db8::1:0:0:1'
>>> long2ip(MIN_IP)
'::'
>>> long2ip(MAX_IP)
'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'
>>> long2i... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv6.py#L281-L353 | [
"def long2rfc1924(l):\n \"\"\"Convert a network byte order 128-bit integer to an rfc1924 IPv6\n address.\n\n\n >>> long2rfc1924(ip2long('1080::8:800:200C:417A'))\n '4)+k&C#VzJ4br>0wv%Yp'\n >>> long2rfc1924(ip2long('::'))\n '00000000000000000000'\n >>> long2rfc1924(MAX_IP)\n '=r54lj&NUUO~Hi%c... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv6.py | long2rfc1924 | python | def long2rfc1924(l):
if MAX_IP < l or l < MIN_IP:
raise TypeError(
"expected int between %d and %d inclusive" % (MIN_IP, MAX_IP))
o = []
r = l
while r > 85:
o.append(_RFC1924_ALPHABET[r % 85])
r = r // 85
o.append(_RFC1924_ALPHABET[r])
return ''.join(reversed(... | Convert a network byte order 128-bit integer to an rfc1924 IPv6
address.
>>> long2rfc1924(ip2long('1080::8:800:200C:417A'))
'4)+k&C#VzJ4br>0wv%Yp'
>>> long2rfc1924(ip2long('::'))
'00000000000000000000'
>>> long2rfc1924(MAX_IP)
'=r54lj&NUUO~Hi%c2ym0'
:param l: Network byte order 128-b... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv6.py#L357-L384 | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv6.py | rfc19242long | python | def rfc19242long(s):
global _RFC1924_REV
if not _RFC1924_RE.match(s):
return None
if _RFC1924_REV is None:
_RFC1924_REV = {v: k for k, v in enumerate(_RFC1924_ALPHABET)}
x = 0
for c in s:
x = x * 85 + _RFC1924_REV[c]
if x > MAX_IP:
return None
return x | Convert an RFC 1924 IPv6 address to a network byte order 128-bit
integer.
>>> expect = 0
>>> rfc19242long('00000000000000000000') == expect
True
>>> expect = 21932261930451111902915077091070067066
>>> rfc19242long('4)+k&C#VzJ4br>0wv%Yp') == expect
True
>>> rfc19242long('pizza') == None... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv6.py#L387-L420 | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv6.py | validate_cidr | python | def validate_cidr(s):
if _CIDR_RE.match(s):
ip, mask = s.split('/')
if validate_ip(ip):
if int(mask) > 128:
return False
else:
return False
return True
return False | Validate a CIDR notation ip address.
The string is considered a valid CIDR address if it consists of a valid
IPv6 address in hextet format followed by a forward slash (/) and a bit
mask length (0-128).
>>> validate_cidr('::/128')
True
>>> validate_cidr('::/0')
True
>>> validate_cidr('... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv6.py#L423-L462 | [
"def validate_ip(s):\n \"\"\"Validate a hexidecimal IPv6 ip address.\n\n\n >>> validate_ip('::')\n True\n >>> validate_ip('::1')\n True\n >>> validate_ip('2001:db8:85a3::8a2e:370:7334')\n True\n >>> validate_ip('2001:db8:85a3:0:0:8a2e:370:7334')\n True\n >>> validate_ip('2001:0db8:85a3... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv6.py | cidr2block | python | def cidr2block(cidr):
if not validate_cidr(cidr):
return None
ip, prefix = cidr.split('/')
prefix = int(prefix)
ip = ip2long(ip)
# keep left most prefix bits of ip
shift = 128 - prefix
block_start = ip >> shift << shift
# expand right most 128 - prefix bits to 1
mask = (1 ... | Convert a CIDR notation ip address into a tuple containing the network
block start and end addresses.
>>> cidr2block('2001:db8::/48')
('2001:db8::', '2001:db8:0:ffff:ffff:ffff:ffff:ffff')
>>> cidr2block('::/0')
('::', 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
:param cidr: CIDR notation ip a... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv6.py#L466-L496 | [
"def validate_cidr(s):\n \"\"\"Validate a CIDR notation ip address.\n\n The string is considered a valid CIDR address if it consists of a valid\n IPv6 address in hextet format followed by a forward slash (/) and a bit\n mask length (0-128).\n\n\n >>> validate_cidr('::/128')\n True\n >>> validat... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | validate_ip | python | def validate_ip(s):
if _DOTTED_QUAD_RE.match(s):
quads = s.split('.')
for q in quads:
if int(q) > 255:
return False
return True
return False | Validate a dotted-quad ip address.
The string is considered a valid dotted-quad address if it consists of
one to four octets (0-255) seperated by periods (.).
>>> validate_ip('127.0.0.1')
True
>>> validate_ip('127.0')
True
>>> validate_ip('127.0.0.256')
False
>>> validate_ip(LOCAL... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L190-L222 | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | validate_netmask | python | def validate_netmask(s):
if validate_ip(s):
# Convert to binary string, strip '0b' prefix, 0 pad to 32 bits
mask = bin(ip2network(s))[2:].zfill(32)
# all left most bits must be 1, all right most must be 0
seen0 = False
for c in mask:
if '1' == c:
i... | Validate that a dotted-quad ip address is a valid netmask.
>>> validate_netmask('0.0.0.0')
True
>>> validate_netmask('128.0.0.0')
True
>>> validate_netmask('255.0.0.0')
True
>>> validate_netmask('255.255.255.255')
True
>>> validate_netmask(BROADCAST)
True
>>> validate_netma... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L269-L309 | [
"def ip2network(ip):\n \"\"\"Convert a dotted-quad ip to base network number.\n\n This differs from :func:`ip2long` in that partial addresses as treated as\n all network instead of network plus host (eg. '127.1' expands to\n '127.1.0.0')\n\n :param ip: dotted-quad ip address (eg. ‘127.0.0.1’).\n :... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | validate_subnet | python | def validate_subnet(s):
if isinstance(s, basestring):
if '/' in s:
start, mask = s.split('/', 2)
return validate_ip(start) and validate_netmask(mask)
else:
return False
raise TypeError("expected string or unicode") | Validate a dotted-quad ip address including a netmask.
The string is considered a valid dotted-quad address with netmask if it
consists of one to four octets (0-255) seperated by periods (.) followed
by a forward slash (/) and a subnet bitmask which is expressed in
dotted-quad format.
>>> validat... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L313-L352 | [
"def validate_ip(s):\n \"\"\"Validate a dotted-quad ip address.\n\n The string is considered a valid dotted-quad address if it consists of\n one to four octets (0-255) seperated by periods (.).\n\n\n >>> validate_ip('127.0.0.1')\n True\n >>> validate_ip('127.0')\n True\n >>> validate_ip('127... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | ip2long | python | def ip2long(ip):
if not validate_ip(ip):
return None
quads = ip.split('.')
if len(quads) == 1:
# only a network quad
quads = quads + [0, 0, 0]
elif len(quads) < 4:
# partial form, last supplied quad is host address, rest is network
host = quads[-1:]
quads ... | Convert a dotted-quad ip address to a network byte order 32-bit
integer.
>>> ip2long('127.0.0.1')
2130706433
>>> ip2long('127.1')
2130706433
>>> ip2long('127')
2130706432
>>> ip2long('127.0.0.256') is None
True
:param ip: Dotted-quad ip address (eg. '127.0.0.1').
:type ip... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L356-L389 | [
"def validate_ip(s):\n \"\"\"Validate a dotted-quad ip address.\n\n The string is considered a valid dotted-quad address if it consists of\n one to four octets (0-255) seperated by periods (.).\n\n\n >>> validate_ip('127.0.0.1')\n True\n >>> validate_ip('127.0')\n True\n >>> validate_ip('127... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | ip2network | python | def ip2network(ip):
if not validate_ip(ip):
return None
quads = ip.split('.')
netw = 0
for i in range(4):
netw = (netw << 8) | int(len(quads) > i and quads[i] or 0)
return netw | Convert a dotted-quad ip to base network number.
This differs from :func:`ip2long` in that partial addresses as treated as
all network instead of network plus host (eg. '127.1' expands to
'127.1.0.0')
:param ip: dotted-quad ip address (eg. ‘127.0.0.1’).
:type ip: str
:returns: Network byte ord... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L393-L410 | [
"def validate_ip(s):\n \"\"\"Validate a dotted-quad ip address.\n\n The string is considered a valid dotted-quad address if it consists of\n one to four octets (0-255) seperated by periods (.).\n\n\n >>> validate_ip('127.0.0.1')\n True\n >>> validate_ip('127.0')\n True\n >>> validate_ip('127... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | long2ip | python | def long2ip(l):
if MAX_IP < l or l < MIN_IP:
raise TypeError(
"expected int between %d and %d inclusive" % (MIN_IP, MAX_IP))
return '%d.%d.%d.%d' % (
l >> 24 & 255, l >> 16 & 255, l >> 8 & 255, l & 255) | Convert a network byte order 32-bit integer to a dotted quad ip
address.
>>> long2ip(2130706433)
'127.0.0.1'
>>> long2ip(MIN_IP)
'0.0.0.0'
>>> long2ip(MAX_IP)
'255.255.255.255'
>>> long2ip(None) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
T... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L414-L452 | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | cidr2block | python | def cidr2block(cidr):
if not validate_cidr(cidr):
return None
ip, prefix = cidr.split('/')
prefix = int(prefix)
# convert dotted-quad ip to base network number
network = ip2network(ip)
return _block_from_ip_and_prefix(network, prefix) | Convert a CIDR notation ip address into a tuple containing the network
block start and end addresses.
>>> cidr2block('127.0.0.1/32')
('127.0.0.1', '127.0.0.1')
>>> cidr2block('127/8')
('127.0.0.0', '127.255.255.255')
>>> cidr2block('127.0.1/16')
('127.0.0.0', '127.0.255.255')
>>> cidr2... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L514-L547 | [
"def validate_cidr(s):\n \"\"\"Validate a CIDR notation ip address.\n\n The string is considered a valid CIDR address if it consists of a valid\n IPv4 address in dotted-quad format followed by a forward slash (/) and\n a bit mask length (1-32).\n\n\n >>> validate_cidr('127.0.0.1/32')\n True\n >... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | subnet2block | python | def subnet2block(subnet):
if not validate_subnet(subnet):
return None
ip, netmask = subnet.split('/')
prefix = netmask2prefix(netmask)
# convert dotted-quad ip to base network number
network = ip2network(ip)
return _block_from_ip_and_prefix(network, prefix) | Convert a dotted-quad ip address including a netmask into a tuple
containing the network block start and end addresses.
>>> subnet2block('127.0.0.1/255.255.255.255')
('127.0.0.1', '127.0.0.1')
>>> subnet2block('127/255')
('127.0.0.0', '127.255.255.255')
>>> subnet2block('127.0.1/255.255')
... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L579-L613 | [
"def validate_subnet(s):\n \"\"\"Validate a dotted-quad ip address including a netmask.\n\n The string is considered a valid dotted-quad address with netmask if it\n consists of one to four octets (0-255) seperated by periods (.) followed\n by a forward slash (/) and a subnet bitmask which is expressed ... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/ipv4.py | _block_from_ip_and_prefix | python | def _block_from_ip_and_prefix(ip, prefix):
# keep left most prefix bits of ip
shift = 32 - prefix
block_start = ip >> shift << shift
# expand right most 32 - prefix bits to 1
mask = (1 << shift) - 1
block_end = block_start | mask
return (long2ip(block_start), long2ip(block_end)) | Create a tuple of (start, end) dotted-quad addresses from the given
ip address and prefix length.
:param ip: Ip address in block
:type ip: long
:param prefix: Prefix size for block
:type prefix: int
:returns: Tuple of block (start, end) | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/ipv4.py#L617-L634 | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/__init__.py | _address2long | python | def _address2long(address):
parsed = ipv4.ip2long(address)
if parsed is None:
parsed = ipv6.ip2long(address)
return parsed | Convert an address string to a long. | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/__init__.py#L58-L65 | [
"def ip2long(ip):\n \"\"\"Convert a dotted-quad ip address to a network byte order 32-bit\n integer.\n\n\n >>> ip2long('127.0.0.1')\n 2130706433\n >>> ip2long('127.1')\n 2130706433\n >>> ip2long('127')\n 2130706432\n >>> ip2long('127.0.0.256') is None\n True\n\n\n :param ip: Dotted-... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2014, Bryan Davis and iptools contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the abo... |
bd808/python-iptools | iptools/__init__.py | IpRange.index | python | def index(self, item):
item = self._cast(item)
offset = item - self.startIp
if offset >= 0 and offset < self._len:
return offset
raise ValueError('%s is not in range' % self._ipver.long2ip(item)) | Return the 0-based position of `item` in this IpRange.
>>> r = IpRange('127.0.0.1', '127.255.255.255')
>>> r.index('127.0.0.1')
0
>>> r.index('127.255.255.255')
16777214
>>> r.index('10.0.0.1')
Traceback (most recent call last):
...
ValueErro... | train | https://github.com/bd808/python-iptools/blob/5d3fae0056297540355bb7c6c112703cfaa4b6ce/iptools/__init__.py#L259-L283 | [
"def _cast(self, item):\n if isinstance(item, basestring):\n item = _address2long(item)\n if type(item) not in (type(1), type(ipv4.MAX_IP), type(ipv6.MAX_IP)):\n raise TypeError(\n \"expected ip address, 32-bit integer or 128-bit integer\")\n\n if ipv4 == self._ipver and item > ipv... | class IpRange (Sequence):
"""
Range of ip addresses.
Converts a CIDR notation address, ip address and subnet, tuple of ip
addresses or start and end addresses into a smart object which can perform
``in`` and ``not in`` tests and iterate all of the addresses in the range.
>>> r = IpRange('127.... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.get | python | def get(self, uri, params={}):
'''A generic method to make GET requests to the OpenDNS Investigate API
on the given URI.
'''
return self._session.get(urljoin(Investigate.BASE_URL, uri),
params=params, headers=self._auth_header, proxies=self.proxies
) | A generic method to make GET requests to the OpenDNS Investigate API
on the given URI. | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L62-L68 | null | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.post | python | def post(self, uri, params={}, data={}):
'''A generic method to make POST requests to the OpenDNS Investigate API
on the given URI.
'''
return self._session.post(
urljoin(Investigate.BASE_URL, uri),
params=params, data=data, headers=self._auth_header,
... | A generic method to make POST requests to the OpenDNS Investigate API
on the given URI. | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L70-L78 | null | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.get_parse | python | def get_parse(self, uri, params={}):
'''Convenience method to call get() on an arbitrary URI and parse the response
into a JSON object. Raises an error on non-200 response status.
'''
return self._request_parse(self.get, uri, params) | Convenience method to call get() on an arbitrary URI and parse the response
into a JSON object. Raises an error on non-200 response status. | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L85-L89 | [
"def _request_parse(self, method, *args):\n r = method(*args)\n r.raise_for_status()\n return r.json()\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.post_parse | python | def post_parse(self, uri, params={}, data={}):
'''Convenience method to call post() on an arbitrary URI and parse the response
into a JSON object. Raises an error on non-200 response status.
'''
return self._request_parse(self.post, uri, params, data) | Convenience method to call post() on an arbitrary URI and parse the response
into a JSON object. Raises an error on non-200 response status. | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L91-L95 | [
"def _request_parse(self, method, *args):\n r = method(*args)\n r.raise_for_status()\n return r.json()\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.categorization | python | def categorization(self, domains, labels=False):
'''Get the domain status and categorization of a domain or list of domains.
'domains' can be either a single domain, or a list of domains.
Setting 'labels' to True will give back categorizations in human-readable
form.
For more de... | Get the domain status and categorization of a domain or list of domains.
'domains' can be either a single domain, or a list of domains.
Setting 'labels' to True will give back categorizations in human-readable
form.
For more detail, see https://investigate.umbrella.com/docs/api#categori... | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L108-L121 | [
"def _get_categorization(self, domain, labels):\n uri = urljoin(self._uris['categorization'], domain)\n params = {'showLabels': True} if labels else {}\n return self.get_parse(uri, params)\n",
"def _post_categorization(self, domains, labels):\n params = {'showLabels': True} if labels else {}\n retu... | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.cooccurrences | python | def cooccurrences(self, domain):
'''Get the cooccurrences of the given domain.
For details, see https://investigate.umbrella.com/docs/api#co-occurrences
'''
uri = self._uris["cooccurrences"].format(domain)
return self.get_parse(uri) | Get the cooccurrences of the given domain.
For details, see https://investigate.umbrella.com/docs/api#co-occurrences | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L123-L129 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.related | python | def related(self, domain):
'''Get the related domains of the given domain.
For details, see https://investigate.umbrella.com/docs/api#relatedDomains
'''
uri = self._uris["related"].format(domain)
return self.get_parse(uri) | Get the related domains of the given domain.
For details, see https://investigate.umbrella.com/docs/api#relatedDomains | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L131-L137 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.security | python | def security(self, domain):
'''Get the Security Information for the given domain.
For details, see https://investigate.umbrella.com/docs/api#securityInfo
'''
uri = self._uris["security"].format(domain)
return self.get_parse(uri) | Get the Security Information for the given domain.
For details, see https://investigate.umbrella.com/docs/api#securityInfo | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L139-L145 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.rr_history | python | def rr_history(self, query, query_type="A"):
'''Get the RR (Resource Record) History of the given domain or IP.
The default query type is for 'A' records, but the following query types
are supported:
A, NS, MX, TXT, CNAME
For details, see https://investigate.umbrella.com/docs/a... | Get the RR (Resource Record) History of the given domain or IP.
The default query type is for 'A' records, but the following query types
are supported:
A, NS, MX, TXT, CNAME
For details, see https://investigate.umbrella.com/docs/api#dnsrr_domain | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L155-L172 | [
"def _domain_rr_history(self, domain, query_type):\n uri = self._uris[\"domain_rr_history\"].format(query_type, domain)\n return self.get_parse(uri)\n",
"def _ip_rr_history(self, ip, query_type):\n uri = self._uris[\"ip_rr_history\"].format(query_type, ip)\n return self.get_parse(uri)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.domain_whois | python | def domain_whois(self, domain):
'''Gets whois information for a domain'''
uri = self._uris["whois_domain"].format(domain)
resp_json = self.get_parse(uri)
return resp_json | Gets whois information for a domain | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L187-L191 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.domain_whois_history | python | def domain_whois_history(self, domain, limit=None):
'''Gets whois history for a domain'''
params = dict()
if limit is not None:
params['limit'] = limit
uri = self._uris["whois_domain_history"].format(domain)
resp_json = self.get_parse(uri, params)
return res... | Gets whois history for a domain | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L193-L202 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.ns_whois | python | def ns_whois(self, nameservers, limit=DEFAULT_LIMIT, offset=DEFAULT_OFFSET, sort_field=DEFAULT_SORT):
'''Gets the domains that have been registered with a nameserver or
nameservers'''
if not isinstance(nameservers, list):
uri = self._uris["whois_ns"].format(nameservers)
p... | Gets the domains that have been registered with a nameserver or
nameservers | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L204-L215 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.search | python | def search(self, pattern, start=None, limit=None, include_category=None):
'''Searches for domains that match a given pattern'''
params = dict()
if start is None:
start = datetime.timedelta(days=30)
if isinstance(start, datetime.timedelta):
params['start'] = int... | Searches for domains that match a given pattern | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L231-L253 | null | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.samples | python | def samples(self, anystring, limit=None, offset=None, sortby=None):
'''Return an object representing the samples identified by the input domain, IP, or URL'''
uri = self._uris['samples'].format(anystring)
params = {'limit': limit, 'offset': offset, 'sortby': sortby}
return self.get_par... | Return an object representing the samples identified by the input domain, IP, or URL | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L255-L261 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.sample | python | def sample(self, hash, limit=None, offset=None):
'''Return an object representing the sample identified by the input hash, or an empty object if that sample is not found'''
uri = self._uris['sample'].format(hash)
params = {'limit': limit, 'offset': offset}
return self.get_parse(uri, pa... | Return an object representing the sample identified by the input hash, or an empty object if that sample is not found | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L263-L269 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.as_for_ip | python | def as_for_ip(self, ip):
'''Gets the AS information for a given IP address.'''
if not Investigate.IP_PATTERN.match(ip):
raise Investigate.IP_ERR
uri = self._uris["as_for_ip"].format(ip)
resp_json = self.get_parse(uri)
return resp_json | Gets the AS information for a given IP address. | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L298-L306 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.prefixes_for_asn | python | def prefixes_for_asn(self, asn):
'''Gets the AS information for a given ASN. Return the CIDR and geolocation associated with the AS.'''
uri = self._uris["prefixes_for_asn"].format(asn)
resp_json = self.get_parse(uri)
return resp_json | Gets the AS information for a given ASN. Return the CIDR and geolocation associated with the AS. | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L308-L314 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
opendns/pyinvestigate | investigate/investigate.py | Investigate.timeline | python | def timeline(self, uri):
'''Get the domain tagging timeline for a given uri.
Could be a domain, ip, or url.
For details, see https://docs.umbrella.com/investigate-api/docs/timeline
'''
uri = self._uris["timeline"].format(uri)
resp_json = self.get_parse(uri)
retu... | Get the domain tagging timeline for a given uri.
Could be a domain, ip, or url.
For details, see https://docs.umbrella.com/investigate-api/docs/timeline | train | https://github.com/opendns/pyinvestigate/blob/a182e73a750f03e906d9b25842d556db8d2fd54f/investigate/investigate.py#L316-L324 | [
"def get_parse(self, uri, params={}):\n '''Convenience method to call get() on an arbitrary URI and parse the response\n into a JSON object. Raises an error on non-200 response status.\n '''\n return self._request_parse(self.get, uri, params)\n"
] | class Investigate(object):
BASE_URL = 'https://investigate.api.umbrella.com/'
SUPPORTED_DNS_TYPES = [
"A",
"NS",
"MX",
"TXT",
"CNAME",
]
DEFAULT_LIMIT = None
DEFAULT_OFFSET = None
DEFAULT_SORT = None
IP_PATTERN = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
... |
greyli/flask-avatars | flask_avatars/__init__.py | _Avatars.gravatar | python | def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False):
if include_extension:
hash += '.jpg'
default = default or current_app.config['AVATARS_GRAVATAR_DEFAULT']
query_string = urlencode({'s': int(size), 'r': rating, 'd': default})... | Pass email hash, return Gravatar URL. You can get email hash like this::
import hashlib
avatar_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest()
Visit https://en.gravatar.com/site/implement/images/ for more information.
:param hash: The email hash used to generate ... | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L27-L50 | null | class _Avatars(object):
@staticmethod
@staticmethod
def robohash(text, size=200):
"""Pass text, return Robohash-style avatar (robot).
Visit https://robohash.org/ for more information.
:param text: The text used to generate avatar.
:param size: The size of the avatar, defa... |
greyli/flask-avatars | flask_avatars/__init__.py | _Avatars.social_media | python | def social_media(username, platform='twitter', size='medium'):
return 'https://avatars.io/{platform}/{username}/{size}'.format(
platform=platform, username=username, size=size) | Return avatar URL at social media.
Visit https://avatars.io for more information.
:param username: The username of the social media.
:param platform: One of facebook, instagram, twitter, gravatar.
:param size: The size of avatar, one of small, medium and large. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L63-L72 | null | class _Avatars(object):
@staticmethod
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False):
"""Pass email hash, return Gravatar URL. You can get email hash like this::
import hashlib
avatar_hash = hashlib.md5(email.lower().... |
greyli/flask-avatars | flask_avatars/__init__.py | _Avatars.jcrop_css | python | def jcrop_css(css_url=None):
if css_url is None:
if current_app.config['AVATARS_SERVE_LOCAL']:
css_url = url_for('avatars.static', filename='jcrop/css/jquery.Jcrop.min.css')
else:
css_url = 'https://cdn.jsdelivr.net/npm/jcrop-0.9.12@0.9.12/css/jquery.Jcrop... | Load jcrop css file.
:param css_url: The custom CSS URL. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L84-L94 | null | class _Avatars(object):
@staticmethod
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False):
"""Pass email hash, return Gravatar URL. You can get email hash like this::
import hashlib
avatar_hash = hashlib.md5(email.lower().... |
greyli/flask-avatars | flask_avatars/__init__.py | _Avatars.jcrop_js | python | def jcrop_js(js_url=None, with_jquery=True):
serve_local = current_app.config['AVATARS_SERVE_LOCAL']
if js_url is None:
if serve_local:
js_url = url_for('avatars.static', filename='jcrop/js/jquery.Jcrop.min.js')
else:
js_url = 'https://cdn.jsdeliv... | Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L97-L119 | null | class _Avatars(object):
@staticmethod
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False):
"""Pass email hash, return Gravatar URL. You can get email hash like this::
import hashlib
avatar_hash = hashlib.md5(email.lower().... |
greyli/flask-avatars | flask_avatars/__init__.py | _Avatars.crop_box | python | def crop_box(endpoint=None, filename=None):
crop_size = current_app.config['AVATARS_CROP_BASE_WIDTH']
if endpoint is None or filename is None:
url = url_for('avatars.static', filename='default/default_l.jpg')
else:
url = url_for(endpoint, filename=filename)
retur... | Create a crop box.
:param endpoint: The endpoint of view function that serve avatar image file.
:param filename: The filename of the image that need to be crop. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L122-L134 | null | class _Avatars(object):
@staticmethod
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False):
"""Pass email hash, return Gravatar URL. You can get email hash like this::
import hashlib
avatar_hash = hashlib.md5(email.lower().... |
greyli/flask-avatars | flask_avatars/__init__.py | _Avatars.preview_box | python | def preview_box(endpoint=None, filename=None):
preview_size = current_app.config['AVATARS_CROP_PREVIEW_SIZE'] or current_app.config['AVATARS_SIZE_TUPLE'][2]
if endpoint is None or filename is None:
url = url_for('avatars.static', filename='default/default_l.jpg')
else:
u... | Create a preview box.
:param endpoint: The endpoint of view function that serve avatar image file.
:param filename: The filename of the image that need to be crop. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L137-L154 | null | class _Avatars(object):
@staticmethod
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False):
"""Pass email hash, return Gravatar URL. You can get email hash like this::
import hashlib
avatar_hash = hashlib.md5(email.lower().... |
greyli/flask-avatars | flask_avatars/__init__.py | _Avatars.init_jcrop | python | def init_jcrop(min_size=None):
init_x = current_app.config['AVATARS_CROP_INIT_POS'][0]
init_y = current_app.config['AVATARS_CROP_INIT_POS'][1]
init_size = current_app.config['AVATARS_CROP_INIT_SIZE'] or current_app.config['AVATARS_SIZE_TUPLE'][2]
if current_app.config['AVATARS_CROP_MIN_... | Initialize jcrop.
:param min_size: The minimal size of crop area. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L157-L226 | null | class _Avatars(object):
@staticmethod
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False):
"""Pass email hash, return Gravatar URL. You can get email hash like this::
import hashlib
avatar_hash = hashlib.md5(email.lower().... |
greyli/flask-avatars | flask_avatars/__init__.py | Avatars.resize_avatar | python | def resize_avatar(self, img, base_width):
w_percent = (base_width / float(img.size[0]))
h_size = int((float(img.size[1]) * float(w_percent)))
img = img.resize((base_width, h_size), PIL.Image.ANTIALIAS)
return img | Resize an avatar.
:param img: The image that needs to be resize.
:param base_width: The width of output image. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L278-L287 | null | class Avatars(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['avatars'] = _Avatars
app.context_processor(self.context_processor)
... |
greyli/flask-avatars | flask_avatars/__init__.py | Avatars.save_avatar | python | def save_avatar(self, image):
path = current_app.config['AVATARS_SAVE_PATH']
filename = uuid4().hex + '_raw.png'
image.save(os.path.join(path, filename))
return filename | Save an avatar as raw image, return new filename.
:param image: The image that needs to be saved. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L289-L297 | null | class Avatars(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['avatars'] = _Avatars
app.context_processor(self.context_processor)
... |
greyli/flask-avatars | flask_avatars/__init__.py | Avatars.crop_avatar | python | def crop_avatar(self, filename, x, y, w, h):
x = int(x)
y = int(y)
w = int(w)
h = int(h)
sizes = current_app.config['AVATARS_SIZE_TUPLE']
if not filename:
path = os.path.join(self.root_path, 'static/default/default_l.jpg')
else:
path = os... | Crop avatar with given size, return a list of file name: [filename_s, filename_m, filename_l].
:param filename: The raw image's filename.
:param x: The x-pos to start crop.
:param y: The y-pos to start crop.
:param w: The crop width.
:param h: The crop height. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L299-L349 | [
"def resize_avatar(self, img, base_width):\n \"\"\"Resize an avatar.\n\n :param img: The image that needs to be resize.\n :param base_width: The width of output image.\n \"\"\"\n w_percent = (base_width / float(img.size[0]))\n h_size = int((float(img.size[1]) * float(w_percent)))\n img = img.re... | class Avatars(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['avatars'] = _Avatars
app.context_processor(self.context_processor)
... |
greyli/flask-avatars | flask_avatars/identicon.py | Identicon.get_image | python | def get_image(self, string, width, height, pad=0):
hex_digest_byte_list = self._string_to_byte_list(string)
matrix = self._create_matrix(hex_digest_byte_list)
return self._create_image(matrix, width, height, pad) | Byte representation of a PNG image | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L72-L78 | [
"def _string_to_byte_list(self, data):\n \"\"\"\n Creates a hex digest of the input string given to create the image,\n if it's not already hexadecimal\n\n Returns:\n Length 16 list of rgb value range integers\n (each representing a byte of the hex digest)\n \"\"\"\n bytes_length = 1... | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
greyli/flask-avatars | flask_avatars/identicon.py | Identicon._get_pastel_colour | python | def _get_pastel_colour(self, lighten=127):
def r():
return random.randint(0, 128) + lighten
return r(), r(), r() | Create a pastel colour hex colour string | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L87-L93 | null | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
greyli/flask-avatars | flask_avatars/identicon.py | Identicon._luminance | python | def _luminance(self, rgb):
a = []
for v in rgb:
v = v / float(255)
if v < 0.03928:
result = v / 12.92
else:
result = math.pow(((v + 0.055) / 1.055), 2.4)
a.append(result)
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] ... | Determine the liminanace of an RGB colour | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L95-L108 | null | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
greyli/flask-avatars | flask_avatars/identicon.py | Identicon._string_to_byte_list | python | def _string_to_byte_list(self, data):
bytes_length = 16
m = self.digest()
m.update(str.encode(data))
hex_digest = m.hexdigest()
return list(int(hex_digest[num * 2:num * 2 + 2], bytes_length)
for num in range(bytes_length)) | Creates a hex digest of the input string given to create the image,
if it's not already hexadecimal
Returns:
Length 16 list of rgb value range integers
(each representing a byte of the hex digest) | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L110-L126 | null | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
greyli/flask-avatars | flask_avatars/identicon.py | Identicon._bit_is_one | python | def _bit_is_one(self, n, hash_bytes):
scale = 16 # hexadecimal
if not hash_bytes[int(n / (scale / 2))] >> int(
(scale / 2) - ((n % (scale / 2)) + 1)) & 1 == 1:
return False
return True | Check if the n (index) of hash_bytes is 1 or 0. | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L128-L138 | null | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
greyli/flask-avatars | flask_avatars/identicon.py | Identicon._create_image | python | def _create_image(self, matrix, width, height, pad):
image = Image.new("RGB", (width + (pad * 2),
height + (pad * 2)), self.bg_colour)
image_draw = ImageDraw.Draw(image)
# Calculate the block width and height.
block_width = float(width) / self.cols
... | Generates a PNG byte list | train | https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L140-L167 | null | class Identicon(object):
def __init__(self, rows=None, cols=None, bg_color=None):
"""Generate identicon image.
:param rows: The row of pixels in avatar.
:param columns: The column of pixels in avatar.
:param bg_color: Backgroud color, pass RGB tuple, for example: (125, 125, 125).
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.