Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-bytes not available") greetings_bytes = [g.encode('utf-8') for g in greetings] arrays = [ np.array([b'foo', b'bar', b'baz'] * 300, dtype=object), np.array(greetings_bytes * 100, dtype=object), np.array([b'foo', b'bar', b'baz'] * 300, dtype=object).reshape(90, 10), np.array(greetings_bytes * 1000, dtype=object).reshape(len(greetings_bytes), 100, 10, order='F'), ] def test_encode_decode(): for arr in arrays: codec = VLenBytes() <|code_end|> , predict the immediate next line with the help of imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenBytes from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and context (classes, functions, sometimes code) from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_encode_decode_array(arr, codec)
Given the following code snippet before the placeholder: <|code_start|> greetings_bytes = [g.encode('utf-8') for g in greetings] arrays = [ np.array([b'foo', b'bar', b'baz'] * 300, dtype=object), np.array(greetings_bytes * 100, dtype=object), np.array([b'foo', b'bar', b'baz'] * 300, dtype=object).reshape(90, 10), np.array(greetings_bytes * 1000, dtype=object).reshape(len(greetings_bytes), 100, 10, order='F'), ] def test_encode_decode(): for arr in arrays: codec = VLenBytes() check_encode_decode_array(arr, codec) def test_config(): codec = VLenBytes() check_config(codec) def test_repr(): check_repr("VLenBytes()") def test_backwards_compatibility(): <|code_end|> , predict the next line using imports from the current file: import unittest import numpy as np import pytest from numcodecs.vlen import VLenBytes from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and context including class names, function names, and sometimes code from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_backwards_compatibility(VLenBytes.codec_id, arrays, [VLenBytes()])
Given the code snippet: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-bytes not available") <|code_end|> , generate the next line using the imports in this file: import unittest import numpy as np import pytest from numcodecs.vlen import VLenBytes from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
greetings_bytes = [g.encode('utf-8') for g in greetings]
Predict the next line after this snippet: <|code_start|> with pytest.raises(TypeError): codec.decode(1234) # these should look like corrupt data with pytest.raises(ValueError): codec.decode(b'foo') with pytest.raises(ValueError): codec.decode(np.arange(2, 3, dtype='i4')) with pytest.raises(ValueError): codec.decode(np.arange(10, 20, dtype='i4')) with pytest.raises(TypeError): codec.decode('foo') # test out parameter enc = codec.encode(arrays[0]) with pytest.raises(TypeError): codec.decode(enc, out=b'foo') with pytest.raises(TypeError): codec.decode(enc, out='foo') with pytest.raises(TypeError): codec.decode(enc, out=123) with pytest.raises(ValueError): codec.decode(enc, out=np.zeros(10, dtype='i4')) def test_encode_none(): a = np.array([b'foo', None, b'bar'], dtype=object) codec = VLenBytes() enc = codec.encode(a) dec = codec.decode(enc) expect = np.array([b'foo', b'', b'bar'], dtype=object) <|code_end|> using the current file's imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenBytes from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and any relevant context from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
assert_array_items_equal(expect, dec)
Predict the next line for this snippet: <|code_start|> class Shuffle(Codec): """Codec providing shuffle Parameters ---------- elementsize : int Size in bytes of the array elements. Default = 4 """ codec_id = 'shuffle' def __init__(self, elementsize=4): self.elementsize = elementsize def _prepare_arrays(self, buf, out): <|code_end|> with the help of current file imports: import numpy as np from .compat import ensure_contiguous_ndarray from .abc import Codec from ._shuffle import _doShuffle, _doUnshuffle and context from other files: # Path: numcodecs/compat.py # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr # # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r , which may contain function names, class names, or code. Output only the next line.
buf = ensure_contiguous_ndarray(buf)
Predict the next line for this snippet: <|code_start|> >>> y3 = codec.encode(x) >>> y3 array([ 0, 111, 222, 333, 444, 556, 667, 778, 889, 1000], dtype=uint16) >>> z3 = codec.decode(y3) >>> z3 array([1000. , 1000.111, 1000.222, 1000.333, 1000.444, 1000.556, 1000.667, 1000.778, 1000.889, 1001. ]) See Also -------- numcodecs.quantize.Quantize """ codec_id = 'fixedscaleoffset' def __init__(self, offset, scale, dtype, astype=None): self.offset = offset self.scale = scale self.dtype = np.dtype(dtype) if astype is None: self.astype = self.dtype else: self.astype = np.dtype(astype) if self.dtype == object or self.astype == object: raise ValueError('object arrays are not supported') def encode(self, buf): # normalise input <|code_end|> with the help of current file imports: import numpy as np from .abc import Codec from .compat import ensure_ndarray, ndarray_copy and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst , which may contain function names, class names, or code. Output only the next line.
arr = ensure_ndarray(buf).view(self.dtype)
Given the code snippet: <|code_start|> # flatten to simplify implementation arr = arr.reshape(-1, order='A') # compute scale offset enc = (arr - self.offset) * self.scale # round to nearest integer enc = np.around(enc) # convert dtype enc = enc.astype(self.astype, copy=False) return enc def decode(self, buf, out=None): # interpret buffer as numpy array enc = ensure_ndarray(buf).view(self.astype) # flatten to simplify implementation enc = enc.reshape(-1, order='A') # decode scale offset dec = (enc / self.scale) + self.offset # convert dtype dec = dec.astype(self.dtype, copy=False) # handle output <|code_end|> , generate the next line using the imports in this file: import numpy as np from .abc import Codec from .compat import ensure_ndarray, ndarray_copy and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst . Output only the next line.
return ndarray_copy(dec, out)
Continue the code snippet: <|code_start|> np.linspace(1000, 1001, 1000, dtype="f8"), np.random.normal(loc=1000, scale=1, size=(100, 10)), np.random.normal(loc=1000, scale=1, size=(10, 10, 10)), np.random.normal(loc=1000, scale=1, size=(2, 5, 10, 10)), np.asfortranarray(np.random.normal(loc=1000, scale=1, size=(5, 10, 20))), np.random.randint(-(2 ** 31), -(2 ** 31) + 20, size=1000, dtype="i4").reshape( 100, 10 ), np.random.randint(-(2 ** 63), -(2 ** 63) + 20, size=1000, dtype="i8").reshape( 10, 10, 10 ), ] def test_encode_decode(): for arr in arrays: if arr.dtype == np.int32 or arr.dtype == np.int64: codec = [codecs[-1]] else: codec = codecs for code in codec: check_encode_decode_array(arr, code) def test_config(): for codec in codecs: check_config(codec) def test_repr(): <|code_end|> . Use current file imports: import pytest import numpy as np from numcodecs.zfpy import ZFPY, _zfpy from numcodecs.tests.common import ( check_encode_decode_array, check_config, check_repr, check_backwards_compatibility, check_err_decode_object_buffer, check_err_encode_object_buffer, ) and context (classes, functions, or code) from other files: # Path: numcodecs/tests/common.py # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def check_err_decode_object_buffer(compressor): # # cannot decode directly into object array, leads to segfaults # a = np.arange(10) # enc = compressor.encode(a) # out = np.empty(10, dtype=object) # with pytest.raises(TypeError): # compressor.decode(enc, out=out) # # def check_err_encode_object_buffer(compressor): # # compressors cannot encode object array # a = np.array(['foo', 'bar', 'baz'], dtype=object) # with pytest.raises(TypeError): # compressor.encode(a) . Output only the next line.
check_repr("ZFPY(mode=4, tolerance=0.001, rate=-1, precision=-1)")
Based on the snippet: <|code_start|> ), np.random.randint(-(2 ** 63), -(2 ** 63) + 20, size=1000, dtype="i8").reshape( 10, 10, 10 ), ] def test_encode_decode(): for arr in arrays: if arr.dtype == np.int32 or arr.dtype == np.int64: codec = [codecs[-1]] else: codec = codecs for code in codec: check_encode_decode_array(arr, code) def test_config(): for codec in codecs: check_config(codec) def test_repr(): check_repr("ZFPY(mode=4, tolerance=0.001, rate=-1, precision=-1)") def test_backwards_compatibility(): for code in codecs: if code.mode == _zfpy.mode_fixed_rate: codec = [code] <|code_end|> , predict the immediate next line with the help of imports: import pytest import numpy as np from numcodecs.zfpy import ZFPY, _zfpy from numcodecs.tests.common import ( check_encode_decode_array, check_config, check_repr, check_backwards_compatibility, check_err_decode_object_buffer, check_err_encode_object_buffer, ) and context (classes, functions, sometimes code) from other files: # Path: numcodecs/tests/common.py # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def check_err_decode_object_buffer(compressor): # # cannot decode directly into object array, leads to segfaults # a = np.arange(10) # enc = compressor.encode(a) # out = np.empty(10, dtype=object) # with pytest.raises(TypeError): # compressor.decode(enc, out=out) # # def check_err_encode_object_buffer(compressor): # # compressors cannot encode object array # a = np.array(['foo', 'bar', 'baz'], dtype=object) # with pytest.raises(TypeError): # compressor.encode(a) . Output only the next line.
check_backwards_compatibility(ZFPY.codec_id, arrays, codec)
Given snippet: <|code_start|> for arr in arrays: if arr.dtype == np.int32 or arr.dtype == np.int64: codec = [codecs[-1]] else: codec = codecs for code in codec: check_encode_decode_array(arr, code) def test_config(): for codec in codecs: check_config(codec) def test_repr(): check_repr("ZFPY(mode=4, tolerance=0.001, rate=-1, precision=-1)") def test_backwards_compatibility(): for code in codecs: if code.mode == _zfpy.mode_fixed_rate: codec = [code] check_backwards_compatibility(ZFPY.codec_id, arrays, codec) else: check_backwards_compatibility( ZFPY.codec_id, arrays[: len(arrays) - 2], codecs ) def test_err_decode_object_buffer(): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest import numpy as np from numcodecs.zfpy import ZFPY, _zfpy from numcodecs.tests.common import ( check_encode_decode_array, check_config, check_repr, check_backwards_compatibility, check_err_decode_object_buffer, check_err_encode_object_buffer, ) and context: # Path: numcodecs/tests/common.py # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def check_err_decode_object_buffer(compressor): # # cannot decode directly into object array, leads to segfaults # a = np.arange(10) # enc = compressor.encode(a) # out = np.empty(10, dtype=object) # with pytest.raises(TypeError): # compressor.decode(enc, out=out) # # def check_err_encode_object_buffer(compressor): # # compressors cannot encode object array # a = np.array(['foo', 'bar', 'baz'], dtype=object) # with pytest.raises(TypeError): # compressor.encode(a) which might include code, classes, or functions. Output only the next line.
check_err_decode_object_buffer(ZFPY())
Predict the next line after this snippet: <|code_start|> codec = codecs for code in codec: check_encode_decode_array(arr, code) def test_config(): for codec in codecs: check_config(codec) def test_repr(): check_repr("ZFPY(mode=4, tolerance=0.001, rate=-1, precision=-1)") def test_backwards_compatibility(): for code in codecs: if code.mode == _zfpy.mode_fixed_rate: codec = [code] check_backwards_compatibility(ZFPY.codec_id, arrays, codec) else: check_backwards_compatibility( ZFPY.codec_id, arrays[: len(arrays) - 2], codecs ) def test_err_decode_object_buffer(): check_err_decode_object_buffer(ZFPY()) def test_err_encode_object_buffer(): <|code_end|> using the current file's imports: import pytest import numpy as np from numcodecs.zfpy import ZFPY, _zfpy from numcodecs.tests.common import ( check_encode_decode_array, check_config, check_repr, check_backwards_compatibility, check_err_decode_object_buffer, check_err_encode_object_buffer, ) and any relevant context from other files: # Path: numcodecs/tests/common.py # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def check_err_decode_object_buffer(compressor): # # cannot decode directly into object array, leads to segfaults # a = np.arange(10) # enc = compressor.encode(a) # out = np.empty(10, dtype=object) # with pytest.raises(TypeError): # compressor.decode(enc, out=out) # # def check_err_encode_object_buffer(compressor): # # compressors cannot encode object array # a = np.array(['foo', 'bar', 'baz'], dtype=object) # with pytest.raises(TypeError): # compressor.encode(a) . Output only the next line.
check_err_encode_object_buffer(ZFPY())
Predict the next line for this snippet: <|code_start|> class Zlib(Codec): """Codec providing compression using zlib via the Python standard library. Parameters ---------- level : int Compression level. """ codec_id = 'zlib' def __init__(self, level=1): self.level = level def encode(self, buf): # normalise inputs <|code_end|> with the help of current file imports: import zlib as _zlib from .abc import Codec from .compat import ndarray_copy, ensure_contiguous_ndarray and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst # # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr , which may contain function names, class names, or code. Output only the next line.
buf = ensure_contiguous_ndarray(buf)
Given the code snippet: <|code_start|> def test_ensure_text(): bufs = [ b'adsdasdas', 'adsdasdas', np.asarray(memoryview(b'adsdasdas')), array.array('B', b'qwertyuiqwertyui') ] for buf in bufs: <|code_end|> , generate the next line using the imports in this file: import array import mmap import numpy as np import pytest from numcodecs.compat import ensure_text, ensure_bytes, ensure_contiguous_ndarray and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/compat.py # def ensure_text(s, encoding='utf-8'): # if not isinstance(s, str): # s = ensure_contiguous_ndarray(s) # s = codecs.decode(s, encoding) # return s # # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr . Output only the next line.
b = ensure_text(buf)
Given the code snippet: <|code_start|> def test_ensure_text(): bufs = [ b'adsdasdas', 'adsdasdas', np.asarray(memoryview(b'adsdasdas')), array.array('B', b'qwertyuiqwertyui') ] for buf in bufs: b = ensure_text(buf) assert isinstance(b, str) def test_ensure_bytes(): bufs = [ b'adsdasdas', bytes(20), np.arange(100), array.array('l', b'qwertyuiqwertyui') ] for buf in bufs: <|code_end|> , generate the next line using the imports in this file: import array import mmap import numpy as np import pytest from numcodecs.compat import ensure_text, ensure_bytes, ensure_contiguous_ndarray and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/compat.py # def ensure_text(s, encoding='utf-8'): # if not isinstance(s, str): # s = ensure_contiguous_ndarray(s) # s = codecs.decode(s, encoding) # return s # # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr . Output only the next line.
b = ensure_bytes(buf)
Continue the code snippet: <|code_start|> assert isinstance(b, str) def test_ensure_bytes(): bufs = [ b'adsdasdas', bytes(20), np.arange(100), array.array('l', b'qwertyuiqwertyui') ] for buf in bufs: b = ensure_bytes(buf) assert isinstance(b, bytes) def test_ensure_contiguous_ndarray_shares_memory(): typed_bufs = [ ('u', 1, b'adsdasdas'), ('u', 1, bytes(20)), ('i', 8, np.arange(100, dtype=np.int64)), ('f', 8, np.linspace(0, 1, 100, dtype=np.float64)), ('i', 4, array.array('i', b'qwertyuiqwertyui')), ('u', 4, array.array('I', b'qwertyuiqwertyui')), ('f', 4, array.array('f', b'qwertyuiqwertyui')), ('f', 8, array.array('d', b'qwertyuiqwertyui')), ('i', 1, array.array('b', b'qwertyuiqwertyui')), ('u', 1, array.array('B', b'qwertyuiqwertyui')), ('u', 1, mmap.mmap(-1, 10)) ] for expected_kind, expected_itemsize, buf in typed_bufs: <|code_end|> . Use current file imports: import array import mmap import numpy as np import pytest from numcodecs.compat import ensure_text, ensure_bytes, ensure_contiguous_ndarray and context (classes, functions, or code) from other files: # Path: numcodecs/compat.py # def ensure_text(s, encoding='utf-8'): # if not isinstance(s, str): # s = ensure_contiguous_ndarray(s) # s = codecs.decode(s, encoding) # return s # # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr . Output only the next line.
a = ensure_contiguous_ndarray(buf)
Continue the code snippet: <|code_start|> >>> codec = numcodecs.MsgPack() >>> codec.decode(codec.encode(x)) array(['foo', 'bar', 'baz'], dtype=object) See Also -------- numcodecs.pickles.Pickle, numcodecs.json.JSON, numcodecs.vlen.VLenUTF8 Notes ----- Requires `msgpack <https://pypi.org/project/msgpack/>`_ to be installed. """ codec_id = 'msgpack2' def __init__(self, use_single_float=False, use_bin_type=True, raw=False): self.use_single_float = use_single_float self.use_bin_type = use_bin_type self.raw = raw def encode(self, buf): buf = np.asarray(buf) items = buf.tolist() items.append(buf.dtype.str) items.append(buf.shape) return msgpack.packb(items, use_bin_type=self.use_bin_type, use_single_float=self.use_single_float) def decode(self, buf, out=None): <|code_end|> . Use current file imports: import numpy as np import msgpack from .abc import Codec from .compat import ensure_contiguous_ndarray and context (classes, functions, or code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr . Output only the next line.
buf = ensure_contiguous_ndarray(buf)
Based on the snippet: <|code_start|> codec_id = 'json2' def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=True, indent=None, separators=None, strict=True): self._text_encoding = encoding if separators is None: # ensure separators are explicitly specified, and consistent behaviour across # Python versions, and most compact representation if indent is None if indent is None: separators = ',', ':' else: separators = ', ', ': ' separators = tuple(separators) self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, sort_keys=sort_keys) self._encoder = _json.JSONEncoder(**self._encoder_config) self._decoder_config = dict(strict=strict) self._decoder = _json.JSONDecoder(**self._decoder_config) def encode(self, buf): buf = np.asarray(buf) items = buf.tolist() items.append(buf.dtype.str) items.append(buf.shape) return self._encoder.encode(items).encode(self._text_encoding) def decode(self, buf, out=None): <|code_end|> , predict the immediate next line with the help of imports: import json as _json import textwrap import numpy as np from .abc import Codec from .compat import ensure_text and context (classes, functions, sometimes code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_text(s, encoding='utf-8'): # if not isinstance(s, str): # s = ensure_contiguous_ndarray(s) # s = codecs.decode(s, encoding) # return s . Output only the next line.
items = self._decoder.decode(ensure_text(buf, self._text_encoding))
Given snippet: <|code_start|> # be compared to the original array. # encoding should support any object exporting the buffer protocol # test encoding of numpy array enc = codec.encode(arr) dec = codec.decode(enc) compare_arrays(arr, dec, precision=precision) # test encoding of bytes buf = arr.tobytes(order='A') enc = codec.encode(buf) dec = codec.decode(enc) compare_arrays(arr, dec, precision=precision) # test encoding of bytearray buf = bytearray(arr.tobytes(order='A')) enc = codec.encode(buf) dec = codec.decode(enc) compare_arrays(arr, dec, precision=precision) # test encoding of array.array buf = array.array('b', arr.tobytes(order='A')) enc = codec.encode(buf) dec = codec.decode(enc) compare_arrays(arr, dec, precision=precision) # decoding should support any object exporting the buffer protocol, # setup <|code_end|> , continue by predicting the next line. Consider current file imports: import array import json as _json import os import numpy as np import pytest from glob import glob from numpy.testing import assert_array_almost_equal, assert_array_equal from numcodecs.compat import ensure_bytes, ensure_ndarray from numcodecs.registry import get_codec from numcodecs import * # noqa and context: # Path: numcodecs/compat.py # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # Path: numcodecs/registry.py # def get_codec(config): # """Obtain a codec for the given configuration. # # Parameters # ---------- # config : dict-like # Configuration object. # # Returns # ------- # codec : Codec # # Examples # -------- # # >>> import numcodecs as codecs # >>> codec = codecs.get_codec(dict(id='zlib', level=1)) # >>> codec # Zlib(level=1) # # """ # config = dict(config) # codec_id = config.pop('id', None) # cls = codec_registry.get(codec_id) # if cls is None: # if codec_id in entries: # logger.debug("Auto loading codec '%s' from entrypoint", codec_id) # cls = entries[codec_id].load() # register_codec(cls, codec_id=codec_id) # if cls: # return cls.from_config(config) # raise ValueError('codec not available: %r' % codec_id) which might include code, classes, or functions. Output only the next line.
enc_bytes = ensure_bytes(enc)
Predict the next line for this snippet: <|code_start|> # star import needed for repr tests so eval finds names greetings = ['¡Hola mundo!', 'Hej Världen!', 'Servus Woid!', 'Hei maailma!', 'Xin chào thế giới', 'Njatjeta Botë!', 'Γεια σου κόσμε!', 'こんにちは世界', '世界,你好!', 'Helló, világ!', 'Zdravo svete!', 'เฮลโลเวิลด์'] def compare_arrays(arr, res, precision=None): # ensure numpy array with matching dtype <|code_end|> with the help of current file imports: import array import json as _json import os import numpy as np import pytest from glob import glob from numpy.testing import assert_array_almost_equal, assert_array_equal from numcodecs.compat import ensure_bytes, ensure_ndarray from numcodecs.registry import get_codec from numcodecs import * # noqa and context from other files: # Path: numcodecs/compat.py # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # Path: numcodecs/registry.py # def get_codec(config): # """Obtain a codec for the given configuration. # # Parameters # ---------- # config : dict-like # Configuration object. # # Returns # ------- # codec : Codec # # Examples # -------- # # >>> import numcodecs as codecs # >>> codec = codecs.get_codec(dict(id='zlib', level=1)) # >>> codec # Zlib(level=1) # # """ # config = dict(config) # codec_id = config.pop('id', None) # cls = codec_registry.get(codec_id) # if cls is None: # if codec_id in entries: # logger.debug("Auto loading codec '%s' from entrypoint", codec_id) # cls = entries[codec_id].load() # register_codec(cls, codec_id=codec_id) # if cls: # return cls.from_config(config) # raise ValueError('codec not available: %r' % codec_id) , which may contain function names, class names, or code. Output only the next line.
res = ensure_ndarray(res).view(arr.dtype)
Here is a snippet: <|code_start|> arr = arr.ravel().tolist() res = res.ravel().tolist() for a, r in zip(arr, res): if isinstance(a, np.ndarray): assert_array_equal(a, r) elif a != a: assert r != r else: assert a == r def check_encode_decode_array(arr, codec): enc = codec.encode(arr) dec = codec.decode(enc) assert_array_items_equal(arr, dec) out = np.empty_like(arr) codec.decode(enc, out=out) assert_array_items_equal(arr, out) enc = codec.encode(arr) dec = codec.decode(ensure_ndarray(enc)) assert_array_items_equal(arr, dec) def check_config(codec): config = codec.get_config() # round-trip through JSON to check serialization config = _json.loads(_json.dumps(config)) <|code_end|> . Write the next line using the current file imports: import array import json as _json import os import numpy as np import pytest from glob import glob from numpy.testing import assert_array_almost_equal, assert_array_equal from numcodecs.compat import ensure_bytes, ensure_ndarray from numcodecs.registry import get_codec from numcodecs import * # noqa and context from other files: # Path: numcodecs/compat.py # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # Path: numcodecs/registry.py # def get_codec(config): # """Obtain a codec for the given configuration. # # Parameters # ---------- # config : dict-like # Configuration object. # # Returns # ------- # codec : Codec # # Examples # -------- # # >>> import numcodecs as codecs # >>> codec = codecs.get_codec(dict(id='zlib', level=1)) # >>> codec # Zlib(level=1) # # """ # config = dict(config) # codec_id = config.pop('id', None) # cls = codec_registry.get(codec_id) # if cls is None: # if codec_id in entries: # logger.debug("Auto loading codec '%s' from entrypoint", codec_id) # cls = entries[codec_id].load() # register_codec(cls, codec_id=codec_id) # if cls: # return cls.from_config(config) # raise ValueError('codec not available: %r' % codec_id) , which may include functions, classes, or code. Output only the next line.
assert codec == get_codec(config)
Given the code snippet: <|code_start|> codecs = [Pickle(protocol=i) for i in range(5)] # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode_array(arr, codec) def test_config(): codec = Pickle(protocol=-1) <|code_end|> , generate the next line using the imports in this file: import itertools import sys import numpy as np import pytest from numcodecs.pickles import Pickle from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/pickles.py # class Pickle(Codec): # """Codec to encode data as as pickled bytes. Useful for encoding an array of Python string # objects. # # Parameters # ---------- # protocol : int, defaults to pickle.HIGHEST_PROTOCOL # The protocol used to pickle data. # # Examples # -------- # >>> import numcodecs as codecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> f = codecs.Pickle() # >>> f.decode(f.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'pickle' # # def __init__(self, protocol=pickle.HIGHEST_PROTOCOL): # self.protocol = protocol # # def encode(self, buf): # return pickle.dumps(buf, protocol=self.protocol) # # def decode(self, buf, out=None): # buf = ensure_contiguous_ndarray(buf) # dec = pickle.loads(buf) # # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # return dict(id=self.codec_id, # protocol=self.protocol) # # def __repr__(self): # return 'Pickle(protocol=%s)' % self.protocol # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_config(codec)
Given the code snippet: <|code_start|> # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode_array(arr, codec) def test_config(): codec = Pickle(protocol=-1) check_config(codec) for codec in codecs: check_config(codec) def test_repr(): <|code_end|> , generate the next line using the imports in this file: import itertools import sys import numpy as np import pytest from numcodecs.pickles import Pickle from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/pickles.py # class Pickle(Codec): # """Codec to encode data as as pickled bytes. Useful for encoding an array of Python string # objects. # # Parameters # ---------- # protocol : int, defaults to pickle.HIGHEST_PROTOCOL # The protocol used to pickle data. # # Examples # -------- # >>> import numcodecs as codecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> f = codecs.Pickle() # >>> f.decode(f.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'pickle' # # def __init__(self, protocol=pickle.HIGHEST_PROTOCOL): # self.protocol = protocol # # def encode(self, buf): # return pickle.dumps(buf, protocol=self.protocol) # # def decode(self, buf, out=None): # buf = ensure_contiguous_ndarray(buf) # dec = pickle.loads(buf) # # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # return dict(id=self.codec_id, # protocol=self.protocol) # # def __repr__(self): # return 'Pickle(protocol=%s)' % self.protocol # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_repr("Pickle(protocol=-1)")
Given the code snippet: <|code_start|> codecs = [Pickle(protocol=i) for i in range(5)] # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): <|code_end|> , generate the next line using the imports in this file: import itertools import sys import numpy as np import pytest from numcodecs.pickles import Pickle from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/pickles.py # class Pickle(Codec): # """Codec to encode data as as pickled bytes. Useful for encoding an array of Python string # objects. # # Parameters # ---------- # protocol : int, defaults to pickle.HIGHEST_PROTOCOL # The protocol used to pickle data. # # Examples # -------- # >>> import numcodecs as codecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> f = codecs.Pickle() # >>> f.decode(f.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'pickle' # # def __init__(self, protocol=pickle.HIGHEST_PROTOCOL): # self.protocol = protocol # # def encode(self, buf): # return pickle.dumps(buf, protocol=self.protocol) # # def decode(self, buf, out=None): # buf = ensure_contiguous_ndarray(buf) # dec = pickle.loads(buf) # # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # return dict(id=self.codec_id, # protocol=self.protocol) # # def __repr__(self): # return 'Pickle(protocol=%s)' % self.protocol # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_encode_decode_array(arr, codec)
Given the following code snippet before the placeholder: <|code_start|> def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode_array(arr, codec) def test_config(): codec = Pickle(protocol=-1) check_config(codec) for codec in codecs: check_config(codec) def test_repr(): check_repr("Pickle(protocol=-1)") # Details on xfail # https://stackoverflow.com/questions/58194852/modulenotfounderror-no-module-named-numpy-core-multiarray-r @pytest.mark.skipif( sys.byteorder != "little", reason="Pickle does not restore byte orders" ) @pytest.mark.xfail( sys.platform == "win32", reason=( "Pickle fails to read w/ Windows carriage return " "( https://github.com/zarr-developers/numcodecs/issues/271 )" ) ) def test_backwards_compatibility(): <|code_end|> , predict the next line using imports from the current file: import itertools import sys import numpy as np import pytest from numcodecs.pickles import Pickle from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context including class names, function names, and sometimes code from other files: # Path: numcodecs/pickles.py # class Pickle(Codec): # """Codec to encode data as as pickled bytes. Useful for encoding an array of Python string # objects. # # Parameters # ---------- # protocol : int, defaults to pickle.HIGHEST_PROTOCOL # The protocol used to pickle data. # # Examples # -------- # >>> import numcodecs as codecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> f = codecs.Pickle() # >>> f.decode(f.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'pickle' # # def __init__(self, protocol=pickle.HIGHEST_PROTOCOL): # self.protocol = protocol # # def encode(self, buf): # return pickle.dumps(buf, protocol=self.protocol) # # def decode(self, buf, out=None): # buf = ensure_contiguous_ndarray(buf) # dec = pickle.loads(buf) # # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # return dict(id=self.codec_id, # protocol=self.protocol) # # def __repr__(self): # return 'Pickle(protocol=%s)' % self.protocol # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_backwards_compatibility(Pickle.codec_id, arrays, codecs)
Given snippet: <|code_start|> codecs = [Pickle(protocol=i) for i in range(5)] # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), <|code_end|> , continue by predicting the next line. Consider current file imports: import itertools import sys import numpy as np import pytest from numcodecs.pickles import Pickle from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context: # Path: numcodecs/pickles.py # class Pickle(Codec): # """Codec to encode data as as pickled bytes. Useful for encoding an array of Python string # objects. # # Parameters # ---------- # protocol : int, defaults to pickle.HIGHEST_PROTOCOL # The protocol used to pickle data. # # Examples # -------- # >>> import numcodecs as codecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> f = codecs.Pickle() # >>> f.decode(f.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'pickle' # # def __init__(self, protocol=pickle.HIGHEST_PROTOCOL): # self.protocol = protocol # # def encode(self, buf): # return pickle.dumps(buf, protocol=self.protocol) # # def decode(self, buf, out=None): # buf = ensure_contiguous_ndarray(buf) # dec = pickle.loads(buf) # # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # return dict(id=self.codec_id, # protocol=self.protocol) # # def __repr__(self): # return 'Pickle(protocol=%s)' % self.protocol # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): which might include code, classes, or functions. Output only the next line.
np.array(greetings * 100),
Continue the code snippet: <|code_start|> arr = ensure_ndarray(buf).view(self.dtype) # flatten to simplify implementation arr = arr.reshape(-1, order='A') # setup output array enc = np.zeros_like(arr, dtype=self.astype) # apply encoding, reserving 0 for values not specified in labels for i, l in enumerate(self.labels): enc[arr == l] = i + 1 return enc def decode(self, buf, out=None): # normalise input enc = ensure_ndarray(buf).view(self.astype) # flatten to simplify implementation enc = enc.reshape(-1, order='A') # setup output dec = np.full_like(enc, fill_value='', dtype=self.dtype) # apply decoding for i, l in enumerate(self.labels): dec[enc == (i + 1)] = l # handle output <|code_end|> . Use current file imports: from .abc import Codec from .compat import ensure_ndarray, ndarray_copy, ensure_text import numpy as np and context (classes, functions, or code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst # # def ensure_text(s, encoding='utf-8'): # if not isinstance(s, str): # s = ensure_contiguous_ndarray(s) # s = codecs.decode(s, encoding) # return s . Output only the next line.
dec = ndarray_copy(dec, out)
Based on the snippet: <|code_start|>codecs = [ JSON(), JSON(indent=True), ] # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode_array(arr, codec) def test_config(): for codec in codecs: <|code_end|> , predict the immediate next line with the help of imports: import itertools import numpy as np from numcodecs.json import JSON from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (classes, functions, sometimes code) from other files: # Path: numcodecs/json.py # class JSON(Codec): # """Codec to encode data as JSON. Useful for encoding an array of Python objects. # # .. versionchanged:: 0.6 # The encoding format has been changed to include the array shape in the encoded # data, which ensures that all object arrays can be correctly encoded and decoded. # # Examples # -------- # >>> import numcodecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> codec = numcodecs.JSON() # >>> codec.decode(codec.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.pickles.Pickle, numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'json2' # # def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True, # check_circular=True, allow_nan=True, sort_keys=True, indent=None, # separators=None, strict=True): # self._text_encoding = encoding # if separators is None: # # ensure separators are explicitly specified, and consistent behaviour across # # Python versions, and most compact representation if indent is None # if indent is None: # separators = ',', ':' # else: # separators = ', ', ': ' # separators = tuple(separators) # self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii, # check_circular=check_circular, allow_nan=allow_nan, # indent=indent, separators=separators, # sort_keys=sort_keys) # self._encoder = _json.JSONEncoder(**self._encoder_config) # self._decoder_config = dict(strict=strict) # self._decoder = _json.JSONDecoder(**self._decoder_config) # # def encode(self, buf): # buf = np.asarray(buf) # items = buf.tolist() # items.append(buf.dtype.str) # items.append(buf.shape) # return self._encoder.encode(items).encode(self._text_encoding) # # def decode(self, buf, out=None): # items = self._decoder.decode(ensure_text(buf, self._text_encoding)) # dec = np.empty(items[-1], dtype=items[-2]) # dec[:] = items[:-2] # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # config = dict(id=self.codec_id, encoding=self._text_encoding) # config.update(self._encoder_config) # config.update(self._decoder_config) # return config # # def __repr__(self): # params = ['encoding=%r' % self._text_encoding] # for k, v in sorted(self._encoder_config.items()): # params.append('{}={!r}'.format(k, v)) # for k, v in sorted(self._decoder_config.items()): # params.append('{}={!r}'.format(k, v)) # classname = type(self).__name__ # r = '{}({})'.format(classname, ', '.join(params)) # r = textwrap.fill(r, width=80, break_long_words=False, subsequent_indent=' ') # return r # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_config(codec)
Here is a snippet: <|code_start|># ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode_array(arr, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr(): r = ( "JSON(encoding='utf-8', allow_nan=True, check_circular=True, ensure_ascii=True,\n" " indent=None, separators=(',', ':'), skipkeys=False, sort_keys=True,\n" " strict=True)" ) <|code_end|> . Write the next line using the current file imports: import itertools import numpy as np from numcodecs.json import JSON from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context from other files: # Path: numcodecs/json.py # class JSON(Codec): # """Codec to encode data as JSON. Useful for encoding an array of Python objects. # # .. versionchanged:: 0.6 # The encoding format has been changed to include the array shape in the encoded # data, which ensures that all object arrays can be correctly encoded and decoded. # # Examples # -------- # >>> import numcodecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> codec = numcodecs.JSON() # >>> codec.decode(codec.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.pickles.Pickle, numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'json2' # # def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True, # check_circular=True, allow_nan=True, sort_keys=True, indent=None, # separators=None, strict=True): # self._text_encoding = encoding # if separators is None: # # ensure separators are explicitly specified, and consistent behaviour across # # Python versions, and most compact representation if indent is None # if indent is None: # separators = ',', ':' # else: # separators = ', ', ': ' # separators = tuple(separators) # self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii, # check_circular=check_circular, allow_nan=allow_nan, # indent=indent, separators=separators, # sort_keys=sort_keys) # self._encoder = _json.JSONEncoder(**self._encoder_config) # self._decoder_config = dict(strict=strict) # self._decoder = _json.JSONDecoder(**self._decoder_config) # # def encode(self, buf): # buf = np.asarray(buf) # items = buf.tolist() # items.append(buf.dtype.str) # items.append(buf.shape) # return self._encoder.encode(items).encode(self._text_encoding) # # def decode(self, buf, out=None): # items = self._decoder.decode(ensure_text(buf, self._text_encoding)) # dec = np.empty(items[-1], dtype=items[-2]) # dec[:] = items[:-2] # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # config = dict(id=self.codec_id, encoding=self._text_encoding) # config.update(self._encoder_config) # config.update(self._decoder_config) # return config # # def __repr__(self): # params = ['encoding=%r' % self._text_encoding] # for k, v in sorted(self._encoder_config.items()): # params.append('{}={!r}'.format(k, v)) # for k, v in sorted(self._decoder_config.items()): # params.append('{}={!r}'.format(k, v)) # classname = type(self).__name__ # r = '{}({})'.format(classname, ', '.join(params)) # r = textwrap.fill(r, width=80, break_long_words=False, subsequent_indent=' ') # return r # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): , which may include functions, classes, or code. Output only the next line.
check_repr(r)
Using the snippet: <|code_start|> codecs = [ JSON(), JSON(indent=True), ] # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): <|code_end|> , determine the next line of code. You have imports: import itertools import numpy as np from numcodecs.json import JSON from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (class names, function names, or code) available: # Path: numcodecs/json.py # class JSON(Codec): # """Codec to encode data as JSON. Useful for encoding an array of Python objects. # # .. versionchanged:: 0.6 # The encoding format has been changed to include the array shape in the encoded # data, which ensures that all object arrays can be correctly encoded and decoded. # # Examples # -------- # >>> import numcodecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> codec = numcodecs.JSON() # >>> codec.decode(codec.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.pickles.Pickle, numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'json2' # # def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True, # check_circular=True, allow_nan=True, sort_keys=True, indent=None, # separators=None, strict=True): # self._text_encoding = encoding # if separators is None: # # ensure separators are explicitly specified, and consistent behaviour across # # Python versions, and most compact representation if indent is None # if indent is None: # separators = ',', ':' # else: # separators = ', ', ': ' # separators = tuple(separators) # self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii, # check_circular=check_circular, allow_nan=allow_nan, # indent=indent, separators=separators, # sort_keys=sort_keys) # self._encoder = _json.JSONEncoder(**self._encoder_config) # self._decoder_config = dict(strict=strict) # self._decoder = _json.JSONDecoder(**self._decoder_config) # # def encode(self, buf): # buf = np.asarray(buf) # items = buf.tolist() # items.append(buf.dtype.str) # items.append(buf.shape) # return self._encoder.encode(items).encode(self._text_encoding) # # def decode(self, buf, out=None): # items = self._decoder.decode(ensure_text(buf, self._text_encoding)) # dec = np.empty(items[-1], dtype=items[-2]) # dec[:] = items[:-2] # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # config = dict(id=self.codec_id, encoding=self._text_encoding) # config.update(self._encoder_config) # config.update(self._decoder_config) # return config # # def __repr__(self): # params = ['encoding=%r' % self._text_encoding] # for k, v in sorted(self._encoder_config.items()): # params.append('{}={!r}'.format(k, v)) # for k, v in sorted(self._decoder_config.items()): # params.append('{}={!r}'.format(k, v)) # classname = type(self).__name__ # r = '{}({})'.format(classname, ', '.join(params)) # r = textwrap.fill(r, width=80, break_long_words=False, subsequent_indent=' ') # return r # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_encode_decode_array(arr, codec)
Continue the code snippet: <|code_start|> np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode_array(arr, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr(): r = ( "JSON(encoding='utf-8', allow_nan=True, check_circular=True, ensure_ascii=True,\n" " indent=None, separators=(',', ':'), skipkeys=False, sort_keys=True,\n" " strict=True)" ) check_repr(r) def test_backwards_compatibility(): <|code_end|> . Use current file imports: import itertools import numpy as np from numcodecs.json import JSON from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (classes, functions, or code) from other files: # Path: numcodecs/json.py # class JSON(Codec): # """Codec to encode data as JSON. Useful for encoding an array of Python objects. # # .. versionchanged:: 0.6 # The encoding format has been changed to include the array shape in the encoded # data, which ensures that all object arrays can be correctly encoded and decoded. # # Examples # -------- # >>> import numcodecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> codec = numcodecs.JSON() # >>> codec.decode(codec.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.pickles.Pickle, numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'json2' # # def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True, # check_circular=True, allow_nan=True, sort_keys=True, indent=None, # separators=None, strict=True): # self._text_encoding = encoding # if separators is None: # # ensure separators are explicitly specified, and consistent behaviour across # # Python versions, and most compact representation if indent is None # if indent is None: # separators = ',', ':' # else: # separators = ', ', ': ' # separators = tuple(separators) # self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii, # check_circular=check_circular, allow_nan=allow_nan, # indent=indent, separators=separators, # sort_keys=sort_keys) # self._encoder = _json.JSONEncoder(**self._encoder_config) # self._decoder_config = dict(strict=strict) # self._decoder = _json.JSONDecoder(**self._decoder_config) # # def encode(self, buf): # buf = np.asarray(buf) # items = buf.tolist() # items.append(buf.dtype.str) # items.append(buf.shape) # return self._encoder.encode(items).encode(self._text_encoding) # # def decode(self, buf, out=None): # items = self._decoder.decode(ensure_text(buf, self._text_encoding)) # dec = np.empty(items[-1], dtype=items[-2]) # dec[:] = items[:-2] # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # config = dict(id=self.codec_id, encoding=self._text_encoding) # config.update(self._encoder_config) # config.update(self._decoder_config) # return config # # def __repr__(self): # params = ['encoding=%r' % self._text_encoding] # for k, v in sorted(self._encoder_config.items()): # params.append('{}={!r}'.format(k, v)) # for k, v in sorted(self._decoder_config.items()): # params.append('{}={!r}'.format(k, v)) # classname = type(self).__name__ # r = '{}({})'.format(classname, ', '.join(params)) # r = textwrap.fill(r, width=80, break_long_words=False, subsequent_indent=' ') # return r # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_backwards_compatibility(JSON.codec_id, arrays, codecs)
Based on the snippet: <|code_start|> codecs = [ JSON(), JSON(indent=True), ] # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), <|code_end|> , predict the immediate next line with the help of imports: import itertools import numpy as np from numcodecs.json import JSON from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (classes, functions, sometimes code) from other files: # Path: numcodecs/json.py # class JSON(Codec): # """Codec to encode data as JSON. Useful for encoding an array of Python objects. # # .. versionchanged:: 0.6 # The encoding format has been changed to include the array shape in the encoded # data, which ensures that all object arrays can be correctly encoded and decoded. # # Examples # -------- # >>> import numcodecs # >>> import numpy as np # >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') # >>> codec = numcodecs.JSON() # >>> codec.decode(codec.encode(x)) # array(['foo', 'bar', 'baz'], dtype=object) # # See Also # -------- # numcodecs.pickles.Pickle, numcodecs.msgpacks.MsgPack # # """ # # codec_id = 'json2' # # def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True, # check_circular=True, allow_nan=True, sort_keys=True, indent=None, # separators=None, strict=True): # self._text_encoding = encoding # if separators is None: # # ensure separators are explicitly specified, and consistent behaviour across # # Python versions, and most compact representation if indent is None # if indent is None: # separators = ',', ':' # else: # separators = ', ', ': ' # separators = tuple(separators) # self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii, # check_circular=check_circular, allow_nan=allow_nan, # indent=indent, separators=separators, # sort_keys=sort_keys) # self._encoder = _json.JSONEncoder(**self._encoder_config) # self._decoder_config = dict(strict=strict) # self._decoder = _json.JSONDecoder(**self._decoder_config) # # def encode(self, buf): # buf = np.asarray(buf) # items = buf.tolist() # items.append(buf.dtype.str) # items.append(buf.shape) # return self._encoder.encode(items).encode(self._text_encoding) # # def decode(self, buf, out=None): # items = self._decoder.decode(ensure_text(buf, self._text_encoding)) # dec = np.empty(items[-1], dtype=items[-2]) # dec[:] = items[:-2] # if out is not None: # np.copyto(out, dec) # return out # else: # return dec # # def get_config(self): # config = dict(id=self.codec_id, encoding=self._text_encoding) # config.update(self._encoder_config) # config.update(self._decoder_config) # return config # # def __repr__(self): # params = ['encoding=%r' % self._text_encoding] # for k, v in sorted(self._encoder_config.items()): # params.append('{}={!r}'.format(k, v)) # for k, v in sorted(self._decoder_config.items()): # params.append('{}={!r}'.format(k, v)) # classname = type(self).__name__ # r = '{}({})'.format(classname, ', '.join(params)) # r = textwrap.fill(r, width=80, break_long_words=False, subsequent_indent=' ') # return r # # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
np.array(greetings * 100),
Predict the next line for this snippet: <|code_start|> raise unittest.SkipTest("msgpack not available") # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([b'foo', b'bar', b'baz'] * 300, dtype=object), np.array([g.encode('utf-8') for g in greetings] * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr in arrays: check_encode_decode_array(arr, MsgPack()) def test_config(): <|code_end|> with the help of current file imports: import unittest import numpy as np from numcodecs.msgpacks import MsgPack from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): , which may contain function names, class names, or code. Output only the next line.
check_config(MsgPack())
Given the following code snippet before the placeholder: <|code_start|> # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([b'foo', b'bar', b'baz'] * 300, dtype=object), np.array([g.encode('utf-8') for g in greetings] * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr in arrays: check_encode_decode_array(arr, MsgPack()) def test_config(): check_config(MsgPack()) def test_repr(): <|code_end|> , predict the next line using imports from the current file: import unittest import numpy as np from numcodecs.msgpacks import MsgPack from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context including class names, function names, and sometimes code from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_repr("MsgPack(raw=False, use_bin_type=True, use_single_float=False)")
Continue the code snippet: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("msgpack not available") # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([b'foo', b'bar', b'baz'] * 300, dtype=object), np.array([g.encode('utf-8') for g in greetings] * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr in arrays: <|code_end|> . Use current file imports: import unittest import numpy as np from numcodecs.msgpacks import MsgPack from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (classes, functions, or code) from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_encode_decode_array(arr, MsgPack())
Using the snippet: <|code_start|> np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), np.array(greetings * 100), np.array(greetings * 100, dtype=object), np.array([b'foo', b'bar', b'baz'] * 300, dtype=object), np.array([g.encode('utf-8') for g in greetings] * 100, dtype=object), np.array([[0, 1], [2, 3]], dtype=object), ] def test_encode_decode(): for arr in arrays: check_encode_decode_array(arr, MsgPack()) def test_config(): check_config(MsgPack()) def test_repr(): check_repr("MsgPack(raw=False, use_bin_type=True, use_single_float=False)") check_repr("MsgPack(raw=True, use_bin_type=False, use_single_float=True)") def test_backwards_compatibility(): codec = MsgPack() <|code_end|> , determine the next line of code. You have imports: import unittest import numpy as np from numcodecs.msgpacks import MsgPack from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (class names, function names, or code) available: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_backwards_compatibility(codec.codec_id, arrays, [codec])
Given the code snippet: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("msgpack not available") # object array with strings # object array with mix strings / nans # object array with mix of string, int, float # ... arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array([['foo', 'bar', np.nan]] * 300, dtype=object), np.array(['foo', 1.0, 2] * 300, dtype=object), np.arange(1000, dtype='i4'), np.array(['foo', 'bar', 'baz'] * 300), np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object), <|code_end|> , generate the next line using the imports in this file: import unittest import numpy as np from numcodecs.msgpacks import MsgPack from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings) and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
np.array(greetings * 100),
Predict the next line for this snippet: <|code_start|> Compression level. """ codec_id = 'gzip' def __init__(self, level=1): self.level = level def encode(self, buf): # normalise inputs buf = ensure_contiguous_ndarray(buf) # do compression compressed = io.BytesIO() with _gzip.GzipFile(fileobj=compressed, mode='wb', compresslevel=self.level) as compressor: compressor.write(buf) compressed = compressed.getvalue() return compressed # noinspection PyMethodMayBeStatic def decode(self, buf, out=None): # normalise inputs # BytesIO only copies if the data is not of `bytes` type. # This allows `bytes` objects to pass through without copying. <|code_end|> with the help of current file imports: import gzip as _gzip import io from .abc import Codec from .compat import ensure_bytes, ensure_contiguous_ndarray and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr , which may contain function names, class names, or code. Output only the next line.
buf = io.BytesIO(ensure_bytes(buf))
Given the code snippet: <|code_start|> class GZip(Codec): """Codec providing gzip compression using zlib via the Python standard library. Parameters ---------- level : int Compression level. """ codec_id = 'gzip' def __init__(self, level=1): self.level = level def encode(self, buf): # normalise inputs <|code_end|> , generate the next line using the imports in this file: import gzip as _gzip import io from .abc import Codec from .compat import ensure_bytes, ensure_contiguous_ndarray and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_bytes(buf): # """Obtain a bytes object from memory exposed by `buf`.""" # # if not isinstance(buf, bytes): # # # go via numpy, for convenience # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, # # actual memory holding item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # create bytes # buf = arr.tobytes(order='A') # # return buf # # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr . Output only the next line.
buf = ensure_contiguous_ndarray(buf)
Predict the next line for this snippet: <|code_start|> >>> z array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118], dtype=int8) """ codec_id = 'astype' def __init__(self, encode_dtype, decode_dtype): self.encode_dtype = np.dtype(encode_dtype) self.decode_dtype = np.dtype(decode_dtype) def encode(self, buf): # normalise input arr = ensure_ndarray(buf).view(self.decode_dtype) # convert and copy enc = arr.astype(self.encode_dtype) return enc def decode(self, buf, out=None): # normalise input enc = ensure_ndarray(buf).view(self.encode_dtype) # convert and copy dec = enc.astype(self.decode_dtype) # handle output <|code_end|> with the help of current file imports: import numpy as np from .abc import Codec from .compat import ndarray_copy, ensure_ndarray and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst # # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr , which may contain function names, class names, or code. Output only the next line.
out = ndarray_copy(dec, out)
Given the following code snippet before the placeholder: <|code_start|> class Checksum32(Codec): checksum = None def encode(self, buf): <|code_end|> , predict the next line using imports from the current file: import zlib import numpy as np from .abc import Codec from .compat import ensure_contiguous_ndarray, ndarray_copy and context including class names, function names, and sometimes code from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst . Output only the next line.
arr = ensure_contiguous_ndarray(buf).view('u1')
Here is a snippet: <|code_start|> class Checksum32(Codec): checksum = None def encode(self, buf): arr = ensure_contiguous_ndarray(buf).view('u1') checksum = self.checksum(arr) & 0xffffffff enc = np.empty(arr.nbytes + 4, dtype='u1') enc[:4].view('<u4')[0] = checksum <|code_end|> . Write the next line using the current file imports: import zlib import numpy as np from .abc import Codec from .compat import ensure_contiguous_ndarray, ndarray_copy and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst , which may include functions, classes, or code. Output only the next line.
ndarray_copy(arr, enc[4:])
Given the code snippet: <|code_start|> Examples -------- >>> import numcodecs >>> import numpy as np >>> x = np.arange(100, 120, 2, dtype='i8') >>> codec = numcodecs.Delta(dtype='i8', astype='i1') >>> y = codec.encode(x) >>> y array([100, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int8) >>> z = codec.decode(y) >>> z array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118]) """ codec_id = 'delta' def __init__(self, dtype, astype=None): self.dtype = np.dtype(dtype) if astype is None: self.astype = self.dtype else: self.astype = np.dtype(astype) if self.dtype == object or self.astype == object: raise ValueError('object arrays are not supported') def encode(self, buf): # normalise input <|code_end|> , generate the next line using the imports in this file: import numpy as np from .abc import Codec from .compat import ensure_ndarray, ndarray_copy and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst . Output only the next line.
arr = ensure_ndarray(buf).view(self.dtype)
Given the code snippet: <|code_start|> # flatten to simplify implementation arr = arr.reshape(-1, order='A') # setup encoded output enc = np.empty_like(arr, dtype=self.astype) # set first element enc[0] = arr[0] # compute differences enc[1:] = np.diff(arr) return enc def decode(self, buf, out=None): # normalise input enc = ensure_ndarray(buf).view(self.astype) # flatten to simplify implementation enc = enc.reshape(-1, order='A') # setup decoded output dec = np.empty_like(enc, dtype=self.dtype) # decode differences np.cumsum(enc, out=dec) # handle output <|code_end|> , generate the next line using the imports in this file: import numpy as np from .abc import Codec from .compat import ensure_ndarray, ndarray_copy and context (functions, classes, or occasionally code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst . Output only the next line.
out = ndarray_copy(dec, out)
Using the snippet: <|code_start|> class Base64(Codec): """Codec providing base64 compression via the Python standard library.""" codec_id = "base64" def encode(self, buf): # normalise inputs <|code_end|> , determine the next line of code. You have imports: import base64 as _base64 from .abc import Codec from .compat import ensure_contiguous_ndarray, ndarray_copy and context (class names, function names, or code) available: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst . Output only the next line.
buf = ensure_contiguous_ndarray(buf)
Continue the code snippet: <|code_start|> else: self.astype = np.dtype(astype) if self.dtype.kind != 'f' or self.astype.kind != 'f': raise ValueError('only floating point data types are supported') def encode(self, buf): # normalise input arr = ensure_ndarray(buf).view(self.dtype) # apply scaling precision = 10. ** -self.digits exp = math.log(precision, 10) if exp < 0: exp = int(math.floor(exp)) else: exp = int(math.ceil(exp)) bits = math.ceil(math.log(10. ** -exp, 2)) scale = 2. ** bits enc = np.around(scale * arr) / scale # cast dtype enc = enc.astype(self.astype, copy=False) return enc def decode(self, buf, out=None): # filter is lossy, decoding is no-op dec = ensure_ndarray(buf).view(self.astype) dec = dec.astype(self.dtype, copy=False) <|code_end|> . Use current file imports: import math import numpy as np from .abc import Codec from .compat import ensure_ndarray, ndarray_copy and context (classes, functions, or code) from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst . Output only the next line.
return ndarray_copy(dec, out)
Continue the code snippet: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-utf8 not available") arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array(greetings * 100, dtype=object), np.array(['foo', 'bar', 'baz'] * 300, dtype=object).reshape(90, 10), np.array(greetings * 1000, dtype=object).reshape(len(greetings), 100, 10, order='F'), ] def test_encode_decode(): for arr in arrays: codec = VLenUTF8() check_encode_decode_array(arr, codec) def test_config(): codec = VLenUTF8() <|code_end|> . Use current file imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenUTF8 from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and context (classes, functions, or code) from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_config(codec)
Next line prediction: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-utf8 not available") arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array(greetings * 100, dtype=object), np.array(['foo', 'bar', 'baz'] * 300, dtype=object).reshape(90, 10), np.array(greetings * 1000, dtype=object).reshape(len(greetings), 100, 10, order='F'), ] def test_encode_decode(): for arr in arrays: codec = VLenUTF8() check_encode_decode_array(arr, codec) def test_config(): codec = VLenUTF8() check_config(codec) def test_repr(): <|code_end|> . Use current file imports: (import unittest import numpy as np import pytest from numcodecs.vlen import VLenUTF8 from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal)) and context including class names, function names, or small code snippets from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_repr("VLenUTF8()")
Next line prediction: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-utf8 not available") arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array(greetings * 100, dtype=object), np.array(['foo', 'bar', 'baz'] * 300, dtype=object).reshape(90, 10), np.array(greetings * 1000, dtype=object).reshape(len(greetings), 100, 10, order='F'), ] def test_encode_decode(): for arr in arrays: codec = VLenUTF8() <|code_end|> . Use current file imports: (import unittest import numpy as np import pytest from numcodecs.vlen import VLenUTF8 from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal)) and context including class names, function names, or small code snippets from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_encode_decode_array(arr, codec)
Using the snippet: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-utf8 not available") arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), np.array(greetings * 100, dtype=object), np.array(['foo', 'bar', 'baz'] * 300, dtype=object).reshape(90, 10), np.array(greetings * 1000, dtype=object).reshape(len(greetings), 100, 10, order='F'), ] def test_encode_decode(): for arr in arrays: codec = VLenUTF8() check_encode_decode_array(arr, codec) def test_config(): codec = VLenUTF8() check_config(codec) def test_repr(): check_repr("VLenUTF8()") def test_backwards_compatibility(): <|code_end|> , determine the next line of code. You have imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenUTF8 from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and context (class names, function names, or code) available: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
check_backwards_compatibility(VLenUTF8.codec_id, arrays, [VLenUTF8()])
Based on the snippet: <|code_start|> try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-utf8 not available") arrays = [ np.array(['foo', 'bar', 'baz'] * 300, dtype=object), <|code_end|> , predict the immediate next line with the help of imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenUTF8 from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and context (classes, functions, sometimes code) from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
np.array(greetings * 100, dtype=object),
Continue the code snippet: <|code_start|> with pytest.raises(TypeError): codec.decode(1234) # these should look like corrupt data with pytest.raises(ValueError): codec.decode(b'foo') with pytest.raises(ValueError): codec.decode(np.arange(2, 3, dtype='i4')) with pytest.raises(ValueError): codec.decode(np.arange(10, 20, dtype='i4')) with pytest.raises(TypeError): codec.decode('foo') # test out parameter enc = codec.encode(arrays[0]) with pytest.raises(TypeError): codec.decode(enc, out=b'foo') with pytest.raises(TypeError): codec.decode(enc, out='foo') with pytest.raises(TypeError): codec.decode(enc, out=123) with pytest.raises(ValueError): codec.decode(enc, out=np.zeros(10, dtype='i4')) def test_encode_utf8(): a = np.array(['foo', None, 'bar'], dtype=object) codec = VLenUTF8() enc = codec.encode(a) dec = codec.decode(enc) expect = np.array(['foo', '', 'bar'], dtype=object) <|code_end|> . Use current file imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenUTF8 from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, greetings, assert_array_items_equal) and context (classes, functions, or code) from other files: # Path: numcodecs/tests/common.py # def compare_arrays(arr, res, precision=None): # def check_encode_decode(arr, codec, precision=None): # def check_encode_decode_partial(arr, codec, precision=None): # def assert_array_items_equal(res, arr): # def check_encode_decode_array(arr, codec): # def check_config(codec): # def check_repr(stmt): # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # def check_err_decode_object_buffer(compressor): # def check_err_encode_object_buffer(compressor): # def check_max_buffer_size(codec): . Output only the next line.
assert_array_items_equal(expect, dec)
Here is a snippet: <|code_start|> class BZ2(Codec): """Codec providing compression using bzip2 via the Python standard library. Parameters ---------- level : int Compression level. """ codec_id = 'bz2' def __init__(self, level=1): self.level = level def encode(self, buf): # normalise input <|code_end|> . Write the next line using the current file imports: import bz2 as _bz2 from numcodecs.abc import Codec from numcodecs.compat import ndarray_copy, ensure_contiguous_ndarray and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst # # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr , which may include functions, classes, or code. Output only the next line.
buf = ensure_contiguous_ndarray(buf)
Given snippet: <|code_start|>arrays = [ np.array([np.array([1, 2, 3]), np.array([4]), np.array([5, 6])] * 300, dtype=object), np.array([np.array([1, 2, 3]), np.array([4]), np.array([5, 6])] * 300, dtype=object).reshape(90, 10), ] codecs = [ VLenArray('<i1'), VLenArray('<i2'), VLenArray('<i4'), VLenArray('<i8'), VLenArray('<u1'), VLenArray('<u2'), VLenArray('<u4'), VLenArray('<u8'), ] def test_encode_decode(): for arr in arrays: for codec in codecs: check_encode_decode_array(arr, codec) def test_config(): codec = VLenArray('<i8') <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenArray from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, assert_array_items_equal) and context: # Path: numcodecs/tests/common.py # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def assert_array_items_equal(res, arr): # # assert isinstance(res, np.ndarray) # res = res.reshape(-1, order='A') # arr = arr.reshape(-1, order='A') # assert res.shape == arr.shape # assert res.dtype == arr.dtype # # # numpy asserts don't compare object arrays # # properly; assert that we have the same nans # # and values # arr = arr.ravel().tolist() # res = res.ravel().tolist() # for a, r in zip(arr, res): # if isinstance(a, np.ndarray): # assert_array_equal(a, r) # elif a != a: # assert r != r # else: # assert a == r which might include code, classes, or functions. Output only the next line.
check_config(codec)
Based on the snippet: <|code_start|> np.array([np.array([1, 2, 3]), np.array([4]), np.array([5, 6])] * 300, dtype=object).reshape(90, 10), ] codecs = [ VLenArray('<i1'), VLenArray('<i2'), VLenArray('<i4'), VLenArray('<i8'), VLenArray('<u1'), VLenArray('<u2'), VLenArray('<u4'), VLenArray('<u8'), ] def test_encode_decode(): for arr in arrays: for codec in codecs: check_encode_decode_array(arr, codec) def test_config(): codec = VLenArray('<i8') check_config(codec) def test_repr(): <|code_end|> , predict the immediate next line with the help of imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenArray from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, assert_array_items_equal) and context (classes, functions, sometimes code) from other files: # Path: numcodecs/tests/common.py # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def assert_array_items_equal(res, arr): # # assert isinstance(res, np.ndarray) # res = res.reshape(-1, order='A') # arr = arr.reshape(-1, order='A') # assert res.shape == arr.shape # assert res.dtype == arr.dtype # # # numpy asserts don't compare object arrays # # properly; assert that we have the same nans # # and values # arr = arr.ravel().tolist() # res = res.ravel().tolist() # for a, r in zip(arr, res): # if isinstance(a, np.ndarray): # assert_array_equal(a, r) # elif a != a: # assert r != r # else: # assert a == r . Output only the next line.
check_repr("VLenArray(dtype='<i8')")
Given the following code snippet before the placeholder: <|code_start|>try: except ImportError: # pragma: no cover raise unittest.SkipTest("vlen-array not available") arrays = [ np.array([np.array([1, 2, 3]), np.array([4]), np.array([5, 6])] * 300, dtype=object), np.array([np.array([1, 2, 3]), np.array([4]), np.array([5, 6])] * 300, dtype=object).reshape(90, 10), ] codecs = [ VLenArray('<i1'), VLenArray('<i2'), VLenArray('<i4'), VLenArray('<i8'), VLenArray('<u1'), VLenArray('<u2'), VLenArray('<u4'), VLenArray('<u8'), ] def test_encode_decode(): for arr in arrays: for codec in codecs: <|code_end|> , predict the next line using imports from the current file: import unittest import numpy as np import pytest from numcodecs.vlen import VLenArray from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, assert_array_items_equal) and context including class names, function names, and sometimes code from other files: # Path: numcodecs/tests/common.py # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def assert_array_items_equal(res, arr): # # assert isinstance(res, np.ndarray) # res = res.reshape(-1, order='A') # arr = arr.reshape(-1, order='A') # assert res.shape == arr.shape # assert res.dtype == arr.dtype # # # numpy asserts don't compare object arrays # # properly; assert that we have the same nans # # and values # arr = arr.ravel().tolist() # res = res.ravel().tolist() # for a, r in zip(arr, res): # if isinstance(a, np.ndarray): # assert_array_equal(a, r) # elif a != a: # assert r != r # else: # assert a == r . Output only the next line.
check_encode_decode_array(arr, codec)
Using the snippet: <|code_start|> codecs = [ VLenArray('<i1'), VLenArray('<i2'), VLenArray('<i4'), VLenArray('<i8'), VLenArray('<u1'), VLenArray('<u2'), VLenArray('<u4'), VLenArray('<u8'), ] def test_encode_decode(): for arr in arrays: for codec in codecs: check_encode_decode_array(arr, codec) def test_config(): codec = VLenArray('<i8') check_config(codec) def test_repr(): check_repr("VLenArray(dtype='<i8')") def test_backwards_compatibility(): <|code_end|> , determine the next line of code. You have imports: import unittest import numpy as np import pytest from numcodecs.vlen import VLenArray from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwards_compatibility, assert_array_items_equal) and context (class names, function names, or code) available: # Path: numcodecs/tests/common.py # def check_config(codec): # config = codec.get_config() # # round-trip through JSON to check serialization # config = _json.loads(_json.dumps(config)) # assert codec == get_codec(config) # # def check_repr(stmt): # # check repr matches instantiation statement # codec = eval(stmt) # actual = repr(codec) # assert stmt == actual # # def check_encode_decode_array(arr, codec): # # enc = codec.encode(arr) # dec = codec.decode(enc) # assert_array_items_equal(arr, dec) # # out = np.empty_like(arr) # codec.decode(enc, out=out) # assert_array_items_equal(arr, out) # # enc = codec.encode(arr) # dec = codec.decode(ensure_ndarray(enc)) # assert_array_items_equal(arr, dec) # # def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, prefix=None): # # # setup directory to hold data fixture # if prefix: # fixture_dir = os.path.join('fixture', codec_id, prefix) # else: # fixture_dir = os.path.join('fixture', codec_id) # if not os.path.exists(fixture_dir): # pragma: no cover # os.makedirs(fixture_dir) # # # save fixture data # for i, arr in enumerate(arrays): # arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i)) # if not os.path.exists(arr_fn): # pragma: no cover # np.save(arr_fn, arr) # # # load fixture data # for arr_fn in glob(os.path.join(fixture_dir, 'array.*.npy')): # # # setup # i = int(arr_fn.split('.')[-2]) # arr = np.load(arr_fn, allow_pickle=True) # arr_bytes = arr.tobytes(order='A') # if arr.flags.f_contiguous: # order = 'F' # else: # order = 'C' # # for j, codec in enumerate(codecs): # # if codec is None: # pytest.skip("codec has been removed") # # # setup a directory to hold encoded data # codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j)) # if not os.path.exists(codec_dir): # pragma: no cover # os.makedirs(codec_dir) # # # file with codec configuration information # codec_fn = os.path.join(codec_dir, 'config.json') # # one time save config # if not os.path.exists(codec_fn): # pragma: no cover # with open(codec_fn, mode='w') as cf: # _json.dump(codec.get_config(), cf, sort_keys=True, indent=4) # # load config and compare with expectation # with open(codec_fn, mode='r') as cf: # config = _json.load(cf) # assert codec == get_codec(config) # # enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i)) # # # one time encode and save array # if not os.path.exists(enc_fn): # pragma: no cover # enc = codec.encode(arr) # enc = ensure_bytes(enc) # with open(enc_fn, mode='wb') as ef: # ef.write(enc) # # # load and decode data # with open(enc_fn, mode='rb') as ef: # enc = ef.read() # dec = codec.decode(enc) # dec_arr = ensure_ndarray(dec).reshape(-1, order='A') # dec_arr = dec_arr.view(dtype=arr.dtype).reshape(arr.shape, order=order) # if precision and precision[j] is not None: # assert_array_almost_equal(arr, dec_arr, decimal=precision[j]) # elif arr.dtype == 'object': # assert_array_items_equal(arr, dec_arr) # else: # assert_array_equal(arr, dec_arr) # assert arr_bytes == ensure_bytes(dec) # # def assert_array_items_equal(res, arr): # # assert isinstance(res, np.ndarray) # res = res.reshape(-1, order='A') # arr = arr.reshape(-1, order='A') # assert res.shape == arr.shape # assert res.dtype == arr.dtype # # # numpy asserts don't compare object arrays # # properly; assert that we have the same nans # # and values # arr = arr.ravel().tolist() # res = res.ravel().tolist() # for a, r in zip(arr, res): # if isinstance(a, np.ndarray): # assert_array_equal(a, r) # elif a != a: # assert r != r # else: # assert a == r . Output only the next line.
check_backwards_compatibility(VLenArray.codec_id, arrays, codecs)
Predict the next line for this snippet: <|code_start|> """Codec to pack elements of a boolean array into bits in a uint8 array. Examples -------- >>> import numcodecs >>> import numpy as np >>> codec = numcodecs.PackBits() >>> x = np.array([True, False, False, True], dtype=bool) >>> y = codec.encode(x) >>> y array([ 4, 144], dtype=uint8) >>> z = codec.decode(y) >>> z array([ True, False, False, True]) Notes ----- The first element of the encoded array stores the number of bits that were padded to complete the final byte. """ codec_id = 'packbits' def __init__(self): pass def encode(self, buf): # normalise input <|code_end|> with the help of current file imports: import numpy as np from .abc import Codec from .compat import ensure_ndarray, ndarray_copy and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst , which may contain function names, class names, or code. Output only the next line.
arr = ensure_ndarray(buf).view(bool)
Given the following code snippet before the placeholder: <|code_start|> n_bits_padded = 0 enc[0] = n_bits_padded # apply encoding enc[1:] = np.packbits(arr) return enc def decode(self, buf, out=None): # normalise input enc = ensure_ndarray(buf).view('u1') # flatten to simplify implementation enc = enc.reshape(-1, order='A') # find out how many bits were padded n_bits_padded = int(enc[0]) # apply decoding dec = np.unpackbits(enc[1:]) # remove padded bits if n_bits_padded: dec = dec[:-n_bits_padded] # view as boolean array dec = dec.view(bool) # handle destination <|code_end|> , predict the next line using imports from the current file: import numpy as np from .abc import Codec from .compat import ensure_ndarray, ndarray_copy and context including class names, function names, and sometimes code from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_ndarray(buf): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # if isinstance(buf, np.ndarray): # # already a numpy array # arr = buf # # elif isinstance(buf, array.array) and buf.typecode in 'cu': # # Guard condition, do not support array.array with unicode type, this is # # problematic because numpy does not support it on all platforms. Also do not # # support char as it was removed in Python 3. # raise TypeError('array.array with char or unicode type is not supported') # # else: # # # N.B., first take a memoryview to make sure that we subsequently create a # # numpy array from a memory buffer with no copy # mem = memoryview(buf) # # # instantiate array from memoryview, ensures no copy # arr = np.array(mem, copy=False) # # return arr # # def ndarray_copy(src, dst): # """Copy the contents of the array from `src` to `dst`.""" # # if dst is None: # # no-op # return src # # # ensure ndarrays # src = ensure_ndarray(src) # dst = ensure_ndarray(dst) # # # flatten source array # src = src.reshape(-1, order='A') # # # ensure same data type # if dst.dtype != object: # src = src.view(dst.dtype) # # # reshape source to match destination # if src.shape != dst.shape: # if dst.flags.f_contiguous: # order = 'F' # else: # order = 'C' # src = src.reshape(dst.shape, order=order) # # # copy via numpy # np.copyto(dst, src) # # return dst . Output only the next line.
return ndarray_copy(dec, out)
Here is a snippet: <|code_start|> Parameters ---------- protocol : int, defaults to pickle.HIGHEST_PROTOCOL The protocol used to pickle data. Examples -------- >>> import numcodecs as codecs >>> import numpy as np >>> x = np.array(['foo', 'bar', 'baz'], dtype='object') >>> f = codecs.Pickle() >>> f.decode(f.encode(x)) array(['foo', 'bar', 'baz'], dtype=object) See Also -------- numcodecs.msgpacks.MsgPack """ codec_id = 'pickle' def __init__(self, protocol=pickle.HIGHEST_PROTOCOL): self.protocol = protocol def encode(self, buf): return pickle.dumps(buf, protocol=self.protocol) def decode(self, buf, out=None): <|code_end|> . Write the next line using the current file imports: import pickle import numpy as np from .abc import Codec from .compat import ensure_contiguous_ndarray and context from other files: # Path: numcodecs/abc.py # class Codec: # """Codec abstract base class.""" # # # override in sub-class # codec_id = None # """Codec identifier.""" # # @abstractmethod # def encode(self, buf): # pragma: no cover # """Encode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Data to be encoded. May be any object supporting the new-style # buffer protocol. # # Returns # ------- # enc : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # """ # # @abstractmethod # def decode(self, buf, out=None): # pragma: no cover # """Decode data in `buf`. # # Parameters # ---------- # buf : buffer-like # Encoded data. May be any object supporting the new-style buffer # protocol. # out : buffer-like, optional # Writeable buffer to store decoded data. N.B. if provided, this buffer must # be exactly the right size to store the decoded data. # # Returns # ------- # dec : buffer-like # Decoded data. May be any object supporting the new-style # buffer protocol. # """ # # def get_config(self): # """Return a dictionary holding configuration parameters for this # codec. Must include an 'id' field with the codec identifier. All # values must be compatible with JSON encoding.""" # # # override in sub-class if need special encoding of config values # # # setup config object # config = dict(id=self.codec_id) # # # by default, assume all non-private members are configuration # # parameters - override this in sub-class if not the case # for k in self.__dict__: # if not k.startswith('_'): # config[k] = getattr(self, k) # # return config # # @classmethod # def from_config(cls, config): # """Instantiate codec from a configuration object.""" # # N.B., assume at this point the 'id' field has been removed from # # the config object # # # override in sub-class if need special decoding of config values # # # by default, assume constructor accepts configuration parameters as # # keyword arguments without any special decoding # return cls(**config) # # def __eq__(self, other): # # override in sub-class if need special equality comparison # try: # return self.get_config() == other.get_config() # except AttributeError: # return False # # def __repr__(self): # # # override in sub-class if need special representation # # # by default, assume all non-private members are configuration # # parameters and valid keyword arguments to constructor function # # r = '%s(' % type(self).__name__ # params = ['{}={!r}'.format(k, getattr(self, k)) # for k in sorted(self.__dict__) # if not k.startswith('_')] # r += ', '.join(params) + ')' # return r # # Path: numcodecs/compat.py # def ensure_contiguous_ndarray(buf, max_buffer_size=None): # """Convenience function to coerce `buf` to a numpy array, if it is not already a # numpy array. Also ensures that the returned value exports fully contiguous memory, # and supports the new-style buffer interface. If the optional max_buffer_size is # provided, raise a ValueError if the number of bytes consumed by the returned # array exceeds this value. # # Parameters # ---------- # buf : array-like or bytes-like # A numpy array or any object exporting a buffer interface. # max_buffer_size : int # If specified, the largest allowable value of arr.nbytes, where arr # is the returned array. # # Returns # ------- # arr : ndarray # A numpy array, sharing memory with `buf`. # # Notes # ----- # This function will not create a copy under any circumstances, it is guaranteed to # return a view on memory exported by `buf`. # # """ # # # ensure input is a numpy array # arr = ensure_ndarray(buf) # # # check for object arrays, these are just memory pointers, actual memory holding # # item data is scattered elsewhere # if arr.dtype == object: # raise TypeError('object arrays are not supported') # # # check for datetime or timedelta ndarray, the buffer interface doesn't support those # if arr.dtype.kind in 'Mm': # arr = arr.view(np.int64) # # # check memory is contiguous, if so flatten # if arr.flags.c_contiguous or arr.flags.f_contiguous: # # can flatten without copy # arr = arr.reshape(-1, order='A') # # else: # raise ValueError('an array with contiguous memory is required') # # if max_buffer_size is not None and arr.nbytes > max_buffer_size: # msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size) # raise ValueError(msg) # # return arr , which may include functions, classes, or code. Output only the next line.
buf = ensure_contiguous_ndarray(buf)
Given the code snippet: <|code_start|># -*- coding:utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. def fail(type, msg): return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg]) def success(datas): <|code_end|> , generate the next line using the imports in this file: from elevator.constants import SUCCESS_STATUS, FAILURE_STATUS and context (functions, classes, or occasionally code) from other files: # Path: elevator/constants.py # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 . Output only the next line.
return SUCCESS_STATUS, datas
Predict the next line after this snippet: <|code_start|> count = 0 while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) count += 1 def cancel(self): self.finished.set() class DatabaseOptions(dict): def __init__(self, *args, **kwargs): self['create_if_missing'] = True self['error_if_exists'] = False self['paranoid_checks'] = False self['block_cache_size'] = 8 * (2 << 20) self['write_buffer_size'] = 2 * (2 << 20) self['block_size'] = 4096 self['max_open_files'] = 1000 for key, value in kwargs.iteritems(): if key in self: self[key] = value class DatabasesHandler(dict): STATUSES = enum('MOUNTED', 'UNMOUNTED') def __init__(self, store, dest, *args, **kwargs): <|code_end|> using the current file's imports: import os import uuid import logging import leveldb import ujson as json from shutil import rmtree from threading import Thread, Event from leveldb import LevelDBError from .env import Environment from .constants import OS_ERROR, DATABASE_ERROR from .utils.snippets import from_bytes_to_mo from .utils.patterns import enum from .helpers.internals import failure, success and any relevant context from other files: # Path: debian/elevator/usr/share/pyshared/elevator/env.py # class Environment(dict): # """ # Unix shells like environment class. Implements add, # get, load, flush methods. Handles lists of values too. # Basically Acts like a basic key/value store. # """ # __metaclass__ = Singleton # # def __init__(self, env_file='', *args, **kwargs): # if env_file: # self.load_from_file(env_file=env_file) # Has to be called last! # # self.update(kwargs) # dict.__init__(self, *args, **kwargs) # # def load_from_file(self, env_file): # """ # Updates the environment using an ini file containing # key/value descriptions. # """ # config = ConfigParser() # # with open(env_file, 'r') as f: # config.readfp(f) # # for section in config.sections(): # self.update({section: items_to_dict(config.items(section))}) # # def reload_from_file(self, env_file=''): # self.flush(env_file) # self.load(env_file) # # def load_from_args(self, section, args): # """Loads argparse kwargs into environment, as `section`""" # if not section in self: # self[section] = {} # # for (arg, value) in args: # self[section][arg] = value # # def flush(self): # """ # Flushes the environment from it's manually # set attributes. # """ # for attr in self.attributes: # delattr(self, attr) # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # OS_ERROR = 5 # # DATABASE_ERROR = 6 # # Path: debian/elevator/usr/share/pyshared/elevator/utils/snippets.py # def items_to_dict(items): . Output only the next line.
self.env = Environment()
Based on the snippet: <|code_start|> self[db_uid]['status'] = self.STATUSES.UNMOUNTED del self[db_uid]['connector'] self[db_uid]['connector'] = None else: return failure(DATABASE_ERROR, "Database %r already unmounted" % db_name) return success() def add(self, db_name, db_options=None): """Adds a db to the DatabasesHandler object, and sync it to the store file""" db_options = db_options or DatabaseOptions() cache_status, ratio = self._disposable_cache(db_options["block_cache_size"]) if not cache_status: return failure(DATABASE_ERROR, "Not enough disposable cache memory " "%d Mo missing" % ratio) db_name_is_path = db_name.startswith('.') or ('/' in db_name) is_abspath = lambda: not db_name.startswith('.') and ('/' in db_name) # Handle case when a db is a path if db_name_is_path: if not is_abspath(): return failure(DATABASE_ERROR, "Canno't create database from relative path") try: new_db_path = db_name if not os.path.exists(new_db_path): os.mkdir(new_db_path) except OSError as e: <|code_end|> , predict the immediate next line with the help of imports: import os import uuid import logging import leveldb import ujson as json from shutil import rmtree from threading import Thread, Event from leveldb import LevelDBError from .env import Environment from .constants import OS_ERROR, DATABASE_ERROR from .utils.snippets import from_bytes_to_mo from .utils.patterns import enum from .helpers.internals import failure, success and context (classes, functions, sometimes code) from other files: # Path: debian/elevator/usr/share/pyshared/elevator/env.py # class Environment(dict): # """ # Unix shells like environment class. Implements add, # get, load, flush methods. Handles lists of values too. # Basically Acts like a basic key/value store. # """ # __metaclass__ = Singleton # # def __init__(self, env_file='', *args, **kwargs): # if env_file: # self.load_from_file(env_file=env_file) # Has to be called last! # # self.update(kwargs) # dict.__init__(self, *args, **kwargs) # # def load_from_file(self, env_file): # """ # Updates the environment using an ini file containing # key/value descriptions. # """ # config = ConfigParser() # # with open(env_file, 'r') as f: # config.readfp(f) # # for section in config.sections(): # self.update({section: items_to_dict(config.items(section))}) # # def reload_from_file(self, env_file=''): # self.flush(env_file) # self.load(env_file) # # def load_from_args(self, section, args): # """Loads argparse kwargs into environment, as `section`""" # if not section in self: # self[section] = {} # # for (arg, value) in args: # self[section][arg] = value # # def flush(self): # """ # Flushes the environment from it's manually # set attributes. # """ # for attr in self.attributes: # delattr(self, attr) # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # OS_ERROR = 5 # # DATABASE_ERROR = 6 # # Path: debian/elevator/usr/share/pyshared/elevator/utils/snippets.py # def items_to_dict(items): . Output only the next line.
return failure(OS_ERROR, e.strerror)
Given the following code snippet before the placeholder: <|code_start|> 'ref_count': 0, } }) # Always bootstrap 'default' if 'default' not in self.index['name_to_uid']: self.add('default') def store_update(self, db_name, db_desc): """Updates the database store file db_name key, with db_desc value""" store_datas = self.extract_store_datas() store_datas.update({db_name: db_desc}) json.dump(store_datas, open(self.store, 'w')) def store_remove(self, db_name): """Removes a database from store file""" store_datas = self.extract_store_datas() store_datas.pop(db_name) json.dump(store_datas, open(self.store, 'w')) def mount(self, db_name): db_uid = self.index['name_to_uid'][db_name] if db_name in self.index['name_to_uid'] else None if self[db_uid]['status'] == self.STATUSES.UNMOUNTED: db_path = self[db_uid]['path'] connector = self._get_db_connector(db_path) if connector is None: <|code_end|> , predict the next line using imports from the current file: import os import uuid import logging import leveldb import ujson as json from shutil import rmtree from threading import Thread, Event from leveldb import LevelDBError from .env import Environment from .constants import OS_ERROR, DATABASE_ERROR from .utils.snippets import from_bytes_to_mo from .utils.patterns import enum from .helpers.internals import failure, success and context including class names, function names, and sometimes code from other files: # Path: debian/elevator/usr/share/pyshared/elevator/env.py # class Environment(dict): # """ # Unix shells like environment class. Implements add, # get, load, flush methods. Handles lists of values too. # Basically Acts like a basic key/value store. # """ # __metaclass__ = Singleton # # def __init__(self, env_file='', *args, **kwargs): # if env_file: # self.load_from_file(env_file=env_file) # Has to be called last! # # self.update(kwargs) # dict.__init__(self, *args, **kwargs) # # def load_from_file(self, env_file): # """ # Updates the environment using an ini file containing # key/value descriptions. # """ # config = ConfigParser() # # with open(env_file, 'r') as f: # config.readfp(f) # # for section in config.sections(): # self.update({section: items_to_dict(config.items(section))}) # # def reload_from_file(self, env_file=''): # self.flush(env_file) # self.load(env_file) # # def load_from_args(self, section, args): # """Loads argparse kwargs into environment, as `section`""" # if not section in self: # self[section] = {} # # for (arg, value) in args: # self[section][arg] = value # # def flush(self): # """ # Flushes the environment from it's manually # set attributes. # """ # for attr in self.attributes: # delattr(self, attr) # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # OS_ERROR = 5 # # DATABASE_ERROR = 6 # # Path: debian/elevator/usr/share/pyshared/elevator/utils/snippets.py # def items_to_dict(items): . Output only the next line.
return failure(DATABASE_ERROR, "Database %s could not be mounted" % db_path)
Given the code snippet: <|code_start|> for key, value in kwargs.iteritems(): if key in self: self[key] = value class DatabasesHandler(dict): STATUSES = enum('MOUNTED', 'UNMOUNTED') def __init__(self, store, dest, *args, **kwargs): self.env = Environment() self.index = dict().fromkeys('name_to_uid') self.index['name_to_uid'] = {} self['reverse_name_index'] = {} self['paths_index'] = {} self.dest = dest self.store = store self._global_cache_size = None self.load() self.mount('default') # Always mount default @property def global_cache_size(self): store_datas = self.extract_store_datas() max_caches = [int(db["options"]["block_cache_size"]) for db in store_datas.itervalues()] <|code_end|> , generate the next line using the imports in this file: import os import uuid import logging import leveldb import ujson as json from shutil import rmtree from threading import Thread, Event from leveldb import LevelDBError from .env import Environment from .constants import OS_ERROR, DATABASE_ERROR from .utils.snippets import from_bytes_to_mo from .utils.patterns import enum from .helpers.internals import failure, success and context (functions, classes, or occasionally code) from other files: # Path: debian/elevator/usr/share/pyshared/elevator/env.py # class Environment(dict): # """ # Unix shells like environment class. Implements add, # get, load, flush methods. Handles lists of values too. # Basically Acts like a basic key/value store. # """ # __metaclass__ = Singleton # # def __init__(self, env_file='', *args, **kwargs): # if env_file: # self.load_from_file(env_file=env_file) # Has to be called last! # # self.update(kwargs) # dict.__init__(self, *args, **kwargs) # # def load_from_file(self, env_file): # """ # Updates the environment using an ini file containing # key/value descriptions. # """ # config = ConfigParser() # # with open(env_file, 'r') as f: # config.readfp(f) # # for section in config.sections(): # self.update({section: items_to_dict(config.items(section))}) # # def reload_from_file(self, env_file=''): # self.flush(env_file) # self.load(env_file) # # def load_from_args(self, section, args): # """Loads argparse kwargs into environment, as `section`""" # if not section in self: # self[section] = {} # # for (arg, value) in args: # self[section][arg] = value # # def flush(self): # """ # Flushes the environment from it's manually # set attributes. # """ # for attr in self.attributes: # delattr(self, attr) # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # OS_ERROR = 5 # # DATABASE_ERROR = 6 # # Path: debian/elevator/usr/share/pyshared/elevator/utils/snippets.py # def items_to_dict(items): . Output only the next line.
return sum([from_bytes_to_mo(x) for x in max_caches])
Based on the snippet: <|code_start|> # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from __future__ import absolute_import class Client(object): def __init__(self, *args, **kwargs): self.protocol = kwargs.pop('protocol', 'tcp') self.endpoint = kwargs.pop('endpoint', '127.0.0.1:4141') self.host = "%s://%s" % (self.protocol, self.endpoint) self.context = None self.socket = None self.timeout = kwargs.pop('timeout', 10000) self.db_uid = None self.db_name = None self.setup_socket() if self.ping(): self.connect() else: failure_msg = 'No elevator server hanging on {0}://{1}'.format(self.protocol, self.endpoint) <|code_end|> , predict the immediate next line with the help of imports: import zmq from elevator.constants import * from .io import output_result from .errors import * from .helpers import success, fail from .message import Request, ResponseHeader, Response and context (classes, functions, sometimes code) from other files: # Path: elevator_cli/io.py # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/helpers.py # def success(datas): # return SUCCESS_STATUS, datas # # def fail(type, msg): # return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg]) # # Path: elevator_cli/message.py # class Request(object): # """Handler objects for frontend->backend objects messages""" # def __new__(cls, *args, **kwargs): # try: # content = { # 'meta': kwargs.pop('meta', {}), # 'uid': kwargs.get('db_uid'), # uid can eventually be None # 'cmd': kwargs.pop('command'), # 'args': kwargs.pop('args'), # } # except KeyError: # raise MessageFormatError("Invalid request format : %s" % str(kwargs)) # # return msgpack.packb(content) # # class ResponseHeader(object): # def __init__(self, raw_header): # header = msgpack.unpackb(raw_header) # # try: # self.status = header.pop('status') # self.err_code = header.pop('err_code') # self.err_msg = header.pop('err_msg') # except KeyError: # errors_logger.exception("Invalid response header : %s" % # header) # raise MessageFormatError("Invalid response header") # # for key, value in header.iteritems(): # setattr(self, key, value) # # class Response(object): # def __init__(self, raw_message, *args, **kwargs): # message = msgpack.unpackb(raw_message) # # try: # self.datas = message['datas'] # except KeyError: # errors_logger.exception("Invalid response message : %s" % # message) # raise MessageFormatError("Invalid response message") . Output only the next line.
output_result(FAILURE_STATUS, failure_msg)
Given snippet: <|code_start|> self.socket.close() self.context.term() def _process_request(self, command, arguments): if command in ["MGET"] and arguments: return command, [arguments] return command, arguments def _process_response(self, req_cmd, res_datas): if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: return res_datas[0] return res_datas def send_cmd(self, db_uid, command, arguments, *args, **kwargs): command, arguments = self._process_request(command, arguments) self.socket.send_multipart([Request(db_uid=db_uid, command=command, args=arguments, meta={})],) try: raw_header, raw_response = self.socket.recv_multipart() header = ResponseHeader(raw_header) response = Response(raw_response) if header.status == FAILURE_STATUS: return fail(ELEVATOR_ERROR[header.err_code], header.err_msg) except zmq.core.error.ZMQError: return fail("TimeoutError", "Server did not respond in time") <|code_end|> , continue by predicting the next line. Consider current file imports: import zmq from elevator.constants import * from .io import output_result from .errors import * from .helpers import success, fail from .message import Request, ResponseHeader, Response and context: # Path: elevator_cli/io.py # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/helpers.py # def success(datas): # return SUCCESS_STATUS, datas # # def fail(type, msg): # return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg]) # # Path: elevator_cli/message.py # class Request(object): # """Handler objects for frontend->backend objects messages""" # def __new__(cls, *args, **kwargs): # try: # content = { # 'meta': kwargs.pop('meta', {}), # 'uid': kwargs.get('db_uid'), # uid can eventually be None # 'cmd': kwargs.pop('command'), # 'args': kwargs.pop('args'), # } # except KeyError: # raise MessageFormatError("Invalid request format : %s" % str(kwargs)) # # return msgpack.packb(content) # # class ResponseHeader(object): # def __init__(self, raw_header): # header = msgpack.unpackb(raw_header) # # try: # self.status = header.pop('status') # self.err_code = header.pop('err_code') # self.err_msg = header.pop('err_msg') # except KeyError: # errors_logger.exception("Invalid response header : %s" % # header) # raise MessageFormatError("Invalid response header") # # for key, value in header.iteritems(): # setattr(self, key, value) # # class Response(object): # def __init__(self, raw_message, *args, **kwargs): # message = msgpack.unpackb(raw_message) # # try: # self.datas = message['datas'] # except KeyError: # errors_logger.exception("Invalid response message : %s" % # message) # raise MessageFormatError("Invalid response message") which might include code, classes, or functions. Output only the next line.
return success(self._process_response(command, response.datas))
Continue the code snippet: <|code_start|> self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) self.socket.connect(self.host) def teardown_socket(self): self.socket.close() self.context.term() def _process_request(self, command, arguments): if command in ["MGET"] and arguments: return command, [arguments] return command, arguments def _process_response(self, req_cmd, res_datas): if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: return res_datas[0] return res_datas def send_cmd(self, db_uid, command, arguments, *args, **kwargs): command, arguments = self._process_request(command, arguments) self.socket.send_multipart([Request(db_uid=db_uid, command=command, args=arguments, meta={})],) try: raw_header, raw_response = self.socket.recv_multipart() header = ResponseHeader(raw_header) response = Response(raw_response) if header.status == FAILURE_STATUS: <|code_end|> . Use current file imports: import zmq from elevator.constants import * from .io import output_result from .errors import * from .helpers import success, fail from .message import Request, ResponseHeader, Response and context (classes, functions, or code) from other files: # Path: elevator_cli/io.py # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/helpers.py # def success(datas): # return SUCCESS_STATUS, datas # # def fail(type, msg): # return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg]) # # Path: elevator_cli/message.py # class Request(object): # """Handler objects for frontend->backend objects messages""" # def __new__(cls, *args, **kwargs): # try: # content = { # 'meta': kwargs.pop('meta', {}), # 'uid': kwargs.get('db_uid'), # uid can eventually be None # 'cmd': kwargs.pop('command'), # 'args': kwargs.pop('args'), # } # except KeyError: # raise MessageFormatError("Invalid request format : %s" % str(kwargs)) # # return msgpack.packb(content) # # class ResponseHeader(object): # def __init__(self, raw_header): # header = msgpack.unpackb(raw_header) # # try: # self.status = header.pop('status') # self.err_code = header.pop('err_code') # self.err_msg = header.pop('err_msg') # except KeyError: # errors_logger.exception("Invalid response header : %s" % # header) # raise MessageFormatError("Invalid response header") # # for key, value in header.iteritems(): # setattr(self, key, value) # # class Response(object): # def __init__(self, raw_message, *args, **kwargs): # message = msgpack.unpackb(raw_message) # # try: # self.datas = message['datas'] # except KeyError: # errors_logger.exception("Invalid response message : %s" % # message) # raise MessageFormatError("Invalid response message") . Output only the next line.
return fail(ELEVATOR_ERROR[header.err_code], header.err_msg)
Using the snippet: <|code_start|> def __init__(self, *args, **kwargs): self.protocol = kwargs.pop('protocol', 'tcp') self.endpoint = kwargs.pop('endpoint', '127.0.0.1:4141') self.host = "%s://%s" % (self.protocol, self.endpoint) self.context = None self.socket = None self.timeout = kwargs.pop('timeout', 10000) self.db_uid = None self.db_name = None self.setup_socket() if self.ping(): self.connect() else: failure_msg = 'No elevator server hanging on {0}://{1}'.format(self.protocol, self.endpoint) output_result(FAILURE_STATUS, failure_msg) def __del__(self): self.socket.close() self.context.term() def ping(self, *args, **kwargs): pings = True timeout = kwargs.pop('timeout', 1000) orig_timeout = self.timeout self.socket.setsockopt(zmq.RCVTIMEO, timeout) <|code_end|> , determine the next line of code. You have imports: import zmq from elevator.constants import * from .io import output_result from .errors import * from .helpers import success, fail from .message import Request, ResponseHeader, Response and context (class names, function names, or code) available: # Path: elevator_cli/io.py # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/helpers.py # def success(datas): # return SUCCESS_STATUS, datas # # def fail(type, msg): # return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg]) # # Path: elevator_cli/message.py # class Request(object): # """Handler objects for frontend->backend objects messages""" # def __new__(cls, *args, **kwargs): # try: # content = { # 'meta': kwargs.pop('meta', {}), # 'uid': kwargs.get('db_uid'), # uid can eventually be None # 'cmd': kwargs.pop('command'), # 'args': kwargs.pop('args'), # } # except KeyError: # raise MessageFormatError("Invalid request format : %s" % str(kwargs)) # # return msgpack.packb(content) # # class ResponseHeader(object): # def __init__(self, raw_header): # header = msgpack.unpackb(raw_header) # # try: # self.status = header.pop('status') # self.err_code = header.pop('err_code') # self.err_msg = header.pop('err_msg') # except KeyError: # errors_logger.exception("Invalid response header : %s" % # header) # raise MessageFormatError("Invalid response header") # # for key, value in header.iteritems(): # setattr(self, key, value) # # class Response(object): # def __init__(self, raw_message, *args, **kwargs): # message = msgpack.unpackb(raw_message) # # try: # self.datas = message['datas'] # except KeyError: # errors_logger.exception("Invalid response message : %s" % # message) # raise MessageFormatError("Invalid response message") . Output only the next line.
request = Request(db_uid=None, command="PING", args=[])
Given snippet: <|code_start|> def setup_socket(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.XREQ) self.socket.setsockopt(zmq.LINGER, 0) self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) self.socket.connect(self.host) def teardown_socket(self): self.socket.close() self.context.term() def _process_request(self, command, arguments): if command in ["MGET"] and arguments: return command, [arguments] return command, arguments def _process_response(self, req_cmd, res_datas): if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: return res_datas[0] return res_datas def send_cmd(self, db_uid, command, arguments, *args, **kwargs): command, arguments = self._process_request(command, arguments) self.socket.send_multipart([Request(db_uid=db_uid, command=command, args=arguments, meta={})],) try: raw_header, raw_response = self.socket.recv_multipart() <|code_end|> , continue by predicting the next line. Consider current file imports: import zmq from elevator.constants import * from .io import output_result from .errors import * from .helpers import success, fail from .message import Request, ResponseHeader, Response and context: # Path: elevator_cli/io.py # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/helpers.py # def success(datas): # return SUCCESS_STATUS, datas # # def fail(type, msg): # return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg]) # # Path: elevator_cli/message.py # class Request(object): # """Handler objects for frontend->backend objects messages""" # def __new__(cls, *args, **kwargs): # try: # content = { # 'meta': kwargs.pop('meta', {}), # 'uid': kwargs.get('db_uid'), # uid can eventually be None # 'cmd': kwargs.pop('command'), # 'args': kwargs.pop('args'), # } # except KeyError: # raise MessageFormatError("Invalid request format : %s" % str(kwargs)) # # return msgpack.packb(content) # # class ResponseHeader(object): # def __init__(self, raw_header): # header = msgpack.unpackb(raw_header) # # try: # self.status = header.pop('status') # self.err_code = header.pop('err_code') # self.err_msg = header.pop('err_msg') # except KeyError: # errors_logger.exception("Invalid response header : %s" % # header) # raise MessageFormatError("Invalid response header") # # for key, value in header.iteritems(): # setattr(self, key, value) # # class Response(object): # def __init__(self, raw_message, *args, **kwargs): # message = msgpack.unpackb(raw_message) # # try: # self.datas = message['datas'] # except KeyError: # errors_logger.exception("Invalid response message : %s" % # message) # raise MessageFormatError("Invalid response message") which might include code, classes, or functions. Output only the next line.
header = ResponseHeader(raw_header)
Here is a snippet: <|code_start|> self.context = zmq.Context() self.socket = self.context.socket(zmq.XREQ) self.socket.setsockopt(zmq.LINGER, 0) self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) self.socket.connect(self.host) def teardown_socket(self): self.socket.close() self.context.term() def _process_request(self, command, arguments): if command in ["MGET"] and arguments: return command, [arguments] return command, arguments def _process_response(self, req_cmd, res_datas): if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: return res_datas[0] return res_datas def send_cmd(self, db_uid, command, arguments, *args, **kwargs): command, arguments = self._process_request(command, arguments) self.socket.send_multipart([Request(db_uid=db_uid, command=command, args=arguments, meta={})],) try: raw_header, raw_response = self.socket.recv_multipart() header = ResponseHeader(raw_header) <|code_end|> . Write the next line using the current file imports: import zmq from elevator.constants import * from .io import output_result from .errors import * from .helpers import success, fail from .message import Request, ResponseHeader, Response and context from other files: # Path: elevator_cli/io.py # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/helpers.py # def success(datas): # return SUCCESS_STATUS, datas # # def fail(type, msg): # return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg]) # # Path: elevator_cli/message.py # class Request(object): # """Handler objects for frontend->backend objects messages""" # def __new__(cls, *args, **kwargs): # try: # content = { # 'meta': kwargs.pop('meta', {}), # 'uid': kwargs.get('db_uid'), # uid can eventually be None # 'cmd': kwargs.pop('command'), # 'args': kwargs.pop('args'), # } # except KeyError: # raise MessageFormatError("Invalid request format : %s" % str(kwargs)) # # return msgpack.packb(content) # # class ResponseHeader(object): # def __init__(self, raw_header): # header = msgpack.unpackb(raw_header) # # try: # self.status = header.pop('status') # self.err_code = header.pop('err_code') # self.err_msg = header.pop('err_msg') # except KeyError: # errors_logger.exception("Invalid response header : %s" % # header) # raise MessageFormatError("Invalid response header") # # for key, value in header.iteritems(): # setattr(self, key, value) # # class Response(object): # def __init__(self, raw_message, *args, **kwargs): # message = msgpack.unpackb(raw_message) # # try: # self.datas = message['datas'] # except KeyError: # errors_logger.exception("Invalid response message : %s" % # message) # raise MessageFormatError("Invalid response message") , which may include functions, classes, or code. Output only the next line.
response = Response(raw_response)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. def prompt(*args, **kwargs): current_db = kwargs.pop('current_db', 'default') if current_db: pattern = '@ Elevator.{db} => '.format(db=current_db) else: pattern = '! Offline => ' input_str = raw_input(pattern) return input_str def parse_input(input_str, *args, **kwargs): input_str = shlex.split(input_str.strip()) <|code_end|> . Use current file imports: import shlex from clint.textui import puts, colored from elevator.utils.patterns import destructurate from .helpers import FAILURE_STATUS and context (classes, functions, or code) from other files: # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator_cli/helpers.py # def fail(type, msg): # def success(datas): . Output only the next line.
command, args = destructurate(input_str)
Based on the snippet: <|code_start|> # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. def prompt(*args, **kwargs): current_db = kwargs.pop('current_db', 'default') if current_db: pattern = '@ Elevator.{db} => '.format(db=current_db) else: pattern = '! Offline => ' input_str = raw_input(pattern) return input_str def parse_input(input_str, *args, **kwargs): input_str = shlex.split(input_str.strip()) command, args = destructurate(input_str) return command.upper(), args def output_result(status, result, *args, **kwargs): if result: <|code_end|> , predict the immediate next line with the help of imports: import shlex from clint.textui import puts, colored from elevator.utils.patterns import destructurate from .helpers import FAILURE_STATUS and context (classes, functions, sometimes code) from other files: # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator_cli/helpers.py # def fail(type, msg): # def success(datas): . Output only the next line.
if status == FAILURE_STATUS:
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. mkdtemp = lambda _dir: tempfile.mkdtemp(suffix='-test', prefix='elevator-', dir=_dir) mkstemp = lambda suffix, _dir: tempfile.mkstemp(suffix="-test" + suffix, prefix='elevator-', dir=_dir)[1] def gen_test_config(): tmp = mkdtemp('/tmp') <|code_end|> , predict the immediate next line with the help of imports: import os import shutil import subprocess import tempfile import ConfigParser import random from elevator.config import Config and context (classes, functions, sometimes code) from other files: # Path: elevator/config.py # class Config(dict): # """ # Unix shells like environment class. Implements add, # get, load, flush methods. Handles lists of values too. # Basically Acts like a basic key/value store. # """ # def __init__(self, f=None, *args, **kwargs): # if f: # self.update_with_file(f) # Has to be called last! # # self.update(kwargs) # dict.__init__(self, *args, **kwargs) # # def update_with_file(self, f): # """ # Updates the environment using an ini file containing # key/value descriptions. # """ # config = ConfigParser() # # with open(f, 'r') as f: # config.readfp(f) # # for section in config.sections(): # self.update(items_to_dict(config.items(section))) # # def reload_from_file(self, f=''): # self.flush(f) # self.load(f) # # def update_with_args(self, args): # """Loads argparse kwargs into environment, as `section`""" # for (arg, value) in args: # if value is not None: # self[arg] = value # # def flush(self): # """ # Flushes the environment from it's manually # set attributes. # """ # for attr in self.attributes: # delattr(self, attr) . Output only the next line.
return Config(**{
Given snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from __future__ import absolute_import def main(): args = init_parser().parse_args(sys.argv[1:]) client = Client(protocol=args.protocol, endpoint=args.endpoint) try: while True: <|code_end|> , continue by predicting the next line. Consider current file imports: import sys from .io import prompt, parse_input, output_result from .client import Client from .args import init_parser and context: # Path: elevator_cli/io.py # def prompt(*args, **kwargs): # current_db = kwargs.pop('current_db', 'default') # # if current_db: # pattern = '@ Elevator.{db} => '.format(db=current_db) # else: # pattern = '! Offline => ' # input_str = raw_input(pattern) # # return input_str # # def parse_input(input_str, *args, **kwargs): # input_str = shlex.split(input_str.strip()) # command, args = destructurate(input_str) # return command.upper(), args # # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/client.py # class Client(object): # def __init__(self, *args, **kwargs): # self.protocol = kwargs.pop('protocol', 'tcp') # self.endpoint = kwargs.pop('endpoint', '127.0.0.1:4141') # self.host = "%s://%s" % (self.protocol, self.endpoint) # # self.context = None # self.socket = None # self.timeout = kwargs.pop('timeout', 10000) # # self.db_uid = None # self.db_name = None # # self.setup_socket() # # if self.ping(): # self.connect() # else: # failure_msg = 'No elevator server hanging on {0}://{1}'.format(self.protocol, self.endpoint) # output_result(FAILURE_STATUS, failure_msg) # # def __del__(self): # self.socket.close() # self.context.term() # # def ping(self, *args, **kwargs): # pings = True # timeout = kwargs.pop('timeout', 1000) # orig_timeout = self.timeout # self.socket.setsockopt(zmq.RCVTIMEO, timeout) # # request = Request(db_uid=None, command="PING", args=[]) # self.socket.send_multipart([request]) # # try: # self.socket.recv_multipart() # except zmq.core.error.ZMQError: # pings = False # # # Restore original timeout # self.timeout = orig_timeout # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # # return pings # # def connect(self, db_name=None, *args, **kwargs): # db_name = 'default' if db_name is None else db_name # status, datas = self.send_cmd(None, 'DBCONNECT', [db_name], *args, **kwargs) # # if status == FAILURE_STATUS: # return status, datas # else: # self.db_uid = datas # self.db_name = db_name # # def setup_socket(self): # self.context = zmq.Context() # self.socket = self.context.socket(zmq.XREQ) # self.socket.setsockopt(zmq.LINGER, 0) # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # self.socket.connect(self.host) # # def teardown_socket(self): # self.socket.close() # self.context.term() # # def _process_request(self, command, arguments): # if command in ["MGET"] and arguments: # return command, [arguments] # return command, arguments # # def _process_response(self, req_cmd, res_datas): # if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: # return res_datas[0] # return res_datas # # def send_cmd(self, db_uid, command, arguments, *args, **kwargs): # command, arguments = self._process_request(command, arguments) # self.socket.send_multipart([Request(db_uid=db_uid, # command=command, # args=arguments, # meta={})],) # # try: # raw_header, raw_response = self.socket.recv_multipart() # header = ResponseHeader(raw_header) # response = Response(raw_response) # # if header.status == FAILURE_STATUS: # return fail(ELEVATOR_ERROR[header.err_code], header.err_msg) # except zmq.core.error.ZMQError: # return fail("TimeoutError", "Server did not respond in time") # # return success(self._process_response(command, response.datas)) # # Path: elevator_cli/args.py # def init_parser(): # parser = argparse.ArgumentParser(description="Elevator command line client") # parser.add_argument('-c', '--config', action='store', type=str, # default=DEFAULT_CONFIG_FILE) # # tcp or ipc # parser.add_argument('-t', '--protocol', action='store', type=str, # default='tcp') # parser.add_argument('-b', '--endpoint', action='store', type=str, # default='127.0.0.1:4141') # # return parser which might include code, classes, or functions. Output only the next line.
input_str = prompt(current_db=client.db_name)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from __future__ import absolute_import def main(): args = init_parser().parse_args(sys.argv[1:]) client = Client(protocol=args.protocol, endpoint=args.endpoint) try: while True: input_str = prompt(current_db=client.db_name) if input_str: <|code_end|> using the current file's imports: import sys from .io import prompt, parse_input, output_result from .client import Client from .args import init_parser and any relevant context from other files: # Path: elevator_cli/io.py # def prompt(*args, **kwargs): # current_db = kwargs.pop('current_db', 'default') # # if current_db: # pattern = '@ Elevator.{db} => '.format(db=current_db) # else: # pattern = '! Offline => ' # input_str = raw_input(pattern) # # return input_str # # def parse_input(input_str, *args, **kwargs): # input_str = shlex.split(input_str.strip()) # command, args = destructurate(input_str) # return command.upper(), args # # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/client.py # class Client(object): # def __init__(self, *args, **kwargs): # self.protocol = kwargs.pop('protocol', 'tcp') # self.endpoint = kwargs.pop('endpoint', '127.0.0.1:4141') # self.host = "%s://%s" % (self.protocol, self.endpoint) # # self.context = None # self.socket = None # self.timeout = kwargs.pop('timeout', 10000) # # self.db_uid = None # self.db_name = None # # self.setup_socket() # # if self.ping(): # self.connect() # else: # failure_msg = 'No elevator server hanging on {0}://{1}'.format(self.protocol, self.endpoint) # output_result(FAILURE_STATUS, failure_msg) # # def __del__(self): # self.socket.close() # self.context.term() # # def ping(self, *args, **kwargs): # pings = True # timeout = kwargs.pop('timeout', 1000) # orig_timeout = self.timeout # self.socket.setsockopt(zmq.RCVTIMEO, timeout) # # request = Request(db_uid=None, command="PING", args=[]) # self.socket.send_multipart([request]) # # try: # self.socket.recv_multipart() # except zmq.core.error.ZMQError: # pings = False # # # Restore original timeout # self.timeout = orig_timeout # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # # return pings # # def connect(self, db_name=None, *args, **kwargs): # db_name = 'default' if db_name is None else db_name # status, datas = self.send_cmd(None, 'DBCONNECT', [db_name], *args, **kwargs) # # if status == FAILURE_STATUS: # return status, datas # else: # self.db_uid = datas # self.db_name = db_name # # def setup_socket(self): # self.context = zmq.Context() # self.socket = self.context.socket(zmq.XREQ) # self.socket.setsockopt(zmq.LINGER, 0) # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # self.socket.connect(self.host) # # def teardown_socket(self): # self.socket.close() # self.context.term() # # def _process_request(self, command, arguments): # if command in ["MGET"] and arguments: # return command, [arguments] # return command, arguments # # def _process_response(self, req_cmd, res_datas): # if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: # return res_datas[0] # return res_datas # # def send_cmd(self, db_uid, command, arguments, *args, **kwargs): # command, arguments = self._process_request(command, arguments) # self.socket.send_multipart([Request(db_uid=db_uid, # command=command, # args=arguments, # meta={})],) # # try: # raw_header, raw_response = self.socket.recv_multipart() # header = ResponseHeader(raw_header) # response = Response(raw_response) # # if header.status == FAILURE_STATUS: # return fail(ELEVATOR_ERROR[header.err_code], header.err_msg) # except zmq.core.error.ZMQError: # return fail("TimeoutError", "Server did not respond in time") # # return success(self._process_response(command, response.datas)) # # Path: elevator_cli/args.py # def init_parser(): # parser = argparse.ArgumentParser(description="Elevator command line client") # parser.add_argument('-c', '--config', action='store', type=str, # default=DEFAULT_CONFIG_FILE) # # tcp or ipc # parser.add_argument('-t', '--protocol', action='store', type=str, # default='tcp') # parser.add_argument('-b', '--endpoint', action='store', type=str, # default='127.0.0.1:4141') # # return parser . Output only the next line.
command, args = parse_input(input_str)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from __future__ import absolute_import def main(): args = init_parser().parse_args(sys.argv[1:]) client = Client(protocol=args.protocol, endpoint=args.endpoint) try: while True: input_str = prompt(current_db=client.db_name) if input_str: command, args = parse_input(input_str) if not command == "DBCONNECT": status, result = client.send_cmd(client.db_uid, command, args) <|code_end|> . Write the next line using the current file imports: import sys from .io import prompt, parse_input, output_result from .client import Client from .args import init_parser and context from other files: # Path: elevator_cli/io.py # def prompt(*args, **kwargs): # current_db = kwargs.pop('current_db', 'default') # # if current_db: # pattern = '@ Elevator.{db} => '.format(db=current_db) # else: # pattern = '! Offline => ' # input_str = raw_input(pattern) # # return input_str # # def parse_input(input_str, *args, **kwargs): # input_str = shlex.split(input_str.strip()) # command, args = destructurate(input_str) # return command.upper(), args # # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/client.py # class Client(object): # def __init__(self, *args, **kwargs): # self.protocol = kwargs.pop('protocol', 'tcp') # self.endpoint = kwargs.pop('endpoint', '127.0.0.1:4141') # self.host = "%s://%s" % (self.protocol, self.endpoint) # # self.context = None # self.socket = None # self.timeout = kwargs.pop('timeout', 10000) # # self.db_uid = None # self.db_name = None # # self.setup_socket() # # if self.ping(): # self.connect() # else: # failure_msg = 'No elevator server hanging on {0}://{1}'.format(self.protocol, self.endpoint) # output_result(FAILURE_STATUS, failure_msg) # # def __del__(self): # self.socket.close() # self.context.term() # # def ping(self, *args, **kwargs): # pings = True # timeout = kwargs.pop('timeout', 1000) # orig_timeout = self.timeout # self.socket.setsockopt(zmq.RCVTIMEO, timeout) # # request = Request(db_uid=None, command="PING", args=[]) # self.socket.send_multipart([request]) # # try: # self.socket.recv_multipart() # except zmq.core.error.ZMQError: # pings = False # # # Restore original timeout # self.timeout = orig_timeout # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # # return pings # # def connect(self, db_name=None, *args, **kwargs): # db_name = 'default' if db_name is None else db_name # status, datas = self.send_cmd(None, 'DBCONNECT', [db_name], *args, **kwargs) # # if status == FAILURE_STATUS: # return status, datas # else: # self.db_uid = datas # self.db_name = db_name # # def setup_socket(self): # self.context = zmq.Context() # self.socket = self.context.socket(zmq.XREQ) # self.socket.setsockopt(zmq.LINGER, 0) # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # self.socket.connect(self.host) # # def teardown_socket(self): # self.socket.close() # self.context.term() # # def _process_request(self, command, arguments): # if command in ["MGET"] and arguments: # return command, [arguments] # return command, arguments # # def _process_response(self, req_cmd, res_datas): # if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: # return res_datas[0] # return res_datas # # def send_cmd(self, db_uid, command, arguments, *args, **kwargs): # command, arguments = self._process_request(command, arguments) # self.socket.send_multipart([Request(db_uid=db_uid, # command=command, # args=arguments, # meta={})],) # # try: # raw_header, raw_response = self.socket.recv_multipart() # header = ResponseHeader(raw_header) # response = Response(raw_response) # # if header.status == FAILURE_STATUS: # return fail(ELEVATOR_ERROR[header.err_code], header.err_msg) # except zmq.core.error.ZMQError: # return fail("TimeoutError", "Server did not respond in time") # # return success(self._process_response(command, response.datas)) # # Path: elevator_cli/args.py # def init_parser(): # parser = argparse.ArgumentParser(description="Elevator command line client") # parser.add_argument('-c', '--config', action='store', type=str, # default=DEFAULT_CONFIG_FILE) # # tcp or ipc # parser.add_argument('-t', '--protocol', action='store', type=str, # default='tcp') # parser.add_argument('-b', '--endpoint', action='store', type=str, # default='127.0.0.1:4141') # # return parser , which may include functions, classes, or code. Output only the next line.
output_result(status, result)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. from __future__ import absolute_import def main(): args = init_parser().parse_args(sys.argv[1:]) <|code_end|> , generate the next line using the imports in this file: import sys from .io import prompt, parse_input, output_result from .client import Client from .args import init_parser and context (functions, classes, or occasionally code) from other files: # Path: elevator_cli/io.py # def prompt(*args, **kwargs): # current_db = kwargs.pop('current_db', 'default') # # if current_db: # pattern = '@ Elevator.{db} => '.format(db=current_db) # else: # pattern = '! Offline => ' # input_str = raw_input(pattern) # # return input_str # # def parse_input(input_str, *args, **kwargs): # input_str = shlex.split(input_str.strip()) # command, args = destructurate(input_str) # return command.upper(), args # # def output_result(status, result, *args, **kwargs): # if result: # if status == FAILURE_STATUS: # puts(colored.red(str(result))) # else: # puts(str(result)) # # Path: elevator_cli/client.py # class Client(object): # def __init__(self, *args, **kwargs): # self.protocol = kwargs.pop('protocol', 'tcp') # self.endpoint = kwargs.pop('endpoint', '127.0.0.1:4141') # self.host = "%s://%s" % (self.protocol, self.endpoint) # # self.context = None # self.socket = None # self.timeout = kwargs.pop('timeout', 10000) # # self.db_uid = None # self.db_name = None # # self.setup_socket() # # if self.ping(): # self.connect() # else: # failure_msg = 'No elevator server hanging on {0}://{1}'.format(self.protocol, self.endpoint) # output_result(FAILURE_STATUS, failure_msg) # # def __del__(self): # self.socket.close() # self.context.term() # # def ping(self, *args, **kwargs): # pings = True # timeout = kwargs.pop('timeout', 1000) # orig_timeout = self.timeout # self.socket.setsockopt(zmq.RCVTIMEO, timeout) # # request = Request(db_uid=None, command="PING", args=[]) # self.socket.send_multipart([request]) # # try: # self.socket.recv_multipart() # except zmq.core.error.ZMQError: # pings = False # # # Restore original timeout # self.timeout = orig_timeout # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # # return pings # # def connect(self, db_name=None, *args, **kwargs): # db_name = 'default' if db_name is None else db_name # status, datas = self.send_cmd(None, 'DBCONNECT', [db_name], *args, **kwargs) # # if status == FAILURE_STATUS: # return status, datas # else: # self.db_uid = datas # self.db_name = db_name # # def setup_socket(self): # self.context = zmq.Context() # self.socket = self.context.socket(zmq.XREQ) # self.socket.setsockopt(zmq.LINGER, 0) # self.socket.setsockopt(zmq.RCVTIMEO, self.timeout) # self.socket.connect(self.host) # # def teardown_socket(self): # self.socket.close() # self.context.term() # # def _process_request(self, command, arguments): # if command in ["MGET"] and arguments: # return command, [arguments] # return command, arguments # # def _process_response(self, req_cmd, res_datas): # if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas: # return res_datas[0] # return res_datas # # def send_cmd(self, db_uid, command, arguments, *args, **kwargs): # command, arguments = self._process_request(command, arguments) # self.socket.send_multipart([Request(db_uid=db_uid, # command=command, # args=arguments, # meta={})],) # # try: # raw_header, raw_response = self.socket.recv_multipart() # header = ResponseHeader(raw_header) # response = Response(raw_response) # # if header.status == FAILURE_STATUS: # return fail(ELEVATOR_ERROR[header.err_code], header.err_msg) # except zmq.core.error.ZMQError: # return fail("TimeoutError", "Server did not respond in time") # # return success(self._process_response(command, response.datas)) # # Path: elevator_cli/args.py # def init_parser(): # parser = argparse.ArgumentParser(description="Elevator command line client") # parser.add_argument('-c', '--config', action='store', type=str, # default=DEFAULT_CONFIG_FILE) # # tcp or ipc # parser.add_argument('-t', '--protocol', action='store', type=str, # default='tcp') # parser.add_argument('-b', '--endpoint', action='store', type=str, # default='127.0.0.1:4141') # # return parser . Output only the next line.
client = Client(protocol=args.protocol,
Given snippet: <|code_start|> [VALUE_ERROR, "Batch only accepts sequences (list, tuples,...)"]) except TypeError: return (FAILURE_STATUS, [TYPE_ERROR, "Invalid type supplied"]) db.Write(batch) return success() def DBConnect(self, *args, **kwargs): db_name = args[0] if (not db_name or not self.databases.exists(db_name)): error_msg = "Database %s doesn't exist" % db_name errors_logger.error(error_msg) return failure(DATABASE_ERROR, error_msg) db_uid = self.databases.index['name_to_uid'][db_name] if self.databases[db_uid]['status'] == self.databases.STATUSES.UNMOUNTED: self.databases.mount(db_name) return success(db_uid) def DBMount(self, db_name, *args, **kwargs): return self.databases.mount(db_name) def DBUmount(self, db_name, *args, **kwargs): return self.databases.umount(db_name) def DBCreate(self, db, db_name, db_options=None, *args, **kwargs): <|code_end|> , continue by predicting the next line. Consider current file imports: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 which might include code, classes, or functions. Output only the next line.
db_options = DatabaseOptions(**db_options) if db_options else DatabaseOptions()
Given snippet: <|code_start|> 'GET': self.Get, 'PUT': self.Put, 'DELETE': self.Delete, 'RANGE': self.Range, 'SLICE': self.Slice, 'BATCH': self.Batch, 'MGET': self.MGet, 'DBCONNECT': self.DBConnect, 'DBMOUNT': self.DBMount, 'DBUMOUNT': self.DBUmount, 'DBCREATE': self.DBCreate, 'DBDROP': self.DBDrop, 'DBLIST': self.DBList, 'DBREPAIR': self.DBRepair, } self.context = {} def Get(self, db, key, *args, **kwargs): """ Handles GET message command. Executes a Get operation over the leveldb backend. db => LevelDB object *args => (key) to fetch """ try: return success(db.Get(key)) except KeyError: error_msg = "Key %r does not exist" % key errors_logger.exception(error_msg) <|code_end|> , continue by predicting the next line. Consider current file imports: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 which might include code, classes, or functions. Output only the next line.
return failure(KEY_ERROR, error_msg)
Given the following code snippet before the placeholder: <|code_start|> def get_or_none(key, context): try: res = db.Get(key) except KeyError: warning_msg = "Key {0} does not exist".format(key) context['status'] = WARNING_STATUS errors_logger.warning(warning_msg) res = None return res context = {'status': SUCCESS_STATUS} value = [get_or_none(key, context) for key in keys] status = context['status'] return status, value def Put(self, db, key, value, *args, **kwargs): """ Handles Put message command. Executes a Put operation over the leveldb backend. db => LevelDB object *args => (key, value) to update """ try: return success(db.Put(key, value)) except TypeError: error_msg = "Unsupported value type : %s" % type(value) errors_logger.exception(error_msg) <|code_end|> , predict the next line using imports from the current file: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context including class names, function names, and sometimes code from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
return failure(TYPE_ERROR, error_msg)
Given the code snippet: <|code_start|> batch = leveldb.WriteBatch() batch_actions = { SIGNAL_BATCH_PUT: batch.Put, SIGNAL_BATCH_DELETE: batch.Delete, } try: for command in collection: signal, args = destructurate(command) batch_actions[signal](*args) except KeyError: # Unrecognized signal return (FAILURE_STATUS, [SIGNAL_ERROR, "Unrecognized signal received : %r" % signal]) except ValueError: return (FAILURE_STATUS, [VALUE_ERROR, "Batch only accepts sequences (list, tuples,...)"]) except TypeError: return (FAILURE_STATUS, [TYPE_ERROR, "Invalid type supplied"]) db.Write(batch) return success() def DBConnect(self, *args, **kwargs): db_name = args[0] if (not db_name or not self.databases.exists(db_name)): error_msg = "Database %s doesn't exist" % db_name errors_logger.error(error_msg) <|code_end|> , generate the next line using the imports in this file: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context (functions, classes, or occasionally code) from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
return failure(DATABASE_ERROR, error_msg)
Predict the next line after this snippet: <|code_start|> db_snapshot = db.CreateSnapshot() it = db_snapshot.RangeIter(key_from) value = [] pos = 0 while pos < offset: try: value.append(it.next()) except StopIteration: break pos += 1 return success(value) def Batch(self, db, collection, *args, **kwargs): batch = leveldb.WriteBatch() batch_actions = { SIGNAL_BATCH_PUT: batch.Put, SIGNAL_BATCH_DELETE: batch.Delete, } try: for command in collection: signal, args = destructurate(command) batch_actions[signal](*args) except KeyError: # Unrecognized signal return (FAILURE_STATUS, [SIGNAL_ERROR, "Unrecognized signal received : %r" % signal]) except ValueError: return (FAILURE_STATUS, <|code_end|> using the current file's imports: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and any relevant context from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
[VALUE_ERROR, "Batch only accepts sequences (list, tuples,...)"])
Predict the next line after this snippet: <|code_start|> def DBRepair(self, db, db_uid, *args, **kwargs): db_path = self.databases['paths_index'][db_uid] leveldb.RepairDB(db_path) return success() def _gen_response(self, request, cmd_status, cmd_value): if cmd_status == FAILURE_STATUS: header = ResponseHeader(status=cmd_status, err_code=cmd_value[0], err_msg=cmd_value[1]) content = ResponseContent(datas=None) else: if 'compression' in request.meta: compression = request.meta['compression'] else: compression = False header = ResponseHeader(status=cmd_status, compression=compression) content = ResponseContent(datas=cmd_value, compression=compression) return header, content def command(self, message, *args, **kwargs): status = SUCCESS_STATUS err_code, err_msg = None, None # DB does not exist if message.db_uid and (not message.db_uid in self.databases): error_msg = "Database %s doesn't exist" % message.db_uid errors_logger.error(error_msg) <|code_end|> using the current file's imports: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and any relevant context from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
status, value = failure(RUNTIME_ERROR, error_msg)
Here is a snippet: <|code_start|> starting a `key_from`""" # Operates over a snapshot in order to return # a consistent state of the db db_snapshot = db.CreateSnapshot() it = db_snapshot.RangeIter(key_from) value = [] pos = 0 while pos < offset: try: value.append(it.next()) except StopIteration: break pos += 1 return success(value) def Batch(self, db, collection, *args, **kwargs): batch = leveldb.WriteBatch() batch_actions = { SIGNAL_BATCH_PUT: batch.Put, SIGNAL_BATCH_DELETE: batch.Delete, } try: for command in collection: signal, args = destructurate(command) batch_actions[signal](*args) except KeyError: # Unrecognized signal return (FAILURE_STATUS, <|code_end|> . Write the next line using the current file imports: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 , which may include functions, classes, or code. Output only the next line.
[SIGNAL_ERROR, "Unrecognized signal received : %r" % signal])
Continue the code snippet: <|code_start|> 'DBREPAIR': self.DBRepair, } self.context = {} def Get(self, db, key, *args, **kwargs): """ Handles GET message command. Executes a Get operation over the leveldb backend. db => LevelDB object *args => (key) to fetch """ try: return success(db.Get(key)) except KeyError: error_msg = "Key %r does not exist" % key errors_logger.exception(error_msg) return failure(KEY_ERROR, error_msg) def MGet(self, db, keys, *args, **kwargs): def get_or_none(key, context): try: res = db.Get(key) except KeyError: warning_msg = "Key {0} does not exist".format(key) context['status'] = WARNING_STATUS errors_logger.warning(warning_msg) res = None return res <|code_end|> . Use current file imports: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context (classes, functions, or code) from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
context = {'status': SUCCESS_STATUS}
Given the following code snippet before the placeholder: <|code_start|> """Returns a slice of the db. `offset` keys, starting a `key_from`""" # Operates over a snapshot in order to return # a consistent state of the db db_snapshot = db.CreateSnapshot() it = db_snapshot.RangeIter(key_from) value = [] pos = 0 while pos < offset: try: value.append(it.next()) except StopIteration: break pos += 1 return success(value) def Batch(self, db, collection, *args, **kwargs): batch = leveldb.WriteBatch() batch_actions = { SIGNAL_BATCH_PUT: batch.Put, SIGNAL_BATCH_DELETE: batch.Delete, } try: for command in collection: signal, args = destructurate(command) batch_actions[signal](*args) except KeyError: # Unrecognized signal <|code_end|> , predict the next line using imports from the current file: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context including class names, function names, and sometimes code from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
return (FAILURE_STATUS,
Given the following code snippet before the placeholder: <|code_start|> 'DBMOUNT': self.DBMount, 'DBUMOUNT': self.DBUmount, 'DBCREATE': self.DBCreate, 'DBDROP': self.DBDrop, 'DBLIST': self.DBList, 'DBREPAIR': self.DBRepair, } self.context = {} def Get(self, db, key, *args, **kwargs): """ Handles GET message command. Executes a Get operation over the leveldb backend. db => LevelDB object *args => (key) to fetch """ try: return success(db.Get(key)) except KeyError: error_msg = "Key %r does not exist" % key errors_logger.exception(error_msg) return failure(KEY_ERROR, error_msg) def MGet(self, db, keys, *args, **kwargs): def get_or_none(key, context): try: res = db.Get(key) except KeyError: warning_msg = "Key {0} does not exist".format(key) <|code_end|> , predict the next line using imports from the current file: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context including class names, function names, and sometimes code from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
context['status'] = WARNING_STATUS
Using the snippet: <|code_start|> `key_from and `key_to`""" # Operate over a snapshot in order to return # a consistent state of the db db_snapshot = db.CreateSnapshot() value = list(db_snapshot.RangeIter(key_from, key_to)) return success(value) def Slice(self, db, key_from, offset, *args, **kwargs): """Returns a slice of the db. `offset` keys, starting a `key_from`""" # Operates over a snapshot in order to return # a consistent state of the db db_snapshot = db.CreateSnapshot() it = db_snapshot.RangeIter(key_from) value = [] pos = 0 while pos < offset: try: value.append(it.next()) except StopIteration: break pos += 1 return success(value) def Batch(self, db, collection, *args, **kwargs): batch = leveldb.WriteBatch() batch_actions = { <|code_end|> , determine the next line of code. You have imports: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context (class names, function names, or code) available: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
SIGNAL_BATCH_PUT: batch.Put,
Given the code snippet: <|code_start|> # Operate over a snapshot in order to return # a consistent state of the db db_snapshot = db.CreateSnapshot() value = list(db_snapshot.RangeIter(key_from, key_to)) return success(value) def Slice(self, db, key_from, offset, *args, **kwargs): """Returns a slice of the db. `offset` keys, starting a `key_from`""" # Operates over a snapshot in order to return # a consistent state of the db db_snapshot = db.CreateSnapshot() it = db_snapshot.RangeIter(key_from) value = [] pos = 0 while pos < offset: try: value.append(it.next()) except StopIteration: break pos += 1 return success(value) def Batch(self, db, collection, *args, **kwargs): batch = leveldb.WriteBatch() batch_actions = { SIGNAL_BATCH_PUT: batch.Put, <|code_end|> , generate the next line using the imports in this file: import leveldb import logging from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context (functions, classes, or occasionally code) from other files: # Path: debian/elevator/usr/share/pyshared/elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['paranoid_checks'] = False # self['block_cache_size'] = 8 * (2 << 20) # self['write_buffer_size'] = 2 * (2 << 20) # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: debian/elevator/usr/share/pyshared/elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 . Output only the next line.
SIGNAL_BATCH_DELETE: batch.Delete,
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import class RequestTest(unittest2.TestCase): def setUp(self): pass def tearDown(self): pass @raises(MessageFormatError) def test_request_with_missing_mandatory_arguments(self): request = msgpack.packb({ 'uid': '123-456-789', 'cmd': 'GET', }) <|code_end|> using the current file's imports: import unittest2 import msgpack from nose.tools import raises from elevator.message import Request, ResponseContent,\ ResponseHeader, MessageFormatError from elevator.constants import * and any relevant context from other files: # Path: elevator/message.py # class Request(object): # """Handler objects for client requests messages # # Format : # { # 'meta': {...}, # 'cmd': 'GET', # 'uid': 'mysuperduperdbuid', # 'args': [...], # } # """ # def __init__(self, raw_message): # self.message = msgpack.unpackb(raw_message) # self.meta = self.message.get('meta', {}) # activity_logger.debug('<Request ' + str(self.message) + '>') # # try: # self.db_uid = self.message.get('uid') # In some case db_uid should be None # self.command = self.message['cmd'] # self.data = self.message['args'] # __getitem__ will raise if !key # except KeyError: # errors_logger.exception("Invalid request message : %s" % self.message) # raise MessageFormatError("Invalid request message : %r" % self.message) # # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # class MessageFormatError(Exception): # def __init__(self, value): # self.value = value # # def __str__(self): # return repr(self.value) . Output only the next line.
request = Request(request)
Given the code snippet: <|code_start|> 'meta': { 'test': 'test', }, 'uid': '123-456-789', 'cmd': 'PUT', 'args': ['key', 'value'] }) request = Request(request) self.assertIsNotNone(request) self.assertTrue(hasattr(request, 'meta')) self.assertTrue(hasattr(request, 'db_uid')) self.assertTrue(hasattr(request, 'command')) self.assertTrue(hasattr(request, 'data')) self.assertEqual(request.meta, {'test': 'test'}) self.assertEqual(request.db_uid, '123-456-789') self.assertEqual(request.command, 'PUT') self.assertEqual(request.data, ('key', 'value')) class ResponseContentTest(unittest2.TestCase): def setUp(self): pass def tearDown(self): pass def test_success_response_with_values(self): <|code_end|> , generate the next line using the imports in this file: import unittest2 import msgpack from nose.tools import raises from elevator.message import Request, ResponseContent,\ ResponseHeader, MessageFormatError from elevator.constants import * and context (functions, classes, or occasionally code) from other files: # Path: elevator/message.py # class Request(object): # """Handler objects for client requests messages # # Format : # { # 'meta': {...}, # 'cmd': 'GET', # 'uid': 'mysuperduperdbuid', # 'args': [...], # } # """ # def __init__(self, raw_message): # self.message = msgpack.unpackb(raw_message) # self.meta = self.message.get('meta', {}) # activity_logger.debug('<Request ' + str(self.message) + '>') # # try: # self.db_uid = self.message.get('uid') # In some case db_uid should be None # self.command = self.message['cmd'] # self.data = self.message['args'] # __getitem__ will raise if !key # except KeyError: # errors_logger.exception("Invalid request message : %s" % self.message) # raise MessageFormatError("Invalid request message : %r" % self.message) # # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # class MessageFormatError(Exception): # def __init__(self, value): # self.value = value # # def __str__(self): # return repr(self.value) . Output only the next line.
response = ResponseContent(datas=['thisistheres'])
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual(request.data, ('key', 'value')) class ResponseContentTest(unittest2.TestCase): def setUp(self): pass def tearDown(self): pass def test_success_response_with_values(self): response = ResponseContent(datas=['thisistheres']) unpacked_response = msgpack.unpackb(response) self.assertIsInstance(unpacked_response, dict) self.assertIn('datas', unpacked_response) self.assertEqual(unpacked_response['datas'], ('thisistheres',)) @raises def test_success_response_without_values(self): ResponseContent() class ResponseHeaderTest(unittest2.TestCase): def setUp(self): pass def tearDown(self): pass def test_success_header(self): <|code_end|> , predict the next line using imports from the current file: import unittest2 import msgpack from nose.tools import raises from elevator.message import Request, ResponseContent,\ ResponseHeader, MessageFormatError from elevator.constants import * and context including class names, function names, and sometimes code from other files: # Path: elevator/message.py # class Request(object): # """Handler objects for client requests messages # # Format : # { # 'meta': {...}, # 'cmd': 'GET', # 'uid': 'mysuperduperdbuid', # 'args': [...], # } # """ # def __init__(self, raw_message): # self.message = msgpack.unpackb(raw_message) # self.meta = self.message.get('meta', {}) # activity_logger.debug('<Request ' + str(self.message) + '>') # # try: # self.db_uid = self.message.get('uid') # In some case db_uid should be None # self.command = self.message['cmd'] # self.data = self.message['args'] # __getitem__ will raise if !key # except KeyError: # errors_logger.exception("Invalid request message : %s" % self.message) # raise MessageFormatError("Invalid request message : %r" % self.message) # # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # class MessageFormatError(Exception): # def __init__(self, value): # self.value = value # # def __str__(self): # return repr(self.value) . Output only the next line.
header = ResponseHeader(status=SUCCESS_STATUS)
Given the code snippet: <|code_start|>from __future__ import absolute_import class RequestTest(unittest2.TestCase): def setUp(self): pass def tearDown(self): pass <|code_end|> , generate the next line using the imports in this file: import unittest2 import msgpack from nose.tools import raises from elevator.message import Request, ResponseContent,\ ResponseHeader, MessageFormatError from elevator.constants import * and context (functions, classes, or occasionally code) from other files: # Path: elevator/message.py # class Request(object): # """Handler objects for client requests messages # # Format : # { # 'meta': {...}, # 'cmd': 'GET', # 'uid': 'mysuperduperdbuid', # 'args': [...], # } # """ # def __init__(self, raw_message): # self.message = msgpack.unpackb(raw_message) # self.meta = self.message.get('meta', {}) # activity_logger.debug('<Request ' + str(self.message) + '>') # # try: # self.db_uid = self.message.get('uid') # In some case db_uid should be None # self.command = self.message['cmd'] # self.data = self.message['args'] # __getitem__ will raise if !key # except KeyError: # errors_logger.exception("Invalid request message : %s" % self.message) # raise MessageFormatError("Invalid request message : %r" % self.message) # # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # class MessageFormatError(Exception): # def __init__(self, value): # self.value = value # # def __str__(self): # return repr(self.value) . Output only the next line.
@raises(MessageFormatError)
Based on the snippet: <|code_start|> return failure(TYPE_ERROR, "Invalid type supplied") batch.write() return success() def Ping(self, *args, **kwargs): return success("PONG") def DBConnect(self, *args, **kwargs): db_name = args[0] if (not db_name or not self.databases.exists(db_name)): error_msg = "Database %s doesn't exist" % db_name errors_logger.error(error_msg) return failure(DATABASE_ERROR, error_msg) db_uid = self.databases.index['name_to_uid'][db_name] if self.databases[db_uid].status == self.databases.STATUSES.UNMOUNTED: self.databases.mount(db_name) return success(db_uid) def DBMount(self, db_name, *args, **kwargs): return self.databases.mount(db_name) def DBUmount(self, db_name, *args, **kwargs): return self.databases.umount(db_name) def DBCreate(self, db, db_name, db_options=None, *args, **kwargs): <|code_end|> , predict the immediate next line with the help of imports: import plyvel import logging import time from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context (classes, functions, sometimes code) from other files: # Path: elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc # self['paranoid_checks'] = False # self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo # self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: elevator/message.py # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # Path: elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 # # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator/helpers/internals.py # def failure(err_code, err_msg): # """Returns a formatted error status and content""" # return (FAILURE_STATUS, [err_code, err_msg]) # # def success(content=None): # """Returns a formatted success status and content""" # return (SUCCESS_STATUS, content) . Output only the next line.
db_options = DatabaseOptions(**db_options) if db_options else DatabaseOptions()
Predict the next line for this snippet: <|code_start|> if db_name in self.databases.index['name_to_uid']: error_msg = "Database %s already exists" % db_name errors_logger.error(error_msg) return failure(DATABASE_ERROR, error_msg) return self.databases.add(db_name, db_options) def DBDrop(self, db, db_name, *args, **kwargs): if not self.databases.exists(db_name): error_msg = "Database %s does not exist" % db_name errors_logger.error(error_msg) return failure(DATABASE_ERROR, error_msg) status, content = self.databases.drop(db_name) return status, content def DBList(self, db, *args, **kwargs): return success(self.databases.list()) def DBRepair(self, db, db_uid, *args, **kwargs): db_path = self.databases['paths_index'][db_uid] plyvel.RepairDB(db_path) return success() def _gen_response(self, request, cmd_status, cmd_value): if cmd_status == FAILURE_STATUS: header = ResponseHeader(status=cmd_status, err_code=cmd_value[0], err_msg=cmd_value[1]) <|code_end|> with the help of current file imports: import plyvel import logging import time from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context from other files: # Path: elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc # self['paranoid_checks'] = False # self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo # self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: elevator/message.py # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # Path: elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 # # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator/helpers/internals.py # def failure(err_code, err_msg): # """Returns a formatted error status and content""" # return (FAILURE_STATUS, [err_code, err_msg]) # # def success(content=None): # """Returns a formatted success status and content""" # return (SUCCESS_STATUS, content) , which may contain function names, class names, or code. Output only the next line.
content = ResponseContent(datas=None)
Given the following code snippet before the placeholder: <|code_start|> db_options = DatabaseOptions(**db_options) if db_options else DatabaseOptions() if db_name in self.databases.index['name_to_uid']: error_msg = "Database %s already exists" % db_name errors_logger.error(error_msg) return failure(DATABASE_ERROR, error_msg) return self.databases.add(db_name, db_options) def DBDrop(self, db, db_name, *args, **kwargs): if not self.databases.exists(db_name): error_msg = "Database %s does not exist" % db_name errors_logger.error(error_msg) return failure(DATABASE_ERROR, error_msg) status, content = self.databases.drop(db_name) return status, content def DBList(self, db, *args, **kwargs): return success(self.databases.list()) def DBRepair(self, db, db_uid, *args, **kwargs): db_path = self.databases['paths_index'][db_uid] plyvel.RepairDB(db_path) return success() def _gen_response(self, request, cmd_status, cmd_value): if cmd_status == FAILURE_STATUS: <|code_end|> , predict the next line using imports from the current file: import plyvel import logging import time from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context including class names, function names, and sometimes code from other files: # Path: elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc # self['paranoid_checks'] = False # self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo # self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: elevator/message.py # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # Path: elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 # # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator/helpers/internals.py # def failure(err_code, err_msg): # """Returns a formatted error status and content""" # return (FAILURE_STATUS, [err_code, err_msg]) # # def success(content=None): # """Returns a formatted success status and content""" # return (SUCCESS_STATUS, content) . Output only the next line.
header = ResponseHeader(status=cmd_status, err_code=cmd_value[0], err_msg=cmd_value[1])
Given snippet: <|code_start|> 'DELETE': self.Delete, 'EXISTS': self.Exists, 'RANGE': self.Range, 'SLICE': self.Slice, 'BATCH': self.Batch, 'MGET': self.MGet, 'PING': self.Ping, 'DBCONNECT': self.DBConnect, 'DBMOUNT': self.DBMount, 'DBUMOUNT': self.DBUmount, 'DBCREATE': self.DBCreate, 'DBDROP': self.DBDrop, 'DBLIST': self.DBList, 'DBREPAIR': self.DBRepair, } self.context = {} def Get(self, db, key, *args, **kwargs): """ Handles GET message command. Executes a Get operation over the plyvel backend. db => LevelDB object *args => (key) to fetch """ value = db.get(key) if not value: error_msg = "Key %r does not exist" % key errors_logger.exception(error_msg) <|code_end|> , continue by predicting the next line. Consider current file imports: import plyvel import logging import time from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context: # Path: elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc # self['paranoid_checks'] = False # self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo # self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: elevator/message.py # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # Path: elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 # # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator/helpers/internals.py # def failure(err_code, err_msg): # """Returns a formatted error status and content""" # return (FAILURE_STATUS, [err_code, err_msg]) # # def success(content=None): # """Returns a formatted success status and content""" # return (SUCCESS_STATUS, content) which might include code, classes, or functions. Output only the next line.
return failure(KEY_ERROR, error_msg)
Predict the next line for this snippet: <|code_start|> status = SUCCESS_STATUS db_snapshot = db.snapshot() values = [None] * len(keys) min_key, max_key = min(keys), max(keys) keys_index = {k: index for index, k in enumerate(keys)} bound_range = db_snapshot.iterator(start=min_key, stop=max_key, include_stop=True) for key, value in bound_range: if key in keys_index: values[keys_index[key]] = value status = WARNING_STATUS if any(v is None for v in values) else status return status, values def Put(self, db, key, value, *args, **kwargs): """ Handles Put message command. Executes a Put operation over the plyvel backend. db => LevelDB object *args => (key, value) to update """ try: return success(db.put(key, value)) except TypeError: error_msg = "Unsupported value type : %s" % type(value) errors_logger.exception(error_msg) <|code_end|> with the help of current file imports: import plyvel import logging import time from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context from other files: # Path: elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc # self['paranoid_checks'] = False # self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo # self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: elevator/message.py # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # Path: elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 # # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator/helpers/internals.py # def failure(err_code, err_msg): # """Returns a formatted error status and content""" # return (FAILURE_STATUS, [err_code, err_msg]) # # def success(content=None): # """Returns a formatted success status and content""" # return (SUCCESS_STATUS, content) , which may contain function names, class names, or code. Output only the next line.
return failure(TYPE_ERROR, error_msg)
Next line prediction: <|code_start|> batch = db.write_batch() batch_actions = { SIGNAL_BATCH_PUT: batch.put, SIGNAL_BATCH_DELETE: batch.delete, } try: for command in collection: signal, args = destructurate(command) batch_actions[signal](*args) except KeyError: # Unrecognized signal return failure(SIGNAL_ERROR, "Unrecognized signal received : %r" % signal) except ValueError: return failure(VALUE_ERROR, "Batch only accepts sequences (list, tuples,...)") except TypeError: return failure(TYPE_ERROR, "Invalid type supplied") batch.write() return success() def Ping(self, *args, **kwargs): return success("PONG") def DBConnect(self, *args, **kwargs): db_name = args[0] if (not db_name or not self.databases.exists(db_name)): error_msg = "Database %s doesn't exist" % db_name errors_logger.error(error_msg) <|code_end|> . Use current file imports: (import plyvel import logging import time from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success) and context including class names, function names, or small code snippets from other files: # Path: elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc # self['paranoid_checks'] = False # self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo # self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: elevator/message.py # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # Path: elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 # # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator/helpers/internals.py # def failure(err_code, err_msg): # """Returns a formatted error status and content""" # return (FAILURE_STATUS, [err_code, err_msg]) # # def success(content=None): # """Returns a formatted success status and content""" # return (SUCCESS_STATUS, content) . Output only the next line.
return failure(DATABASE_ERROR, error_msg)
Given snippet: <|code_start|> it = db_snapshot.iterator(start=key_from, include_key=include_key, include_value=include_value, include_stop=True) value = [] pos = 0 while pos < offset: try: value.append(it.next()) except StopIteration: break pos += 1 return success(value) def Batch(self, db, collection, *args, **kwargs): batch = db.write_batch() batch_actions = { SIGNAL_BATCH_PUT: batch.put, SIGNAL_BATCH_DELETE: batch.delete, } try: for command in collection: signal, args = destructurate(command) batch_actions[signal](*args) except KeyError: # Unrecognized signal return failure(SIGNAL_ERROR, "Unrecognized signal received : %r" % signal) except ValueError: <|code_end|> , continue by predicting the next line. Consider current file imports: import plyvel import logging import time from .db import DatabaseOptions from .message import ResponseContent, ResponseHeader from .constants import KEY_ERROR, TYPE_ERROR, DATABASE_ERROR,\ VALUE_ERROR, RUNTIME_ERROR, SIGNAL_ERROR,\ SUCCESS_STATUS, FAILURE_STATUS, WARNING_STATUS,\ SIGNAL_BATCH_PUT, SIGNAL_BATCH_DELETE from .utils.patterns import destructurate from .helpers.internals import failure, success and context: # Path: elevator/db.py # class DatabaseOptions(dict): # def __init__(self, *args, **kwargs): # self['create_if_missing'] = True # self['error_if_exists'] = False # self['bloom_filter_bits'] = 10 # Value recommended by leveldb doc # self['paranoid_checks'] = False # self['lru_cache_size'] = 512 * (1 << 20) # 512 Mo # self['write_buffer_size'] = 4 * (1 << 20) # 4 Mo # self['block_size'] = 4096 # self['max_open_files'] = 1000 # # for key, value in kwargs.iteritems(): # if key in self: # self[key] = value # # Path: elevator/message.py # class ResponseContent(tuple): # """Handler objects for responses messages # # Format: # { # 'meta': { # 'status': 1|0|-1, # 'err_code': null|0|1|[...], # 'err_msg': '', # }, # 'datas': [...], # } # """ # def __new__(cls, *args, **kwargs): # response = { # 'datas': cls._format_datas(kwargs['datas']), # } # activity_logger.debug('<Response ' + str(response['datas']) + '>') # msg = msgpack.packb(response) # # if kwargs.pop('compression', False) is True: # msg = lz4.dumps(msg) # # return msg # # @classmethod # def _format_datas(cls, datas): # if datas and not isinstance(datas, (tuple, list)): # datas = [datas] # return datas # # class ResponseHeader(dict): # def __new__(cls, *args, **kwargs): # header = { # 'status': kwargs.pop('status'), # 'err_code': kwargs.pop('err_code', None), # 'err_msg': kwargs.pop('err_msg', None), # 'compression': kwargs.pop('compression', False) # } # activity_logger.debug('<ResponseHeader ' + str(header) + '>') # # for key, value in kwargs.iteritems(): # header.update({key: value}) # # return msgpack.packb(header) # # Path: elevator/constants.py # KEY_ERROR = 1 # # TYPE_ERROR = 0 # # DATABASE_ERROR = 6 # # VALUE_ERROR = 2 # # RUNTIME_ERROR = 4 # # SIGNAL_ERROR = 7 # # SUCCESS_STATUS = 1 # # FAILURE_STATUS = -1 # # WARNING_STATUS = -2 # # SIGNAL_BATCH_PUT = 1 # # SIGNAL_BATCH_DELETE = 0 # # Path: elevator/utils/patterns.py # def destructurate(container): # try: # return container[0], container[1:] # except (KeyError, AttributeError): # raise DestructurationError("Can't destructurate a non-sequence container") # # Path: elevator/helpers/internals.py # def failure(err_code, err_msg): # """Returns a formatted error status and content""" # return (FAILURE_STATUS, [err_code, err_msg]) # # def success(content=None): # """Returns a formatted success status and content""" # return (SUCCESS_STATUS, content) which might include code, classes, or functions. Output only the next line.
return failure(VALUE_ERROR, "Batch only accepts sequences (list, tuples,...)")