code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
OPENJP2.opj_decode_tile_data.argtypes = [CODEC_TYPE,
ctypes.c_uint32,
ctypes.POINTER(ctypes.c_uint8),
ctypes.c_uint32,
STREAM_TYPE_... | def decode_tile_data(codec, tidx, data, data_size, stream) | Reads tile data.
Wraps the openjp2 library function opj_decode_tile_data.
Parameters
----------
codec : CODEC_TYPE
The JPEG2000 codec
tile_index : int
The index of the tile being decoded
data : array
Holds a memory block into which data will be decoded.
data_size : ... | 2.459902 | 2.293536 | 1.072537 |
OPENJP2.opj_create_decompress.argtypes = [CODEC_FORMAT_TYPE]
OPENJP2.opj_create_decompress.restype = CODEC_TYPE
codec = OPENJP2.opj_create_decompress(codec_format)
return codec | def create_decompress(codec_format) | Creates a J2K/JP2 decompress structure.
Wraps the openjp2 library function opj_create_decompress.
Parameters
----------
codec_format : int
Specifies codec to select. Should be one of CODEC_J2K or CODEC_JP2.
Returns
-------
codec : Reference to CODEC_TYPE instance. | 3.16206 | 3.017767 | 1.047814 |
OPENJP2.opj_destroy_codec.argtypes = [CODEC_TYPE]
OPENJP2.opj_destroy_codec.restype = ctypes.c_void_p
OPENJP2.opj_destroy_codec(codec) | def destroy_codec(codec) | Destroy a decompressor handle.
Wraps the openjp2 library function opj_destroy_codec.
Parameters
----------
codec : CODEC_TYPE
Decompressor handle to destroy. | 3.347893 | 2.826657 | 1.1844 |
OPENJP2.opj_encode.argtypes = [CODEC_TYPE, STREAM_TYPE_P]
OPENJP2.opj_encode.restype = check_error
OPENJP2.opj_encode(codec, stream) | def encode(codec, stream) | Wraps openjp2 library function opj_encode.
Encode an image into a JPEG 2000 codestream.
Parameters
----------
codec : CODEC_TYPE
The jpeg2000 codec.
stream : STREAM_TYPE_P
The stream to which data is written.
Raises
------
RuntimeError
If the OpenJPEG library r... | 5.743344 | 3.745041 | 1.533586 |
OPENJP2.opj_get_decoded_tile.argtypes = [CODEC_TYPE,
STREAM_TYPE_P,
ctypes.POINTER(ImageType),
ctypes.c_uint32]
OPENJP2.opj_get_decoded_tile.restype = check_error
OPEN... | def get_decoded_tile(codec, stream, imagep, tile_index) | get the decoded tile from the codec
Wraps the openjp2 library function opj_get_decoded_tile.
Parameters
----------
codec : CODEC_TYPE
The jpeg2000 codec.
stream : STREAM_TYPE_P
The input stream.
image : ImageType
Output image structure.
tiler_index : int
Ind... | 3.553562 | 2.676682 | 1.3276 |
OPENJP2.opj_end_compress.argtypes = [CODEC_TYPE, STREAM_TYPE_P]
OPENJP2.opj_end_compress.restype = check_error
OPENJP2.opj_end_compress(codec, stream) | def end_compress(codec, stream) | End of compressing the current image.
Wraps the openjp2 library function opj_end_compress.
Parameters
----------
codec : CODEC_TYPE
Compressor handle.
stream : STREAM_TYPE_P
Output stream buffer.
Raises
------
RuntimeError
If the OpenJPEG library routine opj_en... | 4.196396 | 3.177088 | 1.320831 |
OPENJP2.opj_end_decompress.argtypes = [CODEC_TYPE, STREAM_TYPE_P]
OPENJP2.opj_end_decompress.restype = check_error
OPENJP2.opj_end_decompress(codec, stream) | def end_decompress(codec, stream) | End of decompressing the current image.
Wraps the openjp2 library function opj_end_decompress.
Parameters
----------
codec : CODEC_TYPE
Compressor handle.
stream : STREAM_TYPE_P
Output stream buffer.
Raises
------
RuntimeError
If the OpenJPEG library routine op... | 3.934242 | 2.941031 | 1.337708 |
OPENJP2.opj_image_destroy.argtypes = [ctypes.POINTER(ImageType)]
OPENJP2.opj_image_destroy.restype = ctypes.c_void_p
OPENJP2.opj_image_destroy(image) | def image_destroy(image) | Deallocate any resources associated with an image.
Wraps the openjp2 library function opj_image_destroy.
Parameters
----------
image : ImageType pointer
Image resource to be disposed. | 3.909357 | 3.072242 | 1.272477 |
OPENJP2.opj_image_create.argtypes = [ctypes.c_uint32,
ctypes.POINTER(ImageComptParmType),
COLOR_SPACE_TYPE]
OPENJP2.opj_image_create.restype = ctypes.POINTER(ImageType)
image = OPENJP2.opj_image_create(len(comptparms),
... | def image_create(comptparms, clrspc) | Creates a new image structure.
Wraps the openjp2 library function opj_image_create.
Parameters
----------
cmptparms : comptparms_t
The component parameters.
clrspc : int
Specifies the color space.
Returns
-------
image : ImageType
Reference to ImageType instanc... | 3.997983 | 3.825583 | 1.045065 |
ARGTYPES = [ctypes.c_uint32,
ctypes.POINTER(ImageComptParmType),
COLOR_SPACE_TYPE]
OPENJP2.opj_image_tile_create.argtypes = ARGTYPES
OPENJP2.opj_image_tile_create.restype = ctypes.POINTER(ImageType)
image = OPENJP2.opj_image_tile_create(len(comptparms),
... | def image_tile_create(comptparms, clrspc) | Creates a new image structure.
Wraps the openjp2 library function opj_image_tile_create.
Parameters
----------
cmptparms : comptparms_t
The component parameters.
clrspc : int
Specifies the color space.
Returns
-------
image : ImageType
Reference to ImageType in... | 3.853431 | 3.742248 | 1.02971 |
ARGTYPES = [STREAM_TYPE_P, CODEC_TYPE,
ctypes.POINTER(ctypes.POINTER(ImageType))]
OPENJP2.opj_read_header.argtypes = ARGTYPES
OPENJP2.opj_read_header.restype = check_error
imagep = ctypes.POINTER(ImageType)()
OPENJP2.opj_read_header(stream, codec, ctypes.byref(imagep))
retu... | def read_header(stream, codec) | Decodes an image header.
Wraps the openjp2 library function opj_read_header.
Parameters
----------
stream: STREAM_TYPE_P
The JPEG2000 stream.
codec: codec_t
The JPEG2000 codec to read.
Returns
-------
imagep : reference to ImageType instance
The image structur... | 4.638935 | 3.313737 | 1.39991 |
ARGTYPES = [CODEC_TYPE,
STREAM_TYPE_P,
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_int32),
ctypes.POINTER(ctypes.c_int32),
ctypes.POINTER(ctypes.c_int32),
... | def read_tile_header(codec, stream) | Reads a tile header.
Wraps the openjp2 library function opj_read_tile_header.
Parameters
----------
codec : codec_t
The JPEG2000 codec to read.
stream : STREAM_TYPE_P
The JPEG2000 stream.
Returns
-------
tile_index : int
index of the tile being decoded
data... | 1.77494 | 1.564373 | 1.134602 |
OPENJP2.opj_set_decode_area.argtypes = [CODEC_TYPE,
ctypes.POINTER(ImageType),
ctypes.c_int32,
ctypes.c_int32,
ctypes.c_int32,
... | def set_decode_area(codec, image, start_x=0, start_y=0, end_x=0, end_y=0) | Wraps openjp2 library function opj_set_decode area.
Sets the given area to be decoded. This function should be called right
after read_header and before any tile header reading.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_decompress function.
image : ImageType... | 1.926038 | 1.822749 | 1.056667 |
ARGTYPES = [ctypes.POINTER(DecompressionParametersType)]
OPENJP2.opj_set_default_decoder_parameters.argtypes = ARGTYPES
OPENJP2.opj_set_default_decoder_parameters.restype = ctypes.c_void_p
dparams = DecompressionParametersType()
OPENJP2.opj_set_default_decoder_parameters(ctypes.byref(dparams))... | def set_default_decoder_parameters() | Wraps openjp2 library function opj_set_default_decoder_parameters.
Sets decoding parameters to default values.
Returns
-------
dparam : DecompressionParametersType
Decompression parameters. | 3.315639 | 2.354946 | 1.407947 |
ARGTYPES = [ctypes.POINTER(CompressionParametersType)]
OPENJP2.opj_set_default_encoder_parameters.argtypes = ARGTYPES
OPENJP2.opj_set_default_encoder_parameters.restype = ctypes.c_void_p
cparams = CompressionParametersType()
OPENJP2.opj_set_default_encoder_parameters(ctypes.byref(cparams))
... | def set_default_encoder_parameters() | Wraps openjp2 library function opj_set_default_encoder_parameters.
Sets encoding parameters to default values. That means
lossless
1 tile
size of precinct : 2^15 x 2^15 (means 1 precinct)
size of code-block : 64 x 64
number of resolutions: 6
no SOP marker in the co... | 3.298639 | 2.411221 | 1.368037 |
OPENJP2.opj_set_error_handler.argtypes = [CODEC_TYPE,
ctypes.c_void_p,
ctypes.c_void_p]
OPENJP2.opj_set_error_handler.restype = check_error
OPENJP2.opj_set_error_handler(codec, handler, data) | def set_error_handler(codec, handler, data=None) | Wraps openjp2 library function opj_set_error_handler.
Set the error handler use by openjpeg.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_compress function.
handler : python function
The callback function to be used.
user_data : anything
User/cli... | 2.834312 | 2.589952 | 1.094349 |
OPENJP2.opj_set_info_handler.argtypes = [CODEC_TYPE,
ctypes.c_void_p,
ctypes.c_void_p]
OPENJP2.opj_set_info_handler.restype = check_error
OPENJP2.opj_set_info_handler(codec, handler, data) | def set_info_handler(codec, handler, data=None) | Wraps openjp2 library function opj_set_info_handler.
Set the info handler use by openjpeg.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_compress function.
handler : python function
The callback function to be used.
user_data : anything
User/clien... | 2.863484 | 2.549581 | 1.12312 |
OPENJP2.opj_set_warning_handler.argtypes = [CODEC_TYPE,
ctypes.c_void_p,
ctypes.c_void_p]
OPENJP2.opj_set_warning_handler.restype = check_error
OPENJP2.opj_set_warning_handler(codec, handler, data) | def set_warning_handler(codec, handler, data=None) | Wraps openjp2 library function opj_set_warning_handler.
Set the warning handler use by openjpeg.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_compress function.
handler : python function
The callback function to be used.
user_data : anything
User... | 2.931956 | 2.646526 | 1.107851 |
ARGTYPES = [CODEC_TYPE, ctypes.POINTER(DecompressionParametersType)]
OPENJP2.opj_setup_decoder.argtypes = ARGTYPES
OPENJP2.opj_setup_decoder.restype = check_error
OPENJP2.opj_setup_decoder(codec, ctypes.byref(dparams)) | def setup_decoder(codec, dparams) | Wraps openjp2 library function opj_setup_decoder.
Setup the decoder with decompression parameters.
Parameters
----------
codec: CODEC_TYPE
Codec initialized by create_compress function.
dparams: DecompressionParametersType
Decompression parameters.
Raises
------
Runt... | 5.240896 | 3.202051 | 1.636731 |
ARGTYPES = [CODEC_TYPE,
ctypes.POINTER(CompressionParametersType),
ctypes.POINTER(ImageType)]
OPENJP2.opj_setup_encoder.argtypes = ARGTYPES
OPENJP2.opj_setup_encoder.restype = check_error
OPENJP2.opj_setup_encoder(codec, ctypes.byref(cparams), image) | def setup_encoder(codec, cparams, image) | Wraps openjp2 library function opj_setup_encoder.
Setup the encoder parameters using the current image and using user
parameters.
Parameters
----------
codec : CODEC_TYPE
codec initialized by create_compress function
cparams : CompressionParametersType
compression parameters
... | 4.367958 | 3.061871 | 1.426565 |
OPENJP2.opj_start_compress.argtypes = [CODEC_TYPE,
ctypes.POINTER(ImageType),
STREAM_TYPE_P]
OPENJP2.opj_start_compress.restype = check_error
OPENJP2.opj_start_compress(codec, image, stream) | def start_compress(codec, image, stream) | Wraps openjp2 library function opj_start_compress.
Start to compress the current image.
Parameters
----------
codec : CODEC_TYPE
Compressor handle.
image : pointer to ImageType
Input filled image.
stream : STREAM_TYPE_P
Input stream.
Raises
------
RuntimeEr... | 4.492912 | 3.148629 | 1.426942 |
ARGTYPES = [ctypes.c_char_p, ctypes.c_int32]
OPENJP2.opj_stream_create_default_file_stream.argtypes = ARGTYPES
OPENJP2.opj_stream_create_default_file_stream.restype = STREAM_TYPE_P
read_stream = 1 if isa_read_stream else 0
file_argument = ctypes.c_char_p(fname.encode())
stream = OPENJP2.opj... | def stream_create_default_file_stream(fname, isa_read_stream) | Wraps openjp2 library function opj_stream_create_default_vile_stream.
Sets the stream to be a file stream. This function is only valid for the
2.1 version of the openjp2 library.
Parameters
----------
fname : str
Specifies a file.
isa_read_stream: bool
True (read) or False (w... | 3.091166 | 2.845359 | 1.086389 |
OPENJP2.opj_stream_destroy.argtypes = [STREAM_TYPE_P]
OPENJP2.opj_stream_destroy.restype = ctypes.c_void_p
OPENJP2.opj_stream_destroy(stream) | def stream_destroy(stream) | Wraps openjp2 library function opj_stream_destroy.
Destroys the stream created by create_stream.
Parameters
----------
stream : STREAM_TYPE_P
The file stream. | 3.813633 | 2.603522 | 1.464798 |
OPENJP2.opj_write_tile.argtypes = [CODEC_TYPE,
ctypes.c_uint32,
ctypes.POINTER(ctypes.c_uint8),
ctypes.c_uint32,
STREAM_TYPE_P]
OPENJP2.opj_write_tile.... | def write_tile(codec, tile_index, data, data_size, stream) | Wraps openjp2 library function opj_write_tile.
Write a tile into an image.
Parameters
----------
codec : CODEC_TYPE
The jpeg2000 codec
tile_index : int
The index of the tile to write, zero-indexing assumed
data : array
Image data arranged in usual C-order
data_size ... | 2.573149 | 2.314654 | 1.111678 |
''' Function to calculate the length of the required padding
Input: (int) str_len - String length of the text
(int) blocksize - block size of the algorithm
Returns: (int) number of required pad bytes for string of size.'''
assert 0 < blocksize < 255, 'blocksize must be between 0 and 255'
asser... | def paddingLength(str_len, blocksize=AES_blocksize) | Function to calculate the length of the required padding
Input: (int) str_len - String length of the text
(int) blocksize - block size of the algorithm
Returns: (int) number of required pad bytes for string of size. | 5.57778 | 2.653243 | 2.10225 |
'''CMS padding: Remove padding with bytes containing the number of padding bytes '''
try:
pad_len = ord(str[-1]) # last byte contains number of padding bytes
except TypeError:
pad_len = str[-1]
assert pad_len <= blocksize, 'padding error'
assert pad_len <= len(str), 'padding error'
return str[... | def removeCMSPadding(str, blocksize=AES_blocksize) | CMS padding: Remove padding with bytes containing the number of padding bytes | 6.167215 | 3.901879 | 1.580576 |
'''Bit padding a.k.a. One and Zeroes Padding
A single set ('1') bit is added to the message and then as many reset ('0') bits as required (possibly none) are added.
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
Return: Padded string according to ANSI X.923 standar... | def appendBitPadding(str, blocksize=AES_blocksize) | Bit padding a.k.a. One and Zeroes Padding
A single set ('1') bit is added to the message and then as many reset ('0') bits as required (possibly none) are added.
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
Return: Padded string according to ANSI X.923 standart
... | 8.532208 | 1.543234 | 5.528783 |
'Remove bit padding with 0x80 followed by zero (null) bytes'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == '\0':
pad_len += 1
else:
break
pad_len += 1
str = str[:-pad_len]
return str | def removeBitPadding(str, blocksize=AES_blocksize) | Remove bit padding with 0x80 followed by zero (null) bytes | 5.365757 | 3.577829 | 1.499724 |
'Remove Padding with zeroes + last byte equal to the number of padding bytes'
try:
pad_len = ord(str[-1]) # last byte contains number of padding bytes
except TypeError:
pad_len = str[-1]
assert pad_len < blocksize, 'padding error'
assert pad_len < len(str), 'padding error'
return str[:-pad_len... | def removeZeroLenPadding(str, blocksize=AES_blocksize) | Remove Padding with zeroes + last byte equal to the number of padding bytes | 5.873479 | 3.886566 | 1.511226 |
'Pad with null bytes'
pad_len = paddingLength(len(str), blocksize)
padding = '\0'*pad_len
return str + padding | def appendNullPadding(str, blocksize=AES_blocksize) | Pad with null bytes | 8.676059 | 8.105521 | 1.070389 |
'Remove padding with null bytes'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == '\0':
pad_len += 1
else:
break
str = str[:-pad_len]
return str | def removeNullPadding(str, blocksize=AES_blocksize) | Remove padding with null bytes | 4.118583 | 3.917571 | 1.051311 |
'Pad with spaces'
pad_len = paddingLength(len(str), blocksize)
padding = '\0'*pad_len
return str + padding | def appendSpacePadding(str, blocksize=AES_blocksize) | Pad with spaces | 10.298545 | 9.065825 | 1.135974 |
'Remove padding with spaces'
pad_len = 0
for char in str[::-1]: # str[::-1] reverses string
if char == ' ':
pad_len += 1
else:
break
str = str[:-pad_len]
return str | def removeSpacePadding(str, blocksize=AES_blocksize) | Remove padding with spaces | 5.122557 | 4.58153 | 1.118089 |
'ISO 10126 Padding (withdrawn, 2007): Pad with random bytes + last byte equal to the number of padding bytes'
pad_len = paddingLength(len(str), blocksize) - 1
from os import urandom
padding = urandom(pad_len)+chr(pad_len)
return str + padding | def appendRandomLenPadding(str, blocksize=AES_blocksize) | ISO 10126 Padding (withdrawn, 2007): Pad with random bytes + last byte equal to the number of padding bytes | 9.915067 | 3.299091 | 3.005394 |
'ISO 10126 Padding (withdrawn, 2007): Remove Padding with random bytes + last byte equal to the number of padding bytes'
pad_len = ord(str[-1]) # last byte contains number of padding bytes
assert pad_len < blocksize, 'padding error'
assert pad_len < len(str), 'padding error'
return str[:-pad_len] | def removeRandomLenPadding(str, blocksize=AES_blocksize) | ISO 10126 Padding (withdrawn, 2007): Remove Padding with random bytes + last byte equal to the number of padding bytes | 8.479912 | 2.986717 | 2.839208 |
''' Pad (append padding to) string for use with symmetric encryption algorithm
Input: (string) str - String to be padded
(int) blocksize - block size of the encryption algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Padded strin... | def appendPadding(str, blocksize=AES_blocksize, mode='CMS') | Pad (append padding to) string for use with symmetric encryption algorithm
Input: (string) str - String to be padded
(int) blocksize - block size of the encryption algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Padded string acco... | 8.50696 | 2.72971 | 3.116433 |
''' Remove padding from string
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Decrypted string without padding
'''
if mode not in (0,'CMS'):
f... | def removePadding(str, blocksize=AES_blocksize, mode='CMS') | Remove padding from string
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
(string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random)
Return:(string) Decrypted string without padding | 9.377034 | 3.494151 | 2.683637 |
msg = "OpenJPEG library error: {0}".format(msg.decode('utf-8').rstrip())
opj2.set_error_message(msg) | def _default_error_handler(msg, _) | Default error handler callback for libopenjp2. | 11.601921 | 7.273788 | 1.595031 |
library_msg = library_msg.decode('utf-8').rstrip()
msg = "OpenJPEG library warning: {0}".format(library_msg)
warnings.warn(msg, UserWarning) | def _default_warning_handler(library_msg, _) | Default warning handler callback. | 4.730823 | 4.526074 | 1.045237 |
self.length = os.path.getsize(self.filename)
with open(self.filename, 'rb') as fptr:
# Make sure we have a JPEG2000 file. It could be either JP2 or
# J2C. Check for J2C first, single box in that case.
read_buffer = fptr.read(2)
signature, = st... | def parse(self) | Parses the JPEG 2000 file.
Raises
------
IOError
The file was not JPEG 2000. | 4.225542 | 4.090886 | 1.032916 |
# A JP2 file must contain certain boxes. The 2nd box must be a file
# type box.
if not isinstance(self.box[1], FileTypeBox):
msg = "{filename} does not contain a valid File Type box."
msg = msg.format(filename=self.filename)
raise IOError(msg)
... | def _validate(self) | Validate the JPEG 2000 outermost superbox. These checks must be
done at a file level. | 5.81827 | 5.190063 | 1.12104 |
if re.match("1.5|2.0", version.openjpeg_version) is not None:
msg = ("Writing Cinema2K or Cinema4K files is not supported with "
"OpenJPEG library versions less than 2.1.0. The installed "
"version of OpenJPEG is {version}.")
msg = msg.form... | def _set_cinema_params(self, cinema_mode, fps) | Populate compression parameters structure for cinema2K.
Parameters
----------
params : ctypes struct
Corresponds to compression parameters structure used by the
library.
cinema_mode : {'cinema2k', 'cinema4k}
Use either Cinema2K or Cinema4K profile.
... | 3.069323 | 2.790583 | 1.099886 |
if re.match("0|1.[0-4]", version.openjpeg_version) is not None:
msg = ("You must have at least version 1.5 of OpenJPEG "
"in order to write images.")
raise RuntimeError(msg)
self._determine_colorspace(**kwargs)
self._populate_cparams(img_array... | def _write(self, img_array, verbose=False, **kwargs) | Write image data to a JP2/JPX/J2k file. Intended usage of the
various parameters follows that of OpenJPEG's opj_compress utility.
This method can only be used to create JPEG 2000 images that can fit
in memory. | 5.601061 | 5.527263 | 1.013352 |
if img_array.ndim == 2:
# Force the image to be 3D. Just makes things easier later on.
img_array = img_array.reshape(img_array.shape[0],
img_array.shape[1],
1)
self._populate_comptparms... | def _write_openjpeg(self, img_array, verbose=False) | Write JPEG 2000 file using OpenJPEG 1.5 interface. | 3.515585 | 3.46456 | 1.014728 |
if cparams.codec_fmt == opj2.CODEC_J2K and colorspace is not None:
msg = 'Do not specify a colorspace when writing a raw codestream.'
raise IOError(msg) | def _validate_j2k_colorspace(self, cparams, colorspace) | Cannot specify a colorspace with J2K. | 9.939561 | 8.235937 | 1.206852 |
if cparams.cblockw_init != 0 and cparams.cblockh_init != 0:
# These fields ARE zero if uninitialized.
width = cparams.cblockw_init
height = cparams.cblockh_init
if height * width > 4096 or height < 4 or width < 4:
msg = ("The code block ar... | def _validate_codeblock_size(self, cparams) | Code block dimensions must satisfy certain restrictions.
They must both be a power of 2 and the total area defined by the width
and height cannot be either too great or too small for the codec. | 3.040788 | 2.847071 | 1.068041 |
code_block_specified = False
if cparams.cblockw_init != 0 and cparams.cblockh_init != 0:
code_block_specified = True
if cparams.res_spec != 0:
# precinct size was not specified if this field is zero.
for j in range(cparams.res_spec):
... | def _validate_precinct_size(self, cparams) | Precinct dimensions must satisfy certain restrictions if specified.
They must both be a power of 2 and must both be at least twice the
size of their codeblock size counterparts. | 2.787969 | 2.569859 | 1.084872 |
if img_array.ndim == 1 or img_array.ndim > 3:
msg = "{0}D imagery is not allowed.".format(img_array.ndim)
raise IOError(msg) | def _validate_image_rank(self, img_array) | Images must be either 2D or 3D. | 3.851944 | 3.417691 | 1.12706 |
if img_array.dtype != np.uint8 and img_array.dtype != np.uint16:
msg = ("Only uint8 and uint16 datatypes are currently supported "
"when writing.")
raise RuntimeError(msg) | def _validate_image_datatype(self, img_array) | Only uint8 and uint16 images are currently supported. | 3.241579 | 2.688522 | 1.205711 |
self._validate_j2k_colorspace(cparams, colorspace)
self._validate_codeblock_size(cparams)
self._validate_precinct_size(cparams)
self._validate_image_rank(img_array)
self._validate_image_datatype(img_array) | def _validate_compression_params(self, img_array, cparams, colorspace) | Check that the compression parameters are valid.
Parameters
----------
img_array : ndarray
Image data to be written to file.
cparams : CompressionParametersType(ctypes.Structure)
Corresponds to cparameters_t type in openjp2 headers. | 3.730128 | 3.805552 | 0.98018 |
if colorspace is None:
# Must infer the colorspace from the image dimensions.
if len(self.shape) < 3:
# A single channel image is grayscale.
self._colorspace = opj2.CLRSPC_GRAY
elif self.shape[2] == 1 or self.shape[2] == 2:
... | def _determine_colorspace(self, colorspace=None, **kwargs) | Determine the colorspace from the supplied inputs.
Parameters
----------
colorspace : str, optional
Either 'rgb' or 'gray'. | 2.728587 | 2.802135 | 0.973753 |
if img_array.ndim == 2:
# Force the image to be 3D. Just makes things easier later on.
numrows, numcols = img_array.shape
img_array = img_array.reshape(numrows, numcols, 1)
self._populate_comptparms(img_array)
with ExitStack() as stack:
... | def _write_openjp2(self, img_array, verbose=False) | Write JPEG 2000 file using OpenJPEG 2.x interface. | 3.616432 | 3.537549 | 1.022299 |
if self._codec_format == opj2.CODEC_J2K:
msg = "Only JP2 files can currently have boxes appended to them."
raise IOError(msg)
if not ((box.box_id == 'xml ') or
(box.box_id == 'uuid' and
box.uuid == UUID('be7acfcb-97a9-42e8-9c71-999491e3a... | def append(self, box) | Append a JP2 box to the file in-place.
Parameters
----------
box : Jp2Box
Instance of a JP2 box. Only UUID and XML boxes can currently be
appended. | 4.128146 | 3.877584 | 1.064618 |
if boxes is None:
boxes = self._get_default_jp2_boxes()
self._validate_jp2_box_sequence(boxes)
with open(filename, 'wb') as ofile:
for box in boxes:
if box.box_id != 'jp2c':
box.write(ofile)
else:
... | def wrap(self, filename, boxes=None) | Create a new JP2/JPX file wrapped in a new set of JP2 boxes.
This method is primarily aimed at wrapping a raw codestream in a set of
of JP2 boxes (turning it into a JP2 file instead of just a raw
codestream), or rewrapping a codestream in a JP2 file in a new "jacket"
of JP2 boxes.
... | 4.080906 | 3.845164 | 1.061309 |
# Codestreams require a bit more care.
# Am I a raw codestream?
if len(self.box) == 0:
# Yes, just write the codestream box header plus all
# of myself out to file.
ofile.write(struct.pack('>I', self.length + 8))
ofile.write(b'jp2c')
... | def _write_wrapped_codestream(self, ofile, box) | Write wrapped codestream. | 4.113712 | 4.086976 | 1.006542 |
# Try to create a reasonable default.
boxes = [JPEG2000SignatureBox(),
FileTypeBox(),
JP2HeaderBox(),
ContiguousCodestreamBox()]
height = self.codestream.segment[1].ysiz
width = self.codestream.segment[1].xsiz
num_compon... | def _get_default_jp2_boxes(self) | Create a default set of JP2 boxes. | 4.749409 | 4.555532 | 1.042559 |
# Remove the first ellipsis we find.
rows = slice(0, numrows)
cols = slice(0, numcols)
bands = slice(0, numbands)
if index[0] is Ellipsis:
if len(index) == 2:
# jp2k[..., other_slice]
newindex = (rows, cols, index[1])
... | def _remove_ellipsis(self, index, numrows, numcols, numbands) | resolve the first ellipsis in the index so that it references the image
Parameters
----------
index : tuple
tuple of index arguments, presumably one of them is the Ellipsis
numrows, numcols, numbands : int
image dimensions
Returns
-------
... | 2.687404 | 2.770465 | 0.970019 |
if re.match("0|1.[01234]", version.openjpeg_version):
msg = ("You must have a version of OpenJPEG at least as high as "
"1.5.0 before you can read JPEG2000 images with glymur. "
"Your version is {version}")
raise TypeError(msg.format(versio... | def _read(self, **kwargs) | Read a JPEG 2000 image.
Returns
-------
ndarray
The image data.
Raises
------
RuntimeError
if the proper version of the OpenJPEG library is not available | 5.229651 | 4.897444 | 1.067833 |
dxs = np.array(self.codestream.segment[1].xrsiz)
dys = np.array(self.codestream.segment[1].yrsiz)
if np.any(dxs - dxs[0]) or np.any(dys - dys[0]):
msg = ("The read_bands method should be used with the subsampling "
"factors are different. "
... | def _subsampling_sanity_check(self) | Check for differing subsample factors. | 5.388247 | 4.802732 | 1.121913 |
self._subsampling_sanity_check()
self._populate_dparams(rlevel)
with ExitStack() as stack:
try:
self._dparams.decod_format = self._codec_format
dinfo = opj.create_decompress(self._dparams.decod_format)
event_mgr = opj.Event... | def _read_openjpeg(self, rlevel=0, verbose=False, area=None) | Read a JPEG 2000 image using libopenjpeg.
Parameters
----------
rlevel : int, optional
Factor by which to rlevel output resolution. Use -1 to get the
lowest resolution thumbnail.
verbose : bool, optional
Print informational messages produced by the O... | 3.711572 | 3.731481 | 0.994665 |
self.layer = layer
self._subsampling_sanity_check()
self._populate_dparams(rlevel, tile=tile, area=area)
image = self._read_openjp2_common()
return image | def _read_openjp2(self, rlevel=0, layer=None, area=None, tile=None,
verbose=False) | Read a JPEG 2000 image using libopenjp2.
Parameters
----------
layer : int, optional
Number of quality layer to decode.
rlevel : int, optional
Factor by which to rlevel output resolution. Use -1 to get the
lowest resolution thumbnail.
area : ... | 8.025135 | 11.205548 | 0.716175 |
with ExitStack() as stack:
filename = self.filename
stream = opj2.stream_create_default_file_stream(filename, True)
stack.callback(opj2.stream_destroy, stream)
codec = opj2.create_decompress(self._codec_format)
stack.callback(opj2.destroy_code... | def _read_openjp2_common(self) | Read a JPEG 2000 image using libopenjp2.
Returns
-------
ndarray or lst
Either the image as an ndarray or a list of ndarrays, each item
corresponding to one band. | 2.957278 | 2.933218 | 1.008203 |
if opj2.OPENJP2 is not None:
dparam = opj2.set_default_decoder_parameters()
else:
dparam = opj.DecompressionParametersType()
opj.set_default_decoder_parameters(ctypes.byref(dparam))
infile = self.filename.encode()
nelts = opj2.PATH_LEN - len(... | def _populate_dparams(self, rlevel, tile=None, area=None) | Populate decompression structure with appropriate input parameters.
Parameters
----------
rlevel : int
Factor by which to rlevel output resolution.
area : tuple
Specifies decoding image area,
(first_row, first_col, last_row, last_col)
tile : i... | 3.889696 | 3.716107 | 1.046713 |
if version.openjpeg_version < '2.1.0':
msg = ("You must have at least version 2.1.0 of OpenJPEG "
"installed before using this method. Your version of "
"OpenJPEG is {version}.")
msg = msg.format(version=version.openjpeg_version)
... | def read_bands(self, rlevel=0, layer=None, area=None, tile=None,
verbose=False, ignore_pclr_cmap_cdef=False) | Read a JPEG 2000 image.
The only time you should use this method is when the image has
different subsampling factors across components. Otherwise you should
use the read method.
Parameters
----------
layer : int, optional
Number of quality layer to decode.
... | 3.850727 | 4.600368 | 0.837048 |
ncomps = raw_image.contents.numcomps
# Make a pass thru the image, see if any of the band datatypes or
# dimensions differ.
dtypes, nrows, ncols = [], [], []
for k in range(raw_image.contents.numcomps):
component = raw_image.contents.comps[k]
dty... | def _extract_image(self, raw_image) | Extract unequally-sized image bands.
Parameters
----------
raw_image : reference to openjpeg ImageType instance
The image structure initialized with image characteristics.
Returns
-------
list or ndarray
If the JPEG 2000 image has unequally-sized... | 2.816924 | 2.76121 | 1.020177 |
if component.prec > 16:
msg = "Unhandled precision: {0} bits.".format(component.prec)
raise IOError(msg)
if component.sgnd:
dtype = np.int8 if component.prec <=8 else np.int16
else:
dtype = np.uint8 if component.prec <=8 else np.uint16
... | def _component2dtype(self, component) | Determin the appropriate numpy datatype for an OpenJPEG component.
Parameters
----------
component : ctypes pointer to ImageCompType (image_comp_t)
single image component structure.
Returns
-------
builtins.type
numpy datatype to be used to const... | 3.928677 | 4.157628 | 0.944932 |
with open(self.filename, 'rb') as fptr:
if self._codec_format == opj2.CODEC_J2K:
codestream = Codestream(fptr, self.length,
header_only=header_only)
else:
box = [x for x in self.box if x.box_id == 'jp2c']
... | def get_codestream(self, header_only=True) | Retrieve codestream.
Parameters
----------
header_only : bool, optional
If True, only marker segments in the main header are parsed.
Supplying False may impose a large performance penalty.
Returns
-------
Codestream
Object describing ... | 3.77187 | 4.247666 | 0.887986 |
numrows, numcols, num_comps = imgdata.shape
for k in range(num_comps):
self._validate_nonzero_image_size(numrows, numcols, k)
# set image offset and reference grid
image.contents.x0 = self._cparams.image_offset_x0
image.contents.y0 = self._cparams.image_off... | def _populate_image_struct(self, image, imgdata) | Populates image struct needed for compression.
Parameters
----------
image : ImageType(ctypes.Structure)
Corresponds to image_t type in openjp2 headers.
img_array : ndarray
Image data to be written to file. | 3.529183 | 3.53643 | 0.997951 |
# Only two precisions are possible.
if img_array.dtype == np.uint8:
comp_prec = 8
else:
comp_prec = 16
numrows, numcols, num_comps = img_array.shape
if version.openjpeg_version_tuple[0] == 1:
comptparms = (opj.ImageComptParmType * num... | def _populate_comptparms(self, img_array) | Instantiate and populate comptparms structure.
This structure defines the image components.
Parameters
----------
img_array : ndarray
Image data to be written to file. | 2.844812 | 2.907592 | 0.978408 |
if nrows == 0 or ncols == 0:
# Letting this situation continue would segfault openjpeg.
msg = "Component {0} has dimensions {1} x {2}"
msg = msg.format(component_index, nrows, ncols)
raise IOError(msg) | def _validate_nonzero_image_size(self, nrows, ncols, component_index) | The image cannot have area of zero. | 5.672947 | 5.171959 | 1.096866 |
JP2_IDS = ['colr', 'cdef', 'cmap', 'jp2c', 'ftyp', 'ihdr', 'jp2h',
'jP ', 'pclr', 'res ', 'resc', 'resd', 'xml ', 'ulst',
'uinf', 'url ', 'uuid']
self._validate_signature_compatibility(boxes)
self._validate_jp2h(boxes)
self._validate_jp2c(... | def _validate_jp2_box_sequence(self, boxes) | Run through series of tests for JP2 box legality.
This is non-exhaustive. | 4.942582 | 4.932213 | 1.002102 |
lst = [box for box in boxes if box.box_id == 'jp2h']
jp2h = lst[0]
for colr in [box for box in jp2h.box if box.box_id == 'colr']:
if colr.approximation != 0:
msg = ("A JP2 colr box cannot have a non-zero approximation "
"field.")
... | def _validate_jp2_colr(self, boxes) | Validate JP2 requirements on colour specification boxes. | 4.432118 | 4.15693 | 1.0662 |
self._validate_label(boxes)
self._validate_jpx_compatibility(boxes, boxes[1].compatibility_list)
self._validate_singletons(boxes)
self._validate_top_level(boxes) | def _validate_jpx_box_sequence(self, boxes) | Run through series of tests for JPX box legality. | 7.673061 | 6.308832 | 1.216241 |
# Check for a bad sequence of boxes.
# 1st two boxes must be 'jP ' and 'ftyp'
if boxes[0].box_id != 'jP ' or boxes[1].box_id != 'ftyp':
msg = ("The first box must be the signature box and the second "
"must be the file type box.")
raise IOErr... | def _validate_signature_compatibility(self, boxes) | Validate the file signature and compatibility status. | 5.341023 | 4.583126 | 1.165367 |
# jp2c must be preceeded by jp2h
jp2h_lst = [idx for (idx, box) in enumerate(boxes)
if box.box_id == 'jp2h']
jp2h_idx = jp2h_lst[0]
jp2c_lst = [idx for (idx, box) in enumerate(boxes)
if box.box_id == 'jp2c']
if len(jp2c_lst) == 0:
... | def _validate_jp2c(self, boxes) | Validate the codestream box in relation to other boxes. | 2.748242 | 2.562622 | 1.072433 |
self._check_jp2h_child_boxes(boxes, 'top-level')
jp2h_lst = [box for box in boxes if box.box_id == 'jp2h']
jp2h = jp2h_lst[0]
# 1st jp2 header box cannot be empty.
if len(jp2h.box) == 0:
msg = "The JP2 header superbox cannot be empty."
raise IOE... | def _validate_jp2h(self, boxes) | Validate the JP2 Header box. | 2.788621 | 2.657312 | 1.049414 |
cdef_lst = [j for (j, box) in enumerate(jp2h.box)
if box.box_id == 'cdef']
if len(cdef_lst) > 1:
msg = ("Only one channel definition box is allowed in the "
"JP2 header.")
raise IOError(msg)
elif len(cdef_lst) == 1:
... | def _validate_channel_definition(self, jp2h, colr) | Validate the channel definition box. | 3.001297 | 2.780045 | 1.079586 |
JP2H_CHILDREN = set(['bpcc', 'cdef', 'cmap', 'ihdr', 'pclr'])
box_ids = set([box.box_id for box in boxes])
intersection = box_ids.intersection(JP2H_CHILDREN)
if len(intersection) > 0 and parent_box_name not in ['jp2h', 'jpch']:
msg = "A {0} box can only be nested in... | def _check_jp2h_child_boxes(self, boxes, parent_box_name) | Certain boxes can only reside in the JP2 header. | 3.874486 | 3.511369 | 1.103412 |
count = Counter([box.box_id for box in boxes])
# Add the counts in the superboxes.
for box in boxes:
if hasattr(box, 'box'):
count.update(self._collect_box_count(box.box))
return count | def _collect_box_count(self, boxes) | Count the occurences of each box type. | 4.350389 | 4.007709 | 1.085505 |
# We are only looking at the boxes contained in a superbox, so if any
# of the blacklisted boxes show up here, it's an error.
TOP_LEVEL_ONLY_BOXES = set(['dtbl'])
box_ids = set([box.box_id for box in boxes])
intersection = box_ids.intersection(TOP_LEVEL_ONLY_BOXES)
... | def _check_superbox_for_top_levels(self, boxes) | Several boxes can only occur at the top level. | 4.14121 | 3.922942 | 1.055639 |
# Add the counts in the superboxes.
for box in boxes:
if hasattr(box, 'box'):
self._check_superbox_for_top_levels(box.box)
count = self._collect_box_count(boxes)
# If there is one data reference box, then there must also be one ftbl.
if 'dtb... | def _validate_top_level(self, boxes) | Several boxes can only occur at the top level. | 7.069323 | 6.517454 | 1.084676 |
count = self._collect_box_count(boxes)
# Which boxes occur more than once?
multiples = [box_id for box_id, bcount in count.items() if bcount > 1]
if 'dtbl' in multiples:
raise IOError('There can only be one dtbl box in a file.') | def _validate_singletons(self, boxes) | Several boxes can only occur once. | 7.258257 | 6.050281 | 1.199656 |
JPX_IDS = ['asoc', 'nlst']
jpx_cl = set(compatibility_list)
for box in boxes:
if box.box_id in JPX_IDS:
if len(set(['jpx ', 'jpxb']).intersection(jpx_cl)) == 0:
msg = ("A JPX box requires that either 'jpx ' or 'jpxb' "
... | def _validate_jpx_compatibility(self, boxes, compatibility_list) | If there is a JPX box then the compatibility list must also contain
'jpx '. | 5.629922 | 4.680677 | 1.202801 |
for box in boxes:
if box.box_id != 'asoc':
if hasattr(box, 'box'):
for boxi in box.box:
if boxi.box_id == 'lbl ':
msg = ("A label box cannot be nested inside a "
"{0} b... | def _validate_label(self, boxes) | Label boxes can only be inside association, codestream headers, or
compositing layer header boxes. | 5.854906 | 4.505378 | 1.299537 |
return getattr(self.session, method)(*args, **kwargs) | def fulfill(self, method, *args, **kwargs) | Fulfill an HTTP request to Keen's API. | 5.618339 | 7.070571 | 0.794609 |
url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url, self.api_version,
self.project_id,
event.event_collection)
headers = utilities.headers(self.write_key)
payload = e... | def post_event(self, event) | Posts a single event to the Keen IO API. The write key must be set first.
:param event: an Event to upload | 4.80848 | 4.037106 | 1.191071 |
url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version,
self.project_id)
headers = utilities.headers(self.write_key)
payload = json.dumps(events)
response = self.fulfill(HTTPMethods.POST, url, data=payload,... | def post_events(self, events) | Posts a single event to the Keen IO API. The write key must be set first.
:param events: an Event to upload | 4.293031 | 3.831754 | 1.120383 |
if not "order_by" in params or not params["order_by"]:
return True
def _order_by_dict_is_not_well_formed(d):
if not isinstance(d, dict):
# Bad type.
return True
if "property_name" in d and d["property_name"]:
i... | def _order_by_is_valid_or_none(self, params) | Validates that a given order_by has proper syntax.
:param params: Query params.
:return: Returns True if either no order_by is present, or if the order_by is well-formed. | 3.039159 | 3.001899 | 1.012412 |
if not "limit" in params or not params["limit"]:
return True
if not isinstance(params["limit"], int) or params["limit"] < 1:
return False
if not "order_by" in params:
return False
return True | def _limit_is_valid_or_none(self, params) | Validates that a given limit is not present or is well-formed.
:param params: Query params.
:return: Returns True if a limit is present or is well-formed. | 2.747102 | 3.00975 | 0.912734 |
if not self._order_by_is_valid_or_none(params):
raise ValueError("order_by given is invalid or is missing required group_by.")
if not self._limit_is_valid_or_none(params):
raise ValueError("limit given is invalid or is missing required order_by.")
url = "{0}/{1}... | def query(self, analysis_type, params, all_keys=False) | Performs a query using the Keen IO analysis API. A read key must be set first. | 4.059164 | 3.797947 | 1.068779 |
url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url,
self.api_version,
self.project_id,
event_collection)
headers = util... | def delete_events(self, event_collection, params) | Deletes events via the Keen IO API. A master key must be set first.
:param event_collection: string, the event collection from which event are being deleted | 4.568332 | 4.246463 | 1.075797 |
url = "{0}/{1}/projects/{2}/events/{3}".format(self.base_url, self.api_version,
self.project_id, event_collection)
headers = utilities.headers(self.read_key)
response = self.fulfill(HTTPMethods.GET, url, headers=headers, timeout=se... | def get_collection(self, event_collection) | Extracts info about a collection using the Keen IO API. A master key must be set first.
:param event_collection: the name of the collection to retrieve info for | 4.621239 | 4.914088 | 0.940406 |
# Get current state via HTTPS.
current_access_key = self.get_access_key(access_key_id)
# Copy and only change the single parameter.
payload_dict = KeenApi._build_access_key_dict(current_access_key)
payload_dict[key] = val
# Now just treat it like a full update.... | def _update_access_key_pair(self, access_key_id, key, val) | Helper for updating access keys in a DRY fashion. | 6.519588 | 5.841893 | 1.116006 |
# Get current state via HTTPS.
current_access_key = self.get_access_key(access_key_id)
# Copy and only change the single parameter.
payload_dict = KeenApi._build_access_key_dict(current_access_key)
# Turn into sets to avoid duplicates.
old_permissions = set(pay... | def add_access_key_permissions(self, access_key_id, permissions) | Adds to the existing list of permissions on this key with the contents of this list.
Will not remove any existing permissions or modify the remainder of the key.
:param access_key_id: the 'key' value of the access key to add permissions to
:param permissions: the new permissions to add to the e... | 4.95466 | 5.104641 | 0.970619 |
# Get current state via HTTPS.
current_access_key = self.get_access_key(access_key_id)
# Copy and only change the single parameter.
payload_dict = KeenApi._build_access_key_dict(current_access_key)
# Turn into sets to avoid duplicates.
old_permissions = set(pay... | def remove_access_key_permissions(self, access_key_id, permissions) | Removes a list of permissions from the existing list of permissions.
Will not remove all existing permissions unless all such permissions are included
in this list. Not to be confused with key revocation.
See also: revoke_access_key()
:param access_key_id: the 'key' value of the access... | 5.435302 | 5.515591 | 0.985443 |
url = "{0}/{1}/projects/{2}/keys/{3}".format(self.base_url, self.api_version,
self.project_id, access_key_id)
headers = utilities.headers(self.master_key)
payload_dict = {
"name": name,
"is_active": is_active,
... | def update_access_key_full(self, access_key_id, name, is_active, permitted, options) | Replaces the 'name', 'is_active', 'permitted', and 'options' values of a given key.
A master key must be set first.
:param access_key_id: the 'key' value of the access key for which the values will be replaced
:param name: the new name desired for this access key
:param is_active: wheth... | 2.916498 | 3.086667 | 0.94487 |
# making the error handling generic so if an status_code starting with 2 doesn't exist, we raise the error
if res.status_code // 100 != 2:
error = self._get_response_json(res)
raise exceptions.KeenApiError(error) | def _error_handling(self, res) | Helper function to do the error handling
:params res: the response from a request | 10.002773 | 9.804706 | 1.020201 |
try:
error = res.json()
except ValueError:
error = {
"message": "The API did not respond with JSON, but: {0}".format(res.text[:1000]),
"error_code": "{0}".format(res.status_code)
}
return error | def _get_response_json(self, res) | Helper function to extract the JSON body out of a response OR throw an exception.
:param res: the response from a request
:return: the JSON body OR throws an exception | 4.127701 | 4.167201 | 0.990521 |
return self._get_json(HTTPMethods.GET,
self._cached_datasets_url,
self._get_master_key()) | def all(self) | Fetch all Cached Datasets for a Project. Read key must be set. | 17.030678 | 8.079444 | 2.107902 |
url = "{0}/{1}".format(self._cached_datasets_url, dataset_name)
return self._get_json(HTTPMethods.GET, url, self._get_read_key()) | def get(self, dataset_name) | Fetch a single Cached Dataset for a Project. Read key must be set.
:param dataset_name: Name of Cached Dataset (not `display_name`) | 6.811543 | 7.073317 | 0.962991 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.