code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Output is the same size as ts1
Ns1 = np.size(ts1)
Ns2 = np.size(ts2)
ts_out = np.zeros((Ns1,1), dtype='float64')
ishift = int(np.floor(Ns2/2)) # origin of ts2
t1m = np.mean(ts1)
t2m = np.mean(ts2)
for k in range(0,Ns1):
lstart = np.int(ishift-k)
if l... | def zncc(ts1,ts2) | Zero mean normalised cross-correlation (ZNCC)
This function does ZNCC of two signals, ts1 and ts2
Normalisation by very small values is avoided by doing
max(nmin,nvalue)
Parameters
--------------
ts1 : ndarray
Input signal 1 to be aligned with
ts2 : ndarray
Input si... | 2.273479 | 2.166867 | 1.049201 |
pyr1 = create_pyramid(ts1,nlevels)
pyr2 = create_pyramid(ts2,nlevels)
logger.debug("pyramid size = %d" % len(pyr1))
logger.debug("size of first element %d " % np.size(pyr1[0]))
logger.debug("size of last element %d " % np.size(pyr1[-1]))
ishift, corrfn = zncc(pyr1[-1],pyr2[-1])
f... | def find_shift_pyr(ts1,ts2,nlevels) | Find shift that best aligns two time series
The shift that aligns the timeseries ts1 with ts2.
This is sought using zero mean normalized cross correlation (ZNCC) in a coarse to fine search with an octave pyramid on nlevels levels.
Parameters
----------------
ts1 : list_like
The first t... | 2.892496 | 3.078788 | 0.939492 |
"Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds)"
file_data = open(filename, 'rb').read()
parser = L3GArduinoParser()
parser.parse(file_data[7:]) # Skip first "GYROLOG" header in file
data = par... | def load_L3G_arduino(filename, remove_begin_spurious=False, return_parser=False) | Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds) | 4.139589 | 3.267858 | 1.266759 |
"Convert combined axis angle vector to rotation matrix"
theta = np.linalg.norm(r)
v = r/theta
R = crisp.rotations.axis_angle_to_rotation_matrix(v, theta)
return R | def to_rot_matrix(r) | Convert combined axis angle vector to rotation matrix | 6.483169 | 5.216104 | 1.242914 |
assert num_sequences >= 2
# Create optical flow for user to select parts in
logger.info("Calculating optical flow")
flow = tracking.optical_flow_magnitude(image_sequence)
# ) Prompt user for sync slices
logger.debug("Prompting user for %d sequences" % num_sequences)
imu_fake_ti... | def pick_manual(image_sequence, imu_gyro, num_sequences=2) | Select N matching sequences and return data indices.
Parameters
---------------
image_sequence : list_like
A list, or generator, of image data
imu_gyro : (3, N) ndarray
Gyroscope data (angular velocities)
num_sequences : int
The number of matching sequences t... | 7.692691 | 7.752953 | 0.992227 |
N = np.zeros((3,3))
for x in gyro_data.T: # Transpose because samples are stored as columns
y = x.reshape(3,1)
N += y.dot(y.T)
(eig_val, eig_vec) = np.linalg.eig(N)
i = np.argmax(eig_val)
v = eig_vec[:,i]
# Make sure v has correct sign
s = 0
for x in gy... | def principal_rotation_axis(gyro_data) | Get the principal rotation axis of angular velocity measurements.
Parameters
-------------
gyro_data : (3, N) ndarray
Angular velocity measurements
Returns
-------------
v : (3,1) ndarray
The principal rotation axis for the chosen sequence | 3.199638 | 3.460771 | 0.924545 |
uri = node.attributes['uri']
doc_folder = os.path.dirname(self.builder.current_docname)
if uri.startswith(doc_folder):
# drop docname prefix
uri = uri[len(doc_folder):]
if uri.startswith("/"):
uri = "." + uri
self.add('\n\n![im... | def visit_image(self, node) | Image directive | 4.226684 | 3.89903 | 1.084035 |
def dec(cls):
# Need _make_method to ensure new variable picked up for each iteration
# of the loop. The defined method picks up this new variable in its
# scope.
for key, (prefix, suffix) in pref_suff_map.items():
setattr(cls, 'visit_' + key, _make_method(prefix))
... | def add_pref_suff(pref_suff_map) | Decorator adds visit, depart methods for prefix/suffix pairs | 7.004432 | 5.521523 | 1.268569 |
def meth(self, node):
pass
def dec(cls):
for element_name in pass_thrus:
for meth_prefix in ('visit_', 'depart_'):
meth_name = meth_prefix + element_name
if hasattr(cls, meth_name):
raise ValueError('method name {} already def... | def add_pass_thru(pass_thrus) | Decorator adds explicit pass-through visit and depart methods | 4.093315 | 3.43395 | 1.192013 |
string = ''.join(self.content)
lines = string.splitlines(True)
if len(lines) == 0:
return
texts = [self.first_prefix + lines[0]]
for line in lines[1:]:
if line.strip() == '': # avoid prefix for empty lines
texts.append('\n')
... | def write(self) | Add ``self.contents`` with current ``prefix`` and ``first_prefix``
Add processed ``self.contents`` to ``self.base``. The first line has
``first_prefix`` prepended, further lines have ``prefix`` prepended.
Empty (all whitespace) lines get written as bare carriage returns, to
avoid ugly... | 3.788306 | 2.97355 | 1.274001 |
key = self.get_public_key_hex()
return ensure_bytes(hexlify(hash160(unhexlify(ensure_bytes(key))))) | def identifier(self) | Get the identifier for this node.
Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256)
of the public key's `key`. This corresponds exactly to the data used in
traditional Bitcoin addresses. It is not advised to represent this data
in base58 format though, as it may be... | 7.73345 | 6.368337 | 1.214359 |
if self.private_key:
raise AssertionError("You already know the private key")
if child_private_key.parent_fingerprint != self.fingerprint:
raise ValueError("This is not a valid child")
if child_private_key.child_number >= 0x80000000:
raise ValueError(... | def crack_private_key(self, child_private_key) | Crack the parent private key given a child private key.
BIP32 has a vulnerability/feature that allows you to recover the
master private key if you're given a master public key and any of its
publicly-derived child private keys. This is a pretty serious security
vulnerability that looks ... | 3.638722 | 3.519689 | 1.033819 |
# Add the network byte, creating the "extended key"
extended_key_hex = self.private_key.get_extended_key()
# BIP32 wallets have a trailing \01 byte
extended_key_bytes = unhexlify(ensure_bytes(extended_key_hex)) + b'\01'
# And return the base58-encoded result with a check... | def export_to_wif(self) | Export a key to WIF.
See https://en.bitcoin.it/wiki/Wallet_import_format for a full
description. | 5.974219 | 6.139271 | 0.973115 |
# Register all distributions and wheels with PyPI. We have to list the dist
# directory and register each file individually because `twine` doesn't
# handle globs.
for filename in os.listdir(dist):
full_path = os.path.join(dist, filename)
if os.path.isfile(full_path):
# ... | def _pypi_push(dist) | Push created package to PyPI.
Requires the following defined environment variables:
- TWINE_USERNAME: The PyPI username to upload this package under
- TWINE_PASSWORD: The password to the user's account
Args:
dist (str):
The distribution to push. Must be a valid directory; s... | 5.522558 | 5.49228 | 1.005513 |
# Ensure proper environment
if not os.getenv(CIRCLECI_ENV_VAR): # pragma: no cover
raise EnvironmentError('Must be on CircleCI to run this script')
current_branch = os.getenv('CIRCLE_BRANCH')
if (target == 'PROD') and (current_branch != 'master'):
raise EnvironmentError(
... | def deploy(target) | Deploys the package and documentation.
Proceeds in the following steps:
1. Ensures proper environment variables are set and checks that we are on Circle CI
2. Tags the repository with the new version
3. Creates a standard distribution and a wheel
4. Updates version.py to have the proper version
... | 4.428761 | 3.910103 | 1.132645 |
return _s(dd['q']), _s(dd.get('r', NoResponse)), _s(dd.get('e', NoResponse)) | def _get_triplet(dd) | Return a triplet from a dialogue dictionary.
:param dd: Dialogue dictionary.
:type dd: Dict[str, str]
:return: (query, response, error response)
:rtype: (str, str | NoResponse, str | NoResponse) | 10.187814 | 5.40942 | 1.883347 |
try:
data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader)
except Exception as e:
raise type(e)('Malformed yaml file:\n%r' % format_exc())
try:
ver = data['spec']
except:
raise ValueError('The file does not specify a spec version')
try:
ver = t... | def _load(content_or_fp) | YAML Parse a file or str and check version. | 4.456128 | 4.204485 | 1.059851 |
with closing(pkg_resources.resource_stream(__name__, name)) as fp:
rbytes = fp.read()
return _load(StringIO(rbytes.decode('utf-8'))) | def parse_resource(name) | Parse a resource file | 4.930798 | 4.501225 | 1.095435 |
for dia in component_dict.get('dialogues', ()):
try:
comp.add_dialogue(*_get_pair(dia))
except Exception as e:
msg = 'In device %s, malformed dialogue %s\n%r'
raise Exception(msg % (name, dia, e))
for prop_name, prop_dict in component_dict.get('propertie... | def update_component(name, comp, component_dict) | Get a component from a component dict. | 2.903284 | 2.938359 | 0.988063 |
bases = definition_dict.get('bases', ())
if bases:
bases = (loader.get_comp_dict(required_version=SPEC_VERSION_TUPLE[0],
**b)
for b in bases)
return SimpleChainmap(definition_dict, *bases)
else:
return definition_dict | def get_bases(definition_dict, loader) | Collect dependencies. | 7.010238 | 6.772827 | 1.035053 |
channel_dict = get_bases(channel_dict, loader)
r_ids = resource_dict.get('channel_ids', {}).get(ch_name, [])
ids = r_ids if r_ids else channel_dict.get('ids', {})
can_select = False if channel_dict.get('can_select') == 'False' else True
channels = Channels(device, ids, can_select)
update... | def get_channel(device, ch_name, channel_dict, loader, resource_dict) | Get a channels from a channels dictionary.
:param name: name of the device
:param device_dict: device dictionary
:rtype: Device | 4.342382 | 5.048952 | 0.860056 |
device = Device(name, device_dict.get('delimiter', ';').encode('utf-8'))
device_dict = get_bases(device_dict, loader)
err = device_dict.get('error', {})
device.add_error_handler(err)
for itype, eom_dict in device_dict.get('eom', {}).items():
device.add_eom(itype, *_get_pair(eom_dict)... | def get_device(name, device_dict, loader, resource_dict) | Get a device from a device dictionary.
:param name: name of the device
:param device_dict: device dictionary
:rtype: Device | 4.064773 | 4.40455 | 0.922858 |
loader = Loader(filename, bundled)
data = loader.data
devices = Devices()
# Iterate through the resources and generate each individual device
# on demand.
for resource_name, resource_dict in data.get('resources', {}).items():
device_name = resource_dict['device']
dd = ... | def get_devices(filename, bundled) | Get a Devices object from a file.
:param filename: full path of the file to parse or name of the resource.
:param is_resource: boolean indicating if it is a resource.
:rtype: Devices | 4.748345 | 4.665359 | 1.017788 |
value = self.validate_value(string_value)
self._value = defaultdict(lambda: value) | def init_value(self, string_value) | Create an empty defaultdict holding the default value. | 6.203954 | 4.605684 | 1.347021 |
value = self.validate_value(string_value)
self._value[self._channel._selected] = value | def set_value(self, string_value) | Set the current value for a channel. | 9.777198 | 7.539616 | 1.296777 |
self._dialogues['__default__'][to_bytes(query)] = to_bytes(response) | def add_dialogue(self, query, response) | Add dialogue to channel.
:param query: query string
:param response: response string | 8.827997 | 12.356613 | 0.714435 |
self._properties[name] = ChannelProperty(self, name,
default_value, specs)
if getter_pair:
query, response = getter_pair
self._getters['__default__'][to_bytes(query)] = name, response
if setter_triplet:
... | def add_property(self, name, default_value, getter_pair, setter_triplet,
specs) | Add property to channel
:param name: property name
:param default_value: default value as string
:param getter_pair: (query, response)
:param setter_triplet: (query, response, error)
:param specs: specification of the Property | 4.902797 | 4.232637 | 1.158332 |
if not self.can_select:
ch_id = self._device._properties['selected_channel'].get_value()
if ch_id in self._ids:
self._selected = ch_id
else:
return
response = self._match_dialog(query,
... | def match(self, query) | Try to find a match for a query in the channel commands. | 3.054541 | 2.950619 | 1.03522 |
q = query.decode('utf-8')
for name, parser, response, error_response in self._setters:
try:
parsed = parser(q)
logger.debug('Found response in setter of %s' % name)
except ValueError:
continue
try:
... | def _match_setters(self, query) | Try to find a match | 4.73665 | 4.668021 | 1.014702 |
from . import __version__
from .parser import SPEC_VERSION
d = OrderedDict()
d['Version'] = '%s' % __version__
d['Spec version'] = SPEC_VERSION
return d | def get_debug_info() | Return a list of lines with backend info. | 6.104523 | 5.657997 | 1.07892 |
try:
open_timeout = int(open_timeout)
except ValueError:
raise ValueError('open_timeout (%r) must be an integer (or compatible type)' % open_timeout)
try:
parsed = rname.parse_resource_name(resource_name)
except rname.InvalidResourceName:
... | def open(self, session, resource_name,
access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE) | Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param session: Resource Manager session
(should always be a session returned
from open_default_resource_manager()).
:param resource_name: Unique symbo... | 4.489754 | 4.371113 | 1.027142 |
try:
del self.sessions[session]
return constants.StatusCode.success
except KeyError:
return constants.StatusCode.error_invalid_object | def close(self, session) | Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode` | 6.693085 | 5.155105 | 1.298341 |
# For each session type, ask for the list of connected resources and merge them into a single list.
resources = self.devices.list_resources()
resources = rname.filter(resources, query)
if resources:
return resources
raise errors.VisaIOError(errors.Status... | def list_resources(self, session, query='?*::INSTR') | Returns a tuple of all connected devices matching query.
:param query: regular expression used to match devices. | 9.370044 | 9.623475 | 0.973665 |
try:
sess = self.sessions[session]
except KeyError:
return b'', constants.StatusCode.error_invalid_object
try:
chunk, status = sess.read(count)
if status == constants.StatusCode.error_timeout:
raise errors.VisaIOError(con... | def read(self, session, count) | Reads data from device or interface synchronously.
Corresponds to viRead function of the VISA library.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: bytes, :class:`... | 4.823313 | 3.288494 | 1.466724 |
try:
sess = self.sessions[session]
except KeyError:
return constants.StatusCode.error_invalid_object
try:
return sess.write(data)
except AttributeError:
return constants.StatusCode.error_nonsupported_operation | def write(self, session, data) | Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: str
:return: Number of bytes actually transferred, return value of the lib... | 4.786569 | 3.668857 | 1.304649 |
try:
return cls._session_classes[(interface_type, resource_class)]
except KeyError:
raise ValueError('No class registered for %s, %s' % (interface_type, resource_class)) | def get_session_class(cls, interface_type, resource_class) | Return the session class for a given interface type and resource class.
:type interface_type: constants.InterfaceType
:type resource_class: str
:return: Session | 2.62733 | 3.181608 | 0.825787 |
def _internal(python_class):
if (interface_type, resource_class) in cls._session_classes:
logger.warning('%s is already registered in the ResourceManager. '
'Overwriting with %s' % ((interface_type, resource_class), python_class))
... | def register(cls, interface_type, resource_class) | Register a session class for a given interface type and resource class.
:type interface_type: constants.InterfaceType
:type resource_class: str | 3.208968 | 3.150506 | 1.018557 |
# Check that the attribute exists.
try:
attr = attributes.AttributesByID[attribute]
except KeyError:
return 0, constants.StatusCode.error_nonsupported_attribute
# Check that the attribute is valid for this session type.
if not attr.in_resource(s... | def get_attribute(self, attribute) | Get an attribute from the session.
:param attribute:
:return: attribute value, status code
:rtype: object, constants.StatusCode | 5.762593 | 5.235809 | 1.100612 |
# Check that the attribute exists.
try:
attr = attributes.AttributesByID[attribute]
except KeyError:
return constants.StatusCode.error_nonsupported_attribute
# Check that the attribute is valid for this session type.
if not attr.in_resource(self... | def set_attribute(self, attribute, attribute_state) | Get an attribute from the session.
:param attribute:
:return: attribute value, status code
:rtype: object, constants.StatusCode | 3.108644 | 2.909631 | 1.068398 |
if val is NoResponse:
return val
val = val.replace('\\r', '\r').replace('\\n', '\n')
return val.encode() | def to_bytes(val) | Takes a text message and return a tuple | 5.899492 | 5.874098 | 1.004323 |
specs = self.specs
if 'type' in specs:
value = specs['type'](string_value)
else:
value = string_value
if 'min' in specs and value < specs['min']:
raise ValueError
if 'max' in specs and value > specs['max']:
raise ValueError... | def validate_value(self, string_value) | Validate that a value match the Property specs. | 2.13781 | 1.953074 | 1.094588 |
if dialogues is None:
dialogues = self._dialogues
# Try to match in the queries
if query in dialogues:
response = dialogues[query]
logger.debug('Found response in queries: %s' % repr(response))
return response | def _match_dialog(self, query, dialogues=None) | Tries to match in dialogues
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None | 4.305189 | 4.222422 | 1.019602 |
if getters is None:
getters = self._getters
if query in getters:
name, response = getters[query]
logger.debug('Found response in getter of %s' % name)
response = response.format(self._properties[name].get_value())
return response.enco... | def _match_getters(self, query, getters=None) | Tries to match in getters
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None | 5.239911 | 4.989408 | 1.050207 |
q = query.decode('utf-8')
for name, parser, response, error_response in self._setters:
try:
value = parser(q)
logger.debug('Found response in setter of %s' % name)
except ValueError:
continue
try:
... | def _match_setters(self, query) | Tries to match in setters
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None | 4.99394 | 4.524316 | 1.1038 |
if isinstance(error_input, dict):
error_response = error_input.get('response', {})
cerr = error_response.get('command_error', NoResponse)
qerr = error_response.get('query_error', NoResponse)
response_dict = {'command_error': cerr,
... | def add_error_handler(self, error_input) | Add error handler to the device | 2.77181 | 2.743768 | 1.01022 |
interface_type, resource_class = type_class.split(' ')
interface_type = getattr(constants.InterfaceType,
interface_type.lower())
self._eoms[(interface_type,
resource_class)] = (to_bytes(query_termination),
... | def add_eom(self, type_class, query_termination, response_termination) | Add default end of message for a given interface type and resource class.
:param type_class: interface type and resource class as strings joined by space
:param query_termination: end of message used in queries.
:param response_termination: end of message used in responses. | 4.773901 | 3.573305 | 1.33599 |
logger.debug('Writing into device input buffer: %r' % data)
if not isinstance(data, bytes):
raise TypeError('data must be an instance of bytes')
if len(data) != 1:
msg = 'data must have a length of 1, not %d'
raise ValueError(msg % len(data))
... | def write(self, data) | Write data into the device input buffer.
:param data: single element byte
:type data: bytes | 3.467506 | 3.293747 | 1.052754 |
if self._output_buffer:
b, self._output_buffer = (self._output_buffer[0:1],
self._output_buffer[1:])
return b
return b'' | def read(self) | Return a single byte from the output buffer | 4.944784 | 3.672714 | 1.346357 |
response = self._match_dialog(query)
if response is not None:
return response
response = self._match_getters(query)
if response is not None:
return response
response = self._match_registers(query)
if response is not None:
ret... | def _match(self, query) | Tries to match in dialogues, getters and setters and subcomponents
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None | 2.539156 | 2.202471 | 1.152867 |
if query in self._status_registers:
register = self._status_registers[query]
response = register.value
logger.debug('Found response in status register: %s',
repr(response))
register.clear()
return response | def _match_registers(self, query) | Tries to match in status registers
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None | 6.71451 | 4.900095 | 1.370281 |
if query in self._error_queues:
queue = self._error_queues[query]
response = queue.value
logger.debug('Found response in error queue: %s',
repr(response))
return response | def _match_errors_queues(self, query) | Tries to match in error queues
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None | 5.196151 | 4.665156 | 1.113821 |
if device.resource_name is not None:
msg = 'The device %r is already assigned to %s'
raise ValueError(msg % (device, device.resource_name))
device.resource_name = resource_name
self._internal[device.resource_name] = device | def add_device(self, resource_name, device) | Bind device to resource name | 3.745707 | 3.333735 | 1.123577 |
result = super(SequenceCursorPagination, self).get_ordering(*args, **kwargs)
# Because paginate_queryset sets self.ordering after reading it...we
# need to only modify it sometimes. (This allows re-use of the
# paginator, which probably only happens in tests.)
if result... | def get_ordering(self, *args, **kwargs) | Take whatever the expected ordering is and then first order by QuerySet. | 12.158984 | 11.243523 | 1.081421 |
# Get the QuerySet number of the current instance.
qs_order = getattr(instance, '#')
# Strip the '#' and call the standard _get_position_from_instance.
result = super(SequenceCursorPagination, self)._get_position_from_instance(instance, ordering[1:])
# Return a tuple o... | def _get_position_from_instance(self, instance, ordering) | The position will be a tuple of values:
The QuerySet number inside of the QuerySetSequence.
Whatever the normal value taken from the ordering property gives. | 7.343938 | 5.828568 | 1.25999 |
# Determine if we have a cursor, and if so then decode it.
encoded = request.query_params.get(self.cursor_query_param)
if encoded is None:
return None
try:
querystring = b64decode(encoded.encode('ascii')).decode('ascii')
tokens = urlparse.par... | def decode_cursor(self, request) | Given a request with a cursor, return a `Cursor` instance.
Differs from the standard CursorPagination to handle a tuple in the
position field. | 3.719568 | 3.621684 | 1.027027 |
assert len(it1) == len(it2),\
"Can not element-wise multiply iterables of different length."
return list(map(mul, it1, it2)) | def multiply_iterables(it1, it2) | Element-wise iterables multiplications. | 3.9805 | 3.464877 | 1.148814 |
if isinstance(value1, Model) and isinstance(value2, Model):
field_names = value1._meta.ordering
# Assert that the ordering is the same between different models.
if field_names != value2._meta.ordering:
valid_field_names = (set(cls._get_field_names(va... | def _cmp(cls, value1, value2) | Comparison method that takes into account Django's special rules when
ordering by a field that is a model:
1. Try following the default ordering on the related model.
2. Order by the model's primary key, if there is no Meta.ordering. | 3.524255 | 3.527294 | 0.999139 |
# Ensure that field names is a list and not a tuple.
field_names = list(field_names)
# For fields that start with a '-', reverse the ordering of the
# comparison.
reverses = [1] * len(field_names)
for i, field_name in enumerate(field_names):
if field... | def _generate_comparator(cls, field_names) | Construct a comparator function based on the field names. The comparator
returns the first non-zero comparison value.
Inputs:
field_names (iterable of strings): The field names to sort on.
Returns:
A comparator function. | 3.554152 | 3.686978 | 0.963974 |
# A list of tuples, each with:
# * The iterable
# * The QuerySet number
# * The next value
#
# (Remember that each QuerySet is already sorted.)
iterables = []
for i, qs in zip(self._queryset_idxs, self._querysets):
it = iter(qs)
... | def _ordered_iterator(self) | Interleave the values of each QuerySet in order to handle the requested
ordering. Also adds the '#' property to each returned item. | 3.88498 | 3.764018 | 1.032136 |
for i, qs in zip(self._queryset_idxs, self._querysets):
for item in qs:
setattr(item, '#', i)
yield item | def _unordered_iterator(self) | Return the value of each QuerySet, but also add the '#' property to each
return item. | 10.121241 | 5.013074 | 2.018969 |
# Ensure negate is a boolean.
negate = bool(negate)
for kwarg, value in kwargs.items():
parts = kwarg.split(LOOKUP_SEP)
# Ensure this is being used to filter QuerySets.
if parts[0] != '#':
raise ValueError("Keyword '%s' is not a vali... | def _filter_or_exclude_querysets(self, negate, **kwargs) | Similar to QuerySet._filter_or_exclude, but run over the QuerySets in
the QuerySetSequence instead of over each QuerySet's fields. | 2.898537 | 2.877826 | 1.007197 |
self.reader.decoder.register(key_or_tag, f_val) | def register(self, key_or_tag, f_val) | Register a custom transit tag and decoder/parser function for use
during reads. | 6.955163 | 5.183164 | 1.341876 |
for o in self.reader.loadeach(stream):
yield o | def readeach(self, stream, **kwargs) | Temporary hook for API while streaming reads are in experimental
phase. Read each object from stream as available with generator.
JSON blocks indefinitely waiting on JSON entities to arrive. MsgPack
requires unpacker property to be fed stream using unpacker.feed()
method. | 18.121798 | 11.820041 | 1.533142 |
if is_cache_key(name) and (name in self.key_to_value):
return self.key_to_value[name]
return self.encache(name) if is_cacheable(name, as_map_key) else name | def decode(self, name, as_map_key=False) | Always returns the name | 4.63131 | 4.481937 | 1.033328 |
if name in self.key_to_value:
return self.key_to_value[name]
return self.encache(name) if is_cacheable(name, as_map_key) else name | def encode(self, name, as_map_key=False) | Returns the name the first time and the key after that | 4.280663 | 4.034328 | 1.06106 |
chunk = stream.read(1)
while chunk in SKIP:
chunk = stream.read(1)
if chunk == "\"":
chunk += stream.read(1)
while not chunk.endswith("\""):
if chunk[-1] == ESCAPE:
chunk += stream.read(2)
else:
chunk += stream.read(1)
... | def read_chunk(stream) | Ignore whitespace outside of strings. If we hit a string, read it in
its entirety. | 3.009464 | 2.85209 | 1.055178 |
for s in yield_json(stream):
yield json.loads(s, **kwargs) | def items(stream, **kwargs) | External facing items. Will return item from stream as available.
Currently waits in loop waiting for next item. Can pass keywords that
json.loads accepts (such as object_pairs_hook) | 8.745399 | 8.741602 | 1.000434 |
buff = u""
arr_count = 0
obj_count = 0
while True:
buff += read_chunk(stream)
# If we finish parsing all objs or arrays, yield a finished JSON
# entity.
if buff.endswith('{'):
obj_count += 1
if buff.endswith('['):
arr_count += 1
... | def yield_json(stream) | Uses array and object delimiter counts for balancing. | 3.110245 | 2.861623 | 1.086881 |
for x in m.keys():
if len(self.handlers[x].tag(x)) != 1:
return False
return True | def are_stringable_keys(self, m) | Test whether the keys within a map are stringable - a simple map,
that can be optimized and whose keys can be cached | 7.444247 | 8.01079 | 0.929278 |
handler = self.handlers[obj]
tag = handler.tag(obj)
f = marshal_dispatch.get(tag)
if f:
f(self, obj, handler.string_rep(obj) if as_map_key else handler.rep(obj), as_map_key, cache)
else:
self.emit_encoded(tag, handler, obj, as_map_key, cache) | def marshal(self, obj, as_map_key, cache) | Marshal an individual obj, potentially as part of another container
object (like a list/dictionary/etc). Specify if this object is a key
to a map/dict, and pass in the current cache being used.
This method should only be called by a top-level marshalling call
and should not be considere... | 4.173525 | 4.242138 | 0.983826 |
if not cache:
cache = RollingCache()
handler = self.handlers[obj]
tag = handler.tag(obj)
if tag:
if len(tag) == 1:
self.marshal(TaggedValue(QUOTE, obj), False, cache)
else:
self.marshal(obj, False, cache)
... | def marshal_top(self, obj, cache=None) | Given a complete object that needs to be marshaled into Transit
data, and optionally a cache, dispatch accordingly, and flush the data
directly into the IO stream. | 6.21953 | 5.82721 | 1.067325 |
if self.are_stringable_keys(rep):
return self.emit_map(rep, as_map_key, cache)
return self.emit_cmap(rep, as_map_key, cache) | def dispatch_map(self, rep, as_map_key, cache) | Used to determine and dipatch the writing of a map - a simple
map with strings as keys, or a complex map, whose keys are also
compound types. | 4.821033 | 4.500688 | 1.071177 |
self.emit_array_start(None)
self.marshal(MAP_AS_ARR, False, cache)
for k, v in m.items():
self.marshal(k, True, cache)
self.marshal(v, False, cache)
self.emit_array_end() | def emit_map(self, m, _, cache) | Emits array as per default JSON spec. | 4.221272 | 3.610813 | 1.169064 |
if not cache:
cache = RollingCache()
return self._decode(node, cache, as_map_key) | def decode(self, node, cache=None, as_map_key=False) | Given a node of data (any supported decodeable obj - string, dict,
list), return the decoded object. Optionally set the current decode
cache [None]. If None, a new RollingCache is instantiated and used.
You may also hit to the decoder that this node is to be treated as a
map key [False... | 4.891914 | 2.816541 | 1.736852 |
if node:
if node[0] == MAP_AS_ARR:
# key must be decoded before value for caching to work.
returned_dict = {}
for k, v in pairs(node[1:]):
key = self._decode(k, cache, True)
val = self._decode(v, cache, ... | def decode_list(self, node, cache, as_map_key) | Special case decodes map-as-array.
Otherwise lists are treated as Python lists.
Arguments follow the same convention as the top-level 'decode'
function. | 3.899259 | 3.676497 | 1.060591 |
if is_cache_key(string):
return self.parse_string(cache.decode(string, as_map_key),
cache, as_map_key)
if is_cacheable(string, as_map_key):
cache.encode(string, as_map_key)
return self.parse_string(string, cache, as_map_key) | def decode_string(self, string, cache, as_map_key) | Decode a string - arguments follow the same convention as the
top-level 'decode' function. | 2.812388 | 2.903454 | 0.968635 |
if key_or_tag == "default_decoder":
self.options["default_decoder"] = obj
else:
self.decoders[key_or_tag] = obj | def register(self, key_or_tag, obj) | Register a custom Transit tag and new parsing function with the
decoder. Also, you can optionally set the 'default_decoder' with
this function. Your new tag and parse/decode function will be added
to the interal dictionary of decoders for this Decoder object. | 4.017104 | 2.625591 | 1.529981 |
if isinstance(u, pyversion.string_types):
return uuid.UUID(u)
# hack to remove signs
a = ctypes.c_ulong(u[0])
b = ctypes.c_ulong(u[1])
combined = a.value << 64 | b.value
return uuid.UUID(int=combined) | def from_rep(u) | Given a string, return a UUID object. | 5.395499 | 4.896626 | 1.101881 |
in_port = self.match.get_field(OxmOfbMatchField.OFPXMT_OFB_IN_PORT)
return int.from_bytes(in_port, 'big') | def in_port(self) | Retrieve the 'in_port' that generated the PacketIn.
This method will look for the OXM_TLV with type OFPXMT_OFB_IN_PORT on
the `oxm_match_fields` field from `match` field and return its value,
if the OXM exists.
Returns:
The integer number of the 'in_port' that generated the... | 3.311373 | 3.509081 | 0.943658 |
begin = offset
for attribute_name, class_attribute in self.get_class_attributes():
if type(class_attribute).__name__ != "Header":
attribute = deepcopy(class_attribute)
if attribute_name == 'actions':
length = self.actions_len.value... | def unpack(self, buff, offset=0) | Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results. It is an inplace method and it receives the binary data
of the message **without the header**.
This class' unpack method is like the :meth:`.Gen... | 4.135 | 3.591106 | 1.151456 |
if isinstance(self.actions, ListOfActions):
self.actions_len = self.actions.get_size()
else:
self.actions_len = ListOfActions(self.actions).get_size() | def _update_actions_len(self) | Update the actions_len field based on actions value. | 3.215125 | 2.703334 | 1.189319 |
is_valid_range = self.in_port > 0 and self.in_port <= Port.OFPP_MAX
is_valid_virtual_in_ports = self.in_port in _VIRT_IN_PORTS
if (is_valid_range or is_valid_virtual_in_ports) is False:
raise ValidationError(f'{self.in_port} is not a valid input port.') | def _validate_in_port(self) | Validate in_port attribute.
A valid port is either:
* Greater than 0 and less than or equals to Port.OFPP_MAX
* One of the valid virtual ports: Port.OFPP_LOCAL,
Port.OFPP_CONTROLLER or Port.OFPP_NONE
Raises:
ValidationError: If in_port is an invalid p... | 3.413191 | 2.902176 | 1.17608 |
backup = self.body
if not value:
value = self.body
if hasattr(value, 'pack'):
self.body = value.pack()
stats_request_packed = super().pack()
self.body = backup
return stats_request_packed | def pack(self, value=None) | Pack according to :attr:`body_type`.
Make `body` a binary pack before packing this object. Then, restore
body. | 5.541819 | 5.137377 | 1.078725 |
super().unpack(buff)
class_name = self._get_body_class()
buff = self.body.value
self.body = FixedTypeList(pyof_class=class_name)
self.body.unpack(buff) | def unpack(self, buff, offset=0) | Unpack according to :attr:`body_type`. | 8.697592 | 7.293689 | 1.192482 |
if self.value <= 1:
return InstructionsProperty
elif self.value <= 3:
return NextTablesProperty
elif self.value <= 7:
return ActionsProperty
return OxmProperty | def find_class(self) | Return a class related with this type. | 13.050096 | 11.625028 | 1.122586 |
property_type = UBInt16(enum_ref=TableFeaturePropType)
property_type.unpack(buff, offset)
self.__class__ = TableFeaturePropType(property_type.value).find_class()
length = UBInt16()
length.unpack(buff, offset=offset+2)
super().unpack(buff[:offset+length.value], o... | def unpack(self, buff=None, offset=0) | Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: I... | 5.249997 | 6.78482 | 0.773786 |
length = UBInt16()
length.unpack(buff, offset)
super().unpack(buff[:offset+length.value], offset) | def unpack(self, buff=None, offset=0) | Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: I... | 5.09879 | 8.35833 | 0.610025 |
message_type = str(message_type)
if message_type not in MESSAGE_TYPES:
raise ValueError('"{}" is not known.'.format(message_type))
message_class = MESSAGE_TYPES.get(message_type)
message_instance = message_class()
return message_instance | def new_message_from_message_type(message_type) | Given an OpenFlow Message Type, return an empty message of that type.
Args:
messageType (:class:`~pyof.v0x01.common.header.Type`):
Python-openflow message.
Returns:
Empty OpenFlow message of the requested message type.
Raises:
KytosUndefinedMessageType: Unkown Message_... | 2.723369 | 3.665001 | 0.743075 |
message_type = header.message_type
if not isinstance(message_type, Type):
try:
if isinstance(message_type, str):
message_type = Type[message_type]
elif isinstance(message_type, int):
message_type = Type(message_type)
except ValueError:... | def new_message_from_header(header) | Given an OF Header, return an empty message of header's message_type.
Args:
header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header.
Returns:
Empty OpenFlow message of the same type of message_type attribute from
the given header.
The header attribute of the message... | 2.415435 | 2.42661 | 0.995395 |
hdr_size = Header().get_size()
hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:]
header = Header()
header.unpack(hdr_buff)
message = new_message_from_header(header)
message.unpack(msg_buff)
return message | def unpack_message(buffer) | Unpack the whole buffer, including header pack.
Args:
buffer (bytes): Bytes representation of a openflow message.
Returns:
object: Instance of openflow message. | 2.901048 | 3.761763 | 0.771194 |
band_type = UBInt16(enum_ref=MeterBandType)
band_type.unpack(buff, offset)
self.__class__ = MeterBandType(band_type.value).find_class()
length = UBInt16()
length.unpack(buff, offset=offset+2)
super().unpack(buff[:offset+length.value], offset) | def unpack(self, buff=None, offset=0) | Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: I... | 5.377796 | 6.651429 | 0.808517 |
buff = self.body
if not value:
value = self.body
if value:
if isinstance(value, (list, FixedTypeList)):
obj = self._get_body_instance()
obj.extend(value)
elif hasattr(value, 'pack'):
obj = value
... | def pack(self, value=None) | Pack a StatsReply using the object's attributes.
This method will pack the attribute body and multipart_type before pack
the StatsReply object, then will return this struct as a binary data.
Returns:
stats_reply_packed (bytes): Binary data with StatsReply packed. | 5.802858 | 5.345149 | 1.085631 |
super().unpack(buff[offset:])
self._unpack_body() | def unpack(self, buff, offset=0) | Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results. It is an inplace method and it receives the binary data
of the message **without the header**.
This class' unpack method is like the :meth:`.Gen... | 13.941381 | 16.626034 | 0.838527 |
obj = self._get_body_instance()
obj.unpack(self.body.value)
self.body = obj | def _unpack_body(self) | Unpack `body` replace it by the result. | 6.626363 | 5.473217 | 1.210689 |
exp_header = ExperimenterMultipartHeader
simple_body = {MultipartType.OFPMP_DESC: Desc,
MultipartType.OFPMP_GROUP_FEATURES: GroupFeatures,
MultipartType.OFPMP_METER_FEATURES: MeterFeatures,
MultipartType.OFPMP_EXPERIMENTER: ex... | def _get_body_instance(self) | Return the body instance. | 2.42622 | 2.406788 | 1.008074 |
unpack_length = UBInt16()
unpack_length.unpack(buff, offset)
super().unpack(buff[:offset+unpack_length], offset) | def unpack(self, buff, offset=0) | Unpack a binary message into this object's attributes.
Pass the correct length for list unpacking.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking. | 5.987797 | 7.714731 | 0.776151 |
length = UBInt16()
length.unpack(buff, offset)
length.unpack(buff, offset=offset+MeterStats.meter_id.get_size())
super().unpack(buff[:offset+length.value], offset=offset) | def unpack(self, buff=None, offset=0) | Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: I... | 7.673166 | 10.671535 | 0.719031 |
classes = {1: InstructionGotoTable, 2: InstructionWriteMetadata,
3: InstructionWriteAction, 4: InstructionApplyAction,
5: InstructionClearAction, 6: InstructionMeter}
return classes.get(self.value, None) | def find_class(self) | Return a class related with this type. | 8.286574 | 8.202942 | 1.010195 |
instruction_type = UBInt16(enum_ref=InstructionType)
instruction_type.unpack(buff, offset)
self.__class__ = InstructionType(instruction_type.value).find_class()
length = UBInt16()
length.unpack(buff, offset=offset+2)
super().unpack(buff[:offset+length.value], o... | def unpack(self, buff=None, offset=0) | Unpack *buff* into this object.
This method will convert a binary data into a readable value according
to the attribute format.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: I... | 4.868726 | 5.87558 | 0.828637 |
super().unpack(buff, offset)
# Recover field from field_and_hasmask.
try:
self.oxm_field = self._unpack_oxm_field()
except ValueError as exception:
raise UnpackException(exception)
# The last bit of field_and_mask is oxm_hasmask
self.oxm_... | def unpack(self, buff, offset=0) | Unpack the buffer into a OxmTLV.
Args:
buff (bytes): The binary data to be unpacked.
offset (int): If we need to shift the beginning of the data. | 5.329489 | 4.950391 | 1.076579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.