Raises ValueError if data is not bytes.
        Raises ValueError if len(data) is not length.
        Length may be None for unknown lengths (e.g. scripts).
        length=None will allow 0 length data.
324005
def validate_bytes(data, length=4):
        '''
        
        '''
        if (not isinstance(data, ByteData)
                and not isinstance(data, bytes)
                and not isinstance(data, bytearray)):
            raise ValueError('Expected byte-like object. '
                             'Got: {}'.format(type(data)))

        if length is None:
            return

        if len(data) != length:
            raise ValueError('Expected byte-like object with length {}. '
                             'Got {} with length {}.'
                             .format(length, type(data), len(data)))
855521
def expectedBody(self, data):
        
        bodyLen = None
        if data.len == 1:
            bodyLen = UInt8()
        elif data.len == 2:
            bodyLen = UInt16Be()
        elif data.len == 4:
            bodyLen = UInt32Be()
        else:
            log.error("invalid header length")
            return
        data.readType(bodyLen)
        self.expect(bodyLen.value, self._callbackBody)
1031604
def set_data(self, data):
		""
		if data is None:
			self.data_size = 0
			self.data = None
			return
		self.data_size = len(data)
		# create a string buffer so that null bytes aren't interpreted
		#  as the end of the string
		self.data = ctypes.cast(ctypes.create_string_buffer(data), ctypes.c_void_p)
1228895
static void isCorrectLength(byte[] object, int length, String name) {
    Validate.notNull(object, "%s cannot be null.", name);

    Validate.isTrue(object.length == length,
        "%s should be %d bytes, found %d bytes.", name, length, object.length);
  }
751764
def _check_len(a, b):
    
    if len(a) != len(b):
        msg = "Length must be {}. Got {}".format(len(a), len(b))
        raise ValueError(msg)
597093
def ensure_fixed_length_bytes(var):
    """"""
    dims, data, attrs, encoding = unpack_for_encoding(var)
    if check_vlen_dtype(data.dtype) == bytes:
        # TODO: figure out how to handle this with dask
        data = np.asarray(data, dtype=np.string_)
    return Variable(dims, data, attrs, encoding)
190210
def chunker(data, raise_exception=False):
    
    instructions = []
    data = bytes(data)
    while True:
        if len(data) == 0: break
        try:
            opcode = match_opcode(data)
        except:
            msg = 'unknown opcode starting with {}...)'.format(hex_format(data[0:4]))
            if raise_exception:
                raise ValueError(msg)
            else:
                logger.warning(msg)
                data = data[1:]
                continue
        opcode_def = OPCODES[opcode]
        num_bytes = len(opcode)
        if opcode_def[1] > 0: num_bytes += opcode_def[1]
        if 'raster' in opcode_def[0]:
            num_bytes += data[2] + 2
        #payload = data[len(opcode):num_bytes]
        instructions.append(data[:num_bytes])
        data = data[num_bytes:]
    return instructions
435674
def _check_list_len(row, length):
        
        if len(row) != length:
            raise Exception(
                "row length does not match expected length of " +
                str(length) + "\nrow: " + str(row))
170506
def set_length(len , fill_char)
      return if len <= 0
      old = char_length
      return if old >= len
      self.char_length = len
      check_length
      fill_from_with( old + 1 , fill_char )
    end
1141140
def read_option_value_len_from_byte(byte, pos, values):
        
        h_nibble = (byte & 0xF0) >> 4
        l_nibble = byte & 0x0F
        value = 0
        length = 0
        if h_nibble <= 12:
            value = h_nibble
        elif h_nibble == 13:
            value = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13
            pos += 1
        elif h_nibble == 14:
            s = struct.Struct("!H")
            value = s.unpack_from(values[pos:].to_bytes(2, "big"))[0] + 269
            pos += 2
        else:
            raise AttributeError("Unsupported option number nibble " + str(h_nibble))

        if l_nibble <= 12:
            length = l_nibble
        elif l_nibble == 13:
            length = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13
            pos += 1
        elif l_nibble == 14:
            length = s.unpack_from(values[pos:].to_bytes(2, "big"))[0] + 269
            pos += 2
        else:
            raise AttributeError("Unsupported option length nibble " + str(l_nibble))
        return value, length, pos
529888
def _is_numeric_data(ll):
    
    for l in ll:
        try:
            if any(math.isnan(float(i)) or isinstance(i, str) for i in l):
                return False
            # if not all(isinstance(i, (int, float)) or math.isnan(float(i)) for i in l):
            #     # There is an entry that is a non-numeric entry in this list
            #     return False
        except ValueError:
            # Trying to case a str as a float didnt work, and we got an error
            return False
    # All arrays are 100% numeric or "nan" entries.
    return True
857850
def _fromdata(self, data, maxval=None):
        """"""
        data = numpy.array(data, ndmin=2, copy=True)
        if data.dtype.kind not in "uib":
            raise ValueError("not an integer type: %s" % data.dtype)
        if data.dtype.kind == 'i' and numpy.min(data) < 0:
            raise ValueError("data out of range: %i" % numpy.min(data))
        if maxval is None:
            maxval = numpy.max(data)
            maxval = 255 if maxval < 256 else 65535
        if maxval < 0 or maxval > 65535:
            raise ValueError("data out of range: %i" % maxval)
        data = data.astype('u1' if maxval < 256 else '>u2')
        self._data = data
        if data.ndim > 2 and data.shape[-1] in (3, 4):
            self.depth = data.shape[-1]
            self.width = data.shape[-2]
            self.height = data.shape[-3]
            self.magicnum = b'P7' if self.depth == 4 else b'P6'
        else:
            self.depth = 1
            self.width = data.shape[-1]
            self.height = data.shape[-2]
            self.magicnum = b'P5' if maxval > 1 else b'P4'
        self.maxval = maxval
        self.tupltypes = [self._types[self.magicnum]]
        self.header = self._header()
28805
def data_to_bytes(self, data_element, encoding=None):
        
        if encoding is None:
            encoding = self.encoding
        text = self.data_to_string(data_element)
        return bytes_(text, encoding=encoding)
751506
def _get_data_bytes_or_stream_only(param_name, param_value):
    ''''''
    if param_value is None:
        return b''

    if isinstance(param_value, bytes) or hasattr(param_value, 'read'):
        return param_value

    raise TypeError(_ERROR_VALUE_SHOULD_BE_BYTES_OR_STREAM.format(param_name))
341979
def _setbytes_safe(self, data, length=None, offset=0):
        """"""
        data = bytearray(data)
        if length is None:
            # Use to the end of the data
            length = len(data)*8 - offset
            self._datastore = ByteStore(data, length, offset)
        else:
            if length + offset > len(data) * 8:
                msg = "Not enough data present. Need {0} bits, have {1}."
                raise CreationError(msg, length + offset, len(data) * 8)
            if length == 0:
                self._datastore = ByteStore(bytearray(0))
            else:
                self._datastore = ByteStore(data, length, offset)
324349
def wrap(data):
    
    try:
        cmdid = data[0]
    except IndexError:
        log.warning('data is empty')
        return None

    try:
        message_type = CMDID_MESSAGE[cmdid]
    except KeyError:
        log.error('unknown cmdid %s', cmdid)
        return None

    try:
        message = message_type(data)
    except ValueError:
        log.error('trying to decode invalid message')
        return None

    return message
127250
def check_data_is_empty(data):
    # type: (bytes) -> bool
    
    contentmd5 = compute_md5_for_data_asbase64(data)
    datalen = len(data)
    if datalen == _MAX_PAGE_SIZE_BYTES:
        if contentmd5 == _EMPTY_MAX_PAGE_SIZE_MD5:
            return True
    else:
        data_chk = b'\0' * datalen
        if compute_md5_for_data_asbase64(data_chk) == contentmd5:
            return True
    return False